repo_id stringlengths 4 98 | size int64 611 5.02M | file_path stringlengths 1 276 | content stringlengths 611 5.02M | shard_id int64 0 109 | quality_score float32 0.5 1 | quality_prediction int8 1 1 | quality_confidence float32 0.5 1 | topic_primary stringclasses 1 value | topic_group stringclasses 1 value | topic_score float32 0.05 1 | topic_all stringclasses 96 values | quality2_score float32 0.5 1 | quality2_prediction int8 1 1 | quality2_confidence float32 0.5 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PacktPublishing/Mastering-Cpp-Game-Development | 3,961 | Chapter11/Include/bullet/BulletCollision/Gimpact/btContactProcessing.h | #ifndef BT_CONTACT_H_INCLUDED
#define BT_CONTACT_H_INCLUDED
/*! \file gim_contact.h
\author Francisco Leon Najera
*/
/*
This source file is part of GIMPACT Library.
For the latest info, see http://gimpact.sourceforge.net/
Copyright (c) 2007 Francisco Leon Najera. C.C. 80087371.
email: projectileman@yahoo.com
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "LinearMath/btTransform.h"
#include "LinearMath/btAlignedObjectArray.h"
#include "btTriangleShapeEx.h"
/**
Configuration var for applying interpolation of contact normals
*/
#define NORMAL_CONTACT_AVERAGE 1
#define CONTACT_DIFF_EPSILON 0.00001f
///The GIM_CONTACT is an internal GIMPACT structure, similar to btManifoldPoint.
///@todo: remove and replace GIM_CONTACT by btManifoldPoint.
class GIM_CONTACT
{
public:
btVector3 m_point;
btVector3 m_normal;
btScalar m_depth;//Positive value indicates interpenetration
btScalar m_distance;//Padding not for use
int m_feature1;//Face number
int m_feature2;//Face number
public:
GIM_CONTACT()
{
}
GIM_CONTACT(const GIM_CONTACT & contact):
m_point(contact.m_point),
m_normal(contact.m_normal),
m_depth(contact.m_depth),
m_feature1(contact.m_feature1),
m_feature2(contact.m_feature2)
{
}
GIM_CONTACT(const btVector3 &point,const btVector3 & normal,
btScalar depth, int feature1, int feature2):
m_point(point),
m_normal(normal),
m_depth(depth),
m_feature1(feature1),
m_feature2(feature2)
{
}
//! Calcs key for coord classification
SIMD_FORCE_INLINE unsigned int calc_key_contact() const
{
int _coords[] = {
(int)(m_point[0]*1000.0f+1.0f),
(int)(m_point[1]*1333.0f),
(int)(m_point[2]*2133.0f+3.0f)};
unsigned int _hash=0;
unsigned int *_uitmp = (unsigned int *)(&_coords[0]);
_hash = *_uitmp;
_uitmp++;
_hash += (*_uitmp)<<4;
_uitmp++;
_hash += (*_uitmp)<<8;
return _hash;
}
SIMD_FORCE_INLINE void interpolate_normals( btVector3 * normals,int normal_count)
{
btVector3 vec_sum(m_normal);
for(int i=0;i<normal_count;i++)
{
vec_sum += normals[i];
}
btScalar vec_sum_len = vec_sum.length2();
if(vec_sum_len <CONTACT_DIFF_EPSILON) return;
//GIM_INV_SQRT(vec_sum_len,vec_sum_len); // 1/sqrt(vec_sum_len)
m_normal = vec_sum/btSqrt(vec_sum_len);
}
};
class btContactArray:public btAlignedObjectArray<GIM_CONTACT>
{
public:
btContactArray()
{
reserve(64);
}
SIMD_FORCE_INLINE void push_contact(
const btVector3 &point,const btVector3 & normal,
btScalar depth, int feature1, int feature2)
{
push_back( GIM_CONTACT(point,normal,depth,feature1,feature2) );
}
SIMD_FORCE_INLINE void push_triangle_contacts(
const GIM_TRIANGLE_CONTACT & tricontact,
int feature1,int feature2)
{
for(int i = 0;i<tricontact.m_point_count ;i++ )
{
push_contact(
tricontact.m_points[i],
tricontact.m_separating_normal,
tricontact.m_penetration_depth,feature1,feature2);
}
}
void merge_contacts(const btContactArray & contacts, bool normal_contact_average = true);
void merge_contacts_unique(const btContactArray & contacts);
};
#endif // GIM_CONTACT_H_INCLUDED
| 0 | 0.829017 | 1 | 0.829017 | game-dev | MEDIA | 0.940182 | game-dev | 0.914978 | 1 | 0.914978 |
emileb/OpenGames | 26,011 | opengames/src/main/jni/OpenJK/codemp/game/NPC_AI_Default.c | #include "b_local.h"
#include "g_nav.h"
#include "icarus/Q3_Interface.h"
extern qboolean NPC_SomeoneLookingAtMe(gentity_t *ent);
/*
void NPC_LostEnemyDecideChase(void)
We lost our enemy and want to drop him but see if we should chase him if we are in the proper bState
*/
void NPC_LostEnemyDecideChase(void)
{
switch( NPCS.NPCInfo->behaviorState )
{
case BS_HUNT_AND_KILL:
//We were chasing him and lost him, so try to find him
if ( NPCS.NPC->enemy == NPCS.NPCInfo->goalEntity && NPCS.NPC->enemy->lastWaypoint != WAYPOINT_NONE )
{//Remember his last valid Wp, then check it out
//FIXME: Should we only do this if there's no other enemies or we've got LOCKED_ENEMY on?
NPC_BSSearchStart( NPCS.NPC->enemy->lastWaypoint, BS_SEARCH );
}
//If he's not our goalEntity, we're running somewhere else, so lose him
break;
default:
break;
}
G_ClearEnemy( NPCS.NPC );
}
/*
-------------------------
NPC_StandIdle
-------------------------
*/
void NPC_StandIdle( void )
{
/*
//Must be done with any other animations
if ( NPC->client->ps.legsAnimTimer != 0 )
return;
//Not ready to do another one
if ( TIMER_Done( NPC, "idleAnim" ) == false )
return;
int anim = NPC->client->ps.legsAnim;
if ( anim != BOTH_STAND1 && anim != BOTH_STAND2 )
return;
//FIXME: Account for STAND1 or STAND2 here and set the base anim accordingly
int baseSeq = ( anim == BOTH_STAND1 ) ? BOTH_STAND1_RANDOM1 : BOTH_STAND2_RANDOM1;
//Must have at least one random idle animation
//NOTENOTE: This relies on proper ordering of animations, which SHOULD be okay
if ( PM_HasAnimation( NPC, baseSeq ) == false )
return;
int newIdle = Q_irand( 0, MAX_IDLE_ANIMS-1 );
//FIXME: Technically this could never complete.. but that's not really too likely
while( 1 )
{
if ( PM_HasAnimation( NPC, baseSeq + newIdle ) )
break;
newIdle = Q_irand( 0, MAX_IDLE_ANIMS );
}
//Start that animation going
NPC_SetAnim( NPC, SETANIM_BOTH, baseSeq + newIdle, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD );
int newTime = PM_AnimLength( NPC->client->clientInfo.animFileIndex, (animNumber_t) (baseSeq + newIdle) );
//Don't do this again for a random amount of time
TIMER_Set( NPC, "idleAnim", newTime + Q_irand( 2000, 10000 ) );
*/
}
qboolean NPC_StandTrackAndShoot (gentity_t *NPC, qboolean canDuck)
{
qboolean attack_ok = qfalse;
qboolean duck_ok = qfalse;
qboolean faced = qfalse;
float attack_scale = 1.0;
//First see if we're hurt bad- if so, duck
//FIXME: if even when ducked, we can shoot someone, we should.
//Maybe is can be shot even when ducked, we should run away to the nearest cover?
if ( canDuck )
{
if ( NPC->health < 20 )
{
// if( NPC->svFlags&SVF_HEALING || random() )
if( random() )
{
duck_ok = qtrue;
}
}
else if ( NPC->health < 40 )
{
// if ( NPC->svFlags&SVF_HEALING )
// {//Medic is on the way, get down!
// duck_ok = qtrue;
// }
// no more borg
/// if ( NPC->client->playerTeam!= TEAM_BORG )
// {//Borg don't care if they're about to die
//attack_scale will be a max of .66
// attack_scale = NPC->health/60;
// }
}
}
//NPC_CheckEnemy( qtrue, qfalse, qtrue );
if ( !duck_ok )
{//made this whole part a function call
attack_ok = NPC_CheckCanAttack( attack_scale, qtrue );
faced = qtrue;
}
if ( canDuck && (duck_ok || (!attack_ok && NPCS.client->ps.weaponTime <= 0)) && NPCS.ucmd.upmove != -127 )
{//if we didn't attack check to duck if we're not already
if( !duck_ok )
{
if ( NPC->enemy->client )
{
if ( NPC->enemy->enemy == NPC )
{
if ( NPC->enemy->client->buttons & BUTTON_ATTACK )
{//FIXME: determine if enemy fire angles would hit me or get close
if ( NPC_CheckDefend( 1.0 ) )//FIXME: Check self-preservation? Health?
{
duck_ok = qtrue;
}
}
}
}
}
if ( duck_ok )
{//duck and don't shoot
NPCS.ucmd.upmove = -127;
NPCS.NPCInfo->duckDebounceTime = level.time + 1000;//duck for a full second
}
}
return faced;
}
void NPC_BSIdle( void )
{
//FIXME if there is no nav data, we need to do something else
// if we're stuck, try to move around it
if ( UpdateGoal() )
{
NPC_MoveToGoal( qtrue );
}
if ( ( NPCS.ucmd.forwardmove == 0 ) && ( NPCS.ucmd.rightmove == 0 ) && ( NPCS.ucmd.upmove == 0 ) )
{
// NPC_StandIdle();
}
NPC_UpdateAngles( qtrue, qtrue );
NPCS.ucmd.buttons |= BUTTON_WALKING;
}
void NPC_BSRun (void)
{
//FIXME if there is no nav data, we need to do something else
// if we're stuck, try to move around it
if ( UpdateGoal() )
{
NPC_MoveToGoal( qtrue );
}
NPC_UpdateAngles( qtrue, qtrue );
}
void NPC_BSStandGuard (void)
{
//FIXME: Use Snapshot info
if ( NPCS.NPC->enemy == NULL )
{//Possible to pick one up by being shot
if( random() < 0.5 )
{
if(NPCS.NPC->client->enemyTeam)
{
gentity_t *newenemy = NPC_PickEnemy(NPCS.NPC, NPCS.NPC->client->enemyTeam, (NPCS.NPC->cantHitEnemyCounter < 10), (NPCS.NPC->client->enemyTeam == NPCTEAM_PLAYER), qtrue);
//only checks for vis if couldn't hit last enemy
if(newenemy)
{
G_SetEnemy( NPCS.NPC, newenemy );
}
}
}
}
if ( NPCS.NPC->enemy != NULL )
{
if( NPCS.NPCInfo->tempBehavior == BS_STAND_GUARD )
{
NPCS.NPCInfo->tempBehavior = BS_DEFAULT;
}
if( NPCS.NPCInfo->behaviorState == BS_STAND_GUARD )
{
NPCS.NPCInfo->behaviorState = BS_STAND_AND_SHOOT;
}
}
NPC_UpdateAngles( qtrue, qtrue );
}
/*
-------------------------
NPC_BSHuntAndKill
-------------------------
*/
void NPC_BSHuntAndKill( void )
{
qboolean turned = qfalse;
vec3_t vec;
float enemyDist;
visibility_t oEVis;
int curAnim;
NPC_CheckEnemy( NPCS.NPCInfo->tempBehavior != BS_HUNT_AND_KILL, qfalse, qtrue );//don't find new enemy if this is tempbehav
if ( NPCS.NPC->enemy )
{
oEVis = NPCS.enemyVisibility = NPC_CheckVisibility ( NPCS.NPC->enemy, CHECK_FOV|CHECK_SHOOT );//CHECK_360|//CHECK_PVS|
if(NPCS.enemyVisibility > VIS_PVS)
{
if ( !NPC_EnemyTooFar( NPCS.NPC->enemy, 0, qtrue ) )
{//Enemy is close enough to shoot - FIXME: this next func does this also, but need to know here for info on whether ot not to turn later
NPC_CheckCanAttack( 1.0, qfalse );
turned = qtrue;
}
}
curAnim = NPCS.NPC->client->ps.legsAnim;
if(curAnim != BOTH_ATTACK1 && curAnim != BOTH_ATTACK2 && curAnim != BOTH_ATTACK3 && curAnim != BOTH_MELEE1 && curAnim != BOTH_MELEE2 )
{//Don't move toward enemy if we're in a full-body attack anim
//FIXME, use IdealDistance to determin if we need to close distance
VectorSubtract(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, vec);
enemyDist = VectorLength(vec);
if( enemyDist > 48 && ((enemyDist*1.5)*(enemyDist*1.5) >= NPC_MaxDistSquaredForWeapon() ||
oEVis != VIS_SHOOT ||
//!(ucmd.buttons & BUTTON_ATTACK) ||
enemyDist > IdealDistance(NPCS.NPC)*3 ) )
{//We should close in?
NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy;
NPC_MoveToGoal( qtrue );
}
else if(enemyDist < IdealDistance(NPCS.NPC))
{//We should back off?
//if(ucmd.buttons & BUTTON_ATTACK)
{
NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy;
NPCS.NPCInfo->goalRadius = 12;
NPC_MoveToGoal( qtrue );
NPCS.ucmd.forwardmove *= -1;
NPCS.ucmd.rightmove *= -1;
VectorScale( NPCS.NPC->client->ps.moveDir, -1, NPCS.NPC->client->ps.moveDir );
NPCS.ucmd.buttons |= BUTTON_WALKING;
}
}//otherwise, stay where we are
}
}
else
{//ok, stand guard until we find an enemy
if( NPCS.NPCInfo->tempBehavior == BS_HUNT_AND_KILL )
{
NPCS.NPCInfo->tempBehavior = BS_DEFAULT;
}
else
{
NPCS.NPCInfo->tempBehavior = BS_STAND_GUARD;
NPC_BSStandGuard();
}
return;
}
if(!turned)
{
NPC_UpdateAngles(qtrue, qtrue);
}
}
void NPC_BSStandAndShoot (void)
{
//FIXME:
//When our numbers outnumber enemies 3 to 1, or only one of them,
//go into hunt and kill mode
//FIXME:
//When they're all dead, go to some script or wander off to sickbay?
if(NPCS.NPC->client->playerTeam && NPCS.NPC->client->enemyTeam)
{
//FIXME: don't realize this right away- or else enemies show up and we're standing around
/*
if( teamNumbers[NPC->enemyTeam] == 0 )
{//ok, stand guard until we find another enemy
//reset our rush counter
teamCounter[NPC->playerTeam] = 0;
NPCInfo->tempBehavior = BS_STAND_GUARD;
NPC_BSStandGuard();
return;
}*/
/*
//FIXME: whether to do this or not should be settable
else if( NPC->playerTeam != TEAM_BORG )//Borg don't rush
{
//FIXME: In case reinforcements show up, we should wait a few seconds
//and keep checking before rushing!
//Also: what if not everyone on our team is going after playerTeam?
//Also: our team count includes medics!
if(NPC->health > 25)
{//Can we rush the enemy?
if(teamNumbers[NPC->enemyTeam] == 1 ||
teamNumbers[NPC->playerTeam] >= teamNumbers[NPC->enemyTeam]*3)
{//Only one of them or we outnumber 3 to 1
if(teamStrength[NPC->playerTeam] >= 75 ||
(teamStrength[NPC->playerTeam] >= 50 && teamStrength[NPC->playerTeam] > teamStrength[NPC->enemyTeam]))
{//Our team is strong enough to rush
teamCounter[NPC->playerTeam]++;
if(teamNumbers[NPC->playerTeam] * 17 <= teamCounter[NPC->playerTeam])
{//ok, we waited 1.7 think cycles on average and everyone is go, let's do it!
//FIXME: Should we do this to everyone on our team?
NPCInfo->behaviorState = BS_HUNT_AND_KILL;
//FIXME: if the tide changes, we should retreat!
//FIXME: when do we reset the counter?
NPC_BSHuntAndKill ();
return;
}
}
else//Oops! Something's wrong, reset the counter to rush
teamCounter[NPC->playerTeam] = 0;
}
else//Oops! Something's wrong, reset the counter to rush
teamCounter[NPC->playerTeam] = 0;
}
}
*/
}
NPC_CheckEnemy(qtrue, qfalse, qtrue);
if(NPCS.NPCInfo->duckDebounceTime > level.time && NPCS.NPC->client->ps.weapon != WP_SABER )
{
NPCS.ucmd.upmove = -127;
if(NPCS.NPC->enemy)
{
NPC_CheckCanAttack(1.0, qtrue);
}
return;
}
if(NPCS.NPC->enemy)
{
if(!NPC_StandTrackAndShoot( NPCS.NPC, qtrue ))
{//That func didn't update our angles
NPCS.NPCInfo->desiredYaw = NPCS.NPC->client->ps.viewangles[YAW];
NPCS.NPCInfo->desiredPitch = NPCS.NPC->client->ps.viewangles[PITCH];
NPC_UpdateAngles(qtrue, qtrue);
}
}
else
{
NPCS.NPCInfo->desiredYaw = NPCS.NPC->client->ps.viewangles[YAW];
NPCS.NPCInfo->desiredPitch = NPCS.NPC->client->ps.viewangles[PITCH];
NPC_UpdateAngles(qtrue, qtrue);
// NPC_BSIdle();//only moves if we have a goal
}
}
void NPC_BSRunAndShoot (void)
{
/*if(NPC->playerTeam && NPC->enemyTeam)
{
//FIXME: don't realize this right away- or else enemies show up and we're standing around
if( teamNumbers[NPC->enemyTeam] == 0 )
{//ok, stand guard until we find another enemy
//reset our rush counter
teamCounter[NPC->playerTeam] = 0;
NPCInfo->tempBehavior = BS_STAND_GUARD;
NPC_BSStandGuard();
return;
}
}*/
//NOTE: are we sure we want ALL run and shoot people to move this way?
//Shouldn't it check to see if we have an enemy and our enemy is our goal?!
//Moved that check into NPC_MoveToGoal
//NPCInfo->combatMove = qtrue;
NPC_CheckEnemy( qtrue, qfalse, qtrue );
if ( NPCS.NPCInfo->duckDebounceTime > level.time ) // && NPCInfo->hidingGoal )
{
NPCS.ucmd.upmove = -127;
if ( NPCS.NPC->enemy )
{
NPC_CheckCanAttack( 1.0, qfalse );
}
return;
}
if ( NPCS.NPC->enemy )
{
int monitor = NPCS.NPC->cantHitEnemyCounter;
NPC_StandTrackAndShoot( NPCS.NPC, qfalse );//(NPCInfo->hidingGoal != NULL) );
if ( !(NPCS.ucmd.buttons & BUTTON_ATTACK) && NPCS.ucmd.upmove >= 0 && NPCS.NPC->cantHitEnemyCounter > monitor )
{//not crouching and not firing
vec3_t vec;
VectorSubtract( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, vec );
vec[2] = 0;
if ( VectorLength( vec ) > 128 || NPCS.NPC->cantHitEnemyCounter >= 10 )
{//run at enemy if too far away
//The cantHitEnemyCounter getting high has other repercussions
//100 (10 seconds) will make you try to pick a new enemy...
//But we're chasing, so we clamp it at 50 here
if ( NPCS.NPC->cantHitEnemyCounter > 60 )
{
NPCS.NPC->cantHitEnemyCounter = 60;
}
if ( NPCS.NPC->cantHitEnemyCounter >= (NPCS.NPCInfo->stats.aggression+1) * 10 )
{
NPC_LostEnemyDecideChase();
}
//chase and face
NPCS.ucmd.angles[YAW] = 0;
NPCS.ucmd.angles[PITCH] = 0;
NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy;
NPCS.NPCInfo->goalRadius = 12;
//NAV_ClearLastRoute(NPC);
NPC_MoveToGoal( qtrue );
NPC_UpdateAngles(qtrue, qtrue);
}
else
{
//FIXME: this could happen if they're just on the other side
//of a thin wall or something else blocking out shot. That
//would make us just stand there and not go around it...
//but maybe it's okay- might look like we're waiting for
//him to come out...?
//Current solution: runs around if cantHitEnemyCounter gets
//to 10 (1 second).
}
}
else
{//Clear the can't hit enemy counter here
NPCS.NPC->cantHitEnemyCounter = 0;
}
}
else
{
if ( NPCS.NPCInfo->tempBehavior == BS_HUNT_AND_KILL )
{//lost him, go back to what we were doing before
NPCS.NPCInfo->tempBehavior = BS_DEFAULT;
return;
}
// NPC_BSRun();//only moves if we have a goal
}
}
//Simply turn until facing desired angles
void NPC_BSFace (void)
{
//FIXME: once you stop sending turning info, they reset to whatever their delta_angles was last????
//Once this is over, it snaps back to what it was facing before- WHY???
if( NPC_UpdateAngles ( qtrue, qtrue ) )
{
trap->ICARUS_TaskIDComplete( (sharedEntity_t *)NPCS.NPC, TID_BSTATE );
NPCS.NPCInfo->desiredYaw = NPCS.client->ps.viewangles[YAW];
NPCS.NPCInfo->desiredPitch = NPCS.client->ps.viewangles[PITCH];
NPCS.NPCInfo->aimTime = 0;//ok to turn normally now
}
}
void NPC_BSPointShoot (qboolean shoot)
{//FIXME: doesn't check for clear shot...
vec3_t muzzle, dir, angles, org;
if ( !NPCS.NPC->enemy || !NPCS.NPC->enemy->inuse || (NPCS.NPC->enemy->NPC && NPCS.NPC->enemy->health <= 0) )
{//FIXME: should still keep shooting for a second or two after they actually die...
trap->ICARUS_TaskIDComplete( (sharedEntity_t *)NPCS.NPC, TID_BSTATE );
goto finished;
}
CalcEntitySpot(NPCS.NPC, SPOT_WEAPON, muzzle);
CalcEntitySpot(NPCS.NPC->enemy, SPOT_HEAD, org);//Was spot_org
//Head is a little high, so let's aim for the chest:
if ( NPCS.NPC->enemy->client )
{
org[2] -= 12;//NOTE: is this enough?
}
VectorSubtract(org, muzzle, dir);
vectoangles(dir, angles);
switch( NPCS.NPC->client->ps.weapon )
{
case WP_NONE:
// case WP_TRICORDER:
case WP_STUN_BATON:
case WP_SABER:
//don't do any pitch change if not holding a firing weapon
break;
default:
NPCS.NPCInfo->desiredPitch = NPCS.NPCInfo->lockedDesiredPitch = AngleNormalize360(angles[PITCH]);
break;
}
NPCS.NPCInfo->desiredYaw = NPCS.NPCInfo->lockedDesiredYaw = AngleNormalize360(angles[YAW]);
if ( NPC_UpdateAngles ( qtrue, qtrue ) )
{//FIXME: if angles clamped, this may never work!
//NPCInfo->shotTime = NPC->attackDebounceTime = 0;
if ( shoot )
{//FIXME: needs to hold this down if using a weapon that requires it, like phaser...
NPCS.ucmd.buttons |= BUTTON_ATTACK;
}
//if ( !shoot || !(NPC->svFlags & SVF_LOCKEDENEMY) )
if (1)
{//If locked_enemy is on, dont complete until it is destroyed...
trap->ICARUS_TaskIDComplete( (sharedEntity_t *)NPCS.NPC, TID_BSTATE );
goto finished;
}
}
//else if ( shoot && (NPC->svFlags & SVF_LOCKEDENEMY) )
if (0)
{//shooting them till their dead, not aiming right at them yet...
/*
qboolean movingTarget = qfalse;
if ( NPC->enemy->client )
{
if ( VectorLengthSquared( NPC->enemy->client->ps.velocity ) )
{
movingTarget = qtrue;
}
}
else if ( VectorLengthSquared( NPC->enemy->s.pos.trDelta ) )
{
movingTarget = qtrue;
}
if (movingTarget )
*/
{
float dist = VectorLength( dir );
float yawMiss, yawMissAllow = NPCS.NPC->enemy->r.maxs[0];
float pitchMiss, pitchMissAllow = (NPCS.NPC->enemy->r.maxs[2] - NPCS.NPC->enemy->r.mins[2])/2;
if ( yawMissAllow < 8.0f )
{
yawMissAllow = 8.0f;
}
if ( pitchMissAllow < 8.0f )
{
pitchMissAllow = 8.0f;
}
yawMiss = tan(DEG2RAD(AngleDelta ( NPCS.NPC->client->ps.viewangles[YAW], NPCS.NPCInfo->desiredYaw ))) * dist;
pitchMiss = tan(DEG2RAD(AngleDelta ( NPCS.NPC->client->ps.viewangles[PITCH], NPCS.NPCInfo->desiredPitch))) * dist;
if ( yawMissAllow >= yawMiss && pitchMissAllow > pitchMiss )
{
NPCS.ucmd.buttons |= BUTTON_ATTACK;
}
}
}
return;
finished:
NPCS.NPCInfo->desiredYaw = NPCS.client->ps.viewangles[YAW];
NPCS.NPCInfo->desiredPitch = NPCS.client->ps.viewangles[PITCH];
NPCS.NPCInfo->aimTime = 0;//ok to turn normally now
}
/*
void NPC_BSMove(void)
Move in a direction, face another
*/
void NPC_BSMove(void)
{
gentity_t *goal = NULL;
NPC_CheckEnemy(qtrue, qfalse, qtrue);
if(NPCS.NPC->enemy)
{
NPC_CheckCanAttack(1.0, qfalse);
}
else
{
NPC_UpdateAngles(qtrue, qtrue);
}
goal = UpdateGoal();
if(goal)
{
// NPCInfo->moveToGoalMod = 1.0;
NPC_SlideMoveToGoal();
}
}
/*
void NPC_BSShoot(void)
Move in a direction, face another
*/
void NPC_BSShoot(void)
{
// NPC_BSMove();
NPCS.enemyVisibility = VIS_SHOOT;
if ( NPCS.client->ps.weaponstate != WEAPON_READY && NPCS.client->ps.weaponstate != WEAPON_FIRING )
{
NPCS.client->ps.weaponstate = WEAPON_READY;
}
WeaponThink(qtrue);
}
/*
void NPC_BSPatrol( void )
Same as idle, but you look for enemies every "vigilance"
using your angles, HFOV, VFOV and visrange, and listen for sounds within earshot...
*/
void NPC_BSPatrol( void )
{
//int alertEventNum;
if(level.time > NPCS.NPCInfo->enemyCheckDebounceTime)
{
NPCS.NPCInfo->enemyCheckDebounceTime = level.time + (NPCS.NPCInfo->stats.vigilance * 1000);
NPC_CheckEnemy(qtrue, qfalse, qtrue);
if(NPCS.NPC->enemy)
{//FIXME: do anger script
NPCS.NPCInfo->behaviorState = BS_HUNT_AND_KILL;
//NPC_AngerSound();
return;
}
}
//FIXME: Implement generic sound alerts
/*
alertEventNum = NPC_CheckAlertEvents( qtrue, qtrue );
if( alertEventNum != -1 )
{//If we heard something, see if we should check it out
if ( NPC_CheckInvestigate( alertEventNum ) )
{
return;
}
}
*/
NPCS.NPCInfo->investigateSoundDebounceTime = 0;
//FIXME if there is no nav data, we need to do something else
// if we're stuck, try to move around it
if ( UpdateGoal() )
{
NPC_MoveToGoal( qtrue );
}
NPC_UpdateAngles( qtrue, qtrue );
NPCS.ucmd.buttons |= BUTTON_WALKING;
}
/*
void NPC_BSDefault(void)
uses various scriptflags to determine how an npc should behave
*/
extern void NPC_CheckGetNewWeapon( void );
extern void NPC_BSST_Attack( void );
void NPC_BSDefault( void )
{
// vec3_t enemyDir;
// float enemyDist;
// float shootDist;
// qboolean enemyFOV = qfalse;
// qboolean enemyShotFOV = qfalse;
// qboolean enemyPVS = qfalse;
// vec3_t enemyHead;
// vec3_t muzzle;
// qboolean enemyLOS = qfalse;
// qboolean enemyCS = qfalse;
qboolean move = qtrue;
// qboolean shoot = qfalse;
if( NPCS.NPCInfo->scriptFlags & SCF_FIRE_WEAPON )
{
WeaponThink( qtrue );
}
if ( NPCS.NPCInfo->scriptFlags & SCF_FORCED_MARCH )
{//being forced to walk
if( NPCS.NPC->client->ps.torsoAnim != TORSO_SURRENDER_START )
{
NPC_SetAnim( NPCS.NPC, SETANIM_TORSO, TORSO_SURRENDER_START, SETANIM_FLAG_HOLD );
}
}
//look for a new enemy if don't have one and are allowed to look, validate current enemy if have one
NPC_CheckEnemy( (NPCS.NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES), qfalse, qtrue );
if ( !NPCS.NPC->enemy )
{//still don't have an enemy
if ( !(NPCS.NPCInfo->scriptFlags&SCF_IGNORE_ALERTS) )
{//check for alert events
//FIXME: Check Alert events, see if we should investigate or just look at it
int alertEvent = NPC_CheckAlertEvents( qtrue, qtrue, -1, qtrue, AEL_DISCOVERED );
//There is an event to look at
if ( alertEvent >= 0 && level.alertEvents[alertEvent].ID != NPCS.NPCInfo->lastAlertID )
{//heard/saw something
if ( level.alertEvents[alertEvent].level >= AEL_DISCOVERED && (NPCS.NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES) )
{//was a big event
if ( level.alertEvents[alertEvent].owner && level.alertEvents[alertEvent].owner->client && level.alertEvents[alertEvent].owner->health >= 0 && level.alertEvents[alertEvent].owner->client->playerTeam == NPCS.NPC->client->enemyTeam )
{//an enemy
G_SetEnemy( NPCS.NPC, level.alertEvents[alertEvent].owner );
}
}
else
{//FIXME: investigate lesser events
}
}
//FIXME: also check our allies' condition?
}
}
if ( NPCS.NPC->enemy && !(NPCS.NPCInfo->scriptFlags&SCF_FORCED_MARCH) )
{
// just use the stormtrooper attack AI...
NPC_CheckGetNewWeapon();
if ( NPCS.NPC->client->leader
&& NPCS.NPCInfo->goalEntity == NPCS.NPC->client->leader
&& !trap->ICARUS_TaskIDPending( (sharedEntity_t *)NPCS.NPC, TID_MOVE_NAV ) )
{
NPC_ClearGoal();
}
NPC_BSST_Attack();
return;
/*
//have an enemy
//FIXME: if one of these fails, meaning we can't shoot, do we really need to do the rest?
VectorSubtract( NPC->enemy->r.currentOrigin, NPC->r.currentOrigin, enemyDir );
enemyDist = VectorNormalize( enemyDir );
enemyDist *= enemyDist;
shootDist = NPC_MaxDistSquaredForWeapon();
enemyFOV = InFOV( NPC->enemy, NPC, NPCInfo->stats.hfov, NPCInfo->stats.vfov );
enemyShotFOV = InFOV( NPC->enemy, NPC, 20, 20 );
enemyPVS = trap->inPVS( NPC->enemy->r.currentOrigin, NPC->r.currentOrigin );
if ( enemyPVS )
{//in the pvs
trace_t tr;
CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemyHead );
enemyHead[2] -= Q_flrand( 0.0f, NPC->enemy->maxs[2]*0.5f );
CalcEntitySpot( NPC, SPOT_WEAPON, muzzle );
enemyLOS = NPC_ClearLOS( muzzle, enemyHead );
trap->trace ( &tr, muzzle, vec3_origin, vec3_origin, enemyHead, NPC->s.number, MASK_SHOT );
enemyCS = NPC_EvaluateShot( tr.entityNum, qtrue );
}
else
{//skip thr 2 traces since they would have to fail
enemyLOS = qfalse;
enemyCS = qfalse;
}
if ( enemyCS && enemyShotFOV )
{//can hit enemy if we want
NPC->cantHitEnemyCounter = 0;
}
else
{//can't hit
NPC->cantHitEnemyCounter++;
}
if ( enemyCS && enemyShotFOV && enemyDist < shootDist )
{//can shoot
shoot = qtrue;
if ( NPCInfo->goalEntity == NPC->enemy )
{//my goal is my enemy and I have a clear shot, no need to chase right now
move = qfalse;
}
}
else
{//don't shoot yet, keep chasing
shoot = qfalse;
move = qtrue;
}
//shoot decision
if ( !(NPCInfo->scriptFlags&SCF_DONT_FIRE) )
{//try to shoot
if ( NPC->enemy )
{
if ( shoot )
{
if( !(NPCInfo->scriptFlags & SCF_FIRE_WEAPON) ) // we've already fired, no need to do it again here
{
WeaponThink( qtrue );
}
}
}
}
//chase decision
if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES )
{//go after him
NPCInfo->goalEntity = NPC->enemy;
//FIXME: don't need to chase when have a clear shot and in range?
if ( !enemyCS && NPC->cantHitEnemyCounter > 60 )
{//haven't been able to shoot enemy for about 6 seconds, need to do something
//FIXME: combat points? Just chase?
if ( enemyPVS )
{//in my PVS, just pick a combat point
//FIXME: implement
}
else
{//just chase him
}
}
//FIXME: in normal behavior, should we use combat Points? Do we care? Is anyone actually going to ever use this AI?
}
else if ( NPC->cantHitEnemyCounter > 60 )
{//pick a new one
NPC_CheckEnemy( qtrue, qfalse, qtrue );
}
if ( enemyPVS && enemyLOS )//&& !enemyShotFOV )
{//have a clear LOS to him//, but not looking at him
//Find the desired angles
vec3_t angles;
GetAnglesForDirection( muzzle, enemyHead, angles );
NPCInfo->desiredYaw = AngleNormalize180( angles[YAW] );
NPCInfo->desiredPitch = AngleNormalize180( angles[PITCH] );
}
*/
}
if ( UpdateGoal() )
{//have a goal
if ( !NPCS.NPC->enemy
&& NPCS.NPC->client->leader
&& NPCS.NPCInfo->goalEntity == NPCS.NPC->client->leader
&& !trap->ICARUS_TaskIDPending( (sharedEntity_t *)NPCS.NPC, TID_MOVE_NAV ) )
{
NPC_BSFollowLeader();
}
else
{
//set angles
if ( (NPCS.NPCInfo->scriptFlags & SCF_FACE_MOVE_DIR) || NPCS.NPCInfo->goalEntity != NPCS.NPC->enemy )
{//face direction of movement, NOTE: default behavior when not chasing enemy
NPCS.NPCInfo->combatMove = qfalse;
}
else
{//face goal.. FIXME: what if have a navgoal but want to face enemy while moving? Will this do that?
vec3_t dir, angles;
NPCS.NPCInfo->combatMove = qfalse;
VectorSubtract( NPCS.NPCInfo->goalEntity->r.currentOrigin, NPCS.NPC->r.currentOrigin, dir );
vectoangles( dir, angles );
NPCS.NPCInfo->desiredYaw = angles[YAW];
if ( NPCS.NPCInfo->goalEntity == NPCS.NPC->enemy )
{
NPCS.NPCInfo->desiredPitch = angles[PITCH];
}
}
//set movement
//override default walk/run behavior
//NOTE: redundant, done in NPC_ApplyScriptFlags
if ( NPCS.NPCInfo->scriptFlags & SCF_RUNNING )
{
NPCS.ucmd.buttons &= ~BUTTON_WALKING;
}
else if ( NPCS.NPCInfo->scriptFlags & SCF_WALKING )
{
NPCS.ucmd.buttons |= BUTTON_WALKING;
}
else if ( NPCS.NPCInfo->goalEntity == NPCS.NPC->enemy )
{
NPCS.ucmd.buttons &= ~BUTTON_WALKING;
}
else
{
NPCS.ucmd.buttons |= BUTTON_WALKING;
}
if ( NPCS.NPCInfo->scriptFlags & SCF_FORCED_MARCH )
{//being forced to walk
//if ( g_crosshairEntNum != NPC->s.number )
if (!NPC_SomeoneLookingAtMe(NPCS.NPC))
{//don't walk if player isn't aiming at me
move = qfalse;
}
}
if ( move )
{
//move toward goal
NPC_MoveToGoal( qtrue );
}
}
}
else if ( !NPCS.NPC->enemy && NPCS.NPC->client->leader )
{
NPC_BSFollowLeader();
}
//update angles
NPC_UpdateAngles( qtrue, qtrue );
}
| 0 | 0.975951 | 1 | 0.975951 | game-dev | MEDIA | 0.993602 | game-dev | 0.978131 | 1 | 0.978131 |
5zig/The-5zig-Mod | 1,616 | The 5zig Mod/src/eu/the5zig/mod/chat/gui/DateChatLine.java | package eu.the5zig.mod.chat.gui;
import eu.the5zig.mod.I18n;
import eu.the5zig.mod.The5zigMod;
import eu.the5zig.mod.chat.entity.Message;
import eu.the5zig.mod.gui.Gui;
import eu.the5zig.mod.gui.GuiConversations;
import eu.the5zig.mod.gui.GuiParty;
import eu.the5zig.util.Utils;
import java.util.List;
/**
* Created by 5zig.
* All rights reserved © 2015
*/
public class DateChatLine extends CenteredChatLine {
public final int LINE_HEIGHT = 8;
public final int MESSAGE_HEIGHT = 14;
private long time;
public DateChatLine(Message message) {
super(message);
this.time = message.getTime();
}
@Override
public void draw(int x, int y) {
int yy = 2;
float scale = 0.8f;
String line = Utils.convertToDateWithoutTime(time).replace("Today", I18n.translate("profile.today")).replace("Yesterday", I18n.translate("profile.yesterday"));
Gui.drawScaledString(line, x + 9 + getMaxMessageWidth() / 2 - (int) (The5zigMod.getVars().getStringWidth(line) * scale) / 2, y + yy, scale);
}
@Override
public int getLineHeight() {
List<?> objects = The5zigMod.getVars().splitStringToWidth(getMessage().getMessage(), getMaxMessageWidth());
return (objects.size() - 1) * LINE_HEIGHT + MESSAGE_HEIGHT;
}
@Override
public int getMaxMessageWidth() {
if (The5zigMod.getVars().getCurrentScreen() instanceof GuiConversations) {
return ((GuiConversations) The5zigMod.getVars().getCurrentScreen()).getChatBoxWidth() - 20;
}
if (The5zigMod.getVars().getCurrentScreen() instanceof GuiParty) {
return ((GuiParty) The5zigMod.getVars().getCurrentScreen()).getChatBoxWidth() - 20;
}
return 100;
}
}
| 0 | 0.650303 | 1 | 0.650303 | game-dev | MEDIA | 0.671185 | game-dev | 0.792843 | 1 | 0.792843 |
opentibiabr/canary | 1,306 | data-otservbr-global/npc/humnog_the_guard.lua | local internalNpcName = "Humnog, the guard"
local npcType = Game.createNpcType(internalNpcName)
local npcConfig = {}
npcConfig.name = internalNpcName
npcConfig.description = internalNpcName
npcConfig.health = 100
npcConfig.maxHealth = npcConfig.health
npcConfig.walkInterval = 0
npcConfig.walkRadius = 2
npcConfig.outfit = {
lookType = 70,
lookHead = 20,
lookBody = 30,
lookLegs = 40,
lookFeet = 50,
lookAddons = 0,
}
npcConfig.flags = {
floorchange = false,
}
local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
npcType.onThink = function(npc, interval)
npcHandler:onThink(npc, interval)
end
npcType.onAppear = function(npc, creature)
npcHandler:onAppear(npc, creature)
end
npcType.onDisappear = function(npc, creature)
npcHandler:onDisappear(npc, creature)
end
npcType.onMove = function(npc, creature, fromPosition, toPosition)
npcHandler:onMove(npc, creature, fromPosition, toPosition)
end
npcType.onSay = function(npc, creature, type, message)
npcHandler:onSay(npc, creature, type, message)
end
npcType.onCloseChannel = function(npc, creature)
npcHandler:onCloseChannel(npc, creature)
end
npcHandler:addModule(FocusModule:new(), npcConfig.name, true, true, true)
-- npcType registering the npcConfig table
npcType:register(npcConfig)
| 0 | 0.808834 | 1 | 0.808834 | game-dev | MEDIA | 0.913975 | game-dev | 0.592622 | 1 | 0.592622 |
supertuxkart/stk-code | 24,742 | src/challenges/challenge_data.cpp | //
// SuperTuxKart - a fun racing game with go-kart
// Copyright (C) 2008-2015 Joerg Henrichs
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#include "challenges/challenge_data.hpp"
#include <stdexcept>
#include <sstream>
#include "challenges/unlock_manager.hpp"
#include "io/file_manager.hpp"
#include "karts/abstract_kart.hpp"
#include "karts/kart_properties.hpp"
#include "karts/kart_properties_manager.hpp"
#include "modes/linear_world.hpp"
#include "race/grand_prix_data.hpp"
#include "race/grand_prix_manager.hpp"
#include "race/race_manager.hpp"
#include "replay/replay_play.hpp"
#include "tracks/track.hpp"
#include "tracks/track_manager.hpp"
#include "utils/string_utils.hpp"
#include "utils/translation.hpp"
ChallengeData::ChallengeData(const std::string& filename)
{
m_filename = filename;
m_mode = CM_SINGLE_RACE;
m_minor = RaceManager::MINOR_MODE_NORMAL_RACE;
m_num_laps = -1;
m_reverse = false;
m_track_id = "";
m_gp_id = "";
m_version = 0;
m_num_trophies = 0;
m_num_completed_challenges = 0;
m_is_unlock_list = false;
m_is_ghost_replay = false;
m_unlock_special_type = SPECIAL_NONE;
m_unlock_special_value = -1;
for (int d=0; d<RaceManager::DIFFICULTY_COUNT; d++)
{
m_default_num_karts[d] = -1;
m_position[d] = -1;
m_time[d] = -1.0f;
m_energy[d] = -1;
m_ai_superpower[d] = RaceManager::SUPERPOWER_NONE;
}
// we are using auto_ptr to make sure the XML node is released when leaving
// the scope
std::unique_ptr<XMLNode> root(new XMLNode( filename ));
if(root.get() == NULL || root->getName()!="challenge")
{
std::ostringstream msg;
msg << "Couldn't load challenge '" << filename
<< "': no challenge node.";
throw std::runtime_error(msg.str());
}
setChallengeId(StringUtils::removeExtension(StringUtils::getBasename(filename)));
root->get("version", &m_version);
// No need to get the rest of the data if this challenge
// is not supported anyway (id is needed for warning message)
if(!unlock_manager->isSupportedVersion(*this))
{
Log::warn("ChallengeData", "Challenge <%s> is older "
"or newer than this version of STK, will be ignored.\n",
filename.c_str());
return;
}
m_is_unlock_list = false;
const XMLNode* unlock_list_node = root->getNode("unlock_list");
if (unlock_list_node != NULL)
{
std::string list;
unlock_list_node->get("list", &list);
m_is_unlock_list = (list=="true");
}
std::vector<XMLNode*> unlocks;
root->getNodes("unlock", unlocks);
for(unsigned int i=0; i<unlocks.size(); i++)
{
std::string s;
if(unlocks[i]->get("kart", &s))
setUnlocks(s, ChallengeData::UNLOCK_KART);
else if(unlocks[i]->get("track", &s))
addUnlockTrackReward(s);
else if(unlocks[i]->get("gp", &s))
setUnlocks(s, ChallengeData::UNLOCK_GP);
else if(unlocks[i]->get("mode", &s))
setUnlocks(s, ChallengeData::UNLOCK_MODE);
else if(unlocks[i]->get("difficulty", &s))
setUnlocks(s, ChallengeData::UNLOCK_DIFFICULTY);
else
{
Log::warn("ChallengeData", "Unknown unlock entry. Must be one of kart, track, gp, mode, difficulty.");
throw std::runtime_error("Unknown unlock entry");
}
}
const XMLNode* requirements_node = root->getNode("requirements");
if (requirements_node == NULL)
{
throw std::runtime_error("Challenge file " + filename +
" has no <requirements> node!");
}
requirements_node->get("trophies", &m_num_trophies);
requirements_node->get("challenges", &m_num_completed_challenges);
if (m_is_unlock_list)
{
requirements_node = root->getNode("alt_requirements");
if (requirements_node != NULL)
{
if(requirements_node->get("max-req-in-lower-diff", &m_unlock_special_value))
m_unlock_special_type = SPECIAL_MAX_REQ_IN_LOWER_DIFF;
}
}
//Don't check further if this is an unlock list
if(m_is_unlock_list)
return;
const XMLNode* mode_node = root->getNode("mode");
if (mode_node == NULL)
{
throw std::runtime_error("Challenge file " + filename +
" has no <mode> node!");
}
std::string mode;
mode_node->get("major", &mode);
if(mode=="grandprix")
m_mode = CM_GRAND_PRIX;
else if(mode=="single")
m_mode = CM_SINGLE_RACE;
else if(mode=="any")
m_mode = CM_ANY;
else
error("major");
mode_node->get("minor", &mode);
if(mode=="timetrial")
m_minor = RaceManager::MINOR_MODE_TIME_TRIAL;
else if(mode=="quickrace")
m_minor = RaceManager::MINOR_MODE_NORMAL_RACE;
else if(mode=="followtheleader")
m_minor = RaceManager::MINOR_MODE_FOLLOW_LEADER;
else
error("minor");
const XMLNode* track_node = root->getNode("track");
const XMLNode* gp_node = root->getNode("grandprix");
if (m_mode == CM_SINGLE_RACE && track_node == NULL)
{
throw std::runtime_error("Challenge file " + filename +
" has no <track> node!");
}
if (m_mode == CM_GRAND_PRIX && gp_node == NULL)
{
throw std::runtime_error("Challenge file " + filename +
" has no <grandprix> node!");
}
if (track_node != NULL)
{
if (!track_node->get("id", &m_track_id ))
{
error("track");
}
if (track_manager->getTrack(m_track_id) == NULL)
{
error("track");
}
if (!track_node->get("laps", &m_num_laps) &&
m_minor != RaceManager::MINOR_MODE_FOLLOW_LEADER)
{
error("laps");
}
if (!track_node->get("reverse", &m_reverse))
{
Log::warn("Challenge Data",
"No reverse mode specified for challenge %s, defaulting to normal",
filename.c_str());
}
}
else if (gp_node != NULL)
{
if (!gp_node->get("id", &m_gp_id ))
{
error("grandprix");
}
}
const XMLNode* difficulties[RaceManager::DIFFICULTY_COUNT];
difficulties[0] = root->getNode("easy");
difficulties[1] = root->getNode("medium");
difficulties[2] = root->getNode("hard");
difficulties[3] = root->getNode("best");
if (difficulties[0] == NULL || difficulties[1] == NULL ||
difficulties[2] == NULL || difficulties[3] == NULL)
{
error("<easy> or <medium> or <hard> or <best>");
}
for (int d=0; d<=RaceManager::DIFFICULTY_BEST; d++)
{
const XMLNode* karts_node = difficulties[d]->getNode("karts");
if (karts_node == NULL) error("<karts .../>");
int num_karts = -1;
if (!karts_node->get("number", &num_karts)) error("karts");
m_default_num_karts[d] = num_karts;
std::string replay_file;
if (karts_node->get("replay_file", &replay_file))
{
m_is_ghost_replay = true;
m_replay_files[d] = replay_file;
}
std::string ai_kart_ident;
if (karts_node->get("aiIdent", &ai_kart_ident))
m_ai_kart_ident[d] = ai_kart_ident;
std::string superPower;
if (karts_node->get("superPower", &superPower))
{
if (superPower == "nolokBoss")
{
m_ai_superpower[d] = RaceManager::SUPERPOWER_NOLOK_BOSS;
}
else
{
Log::warn("ChallengeData", "Unknown superpower '%s'",
superPower.c_str());
}
}
const XMLNode* requirements_node =
difficulties[d]->getNode("requirements");
if (requirements_node == NULL) error("<requirements .../>");
int position = -1;
if (!requirements_node->get("position", &position) &&
(m_minor == RaceManager::MINOR_MODE_FOLLOW_LEADER ||
m_mode == CM_GRAND_PRIX))
{
error("position");
}
else
{
m_position[d] = position;
}
int time = -1;
if (requirements_node->get("time", &time)) m_time[d] = (float)time;
if (m_time[d] < 0 && m_position[d] < 0) error("position/time");
// This is optional
int energy = -1;
if (requirements_node->get("energy", &energy)) m_energy[d] = energy;
}
} // ChallengeData
// ----------------------------------------------------------------------------
const irr::core::stringw ChallengeData::getChallengeDescription() const
{
core::stringw description;
if (m_is_unlock_list)
return description;
if (m_mode == CM_GRAND_PRIX)
{
if (m_minor == RaceManager::MINOR_MODE_NORMAL_RACE)
description = _("Normal Race (Grand Prix)");
else if (m_minor == RaceManager::MINOR_MODE_TIME_TRIAL)
description = _("Time-Trial (Grand Prix)");
}
else if (!m_track_id.empty())
{
if (m_is_ghost_replay)
description = _("Time-Trial - beat the replay");
else if (m_energy[0] > 0)
description = _("Time-Trial - nitro challenge");
else if (m_minor == RaceManager::MINOR_MODE_NORMAL_RACE)
description = _("Normal Race (single race)");
else if (m_minor == RaceManager::MINOR_MODE_TIME_TRIAL)
description = _("Time-Trial (single race)");
else if (m_minor == RaceManager::MINOR_MODE_FOLLOW_LEADER)
description = _("Follow the Leader (single race)");
}
if (m_reverse == true)
{
description += core::stringw(L"\n");
description += _("Mode: Reverse");
}
return description;
} // getChallengeDescription
// ----------------------------------------------------------------------------
void ChallengeData::error(const char *id) const
{
std::ostringstream msg;
msg << "Undefined or incorrect value for '" << id
<< "' in challenge file '" << m_filename << "'.";
Log::error("ChallengeData", "%s", msg.str().c_str());
throw std::runtime_error(msg.str());
} // error
// ----------------------------------------------------------------------------
/** Checks if this challenge is valid, i.e. contains a valid track or a valid
* GP. If incorrect data are found, STK is aborted with an error message.
* (otherwise STK aborts when trying to do this challenge, which is worse).
*/
void ChallengeData::check() const
{
if(m_mode==CM_SINGLE_RACE)
{
try
{
track_manager->getTrack(m_track_id);
}
catch(std::exception&)
{
error("track");
}
}
else if(m_mode==CM_GRAND_PRIX)
{
const GrandPrixData* gp = grand_prix_manager->getGrandPrix(m_gp_id);
if (gp == NULL)
{
error("gp");
}
const bool gp_ok = gp->checkConsistency(false);
if (!gp_ok)
{
error("gp");
}
}
} // check
// ----------------------------------------------------------------------------
/** Adds all rewards for fulfilling this challenge.
* \param id Name of track or gp or kart or mode or difficulty reward.
* \param reward Type of reward (track, gp, mode, difficulty, kart).
*/
void ChallengeData::setUnlocks(const std::string &id, RewardType reward)
{
if (id.empty()) return;
switch(reward)
{
case UNLOCK_TRACK: assert (false);
break;
case UNLOCK_GP: addUnlockGPReward(id);
break;
case UNLOCK_MODE: {
const RaceManager::MinorRaceModeType mode =
RaceManager::getModeIDFromInternalName(id);
addUnlockModeReward(id,
RaceManager::getNameOf(mode));
break;
}
case UNLOCK_DIFFICULTY:
{
addUnlockDifficultyReward(id, core::stringw(id.c_str()));
break;
}
case UNLOCK_KART: {
const KartProperties* prop =
kart_properties_manager->getKart(id);
if (prop == NULL)
{
Log::warn("ChallengeData", "Challenge refers to kart %s, "
"which is unknown. Ignoring reward.",
id.c_str());
break;
}
irr::core::stringw user_name = prop->getName();
addUnlockKartReward(id, user_name);
break;
}
} // switch
} // setUnlocks
// ----------------------------------------------------------------------------
void ChallengeData::setRace(RaceManager::Difficulty d) const
{
if(m_mode==CM_GRAND_PRIX)
RaceManager::get()->setMajorMode(RaceManager::MAJOR_MODE_GRAND_PRIX);
else if(m_mode==CM_SINGLE_RACE)
RaceManager::get()->setMajorMode(RaceManager::MAJOR_MODE_SINGLE);
else
{
Log::error("challenge_data", "Invalid mode %d in setRace.", m_mode);
assert(false);
}
if(m_mode==CM_SINGLE_RACE)
{
RaceManager::get()->setMinorMode(m_minor);
RaceManager::get()->setTrack(m_track_id);
RaceManager::get()->setNumLaps(m_num_laps);
RaceManager::get()->setReverseTrack(m_reverse);
RaceManager::get()->setNumKarts(m_default_num_karts[d]);
RaceManager::get()->setNumPlayers(1);
RaceManager::get()->setCoinTarget(m_energy[d]);
RaceManager::get()->setDifficulty(d);
if (m_time[d] >= 0.0f)
{
RaceManager::get()->setTimeTarget(m_time[d]);
}
else
{
RaceManager::get()->setTimeTarget(0.0f);
}
}
else if(m_mode==CM_GRAND_PRIX)
{
RaceManager::get()->setMinorMode(m_minor);
RaceManager::get()->setGrandPrix(*grand_prix_manager->getGrandPrix(m_gp_id));
RaceManager::get()->setDifficulty(d);
RaceManager::get()->setNumKarts(m_default_num_karts[d]);
RaceManager::get()->setNumPlayers(1);
}
if (m_is_ghost_replay)
{
const bool result = ReplayPlay::get()->addReplayFile(file_manager
->getAsset(FileManager::REPLAY, m_replay_files[d]),
true/*custom_replay*/);
if (!result)
Log::fatal("ChallengeData", "Can't open replay for challenge!");
RaceManager::get()->setRaceGhostKarts(true);
}
if (m_ai_kart_ident[d] != "")
{
RaceManager::get()->setAIKartOverride(m_ai_kart_ident[d]);
}
if (m_ai_superpower[d] != RaceManager::SUPERPOWER_NONE)
{
RaceManager::get()->setAISuperPower(m_ai_superpower[d]);
}
} // setRace
// ----------------------------------------------------------------------------
/** Returns true if this (non-GP) challenge is fulfilled.
* \param check_best : if true, check if the requirement
* for the best difficulty are met at a lower one.
* (requires SuperTux challenges to have a time
ù requirement to make sense)
*/
bool ChallengeData::isChallengeFulfilled(bool check_best) const
{
// GP's use the grandPrixFinished() function,
// so they can't be fulfilled here.
if(m_mode==CM_GRAND_PRIX) return false;
// Single races
// ------------
World *world = World::getWorld();
std::string track_name = Track::getCurrentTrack()->getIdent();
int d = (check_best) ? RaceManager::DIFFICULTY_BEST :
RaceManager::get()->getDifficulty();
AbstractKart* kart = world->getPlayerKart(0);
if (kart->isEliminated() ) return false;
if (track_name != m_track_id ) return false;
if (((int)world->getNumKarts() < m_default_num_karts[d]) && !check_best) return false;
if (m_energy[d] > 0 && kart->getEnergy() < m_energy[d] ) return false;
if (m_position[d] > 0 && kart->getPosition() > m_position[d] ) return false;
// Follow the leader
// -----------------
if(m_minor==RaceManager::MINOR_MODE_FOLLOW_LEADER)
{
// All possible conditions were already checked, so:
// must have been successful
return true;
}
// Quickrace / Timetrial
// ---------------------
// FIXME - encapsulate this better, each race mode needs to be able
// to specify its own challenges and deal with them
LinearWorld* lworld = dynamic_cast<LinearWorld*>(world);
if(lworld != NULL)
{
// wrong number of laps
if(lworld->getLapForKart( kart->getWorldKartId() ) != m_num_laps)
return false;
}
// too slow
if (m_time[d] > 0.0f && kart->getFinishTime() > m_time[d]) return false;
// too slow
if (m_is_ghost_replay)
{
ReplayPlay::get()->addReplayFile(file_manager
->getAsset(FileManager::REPLAY, m_replay_files[d]),
true/*custom_replay*/);
const ReplayPlay::ReplayData& rd = ReplayPlay::get()->getCurrentReplayData();
if (kart->getFinishTime() > rd.m_min_time)
return false;
}
if (m_ai_superpower[d] != RaceManager::SUPERPOWER_NONE &&
RaceManager::get()->getAISuperPower() != m_ai_superpower[d])
{
return false;
}
return true;
} // isChallengeFulfilled
// ----------------------------------------------------------------------------
/** Returns true if this GP challenge is fulfilled.
*/
ChallengeData::GPLevel ChallengeData::isGPFulfilled() const
{
int d = RaceManager::get()->getDifficulty();
// Note that we have to call RaceManager::get()->getNumKarts, since there
// is no world objects to query at this stage.
if (RaceManager::get()->getMajorMode() != RaceManager::MAJOR_MODE_GRAND_PRIX ||
RaceManager::get()->getMinorMode() != m_minor ||
RaceManager::get()->getGrandPrix().getId() != m_gp_id ||
RaceManager::get()->getNumberOfKarts() < (unsigned int)m_default_num_karts[d] ||
RaceManager::get()->getNumPlayers() > 1) return GP_NONE;
// check if the player came first.
// rank == 0 if first, 1 if second, etc.
const int rank = RaceManager::get()->getLocalPlayerGPRank(0);
// In superior difficulty levels, losing a place means
// getting a cup of the inferior level rather than
// nothing at all
int unlock_level = d - rank;
if (unlock_level == 3)
return GP_BEST;
if (unlock_level == 2)
return GP_HARD;
if (unlock_level == 1)
return GP_MEDIUM;
if (unlock_level == 0)
return GP_EASY;
return GP_NONE;
} // isGPFulfilled
// ----------------------------------------------------------------------------
const irr::core::stringw
ChallengeData::UnlockableFeature::getUnlockedMessage() const
{
switch (m_type)
{
case UNLOCK_TRACK:
{ // {} avoids compiler warning
const Track* track = track_manager->getTrack(m_name);
// shouldn't happen but let's avoid crashes as much as possible...
if (track == NULL) return irr::core::stringw( L"????" );
return _("New track '%s' now available", track->getName());
}
case UNLOCK_MODE:
{
return _("New game mode '%s' now available", m_user_name);
}
case UNLOCK_GP:
{
const GrandPrixData* gp = grand_prix_manager->getGrandPrix(m_name);
// shouldn't happen but let's avoid crashes as much as possible...
if (gp == NULL) return irr::core::stringw( L"????" );
const irr::core::stringw& gp_user_name = gp->getName();
return _("New Grand Prix '%s' now available", gp_user_name);
}
case UNLOCK_DIFFICULTY:
{
return _("New difficulty '%s' now available", m_user_name);
}
case UNLOCK_KART:
{
const KartProperties* kp =
kart_properties_manager->getKart(m_name);
// shouldn't happen but let's avoid crashes as much as possible...
if (kp == NULL) return irr::core::stringw( L"????" );
return _("New kart '%s' now available", kp->getName());
}
default:
assert(false);
return L"";
} // switch
} // UnlockableFeature::getUnlockedMessage
//-----------------------------------------------------------------------------
/** Sets that the given track will be unlocked if this challenge
* is unlocked.
* \param track_name Name of the track to unlock.
*/
void ChallengeData::addUnlockTrackReward(const std::string &track_name)
{
if (track_manager->getTrack(track_name) == NULL)
{
throw std::runtime_error(
StringUtils::insertValues("Challenge refers to unknown track <%s>",
track_name.c_str()));
}
UnlockableFeature feature;
feature.m_name = track_name;
feature.m_type = UNLOCK_TRACK;
m_feature.push_back(feature);
} // addUnlockTrackReward
//-----------------------------------------------------------------------------
void ChallengeData::addUnlockModeReward(const std::string &internal_mode_name,
const irr::core::stringw &user_mode_name)
{
UnlockableFeature feature;
feature.m_name = internal_mode_name;
feature.m_type = UNLOCK_MODE;
feature.m_user_name = user_mode_name;
m_feature.push_back(feature);
} // addUnlockModeReward
//-----------------------------------------------------------------------------
void ChallengeData::addUnlockGPReward(const std::string &gp_name)
{
if (grand_prix_manager->getGrandPrix(gp_name) == NULL)
{
throw std::runtime_error(
StringUtils::insertValues(
"Challenge refers to unknown Grand Prix <%s>",
gp_name.c_str()));
}
UnlockableFeature feature;
feature.m_name = gp_name.c_str();
feature.m_type = UNLOCK_GP;
m_feature.push_back(feature);
} // addUnlockGPReward
//-----------------------------------------------------------------------------
void ChallengeData::addUnlockDifficultyReward(const std::string &internal_name,
const irr::core::stringw &user_name)
{
UnlockableFeature feature;
feature.m_name = internal_name;
feature.m_type = UNLOCK_DIFFICULTY;
feature.m_user_name = user_name;
m_feature.push_back(feature);
} // addUnlockDifficultyReward
//-----------------------------------------------------------------------------
void ChallengeData::addUnlockKartReward(const std::string &internal_name,
const irr::core::stringw &user_name)
{
try
{
kart_properties_manager->getKartId(internal_name);
}
catch (std::exception& e)
{
(void)e; // avoid compiler warning
throw std::runtime_error(
StringUtils::insertValues("Challenge refers to unknown kart <%s>",
internal_name.c_str()));
}
UnlockableFeature feature;
feature.m_name = internal_name;
feature.m_type = UNLOCK_KART;
feature.m_user_name = user_name;
m_feature.push_back(feature);
} // addUnlockKartReward
| 0 | 0.992773 | 1 | 0.992773 | game-dev | MEDIA | 0.80838 | game-dev | 0.97376 | 1 | 0.97376 |
Xeeynamo/sotn-decomp | 3,937 | src/boss/rbo3/12D64.c | // SPDX-License-Identifier: AGPL-3.0-or-later
#include "rbo3.h"
extern EInit D_us_801804BC;
extern s32 D_us_8018072C;
extern u32 D_psp_09254D28;
void func_us_80192D64(Entity* self) {
s32 i;
s32 fg;
s32 fgIndex;
s32 y;
Entity* next;
switch (self->step) {
case 0:
InitializeEntity(D_us_801804BC);
self->zPriority = 0x5C;
if (self->params & 2) {
self->animCurFrame = 0xE;
return;
}
if (self->params & 1) {
self->animCurFrame = 13;
self->posX.i.hi = 48 - g_Tilemap.scrollX.i.hi;
self->posY.i.hi = 224 - g_Tilemap.scrollY.i.hi;
} else {
self->animCurFrame = 12;
self->posX.i.hi = 496 - g_Tilemap.scrollX.i.hi;
self->posY.i.hi = 224 - g_Tilemap.scrollY.i.hi;
}
next = self + 1;
#ifdef VERSION_PSP
CreateEntityFromEntity(D_psp_09254D28, self, next);
#else
CreateEntityFromEntity(UNK_ENTITY_29, self, self + 1);
#endif
next->params = 2;
next->posY.i.hi = 96;
if (self->params) {
next->posX.i.hi -= 16;
}
break;
case 1:
if (D_us_8018072C) {
if (self->params & 2) {
self->step = 8;
break;
}
if (self->params) {
fgIndex = 0xC1;
} else {
fgIndex = 0xDE;
}
for (i = 0; i < 4; i++) {
g_Tilemap.fg[fgIndex] = 0x4B3;
fgIndex += 0x20;
}
self->step = 2;
}
break;
case 2:
self->posY.val -= FIX(1.125);
if (self->posY.i.hi < 186) {
self->posY.i.hi = 186;
self->step++;
}
break;
case 3:
if (D_us_8018072C == 0) {
if (self->params) {
fgIndex = 0xC1;
} else {
fgIndex = 0xDE;
}
for (i = 0; i < 4; i++) {
g_Tilemap.fg[fgIndex] = 0;
fgIndex += 0x20;
}
self->step++;
}
break;
case 4:
self->posY.val += FIX(0.75);
y = self->posY.i.hi + g_Tilemap.scrollY.i.hi;
if (y > 0xE0) {
self->posY.i.hi = 0xE0 - g_Tilemap.scrollY.i.hi;
self->step++;
}
break;
case 5:
case 6:
case 7:
break;
case 8:
self->posY.val += FIX(1.125);
if (self->posY.i.hi > 127) {
self->posY.i.hi = 127;
self->step++;
}
break;
case 9:
if (D_us_8018072C == 0) {
self->step++;
}
break;
case 10:
self->posY.val += FIX(-0.75);
y = self->posY.i.hi + g_Tilemap.scrollY.i.hi;
if (y < 96) {
self->posY.i.hi = 96 - g_Tilemap.scrollY.i.hi;
self->step++;
}
break;
case 11:
break;
}
}
extern EInit g_EInitInteractable;
void func_us_80193050(Entity* self) {
Primitive* prim;
s16 primIndex;
s32 x;
if (self->step != 0) {
return;
}
InitializeEntity(g_EInitInteractable);
primIndex = g_api.AllocPrimitives(PRIM_GT4, 5);
if (primIndex == -1) {
DestroyEntity(self);
return;
}
prim = &g_PrimBuf[primIndex];
self->primIndex = primIndex;
self->flags |= FLAG_HAS_PRIMS;
x = 0;
while (prim != NULL) {
prim->x0 = prim->x2 = x;
x += 62;
prim->x1 = prim->x3 = x;
prim->tpage = 0xF;
prim->clut = 0xC5;
prim->u0 = prim->u2 = 65;
prim->u1 = prim->u3 = 127;
prim->v0 = prim->v1 = 169;
prim->v2 = prim->v3 = 198;
prim->y0 = prim->y1 = 64;
prim->y2 = prim->y3 = 18;
prim->priority = 0x10;
prim->drawMode = DRAW_DEFAULT;
prim = prim->next;
}
}
| 0 | 0.77754 | 1 | 0.77754 | game-dev | MEDIA | 0.300635 | game-dev | 0.985037 | 1 | 0.985037 |
MrCrayfish/Controllable | 1,481 | common/src/main/java/com/mrcrayfish/controllable/client/gui/components/TabOptionTitleItem.java | package com.mrcrayfish.controllable.client.gui.components;
import com.mrcrayfish.controllable.client.gui.navigation.SkipItem;
import com.mrcrayfish.controllable.client.util.ScreenHelper;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.events.GuiEventListener;
import net.minecraft.client.gui.narration.NarratableEntry;
import net.minecraft.network.chat.Component;
import java.util.Collections;
import java.util.List;
/**
* Author: MrCrayfish
*/
public class TabOptionTitleItem extends TabOptionBaseItem implements SkipItem
{
public TabOptionTitleItem(Component label)
{
super(label);
}
@Override
public void renderContent(GuiGraphics graphics, int mouseX, int mouseY, boolean hovered, float partialTick)
{
Font font = Minecraft.getInstance().font;
int labelWidth = font.width(this.label) + 2;
ScreenHelper.drawRoundedBox(graphics, this.getX() + this.getWidth() / 2 - labelWidth / 2, this.getY() + 4, labelWidth, 14, 0x88000000);
graphics.drawCenteredString(font, this.label, this.getX() + this.getWidth() / 2, this.getY() + 7, 0xFFFFFFFF);
}
@Override
public List<? extends NarratableEntry> narratables()
{
return Collections.emptyList();
}
@Override
public List<? extends GuiEventListener> children()
{
return Collections.emptyList();
}
}
| 0 | 0.776469 | 1 | 0.776469 | game-dev | MEDIA | 0.980003 | game-dev | 0.939102 | 1 | 0.939102 |
nasfadev/store-simulator-game | 29,055 | Assets/Plugins/CW/LeanLocalization/Required/Scripts/LeanLocalization.cs | using UnityEngine;
using System.Collections.Generic;
using Lean.Common;
using CW.Common;
namespace Lean.Localization
{
/// <summary>This component manages a global list of translations for easy access.
/// Translations are gathered from the <b>prefabs</b> list, as well as from any active and enabled <b>LeanSource</b> components in the scene.</summary>
[ExecuteInEditMode]
[HelpURL(HelpUrlPrefix + "LeanLocalization")]
[AddComponentMenu(ComponentPathPrefix + "Localization")]
public class LeanLocalization : MonoBehaviour
{
public enum DetectType
{
None,
SystemLanguage,
CurrentCulture,
CurrentUICulture
}
public enum SaveLoadType
{
None,
WhenChanged,
WhenChangedAlt
}
public const string HelpUrlPrefix = LeanCommon.HelpUrlPrefix + "LeanLocalization#";
public const string ComponentPathPrefix = "Lean/Localization/Lean ";
/// <summary>All active and enabled LeanLocalization components.</summary>
public static List<LeanLocalization> Instances = new List<LeanLocalization>();
public static Dictionary<string, LeanToken> CurrentTokens = new Dictionary<string, LeanToken>();
public static Dictionary<string, LeanLanguage> CurrentLanguages = new Dictionary<string, LeanLanguage>();
public static Dictionary<string, string> CurrentAliases = new Dictionary<string, string>();
/// <summary>Dictionary of all the phrase names mapped to their current translations.</summary>
public static Dictionary<string, LeanTranslation> CurrentTranslations = new Dictionary<string, LeanTranslation>();
/// <summary>The language that is currently being used by this instance.</summary>
[LeanLanguageName]
[SerializeField]
private string currentLanguage;
/// <summary>How should the cultures be used to detect the user's device language?</summary>
public DetectType DetectLanguage { set { detectLanguage = value; } get { return detectLanguage; } } [SerializeField] private DetectType detectLanguage = DetectType.SystemLanguage;
/// <summary>If the application is started and no language has been loaded or auto detected, this language will be used.</summary>
public string DefaultLanguage { set { defaultLanguage = value; } get { return defaultLanguage; } } [SerializeField] [LeanLanguageName] private string defaultLanguage;
/// <summary>This allows you to control if/how this component's <b>CurrentLanguage</b> setting should save/load.
/// None = Only the <b>DetectLanguage</b> and <b>DefaultLanguage</b> settings will be used.
/// WhenChanged = If the <b>CurrentLanguage</b> gets manually changed, automatically save/load it to PlayerPrefs?
///
/// NOTE: This save data can be cleared with <b>ClearSave</b> context menu option.</summary>
public SaveLoadType SaveLoad { set { saveLoad = value; } get { return saveLoad; } } [SerializeField] private SaveLoadType saveLoad = SaveLoadType.WhenChanged;
/// <summary>This stores all prefabs and folders managed by this LeanLocalization instance.</summary>
public List<LeanPrefab> Prefabs { get { if (prefabs == null) prefabs = new List<LeanPrefab>(); return prefabs; } } [SerializeField] private List<LeanPrefab> prefabs;
/// <summary>Called when the language or translations change.</summary>
public static event System.Action OnLocalizationChanged;
private static bool pendingUpdates;
private static Dictionary<string, LeanTranslation> tempTranslations = new Dictionary<string, LeanTranslation>();
private static List<LeanSource> tempSources = new List<LeanSource>(1024);
/// <summary>Change the current language of this instance?</summary>
public string CurrentLanguage
{
set
{
if (currentLanguage != value)
{
currentLanguage = value;
if (saveLoad != SaveLoadType.None)
{
SaveNow();
}
UpdateTranslations();
}
}
get
{
return currentLanguage;
}
}
/// <summary>When rebuilding translations this method is called from any <b>LeanSource</b> components that define a token.</summary>
public static void RegisterToken(string name, LeanToken token)
{
if (string.IsNullOrEmpty(name) == false && token != null && CurrentTokens.ContainsKey(name) == false)
{
CurrentTokens.Add(name, token);
}
}
/// <summary>When rebuilding translations this method is called from any <b>LeanSource</b> components that define a transition.</summary>
public static LeanTranslation RegisterTranslation(string name)
{
var translation = default(LeanTranslation);
if (string.IsNullOrEmpty(name) == false && CurrentTranslations.TryGetValue(name, out translation) == false)
{
if (tempTranslations.TryGetValue(name, out translation) == true)
{
tempTranslations.Remove(name);
CurrentTranslations.Add(name, translation);
}
else
{
translation = new LeanTranslation(name);
CurrentTranslations.Add(name, translation);
}
}
return translation;
}
[ContextMenu("Clear Save")]
public void ClearSave()
{
PlayerPrefs.DeleteKey("LeanLocalization.CurrentLanguage");
PlayerPrefs.Save();
}
[ContextMenu("Clear Save Alt")]
public void ClearSaveAlt()
{
PlayerPrefs.DeleteKey("LeanLocalization.CurrentLanguageAlt");
PlayerPrefs.Save();
}
private void SaveNow()
{
if (saveLoad == SaveLoadType.WhenChanged)
{
PlayerPrefs.SetString("LeanLocalization.CurrentLanguage", currentLanguage);
}
else if (saveLoad == SaveLoadType.WhenChangedAlt)
{
PlayerPrefs.SetString("LeanLocalization.CurrentLanguageAlt", currentLanguage);
}
PlayerPrefs.Save();
}
private void LoadNow()
{
if (saveLoad == SaveLoadType.WhenChanged)
{
currentLanguage = PlayerPrefs.GetString("LeanLocalization.CurrentLanguage");
}
else if (saveLoad == SaveLoadType.WhenChangedAlt)
{
currentLanguage = PlayerPrefs.GetString("LeanLocalization.CurrentLanguageAlt");
}
}
/// <summary>This sets the current language using the specified language name.</summary>
public void SetCurrentLanguage(string newLanguage)
{
CurrentLanguage = newLanguage;
}
/// <summary>This sets the current language of all instances using the specified language name.</summary>
public static void SetCurrentLanguageAll(string newLanguage)
{
foreach (var instance in Instances)
{
instance.CurrentLanguage = newLanguage;
}
}
/// <summary>This returns the <b>CurrentLanguage</b> value from the first <b>LeanLocalization</b> instance in the scene if it exists, or null.</summary>
public static string GetFirstCurrentLanguage()
{
if (Instances.Count > 0)
{
return Instances[0].CurrentLanguage;
}
return null;
}
public static LeanLocalization GetOrCreateInstance()
{
if (Instances.Count == 0)
{
new GameObject("LeanLocalization").AddComponent<LeanLocalization>();
}
return Instances[0];
}
/// <summary>This adds the specified UnityEngine.Object to this LeanLocalization instance, allowing it to be registered as a prefab.</summary>
public void AddPrefab(Object root)
{
for (var i = Prefabs.Count - 1; i >= 0; i--) // NOTE: Property
{
if (prefabs[i].Root == root)
{
return;
}
}
var prefab = new LeanPrefab();
prefab.Root = root;
prefabs.Add(prefab);
}
/// <summary>This calls <b>AddLanguage</b> on the first active and enabled LeanLocalization instance, or creates one first.</summary>
public static LeanLanguage AddLanguageToFirst(string name)
{
return GetOrCreateInstance().AddLanguage(name);
}
/// <summary>This creates a new token with the specified name, and adds it to the current GameObject.</summary>
public LeanLanguage AddLanguage(string name)
{
if (string.IsNullOrEmpty(name) == false)
{
var root = new GameObject(name);
var language = root.AddComponent<LeanLanguage>();
root.transform.SetParent(transform, false);
return language;
}
return null;
}
/// <summary>This calls <b>AddToken</b> on the first active and enabled LeanLocalization instance, or creates one first.</summary>
public static LeanToken AddTokenToFirst(string name)
{
return GetOrCreateInstance().AddToken(name);
}
/// <summary>This creates a new token with the specified name, and adds it to the current GameObject.</summary>
public LeanToken AddToken(string name)
{
if (string.IsNullOrEmpty(name) == false)
{
var root = new GameObject(name);
var token = root.AddComponent<LeanToken>();
root.transform.SetParent(transform, false);
return token;
}
return null;
}
/// <summary>This allows you to set the value of the token with the specified name.
/// If no token exists and allowCreation is enabled, then one will be created for you.</summary>
public static void SetToken(string name, string value, bool allowCreation = true)
{
if (string.IsNullOrEmpty(name) == false)
{
var token = default(LeanToken);
if (CurrentTokens.TryGetValue(name, out token) == true)
{
token.Value = value;
}
else if (allowCreation == true)
{
token = AddTokenToFirst(name);
token.Value = value;
}
}
}
/// <summary>This allows you to get the value of the token with the specified name.
/// If no token exists, then the defaultValue will be returned.</summary>
public static string GetToken(string name, string defaultValue = null)
{
var token = default(LeanToken);
if (string.IsNullOrEmpty(name) == false)
{
if (CurrentTokens.TryGetValue(name, out token) == true)
{
return token.Value;
}
}
return defaultValue;
}
/// <summary>This calls <b>AddPhrase</b> on the first active and enabled LeanLocalization instance, or creates one first.</summary>
public static LeanPhrase AddPhraseToFirst(string name)
{
return GetOrCreateInstance().AddPhrase(name);
}
/// <summary>This creates a new phrase with the specified name, and adds it to the current GameObject.</summary>
public LeanPhrase AddPhrase(string name)
{
if (string.IsNullOrEmpty(name) == false)
{
var root = new GameObject(name);
var phrase = root.AddComponent<LeanPhrase>();
root.transform.SetParent(transform, false);
return phrase;
}
return null;
}
/// <summary>This will return the translation with the specified name, or null if none was found.</summary>
public static LeanTranslation GetTranslation(string name)
{
var translation = default(LeanTranslation);
if (string.IsNullOrEmpty(name) == false)
{
CurrentTranslations.TryGetValue(name, out translation);
}
return translation;
}
/// <summary>This will return the translated string with the specified name, or the fallback if none is found.</summary>
public static string GetTranslationText(string name, string fallback = null, bool replaceTokens = true)
{
var translation = default(LeanTranslation);
if (string.IsNullOrEmpty(name) == false && CurrentTranslations.TryGetValue(name, out translation) == true && translation.Data is string)
{
fallback = (string)translation.Data;
}
if (replaceTokens == true)
{
fallback = LeanTranslation.FormatText(fallback);
}
return fallback;
}
/// <summary>This will return the translated UnityEngine.Object with the specified name, or the fallback if none is found.</summary>
public static T GetTranslationObject<T>(string name, T fallback = null)
where T : Object
{
var translation = default(LeanTranslation);
if (string.IsNullOrEmpty(name) == false && CurrentTranslations.TryGetValue(name, out translation) == true && translation.Data is T)
{
return (T)translation.Data;
}
return fallback;
}
/// <summary>This rebuilds the dictionary used to quickly map phrase names to translations for the current language.</summary>
public static void UpdateTranslations(bool forceUpdate = true)
{
if (pendingUpdates == true || forceUpdate == true)
{
pendingUpdates = false;
// Copy previous translations to temp dictionary
tempTranslations.Clear();
foreach (var pair in CurrentTranslations)
{
var translation = pair.Value;
translation.Clear();
tempTranslations.Add(pair.Key, translation);
}
// Clear currents
CurrentTokens.Clear();
CurrentLanguages.Clear();
CurrentAliases.Clear();
CurrentTranslations.Clear();
// Rebuild all currents
foreach (var instance in Instances)
{
instance.RegisterAll();
}
// Notify changes?
if (OnLocalizationChanged != null)
{
OnLocalizationChanged();
}
}
}
/// <summary>If you call this method, then UpdateTranslations will be called next Update.</summary>
public static void DelayUpdateTranslations()
{
pendingUpdates = true;
#if UNITY_EDITOR
// Go through all enabled phrases
for (var i = 0; i < Instances.Count; i++)
{
// UnityEditor.EditorUtility.SetDirty(Instances[i].gameObject);
}
#endif
}
/// <summary>Set the instance, merge old instance, and update translations.</summary>
protected virtual void OnEnable()
{
Instances.Add(this);
UpdateTranslations();
}
/// <summary>Unset instance?</summary>
protected virtual void OnDisable()
{
Instances.Remove(this);
UpdateTranslations();
}
protected virtual void Update()
{
UpdateTranslations(false);
}
#if UNITY_EDITOR
// Inspector modified?
protected virtual void OnValidate()
{
UpdateTranslations();
}
#endif
private void RegisterAll()
{
GetComponentsInChildren(tempSources);
// First pass
if (prefabs != null)
{
foreach (var prefab in prefabs)
{
foreach (var source in prefab.Sources)
{
source.Register();
}
}
}
foreach (var source in tempSources)
{
source.Register();
}
// Update language (depends on first pass)
UpdateCurrentLanguage();
// Second pass
if (prefabs != null)
{
foreach (var prefab in prefabs)
{
foreach (var source in prefab.Sources)
{
source.Register(currentLanguage, defaultLanguage);
}
}
}
foreach (var source in tempSources)
{
source.Register(currentLanguage, defaultLanguage);
}
tempSources.Clear();
}
private void UpdateCurrentLanguage()
{
// Load saved language?
if (saveLoad != SaveLoadType.None)
{
LoadNow();
}
// Find language by culture?
if (string.IsNullOrEmpty(currentLanguage) == true)
{
switch (detectLanguage)
{
case DetectType.SystemLanguage:
{
CurrentAliases.TryGetValue(Application.systemLanguage.ToString(), out currentLanguage);
}
break;
case DetectType.CurrentCulture:
{
var cultureInfo = System.Globalization.CultureInfo.CurrentCulture;
if (cultureInfo != null)
{
CurrentAliases.TryGetValue(cultureInfo.Name, out currentLanguage);
}
}
break;
case DetectType.CurrentUICulture:
{
var cultureInfo = System.Globalization.CultureInfo.CurrentUICulture;
if (cultureInfo != null)
{
CurrentAliases.TryGetValue(cultureInfo.Name, out currentLanguage);
}
}
break;
}
}
// Use default language?
if (string.IsNullOrEmpty(currentLanguage) == true)
{
currentLanguage = defaultLanguage;
}
}
#if UNITY_EDITOR
/// <summary>This exports all text phrases in the LeanLocalization component for the Language specified by this component.</summary>
[ContextMenu("Export CurrentLanguage To CSV (Comma Format)")]
private void ExportTextAsset()
{
if (string.IsNullOrEmpty(currentLanguage) == false)
{
// Find where we want to save the file
var path = UnityEditor.EditorUtility.SaveFilePanelInProject("Export Text Asset for " + currentLanguage, currentLanguage, "csv", "");
// Make sure we didn't cancel the panel
if (string.IsNullOrEmpty(path) == false)
{
DoExportTextAsset(path);
}
}
}
private void DoExportTextAsset(string path)
{
var data = "";
var gaps = false;
// Add all phrase names and existing translations to lines
foreach (var pair in CurrentTranslations)
{
var translation = pair.Value;
if (gaps == true)
{
data += System.Environment.NewLine;
}
data += pair.Key + ",\"";
gaps = true;
if (translation.Data is string)
{
var text = (string)translation.Data;
// Replace all new line permutations with the new line token
text = text.Replace("\r\n", "\n");
text = text.Replace("\n\r", "\n");
text = text.Replace("\r", "\n");
data += text;
}
data += "\"";
}
// Write text to file
using (var file = System.IO.File.OpenWrite(path))
{
var encoding = new System.Text.UTF8Encoding();
var bytes = encoding.GetBytes(data);
file.Write(bytes, 0, bytes.Length);
}
// Import asset into project
UnityEditor.AssetDatabase.ImportAsset(path);
// Replace Source with new Text Asset?
var textAsset = (TextAsset)UnityEditor.AssetDatabase.LoadAssetAtPath(path, typeof(TextAsset));
if (textAsset != null)
{
UnityEditor.EditorGUIUtility.PingObject(textAsset);
UnityEditor.EditorUtility.SetDirty(this);
}
}
#endif
}
}
#if UNITY_EDITOR
namespace Lean.Localization.Editor
{
using UnityEditor;
using TARGET = LeanLocalization;
[CanEditMultipleObjects]
[CustomEditor(typeof(TARGET))]
public class LeanLocalization_Editor : CwEditor
{
class PresetLanguage
{
public string Name;
public string[] Cultures;
}
private static List<PresetLanguage> presetLanguages = new List<PresetLanguage>();
protected override void OnInspector()
{
TARGET tgt; TARGET[] tgts; GetTargets(out tgt, out tgts);
LeanLocalization.UpdateTranslations();
if (Draw("currentLanguage", "The language that is currently being used by this instance.") == true)
{
Each(tgts, t => t.CurrentLanguage = serializedObject.FindProperty("currentLanguage").stringValue, true);
}
Draw("saveLoad", "This allows you to control if/how this component's <b>CurrentLanguage</b> setting should save/load.\n\nNone = Only the <b>DetectLanguage</b> and <b>DefaultLanguage</b> settings will be used.\n\nWhenChanged = If the <b>CurrentLanguage</b> gets manually changed, automatically save/load it to PlayerPrefs?\n\nNOTE: This save data can be cleared with <b>ClearSave</b> context menu option.");
Separator();
Draw("detectLanguage", "How should the cultures be used to detect the user's device language?");
BeginDisabled(true);
BeginIndent();
switch (tgt.DetectLanguage)
{
case LeanLocalization.DetectType.SystemLanguage:
EditorGUILayout.TextField("SystemLanguage", Application.systemLanguage.ToString());
break;
case LeanLocalization.DetectType.CurrentCulture:
EditorGUILayout.TextField("CurrentCulture", System.Globalization.CultureInfo.CurrentCulture.ToString());
break;
case LeanLocalization.DetectType.CurrentUICulture:
EditorGUILayout.TextField("CurrentUICulture", System.Globalization.CultureInfo.CurrentUICulture.ToString());
break;
}
EndIndent();
EndDisabled();
Draw("defaultLanguage", "If the application is started and no language has been loaded or auto detected, this language will be used.");
Separator();
DrawPrefabs(tgt);
Separator();
DrawLanguages();
Separator();
DrawTokens();
Separator();
DrawTranslations();
}
private void DrawPrefabs(TARGET tgt)
{
var rectA = Reserve();
var rectB = rectA; rectB.xMin += EditorGUIUtility.labelWidth;
EditorGUI.LabelField(rectA, "Prefabs", EditorStyles.boldLabel);
var newPrefab = EditorGUI.ObjectField(rectB, "", default(Object), typeof(Object), false);
if (newPrefab != null)
{
Undo.RecordObject(tgt, "Add Source");
tgt.AddPrefab(newPrefab);
DirtyAndUpdate();
}
BeginIndent();
for (var i = 0; i < tgt.Prefabs.Count; i++)
{
DrawPrefabs(tgt, i);
}
EndIndent();
}
private int expandPrefab = -1;
private void DrawPrefabs(TARGET tgt, int index)
{
var rectA = Reserve();
var rectB = rectA; rectB.xMax -= 22.0f;
var rectC = rectA; rectC.xMin = rectC.xMax - 20.0f;
var prefab = tgt.Prefabs[index];
var rebuilt = false;
var expand = EditorGUI.Foldout(new Rect(rectA.x, rectA.y, 20, rectA.height), expandPrefab == index, "");
if (expand == true)
{
expandPrefab = index;
}
else if (expandPrefab == index)
{
expandPrefab = -1;
}
BeginDisabled(true);
BeginError(prefab.Root == null);
EditorGUI.ObjectField(rectB, prefab.Root, typeof(Object), false);
EndError();
if (prefab.Root != null)
{
Undo.RecordObject(tgt, "Rebuild Sources");
rebuilt |= prefab.RebuildSources();
if (expand == true)
{
var sources = prefab.Sources;
BeginIndent();
foreach (var source in sources)
{
EditorGUI.ObjectField(Reserve(), source, typeof(LeanSource), false);
}
EndIndent();
}
}
EndDisabled();
if (rebuilt == true)
{
DirtyAndUpdate();
}
if (GUI.Button(rectC, "X", EditorStyles.miniButton) == true)
{
Undo.RecordObject(tgt, "Remove Prefab");
tgt.Prefabs.RemoveAt(index);
DirtyAndUpdate();
if (expand == true)
{
expandPrefab = -1;
}
}
}
private static string translationFilter;
private LeanTranslation expandTranslation;
private void DrawTranslations()
{
var rectA = Reserve();
var rectB = rectA; rectB.xMin += EditorGUIUtility.labelWidth; rectB.xMax -= 37.0f;
var rectC = rectA; rectC.xMin = rectC.xMax - 35.0f;
EditorGUI.LabelField(rectA, "Translations", EditorStyles.boldLabel);
translationFilter = EditorGUI.TextField(rectB, "", translationFilter);
BeginDisabled(string.IsNullOrEmpty(translationFilter) == true || LeanLocalization.CurrentTranslations.ContainsKey(translationFilter) == true);
if (GUI.Button(rectC, "Add", EditorStyles.miniButton) == true)
{
var phrase = LeanLocalization.AddPhraseToFirst(translationFilter);
LeanLocalization.UpdateTranslations();
Selection.activeObject = phrase;
EditorGUIUtility.PingObject(phrase);
}
EndDisabled();
if (LeanLocalization.CurrentTranslations.Count == 0 && string.IsNullOrEmpty(translationFilter) == true)
{
Info("Type in the name of a translation, and click the 'Add' button. Or, drag and drop a prefab that contains some.");
}
else
{
var total = 0;
BeginIndent();
foreach (var pair in LeanLocalization.CurrentTranslations)
{
var name = pair.Key;
if (string.IsNullOrEmpty(translationFilter) == true || name.IndexOf(translationFilter, System.StringComparison.InvariantCultureIgnoreCase) >= 0)
{
var translation = pair.Value;
var rectT = Reserve();
var expand = EditorGUI.Foldout(new Rect(rectT.x, rectT.y, 20, rectT.height), expandTranslation == translation, "");
if (expand == true)
{
expandTranslation = translation;
}
else if (expandTranslation == translation)
{
expandTranslation = null;
}
CalculateTranslation(pair.Value);
var data = translation.Data;
total++;
BeginDisabled(true);
BeginError(missing.Count > 0 || clashes.Count > 0);
if (data is Object)
{
EditorGUI.ObjectField(rectT, name, (Object)data, typeof(Object), true);
}
else
{
EditorGUI.TextField(rectT, name, data != null ? data.ToString() : "");
}
EndError();
if (expand == true)
{
BeginIndent();
foreach (var entry in translation.Entries)
{
BeginError(clashes.Contains(entry.Language) == true);
EditorGUILayout.ObjectField(entry.Language, entry.Owner, typeof(Object), true);
EndError();
}
EndIndent();
}
EndDisabled();
if (expand == true)
{
foreach (var language in missing)
{
Warning("This translation isn't defined for the " + language + " language.");
}
foreach (var language in clashes)
{
Warning("This translation is defined multiple times for the " + language + " language.");
}
}
}
}
EndIndent();
if (total == 0)
{
Info("No translation with this name exists, click the 'Add' button to create it.");
}
}
}
private static List<string> missing = new List<string>();
private static List<string> clashes = new List<string>();
private static void CalculateTranslation(LeanTranslation translation)
{
missing.Clear();
clashes.Clear();
foreach (var language in LeanLocalization.CurrentLanguages.Keys)
{
if (translation.Entries.Exists(e => e.Language == language) == false)
{
missing.Add(language);
}
}
foreach (var entry in translation.Entries)
{
var language = entry.Language;
if (clashes.Contains(language) == false)
{
if (translation.LanguageCount(language) > 1)
{
clashes.Add(language);
}
}
}
}
private static string languagesFilter;
private void DrawLanguages()
{
var rectA = Reserve();
var rectB = rectA; rectB.xMin += EditorGUIUtility.labelWidth; rectB.xMax -= 37.0f;
var rectC = rectA; rectC.xMin = rectC.xMax - 35.0f;
EditorGUI.LabelField(rectA, "Languages", EditorStyles.boldLabel);
languagesFilter = EditorGUI.TextField(rectB, "", languagesFilter);
BeginDisabled(string.IsNullOrEmpty(languagesFilter) == true || LeanLocalization.CurrentLanguages.ContainsKey(languagesFilter) == true);
if (GUI.Button(rectC, "Add", EditorStyles.miniButton) == true)
{
var language = LeanLocalization.AddLanguageToFirst(languagesFilter);
LeanLocalization.UpdateTranslations();
Selection.activeObject = language;
EditorGUIUtility.PingObject(language);
}
EndDisabled();
if (LeanLocalization.CurrentLanguages.Count > 0 || string.IsNullOrEmpty(languagesFilter) == false)
{
var total = 0;
BeginIndent();
BeginDisabled(true);
foreach (var pair in LeanLocalization.CurrentLanguages)
{
if (string.IsNullOrEmpty(languagesFilter) == true || pair.Key.IndexOf(languagesFilter, System.StringComparison.InvariantCultureIgnoreCase) >= 0)
{
EditorGUILayout.ObjectField(pair.Key, pair.Value, typeof(Object), true); total++;
}
}
EndDisabled();
EndIndent();
if (total == 0)
{
EditorGUILayout.HelpBox("No language with this name exists, click the 'Add' button to create it.", MessageType.Info);
}
}
}
private static string tokensFilter;
private void DrawTokens()
{
var rectA = Reserve();
var rectB = rectA; rectB.xMin += EditorGUIUtility.labelWidth; rectB.xMax -= 37.0f;
var rectC = rectA; rectC.xMin = rectC.xMax - 35.0f;
EditorGUI.LabelField(rectA, "Tokens", EditorStyles.boldLabel);
tokensFilter = EditorGUI.TextField(rectB, "", tokensFilter);
BeginDisabled(string.IsNullOrEmpty(tokensFilter) == true || LeanLocalization.CurrentTokens.ContainsKey(tokensFilter) == true);
if (GUI.Button(rectC, "Add", EditorStyles.miniButton) == true)
{
var token = LeanLocalization.AddTokenToFirst(tokensFilter);
LeanLocalization.UpdateTranslations();
Selection.activeObject = token;
EditorGUIUtility.PingObject(token);
}
EndDisabled();
if (LeanLocalization.CurrentTokens.Count > 0 || string.IsNullOrEmpty(tokensFilter) == false)
{
var total = 0;
BeginIndent();
BeginDisabled(true);
foreach (var pair in LeanLocalization.CurrentTokens)
{
if (string.IsNullOrEmpty(tokensFilter) == true || pair.Key.IndexOf(tokensFilter, System.StringComparison.InvariantCultureIgnoreCase) >= 0)
{
EditorGUILayout.ObjectField(pair.Key, pair.Value, typeof(Object), true); total++;
}
}
EndDisabled();
EndIndent();
if (total == 0)
{
EditorGUILayout.HelpBox("No token with this name exists, click the 'Add' button to create it.", MessageType.Info);
}
}
}
private void AddLanguage(TARGET tgt, PresetLanguage presetLanguage)
{
Undo.RecordObject(tgt, "Add Language");
tgt.AddLanguage(presetLanguage.Name);
DirtyAndUpdate();
}
private static void AddPresetLanguage(string name, params string[] cultures)
{
var presetLanguage = new PresetLanguage();
presetLanguage.Name = name;
presetLanguage.Cultures = cultures;
presetLanguages.Add(presetLanguage);
}
[MenuItem("GameObject/Lean/Localization", false, 1)]
private static void CreateLocalization()
{
var gameObject = new GameObject(typeof(LeanLocalization).Name);
Undo.RegisterCreatedObjectUndo(gameObject, "Create LeanLocalization");
gameObject.AddComponent<LeanLocalization>();
Selection.activeGameObject = gameObject;
}
}
}
#endif | 0 | 0.937894 | 1 | 0.937894 | game-dev | MEDIA | 0.969288 | game-dev | 0.978162 | 1 | 0.978162 |
praydog/REFramework | 1,889 | shared/sdk/REArray.hpp | class REArrayBase;
namespace utility::re_array {
// Forward declarations
bool has_inline_elements(::REArrayBase* container);
::sdk::RETypeDefinition* get_contained_type(::REArrayBase* container);
uint32_t get_element_size(::REArrayBase* container);
bool has_inline_elements(::REArrayBase* container);
template<typename T> static T* get_inline_element(::REArrayBase* container, int idx);
template<typename T> static T* get_ptr_element(::REArrayBase* container, int idx);
template<typename T> static T* get_element(::REArrayBase* container, int idx);
}
#pragma once
#include "utility/Address.hpp"
#include "REManagedObject.hpp"
#include "REType.hpp"
#include "ReClass.hpp"
namespace sdk {
struct RETypeDefinition;
}
namespace utility::re_array {
template<typename T>
static T* get_inline_element(::REArrayBase* container, int idx) {
if (idx < 0 || idx >= container->numElements) {
return nullptr;
}
const auto element_size = utility::re_array::get_element_size(container);
auto data = Address{ (uintptr_t)((REArrayBase*)utility::re_managed_object::get_field_ptr(container) + 1) - sizeof(REManagedObject) };
return data.get(element_size * idx).as<T*>();
}
template<typename T>
static T* get_ptr_element(::REArrayBase* container, int idx) {
if (idx < 0 || idx >= container->numElements) {
return nullptr;
}
auto data = (T**)((uintptr_t)((REArrayBase*)utility::re_managed_object::get_field_ptr(container) + 1) - sizeof(REManagedObject));
return data[idx];
}
// may need more work to handle unseen cases.
template<typename T>
static T* get_element(::REArrayBase* container, int idx) {
return has_inline_elements(container) ? get_inline_element<T>(container, idx) : get_ptr_element<T>(container, idx);
}
} | 0 | 0.890717 | 1 | 0.890717 | game-dev | MEDIA | 0.131721 | game-dev | 0.938108 | 1 | 0.938108 |
GaijinEntertainment/DagorEngine | 1,072 | prog/1stPartyLibs/protolib/serialization/userTypes/dataBlock.h | #pragma once
#include <ioSys/dag_dataBlock.h>
#include <protolib/serialization/binaryStream.h>
#include <protolib/serialization/outputCodeStream.h>
#include <protolib/serialization/inputCodeStream.h>
#include <protolib/serialization/json/jsonSerializator.h>
#include <util/dag_baseDef.h>
namespace proto
{
inline void clear(DataBlock & v)
{
v.reset();
}
void serialize(proto::io::OutputCodeStream & stream, proto::io::TNumber number, const DataBlock & blk);
bool serialize(proto::io::InputCodeStream & stream, proto::io::StreamTag tag, DataBlock & blk);
inline void load(const BlkSerializator & ser, const char * name, DataBlock & value)
{
value.setFrom(ser.blk.getBlockByNameEx(name));
}
inline void save(const BlkSerializator & ser, const char * name, const DataBlock & value)
{
ser.blk.addNewBlock(&value, name);
}
void load(const JsonReader & ser, const char * name, DataBlock & value);
void save(const JsonWriter & ser, const char * name, const DataBlock & value);
inline void touch_recursive(DataBlock &, version) {}
}
| 0 | 0.79338 | 1 | 0.79338 | game-dev | MEDIA | 0.406735 | game-dev | 0.554354 | 1 | 0.554354 |
GeyserMC/Floodgate | 3,306 | spigot/src/main/java/org/geysermc/floodgate/module/SpigotCommandModule.java | /*
* Copyright (c) 2019-2022 GeyserMC. http://geysermc.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.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Floodgate
*/
package org.geysermc.floodgate.module;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.bukkit.Bukkit;
import org.bukkit.permissions.PermissionDefault;
import org.bukkit.plugin.PluginManager;
import org.geysermc.floodgate.SpigotPlugin;
import org.geysermc.floodgate.command.util.Permission;
import org.geysermc.floodgate.platform.command.CommandUtil;
import org.geysermc.floodgate.player.FloodgateCommandPreprocessor;
import org.geysermc.floodgate.player.UserAudience;
import org.geysermc.floodgate.player.audience.FloodgateSenderMapper;
import org.incendo.cloud.CommandManager;
import org.incendo.cloud.execution.ExecutionCoordinator;
import org.incendo.cloud.paper.LegacyPaperCommandManager;
@RequiredArgsConstructor
public final class SpigotCommandModule extends CommandModule {
private final SpigotPlugin plugin;
@Override
protected void configure() {
super.configure();
registerPermissions();
}
@Provides
@Singleton
@SneakyThrows
public CommandManager<UserAudience> commandManager(CommandUtil commandUtil) {
CommandManager<UserAudience> commandManager = new LegacyPaperCommandManager<>(
plugin,
ExecutionCoordinator.simpleCoordinator(),
new FloodgateSenderMapper<>(commandUtil)
);
commandManager.registerCommandPreProcessor(new FloodgateCommandPreprocessor<>(commandUtil));
return commandManager;
}
private void registerPermissions() {
PluginManager manager = Bukkit.getPluginManager();
for (Permission permission : Permission.values()) {
if (manager.getPermission(permission.get()) != null) {
continue;
}
PermissionDefault defaultValue =
PermissionDefault.getByName(permission.defaultValue().name());
manager.addPermission(new org.bukkit.permissions.Permission(
permission.get(), defaultValue
));
}
}
}
| 0 | 0.910861 | 1 | 0.910861 | game-dev | MEDIA | 0.40515 | game-dev | 0.759167 | 1 | 0.759167 |
haloman9527/3.0_GraphProcessor | 1,134 | Examples/FlowExample/Editor/FlowGraphView.cs | #if UNITY_EDITOR
#region 注 释
/***
*
* Title:
*
* Description:
*
* Date:
* Version:
* Writer: 半只龙虾人
* Github: https://github.com/haloman9527
* Blog: https://www.haloman.net/
*
*/
#endregion
using Atom;
using Atom.GraphProcessor;
using Atom.GraphProcessor.Editors;
using System;
using System.Collections.Generic;
using UnityEditor.Experimental.GraphView;
using UnityEngine;
public class FlowGraphView : BaseGraphView
{
protected override void BuildNodeMenu(NodeMenuWindow nodeMenu)
{
foreach (var nodeInfo in GraphProcessorUtil.GetNodeStaticInfos())
{
if (nodeInfo.Hidden)
continue;
if (!typeof(FlowNode).IsAssignableFrom(nodeInfo.NodeType))
continue;
var path = nodeInfo.Path;
var menu = nodeInfo.Menu;
nodeMenu.entries.Add(new NodeMenuWindow.NodeEntry(path, menu, nodeInfo.NodeType));
}
}
protected override BaseConnectionView NewConnectionView(BaseConnectionProcessor connection)
{
return new SampleConnectionView();
}
}
#endif | 0 | 0.802671 | 1 | 0.802671 | game-dev | MEDIA | 0.401008 | game-dev,desktop-app | 0.793553 | 1 | 0.793553 |
LiangliangNan/Easy3D | 13,889 | 3rd_party/opcode/OPC_BoxPruning.cpp | /*
* OPCODE - Optimized Collision Detection
* http://www.codercorner.com/Opcode.htm
*
* Copyright (c) 2001-2008 Pierre Terdiman, pierre@codercorner.com
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Contains code for box pruning.
* \file IceBoxPruning.cpp
* \author Pierre Terdiman
* \date January, 29, 2000
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
You could use a complex sweep-and-prune as implemented in I-Collide.
You could use a complex hashing scheme as implemented in V-Clip or recently in ODE it seems.
You could use a "Recursive Dimensional Clustering" algorithm as implemented in GPG2.
Or you could use this.
Faster ? I don't know. Probably not. It would be a shame. But who knows ?
Easier ? Definitely. Enjoy the sheer simplicity.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Precompiled Header
#include "Opcode.h"
using namespace Opcode;
inline_ void FindRunningIndex(udword& index, float* array, udword* sorted, int last, float max)
{
int First=index;
while(First<=last)
{
index = (First+last)>>1;
if(max>array[sorted[index]]) First = index+1;
else last = index-1;
}
}
// ### could be log(n) !
// and maybe use cmp integers
// InsertionSort has better coherence, RadixSort is better for one-shot queries.
#define PRUNING_SORTER RadixSort
//#define PRUNING_SORTER InsertionSort
// Static for coherence
static PRUNING_SORTER* gCompletePruningSorter = null;
static PRUNING_SORTER* gBipartitePruningSorter0 = null;
static PRUNING_SORTER* gBipartitePruningSorter1 = null;
inline_ PRUNING_SORTER* GetCompletePruningSorter()
{
if(!gCompletePruningSorter) gCompletePruningSorter = new PRUNING_SORTER;
return gCompletePruningSorter;
}
inline_ PRUNING_SORTER* GetBipartitePruningSorter0()
{
if(!gBipartitePruningSorter0) gBipartitePruningSorter0 = new PRUNING_SORTER;
return gBipartitePruningSorter0;
}
inline_ PRUNING_SORTER* GetBipartitePruningSorter1()
{
if(!gBipartitePruningSorter1) gBipartitePruningSorter1 = new PRUNING_SORTER;
return gBipartitePruningSorter1;
}
void ReleasePruningSorters()
{
DELETESINGLE(gBipartitePruningSorter1);
DELETESINGLE(gBipartitePruningSorter0);
DELETESINGLE(gCompletePruningSorter);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Bipartite box pruning. Returns a list of overlapping pairs of boxes, each box of the pair belongs to a different set.
* \param nb0 [in] number of boxes in the first set
* \param array0 [in] array of boxes for the first set
* \param nb1 [in] number of boxes in the second set
* \param array1 [in] array of boxes for the second set
* \param pairs [out] array of overlapping pairs
* \param axes [in] projection order (0,2,1 is often best)
* \return true if success.
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool Opcode::BipartiteBoxPruning(udword nb0, const AABB** array0, udword nb1, const AABB** array1, Pairs& pairs, const Axes& axes)
{
// Checkings
if(!nb0 || !array0 || !nb1 || !array1) return false;
// Catch axes
udword Axis0 = axes.mAxis0;
udword Axis1 = axes.mAxis1;
udword Axis2 = axes.mAxis2;
// Allocate some temporary data
float* MinPosList0 = new float[nb0];
float* MinPosList1 = new float[nb1];
// 1) Build main lists using the primary axis
for(udword i=0;i<nb0;i++) MinPosList0[i] = array0[i]->GetMin(Axis0);
for(udword i=0;i<nb1;i++) MinPosList1[i] = array1[i]->GetMin(Axis0);
// 2) Sort the lists
PRUNING_SORTER* RS0 = GetBipartitePruningSorter0();
PRUNING_SORTER* RS1 = GetBipartitePruningSorter1();
const udword* Sorted0 = RS0->Sort(MinPosList0, nb0).GetRanks();
const udword* Sorted1 = RS1->Sort(MinPosList1, nb1).GetRanks();
// 3) Prune the lists
udword Index0, Index1;
const udword* const LastSorted0 = &Sorted0[nb0];
const udword* const LastSorted1 = &Sorted1[nb1];
const udword* RunningAddress0 = Sorted0;
const udword* RunningAddress1 = Sorted1;
while(RunningAddress1<LastSorted1 && Sorted0<LastSorted0)
{
Index0 = *Sorted0++;
while(RunningAddress1<LastSorted1 && MinPosList1[*RunningAddress1]<MinPosList0[Index0]) RunningAddress1++;
const udword* RunningAddress2_1 = RunningAddress1;
while(RunningAddress2_1<LastSorted1 && MinPosList1[Index1 = *RunningAddress2_1++]<=array0[Index0]->GetMax(Axis0))
{
if(array0[Index0]->Intersect(*array1[Index1], Axis1))
{
if(array0[Index0]->Intersect(*array1[Index1], Axis2))
{
pairs.AddPair(Index0, Index1);
}
}
}
}
////
while(RunningAddress0<LastSorted0 && Sorted1<LastSorted1)
{
Index0 = *Sorted1++;
while(RunningAddress0<LastSorted0 && MinPosList0[*RunningAddress0]<=MinPosList1[Index0]) RunningAddress0++;
const udword* RunningAddress2_0 = RunningAddress0;
while(RunningAddress2_0<LastSorted0 && MinPosList0[Index1 = *RunningAddress2_0++]<=array1[Index0]->GetMax(Axis0))
{
if(array0[Index1]->Intersect(*array1[Index0], Axis1))
{
if(array0[Index1]->Intersect(*array1[Index0], Axis2))
{
pairs.AddPair(Index1, Index0);
}
}
}
}
DELETEARRAY(MinPosList1);
DELETEARRAY(MinPosList0);
return true;
}
#define ORIGINAL_VERSION
//#define JOAKIM
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Complete box pruning. Returns a list of overlapping pairs of boxes, each box of the pair belongs to the same set.
* \param nb [in] number of boxes
* \param array [in] array of boxes
* \param pairs [out] array of overlapping pairs
* \param axes [in] projection order (0,2,1 is often best)
* \return true if success.
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool Opcode::CompleteBoxPruning(udword nb, const AABB** array, Pairs& pairs, const Axes& axes)
{
// Checkings
if(!nb || !array) return false;
// Catch axes
udword Axis0 = axes.mAxis0;
udword Axis1 = axes.mAxis1;
udword Axis2 = axes.mAxis2;
#ifdef ORIGINAL_VERSION
// Allocate some temporary data
// float* PosList = new float[nb];
float* PosList = new float[nb+1];
// 1) Build main list using the primary axis
for(udword i=0;i<nb;i++) PosList[i] = array[i]->GetMin(Axis0);
PosList[nb++] = MAX_FLOAT;
// 2) Sort the list
PRUNING_SORTER* RS = GetCompletePruningSorter();
const udword* Sorted = RS->Sort(PosList, nb).GetRanks();
// 3) Prune the list
const udword* const LastSorted = &Sorted[nb];
const udword* RunningAddress = Sorted;
udword Index0, Index1;
while(RunningAddress<LastSorted && Sorted<LastSorted)
{
Index0 = *Sorted++;
// while(RunningAddress<LastSorted && PosList[*RunningAddress++]<PosList[Index0]);
while(PosList[*RunningAddress++]<PosList[Index0]);
if(RunningAddress<LastSorted)
{
const udword* RunningAddress2 = RunningAddress;
// while(RunningAddress2<LastSorted && PosList[Index1 = *RunningAddress2++]<=array[Index0]->GetMax(Axis0))
while(PosList[Index1 = *RunningAddress2++]<=array[Index0]->GetMax(Axis0))
{
// if(Index0!=Index1)
// {
if(array[Index0]->Intersect(*array[Index1], Axis1))
{
if(array[Index0]->Intersect(*array[Index1], Axis2))
{
pairs.AddPair(Index0, Index1);
}
}
// }
}
}
}
DELETEARRAY(PosList);
#endif
#ifdef JOAKIM
// Allocate some temporary data
// float* PosList = new float[nb];
float* MinList = new float[nb+1];
// 1) Build main list using the primary axis
for(udword i=0;i<nb;i++) MinList[i] = array[i]->GetMin(Axis0);
MinList[nb] = MAX_FLOAT;
// 2) Sort the list
PRUNING_SORTER* RS = GetCompletePruningSorter();
udword* Sorted = RS->Sort(MinList, nb+1).GetRanks();
// 3) Prune the list
// const udword* const LastSorted = &Sorted[nb];
// const udword* const LastSorted = &Sorted[nb-1];
const udword* RunningAddress = Sorted;
udword Index0, Index1;
// while(RunningAddress<LastSorted && Sorted<LastSorted)
// while(RunningAddress<LastSorted)
while(RunningAddress<&Sorted[nb])
// while(Sorted<LastSorted)
{
// Index0 = *Sorted++;
Index0 = *RunningAddress++;
// while(RunningAddress<LastSorted && PosList[*RunningAddress++]<PosList[Index0]);
// while(PosList[*RunningAddress++]<PosList[Index0]);
//RunningAddress = Sorted;
// if(RunningAddress<LastSorted)
{
const udword* RunningAddress2 = RunningAddress;
// while(RunningAddress2<LastSorted && PosList[Index1 = *RunningAddress2++]<=array[Index0]->GetMax(Axis0))
// float CurrentMin = array[Index0]->GetMin(Axis0);
float CurrentMax = array[Index0]->GetMax(Axis0);
while(MinList[Index1 = *RunningAddress2] <= CurrentMax)
// while(PosList[Index1 = *RunningAddress] <= CurrentMax)
{
// if(Index0!=Index1)
// {
if(array[Index0]->Intersect(*array[Index1], Axis1))
{
if(array[Index0]->Intersect(*array[Index1], Axis2))
{
pairs.AddPair(Index0, Index1);
}
}
// }
RunningAddress2++;
// RunningAddress++;
}
}
}
DELETEARRAY(MinList);
#endif
return true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Brute-force versions are kept:
// - to check the optimized versions return the correct list of intersections
// - to check the speed of the optimized code against the brute-force one
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Brute-force bipartite box pruning. Returns a list of overlapping pairs of boxes, each box of the pair belongs to a different set.
* \param nb0 [in] number of boxes in the first set
* \param array0 [in] array of boxes for the first set
* \param nb1 [in] number of boxes in the second set
* \param array1 [in] array of boxes for the second set
* \param pairs [out] array of overlapping pairs
* \return true if success.
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool Opcode::BruteForceBipartiteBoxTest(udword nb0, const AABB** array0, udword nb1, const AABB** array1, Pairs& pairs)
{
// Checkings
if(!nb0 || !array0 || !nb1 || !array1) return false;
// Brute-force nb0*nb1 overlap tests
for(udword i=0;i<nb0;i++)
{
for(udword j=0;j<nb1;j++)
{
if(array0[i]->Intersect(*array1[j])) pairs.AddPair(i, j);
}
}
return true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Complete box pruning. Returns a list of overlapping pairs of boxes, each box of the pair belongs to the same set.
* \param nb [in] number of boxes
* \param array [in] array of boxes
* \param pairs [out] array of overlapping pairs
* \return true if success.
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool Opcode::BruteForceCompleteBoxTest(udword nb, const AABB** array, Pairs& pairs)
{
// Checkings
if(!nb || !array) return false;
// Brute-force n(n-1)/2 overlap tests
for(udword i=0;i<nb;i++)
{
for(udword j=i+1;j<nb;j++)
{
if(array[i]->Intersect(*array[j])) pairs.AddPair(i, j);
}
}
return true;
}
| 0 | 0.762224 | 1 | 0.762224 | game-dev | MEDIA | 0.275494 | game-dev | 0.950267 | 1 | 0.950267 |
ErLinErYi/PlantsVsZombies | 6,514 | PlantsVsZombies/cocos2d/extensions/Particle3D/PU/CCPUPlaneCollider.cpp | /****************************************************************************
Copyright (C) 2013 Henry van Merode. All rights reserved.
Copyright (c) 2015-2017 Chukong Technologies Inc.
http://www.cocos2d-x.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 "CCPUPlaneCollider.h"
#include "extensions/Particle3D/PU/CCPUParticleSystem3D.h"
NS_CC_BEGIN
// Constants
const Vec3 PUPlaneCollider::DEFAULT_NORMAL(0, 0, 0);
//-----------------------------------------------------------------------
PUPlaneCollider::PUPlaneCollider(void) :
PUBaseCollider(),
_normal(DEFAULT_NORMAL)
{
}
PUPlaneCollider::~PUPlaneCollider( void )
{
}
//-----------------------------------------------------------------------
const Vec3 PUPlaneCollider::getNormal(void) const
{
return _normal;
}
//-----------------------------------------------------------------------
void PUPlaneCollider::setNormal(const Vec3& normal)
{
_normal = normal;
_plane.redefine(_normal, getDerivedPosition()); // Changed in 1.3.1
}
//-----------------------------------------------------------------------
void PUPlaneCollider::notifyRescaled(const Vec3& /*scale*/)
{
// Function added in 1.3.1
_plane.redefine(_normal, getDerivedPosition());
}
//-----------------------------------------------------------------------
void PUPlaneCollider::calculateDirectionAfterCollision(PUParticle3D* particle, float timeElapsed)
{
float directionLength = particle->direction.length();
switch (_collisionType)
{
case PUBaseCollider::CT_BOUNCE:
{
/** If the particle is on the plane or at the back of the plane, bounce it.
Make use of the same formula as the sphere collider.
*/
particle->direction.normalize();
particle->direction = 2 * (-particle->direction.dot(-_normal)) * -_normal + particle->direction;
// Adjust to original speed
particle->direction *= directionLength;
// Accelerate/slow down, using the bounce value
particle->direction *= _bouncyness;
}
break;
case PUBaseCollider::CT_FLOW:
{
/** Reset the position (just in front of the plane), but keep the direction.
@remarks
This is not really the correct way, because the particle 'jumps'. Maybe it is better to change
the direction parallel to the plane.
*/
particle->position += timeElapsed * directionLength * _normal;
}
break;
default:
break;
}
}
void PUPlaneCollider::updatePUAffector( PUParticle3D *particle, float deltaTime )
{
//for (auto iter : _particleSystem->getParticles())
{
//PUParticle3D *particle = iter;
_predictedPosition = particle->position + _velocityScale * particle->direction;
bool collision = false;
switch(_intersectionType)
{
case PUBaseCollider::IT_POINT:
{
// Validate for a point-plane intersection (on the plane or the back side)
// First determine whether it is now colliding (some affector made the particle move), else
// determine whether it WILL be colliding
if (_plane.getDistance(particle->position) <= 0.0f)
{
// Collision detected (re-position the particle)
particle->position -= _velocityScale * particle->direction;
collision = true;
}
else if (_plane.getDistance(_predictedPosition) <= 0.0f)
{
// Collision detected
collision = true;
}
}
break;
case PUBaseCollider::IT_BOX:
{
AABB box;
populateAlignedBox(box,
particle->position,
particle->width,
particle->height,
particle->depth);
//FIXME
//if (box.intersects(_plane))
//{
// // Collision detected (re-position the particle)
// particle->position -= _velocityScale * particle->direction;
// collision = true;
//}
//else
//{
// populateAlignedBox(box,
// _predictedPosition,
// particle->width,
// particle->height,
// particle->depth);
// if (box.intersects(_plane))
// {
// // Collision detected
// collision = true;
// }
//}
}
break;
}
if (collision)
{
calculateDirectionAfterCollision(particle, deltaTime);
calculateRotationSpeedAfterCollision(particle);
particle->addEventFlags(PUParticle3D::PEF_COLLIDED);
}
}
}
PUPlaneCollider* PUPlaneCollider::create()
{
auto ppc = new (std::nothrow) PUPlaneCollider();
ppc->autorelease();
return ppc;
}
void PUPlaneCollider::copyAttributesTo( PUAffector* affector )
{
PUBaseCollider::copyAttributesTo(affector);
PUPlaneCollider* planeCollider = static_cast<PUPlaneCollider*>(affector);
planeCollider->setNormal(_normal);
}
NS_CC_END
| 0 | 0.937546 | 1 | 0.937546 | game-dev | MEDIA | 0.804148 | game-dev | 0.922155 | 1 | 0.922155 |
livekit-examples/python-agents-examples | 23,810 | complex-agents/role-playing/agents/combat_agent.py | """
---
title: Combat Agent
category: complex-agents
tags: [rpg, combat-system, turn-based-combat, npc-ai, function-tools]
difficulty: advanced
description: Specialized agent for handling turn-based combat encounters in RPG games
demonstrates:
- Turn-based combat management
- Combat action queueing and processing
- NPC AI for automated combat turns
- Real-time combat state updates via RPC
- Experience and loot distribution
- Dynamic combat flow with player/NPC interactions
- Combat action validation and execution
---
"""
import asyncio
import logging
import re
from typing import List, TYPE_CHECKING
from livekit.agents.llm import function_tool
from livekit.plugins import deepgram, openai, silero, inworld
from agents.base_agent import BaseGameAgent
from character import NPCCharacter, PlayerCharacter
from core.game_state import RunContext_T, GameUserData
from game_mechanics import Combat, SpellCasting, GameUtilities, CombatAction
from utils.display import Colors
from utils.prompt_loader import load_prompt
logger = logging.getLogger("dungeons-and-agents")
if TYPE_CHECKING:
from agents.narrator_agent import NarratorAgent
class CombatAgent(BaseGameAgent):
"""Handles combat encounters with fast-paced action"""
def __init__(self) -> None:
super().__init__(
instructions=load_prompt('combat_prompt.yaml'),
stt=deepgram.STT(),
llm=openai.LLM(model="gpt-4o"),
tts=inworld.TTS(voice="Hades"),
vad=silero.VAD.load()
)
async def on_enter(self) -> None:
await super().on_enter()
userdata: GameUserData = self.session.userdata
if userdata.combat_state and not userdata.combat_state.is_complete:
# Clear any leftover messages in the queue to avoid repetition
while not userdata.combat_state.action_queue.empty():
userdata.combat_state.action_queue.get()
current_char = userdata.combat_state.get_current_character()
if current_char == userdata.player_character:
# Queue player turn message
userdata.combat_state.action_queue.put(
CombatAction(message="It's your turn! You can attack, defend, cast a spell, use an item, or try to flee!", delay=0.0)
)
await self._process_action_queue()
else:
await self._queue_npc_turn()
await self._process_action_queue()
async def _process_action_queue(self):
"""Process combat actions from the queue sequentially"""
userdata: GameUserData = self.session.userdata
combat_state = userdata.combat_state
if not combat_state:
return
while not combat_state.action_queue.empty():
action = combat_state.action_queue.get()
if action.delay > 0:
await asyncio.sleep(action.delay)
self.session.say(action.message)
await asyncio.sleep(1.0)
async def _queue_npc_turn(self):
"""Queue NPC turns for processing"""
userdata: GameUserData = self.session.userdata
combat_state = userdata.combat_state
if not combat_state or combat_state.is_complete:
return
while True:
current_char = combat_state.get_current_character()
if not current_char or current_char == userdata.player_character:
if current_char == userdata.player_character:
combat_state.action_queue.put(
CombatAction(message="It's your turn! You can attack, defend, cast a spell, use an item, or try to flee!", delay=0.5)
)
break
if isinstance(current_char, NPCCharacter):
# Process this NPC's turn and queue the action
await self._queue_single_npc_action(current_char)
# Check if combat ended
if combat_state.is_complete:
break
# Advance to next turn
combat_state.next_turn()
else:
break
async def _queue_single_npc_action(self, npc: NPCCharacter):
"""Queue a single NPC's combat action"""
userdata: GameUserData = self.session.userdata
combat_state = userdata.combat_state
if not combat_state or combat_state.is_complete:
return
# TODO: Add a more complex AI for the NPCs
result = Combat.perform_attack(npc, userdata.player_character)
hit, damage, description = result
# Emit combat update
await self.emit_state_update("combat_action", {
"action": "attack",
"attacker": npc.name,
"target": userdata.player_character.name,
"hit": hit,
"damage": damage
})
# Create a cinematic description for TTS
if hit:
if damage > 0:
# Get weapon description for NPCs
weapon_action = "strikes with their weapon"
if npc.equipped_weapon:
weapon_action = f"slashes with their {npc.equipped_weapon.name}"
elif "goblin" in npc.name.lower():
weapon_action = "stabs with a rusty blade"
elif "orc" in npc.name.lower():
weapon_action = "swings a massive club"
tts_description = f"{npc.name} {weapon_action}! You take {damage} damage"
if userdata.player_character.current_health <= 0:
tts_description += " and fall to your knees. You have been defeated!"
else:
health_percent = (userdata.player_character.current_health / userdata.player_character.max_health) * 100
if health_percent < 25:
tts_description += "! You're gravely wounded!"
elif health_percent < 50:
tts_description += "! Pain shoots through your body!"
else:
tts_description += "!"
else:
tts_description = f"{npc.name}'s attack glances off your armor!"
else:
tts_description = f"You dodge {npc.name}'s attack!"
# Queue the NPC action
combat_state.action_queue.put(CombatAction(message=tts_description, delay=0.3))
# Check if player was defeated
if userdata.player_character.current_health <= 0:
combat_state.is_complete = True
userdata.game_state = "game_over"
defeat_action = CombatAction(
message="Your adventure ends here... for now.",
delay=1.0
)
combat_state.action_queue.put(defeat_action)
# Process the final message
await self._process_action_queue()
# Emit defeat update
await self.emit_state_update("character_defeated", {
"character": userdata.player_character.name,
"type": "player"
})
# End the session properly
logger.info("Player defeated - ending session")
await self.session.say("Thank you for playing Dungeons and Agents. Until next time, brave adventurer!")
await self.session.drain() # Ensure all messages are sent
await self.session.aclose()
# Delete the room
try:
from livekit import api
await userdata.ctx.api.room.delete_room(
api.DeleteRoomRequest(room=userdata.ctx.room.name)
)
except Exception as e:
logger.error(f"Error deleting room: {e}")
@function_tool
async def attack(self, context: RunContext_T, target_name: str = None):
"""Attack an enemy"""
userdata = context.userdata
combat_state = userdata.combat_state
if not combat_state or combat_state.is_complete:
return "You're not in combat!"
# Verify it's player's turn
if combat_state.get_current_character() != userdata.player_character:
return "It's not your turn!"
# Find target
enemies = self._get_active_enemies(userdata)
if not enemies:
return "No enemies to attack!"
target = None
if target_name:
# Look for target in the initiative order to ensure we have the right reference
for char in combat_state.initiative_order:
if isinstance(char, NPCCharacter) and char.name.lower() == target_name.lower():
target = char
break
if not target and enemies:
target = enemies[0] # Default to first enemy
# Perform attack
hit, damage, description = Combat.perform_attack(userdata.player_character, target)
combat_state.combat_log.append(description)
# Emit combat update
await self.emit_state_update("combat_action", {
"action": "attack",
"attacker": userdata.player_character.name,
"target": target.name,
"hit": hit,
"damage": damage
})
# Create cinematic response for TTS
if hit:
if damage > 0:
# Get weapon name for flavor
weapon_name = userdata.player_character.equipped_weapon.name if userdata.player_character.equipped_weapon else "weapon"
response = f"Your {weapon_name} strikes true! {target.name} takes {damage} damage"
if target.current_health <= 0:
response += f" and falls to the ground, defeated!"
elif target.current_health < target.max_health * 0.25:
response += f"! {target.name} is barely standing!"
elif target.current_health < target.max_health * 0.5:
response += f"! {target.name} is badly wounded!"
else:
response += "!"
else:
response = f"Your attack connects but {target.name}'s armor absorbs the blow!"
else:
response = f"{target.name} dodges your attack!"
# Queue the player's attack result
combat_state.action_queue.put(CombatAction(message=response, delay=0.0))
# Check if enemy defeated
if target.current_health <= 0:
logger.info(f"Enemy {target.name} defeated, removing from combat")
logger.info(f"Before removal - initiative_order: {[c.name for c in combat_state.initiative_order]}")
logger.info(f"Combat state before removal - is_complete: {combat_state.is_complete}")
# Track defeated enemy for XP calculation
combat_state.defeated_enemies.append(target)
logger.info(f"Added {target.name} (level {target.level}) to defeated enemies list")
combat_state.remove_defeated(target)
userdata.current_npcs.remove(target)
logger.info(f"After removal - initiative_order: {[c.name for c in combat_state.initiative_order]}")
logger.info(f"Combat state after removal - is_complete: {combat_state.is_complete}")
# Emit defeat update
await self.emit_state_update("character_defeated", {
"character": target.name,
"type": "enemy"
})
# Check if combat is over
if combat_state.is_complete:
logger.info("Combat is complete, ending combat and returning to narrator")
# End combat and switch to narrator
result = await self._end_combat(context, victory=True)
return result
# Advance turn
combat_state.next_turn()
# Queue NPC turn processing
await self._queue_npc_turn()
# Process the action queue
await self._process_action_queue()
return None
@function_tool
async def defend(self, context: RunContext_T):
"""Take a defensive stance"""
userdata = context.userdata
combat_state = userdata.combat_state
if not combat_state or combat_state.is_complete:
return "You're not in combat!"
if combat_state.get_current_character() != userdata.player_character:
return "It's not your turn!"
# Temporary AC boost (would need to track this properly in real implementation)
description = Combat.perform_defend(userdata.player_character)
combat_state.combat_log.append(description)
# Queue the defend action
combat_state.action_queue.put(CombatAction(message=description, delay=0.0))
# Advance turn
combat_state.next_turn()
# Queue NPC turns and process
await self._queue_npc_turn()
await self._process_action_queue()
return None
@function_tool
async def cast_spell(self, context: RunContext_T, spell_name: str, target_name: str = None):
"""Cast a spell"""
userdata = context.userdata
combat_state = userdata.combat_state
if not combat_state or combat_state.is_complete:
return "You're not in combat!"
if combat_state.get_current_character() != userdata.player_character:
return "It's not your turn!"
# Find target if needed
target = None
if target_name:
if target_name.lower() == "self" or target_name.lower() == userdata.player_character.name.lower():
target = userdata.player_character
else:
for enemy in self._get_active_enemies(userdata):
if enemy.name.lower() == target_name.lower():
target = enemy
break
# Cast spell
result = SpellCasting.cast_spell(userdata.player_character, spell_name.lower(), target)
combat_state.combat_log.append(result)
# Queue the spell cast result
combat_state.action_queue.put(CombatAction(message=result, delay=0.0))
# Check if any enemies defeated
for enemy in list(self._get_active_enemies(userdata)):
logger.info(f"Checking enemy {enemy.name}: health = {enemy.current_health}")
if enemy.current_health <= 0:
logger.info(f"Enemy {enemy.name} defeated! Removing from combat.")
# Track defeated enemy for XP calculation
combat_state.defeated_enemies.append(enemy)
logger.info(f"Added {enemy.name} (level {enemy.level}) to defeated enemies list")
combat_state.remove_defeated(enemy)
userdata.current_npcs.remove(enemy)
logger.info(f"Checking if combat is complete: {combat_state.is_complete}")
logger.info(f"Remaining enemies in combat: {[e.name for e in self._get_active_enemies(userdata)]}")
if combat_state.is_complete:
logger.info("Combat is complete! Ending combat...")
result = await self._end_combat(context, victory=True)
return result
# Advance turn
combat_state.next_turn()
# Queue NPC turns and process
await self._queue_npc_turn()
await self._process_action_queue()
return None
@function_tool
async def use_combat_item(self, context: RunContext_T, item_name: str):
"""Use an item during combat"""
userdata = context.userdata
combat_state = userdata.combat_state
if not combat_state or combat_state.is_complete:
return "You're not in combat!"
if combat_state.get_current_character() != userdata.player_character:
return "It's not your turn!"
# Delegate to narrator's use_item but in combat context
from agents.narrator_agent import NarratorAgent
narrator = NarratorAgent()
result = await narrator.use_item(context, item_name)
combat_state.combat_log.append(result)
# Queue the item use result
combat_state.action_queue.put(CombatAction(message=result, delay=0.0))
# Advance turn
combat_state.next_turn()
# Queue NPC turns and process
await self._queue_npc_turn()
await self._process_action_queue()
return None
@function_tool
async def flee_combat(self, context: RunContext_T):
"""Attempt to flee from combat"""
userdata = context.userdata
combat_state = userdata.combat_state
if not combat_state or combat_state.is_complete:
return "You're not in combat!"
if combat_state.get_current_character() != userdata.player_character:
return "It's not your turn!"
enemies = self._get_active_enemies(userdata)
success, description = Combat.attempt_flee(userdata.player_character, enemies)
# Queue the flee attempt result
combat_state.action_queue.put(CombatAction(message=description, delay=0.0))
if success:
# Process queue before ending combat
await self._process_action_queue()
# End combat
result = await self._end_combat(context, victory=False, fled=True)
return result
else:
# Failed - lose turn
combat_state.combat_log.append(description)
combat_state.next_turn()
# Queue NPC turns and process
await self._queue_npc_turn()
await self._process_action_queue()
return None
async def _end_combat(self, context: RunContext_T, victory: bool, fled: bool = False):
"""End combat and return to narrator"""
userdata = context.userdata
if victory and not fled:
# Calculate rewards from defeated enemies tracked during combat
combat_state = userdata.combat_state
total_xp = sum(enemy.level * 50 for enemy in combat_state.defeated_enemies)
logger.info(f"Calculating XP from {len(combat_state.defeated_enemies)} defeated enemies")
logger.info(f"Defeated enemies: {[(e.name, e.level) for e in combat_state.defeated_enemies]}")
logger.info(f"Total XP earned: {total_xp}")
all_loot = []
total_gold = 0
# Transfer loot from defeated enemies
for enemy in combat_state.defeated_enemies:
loot_desc = GameUtilities.transfer_loot(enemy, userdata.player_character)
if "gold" in loot_desc:
# Extract gold amount for total
gold_match = re.search(r'(\d+) gold', loot_desc)
if gold_match:
total_gold += int(gold_match.group(1))
# Extract actual items from loot description
if loot_desc != "The enemy had nothing of value.":
# Remove "You found: " prefix and just store the items
clean_loot = loot_desc.replace("You found: ", "")
# Don't include gold in the loot list since we track it separately
if "gold" in clean_loot and not any(word in clean_loot for word in ["golden", "gold-"]):
# Extract non-gold items
parts = clean_loot.split(" and ")
for part in parts:
if "gold" not in part or any(word in part for word in ["golden", "gold-"]):
all_loot.append(part.strip())
else:
all_loot.append(clean_loot)
# Grant experience
level_up_msg = userdata.player_character.gain_experience(total_xp)
# Store combat results for narrator
userdata.combat_result = {
"xp_gained": total_xp,
"level_up": level_up_msg,
"loot": all_loot,
"gold_gained": total_gold,
"defeated_enemies": [(e.name, e.level) for e in combat_state.defeated_enemies]
}
# No need to build result message - narrator will handle it
# Emit inventory update after loot collection
await self.emit_state_update("inventory_changed", {
"action": "loot_collected",
"gold_gained": total_gold,
"items_gained": len(all_loot)
})
# Print loot summary to console
if all_loot or total_gold > 0:
print(f"\n{Colors.YELLOW}{'💰' * 20}{Colors.ENDC}")
print(f"{Colors.BOLD}📦 LOOT COLLECTED{Colors.ENDC}")
if total_gold > 0:
print(f"{Colors.BOLD} Gold: {Colors.YELLOW}{total_gold}{Colors.ENDC}")
for loot_line in all_loot:
if "gold" not in loot_line.lower() or "item" in loot_line.lower():
print(f" {loot_line}")
print(f"{Colors.YELLOW}{'💰' * 20}{Colors.ENDC}\n")
userdata.add_story_event(f"Won combat - gained {total_xp} XP")
elif fled:
userdata.add_story_event("Fled from combat")
else:
userdata.game_state = "game_over"
# Clean up combat state
userdata.combat_state = None
userdata.game_state = "exploration" if victory or fled else "game_over"
userdata.current_agent_type = "narrator"
userdata.active_npc = None # Clear active NPC when combat ends
# Clear defeated enemies
userdata.current_npcs = [npc for npc in userdata.current_npcs if npc.current_health > 0]
# Store current agent for context preservation
userdata.prev_agent = self
# Set flag for narrator to know combat just ended
userdata.combat_just_ended = True
# Don't say anything - let the narrator handle all messaging
# Just switch back to narrator agent
from agents.narrator_agent import NarratorAgent
self.session.update_agent(NarratorAgent())
return "Combat ended"
@function_tool
async def check_combat_status(self, context: RunContext_T):
"""Check the current combat status"""
userdata = context.userdata
combat_state = userdata.combat_state
if not combat_state or combat_state.is_complete:
return "You're not in combat!"
status = f"Round {combat_state.round_number}\n"
status += f"Turn order: {', '.join(c.name for c in combat_state.initiative_order)}\n"
status += f"Current turn: {combat_state.get_current_character().name}\n\n"
# Character statuses
for char in combat_state.initiative_order:
status += char.get_status_description() + "\n"
return status | 0 | 0.90935 | 1 | 0.90935 | game-dev | MEDIA | 0.713005 | game-dev,web-backend | 0.984037 | 1 | 0.984037 |
OpenXRay/xray-15 | 12,386 | cs/sdk/3d_sdk/maya/ver-2008/devkit/obsolete/games/vrml2Export/vrml2Tags.mel | //-
// ==========================================================================
// Copyright (C) 1995 - 2005 Alias Systems Corp. and/or its licensors. All
// rights reserved.
//
// The coded instructions, statements, computer programs, and/or related
// material (collectively the "Data") in these files are provided by Alias
// Systems Corp. ("Alias") and/or its licensors for the exclusive use of the
// Customer (as defined in the Alias Software License Agreement that
// accompanies this Alias software). Such Customer has the right to use,
// modify, and incorporate the Data into other products and to distribute such
// products for use by end-users.
//
// THE DATA IS PROVIDED "AS IS". ALIAS HEREBY DISCLAIMS ALL WARRANTIES
// RELATING TO THE DATA, INCLUDING, WITHOUT LIMITATION, ANY AND ALL EXPRESS OR
// IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE. IN NO EVENT SHALL ALIAS BE LIABLE FOR ANY DAMAGES
// WHATSOEVER, WHETHER DIRECT, INDIRECT, SPECIAL, OR PUNITIVE, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, OR IN EQUITY,
// ARISING OUT OF ACCESS TO, USE OF, OR RELIANCE UPON THE DATA.
// ==========================================================================
//+
//
// This Mel file supports the VRML2 properties that can be attached to
// nodes that the VRML2 translator will query and export into the VRML2
// file.
//
global int $gVrmlIdx = 0;
//
// Reset the global pointer to the 1st selected item on the selection list
//
global proc firstVRML2()
{
global int $gVrmlIdx;
$gVrmlIdx = 0;
loadVRML2();
}
//
// Skip to the previous item on the selection list
//
global proc backVRML2()
{
global int $gVrmlIdx;
if ( $gVrmlIdx > 0 )
$gVrmlIdx--;
loadVRML2();
}
//
// Skip to the next item on the selection list
//
global proc forwardVRML2()
{
global int $gVrmlIdx;
$gVrmlIdx++;
loadVRML2();
}
//
// Skip to the last item on the selection list
//
global proc lastVRML2()
{
global int $gVrmlIdx;
$gVrmlIdx = size( `ls -st` );
loadVRML2();
}
//
// Copy out the VRML2 properties of the current index item on the
// selection list, into the UI generated here, so the user can actually
// see what is there.
//
global proc loadVRML2()
{
global int $gVrmlIdx;
string $title;
string $linkl;
string $msg;
string $aBill;
int $bill;
string $aPrim;
int $prim;
string $aSensor;
int $sensor;
string $aColl;
int $coll;
$obj = `ls -sl`;
if ( size( $obj ) == 0 )
{
$gVrmlIdx = 0;
return;
} else {
if ( $gVrmlIdx >= size( $obj ) )
$gVrmlIdx = size( $obj ) - 1;
}
if ( `attributeQuery -exists -node $obj[$gVrmlIdx] "vrml2Link"` )
{
$title = "VRML2 Properties for " + $obj[$gVrmlIdx];
text -e -label $title vrmlTitle;
$link = $obj[$gVrmlIdx] + "." + "vrml2Link";
textFieldGrp -e -text `getAttr $link` vrmlLink;
$msg = $obj[$gVrmlIdx] + "." + "vrml2Desc";
textFieldGrp -e -text `getAttr $msg` vrmlDesc;
$aBill = $obj[$gVrmlIdx] + "." + "vrml2Billboard";
$bill = `getAttr $aBill` + 1;
optionMenuGrp -e -sl $bill vrmlBillboard;
$aPrim = $obj[$gVrmlIdx] + "." + "vrml2Primitive";
$prim = `getAttr $aPrim` + 1;
optionMenuGrp -e -sl $prim vrmlPrimitive;
$aSensor = $obj[$gVrmlIdx] + "." + "vrml2Sensor";
$sensor = `getAttr $aSensor` + 1;
optionMenuGrp -e -sl $sensor vrmlSensor;
$aColl = $obj[$gVrmlIdx] + "." + "vrml2Collision";
$coll = `getAttr $aColl` + 1;
optionMenuGrp -e -sl $coll vrmlCollision;
$title = "VRML2 Properties for " + $obj[$gVrmlIdx];
text -e -label $title vrmlTitle;
}
else
{
$title = "VRML2 Properties for " + $obj[$gVrmlIdx] + " not defined";
text -e -label $title vrmlTitle;
}
}
//
// Update the currently selection item of the selection list with the
// current data that is displayed in the UI
//
global proc updateVRML2( int $mode )
{
global int $gVrmlIdx;
string $title;
string $linkl;
string $msg;
string $aBill;
int $bill;
string $aPrim;
int $prim;
string $aSensor;
int $sensor;
string $aColl;
int $coll;
$obj = `ls -sl`;
if ( size( $obj ) == 0 )
{
$gVrmlIdx = 0;
return;
} else {
if ( $gVrmlIdx >= size( $obj ) )
$gVrmlIdx = size( $obj ) - 1;
}
if ( `attributeQuery -exists -node $obj[$gVrmlIdx] "vrml2Link"` )
{
$title = "VRML2 Properties for " + $obj[$gVrmlIdx];
text -e -label $title vrmlTitle;
$link = $obj[$gVrmlIdx] + "." + "vrml2Link";
$text = `textFieldGrp -q -text vrmlLink`;
setAttr -typ "string" $link $text;
$msg = $obj[$gVrmlIdx] + "." + "vrml2Desc";
$text = `textFieldGrp -q -text vrmlDesc`;
setAttr -typ "string" $msg $text;
$aBill = $obj[$gVrmlIdx] + "." + "vrml2Billboard";
$bill = `optionMenuGrp -q -sl vrmlBillboard`;
$bill = $bill - 1;
setAttr $aBill $bill;
$aPrim = $obj[$gVrmlIdx] + "." + "vrml2Primitive";
$prim = `optionMenuGrp -q -sl vrmlPrimitive`;
$prim = $prim - 1;
setAttr $aPrim $prim;
$aSensor = $obj[$gVrmlIdx] + "." + "vrml2Sensor";
$sensor = `optionMenuGrp -q -sl vrmlSensor`;
$sensor = $sensor - 1;
setAttr $aSensor $sensor;
$aColl = $obj[$gVrmlIdx] + "." + "vrml2Collision";
$coll = `optionMenuGrp -q -sl vrmlCollision`;
$coll = $coll - 1;
setAttr $aColl $coll;
$title = "VRML2 Properties for " + $obj[$gVrmlIdx];
text -e -label $title vrmlTitle;
}
else
{
$title = "VRML2 Properties for " + $obj[$gVrmlIdx] + " not defined";
text -e -label $title vrmlTitle;
}
}
//
// Add the basic VRML2 properties to the selected item in the selection list
// There is are options to do this operation on the entire selection list
// as well as to add in the current displayed values to the objects at the
// same time.
//
global proc addVRML2()
{
// Here we create the dynamic attributes on the selected object
// if there isn't already a vrml2Link attribute there.
global int $gVrmlIdx;
$obj = `ls -sl`;
int $idx;
int $last;
int $saveCurIdx;
// Find the number of selected items. If zero then quit now
$last = size( $obj );
if ( $last == 0 )
return;
// See if we are doing this for all selected items
$saveCurIdx = $gVrmlIdx;
if ( `checkBoxGrp -q -v1 vrmlDoAll` == 0 )
{
$idx = $gVrmlIdx;
$last = $gVrmlIdx + 1;
} else {
$idx = 0;
}
// Now do the actual work of deleting the attributes
for ( ; $idx < $last; $idx++ )
{
if ( `attributeQuery -exists -node $obj[$idx] "vrml2Link"` )
{
//print ( "VRML2 properties already defined for " + $obj[$idx] );
} else {
addAttr -ln "vrml2Link" -sn "vL" -dt "string" $obj[$idx];
addAttr -ln "vrml2Desc" -sn "vD" -dt "string" $obj[$idx];
addAttr -ln "vrml2Billboard" -sn "vB" -at long $obj[$idx];
addAttr -ln "vrml2Primitive" -sn "vP" -at long $obj[$idx];
addAttr -ln "vrml2Sensor" -sn "vS" -at long $obj[$idx];
addAttr -ln "vrml2Collision" -sn "vC" -at long -dv 1 $obj[$idx];
}
// See if want to set the data to the current values
// at the same time as creating attributes
if ( `checkBoxGrp -q -v1 vrmlDoAdd` == 1 )
{
$gVrmlIdx = $idx;
updateVRML2( 1 );
}
}
// Now restore the original index
$gVrmlIdx = $saveCurIdx;
loadVRML2();
}
//
// Here we will be deleting the VRML2 property dynamic attributes off of
// the currently selected item in the selection list or if defined by the
// option, the entire selection list
//
global proc deleteVRML2()
{
// Here we delete the dynamic attributes on the selected object
// if there is a vrml2Link attribute there.
$obj = `ls -sl`;
int $idx;
int $last;
// Find the number of selected items. If zero then quit now
$last = size( $obj );
if ( $last == 0 )
return;
// See if we are doing this for all selected items
if ( `checkBoxGrp -q -v1 vrmlDoAll` == 0 )
$last = 1;
// Now do the actual work of deleting the attributes
for ( $idx = 0; $idx < $last; $idx++ )
{
if ( `attributeQuery -exists -node $obj[$idx] "vrml2Link"` )
{
deleteAttr -at "vrml2Link" $obj[$idx];
deleteAttr -at "vrml2Desc" $obj[$idx];
deleteAttr -at "vrml2Billboard" $obj[$idx];
deleteAttr -at "vrml2Primitive" $obj[$idx];
deleteAttr -at "vrml2Sensor" $obj[$idx];
deleteAttr -at "vrml2Collision" $obj[$idx];
}
}
}
//
// Routine to close the UI dialog window
//
global proc closeVRML2()
{
deleteUI vrml2TagsWin;
}
//
// Description:
// If the selection changes while the vrml2 properties window is
// visible, we want to update the current displayed data
//
global proc newSelectionVRML2()
{
if ( (`isTrue SomethingSelected` == 0) ||
!`window -exists vrml2TagsWin` )
{
$title = "VRML2 Properties for ";
text -e -label $title vrmlTitle;
return;
}
loadVRML2();
}
//
// Here we build the basic window that will display the information for
// us. This can be modified and extended as the need arises to enable
// more functionality of the VRML2 spec, and the translator.
//
global proc buildVRML2Window ( )
{
window
-rtf true
vrml2TagsWin;
columnLayout;
text -label "VRML2 Properties" vrmlTitle;
textFieldGrp -label "vrml2 Link"
-text ""
-cc "updateVRML2(0)" vrmlLink;
textFieldGrp -label "vrml2 Msg"
-text ""
-cc "updateVRML2(0)" vrmlDesc;
optionMenuGrp -label "vrml2 Billboard"
-cal 1 "right"
-cc "updateVRML2(0)" vrmlBillboard;
menuItem -label "None";
menuItem -label "X Rotating";
menuItem -label "Y Rotating";
menuItem -label "Screen Aligned";
optionMenuGrp -e -sl 1 vrmlBillboard;
optionMenuGrp -label "vrml2 Primitive"
-cal 1 "right"
-cc "updateVRML2(0)" vrmlPrimitive;
menuItem -label "None";
menuItem -label "Box";
menuItem -label "Cone";
menuItem -label "Cylinder";
menuItem -label "Sphere";
menuItem -label "Elevation grid";
optionMenuGrp -e -sl 1 vrmlPrimitive;
optionMenuGrp -label "vrml2 Sensor"
-cal 1 "right"
-cc "updateVRML2(0)" vrmlSensor;
menuItem -label "None";
menuItem -label "Cylinder";
menuItem -label "Sphere";
menuItem -label "Plane";
menuItem -label "Proximity";
menuItem -label "Touch";
menuItem -label "Visibility";
optionMenuGrp -e -sl 1 vrmlSensor;
optionMenuGrp -label "vrml2 Collision"
-cal 1 "right"
-cc "updateVRML2(0)" vrmlCollision;
menuItem -label "None";
menuItem -label "Object";
optionMenuGrp -e -sl 2 vrmlCollision;
checkBoxGrp -label " " -ncb 1
-cw 2 200
-l1 "Do All selected" vrmlDoAll;
checkBoxGrp -label " " -ncb 1
-cw 2 200
-l1 "Add and Update" vrmlDoAdd;
rowLayout -nc 4 -cw 3 112
-cat 1 "both" 0
-cat 2 "both" 0
-cat 3 "both" 0
-cat 4 "both" 0
btnRow;
button -rs 0 -h 28 -l "Add" -al "center" -c "addVRML2";
button -rs 0 -h 28 -l "Delete" -al "center" -c "deleteVRML2";
gridLayout
-cellWidth 28
-numberOfRowsColumns 1 4;
symbolButton
-image "timerew.xpm"
-annotation "first item"
-command firstVRML2;
symbolButton
-image "timeend.xpm"
-annotation "Step back one item"
-command backVRML2;
symbolButton
-image "timestart.xpm"
-annotation "Step forward one item"
-command forwardVRML2;
symbolButton
-image "timefwd.xpm"
-annotation "Step forward one item"
-command lastVRML2;
setParent ..;
button -rs 0 -h 28 -l "Close" -al "center" -c "closeVRML2";
setParent ..;
setParent ..;
}
//
// The main VRML2 property control Mel command
//
global proc vrml2Tags ( )
{
if (!`window -exists vrml2TagsWin`) {
buildVRML2Window;
}
// Setup a scriptJob to see selection changes.
scriptJob -e "SelectionChanged" newSelectionVRML2 -p vrml2TagsWin;
// Load in the current selected item
loadVRML2();
// Show the window to all
showWindow vrml2TagsWin;
}
| 0 | 0.847446 | 1 | 0.847446 | game-dev | MEDIA | 0.283085 | game-dev | 0.528265 | 1 | 0.528265 |
Tesserex/C--MegaMan-Engine | 4,668 | IO/Xml/ProjectXmlReader.cs | using System.Linq;
using System.Xml.Linq;
using MegaMan.Common;
using MegaMan.IO.DataSources;
using MegaMan.IO.Xml.Handlers;
namespace MegaMan.IO.Xml
{
internal class ProjectXmlReader : IProjectReader
{
private Project project;
private IDataSource dataSource;
private readonly HandlerTransferXmlReader transferReader;
public ProjectXmlReader(HandlerTransferXmlReader transferReader)
{
this.transferReader = transferReader;
}
public string Extension { get { return ".xml"; } }
public void Init(IDataSource dataSource)
{
this.dataSource = dataSource;
}
public Project Load()
{
project = new Project();
var gameFilePath = dataSource.GetGameFile();
project.GameFile = gameFilePath;
var stream = dataSource.GetData(gameFilePath);
var reader = XElement.Load(stream);
stream.Dispose();
var nameAttr = reader.Attribute("name");
if (nameAttr != null) project.Name = nameAttr.Value;
var authAttr = reader.Attribute("author");
if (authAttr != null) project.Author = authAttr.Value;
var sizeNode = reader.Element("Size");
if (sizeNode != null)
{
project.ScreenWidth = sizeNode.TryAttribute<int>("x");
project.ScreenHeight = sizeNode.TryAttribute<int>("y");
}
var nsfNode = reader.Element("NSF");
if (nsfNode != null)
{
LoadNsfInfo(nsfNode);
}
var stagesNode = reader.Element("Stages");
if (stagesNode != null)
{
foreach (var stageNode in stagesNode.Elements("Stage"))
{
var info = new StageLinkInfo();
info.Name = stageNode.RequireAttribute("name").Value;
info.StagePath = FilePath.FromRelative(stageNode.RequireAttribute("path").Value, project.BaseDir);
var winNode = stageNode.Element("Win");
if (winNode != null)
{
var winHandlerNode = winNode.Element("Next");
if (winHandlerNode != null)
{
info.WinHandler = transferReader.Load(winHandlerNode);
}
}
var loseNode = stageNode.Element("Lose");
if (loseNode != null)
{
var loseHandlerNode = loseNode.Element("Next");
if (loseHandlerNode != null)
{
info.LoseHandler = transferReader.Load(loseHandlerNode);
}
}
project.AddStage(info);
}
}
var startNode = reader.Element("Next");
if (startNode != null)
{
project.StartHandler = transferReader.Load(startNode);
}
project.AddIncludeFiles(reader.Elements("Include")
.Select(e => e.Value)
.Where(v => !string.IsNullOrEmpty(v.Trim())));
project.AddIncludeFolders(reader.Elements("IncludeFolder")
.Select(e => e.Value)
.Where(v => !string.IsNullOrEmpty(v.Trim())));
var includeReader = new IncludeFileXmlReader();
var includedFilesFromFolders = project.IncludeFolders.SelectMany(dataSource.GetFilesInFolder);
var allIncludedFiles = project.IncludeFiles.ToList()
.Concat(includedFilesFromFolders)
.Distinct().ToList();
foreach (var includePath in allIncludedFiles)
{
var includeStream = dataSource.GetData(includePath);
includeReader.LoadIncludedFile(project, includePath, includeStream, dataSource);
includeStream.Dispose();
}
stream.Close();
return project;
}
private void LoadNsfInfo(XElement nsfNode)
{
var musicNode = nsfNode.Element("Music");
if (musicNode != null)
{
project.MusicNsf = FilePath.FromRelative(musicNode.Value, project.BaseDir);
}
var sfxNode = nsfNode.Element("SFX");
if (sfxNode != null)
{
project.EffectsNsf = FilePath.FromRelative(sfxNode.Value, project.BaseDir);
}
}
}
}
| 0 | 0.947107 | 1 | 0.947107 | game-dev | MEDIA | 0.848284 | game-dev | 0.980351 | 1 | 0.980351 |
CFPAOrg/Modpack-GuideBook-i18n | 34,316 | project/FTB Interactions/1.9.1/scripts/AstralSorcery.zs | import crafttweaker.item.IItemStack;
import crafttweaker.item.IIngredient;
import mods.artisanworktables.builder.RecipeBuilder;
import mods.thaumcraft.ArcaneWorkbench;
import mods.thaumcraft.Infusion;
import mods.gregtech.recipe.RecipeMap;
import mods.astralsorcery.Utils;
import crafttweaker.block.IBlockProperties;
import crafttweaker.block.IBlockDefinition;
import crafttweaker.block.IBlock;
import mods.botaniatweaks.Agglomeration;
import mods.botaniatweaks.AgglomerationRecipe;
import mods.thermalexpansion.Insolator;
print("---------------Astral Sorcery Start------------------");
val autoclave = mods.gregtech.recipe.RecipeMap.getByName("autoclave");
val alloyer = mods.gregtech.recipe.RecipeMap.getByName("alloy_smelter");
val macerator = mods.gregtech.recipe.RecipeMap.getByName("macerator");
//<forge:bucketfilled>.withTag({FluidName: "astralsorcery.liquidstarlight", Amount: 1000});
val starlightBucket = <forge:bucketfilled>.withTag({FluidName: "astralsorcery.liquidstarlight", Amount: 1000});
val starlightFluidStack = <liquid:astralsorcery.liquidstarlight>;
val resonatingGem = <astralsorcery:itemcraftingcomponent:4>;
val starmetalOre = <astralsorcery:blockcustomore:1>;
val rockCrystalOre = <astralsorcery:blockcustomore>;
val salisMundis = <thaumcraft:salis_mundus>;
val aquamarineGem = <astralsorcery:itemcraftingcomponent>;
val parchment = <astralsorcery:itemcraftingcomponent:5>;
val scribingTools = <thaumcraft:scribing_tools>;
val illuminationPowder = <astralsorcery:itemusabledust>;
val rockCrystal = mods.astralsorcery.Utils.getCrystalORIngredient(false, false);
val celestialCrystal = mods.astralsorcery.Utils.getCrystalORIngredient(true, false);
val attunedCelestialCrystal = mods.astralsorcery.Utils.getCrystalORIngredient(true,true);
val craftingLens = <astralsorcery:itemcraftingcomponent:3>;
val runedMarble = <astralsorcery:blockmarble:6>;
val sootyMarble = <astralsorcery:blockblackmarble>;
#lightwell additions
#nitor better than aquamarine
mods.astralsorcery.Lightwell.addLiquefaction(<thaumcraft:nitor_yellow>, <liquid:astralsorcery.liquidstarlight>, 0.8, 12, 0);
#nether star lense
mods.astralsorcery.Lightwell.addLiquefaction(<ore:lensNetherStar>.firstItem, <liquid:astralsorcery.liquidstarlight>, 2, 500, 0);
#Primordial Pearl
mods.astralsorcery.Lightwell.addLiquefaction(<thaumcraft:primordial_pearl>, <liquid:astralsorcery.liquidstarlight>, 2.5, 2147480, 0);
#infused wood tooltip
<astralsorcery:blockinfusedwood>.addTooltip(format.darkRed("将原木投入星能液中来制作。"));
#Mana diamond
mods.astralsorcery.Lightwell.addLiquefaction(<botania:manaresource:2>, <liquid:astralsorcery.liquidstarlight>, 0.8, 100, 0);
#dragonstone
mods.astralsorcery.Lightwell.addLiquefaction(<botania:manaresource:9>, <liquid:astralsorcery.liquidstarlight>, 1, 150, 0);
#flawless diamond
mods.astralsorcery.Lightwell.addLiquefaction(<ore:gemFlawlessDiamond>.firstItem, <liquid:astralsorcery.liquidstarlight>, 1, 200, 0);
#flawless sapphire
mods.astralsorcery.Lightwell.addLiquefaction(<ore:gemFlawlessSapphire>.firstItem, <liquid:astralsorcery.liquidstarlight>, 1, 150, 0);
#flawless Lapis
mods.astralsorcery.Lightwell.addLiquefaction(<ore:gemFlawlessLapis>.firstItem, <liquid:astralsorcery.liquidstarlight>, 1, 150, 0);
#flawless vinteum
mods.astralsorcery.Lightwell.addLiquefaction(<ore:gemFlawlessVinteum>.firstItem, <liquid:astralsorcery.liquidstarlight>, 5, 200, 0);
#lava from lava crystal
mods.astralsorcery.Lightwell.addLiquefaction(<bloodmagic:lava_crystal>, <liquid:lava>, 1, 200, 0);
#resonating gem
mods.astralsorcery.StarlightInfusion.removeInfusion(resonatingGem);
Agglomeration.addRecipe(resonatingGem, [aquamarineGem, <ore:dustAstralStarmetal>.firstItem, <botania:manaresource:1>]);
#remove vanilla ore processing, exchange for GT
mods.astralsorcery.StarlightInfusion.removeInfusion(<minecraft:diamond>*4);
mods.astralsorcery.StarlightInfusion.removeInfusion(<minecraft:emerald>*4);
mods.astralsorcery.StarlightInfusion.removeInfusion(<minecraft:redstone_block>);
mods.astralsorcery.StarlightInfusion.removeInfusion(<minecraft:lapis_block>);
mods.astralsorcery.StarlightInfusion.removeInfusion(<minecraft:iron_ingot>*3);
mods.astralsorcery.StarlightInfusion.removeInfusion(<minecraft:gold_ingot>*3);
mods.astralsorcery.StarlightInfusion.addInfusion(<ore:oreDiamond>.firstItem, <minecraft:diamond>*4, false, 0.4, 200);
mods.astralsorcery.StarlightInfusion.addInfusion(<ore:oreEmerald>.firstItem, <minecraft:emerald>*4, false, 0.4, 200);
mods.astralsorcery.StarlightInfusion.addInfusion(<ore:oreRedstone>.firstItem, <minecraft:redstone_block>, false, 0.4, 200);
mods.astralsorcery.StarlightInfusion.addInfusion(<ore:oreLapis>.firstItem, <minecraft:lapis_block>, false, 0.4, 200);
#bismuth from stibnite
mods.astralsorcery.LightTransmutation.addTransmutation(<ore:oreStibnite>.firstItem, <ore:oreBismuth>.firstItem, 250);
mods.astralsorcery.LightTransmutation.addTransmutation(<ore:oreNetherrackStibnite>.firstItem, <ore:oreBismuth>.firstItem, 250);
#infused wood
mods.astralsorcery.StarlightInfusion.removeInfusion(<astralsorcery:blockinfusedwood:6>);
#starlight Infuser
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/starlightinfuser");
mods.astralsorcery.Altar.addAttunementAltarRecipe("astralsorcery:shaped/internal/altar/starlightinfuser", <astralsorcery:blockstarlightinfuser>, 320, 600, [
<ore:screwThaumium>,<ore:plateElectrum>,<ore:screwThaumium>,
<ore:plateElectrum>,starlightFluidStack,<ore:plateElectrum>,
<ore:screwThaumium>,<ore:plateElectrum>,<ore:screwThaumium>,
runedMarble,runedMarble,runedMarble,runedMarble]);
#faint amaranth to glowstone
//mods.thermalexpansion.Insolator.removeRecipe(IItemStack primaryInput, IItemStack secondaryInput);
mods.thermalexpansion.Insolator.removeRecipe(<astralsorcery:blockcustomflower>, <thermalfoundation:fertilizer:2>);
//mods.thermalexpansion.Insolator.addRecipe(IItemStack primaryOutput, IItemStack primaryInput, IItemStack secondaryInput, int energy, @Optional IItemStack secondaryOutput, @Optional int secondaryChance);
mods.thermalexpansion.Insolator.addRecipe(<minecraft:glowstone_dust>, <astralsorcery:blockcustomflower>, <thermalfoundation:fertilizer>, 2500, <astralsorcery:blockcustomflower>, 100);
mods.thermalexpansion.Insolator.addRecipe(<minecraft:glowstone_dust>*2, <astralsorcery:blockcustomflower>, <thermalfoundation:fertilizer:1>, 2500, <astralsorcery:blockcustomflower>, 100);
mods.thermalexpansion.Insolator.addRecipe(<minecraft:glowstone_dust>*3, <astralsorcery:blockcustomflower>, <thermalfoundation:fertilizer:2>, 2500, <astralsorcery:blockcustomflower>, 100);
#faint amaranth flower
mods.thaumcraft.Infusion.registerRecipe("faintamaranth", "INFUSION", <astralsorcery:blockcustomflower>, 4, [<aspect:lux> * 32, <aspect:herba> * 32, <aspect:sensus> * 16], <randomthings:lotusseeds>,
[<astralsorcery:itemcraftingcomponent>,<astralsorcery:itemcraftingcomponent>,<botania:petal:5>,<botania:petal:5>,<plants2:generic:6>,<plants2:generic:6>]);
#Aquamarine
autoclave.recipeBuilder()
.inputs(<ore:gemSapphire> * 1)
.fluidInputs([<liquid:water> * 1000])
.chancedOutput(aquamarineGem, 5000, 500)
.duration(2000)
.EUt(24)
.buildAndRegister();
autoclave.recipeBuilder()
.inputs(<ore:gemSapphire> * 1)
.fluidInputs([<liquid:astralsorcery.liquidstarlight> * 10])
.outputs(aquamarineGem * 1)
.duration(100)
.EUt(4)
.buildAndRegister();
#macerate starmetal
macerator.recipeBuilder()
.inputs(starmetalOre)
.outputs(<astralsorcery:itemcraftingcomponent:2> *2)
.chancedOutput(<astralsorcery:itemcraftingcomponent:2>, 500, 100)
.duration(40)
.EUt(48)
.buildAndRegister();
macerator.recipeBuilder()
.inputs(<ore:ingotAstralStarmetal>)
.outputs(<astralsorcery:itemcraftingcomponent:2>)
.duration(40)
.EUt(48)
.buildAndRegister();
#remove starmetal transmutation
mods.astralsorcery.LightTransmutation.removeTransmutation(starmetalOre, false);
#remove end stone
mods.astralsorcery.LightTransmutation.removeTransmutation(<minecraft:end_stone>, false);
mods.astralsorcery.LightTransmutation.addTransmutation(<advancedrocketry:moonturf_dark>, <minecraft:end_stone>, 250);
mods.astralsorcery.LightTransmutation.addTransmutation(<advancedrocketry:moonturf>, <minecraft:end_stone>, 250);
#shifting Star
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/tool_shiftstar");
mods.astralsorcery.Altar.addAttunementAltarRecipe("astralsorcery:shaped/internal/altar/tool_shiftstar", <astralsorcery:itemshiftingstar>.withTag({astralsorcery: {}}), 500, 600, [
runedMarble, <ore:gemDiamond>, runedMarble,
illuminationPowder, starlightFluidStack,illuminationPowder,
runedMarble, <ore:gemDiamond>, runedMarble,
aquamarineGem, aquamarineGem, aquamarineGem, aquamarineGem]);
#attunement Altar
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/attunementaltar");
mods.astralsorcery.Altar.addAttunementAltarRecipe("astralsorcery:shaped/attunementaltar", <astralsorcery:blockattunementaltar>, 450, 600, [
<ore:screwBrass>, rockCrystal, <ore:screwBrass>,
aquamarineGem, <astralsorcery:itemshiftingstar>,aquamarineGem,
runedMarble, <astralsorcery:blockattunementrelay>, runedMarble,
aquamarineGem,aquamarineGem,aquamarineGem,aquamarineGem]);
#runed marble
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/marble_runed");
mods.chisel.Carving.removeVariation("marble", runedMarble);
recipes.remove(runedMarble);
mods.thaumcraft.ArcaneWorkbench.registerShapedRecipe("RunedMarble", "", 25, [<aspect:ordo> * 1 ], runedMarble *3,
[[<ore:wireFineSteel>, <ore:wireFineSteel>, <ore:wireFineSteel>],
[<ore:blockMarble>, <astralsorcery:blockmarble:4>, <ore:blockMarble>],
[<ore:wireFineSteel>, <ore:wireFineSteel>, <ore:wireFineSteel>]]
);
#Spectral relay
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/attunementrelay");
mods.astralsorcery.Altar.addDiscoveryAltarRecipe("astralsorcery:shaped/internal/altar/attunementrelay", <astralsorcery:blockattunementrelay>, 120, 600, [
null, null, null,
<ore:screwBrass>, <astralsorcery:itemcraftingcomponent:3>,<ore:screwBrass>,
<astralsorcery:blockinfusedwood>, <astralsorcery:blockmarble:4>, <astralsorcery:blockinfusedwood>]);
#Amulet Rerolll
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/enchantment_amulet_reroll");
mods.astralsorcery.Altar.addAttunementAltarRecipe("astralsorcery:shaped/internal/altar/enchantment_amulet_reroll", <astralsorcery:itemenchantmentamulet>, 350, 300, [
null,<astralsorcery:itemenchantmentamulet>,null,
<ore:dustAstralStarmetal>, starlightFluidStack, <ore:dustAstralStarmetal>,
null,null,null,null,
aquamarineGem,aquamarineGem,null,null]);
#constellations
#discidia
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/constellationpaper/discidia");
mods.astralsorcery.Altar.addDiscoveryAltarRecipe("interactions:discidia", <astralsorcery:itemconstellationpaper>.withTag({astralsorcery: {constellationName: "astralsorcery.constellation.discidia"}}), 120, 200, [
<ore:arrow>, salisMundis, <ore:arrow>,
aquamarineGem, parchment, aquamarineGem,
<ore:arrow>, scribingTools, <ore:arrow>]);
#evorsio
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/constellationpaper/evorsio");
mods.astralsorcery.Altar.addDiscoveryAltarRecipe("interactions:evorsio", <astralsorcery:itemconstellationpaper>.withTag({astralsorcery: {constellationName: "astralsorcery.constellation.evorsio"}}), 120, 200, [
<minecraft:stone_pickaxe>, salisMundis, <minecraft:stone_pickaxe>,
aquamarineGem, parchment, aquamarineGem,
<minecraft:stone_pickaxe>, scribingTools, <minecraft:stone_pickaxe>]);
#octans
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/constellationpaper/octans");
mods.astralsorcery.Altar.addDiscoveryAltarRecipe("interactions:octans", <astralsorcery:itemconstellationpaper>.withTag({astralsorcery: {constellationName: "astralsorcery.constellation.octans"}}), 120, 200, [
<ore:listAllfishraw>, salisMundis, <ore:listAllfishraw>,
aquamarineGem, parchment, aquamarineGem,
<ore:listAllfishraw>, scribingTools, <ore:listAllfishraw>]);
#armara
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/constellationpaper/armara");
mods.astralsorcery.Altar.addDiscoveryAltarRecipe("interactions:armara", <astralsorcery:itemconstellationpaper>.withTag({astralsorcery: {constellationName: "astralsorcery.constellation.armara"}}), 120, 200, [
<minecraft:shield>, salisMundis, <minecraft:shield>,
aquamarineGem, parchment, aquamarineGem,
<minecraft:shield>, scribingTools, <minecraft:shield>]);
#lucerna
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/constellationpaper/lucerna");
mods.astralsorcery.Altar.addDiscoveryAltarRecipe("interactions:lucerna", <astralsorcery:itemconstellationpaper>.withTag({astralsorcery: {constellationName: "astralsorcery.constellation.lucerna"}}), 120, 200, [
illuminationPowder, salisMundis, illuminationPowder,
aquamarineGem, parchment, aquamarineGem,
illuminationPowder, scribingTools, illuminationPowder]);
val speed = <minecraft:potion>.withTag({Potion: "minecraft:swiftness"});
#Vicio
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/constellationpaper/vicio");
mods.astralsorcery.Altar.addAttunementAltarRecipe("interactions:vicio", <astralsorcery:itemconstellationpaper>.withTag({astralsorcery: {constellationName: "astralsorcery.constellation.vicio"}}), 500, 300, [
speed, salisMundis, speed,
aquamarineGem, parchment, aquamarineGem,
speed, scribingTools, speed,
illuminationPowder,illuminationPowder,illuminationPowder,illuminationPowder]);
#bootes
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/constellationpaper/bootes");
mods.astralsorcery.Altar.addAttunementAltarRecipe("interactions:bootes", <astralsorcery:itemconstellationpaper>.withTag({astralsorcery: {constellationName: "astralsorcery.constellation.bootes"}}), 500, 300, [
<minecraft:rabbit_foot>, salisMundis, <minecraft:rabbit_foot>,
aquamarineGem, parchment, aquamarineGem,
<minecraft:rabbit_foot>, scribingTools, <minecraft:rabbit_foot>,
illuminationPowder,illuminationPowder,illuminationPowder,illuminationPowder]);
#Pelotrio
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/constellationpaper/pelotrio");
mods.astralsorcery.Altar.addAttunementAltarRecipe("interactions:pelotrio", <astralsorcery:itemconstellationpaper>.withTag({astralsorcery: {constellationName: "astralsorcery.constellation.pelotrio"}}), 500, 300, [
<astralsorcery:itemusabledust:1>, salisMundis, <astralsorcery:itemusabledust:1>,
aquamarineGem, parchment, aquamarineGem,
<astralsorcery:itemusabledust:1>, scribingTools, <astralsorcery:itemusabledust:1>,
illuminationPowder,illuminationPowder,illuminationPowder,illuminationPowder]);
#Fornax
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/constellationpaper/fornax");
mods.astralsorcery.Altar.addAttunementAltarRecipe("interactions:fornax", <astralsorcery:itemconstellationpaper>.withTag({astralsorcery: {constellationName: "astralsorcery.constellation.fornax"}}), 500, 300, [
<bloodmagic:component:1>, salisMundis, <bloodmagic:component:1>,
aquamarineGem, parchment, aquamarineGem,
<bloodmagic:component:1>, scribingTools, <bloodmagic:component:1>,
illuminationPowder,illuminationPowder,illuminationPowder,illuminationPowder]);
#mineralis
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/constellationpaper/mineralis");
mods.astralsorcery.Altar.addConstellationAltarRecipe("interactions:mineralis", <astralsorcery:itemconstellationpaper>.withTag({astralsorcery: {constellationName: "astralsorcery.constellation.mineralis"}}), 2000, 400, [
<ore:blockSkystone>, salisMundis, <ore:blockSkystone>,
aquamarineGem, parchment, aquamarineGem,
<ore:blockSkystone>, scribingTools, <ore:blockSkystone>,
illuminationPowder,illuminationPowder,illuminationPowder,illuminationPowder,
<ore:dustAstralStarmetal>,<ore:dustAstralStarmetal>,<ore:dustAstralStarmetal>,<ore:dustAstralStarmetal>, null, null, null, null]);
#horologium
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/constellationpaper/horologium");
mods.astralsorcery.Altar.addConstellationAltarRecipe("interactions:aevitas", <astralsorcery:itemconstellationpaper>.withTag({astralsorcery: {constellationName: "astralsorcery.constellation.aevitas"}}), 2000, 400, [
<bloodmagic:component:5>, salisMundis, <bloodmagic:component:5>,
aquamarineGem, parchment, aquamarineGem,
<bloodmagic:component:5>, scribingTools, <bloodmagic:component:5>,
illuminationPowder,illuminationPowder,illuminationPowder,illuminationPowder,
<ore:dustAstralStarmetal>,<ore:dustAstralStarmetal>,<ore:dustAstralStarmetal>,<ore:dustAstralStarmetal>, null, null, null, null]);
#Aevitas
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/constellationpaper/aevitas");
mods.astralsorcery.Altar.addConstellationAltarRecipe("interactions:horologium", <astralsorcery:itemconstellationpaper>.withTag({astralsorcery: {constellationName: "astralsorcery.constellation.horologium"}}), 2000, 400, [
<thaumcraft:mind>, salisMundis, <thaumcraft:mind>,
aquamarineGem, parchment, aquamarineGem,
<thaumcraft:mind>, scribingTools, <thaumcraft:mind>,
illuminationPowder,illuminationPowder,illuminationPowder,illuminationPowder,
<ore:dustAstralStarmetal>,<ore:dustAstralStarmetal>,<ore:dustAstralStarmetal>,<ore:dustAstralStarmetal>, null, null, null, null]);
#Ulteria
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/constellationpaper/ulteria");
mods.astralsorcery.Altar.addTraitAltarRecipe("interactions:ulteria",
<astralsorcery:itemconstellationpaper>.withTag({astralsorcery: {constellationName: "astralsorcery.constellation.ulteria"}}), 4500, 400, [
<bloodmagic:component:4>, salisMundis, <bloodmagic:component:4>,
aquamarineGem, parchment, aquamarineGem,
<bloodmagic:component:4>, scribingTools, <bloodmagic:component:4>,
illuminationPowder,illuminationPowder,illuminationPowder,illuminationPowder,
<ore:dustAstralStarmetal>, <ore:dustAstralStarmetal>, <ore:dustAstralStarmetal>, <ore:dustAstralStarmetal>,
<ore:dustStellarAlloy>,<ore:dustStellarAlloy>, null, null, null, null, null, null,
<ore:paper>]);
val permutatio = <thaumcraft:crystal_essence>.withTag({Aspects: [{amount: 1, key: "permutatio"}]});
#Gelu
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/constellationpaper/gelu");
mods.astralsorcery.Altar.addTraitAltarRecipe("interactions:gelu",
<astralsorcery:itemconstellationpaper>.withTag({astralsorcery: {constellationName: "astralsorcery.constellation.gelu"}}), 4500, 400, [
<ore:dustCryotheum>, salisMundis, <ore:dustCryotheum>,
aquamarineGem, parchment, aquamarineGem,
<ore:dustCryotheum>, scribingTools, <ore:dustCryotheum>,
illuminationPowder,illuminationPowder,illuminationPowder,illuminationPowder,
<ore:dustAstralStarmetal>, <ore:dustAstralStarmetal>, <ore:dustAstralStarmetal>, <ore:dustAstralStarmetal>,
<ore:dustStellarAlloy>,<ore:dustStellarAlloy>, null, null, null, null, null, null,
<ore:paper>]);
#Alcara
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/constellationpaper/alcara");
mods.astralsorcery.Altar.addTraitAltarRecipe("interactions:crashtest",
<astralsorcery:itemconstellationpaper>.withTag({astralsorcery: {constellationName: "astralsorcery.constellation.alcara"}}), 4500, 400, [
permutatio, salisMundis, permutatio,
aquamarineGem, parchment, aquamarineGem,
permutatio, scribingTools, permutatio,
illuminationPowder, illuminationPowder, illuminationPowder, illuminationPowder,
<ore:dustAstralStarmetal>, <ore:dustAstralStarmetal>, <ore:dustAstralStarmetal>, <ore:dustAstralStarmetal>,
<ore:dustStellarAlloy>,<ore:dustStellarAlloy>, null, null, null, null, null, null,
<ore:paper>]);
#Vorux
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/constellationpaper/vorux");
mods.astralsorcery.Altar.addTraitAltarRecipe("interactions:vorux", <astralsorcery:itemconstellationpaper>.withTag({astralsorcery: {constellationName: "astralsorcery.constellation.vorux"}}), 4500, 400, [
<botania:tinyplanet>, salisMundis, <botania:tinyplanet>,
aquamarineGem, parchment, aquamarineGem,
<botania:tinyplanet>, scribingTools, <botania:tinyplanet>,
illuminationPowder,illuminationPowder,illuminationPowder,illuminationPowder,
<ore:dustAstralStarmetal>, <ore:dustAstralStarmetal>, <ore:dustAstralStarmetal>, <ore:dustAstralStarmetal>,
<ore:dustStellarAlloy>,<ore:dustStellarAlloy>, null, null, null, null, null, null,
<ore:paper>]);
#perk crystal tooltips
<astralsorcery:itemperkgem>.addTooltip(format.darkRed("将萤石和水晶石投入星能液中来制作。"));
<astralsorcery:itemperkgem:1>.addTooltip(format.darkRed("将萤石和水晶石投入星能液中来制作。"));
<astralsorcery:itemperkgem:2>.addTooltip(format.darkRed("将萤石和水晶石投入星能液中来制作。"));
#custom collector crystal for Astral sorcery
val customCrystal = <astralsorcery:blockcollectorcrystal>.withTag({astralsorcery: {constellationName: "astralsorcery.constellation.aevitas", crystalProperties: {collectiveCapability: 80, size: 350, fract: 0, purity: 80, sizeOverride: -1}, collectorType: 0}});
mods.jei.JEI.addItem(customCrystal);
customCrystal.addTooltip(format.darkRed("一个粗制的人造天体水晶"));
mods.thaumcraft.Infusion.registerRecipe("asCrystal", "INFUSION", customCrystal, 5,
[<aspect:lux> * 64, <aspect:potentia> * 32, <aspect:sensus> * 16],
<astralsorcery:itemrockcrystalsimple>,
[illuminationPowder, illuminationPowder, <projecte:item.pe_covalence_dust:1>,
<projecte:item.pe_covalence_dust:1>, aquamarineGem, aquamarineGem,
<forge:bucketfilled>.withTag({FluidName: "astralsorcery.liquidstarlight", Amount: 1000}),
<forge:bucketfilled>.withTag({FluidName: "astralsorcery.liquidstarlight", Amount: 1000})]);
#Altars
#Starlight Crafting Altar
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/upgrade_tier2");
mods.astralsorcery.Altar.addDiscoveryAltarRecipe("astralsorcery:shaped/internal/altar/upgrade_tier2", <astralsorcery:blockaltar:1>, 120, 600, [
<ore:plateThaumium>, rockCrystal, <ore:plateThaumium>,
<astralsorcery:blockmarble:4>, starlightFluidStack, <astralsorcery:blockmarble:4>,
<astralsorcery:blockmarble:2>, <ore:plateThaumium>, <astralsorcery:blockmarble:2>]);
#Celestial Altar
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/upgrade_tier3");
mods.astralsorcery.Altar.addAttunementAltarRecipe("astralsorcery:shaped/internal/altar/upgrade_tier3", <astralsorcery:blockaltar:2>, 500, 600, [
aquamarineGem, null, aquamarineGem,
aquamarineGem, rockCrystal, aquamarineGem,
<astralsorcery:blockmarble:4>, <ore:plateSterlingSilver>, <astralsorcery:blockmarble:4>,
<ore:plateSterlingSilver>,<ore:plateSterlingSilver>,<astralsorcery:blockmarble:4>,<astralsorcery:blockmarble:4>]);
#starmetal tooltip
<astralsorcery:blockcustomore:1>.addTooltip(format.darkRed("可用作坠星标位的催化剂。"));
#Iredescent Altar
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/upgrade_tier4");
mods.astralsorcery.Altar.addConstellationAltarRecipe("astralsorcery:shaped/internal/altar/upgrade_tier4", <astralsorcery:blockaltar:3>, 1500, 600, [
runedMarble, salisMundis, runedMarble,
<ore:plateStellarAlloy>, celestialCrystal, <ore:plateStellarAlloy>,
runedMarble, <ore:lensNetherStar>, runedMarble,
runedMarble,runedMarble,runedMarble,runedMarble,
<appliedenergistics2:sky_stone_brick>,<appliedenergistics2:sky_stone_brick>,resonatingGem,resonatingGem,
resonatingGem,resonatingGem, <appliedenergistics2:sky_stone_brick>, <appliedenergistics2:sky_stone_brick>]);
#formation wand
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/tool_architect");
mods.bloodmagic.AlchemyArray.addRecipe(<astralsorcery:itemarchitectwand>, <cyclicmagic:cyclic_wand_build>, <minecraft:obsidian>,"bloodmagic:textures/models/AlchemyArrays/shardoflaputa.png");
#change harvest level of rock crystal ore
var crystalOre = <astralsorcery:blockcustomore> as IBlock;
crystalOre.definition.setHarvestLevel("pickaxe", 2);
#Impulsion wand
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/tool_grapple");
mods.astralsorcery.Altar.addAttunementAltarRecipe("astralsorcery:shaped/internal/altar/tool_grapple", <astralsorcery:itemgrapplewand>, 500, 600, [
null, <projecte:item.pe_covalence_dust:1>, <ore:manaPearl>,
<ore:manaPearl>, <ore:stickNetherQuartz>, <projecte:item.pe_covalence_dust:1>,
<ore:stickNetherQuartz>, null, <tconstruct:edible:2>,
null,null,<ore:stickNetherQuartz>,null]);
#Conversion wand
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/tool_exchange");
mods.astralsorcery.Altar.addAttunementAltarRecipe("astralsorcery:shaped/internal/altar/tool_exchange", <astralsorcery:itemexchangewand>, 500, 600, [
null, null, <ore:gemDiamond>,
<ore:gemDiamond>, <ore:stickAluminium>, <projecte:item.pe_covalence_dust:1>,
<ore:stickAluminium>, null, <thaumcraft:morphic_resonator>,
null,null,<ore:stickAluminium>,null]);
#Ritual anchor
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/rituallink");
mods.thaumcraft.ArcaneWorkbench.registerShapedRecipe("Ritual Link", "", 25, [<aspect:aer> * 3, <aspect:ignis> *3, <aspect:ordo> *3, <aspect:perditio> *3, <aspect:terra> *3], <astralsorcery:blockrituallink>*2,
[[runedMarble, <ore:eyeofredstone>, runedMarble],
[craftingLens, <ore:stickSterlingSilver>, craftingLens],
[runedMarble, <ore:plateGold>, runedMarble]]
);
#Celestial Gateway
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/gateway");
mods.astralsorcery.Altar.addAttunementAltarRecipe("astralsorcery:shaped/internal/altar/gateway", <astralsorcery:blockcelestialgateway>, 500, 600, [
illuminationPowder, <lteleporters:endercrystal>, illuminationPowder,
craftingLens, rockCrystal, craftingLens,
runedMarble, <ore:manaPearl>, runedMarble,
<projecte:item.pe_covalence_dust:1>,<projecte:item.pe_covalence_dust:1>,<projecte:item.pe_covalence_dust:1>,<projecte:item.pe_covalence_dust:1>]);
val domicResonator = <astralsorcery:itemskyresonator>.withTag({astralsorcery: {enhanced: 1 as byte, selected_upgrade: 2, upgrades: [0, 2]}});
#Domic resonator
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/resonator/structure");
mods.astralsorcery.Altar.addAttunementAltarRecipe("astralsorcery:shaped/internal/altar/resonator/structure", domicResonator, 500, 600, [
illuminationPowder, null, illuminationPowder,
craftingLens, <astralsorcery:itemskyresonator>, craftingLens,
<ore:dustAluminium>, null, <ore:dustAluminium>,
illuminationPowder,illuminationPowder,<ore:dustAluminium>,<ore:dustAluminium>]);
#manual sooty marble
mods.bloodmagic.AlchemyArray.addRecipe(sootyMarble, <astralsorcery:blockmarble>, <primal_tech:charcoal_block>, "bloodmagic:textures/models/AlchemyArrays/shardoflaputa.png");
#Sooty Marble
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/marble_black_raw");
alloyer.recipeBuilder()
.inputs(<ore:coal>, <astralsorcery:blockmarble>)
.outputs(sootyMarble * 1)
.duration(50)
.EUt(4)
.buildAndRegister();
#Sooty Marble w/charcoal
alloyer.recipeBuilder()
.inputs(<ore:charcoal>, <astralsorcery:blockmarble>)
.outputs(sootyMarble * 1)
.duration(75)
.EUt(8)
.buildAndRegister();
#Vibrant infused via starlight
autoclave.recipeBuilder()
.inputs(<astralsorcery:blockinfusedwood> * 1)
.fluidInputs([<liquid:astralsorcery.liquidstarlight> * 1000])
.outputs(<astralsorcery:blockinfusedwood:6> * 1)
.duration(220)
.EUt(48)
.buildAndRegister();
#Resonating Wand
#hide shale (which is unobtainable)
mods.jei.JEI.removeAndHide(<astralsorcery:blockcustomsandore>);
RecipeBuilder.get("basic")
.setShaped([
[null, <ore:plateBrass>,<bloodmagic:monster_soul>],
[null, <ore:stoneMarble>, <ore:plateBrass>],
[<ore:stoneMarble>, null, null]])
.setFluid(<liquid:mana_fluid> * 500)
.addTool(<ore:toolSaw>, 10)
.addOutput(<astralsorcery:itemwand>)
.create();
#Luminous Crafting table
RecipeBuilder.get("basic")
.setShaped([
[<ore:stoneMarble>, sootyMarble, <ore:stoneMarble>],
[<ore:stoneMarble>, <minecraft:crafting_table>, <ore:stoneMarble>],
[<ore:stoneMarble>, null, <ore:stoneMarble>]])
.setFluid(<liquid:mana_fluid> * 2000)
.addTool(<ore:toolSaw>, 40)
.addOutput(<astralsorcery:blockaltar>)
.create();
#Luminous Crafting Table - redundant recipe so that teammates can also unlock the progression
recipes.addShapeless(<astralsorcery:blockaltar>, [<astralsorcery:blockaltar>]);
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/tool_basicwand");
mods.astralsorcery.Altar.addDiscoveryAltarRecipe("astralsorcery:shaped/internal/altar/tool_basicwand", <astralsorcery:itemwand>, 120, 200, [
null, <ore:plateBrass>, <bloodmagic:monster_soul>,
null, <ore:stoneMarble>, <ore:plateBrass>,
<ore:stoneMarble>, null, null]);
#illumination Powder
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/illuminationpowder");
mods.astralsorcery.Altar.addDiscoveryAltarRecipe("astralsorcery:shaped/internal/altar/illuminationpowder", illuminationPowder*8, 120, 200, [
<projecte:item.pe_covalence_dust:1>, <ore:dustGlass>, <projecte:item.pe_covalence_dust:1>,
<ore:dustGlass>, salisMundis, <ore:dustGlass>,
<projecte:item.pe_covalence_dust:1>, <ore:dustGlass>, <projecte:item.pe_covalence_dust:1>]);
#Cave illuminator
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/illuminator");
mods.thaumcraft.ArcaneWorkbench.registerShapedRecipe("Cave Illuminator", "", 25, [<aspect:aer> * 15, <aspect:ignis> *15, <aspect:ordo> *15], <astralsorcery:blockworldilluminator>,
[[<ore:plateBrass>, illuminationPowder, <ore:plateBrass>],
[craftingLens, aquamarineGem, craftingLens],
[<ore:plateBrass>, illuminationPowder, <ore:plateBrass>]]
);
#Lightwell
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/lightwell");
mods.astralsorcery.Altar.addDiscoveryAltarRecipe("astralsorcery:shaped/internal/altar/lightwell", <astralsorcery:blockwell>, 120, 200, [
runedMarble, <advancedrocketry:lens>, runedMarble,
<astralsorcery:blockmarble:4>, rockCrystal, <astralsorcery:blockmarble:4>,
<ore:plateIron>, runedMarble, <ore:plateIron>
]);
#Tree Beacon
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/treebeacon");
mods.astralsorcery.Altar.addDiscoveryAltarRecipe("astralsorcery:shaped/internal/altar/treebeacon", <astralsorcery:blocktreebeacon>, 120, 200, [
<integrateddynamics:menril_leaves>, craftingLens, <integrateddynamics:menril_leaves>,
<integrateddynamics:menril_leaves>, <thaumcraft:sapling_greatwood>, <integrateddynamics:menril_leaves>,
<integrateddynamics:menril_leaves>, <forge:bucketfilled>.withTag({FluidName: "astralsorcery.liquidstarlight", Amount: 1000}).reuse(), <integrateddynamics:menril_leaves>
]);
#neromatic Prime
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/bore_head_liquid");
mods.thaumcraft.Infusion.registerRecipe("neromaticprime", "INFUSION", <astralsorcery:blockborehead>, 6,
[<aspect:alienis> * 16, <aspect:potentia> * 24, <aspect:instrumentum> * 64, <aspect:vacuos> * 24, <aspect:praecantatio> * 12],
<astralsorcery:blockcollectorcrystal>,
[<bloodmagic:component:8>, <ore:gearRoseGold>, <appliedenergistics2:quartz_vibrant_glass>,
<appliedenergistics2:quartz_vibrant_glass>, <mekanism:reinforcedalloy>, <astralsorcery:blockmarble:6>,
<astralsorcery:blockmarble:6>,<astralsorcery:blockmarble:6>,<astralsorcery:blockmarble:6>,
<astralsorcery:blockmarble:6>,<bloodmagic:component:17>,<astralsorcery:itemcraftingcomponent>]);
#evershifting fountain
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/bore_core");
mods.thaumcraft.Infusion.registerRecipe("evershiftingfountain", "INFUSION", <astralsorcery:blockbore>, 6,
[<aspect:alienis> * 8, <aspect:potentia> * 32, <aspect:tenebrae> * 64, <aspect:vacuos> * 24, <aspect:praecantatio> * 12],
<astralsorcery:blockwell>,
[<astralsorcery:itemcraftingcomponent>, <astralsorcery:itemcraftingcomponent>, <projecte:item.pe_covalence_dust:2>,
<projecte:item.pe_covalence_dust:2>, <astralsorcery:blockmarble:6>, <astralsorcery:blockmarble:6>,
<astralsorcery:blockmarble:6>, <astralsorcery:blockmarble:6>, <ore:plateRoseGold>,
<ore:plateRoseGold>, <ore:plateRoseGold>, <ore:plateRoseGold>,
<astralsorcery:blockinfusedwood:5>, <astralsorcery:blockinfusedwood:5>, <astralsorcery:blockinfusedwood:5>, <astralsorcery:blockinfusedwood:5>]);
#containment chalice
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/chalice");
mods.thaumcraft.Infusion.registerRecipe("containmentchalice", "INFUSION", <astralsorcery:blockchalice>, 4,
[<aspect:lux> * 16, <aspect:potentia> * 12, <aspect:sensus> * 8, <aspect:vacuos> * 12], <botania:pool>,
[<botania:manaresource:1>, <astralsorcery:itemcraftingcomponent>, <astralsorcery:itemcraftingcomponent>,
<thaumcraft:mechanism_complex>, <thaumcraft:mechanism_complex>, <ore:plateRoseGold>, <ore:plateRoseGold>]);
#Written Expertise
mods.astralsorcery.Altar.removeAltarRecipe("astralsorcery:shaped/internal/altar/knowledgeshare");
mods.astralsorcery.Altar.addAttunementAltarRecipe("interactions:shaped/internal/altar/knowledgeshare",
<astralsorcery:itemknowledgeshare>.withTag({astralsorcery: {}}), 500, 300, [
null, <ore:feather>, null,
<ore:powderMana>, parchment, <ore:powderMana>,
null, <ore:dyeBlack>, null,
<astralsorcery:itemusabledust>, <astralsorcery:itemusabledust>, <astralsorcery:itemusabledust>, <astralsorcery:itemusabledust>]);
print("----------------Astral Sorcery End-------------------");
| 0 | 0.868858 | 1 | 0.868858 | game-dev | MEDIA | 0.975562 | game-dev | 0.557874 | 1 | 0.557874 |
Squashwell/bepuik | 3,163 | extern/sdlew/include/SDL2/SDL_mouse.h |
#ifndef _SDL_mouse_h
#define _SDL_mouse_h
#include "SDL_stdinc.h"
#include "SDL_error.h"
#include "SDL_video.h"
#include "begin_code.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct SDL_Cursor SDL_Cursor;
typedef enum
{
SDL_SYSTEM_CURSOR_ARROW,
SDL_SYSTEM_CURSOR_IBEAM,
SDL_SYSTEM_CURSOR_WAIT,
SDL_SYSTEM_CURSOR_CROSSHAIR,
SDL_SYSTEM_CURSOR_WAITARROW,
SDL_SYSTEM_CURSOR_SIZENWSE,
SDL_SYSTEM_CURSOR_SIZENESW,
SDL_SYSTEM_CURSOR_SIZEWE,
SDL_SYSTEM_CURSOR_SIZENS,
SDL_SYSTEM_CURSOR_SIZEALL,
SDL_SYSTEM_CURSOR_NO,
SDL_SYSTEM_CURSOR_HAND,
SDL_NUM_SYSTEM_CURSORS
} SDL_SystemCursor;
typedef SDL_Window * SDLCALL tSDL_GetMouseFocus(void);
typedef Uint32 SDLCALL tSDL_GetMouseState(int *x, int *y);
typedef Uint32 SDLCALL tSDL_GetRelativeMouseState(int *x, int *y);
typedef void SDLCALL tSDL_WarpMouseInWindow(SDL_Window * window,
int x, int y);
typedef int SDLCALL tSDL_SetRelativeMouseMode(SDL_bool enabled);
typedef SDL_bool SDLCALL tSDL_GetRelativeMouseMode(void);
typedef SDL_Cursor * SDLCALL tSDL_CreateCursor(const Uint8 * data,
const Uint8 * mask,
int w, int h, int hot_x,
int hot_y);
typedef SDL_Cursor * SDLCALL tSDL_CreateColorCursor(SDL_Surface *surface,
int hot_x,
int hot_y);
typedef SDL_Cursor * SDLCALL tSDL_CreateSystemCursor(SDL_SystemCursor id);
typedef void SDLCALL tSDL_SetCursor(SDL_Cursor * cursor);
typedef SDL_Cursor * SDLCALL tSDL_GetCursor(void);
typedef SDL_Cursor * SDLCALL tSDL_GetDefaultCursor(void);
typedef void SDLCALL tSDL_FreeCursor(SDL_Cursor * cursor);
typedef int SDLCALL tSDL_ShowCursor(int toggle);
#define SDL_BUTTON(X) (1 << ((X)-1))
#define SDL_BUTTON_LEFT 1
#define SDL_BUTTON_MIDDLE 2
#define SDL_BUTTON_RIGHT 3
#define SDL_BUTTON_X1 4
#define SDL_BUTTON_X2 5
#define SDL_BUTTON_LMASK SDL_BUTTON(SDL_BUTTON_LEFT)
#define SDL_BUTTON_MMASK SDL_BUTTON(SDL_BUTTON_MIDDLE)
#define SDL_BUTTON_RMASK SDL_BUTTON(SDL_BUTTON_RIGHT)
#define SDL_BUTTON_X1MASK SDL_BUTTON(SDL_BUTTON_X1)
#define SDL_BUTTON_X2MASK SDL_BUTTON(SDL_BUTTON_X2)
extern tSDL_GetMouseFocus *SDL_GetMouseFocus;
extern tSDL_GetMouseState *SDL_GetMouseState;
extern tSDL_GetRelativeMouseState *SDL_GetRelativeMouseState;
extern tSDL_WarpMouseInWindow *SDL_WarpMouseInWindow;
extern tSDL_SetRelativeMouseMode *SDL_SetRelativeMouseMode;
extern tSDL_GetRelativeMouseMode *SDL_GetRelativeMouseMode;
extern tSDL_CreateCursor *SDL_CreateCursor;
extern tSDL_CreateColorCursor *SDL_CreateColorCursor;
extern tSDL_CreateSystemCursor *SDL_CreateSystemCursor;
extern tSDL_SetCursor *SDL_SetCursor;
extern tSDL_GetCursor *SDL_GetCursor;
extern tSDL_GetDefaultCursor *SDL_GetDefaultCursor;
extern tSDL_FreeCursor *SDL_FreeCursor;
extern tSDL_ShowCursor *SDL_ShowCursor;
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif
| 0 | 0.814305 | 1 | 0.814305 | game-dev | MEDIA | 0.668463 | game-dev | 0.516107 | 1 | 0.516107 |
SlimeKnights/Mantle | 2,345 | src/main/java/slimeknights/mantle/command/TagPreferenceCommand.java | package slimeknights.mantle.command;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.core.Registry;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
import slimeknights.mantle.command.argument.TagSourceArgument;
import slimeknights.mantle.recipe.helper.TagPreference;
/** Command to test tag preference behavior */
public class TagPreferenceCommand {
private static final String EMPTY_TAG = "command.mantle.tag_preference.empty_tag";
private static final String PREFERENCE = "command.mantle.tag_preference.preference";
/**
* Registers this sub command with the root command
* @param subCommand Command builder
*/
public static void register(LiteralArgumentBuilder<CommandSourceStack> subCommand) {
subCommand.requires(sender -> sender.hasPermission(MantleCommand.PERMISSION_EDIT_SPAWN))
.then(RegistryArgument.argument().then(TagSourceArgument.tagArgument("name").executes(TagPreferenceCommand::run)));
}
/**
* Runs the command
*
* @param context Tag context
* @return Integer return
* @throws CommandSyntaxException If invalid values are passed
*/
private static int run(CommandContext<CommandSourceStack> context) throws CommandSyntaxException {
return runGeneric(context, RegistryArgument.get(context));
}
/**
* Runs the command, fixing issues with generics
*
* @param context Tag context
* @return Integer return
*/
private static <T> int runGeneric(CommandContext<CommandSourceStack> context, Registry<T> registry) {
ResourceLocation name = context.getArgument("name", ResourceLocation.class);
TagKey<T> tag = TagKey.create(registry.key(), name);
T preference = TagPreference.getPreference(tag).orElse(null);
if (preference == null) {
context.getSource().sendSuccess(() -> Component.translatable(EMPTY_TAG, registry.key().location(), name), true);
return 0;
} else {
context.getSource().sendSuccess(() -> Component.translatable(PREFERENCE, registry.key().location(), name, registry.getKey(preference)), true);
return 1;
}
}
}
| 0 | 0.883654 | 1 | 0.883654 | game-dev | MEDIA | 0.924837 | game-dev | 0.897215 | 1 | 0.897215 |
mcclure/bitbucket-backup | 2,040 | repos/template/contents/Modules/Dependencies/include/Box2D/Dynamics/Contacts/b2ContactSolver.h | /*
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef B2_CONTACT_SOLVER_H
#define B2_CONTACT_SOLVER_H
#include <Box2D/Common/b2Math.h>
#include <Box2D/Collision/b2Collision.h>
#include <Box2D/Dynamics/b2Island.h>
class b2Contact;
class b2Body;
class b2StackAllocator;
struct b2ContactConstraintPoint
{
b2Vec2 localPoint;
b2Vec2 rA;
b2Vec2 rB;
float32 normalImpulse;
float32 tangentImpulse;
float32 normalMass;
float32 tangentMass;
float32 velocityBias;
};
struct b2ContactConstraint
{
b2ContactConstraintPoint points[b2_maxManifoldPoints];
b2Vec2 localNormal;
b2Vec2 localPoint;
b2Vec2 normal;
b2Mat22 normalMass;
b2Mat22 K;
b2Body* bodyA;
b2Body* bodyB;
b2Manifold::Type type;
float32 radius;
float32 friction;
int32 pointCount;
b2Manifold* manifold;
};
class b2ContactSolver
{
public:
b2ContactSolver(b2Contact** contacts, int32 contactCount,
b2StackAllocator* allocator, float32 impulseRatio);
~b2ContactSolver();
void WarmStart();
void SolveVelocityConstraints();
void StoreImpulses();
bool SolvePositionConstraints(float32 baumgarte);
b2StackAllocator* m_allocator;
b2ContactConstraint* m_constraints;
int m_constraintCount;
};
#endif
| 0 | 0.695653 | 1 | 0.695653 | game-dev | MEDIA | 0.977931 | game-dev | 0.877596 | 1 | 0.877596 |
forest0xia/dota2bot-OpenHyperAI | 29,049 | bots/BotLib/hero_windrunner.lua | local X = {}
local bDebugMode = ( 1 == 10 )
local bot = GetBot()
local J = require( GetScriptDirectory()..'/FunLib/jmz_func' )
local Minion = dofile( GetScriptDirectory()..'/FunLib/aba_minion' )
local sTalentList = J.Skill.GetTalentList( bot )
local sAbilityList = J.Skill.GetAbilityList( bot )
local sRole = J.Item.GetRoleItemsBuyList( bot )
local tTalentTreeList = {
{--pos1
['t25'] = {10, 0},
['t20'] = {10, 0},
['t15'] = {0, 10},
['t10'] = {10, 0},
},
{--pos2
['t25'] = {10, 0},
['t20'] = {10, 0},
['t15'] = {0, 10},
['t10'] = {10, 0},
},
{--pos3
['t25'] = {10, 0},
['t20'] = {10, 0},
['t15'] = {0, 10},
['t10'] = {10, 0},
},
}
local tAllAbilityBuildList = {
{2,3,2,1,2,6,2,3,3,3,1,6,1,1,6},--pos1
{2,3,2,1,2,6,2,3,3,3,1,6,1,1,6},--pos2
{2,3,2,1,2,6,2,3,3,3,6,1,1,1,6},--pos3
}
local nAbilityBuildList
local nTalentBuildList
if sRole == "pos_1"
then
nAbilityBuildList = tAllAbilityBuildList[1]
nTalentBuildList = J.Skill.GetTalentBuild(tTalentTreeList[1])
elseif sRole == "pos_2"
then
nAbilityBuildList = tAllAbilityBuildList[2]
nTalentBuildList = J.Skill.GetTalentBuild(tTalentTreeList[2])
else
nAbilityBuildList = tAllAbilityBuildList[3]
nTalentBuildList = J.Skill.GetTalentBuild(tTalentTreeList[3])
end
local sUtility = {"item_heavens_halberd", "item_nullifier"}
local nUtility = sUtility[RandomInt(1, #sUtility)]
local sRoleItemsBuyList = {}
sRoleItemsBuyList['pos_1'] = {
"item_tango",
"item_double_branches",
"item_faerie_fire",
"item_double_circlet",
"item_magic_wand",
"item_double_bracer",
"item_power_treads",
"item_maelstrom",
"item_dragon_lance",
"item_black_king_bar",--
"item_mjollnir",--
"item_greater_crit",--
"item_ultimate_scepter",
"item_force_staff",
"item_hurricane_pike",--
"item_travel_boots",
"item_monkey_king_bar",--
"item_ultimate_scepter_2",
"item_travel_boots_2",--
"item_aghanims_shard",
"item_moon_shard",
}
sRoleItemsBuyList['pos_2'] = {
"item_tango",
"item_double_branches",
"item_faerie_fire",
"item_double_circlet",
"item_bottle",
"item_magic_wand",
"item_double_bracer",
"item_power_treads",
"item_maelstrom",
"item_dragon_lance",
"item_black_king_bar",--
"item_mjollnir",--
"item_greater_crit",--
"item_ultimate_scepter",
"item_sheepstick",--
"item_travel_boots",
"item_monkey_king_bar",--
"item_ultimate_scepter_2",
"item_travel_boots_2",--
"item_aghanims_shard",
"item_moon_shard",
}
sRoleItemsBuyList['pos_3'] = {
"item_tango",
"item_double_branches",
"item_faerie_fire",
"item_double_circlet",
"item_magic_wand",
"item_double_bracer",
"item_power_treads",
"item_maelstrom",
"item_black_king_bar",--
"item_ultimate_scepter",
nUtility,--
"item_mjollnir",--
"item_sheepstick",--
"item_travel_boots",
"item_ultimate_scepter_2",
"item_monkey_king_bar",--
"item_travel_boots_2",--
"item_aghanims_shard",
"item_moon_shard",
}
sRoleItemsBuyList['pos_4'] = sRoleItemsBuyList['pos_3']
sRoleItemsBuyList['pos_5'] = sRoleItemsBuyList['pos_3']
X['sBuyList'] = sRoleItemsBuyList[sRole]
X['sSellList'] = {
"item_black_king_bar",
"item_quelling_blade",
}
if J.Role.IsPvNMode() or J.Role.IsAllShadow() then X['sBuyList'], X['sSellList'] = { 'PvN_antimage' }, {} end
nAbilityBuildList, nTalentBuildList, X['sBuyList'], X['sSellList'] = J.SetUserHeroInit( nAbilityBuildList, nTalentBuildList, X['sBuyList'], X['sSellList'] )
X['sSkillList'] = J.Skill.GetSkillList( sAbilityList, nAbilityBuildList, sTalentList, nTalentBuildList )
X['bDeafaultAbility'] = false
X['bDeafaultItem'] = false
function X.MinionThink(hMinionUnit)
Minion.MinionThink(hMinionUnit)
end
local ShackleShot = bot:GetAbilityByName('windrunner_shackleshot')
local Powershot = bot:GetAbilityByName('windrunner_powershot')
local Windrun = bot:GetAbilityByName('windrunner_windrun')
local GaleForce = bot:GetAbilityByName('windrunner_gale_force')
local FocusFire = bot:GetAbilityByName('windrunner_focusfire')
local ShackleShotDesire, ShackleShotTarget
local PowershotDesire, PowershotLocation
local WindrunDesire
local GaleForceDesire, GaleForceLocation
local FocusFireDesire, FocusFireTarget
local botTarget
function X.SkillsComplement()
if J.CanNotUseAbility(bot) then return end
botTarget = J.GetProperTarget(bot)
ShackleShotDesire, ShackleShotTarget = X.ConsiderShackleShot()
if ShackleShotDesire > 0
then
J.SetQueuePtToINT(bot, false)
bot:ActionQueue_UseAbilityOnEntity(ShackleShot, ShackleShotTarget)
return
end
FocusFireDesire, FocusFireTarget = X.ConsiderFocusFire()
if FocusFireDesire > 0
then
bot:Action_UseAbilityOnEntity(FocusFire, FocusFireTarget)
return
end
PowershotDesire, PowershotLocation = X.ConsiderPowershot()
if PowershotDesire > 0
then
J.SetQueuePtToINT(bot, false)
bot:ActionQueue_UseAbilityOnLocation(Powershot, PowershotLocation)
return
end
WindrunDesire = X.ConsiderWindrun()
if WindrunDesire > 0
then
bot:Action_UseAbility(Windrun)
return
end
GaleForceDesire, GaleForceLocation = X.ConsiderGaleForce()
if GaleForceDesire > 0
then
bot:Action_UseAbilityOnLocation(GaleForce, GaleForceLocation)
return
end
end
function X.ConsiderShackleShot()
if not J.CanCastAbility(ShackleShot)
then
return BOT_ACTION_DESIRE_NONE, nil
end
local nCastRange = J.GetProperCastRange(false, bot, ShackleShot:GetCastRange())
local nRadius = ShackleShot:GetSpecialValueInt('shackle_distance')
local nAngle = ShackleShot:GetSpecialValueInt('shackle_angle')
local nStunDuration = ShackleShot:GetSpecialValueFloat('stun_duration')
local tAllyHeroes = J.GetNearbyHeroes(bot,1600, false, BOT_MODE_NONE)
local tEnemyHeroes = J.GetNearbyHeroes(bot,1600, true, BOT_MODE_NONE)
for _, enemyHero in pairs(tEnemyHeroes)
do
if J.IsValidHero(enemyHero)
and J.IsInRange(bot, enemyHero, nCastRange)
and J.CanCastOnNonMagicImmune(enemyHero)
and J.CanCastOnTargetAdvanced(enemyHero)
and enemyHero:IsChanneling()
then
return BOT_ACTION_DESIRE_HIGH, enemyHero
end
end
if J.IsGoingOnSomeone(bot)
then
local target = nil
local targetAttackDamage = 0
for _, enemy in pairs(tEnemyHeroes) do
if J.IsValidTarget(enemy)
and J.CanCastOnNonMagicImmune(enemy)
and J.CanCastOnTargetAdvanced(enemy)
and J.IsInRange(bot, enemy, nCastRange)
and not J.IsDisabled(enemy)
and not enemy:HasModifier('modifier_enigma_black_hole_pull')
and not enemy:HasModifier('modifier_faceless_void_chronosphere_freeze')
and not enemy:HasModifier('modifier_necrolyte_reapers_scythe')
then
local enemyAttackDamge = enemy:GetAttackDamage() * enemy:GetAttackSpeed()
if enemyAttackDamge > targetAttackDamage then
target = enemy
targetAttackDamage = enemyAttackDamge
end
end
end
if target then
local tAllyHeroes_attacking = J.GetSpecialModeAllies(bot, 900, BOT_MODE_ATTACK)
if J.IsChasingTarget(bot, target) and #tAllyHeroes_attacking >= 2
or J.IsAttacking(bot) and bot:GetEstimatedDamageToTarget(true, target, nStunDuration, DAMAGE_TYPE_ALL) > target:GetHealth() then
local target__ = X.GetShackleTarget(bot, target, nRadius, nAngle)
if target__ then
return BOT_ACTION_DESIRE_HIGH, target__
end
end
end
end
if J.IsRetreating(bot)
and not J.IsRealInvisible(bot)
then
for _, enemyHero in pairs(tEnemyHeroes)
do
if J.IsValidHero(enemyHero)
and J.CanCastOnNonMagicImmune(enemyHero)
and J.CanCastOnTargetAdvanced(enemyHero)
and J.IsChasingTarget(enemyHero, bot)
and not J.IsDisabled(enemyHero)
and bot:WasRecentlyDamagedByHero(enemyHero, 3.0)
then
local target = X.GetShackleTarget(bot, enemyHero, nRadius, nAngle)
if target ~= nil
then
return BOT_ACTION_DESIRE_HIGH, target
end
end
end
end
--打断
for _, npcEnemy in pairs( tEnemyHeroes )
do
if J.IsValid( npcEnemy )
and (npcEnemy:IsChanneling() or npcEnemy:HasModifier( 'modifier_teleporting' ) )
and J.CanCastOnNonMagicImmune( npcEnemy )
and J.CanCastOnTargetAdvanced( npcEnemy )
then
return BOT_ACTION_DESIRE_HIGH, npcEnemy
end
end
for _, allyHero in pairs(tAllyHeroes)
do
if J.IsValidHero(allyHero)
and J.IsRetreating(allyHero)
and J.GetMP(bot) > 0.45
and allyHero:WasRecentlyDamagedByAnyHero(3.0)
and not J.IsRealInvisible(bot)
and not allyHero:IsIllusion()
then
local tAllyInRangeEnemy = allyHero:GetNearbyHeroes(1600, true, BOT_MODE_NONE)
for _, enemyHero in pairs(tAllyInRangeEnemy) do
if J.IsValidHero(enemyHero)
and J.CanCastOnNonMagicImmune(enemyHero)
and J.CanCastOnTargetAdvanced(enemyHero)
and J.IsInRange(bot, enemyHero, nCastRange)
and J.IsChasingTarget(enemyHero, allyHero)
and not J.IsDisabled(enemyHero)
and not enemyHero:HasModifier('modifier_enigma_black_hole_pull')
and not enemyHero:HasModifier('modifier_faceless_void_chronosphere_freeze')
and not enemyHero:HasModifier('modifier_necrolyte_reapers_scythe')
then
local target = X.GetShackleTarget(bot, enemyHero, nRadius, nAngle)
if target ~= nil
then
return BOT_ACTION_DESIRE_HIGH, target
end
end
end
end
end
return BOT_ACTION_DESIRE_NONE, nil
end
function X.ConsiderPowershot()
if not J.CanCastAbility(Powershot)
then
return BOT_ACTION_DESIRE_NONE, 0
end
local nCastRange = Powershot:GetCastRange()
local nCastPoint = Powershot:GetCastPoint()
local nRadius = Powershot:GetSpecialValueInt('arrow_width')
local nSpeed = Powershot:GetSpecialValueInt('arrow_speed')
local nDamage = Powershot:GetSpecialValueInt('powershot_damage')
local nAttackRange = bot:GetAttackRange()
local botMP = J.GetMP(bot)
local tAllyHeroes = J.GetNearbyHeroes(bot,1600, false, BOT_MODE_NONE)
local tEnemyHeroes = J.GetNearbyHeroes(bot,1600, true, BOT_MODE_NONE)
for _, enemyHero in pairs(tEnemyHeroes)
do
if J.IsValidHero(enemyHero)
and J.IsInRange(bot, enemyHero, nCastRange)
and J.CanCastOnNonMagicImmune(enemyHero)
and J.CanKillTarget(enemyHero, nDamage, DAMAGE_TYPE_MAGICAL)
and not J.IsInRange(bot, enemyHero, nAttackRange - 100)
and not enemyHero:HasModifier('modifier_abaddon_borrowed_time')
and not enemyHero:HasModifier('modifier_dazzle_shallow_grave')
and not enemyHero:HasModifier('modifier_necrolyte_reapers_scythe')
and not enemyHero:HasModifier('modifier_oracle_false_promise_timer')
and not enemyHero:HasModifier('modifier_templar_assassin_refraction_absorb')
then
local eta = (GetUnitToUnitDistance(bot, enemyHero) / nSpeed) + nCastPoint
return BOT_ACTION_DESIRE_HIGH, J.GetCorrectLoc(enemyHero, eta)
end
end
if J.IsGoingOnSomeone(bot)
then
if J.IsValidHero(botTarget)
and J.CanCastOnNonMagicImmune(botTarget)
and J.IsInRange(bot, botTarget, nCastRange)
and not J.IsInRange(bot, botTarget, nAttackRange)
and not botTarget:HasModifier('modifier_abaddon_borrowed_time')
and not botTarget:HasModifier('modifier_dazzle_shallow_grave')
and not botTarget:HasModifier('modifier_templar_assassin_refraction_absorb')
then
local eta = (GetUnitToUnitDistance(bot, botTarget) / nSpeed) + nCastPoint
if bot:GetLevel() < 6 then
if J.CanKillTarget(botTarget, nDamage + bot:GetAttackDamage() * 3, DAMAGE_TYPE_ALL) then
return BOT_ACTION_DESIRE_HIGH, J.GetCorrectLoc(botTarget, eta)
end
else
return BOT_ACTION_DESIRE_HIGH, J.GetCorrectLoc(botTarget, eta)
end
end
end
if J.IsPushing(bot) or J.IsDefending(bot)
then
local tEnemyLaneCreeps = bot:GetNearbyLaneCreeps(1600, true)
if J.IsValid(tEnemyLaneCreeps[1])
and J.CanBeAttacked(tEnemyLaneCreeps[1])
and not J.IsRunning(tEnemyLaneCreeps[1])
and botMP > 0.45 then
local nLocationAoE = bot:FindAoELocation(true, false, tEnemyLaneCreeps[1]:GetLocation(), 0, nRadius, 0, 0)
if nLocationAoE.count >= 4 then
return BOT_ACTION_DESIRE_HIGH, nLocationAoE.targetloc
end
end
local nLocationAoE = bot:FindAoELocation(true, true, bot:GetLocation(), nCastRange, nRadius, 0, 0)
if nLocationAoE.count >= 2
then
return BOT_ACTION_DESIRE_HIGH, nLocationAoE.targetloc
end
end
if J.IsFarming(bot)
then
if J.IsAttacking(bot)
then
local tCreeps = bot:GetNearbyCreeps(1600, true)
if J.IsValid(tCreeps[1])
and J.CanBeAttacked(tCreeps[1])
and not J.IsRunning(tCreeps[1])
and botMP > 0.33 then
local nLocationAoE = bot:FindAoELocation(true, false, tCreeps[1]:GetLocation(), 0, nRadius, 0, 0)
if nLocationAoE.count >= 3 or nLocationAoE.count >= 1 and tCreeps[1]:IsAncientCreep() then
return BOT_ACTION_DESIRE_HIGH, nLocationAoE.targetloc
end
end
end
end
if J.IsLaning(bot)
and (J.IsCore(bot) or (not J.IsCore(bot) and not J.IsThereNonSelfCoreNearby(1200)))
then
local canKill = 0
local creepList = {}
local nEnemyLaneCreeps = bot:GetNearbyLaneCreeps(1600, true)
for _, creep in pairs(nEnemyLaneCreeps)
do
if J.IsValid(creep)
and (J.IsKeyWordUnit('ranged', creep) or J.IsKeyWordUnit('siege', creep) or J.IsKeyWordUnit('flagbearer', creep))
and creep:GetHealth() > bot:GetAttackDamage()
and J.CanKillTarget(creep, nDamage, DAMAGE_TYPE_MAGICAL)
then
if J.GetMP(bot) > 0.3
and J.CanBeAttacked(creep)
and not J.IsRunning(creep)
then
if J.IsValidHero(tEnemyHeroes[1])
and not J.IsSuspiciousIllusion(tEnemyHeroes[1])
and not J.IsDisabled(tEnemyHeroes[1])
and not bot:WasRecentlyDamagedByTower(1)
and GetUnitToUnitDistance(creep, tEnemyHeroes[1]) < tEnemyHeroes[1]:GetAttackRange()
then
return BOT_ACTION_DESIRE_HIGH, creep:GetLocation()
end
end
end
if J.IsValid(creep)
and J.CanKillTarget(creep, nDamage, DAMAGE_TYPE_MAGICAL)
then
if #creepList > 0 then
if J.IsInRange(creep, creepList[1], nRadius) then
table.insert(creepList, creep)
end
else
table.insert(creepList, creep)
end
end
end
if #creepList >= 3
and J.GetMP(bot) > 0.25
and J.CanBeAttacked(creepList[1])
and not J.IsRunning(creepList[1])
then
return BOT_ACTION_DESIRE_HIGH, J.GetCenterOfUnits(creepList)
end
end
if J.IsDoingRoshan(bot)
then
if J.IsRoshan(botTarget)
and J.CanBeAttacked(botTarget)
and J.CanCastOnNonMagicImmune(botTarget)
and J.IsInRange(bot, botTarget, nCastRange)
and J.IsAttacking(bot)
then
return BOT_ACTION_DESIRE_HIGH, botTarget:GetLocation()
end
end
if J.IsDoingTormentor(bot)
then
if J.IsTormentor(botTarget)
and J.IsInRange(bot, botTarget, nCastRange)
and J.IsAttacking(bot)
then
return BOT_ACTION_DESIRE_HIGH, botTarget:GetLocation()
end
end
return BOT_ACTION_DESIRE_NONE, 0
end
function X.ConsiderWindrun()
if not J.CanCastAbility(Windrun)
or bot:HasModifier('modifier_windrunner_windrun')
then
return BOT_ACTION_DESIRE_NONE
end
local botManaAfter = J.GetManaAfter(Windrun:GetManaCost())
local tAllyHeroes = J.GetNearbyHeroes(bot,1600, false, BOT_MODE_NONE)
local tEnemyHeroes = J.GetNearbyHeroes(bot,1600, true, BOT_MODE_NONE)
if J.IsGoingOnSomeone(bot)
then
if J.IsValidTarget(botTarget)
and not J.IsSuspiciousIllusion(botTarget)
and not botTarget:HasModifier('modifier_enigma_black_hole_pull')
and not botTarget:HasModifier('modifier_faceless_void_chronosphere_freeze')
and not botTarget:HasModifier('modifier_necrolyte_reapers_scythe')
then
if (J.IsChasingTarget(bot, botTarget)
and not J.IsInRange(bot, botTarget, bot:GetAttackRange())
and (botTarget:GetCurrentMovementSpeed() > bot:GetCurrentMovementSpeed() + 10))
or (bot:WasRecentlyDamagedByAnyHero(1.5) and X.IsBeingAttackedByRealHero(bot))
then
return BOT_ACTION_DESIRE_HIGH
end
end
end
if J.IsRetreating(bot)
and not J.IsRealInvisible(bot)
then
if J.IsValidHero(tEnemyHeroes[1])
and J.CanBeAttacked(bot)
and J.IsChasingTarget(tEnemyHeroes[1], bot)
and not J.IsSuspiciousIllusion(tEnemyHeroes[1])
and not J.IsDisabled(tEnemyHeroes[1])
and (bot:WasRecentlyDamagedByAnyHero(2.0) and X.IsBeingAttackedByRealHero(bot))
then
return BOT_ACTION_DESIRE_HIGH
end
end
if J.IsLaning(bot)
then
if botManaAfter > 0.8
and not bot:HasModifier('modifier_fountain_aura_buff')
and J.IsInLaningPhase()
and #tEnemyHeroes == 0
then
local nLane = bot:GetAssignedLane()
local nLaneFrontLocation = GetLaneFrontLocation(GetTeam(), nLane, 0)
if GetUnitToLocationDistance(bot, nLaneFrontLocation) > 800 then
return BOT_ACTION_DESIRE_HIGH
end
end
end
if J.IsDoingRoshan(bot)
then
if J.IsRoshan(botTarget)
and J.IsInRange(bot, botTarget, bot:GetAttackRange())
and J.IsAttacking(bot)
then
if J.GetHP(bot) < 0.5
then
return BOT_ACTION_DESIRE_HIGH
end
end
end
if J.IsDoingTormentor(bot)
then
if J.IsTormentor(botTarget)
and J.IsInRange(bot, botTarget, bot:GetAttackRange())
and J.IsAttacking(bot)
then
if J.GetHP(bot) < 0.5
then
return BOT_ACTION_DESIRE_HIGH
end
end
end
return BOT_ACTION_DESIRE_NONE
end
function X.ConsiderFocusFire()
if not J.CanCastAbility(FocusFire)
then
return BOT_ACTION_DESIRE_NONE, nil
end
local nCastRange = J.GetProperCastRange(false, bot, FocusFire:GetCastRange())
local nDamageReduction = 1 + (FocusFire:GetSpecialValueInt('focusfire_damage_reduction') / 100)
local nDuration = FocusFire:GetDuration()
local nDamage = bot:GetAttackDamage()
local tAllyHeroes = J.GetNearbyHeroes(bot,1600, false, BOT_MODE_NONE)
local tEnemyHeroes = J.GetNearbyHeroes(bot,1600, true, BOT_MODE_NONE)
for _, enemyHero in pairs(tEnemyHeroes)
do
if J.IsValidHero(enemyHero)
and J.CanBeAttacked(enemyHero)
and not J.IsInEtherealForm(enemyHero)
and enemyHero:GetHealth() > bot:GetAttackDamage() * 2
and J.CanCastOnTargetAdvanced(enemyHero)
and J.IsInRange(bot, enemyHero, nCastRange)
and J.CanKillTarget(enemyHero, (nDamage * nDuration) * nDamageReduction, DAMAGE_TYPE_PHYSICAL)
and not enemyHero:HasModifier('modifier_abaddon_borrowed_time')
and not enemyHero:HasModifier('modifier_dazzle_shallow_grave')
and not enemyHero:HasModifier('modifier_necrolyte_reapers_scythe')
and not enemyHero:HasModifier('modifier_templar_assassin_refraction_absorb')
and not enemyHero:HasModifier('modifier_item_aeon_disk_buff')
and not enemyHero:HasModifier('modifier_item_blade_mail_reflect')
then
if J.WeAreStronger(bot, 1600) then
bot:SetTarget(enemyHero)
return BOT_ACTION_DESIRE_HIGH, enemyHero
end
end
end
if J.IsGoingOnSomeone(bot)
then
for _, enemyHero in pairs(tEnemyHeroes)
do
if J.IsValidTarget(enemyHero)
and J.CanBeAttacked(enemyHero)
and not J.IsInEtherealForm(enemyHero)
and enemyHero:GetHealth() > bot:GetAttackDamage() * 3
and J.IsInRange(bot, enemyHero, nCastRange)
and J.CanCastOnTargetAdvanced(enemyHero)
and not enemyHero:HasModifier('modifier_abaddon_borrowed_time')
and not enemyHero:HasModifier('modifier_dazzle_shallow_grave')
and not enemyHero:HasModifier('modifier_necrolyte_reapers_scythe')
and not enemyHero:HasModifier('modifier_item_aeon_disk_buff')
and not enemyHero:HasModifier('modifier_item_blade_mail_reflect')
then
bot:SetTarget(enemyHero)
return BOT_ACTION_DESIRE_HIGH, enemyHero
end
end
end
if J.IsDoingRoshan(bot)
then
if J.IsRoshan(botTarget)
and J.IsInRange(bot, botTarget, 500)
and J.GetHP(botTarget) > 0.25
and J.IsAttacking(bot)
and not botTarget:HasModifier('modifier_roshan_spell_block')
then
return BOT_ACTION_DESIRE_HIGH, botTarget
end
end
if J.IsDoingTormentor(bot)
then
if J.IsTormentor(botTarget)
and J.IsInRange(bot, botTarget, 500)
and J.GetHP(botTarget) > 0.3
and J.IsAttacking(bot)
then
return BOT_ACTION_DESIRE_HIGH, botTarget
end
end
return BOT_ACTION_DESIRE_NONE, nil
end
function X.ConsiderGaleForce()
if not J.CanCastAbility(GaleForce)
then
return BOT_ACTION_DESIRE_NONE, 0
end
local nCastRange = J.GetProperCastRange(false, bot, GaleForce:GetCastRange())
local nRadius = GaleForce:GetSpecialValueInt('radius')
local nCastPoint = GaleForce:GetCastPoint()
if J.IsGoingOnSomeone(bot)
then
local nLocationAoE = bot:FindAoELocation(true, true, bot:GetLocation(), nCastRange + nRadius, nRadius, nCastPoint, 0)
local nInRangeEnemy = J.GetEnemiesNearLoc(nLocationAoE.targetloc, nRadius)
if #nInRangeEnemy >= 2
and not J.IsEnemyChronosphereInLocation(nLocationAoE.targetloc)
and not J.IsEnemyBlackHoleInLocation(nLocationAoE.targetloc)
then
return BOT_ACTION_DESIRE_HIGH, nLocationAoE.targetloc
end
end
if J.IsRetreating(bot)
and not J.IsRealInvisible(bot)
then
local tEnemyHeroes = J.GetNearbyHeroes(bot,1600, true, BOT_MODE_NONE)
for _, enemyHero in pairs(tEnemyHeroes)
do
if J.IsValidHero(enemyHero)
and J.IsInRange(bot, enemyHero, 800)
and J.CanCastOnNonMagicImmune(enemyHero)
and J.IsChasingTarget(enemyHero, bot)
and not J.IsSuspiciousIllusion(enemyHero)
and not J.IsDisabled(enemyHero)
then
local nInRangeAlly = J.GetAlliesNearLoc(enemyHero:GetLocation(), 1200)
local nInRangeEnemy = J.GetEnemiesNearLoc(enemyHero:GetLocation(), 1200)
if #nInRangeEnemy > #nInRangeAlly and bot:WasRecentlyDamagedByAnyHero(3.0)
then
return BOT_ACTION_DESIRE_HIGH, (bot:GetLocation() + J.GetCenterOfUnits(nInRangeEnemy)) / 2
end
end
end
end
return BOT_ACTION_DESIRE_NONE, 0
end
-- Helper Funcs
function X.GetShackleCreepTarget(hSource, hTarget, nRadius, nMaxAngle)
local nCreeps = hTarget:GetNearbyCreeps(nRadius, false)
for _, creep in pairs(nCreeps)
do
if J.IsValid(creep)
then
local angle = X.GetAngleWithThreeVectors(hSource:GetLocation(), creep:GetLocation(), hTarget:GetLocation())
if angle <= nMaxAngle then
return creep
end
end
end
return nil
end
function X.GetShackleHeroTarget(hSource, hTarget, nRadius, nMaxAngle)
local nEnemyHeroes = hTarget:GetNearbyHeroes(nRadius, false, BOT_MODE_NONE)
for _, enemyHero in pairs(nEnemyHeroes)
do
if J.IsValidHero(enemyHero)
and J.CanCastOnNonMagicImmune(enemyHero)
and enemyHero ~= hTarget
then
local angle = X.GetAngleWithThreeVectors(hSource:GetLocation(), enemyHero:GetLocation(), hTarget:GetLocation())
if angle <= nMaxAngle then
return enemyHero
end
end
end
return nil
end
function X.CanShackleToCreep(hSource, hTarget, nRadius, nMaxAngle)
local nCreeps = hTarget:GetNearbyCreeps(nRadius, false)
for _, creep in pairs(nCreeps)
do
if J.IsValid(creep)
then
local angle = X.GetAngleWithThreeVectors(hSource:GetLocation(), hTarget:GetLocation(), creep:GetLocation())
if angle <= nMaxAngle then
return true
end
end
end
return false
end
function X.CanShackleToHero(hSource, hTarget, nRadius, nMaxAngle)
local nEnemyHeroes = J.GetEnemiesNearLoc(hTarget:GetLocation(), nRadius)
-- real
for _, enemyHero in pairs(nEnemyHeroes)
do
if J.IsValidHero(enemyHero)
and enemyHero ~= hTarget
then
local angle = X.GetAngleWithThreeVectors(hSource:GetLocation(), hTarget:GetLocation(), enemyHero:GetLocation())
if angle <= nMaxAngle then
return true
end
end
end
-- include illusions
nEnemyHeroes = hTarget:GetNearbyHeroes(nRadius, false, BOT_MODE_NONE)
for _, enemyHero in pairs(nEnemyHeroes)
do
if J.IsValidHero(enemyHero)
and enemyHero ~= hTarget
then
local angle = X.GetAngleWithThreeVectors(hSource:GetLocation(), hTarget:GetLocation(), enemyHero:GetLocation())
if angle <= nMaxAngle then
return true
end
end
end
return false
end
function X.CanShackleToTree(hSource, hTarget, nRadius, nMaxAngle)
local nTrees = hTarget:GetNearbyTrees(nRadius)
for _, tree in pairs(nTrees) do
if tree then
local angle = X.GetAngleWithThreeVectors(hSource:GetLocation(), hTarget:GetLocation(), GetTreeLocation(tree))
if angle <= nMaxAngle then
return true
end
end
end
return false
end
function X.GetShackleTarget(hSource, hTarget, nRadius, nMaxAngle)
local sTarget = nil
if X.CanShackleToHero(hSource, hTarget, nRadius, nMaxAngle)
or X.CanShackleToTree(hSource, hTarget, nRadius, nMaxAngle)
or X.CanShackleToCreep(hSource, hTarget, nRadius, nMaxAngle) then
sTarget = hTarget
else
sTarget = X.GetShackleCreepTarget(hSource, hTarget, nRadius, nMaxAngle)
if sTarget == nil then
sTarget = X.GetShackleHeroTarget(hSource, hTarget, nRadius, nMaxAngle)
end
end
return sTarget
end
function X.GetAngleWithThreeVectors(A, B, C)
local CA = Vector(C.x - A.x, C.y - A.y, C.z - A.z)
local CB = Vector(C.x - B.x, C.y - B.y, C.z - B.z)
local magCA = math.sqrt(CA.x^2 + CA.y^2 + CA.z^2)
local magCB = math.sqrt(CB.x^2 + CB.y^2 + CB.z^2)
local dot = CA.x * CB.x + CA.y * CB.y + CA.z * CB.z
return (math.acos(dot / (magCA * magCB))) * (180 / math.pi)
end
function X.IsBeingAttackedByRealHero(unit)
for _, enemy in pairs(GetUnitList(UNIT_LIST_ENEMIES))
do
if J.IsValidHero(enemy)
and not J.IsSuspiciousIllusion(enemy)
and (enemy:GetAttackTarget() == unit or J.IsChasingTarget(enemy, unit))
then
return true
end
end
return false
end
return X | 0 | 0.902492 | 1 | 0.902492 | game-dev | MEDIA | 0.964623 | game-dev | 0.965178 | 1 | 0.965178 |
CyrilCermak/pets-therapy | 1,704 | Sources/windows/App/Sources/Capabilities/WallCrawler.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace App
{
public class WallCrawler : EntityCapability
{
private Rect bounds;
public WallCrawler(Rect bounds)
{
this.bounds = bounds;
}
public override void Update(TimeSpan timeSinceLastUpdate, Entity entity)
{
if (entity.Direction.X > 0 && entity.Frame.MaxX() >= bounds.W)
{
entity.Direction.X = 0.0;
entity.Direction.Y = -1.0;
entity.Frame.X = bounds.W - entity.Frame.W;
return;
}
if (entity.Direction.X < 0 && entity.Frame.X <= bounds.X)
{
entity.Direction.X = 0.0;
entity.Direction.Y = 1.0;
entity.Frame.X = 0.0;
return;
}
if (entity.Direction.Y > 0 && entity.Frame.MaxY() >= bounds.H)
{
entity.Direction.X = entity.Frame.X == bounds.X ? 1.0 : -1.0;
entity.Direction.Y = 0.0;
entity.Frame.Y = bounds.H - entity.Frame.H;
return;
}
if (entity.Direction.Y < 0 && entity.Frame.Y <= bounds.Y - entity.Frame.H)
{
entity.Direction.X = 0.0;
entity.Direction.Y = 1.0;
if (entity.Frame.X == bounds.X)
{
entity.Frame.X = bounds.W - entity.Frame.W;
} else
{
entity.Frame.X = bounds.X;
}
return;
}
}
}
} | 0 | 0.722098 | 1 | 0.722098 | game-dev | MEDIA | 0.913302 | game-dev | 0.749691 | 1 | 0.749691 |
gree/pure2d | 7,605 | pure2DDemo/src/main/java/com/funzio/pure2D/demo/effects/MotionTrailShapeActivity.java | /*******************************************************************************
* Copyright (C) 2012-2014 GREE, 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.
******************************************************************************/
package com.funzio.pure2D.demo.effects;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Interpolator;
import com.funzio.pure2D.Manipulatable;
import com.funzio.pure2D.Scene;
import com.funzio.pure2D.demo.activities.StageActivity;
import com.funzio.pure2D.demo.animations.AnimationActivity;
import com.funzio.pure2D.demo.objects.Bouncer;
import com.funzio.pure2D.effects.trails.MotionTrailShape;
import com.funzio.pure2D.gl.GLColor;
import com.funzio.pure2D.gl.gl10.GLState;
import com.funzio.pure2D.gl.gl10.textures.Texture;
import com.longo.pure2D.demo.R;
public class MotionTrailShapeActivity extends StageActivity {
private Interpolator mInterpolator;
@SuppressWarnings("unused")
private Texture mTexture;
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mScene.setListener(new Scene.Listener() {
@Override
public void onSurfaceCreated(final GLState glState, final boolean firstTime) {
if (firstTime) {
loadTexture();
for (int i = 0; i < 100; i++) {
addObject(RANDOM.nextInt(mDisplaySize.x), RANDOM.nextInt(mDisplaySize.y));
}
}
}
});
}
@Override
protected int getLayout() {
return R.layout.stage_motion_trail;
}
@Override
protected int getNumObjects() {
return mScene.getNumGrandChildren();
}
// private void addObject(float x, float y) {
// final GLColor color1 = new GLColor(.5f + RANDOM.nextFloat(), RANDOM.nextFloat(), RANDOM.nextFloat(), 1f);
// final GLColor color2 = new GLColor(color1);
// color2.a = 0;
//
// // create object
// Polyline obj = new Polyline();
// obj.setColor(color1);
// obj.setStrokeRange(10, 50);
//
// PointF[] points = new PointF[5];
// points[0] = new PointF(x, y);
// for (int i = 1; i < points.length; i++) {
// x += RANDOM.nextInt(300) - 150;
// y += RANDOM.nextInt(300) - 150;
// points[i] = new PointF(x, y);
// }
// obj.setPoints(points);
//
// // obj.setPoints(new PointF(x, y), new PointF(x + RANDOM.nextInt(300), y + RANDOM.nextInt(300)), new PointF(x + RANDOM.nextInt(300), y + RANDOM.nextInt(300)));
// // obj.setPoints(new PointF(x, y), new PointF(x + 300, y), new PointF(x + 100, y + 100), new PointF(x + 400, y - 300), new PointF());
//
// // add to scene
// mScene.addChild(obj);
// }
private void loadTexture() {
// create texture
mTexture = mScene.getTextureManager().createDrawableTexture(R.drawable.cc_175, null);
}
private void addObject(final float screenX, final float screenY) {
final GLColor color1 = new GLColor(.5f + RANDOM.nextFloat(), RANDOM.nextFloat(), RANDOM.nextFloat(), 1f);
final GLColor color2 = new GLColor(color1);// new GLColor(.5f + RANDOM.nextFloat(), RANDOM.nextFloat(), RANDOM.nextFloat(), 0.5f);
color2.a = 0.1f;
mScene.screenToGlobal(screenX, screenY, mTempPoint);
// create object
Bouncer obj = new Bouncer();
obj.setSize(30, 30);
obj.setAutoUpdateBounds(true);
obj.setOriginAtCenter();
obj.setColor(color1);
obj.setPosition(mTempPoint);
// add to scene
mScene.addChild(obj);
MotionTrailShape trail = new MotionTrailShape();
// trail.setColor(color1);
trail.setStrokeRange(30, 1);
trail.setNumPoints(20);
trail.setStrokeColors(color1, color2);
// trail.setTexture(mTexture);
// trail.setTextureCoordBuffer(TextureCoordBuffer.getDefault());
trail.setMinLength(100);
trail.setTarget(obj);
trail.setStrokeInterpolator(mInterpolator);
mScene.addChild(trail);
}
private void setStrokeInterpolator(final Interpolator interpolator) {
mInterpolator = interpolator;
mScene.queueEvent(new Runnable() {
@Override
public void run() {
final int num = mScene.getNumChildren();
for (int i = 0; i < num; i++) {
Manipulatable child = mScene.getChildAt(i);
if (child instanceof MotionTrailShape) {
((MotionTrailShape) child).setStrokeInterpolator(interpolator);
}
}
}
});
}
@Override
public boolean onTouch(final View v, final MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
mStage.queueEvent(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 50; i++) {
addObject(event.getX(), event.getY());
}
}
});
}
return true;
}
public void onClickRadio(final View view) {
// tween specific switches
switch (view.getId()) {
case R.id.radio_linear:
setStrokeInterpolator(null);
break;
case R.id.radio_accelarate:
setStrokeInterpolator(AnimationActivity.ACCELERATE);
break;
case R.id.radio_decelarate:
setStrokeInterpolator(AnimationActivity.DECELERATE);
break;
case R.id.radio_accelerate_decelarate:
setStrokeInterpolator(AnimationActivity.ACCELERATE_DECELERATE);
break;
case R.id.radio_bounce:
setStrokeInterpolator(AnimationActivity.BOUNCE);
break;
case R.id.radio_anticipate:
setStrokeInterpolator(AnimationActivity.ANTICIPATE);
break;
case R.id.radio_anticipate_overshoot:
setStrokeInterpolator(AnimationActivity.ANTICIPATE_OVERSHOOT);
break;
case R.id.radio_overshoot:
setStrokeInterpolator(AnimationActivity.OVERSHOOT);
break;
case R.id.radio_cycle:
setStrokeInterpolator(AnimationActivity.CYCLE);
break;
}
}
}
| 0 | 0.711136 | 1 | 0.711136 | game-dev | MEDIA | 0.437989 | game-dev | 0.919509 | 1 | 0.919509 |
PentestSS13/Pentest | 2,159 | code/modules/modular_computers/hardware/ai_slot.dm | /obj/item/computer_hardware/ai_slot
name = "intelliCard interface slot"
desc = "A module allowing this computer to interface with most common intelliCard modules. Necessary for some programs to run properly."
power_usage = 100 //W
icon_state = "card_mini"
w_class = WEIGHT_CLASS_SMALL
device_type = MC_AI
var/obj/item/aicard/stored_card
var/locked = FALSE
///What happens when the intellicard is removed (or deleted) from the module, through try_eject() or not.
/obj/item/computer_hardware/ai_slot/Exited(atom/A, atom/newloc)
if(A == stored_card)
stored_card = null
return ..()
/obj/item/computer_hardware/ai_slot/examine(mob/user)
. = ..()
if(stored_card)
. += "There appears to be an intelliCard loaded. There appears to be a pinhole protecting a manual eject button. A screwdriver could probably press it."
/obj/item/computer_hardware/ai_slot/try_insert(obj/item/I, mob/living/user = null)
if(!holder)
return FALSE
if(!istype(I, /obj/item/aicard))
return FALSE
if(stored_card)
to_chat(user, span_warning("You try to insert \the [I] into \the [src], but the slot is occupied."))
return FALSE
if(user && !user.transferItemToLoc(I, src))
return FALSE
stored_card = I
to_chat(user, span_notice("You insert \the [I] into \the [src]."))
return TRUE
/obj/item/computer_hardware/ai_slot/try_eject(slot=0,mob/living/user = null,forced = 0)
if(!stored_card)
to_chat(user, span_warning("There is no card in \the [src]."))
return FALSE
if(locked && !forced)
to_chat(user, span_warning("Safeties prevent you from removing the card until reconstruction is complete..."))
return FALSE
if(stored_card)
to_chat(user, span_notice("You remove [stored_card] from [src]."))
locked = FALSE
if(user && Adjacent(user) && !issiliconoradminghost(user))
user.put_in_hands(stored_card)
else
stored_card.forceMove(drop_location())
return TRUE
return FALSE
/obj/item/computer_hardware/ai_slot/attackby(obj/item/I, mob/living/user)
if(..())
return
if(I.tool_behaviour == TOOL_SCREWDRIVER)
to_chat(user, span_notice("You press down on the manual eject button with \the [I]."))
try_eject(,user,1)
return
| 0 | 0.911587 | 1 | 0.911587 | game-dev | MEDIA | 0.848305 | game-dev | 0.826801 | 1 | 0.826801 |
MegaMek/megamek | 3,272 | megamek/src/megamek/common/weapons/battleArmor/clan/laser/CLBALaserHeavyMedium.java | /*
* Copyright (C) 2004 Ben Mazur (bmazur@sev.org)
* Copyright (C) 2014-2025 The MegaMek Team. All Rights Reserved.
*
* This file is part of MegaMek.
*
* MegaMek is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License (GPL),
* version 3 or (at your option) any later version,
* as published by the Free Software Foundation.
*
* MegaMek is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* A copy of the GPL should have been included with this project;
* if not, see <https://www.gnu.org/licenses/>.
*
* NOTICE: The MegaMek organization is a non-profit group of volunteers
* creating free software for the BattleTech community.
*
* MechWarrior, BattleMech, `Mech and AeroTech are registered trademarks
* of The Topps Company, Inc. All Rights Reserved.
*
* Catalyst Game Labs and the Catalyst Game Labs logo are trademarks of
* InMediaRes Productions, LLC.
*
* MechWarrior Copyright Microsoft Corporation. MegaMek was created under
* Microsoft's "Game Content Usage Rules"
* <https://www.xbox.com/en-US/developers/rules> and it is not endorsed by or
* affiliated with Microsoft.
*/
package megamek.common.weapons.battleArmor.clan.laser;
import java.io.Serial;
import megamek.common.enums.AvailabilityValue;
import megamek.common.enums.Faction;
import megamek.common.enums.TechBase;
import megamek.common.enums.TechRating;
import megamek.common.weapons.lasers.LaserWeapon;
/**
* @author Andrew Hunter
* @since Sep 12, 2004
*/
public class CLBALaserHeavyMedium extends LaserWeapon {
@Serial
private static final long serialVersionUID = -3836305728245548205L;
public CLBALaserHeavyMedium() {
super();
name = "Heavy Medium Laser";
setInternalName("CLBAHeavyMediumLaser");
addLookupName("Clan BA Medium Heavy Laser");
sortingName = "Laser Heavy C";
heat = 7;
damage = 10;
toHitModifier = 1;
shortRange = 3;
mediumRange = 6;
longRange = 9;
extremeRange = 12;
waterShortRange = 2;
waterMediumRange = 4;
waterLongRange = 6;
waterExtremeRange = 8;
tonnage = 1.0;
criticalSlots = 4;
bv = 76;
cost = 100000;
shortAV = 10;
maxRange = RANGE_SHORT;
flags = flags.or(F_NO_FIRES)
.or(F_BA_WEAPON)
.andNot(F_MEK_WEAPON)
.andNot(F_TANK_WEAPON)
.andNot(F_AERO_WEAPON)
.andNot(F_PROTO_WEAPON);
rulesRefs = "258, TM";
techAdvancement.setTechBase(TechBase.CLAN)
.setIntroLevel(false)
.setUnofficial(false)
.setTechRating(TechRating.F)
.setAvailability(AvailabilityValue.X, AvailabilityValue.X, AvailabilityValue.D, AvailabilityValue.D)
.setClanAdvancement(3057, 3059, 3062, DATE_NONE, DATE_NONE)
.setClanApproximate(true, false, false, false, false)
.setPrototypeFactions(Faction.CSA)
.setProductionFactions(Faction.CSA);
}
}
| 0 | 0.859087 | 1 | 0.859087 | game-dev | MEDIA | 0.979086 | game-dev | 0.713931 | 1 | 0.713931 |
Sandern/lambdawars | 7,214 | src/game/server/ai_moveprobe.h | //========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#ifndef AI_MOVEPROBE_H
#define AI_MOVEPROBE_H
#include "ai_component.h"
#include "ai_navtype.h"
#include "ai_movetypes.h"
#if defined( _WIN32 )
#pragma once
#endif
//-----------------------------------------------------------------------------
// Purpose: Set of basic tools for probing box movements through space.
// No moves actually take place
//-----------------------------------------------------------------------------
enum AI_TestGroundMoveFlags_t
{
AITGM_DEFAULT = 0,
AITGM_IGNORE_FLOOR = 0x01,
AITGM_IGNORE_INITIAL_STAND_POS = 0x02,
AITGM_2D = 0x04,
AITGM_DRAW_RESULTS = 0x08,
AITGM_CRAWL_LARGE_STEPS = 0x10,
};
enum AI_MoveLimitFlags_t
{
AIMLF_DEFAULT = 0,
AIMLF_2D = 0x01,
AIMLF_DRAW_RESULTS = 0x02,
AIMLF_IGNORE_TRANSIENTS = 0x04,
AIMLF_QUICK_REJECT = 0x08,
};
class CAI_MoveProbe : public CAI_Component
{
public:
CAI_MoveProbe( CAI_BaseNPC *pOuter );
~CAI_MoveProbe();
// ----------------------------------------------------
// Queries & probes
// ----------------------------------------------------
bool MoveLimit( Navigation_t navType, const Vector &vecStart, const Vector &vecEnd, unsigned int collisionMask, const CBaseEntity *pTarget, AIMoveTrace_t* pMove = NULL );
bool MoveLimit( Navigation_t navType, const Vector &vecStart, const Vector &vecEnd, unsigned int collisionMask, const CBaseEntity *pTarget, float pctToCheckStandPositions, AIMoveTrace_t* pMove = NULL );
bool MoveLimit( Navigation_t navType, const Vector &vecStart, const Vector &vecEnd, unsigned int collisionMask, const CBaseEntity *pTarget, float pctToCheckStandPositions, unsigned flags, AIMoveTrace_t* pMove = NULL );
bool CheckStandPosition( const Vector &vecStart, unsigned int collisionMask ) const;
bool FloorPoint( const Vector &vecStart, unsigned int collisionMask, float flStartZ, float flEndZ, Vector *pVecResult ) const;
// --------------------------------
// Tracing tools
// --------------------------------
void TraceLine( const Vector &vecStart, const Vector &vecEnd, unsigned int mask,
bool bUseCollisionGroup, trace_t *pResult ) const;
void TraceHull( const Vector &vecStart, const Vector &vecEnd, const Vector &hullMin,
const Vector &hullMax, unsigned int mask,
trace_t *ptr ) const;
void TraceHull( const Vector &vecStart, const Vector &vecEnd, unsigned int mask,
trace_t *ptr ) const;
// --------------------------------
// Checks a ground-based movement
// --------------------------------
bool TestGroundMove( const Vector &vecActualStart, const Vector &vecDesiredEnd,
unsigned int collisionMask, unsigned flags, AIMoveTrace_t *pMoveTrace ) const;
bool TestGroundMove( const Vector &vecActualStart, const Vector &vecDesiredEnd,
unsigned int collisionMask, float pctToCheckStandPositions, unsigned flags, AIMoveTrace_t *pMoveTrace ) const;
bool ShouldBrushBeIgnored( CBaseEntity *pEntity );
void ClearBlockingEntity() { m_hLastBlockingEnt = NULL; }
CBaseEntity * GetBlockingEntity() { return m_hLastBlockingEnt; }
private:
struct CheckStepArgs_t
{
Vector vecStart;
Vector vecStepDir;
float stepSize;
float stepHeight;
float stepDownMultiplier;
float minStepLanding;
unsigned collisionMask;
StepGroundTest_t groundTest;
unsigned flags;
};
struct CheckStepResult_t
{
Vector endPoint;
Vector hitNormal;
bool fStartSolid;
CBaseEntity * pBlocker;
bool bCrawling;
};
bool CheckStep( const CheckStepArgs_t &args, CheckStepResult_t *pResult ) const;
void SetupCheckStepTraceListData( const CheckStepArgs_t &args ) const;
void ResetTraceListData() const { if ( m_pTraceListData ) const_cast<CAI_MoveProbe *>(this)->m_pTraceListData->Reset(); }
bool OldCheckStandPosition( const Vector &vecStart, unsigned int collisionMask ) const;
// these check connections between positions in space, regardless of routes
void GroundMoveLimit( const Vector &vecStart, const Vector &vecEnd, unsigned int collisionMask, const CBaseEntity *pTarget, unsigned testGroundMoveFlags, float pctToCheckStandPositions, AIMoveTrace_t* pMoveTrace ) const;
void FlyMoveLimit( const Vector &vecStart, const Vector &vecEnd, unsigned int collisionMask, const CBaseEntity *pTarget, AIMoveTrace_t* pMoveTrace) const;
void JumpMoveLimit( const Vector &vecStart, const Vector &vecEnd, unsigned int collisionMask, const CBaseEntity *pTarget, AIMoveTrace_t* pMoveTrace) const;
void ClimbMoveLimit( const Vector &vecStart, const Vector &vecEnd, const CBaseEntity *pTarget, AIMoveTrace_t* pMoveTrace) const;
// A floorPoint that is useful only in the contect of iterative movement
bool IterativeFloorPoint( const Vector &vecStart, unsigned int collisionMask, Vector *pVecResult ) const;
bool IterativeFloorPoint( const Vector &vecStart, unsigned int collisionMask, float flAddedStep, Vector *pVecResult ) const;
bool IsJumpLegal( const Vector &startPos, const Vector &apex, const Vector &endPos ) const;
public:
Vector CalcJumpLaunchVelocity(const Vector &startPos, const Vector &endPos, float gravity, float *pminHeight, float maxHorzVelocity, Vector *vecApex ) const;
private:
void CheckStepOverLargeCrawl( CheckStepResult_t *pResult, const CheckStepArgs_t &args, const Vector &vecStart, const Vector &vecEnd, const trace_t &blockedTrace ) const;
// Confirm 3D connectivity between 2 nodes
bool Confirm3DConnectivity( AIMoveTrace_t *pMoveTrace, unsigned flags, const Vector &vecDesiredEnd ) const;
// Common services provided by CAI_BaseNPC, Convenience methods to simplify code
float StepHeight() const;
bool CanStandOn( CBaseEntity *pSurface ) const;
bool m_bIgnoreTransientEntities;
ITraceListData * m_pTraceListData;
EHANDLE m_hLastBlockingEnt;
DECLARE_SIMPLE_DATADESC();
};
// ----------------------------------------------------------------------------
inline bool CAI_MoveProbe::MoveLimit( Navigation_t navType, const Vector &vecStart, const Vector &vecEnd, unsigned int collisionMask, const CBaseEntity *pTarget, float pctToCheckStandPositions, AIMoveTrace_t* pMove)
{
return MoveLimit( navType, vecStart, vecEnd, collisionMask, pTarget, pctToCheckStandPositions, AIMLF_DEFAULT, pMove);
}
// ------------------------------------
inline bool CAI_MoveProbe::MoveLimit( Navigation_t navType, const Vector &vecStart, const Vector &vecEnd, unsigned int collisionMask, const CBaseEntity *pTarget, AIMoveTrace_t* pMove)
{
return MoveLimit( navType, vecStart, vecEnd, collisionMask, pTarget, 100.0f, AIMLF_DEFAULT, pMove);
}
// ------------------------------------
inline bool CAI_MoveProbe::TestGroundMove( const Vector &vecActualStart, const Vector &vecDesiredEnd, unsigned int collisionMask, unsigned flags, AIMoveTrace_t *pMoveTrace ) const
{
return TestGroundMove( vecActualStart, vecDesiredEnd, collisionMask, 100, flags, pMoveTrace ); // floor ignore flag will override 100%
}
#endif // AI_MOVEPROBE_H
| 0 | 0.737205 | 1 | 0.737205 | game-dev | MEDIA | 0.869738 | game-dev | 0.618427 | 1 | 0.618427 |
iTXTech/Genisys | 2,503 | src/pocketmine/block/NetherWart.php | <?php
/*
*
* _____ _____ __ _ _ _____ __ __ _____
* / ___| | ____| | \ | | | | / ___/ \ \ / / / ___/
* | | | |__ | \| | | | | |___ \ \/ / | |___
* | | _ | __| | |\ | | | \___ \ \ / \___ \
* | |_| | | |___ | | \ | | | ___| | / / ___| |
* \_____/ |_____| |_| \_| |_| /_____/ /_/ /_____/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author iTX Technologies
* @link https://itxtech.org
*
*/
namespace pocketmine\block;
use pocketmine\event\block\BlockGrowEvent;
use pocketmine\item\enchantment\Enchantment;
use pocketmine\item\Item;
use pocketmine\level\Level;
use pocketmine\Player;
use pocketmine\Server;
class NetherWart extends Flowable{
protected $id = self::NETHER_WART_BLOCK;
public function __construct($meta = 0){
$this->meta = $meta;
}
public function getName() : string{
return "Nether Wart Block";
}
public function place(Item $item, Block $block, Block $target, $face, $fx, $fy, $fz, Player $player = null){
$down = $this->getSide(0);
if($down->getId() === self::SOUL_SAND){
$this->getLevel()->setBlock($block, $this, true, true);
return true;
}
return false;
}
public function onUpdate($type){
if($type === Level::BLOCK_UPDATE_NORMAL){
if($this->getSide(0)->isTransparent() === true){
$this->getLevel()->useBreakOn($this);
return Level::BLOCK_UPDATE_NORMAL;
}
}elseif($type === Level::BLOCK_UPDATE_RANDOM){
if(mt_rand(0, 12) == 1){//only have 0-3 So maybe slowly
if($this->meta < 0x03){//0x03
$block = clone $this;
++$block->meta;
Server::getInstance()->getPluginManager()->callEvent($ev = new BlockGrowEvent($this, $block));
if(!$ev->isCancelled()){
$this->getLevel()->setBlock($this, $ev->getNewState(), true, true);
}else{
return Level::BLOCK_UPDATE_RANDOM;
}
}
}else{
return Level::BLOCK_UPDATE_RANDOM;
}
}
return false;
}
public function getDrops(Item $item) : array {
$drops = [];
if($this->meta >= 0x03){
$fortunel = $item->getEnchantmentLevel(Enchantment::TYPE_MINING_FORTUNE);
$fortunel = $fortunel > 3 ? 3 : $fortunel;
$drops[] = [Item::NETHER_WART, 0, mt_rand(2, 4 + $fortunel)];
}else{
$drops[] = [Item::NETHER_WART, 0, 1];
}
return $drops;
}
}
| 0 | 0.989644 | 1 | 0.989644 | game-dev | MEDIA | 0.99127 | game-dev | 0.994377 | 1 | 0.994377 |
CyberTianzun/QingTingCheat | 9,512 | src/fm/qingting/qtradio/data/ReserveProgramDS.java | package fm.qingting.qtradio.data;
import android.database.sqlite.SQLiteDatabase;
import com.google.gson.Gson;
import fm.qingting.framework.data.DataCommand;
import fm.qingting.framework.data.DataToken;
import fm.qingting.framework.data.IDataParser;
import fm.qingting.framework.data.IDataRecvHandler;
import fm.qingting.framework.data.IDataSource;
import fm.qingting.framework.data.IDataToken;
import fm.qingting.framework.data.Result;
import fm.qingting.qtradio.model.ReserveNode;
import java.util.List;
import java.util.Map;
public class ReserveProgramDS
implements IDataSource
{
private static ReserveProgramDS instance;
private int MAX_COUNT = 10;
// ERROR //
private List<ReserveNode> acquireReserveProgram(DataCommand paramDataCommand)
{
// Byte code:
// 0: new 22 java/util/ArrayList
// 3: dup
// 4: invokespecial 23 java/util/ArrayList:<init> ()V
// 7: astore_2
// 8: invokestatic 29 fm/qingting/qtradio/data/DBManager:getInstance ()Lfm/qingting/qtradio/data/DBManager;
// 11: ldc 31
// 13: invokevirtual 35 fm/qingting/qtradio/data/DBManager:getReadableDB (Ljava/lang/String;)Landroid/database/sqlite/SQLiteDatabase;
// 16: ldc 37
// 18: aconst_null
// 19: invokevirtual 43 android/database/sqlite/SQLiteDatabase:rawQuery (Ljava/lang/String;[Ljava/lang/String;)Landroid/database/Cursor;
// 22: astore 4
// 24: iconst_0
// 25: istore 5
// 27: new 45 com/google/gson/Gson
// 30: dup
// 31: invokespecial 46 com/google/gson/Gson:<init> ()V
// 34: astore 6
// 36: aconst_null
// 37: astore 7
// 39: aload 4
// 41: invokeinterface 52 1 0
// 46: ifeq +235 -> 281
// 49: iload 5
// 51: aload_0
// 52: getfield 16 fm/qingting/qtradio/data/ReserveProgramDS:MAX_COUNT I
// 55: if_icmpge +226 -> 281
// 58: aload 4
// 60: ldc 54
// 62: invokeinterface 58 2 0
// 67: istore 8
// 69: aload 4
// 71: ldc 60
// 73: invokeinterface 58 2 0
// 78: istore 9
// 80: aload 4
// 82: ldc 62
// 84: invokeinterface 58 2 0
// 89: istore 10
// 91: aload 4
// 93: ldc 64
// 95: invokeinterface 58 2 0
// 100: istore 11
// 102: aload 4
// 104: ldc 66
// 106: invokeinterface 58 2 0
// 111: istore 12
// 113: aload 4
// 115: iload 8
// 117: invokeinterface 70 2 0
// 122: astore 13
// 124: aload 4
// 126: iload 9
// 128: invokeinterface 70 2 0
// 133: astore 14
// 135: aload 4
// 137: iload 10
// 139: invokeinterface 70 2 0
// 144: astore 15
// 146: aload 4
// 148: iload 11
// 150: invokeinterface 70 2 0
// 155: astore 16
// 157: aload 4
// 159: iload 12
// 161: invokeinterface 70 2 0
// 166: astore 17
// 168: aload 6
// 170: aload 13
// 172: ldc 72
// 174: invokevirtual 76 com/google/gson/Gson:fromJson (Ljava/lang/String;Ljava/lang/Class;)Ljava/lang/Object;
// 177: checkcast 78 fm/qingting/qtradio/model/Node
// 180: astore 22
// 182: aload 22
// 184: astore 7
// 186: aload 7
// 188: ifnull +114 -> 302
// 191: new 80 fm/qingting/qtradio/model/ReserveNode
// 194: dup
// 195: invokespecial 81 fm/qingting/qtradio/model/ReserveNode:<init> ()V
// 198: astore 20
// 200: aload 20
// 202: aload 7
// 204: putfield 85 fm/qingting/qtradio/model/ReserveNode:reserveNode Lfm/qingting/qtradio/model/Node;
// 207: aload 20
// 209: aload 14
// 211: invokestatic 91 java/lang/Long:valueOf (Ljava/lang/String;)Ljava/lang/Long;
// 214: invokevirtual 95 java/lang/Long:longValue ()J
// 217: putfield 99 fm/qingting/qtradio/model/ReserveNode:reserveTime J
// 220: aload 20
// 222: aload 15
// 224: invokestatic 104 java/lang/Integer:valueOf (Ljava/lang/String;)Ljava/lang/Integer;
// 227: invokevirtual 108 java/lang/Integer:intValue ()I
// 230: putfield 110 fm/qingting/qtradio/model/ReserveNode:channelId I
// 233: aload 20
// 235: aload 16
// 237: putfield 113 fm/qingting/qtradio/model/ReserveNode:programName Ljava/lang/String;
// 240: aload 20
// 242: aload 17
// 244: invokestatic 104 java/lang/Integer:valueOf (Ljava/lang/String;)Ljava/lang/Integer;
// 247: invokevirtual 108 java/lang/Integer:intValue ()I
// 250: putfield 116 fm/qingting/qtradio/model/ReserveNode:uniqueId I
// 253: aload 20
// 255: getfield 99 fm/qingting/qtradio/model/ReserveNode:reserveTime J
// 258: invokestatic 121 java/lang/System:currentTimeMillis ()J
// 261: ldc2_w 122
// 264: ldiv
// 265: lcmp
// 266: ifle +43 -> 309
// 269: aload_2
// 270: aload 20
// 272: invokeinterface 129 2 0
// 277: pop
// 278: goto +31 -> 309
// 281: aload 4
// 283: invokeinterface 132 1 0
// 288: aload_2
// 289: areturn
// 290: astore 23
// 292: aconst_null
// 293: areturn
// 294: astore_3
// 295: aload_2
// 296: areturn
// 297: astore 18
// 299: goto -113 -> 186
// 302: iload 5
// 304: istore 19
// 306: goto +9 -> 315
// 309: iload 5
// 311: iconst_1
// 312: iadd
// 313: istore 19
// 315: iload 19
// 317: istore 5
// 319: goto -280 -> 39
//
// Exception table:
// from to target type
// 0 8 290 java/lang/Exception
// 8 24 294 java/lang/Exception
// 27 36 294 java/lang/Exception
// 39 168 294 java/lang/Exception
// 191 278 294 java/lang/Exception
// 281 288 294 java/lang/Exception
// 168 182 297 java/lang/Exception
}
private boolean deleteReserveProgram(DataCommand paramDataCommand)
{
try
{
DBManager.getInstance().getWritableDB("reserveprogram").execSQL("delete from reserveprogram");
return true;
}
catch (Exception localException)
{
}
return false;
}
private DataToken doAcquireCommand(DataCommand paramDataCommand)
{
DataToken localDataToken = new DataToken();
localDataToken.setDataInfo(paramDataCommand);
localDataToken.setData(new Result(true, acquireReserveProgram(paramDataCommand)));
return localDataToken;
}
private DataToken doDeleteCommand(DataCommand paramDataCommand)
{
DataToken localDataToken = new DataToken();
localDataToken.setDataInfo(paramDataCommand);
localDataToken.setData(new Result(true, Boolean.valueOf(deleteReserveProgram(paramDataCommand))));
return localDataToken;
}
private DataToken doInsertCommand(DataCommand paramDataCommand)
{
DataToken localDataToken = new DataToken();
localDataToken.setDataInfo(paramDataCommand);
localDataToken.setData(new Result(true, Boolean.valueOf(insertReserveProgram(paramDataCommand))));
return localDataToken;
}
public static ReserveProgramDS getInstance()
{
if (instance == null)
instance = new ReserveProgramDS();
return instance;
}
private boolean insertReserveProgram(DataCommand paramDataCommand)
{
List localList = (List)paramDataCommand.getParam().get("reserveprogram");
if ((localList == null) || (localList.size() == 0))
return false;
try
{
SQLiteDatabase localSQLiteDatabase = DBManager.getInstance().getWritableDB("reserveprogram");
localSQLiteDatabase.beginTransaction();
Gson localGson = new Gson();
for (int i = 0; i < localList.size(); i++)
{
ReserveNode localReserveNode = (ReserveNode)localList.get(i);
int j = localReserveNode.channelId;
String str1 = localReserveNode.programName;
int k = localReserveNode.uniqueId;
long l = localReserveNode.reserveTime;
String str2 = localGson.toJson(localReserveNode.reserveNode);
Object[] arrayOfObject = new Object[5];
arrayOfObject[0] = Long.valueOf(l);
arrayOfObject[1] = str2;
arrayOfObject[2] = Integer.valueOf(j);
arrayOfObject[3] = str1;
arrayOfObject[4] = Integer.valueOf(k);
localSQLiteDatabase.execSQL("insert into reserveprogram(time, reserveProgram,channelId,programName,programId) values(?,?,?,?,?)", arrayOfObject);
}
localSQLiteDatabase.setTransactionSuccessful();
localSQLiteDatabase.endTransaction();
return true;
}
catch (Exception localException)
{
}
return false;
}
public void addParser(IDataParser paramIDataParser)
{
}
public String dataSourceName()
{
return "ReserveProgramDS";
}
public IDataToken doCommand(DataCommand paramDataCommand, IDataRecvHandler paramIDataRecvHandler)
{
String str = paramDataCommand.getCurrentCommand();
if (str.equalsIgnoreCase("insert_reserve_program"))
return doInsertCommand(paramDataCommand);
if (str.equalsIgnoreCase("get_reserve_program"))
return doAcquireCommand(paramDataCommand);
if (str.equalsIgnoreCase("delete_reserve_program"))
return doDeleteCommand(paramDataCommand);
return null;
}
public boolean isSynchronous(String paramString, Map<String, Object> paramMap)
{
return true;
}
}
/* Location: /Users/zhangxun-xy/Downloads/qingting2/classes_dex2jar.jar
* Qualified Name: fm.qingting.qtradio.data.ReserveProgramDS
* JD-Core Version: 0.6.2
*/ | 0 | 0.918401 | 1 | 0.918401 | game-dev | MEDIA | 0.36021 | game-dev | 0.896833 | 1 | 0.896833 |
TupoyeMenu/TupoyeMenu | 3,224 | BigBaseV2/src/util/mobile.hpp | #pragma once
#include "core/enums.hpp"
#include "globals.hpp"
#include "gta_util.hpp"
#include "misc.hpp"
#include "natives.hpp"
#include "notify.hpp"
#include "script.hpp"
#include "script_global.hpp"
#include "script_local.hpp"
#include "vehicle.hpp"
namespace big::mobile
{
inline auto player_global = script_global(2689156);
inline auto mechanic_global = script_global(2810287);
inline auto vehicle_global = script_global(1585844);
namespace util
{
int get_current_personal_vehicle(); // forward declare
inline void despawn_current_personal_vehicle()
{
misc::clear_bits(
vehicle_global.at(get_current_personal_vehicle(), 142).at(103).as<int*>(),
eVehicleFlags::TRIGGER_SPAWN_TOGGLE
);
}
inline int get_current_personal_vehicle()
{
return *script_global(2359296).at(0, 5559).at(675).at(2).as<int*>();
}
}
namespace lester
{
inline void off_radar(bool toggle)
{
*player_global.at(PLAYER::GET_PLAYER_INDEX(), 453).at(209).as<int*>() = toggle;
*script_global(2703656).at(70).as<int*>() = NETWORK::GET_NETWORK_TIME() + 1;
}
}
namespace mors_mutual
{
inline bool fix_index(int veh_idx, bool spawn_veh = false)
{
bool can_be_fixed = misc::has_bits_set(
vehicle_global.at(veh_idx, 142).at(103).as<int*>(),
eVehicleFlags::DESTROYED | eVehicleFlags::HAS_INSURANCE
);
if (can_be_fixed)
{
misc::clear_bits(
vehicle_global.at(veh_idx, 142).at(103).as<int*>(),
eVehicleFlags::DESTROYED | eVehicleFlags::IMPOUNDED | eVehicleFlags::UNK2
);
if (spawn_veh)
{
misc::set_bits(
vehicle_global.at(veh_idx, 142).at(103).as<int*>(),
eVehicleFlags::TRIGGER_SPAWN_TOGGLE | eVehicleFlags::SPAWN_AT_MORS_MUTUAL
);
}
}
return can_be_fixed;
}
inline int fix_all()
{
int fixed_count = 0;
const int arr_size = *vehicle_global.as<int*>();
for (int i = 0; i < arr_size; i++)
if (fix_index(i))
fixed_count++;
return fixed_count;
}
}
namespace mechanic
{
inline void summon_vehicle_by_index(int veh_idx)
{
if (*mechanic_global.at(958).as<int*>() != -1)
return notify::display_help_text("Mechanic is not ready to deliver a vehicle right now.");
TASK::CLEAR_PED_TASKS_IMMEDIATELY(PLAYER::PLAYER_PED_ID());
// despawn current veh
util::despawn_current_personal_vehicle();
mors_mutual::fix_index(veh_idx);
script::get_current()->yield(100ms);
*mechanic_global.at(924).as<int*>() = 1; // disable vehicle node distance check
*mechanic_global.at(911).as<int*>() = 1; // tell freemode to spawn our vehicle
*mechanic_global.at(961).as<int*>() = 0; // required
*mechanic_global.at(958).as<int*>() = veh_idx;
script::get_current()->yield(100ms);
GtaThread* freemode_thread = gta_util::find_script_thread(RAGE_JOAAT("freemode"));
if (freemode_thread)
*script_local(freemode_thread, 17437).at(176).as<int*>() = 0; // spawn vehicle instantly
// blocking call till vehicle is delivered
notify::busy_spinner("Delivering vehicle...", mechanic_global.at(958).as<int*>(), -1);
if (g.vehicle.pv_teleport_into)
vehicle::bring(globals::get_personal_vehicle(), ENTITY::GET_ENTITY_COORDS(PLAYER::PLAYER_PED_ID(), true));
}
}
} | 0 | 0.906445 | 1 | 0.906445 | game-dev | MEDIA | 0.972998 | game-dev | 0.803571 | 1 | 0.803571 |
AdaEngine/AdaEngine | 1,682 | Modules/box2d/src/bitset.h | // SPDX-FileCopyrightText: 2023 Erin Catto
// SPDX-License-Identifier: MIT
#pragma once
#include "core.h"
#include <stdbool.h>
#include <stdint.h>
// Bit set provides fast operations on large arrays of bits.
typedef struct b2BitSet
{
uint64_t* bits;
uint32_t blockCapacity;
uint32_t blockCount;
} b2BitSet;
b2BitSet b2CreateBitSet( uint32_t bitCapacity );
void b2DestroyBitSet( b2BitSet* bitSet );
void b2SetBitCountAndClear( b2BitSet* bitSet, uint32_t bitCount );
void b2InPlaceUnion( b2BitSet* setA, const b2BitSet* setB );
void b2GrowBitSet( b2BitSet* bitSet, uint32_t blockCount );
static inline void b2SetBit( b2BitSet* bitSet, uint32_t bitIndex )
{
uint32_t blockIndex = bitIndex / 64;
B2_ASSERT( blockIndex < bitSet->blockCount );
bitSet->bits[blockIndex] |= ( (uint64_t)1 << bitIndex % 64 );
}
static inline void b2SetBitGrow( b2BitSet* bitSet, uint32_t bitIndex )
{
uint32_t blockIndex = bitIndex / 64;
if ( blockIndex >= bitSet->blockCount )
{
b2GrowBitSet( bitSet, blockIndex + 1 );
}
bitSet->bits[blockIndex] |= ( (uint64_t)1 << bitIndex % 64 );
}
static inline void b2ClearBit( b2BitSet* bitSet, uint32_t bitIndex )
{
uint32_t blockIndex = bitIndex / 64;
if ( blockIndex >= bitSet->blockCount )
{
return;
}
bitSet->bits[blockIndex] &= ~( (uint64_t)1 << bitIndex % 64 );
}
static inline bool b2GetBit( const b2BitSet* bitSet, uint32_t bitIndex )
{
uint32_t blockIndex = bitIndex / 64;
if ( blockIndex >= bitSet->blockCount )
{
return false;
}
return ( bitSet->bits[blockIndex] & ( (uint64_t)1 << bitIndex % 64 ) ) != 0;
}
static inline int b2GetBitSetBytes( b2BitSet* bitSet )
{
return bitSet->blockCapacity * sizeof( uint64_t );
}
| 0 | 0.974566 | 1 | 0.974566 | game-dev | MEDIA | 0.397469 | game-dev | 0.929684 | 1 | 0.929684 |
narknon/WukongB1 | 1,321 | Source/b1Managed/Public/BAIT_MoveToOnWallAndCell.h | #pragma once
#include "CoreMinimal.h"
#include "BAIT_Base.h"
#include "EAIMoveSpeedType.h"
#include "BAIT_MoveToOnWallAndCell.generated.h"
UCLASS(Blueprintable)
class UBAIT_MoveToOnWallAndCell : public UBAIT_Base {
GENERATED_BODY()
public:
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
float AcceptableRadius;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
uint8 IncludeSelfRadius: 1;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
FName TargetPointTag;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
EAIMoveSpeedType SpeedRateType;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
float turnSpeed;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
uint8 EnableRangeAcceptableRadius: 1;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
float MinAcceptableRadius;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
float MaxAcceptableRadius;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
uint8 EnableDebug: 1;
UBAIT_MoveToOnWallAndCell();
};
| 0 | 0.858372 | 1 | 0.858372 | game-dev | MEDIA | 0.914126 | game-dev | 0.67944 | 1 | 0.67944 |
RaphiMC/ViaBedrock | 42,536 | src/main/java/net/raphimc/viabedrock/protocol/packet/WorldEffectPackets.java | /*
* This file is part of ViaBedrock - https://github.com/RaphiMC/ViaBedrock
* Copyright (C) 2023-2025 RK_01/RaphiMC and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.raphimc.viabedrock.protocol.packet;
import com.viaversion.nbt.tag.CompoundTag;
import com.viaversion.nbt.tag.FloatTag;
import com.viaversion.viaversion.api.connection.UserConnection;
import com.viaversion.viaversion.api.minecraft.BlockPosition;
import com.viaversion.viaversion.api.minecraft.Holder;
import com.viaversion.viaversion.api.minecraft.Particle;
import com.viaversion.viaversion.api.protocol.packet.PacketWrapper;
import com.viaversion.viaversion.api.type.Types;
import com.viaversion.viaversion.api.type.types.version.VersionedTypes;
import com.viaversion.viaversion.protocols.v1_21_7to1_21_9.packet.ClientboundPackets1_21_9;
import com.viaversion.viaversion.util.Key;
import net.raphimc.viabedrock.ViaBedrock;
import net.raphimc.viabedrock.api.model.BlockState;
import net.raphimc.viabedrock.api.model.entity.Entity;
import net.raphimc.viabedrock.api.model.resourcepack.SoundDefinitions;
import net.raphimc.viabedrock.api.util.EnumUtil;
import net.raphimc.viabedrock.api.util.MathUtil;
import net.raphimc.viabedrock.api.util.PacketFactory;
import net.raphimc.viabedrock.protocol.BedrockProtocol;
import net.raphimc.viabedrock.protocol.ClientboundBedrockPackets;
import net.raphimc.viabedrock.protocol.data.BedrockMappingData;
import net.raphimc.viabedrock.protocol.data.enums.Dimension;
import net.raphimc.viabedrock.protocol.data.enums.Direction;
import net.raphimc.viabedrock.protocol.data.enums.bedrock.generated.LevelEvent;
import net.raphimc.viabedrock.protocol.data.enums.bedrock.generated.NoteBlockInstrument;
import net.raphimc.viabedrock.protocol.data.enums.bedrock.generated.ParticleType;
import net.raphimc.viabedrock.protocol.data.enums.bedrock.generated.SharedTypes_Legacy_LevelSoundEvent;
import net.raphimc.viabedrock.protocol.data.enums.java.GameEventType;
import net.raphimc.viabedrock.protocol.data.enums.java.PositionSourceType;
import net.raphimc.viabedrock.protocol.data.enums.java.SoundSource;
import net.raphimc.viabedrock.protocol.model.BedrockItem;
import net.raphimc.viabedrock.protocol.model.Position3f;
import net.raphimc.viabedrock.protocol.rewriter.BlockStateRewriter;
import net.raphimc.viabedrock.protocol.rewriter.ItemRewriter;
import net.raphimc.viabedrock.protocol.storage.ChunkTracker;
import net.raphimc.viabedrock.protocol.storage.EntityTracker;
import net.raphimc.viabedrock.protocol.types.BedrockTypes;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.logging.Level;
public class WorldEffectPackets {
// Only log warnings about missing mappings if explicitly enabled for debugging
// The Bedrock Dedicated Server sends a lot of unknown sound events which are expected to be ignored in most cases (Resource packs could add custom sounds for certain events)
private static final boolean LEVEL_SOUND_DEBUG_LOG = false;
public static void register(final BedrockProtocol protocol) {
protocol.registerClientbound(ClientboundBedrockPackets.PLAY_SOUND, ClientboundPackets1_21_9.SOUND, wrapper -> {
final String name = wrapper.read(BedrockTypes.STRING); // sound name
final BlockPosition position = wrapper.read(BedrockTypes.BLOCK_POSITION); // position
final float volume = wrapper.read(BedrockTypes.FLOAT_LE); // volume
final float pitch = wrapper.read(BedrockTypes.FLOAT_LE); // pitch
final BedrockMappingData.JavaSound javaSound = BedrockProtocol.MAPPINGS.getBedrockToJavaSounds().get(name);
if (javaSound == null) {
ViaBedrock.getPlatform().getLogger().log(Level.WARNING, "Unknown bedrock sound: " + name);
wrapper.cancel();
return;
}
wrapper.write(Types.SOUND_EVENT, Holder.of(javaSound.id())); // sound id
wrapper.write(Types.VAR_INT, javaSound.category().ordinal()); // category
wrapper.write(Types.INT, position.x()); // x
wrapper.write(Types.INT, position.y()); // y
wrapper.write(Types.INT, position.z()); // z
wrapper.write(Types.FLOAT, volume); // volume
wrapper.write(Types.FLOAT, pitch); // pitch
wrapper.write(Types.LONG, ThreadLocalRandom.current().nextLong()); // seed
});
protocol.registerClientbound(ClientboundBedrockPackets.STOP_SOUND, ClientboundPackets1_21_9.STOP_SOUND, wrapper -> {
final String name = wrapper.read(BedrockTypes.STRING); // sound name
final boolean stopAll = wrapper.read(Types.BOOLEAN); // stop all
wrapper.read(Types.BOOLEAN); // stop music | Ignored because it seems to do nothing
if (stopAll) {
wrapper.write(Types.BYTE, (byte) 0); // flags
} else {
final BedrockMappingData.JavaSound javaSound = BedrockProtocol.MAPPINGS.getBedrockToJavaSounds().get(name);
if (javaSound == null) {
ViaBedrock.getPlatform().getLogger().log(Level.WARNING, "Unknown bedrock sound: " + name);
wrapper.cancel();
return;
}
wrapper.write(Types.BYTE, (byte) 2); // flags
wrapper.write(Types.STRING, javaSound.identifier()); // sound identifier
}
});
protocol.registerClientbound(ClientboundBedrockPackets.SPAWN_PARTICLE_EFFECT, ClientboundPackets1_21_9.LEVEL_PARTICLES, wrapper -> {
final Dimension dimension = Dimension.getByValue(wrapper.read(Types.BYTE)); // dimension
if (dimension != wrapper.user().get(ChunkTracker.class).getDimension()) {
wrapper.cancel();
return;
}
wrapper.read(BedrockTypes.VAR_LONG); // unique entity id
final Position3f position = wrapper.read(BedrockTypes.POSITION_3F); // position
final String effectIdentifier = wrapper.read(BedrockTypes.STRING); // effect name
if (wrapper.read(Types.BOOLEAN)) { // has molang variables
wrapper.read(BedrockTypes.STRING); // molang variables json
}
final BedrockMappingData.JavaParticle javaParticle = BedrockProtocol.MAPPINGS.getBedrockToJavaParticles().get(effectIdentifier);
if (javaParticle == null) {
ViaBedrock.getPlatform().getLogger().log(Level.WARNING, "Unknown bedrock particle: " + effectIdentifier);
wrapper.cancel();
return;
}
PacketFactory.writeJavaLevelParticles(wrapper, position, switch (effectIdentifier) {
case "minecraft:eyeblossom_close", "minecraft:eyeblossom_open" -> {
final Particle particle = javaParticle.particle().copy();
particle.set(0, Types.DOUBLE, (double) position.x() + ThreadLocalRandom.current().nextFloat() - 0.5F); // target x
particle.set(1, Types.DOUBLE, (double) position.y() + ThreadLocalRandom.current().nextFloat() + 1.5F); // target y
particle.set(2, Types.DOUBLE, (double) position.z() + ThreadLocalRandom.current().nextFloat() - 0.5F); // target z
yield javaParticle.withParticle(particle);
}
default -> javaParticle;
});
});
protocol.registerClientbound(ClientboundBedrockPackets.LEVEL_SOUND_EVENT, ClientboundPackets1_21_9.SOUND, wrapper -> {
final int rawSoundEvent = wrapper.read(BedrockTypes.UNSIGNED_VAR_INT); // event id
final SharedTypes_Legacy_LevelSoundEvent soundEvent = SharedTypes_Legacy_LevelSoundEvent.getByValue(rawSoundEvent);
if (soundEvent == null) {
ViaBedrock.getPlatform().getLogger().log(Level.WARNING, "Unknown SharedTypes_Legacy_LevelSoundEvent: " + rawSoundEvent);
wrapper.cancel();
return;
}
final Position3f position = wrapper.read(BedrockTypes.POSITION_3F); // position
final int data = wrapper.read(BedrockTypes.VAR_INT); // data
final String entityIdentifier = wrapper.read(BedrockTypes.STRING); // entity identifier
final boolean isBabyMob = wrapper.read(Types.BOOLEAN); // is baby mob
final boolean isGlobal = wrapper.read(Types.BOOLEAN); // is global sound
wrapper.read(BedrockTypes.LONG_LE); // unique entity id
final boolean globalSound = isGlobal || Float.isNaN(position.x()) || Float.isNaN(position.y()) || Float.isNaN(position.z());
SoundDefinitions.ConfiguredSound configuredSound;
switch (soundEvent) {
case RecordNull -> {
wrapper.setPacketType(ClientboundPackets1_21_9.STOP_SOUND);
wrapper.write(Types.BYTE, (byte) 1); // flags
wrapper.write(Types.VAR_INT, SoundSource.RECORDS.ordinal()); // category id
return;
}
case Note -> {
final NoteBlockInstrument noteBlockInstrument = NoteBlockInstrument.getByValue(data >> 8, NoteBlockInstrument.Harp);
final String noteBlockSound = BedrockProtocol.MAPPINGS.getBedrockNoteBlockInstrumentSounds().get(noteBlockInstrument);
final int key = data & 0xFF;
final float pitch = (float) Math.pow(2D, (double) (key - 12) / 12);
configuredSound = new SoundDefinitions.ConfiguredSound(noteBlockSound, 1F, 1F, pitch, pitch);
}
default -> {
configuredSound = tryFindSound(wrapper.user(), soundEvent, data, entityIdentifier, isBabyMob);
if (configuredSound == null) { // Fallback for some special handled sounds
switch (soundEvent) {
case AmbientBaby, MobWarningBaby, HurtBaby, DeathBaby, StepBaby, SpawnBaby -> {
final SharedTypes_Legacy_LevelSoundEvent soundEventAdult = EnumUtil.getEnumConstantOrNull(SharedTypes_Legacy_LevelSoundEvent.class, soundEvent.name().replace("Baby", ""));
configuredSound = tryFindSound(wrapper.user(), soundEventAdult, data, entityIdentifier, true);
}
case AmbientInWater, AmbientInAir -> configuredSound = tryFindSound(wrapper.user(), SharedTypes_Legacy_LevelSoundEvent.Ambient, data, entityIdentifier, isBabyMob);
}
}
if (configuredSound == null) {
if (LEVEL_SOUND_DEBUG_LOG) {
ViaBedrock.getPlatform().getLogger().log(Level.WARNING, "Missing level sound event mapping for " + soundEvent + " with entity identifier '" + entityIdentifier + "' and data " + data);
}
wrapper.cancel();
return;
}
}
}
final BedrockMappingData.JavaSound javaSound = BedrockProtocol.MAPPINGS.getBedrockToJavaSounds().get(configuredSound.sound());
if (javaSound == null) {
ViaBedrock.getPlatform().getLogger().log(Level.WARNING, "Unknown bedrock sound: " + configuredSound.sound());
wrapper.cancel();
return;
}
wrapper.write(Types.SOUND_EVENT, Holder.of(javaSound.id())); // sound id
wrapper.write(Types.VAR_INT, javaSound.category().ordinal()); // category
wrapper.write(Types.INT, (int) (position.x() * 8F)); // x
wrapper.write(Types.INT, (int) (position.y() * 8F)); // y
wrapper.write(Types.INT, (int) (position.z() * 8F)); // z
wrapper.write(Types.FLOAT, globalSound ? Integer.MAX_VALUE : MathUtil.randomFloatInclusive(configuredSound.minVolume(), configuredSound.maxVolume())); // volume
wrapper.write(Types.FLOAT, MathUtil.randomFloatInclusive(configuredSound.minPitch(), configuredSound.maxPitch())); // pitch
wrapper.write(Types.LONG, ThreadLocalRandom.current().nextLong()); // seed
});
protocol.registerClientbound(ClientboundBedrockPackets.LEVEL_EVENT, ClientboundPackets1_21_9.LEVEL_EVENT, wrapper -> {
final int rawLevelEvent = wrapper.read(BedrockTypes.VAR_INT); // event id
final Position3f position = wrapper.read(BedrockTypes.POSITION_3F); // position
int data = wrapper.read(BedrockTypes.VAR_INT); // data
if ((rawLevelEvent & LevelEvent.ParticleLegacyEvent.getValue()) != 0 || rawLevelEvent == LevelEvent.ParticleGenericSpawn.getValue()) {
wrapper.setPacketType(ClientboundPackets1_21_9.LEVEL_PARTICLES);
final int rawParticleType = rawLevelEvent == LevelEvent.ParticleGenericSpawn.getValue() ? data : rawLevelEvent & ~LevelEvent.ParticleLegacyEvent.getValue();
final ParticleType particleType = ParticleType.getByValue(rawParticleType);
if (particleType == null) {
ViaBedrock.getPlatform().getLogger().log(Level.WARNING, "Unknown particle type: " + rawParticleType);
wrapper.cancel();
return;
}
if (rawLevelEvent == LevelEvent.ParticleGenericSpawn.getValue()) {
data = 0;
}
final BedrockMappingData.JavaParticle javaParticle = BedrockProtocol.MAPPINGS.getBedrockToJavaLevelEventParticles().get(particleType);
if (javaParticle != null) {
PacketFactory.writeJavaLevelParticles(wrapper, position, switch (particleType) {
case IconCrack, Food -> {
final BedrockItem bedrockItem = new BedrockItem(data >> 16, (short) (data & 0xFFFF), (byte) 1);
final Particle particle = new Particle(javaParticle.particle().id());
particle.add(VersionedTypes.V1_21_9.item, wrapper.user().get(ItemRewriter.class).javaItem(bedrockItem)); // item
yield javaParticle.withParticle(particle);
}
case Terrain, BrushDust -> {
final int javaBlockState = wrapper.user().get(BlockStateRewriter.class).javaId(data);
if (javaBlockState != -1) {
final Particle particle = new Particle(javaParticle.particle().id());
particle.add(Types.VAR_INT, javaBlockState); // block state
yield javaParticle.withParticle(particle);
} else {
ViaBedrock.getPlatform().getLogger().log(Level.WARNING, "Missing block state: " + data);
wrapper.cancel();
yield javaParticle;
}
}
case FallingDust -> {
final Particle particle = new Particle(javaParticle.particle().id());
particle.add(Types.INT, (0xFF << 24) | data); // from color
particle.add(Types.INT, (0xFF << 24) | data); // to color
particle.add(Types.FLOAT, 1F); // scale
yield javaParticle.withParticle(particle);
}
case MobSpell, MobSpellAmbient, MobSpellInstantaneous -> {
final Particle particle = new Particle(javaParticle.particle().id());
particle.add(Types.INT, (0xFF << 24) | data); // color
yield javaParticle.withParticle(particle);
}
case EyeblossomOpen, EyeblossomClose -> {
final Particle particle = javaParticle.particle().copy();
particle.set(0, Types.DOUBLE, (double) position.x() + ThreadLocalRandom.current().nextFloat() - 0.5F); // target x
particle.set(1, Types.DOUBLE, (double) position.y() + ThreadLocalRandom.current().nextFloat() + 1.5F); // target y
particle.set(2, Types.DOUBLE, (double) position.z() + ThreadLocalRandom.current().nextFloat() - 0.5F); // target z
yield javaParticle.withParticle(particle);
}
default -> javaParticle;
});
} else {
ViaBedrock.getPlatform().getLogger().log(Level.WARNING, "Missing level event particle mapping for " + particleType);
wrapper.cancel();
}
return;
}
final LevelEvent levelEvent = LevelEvent.getByValue(rawLevelEvent);
if (levelEvent == null) {
ViaBedrock.getPlatform().getLogger().log(Level.WARNING, "Unknown LevelEvent: " + rawLevelEvent);
wrapper.cancel();
return;
}
switch (levelEvent) {
case ParticleSoundGuardianGhost -> {
PacketFactory.sendJavaGameEvent(wrapper.user(), GameEventType.GUARDIAN_ELDER_EFFECT, 1F);
wrapper.cancel();
}
case StartRaining -> {
PacketFactory.sendJavaGameEvent(wrapper.user(), GameEventType.START_RAINING, 0F);
PacketFactory.sendJavaGameEvent(wrapper.user(), GameEventType.RAIN_LEVEL_CHANGE, data / 65535F);
wrapper.cancel();
}
case StopRaining -> {
PacketFactory.sendJavaGameEvent(wrapper.user(), GameEventType.STOP_RAINING, 0F);
PacketFactory.sendJavaGameEvent(wrapper.user(), GameEventType.RAIN_LEVEL_CHANGE, 0F);
wrapper.cancel();
}
case StartThunderstorm -> {
PacketFactory.sendJavaGameEvent(wrapper.user(), GameEventType.START_RAINING, 0F);
PacketFactory.sendJavaGameEvent(wrapper.user(), GameEventType.THUNDER_LEVEL_CHANGE, data / 65535F);
wrapper.cancel();
}
case StopThunderstorm -> {
PacketFactory.sendJavaGameEvent(wrapper.user(), GameEventType.THUNDER_LEVEL_CHANGE, 0F);
wrapper.cancel();
}
case GlobalPause -> {
if (data != 0) {
ViaBedrock.getPlatform().getLogger().log(Level.SEVERE, "Server paused the game. This is not supported by ViaBedrock.");
}
wrapper.cancel();
}
case SimTimeStep -> {
ViaBedrock.getPlatform().getLogger().log(Level.SEVERE, "Server tick stepped the game. This is not supported by ViaBedrock.");
wrapper.cancel();
}
case SimTimeScale -> {
ViaBedrock.getPlatform().getLogger().log(Level.SEVERE, "Server sped up the game. This is not supported by ViaBedrock.");
wrapper.cancel();
}
case StartBlockCracking, StopBlockCracking, UpdateBlockCracking -> {
wrapper.cancel(); // TODO: Implement block break progress translation
}
default -> {
BedrockMappingData.LevelEventMapping levelEventMapping = BedrockProtocol.MAPPINGS.getBedrockToJavaLevelEvents().get(levelEvent);
if (levelEventMapping instanceof BedrockMappingData.JavaSoundLevelEvent javaSoundLevelEvent) {
if (data == 0) {
levelEventMapping = javaSoundLevelEvent.levelEvent();
} else {
levelEventMapping = javaSoundLevelEvent.sound();
}
}
if (levelEventMapping instanceof BedrockMappingData.JavaLevelEvent javaLevelEvent) {
wrapper.write(Types.INT, javaLevelEvent.levelEvent().getValue()); // event id
wrapper.write(Types.BLOCK_POSITION1_14, new BlockPosition((int) position.x(), (int) position.y(), (int) position.z())); // position
wrapper.write(Types.INT, switch (levelEvent) {
case ParticlesShoot, ParticlesShootWhiteSmoke -> switch (data % 9) {
case 3, 0 -> Direction.WEST.ordinal();
case 4 -> Direction.UP.ordinal();
case 5, 8 -> Direction.EAST.ordinal();
case 7, 6 -> Direction.SOUTH.ordinal();
default /* 1, 2 */ -> Direction.NORTH.ordinal();
};
case ParticlesDestroyBlock, ParticlesDestroyBlockNoSound -> {
final int javaBlockState = wrapper.user().get(BlockStateRewriter.class).javaId(data);
if (javaBlockState != -1) {
yield javaBlockState;
} else {
ViaBedrock.getPlatform().getLogger().log(Level.WARNING, "Missing block state: " + data);
wrapper.cancel();
yield 0;
}
}
default -> javaLevelEvent.data() != null ? javaLevelEvent.data() : data;
}); // data
wrapper.write(Types.BOOLEAN, false); // global
} else if (levelEventMapping instanceof BedrockMappingData.JavaSound javaSound) {
wrapper.setPacketType(ClientboundPackets1_21_9.SOUND);
wrapper.write(Types.SOUND_EVENT, Holder.of(javaSound.id())); // sound id
wrapper.write(Types.VAR_INT, javaSound.category().ordinal()); // category
wrapper.write(Types.INT, (int) (position.x() * 8F)); // x
wrapper.write(Types.INT, (int) (position.y() * 8F)); // y
wrapper.write(Types.INT, (int) (position.z() * 8F)); // z
wrapper.write(Types.FLOAT, 1F); // volume
wrapper.write(Types.FLOAT, switch (levelEvent) {
case SoundClick, SoundClickFail, SoundOpenDoor, SoundFizz, SoundInfinityArrowPickup, SoundAmethystResonate -> {
yield data > 0 && data <= 256_000 ? (data / 1000F) : 1F;
}
default -> 1F;
}); // pitch
wrapper.write(Types.LONG, ThreadLocalRandom.current().nextLong()); // seed
} else if (levelEventMapping instanceof BedrockMappingData.JavaParticle javaParticle) {
wrapper.setPacketType(ClientboundPackets1_21_9.LEVEL_PARTICLES);
PacketFactory.writeJavaLevelParticles(wrapper, switch (levelEvent) {
case ParticlesCrackBlockDown -> new Position3f(MathUtil.floor(position.x()) + 0.5F, MathUtil.floor(position.y()), MathUtil.floor(position.z()) + 0.5F);
case ParticlesCrackBlockUp -> new Position3f(MathUtil.floor(position.x()) + 0.5F, MathUtil.floor(position.y()) + 1F, MathUtil.floor(position.z()) + 0.5F);
case ParticlesCrackBlockNorth -> new Position3f(MathUtil.floor(position.x()) + 0.5F, MathUtil.floor(position.y()) + 0.5F, MathUtil.floor(position.z()));
case ParticlesCrackBlockSouth -> new Position3f(MathUtil.floor(position.x()) + 0.5F, MathUtil.floor(position.y()) + 0.5F, MathUtil.floor(position.z()) + 1F);
case ParticlesCrackBlockWest -> new Position3f(MathUtil.floor(position.x()), MathUtil.floor(position.y()) + 0.5F, MathUtil.floor(position.z()) + 0.5F);
case ParticlesCrackBlockEast -> new Position3f(MathUtil.floor(position.x()) + 1F, MathUtil.floor(position.y()) + 0.5F, MathUtil.floor(position.z()) + 0.5F);
default -> position;
}, switch (levelEvent) {
case ParticlesCrit -> javaParticle.withCount(data);
case ParticlesCrackBlock, ParticlesCrackBlockDown, ParticlesCrackBlockUp, ParticlesCrackBlockNorth,
ParticlesCrackBlockSouth, ParticlesCrackBlockWest, ParticlesCrackBlockEast -> {
final int javaBlockState = wrapper.user().get(BlockStateRewriter.class).javaId(data);
if (javaBlockState != -1) {
final Particle particle = new Particle(javaParticle.particle().id());
particle.add(Types.VAR_INT, javaBlockState); // block state
yield javaParticle.withParticle(particle);
} else {
ViaBedrock.getPlatform().getLogger().log(Level.WARNING, "Missing block state: " + data);
wrapper.cancel();
yield javaParticle;
}
}
default -> javaParticle;
});
} else if (levelEventMapping == null) {
ViaBedrock.getPlatform().getLogger().log(Level.WARNING, "Missing level event mapping for " + levelEvent);
wrapper.cancel();
} else {
throw new IllegalStateException("Unknown level event mapping type: " + levelEventMapping.getClass().getName());
}
}
}
});
protocol.registerClientbound(ClientboundBedrockPackets.LEVEL_EVENT_GENERIC, ClientboundPackets1_21_9.LEVEL_PARTICLES, wrapper -> {
final int rawLevelEvent = wrapper.read(BedrockTypes.VAR_INT); // event id
final CompoundTag data = (CompoundTag) wrapper.read(BedrockTypes.COMPOUND_TAG_VALUE); // data
final LevelEvent levelEvent = LevelEvent.getByValue(rawLevelEvent);
if (levelEvent == null) {
ViaBedrock.getPlatform().getLogger().log(Level.WARNING, "Unknown LevelEvent: " + rawLevelEvent);
wrapper.cancel();
return;
}
switch (levelEvent) {
case ParticlesTeleportTrail -> {
wrapper.cancel();
final Position3f startPosition = new Position3f(data.getFloat("Startx"), data.getFloat("Starty"), data.getFloat("Startz"));
final Position3f endPosition = new Position3f(data.getFloat("Endx"), data.getFloat("Endy"), data.getFloat("Endz"));
final float dirScale = data.getFloat("DirScale");
final float variationX = data.getFloat("Variationx");
final float variationY = data.getFloat("Variationy");
final int count = data.getInt("Count");
for (int i = 0; i < count; i++) {
final float progress = i / (count - 1F);
final Position3f position = new Position3f(
MathUtil.lerp(progress, startPosition.x(), endPosition.x()) + (ThreadLocalRandom.current().nextFloat() - 0.5F) * variationX * 2F,
MathUtil.lerp(progress, startPosition.y(), endPosition.y()) + (ThreadLocalRandom.current().nextFloat() - 0.5F) * variationY * 2F - 1F,
MathUtil.lerp(progress, startPosition.z(), endPosition.z()) + (ThreadLocalRandom.current().nextFloat() - 0.5F) * variationX * 2F
);
final BedrockMappingData.JavaParticle javaParticle = new BedrockMappingData.JavaParticle(
new Particle(BedrockProtocol.MAPPINGS.getJavaParticles().get("minecraft:portal")),
(ThreadLocalRandom.current().nextFloat() - 0.5F) * dirScale,
(ThreadLocalRandom.current().nextFloat() - 0.5F) * dirScale,
(ThreadLocalRandom.current().nextFloat() - 0.5F) * dirScale,
1F,
0
);
PacketFactory.sendJavaLevelParticles(wrapper.user(), position, javaParticle);
}
}
case ParticlesBlockExplosion -> {
wrapper.cancel();
final Position3f originPosition = new Position3f(data.getFloat("originX"), data.getFloat("originY"), data.getFloat("originZ"));
final float radius = data.getFloat("radius");
final int blockCount = data.getInt("size");
for (int i = 0; i < blockCount; i++) {
final Position3f position = new Position3f(data.getFloat("pos" + i + "x"), data.getFloat("pos" + i + "y"), data.getFloat("pos" + i + "z"));
final Particle particle = new Particle(BedrockProtocol.MAPPINGS.getJavaParticles().get("minecraft:smoke"));
PacketFactory.sendJavaLevelParticles(wrapper.user(), position, new BedrockMappingData.JavaParticle(particle, 0F, 0F, 0F, 0F, 0));
}
}
case ParticlesVibrationSignal -> {
if (data.get("origin") instanceof CompoundTag origin && data.get("target") instanceof CompoundTag target && data.get("timeToLive") instanceof FloatTag timeToLive) {
final Position3f originPosition = new Position3f(origin.getFloat("x"), origin.getFloat("y"), origin.getFloat("z"));
final Particle particle = new Particle(BedrockProtocol.MAPPINGS.getJavaParticles().get("minecraft:vibration"));
switch (target.getString("type", "")) {
case "vec3" -> {
final Position3f targetPosition = new Position3f(target.getFloat("x"), target.getFloat("y"), target.getFloat("z"));
particle.add(Types.VAR_INT, PositionSourceType.BLOCK.ordinal()); // destination type
particle.add(Types.BLOCK_POSITION1_14, new BlockPosition((int) targetPosition.x(), (int) targetPosition.y(), (int) targetPosition.z())); // destination block pos
}
case "actor" -> {
final Entity entity = wrapper.user().get(EntityTracker.class).getEntityByUid(target.getLong("uniqueID"));
if (entity == null) {
wrapper.cancel();
return;
}
particle.add(Types.VAR_INT, PositionSourceType.ENTITY.ordinal()); // destination type
particle.add(Types.VAR_INT, entity.javaId()); // destination entity
particle.add(Types.FLOAT, 0F); // y offset
}
default -> {
wrapper.cancel();
return;
}
}
particle.add(Types.VAR_INT, (int) (timeToLive.asFloat() * 20F)); // arrival in ticks
PacketFactory.writeJavaLevelParticles(wrapper, originPosition, new BedrockMappingData.JavaParticle(particle, 0F, 0F, 0F, 0F, 0));
} else {
wrapper.cancel();
}
}
case ParticlesSculkShriek -> {
wrapper.cancel();
final Position3f position = new Position3f(data.getInt("originX") + 0.5F, data.getInt("originY") + 0.5F, data.getInt("originZ") + 0.5F);
for (int i = 0; i < 15; i++) {
final Particle particle = new Particle(BedrockProtocol.MAPPINGS.getJavaParticles().get("minecraft:shriek"));
particle.add(Types.VAR_INT, i * 5); // delay
PacketFactory.sendJavaLevelParticles(wrapper.user(), position, new BedrockMappingData.JavaParticle(particle, 0F, 0F, 0F, 0F, 0));
}
}
case SculkCatalystBloom -> {
final Position3f position = new Position3f(data.getFloat("originX"), data.getFloat("originY"), data.getFloat("originZ"));
final Particle particle = new Particle(BedrockProtocol.MAPPINGS.getJavaParticles().get("minecraft:sculk_soul"));
PacketFactory.writeJavaLevelParticles(wrapper, new Position3f(position.x() + 0.5F, position.y() + 1.15F, position.z() + 0.5F), new BedrockMappingData.JavaParticle(particle, 0F, 0F, 0F, 0F, 0));
final PacketWrapper sound = PacketWrapper.create(ClientboundPackets1_21_9.SOUND, wrapper.user());
sound.write(Types.SOUND_EVENT, Holder.of((int) BedrockProtocol.MAPPINGS.getJavaSounds().get("minecraft:block.sculk_catalyst.bloom"))); // sound id
sound.write(Types.VAR_INT, SoundSource.BLOCKS.ordinal()); // category
sound.write(Types.INT, (int) (position.x() * 8F)); // x
sound.write(Types.INT, (int) (position.y() * 8F)); // y
sound.write(Types.INT, (int) (position.z() * 8F)); // z
sound.write(Types.FLOAT, 2F); // volume
sound.write(Types.FLOAT, 0.6F + ThreadLocalRandom.current().nextFloat() * 0.4F); // pitch
sound.write(Types.LONG, ThreadLocalRandom.current().nextLong()); // seed
sound.send(BedrockProtocol.class);
}
case SculkCharge -> {
wrapper.setPacketType(ClientboundPackets1_21_9.LEVEL_EVENT);
wrapper.write(Types.INT, net.raphimc.viabedrock.protocol.data.enums.java.LevelEvent.PARTICLES_SCULK_CHARGE.getValue()); // event id
wrapper.write(Types.BLOCK_POSITION1_14, new BlockPosition(data.getInt("x"), data.getInt("y"), data.getInt("z"))); // position
wrapper.write(Types.INT, (data.getShort("charge") << 6) | (data.getShort("facing") & 0x3F)); // data
wrapper.write(Types.BOOLEAN, false); // global
}
case SculkChargePop -> {
final Position3f position = new Position3f(data.getInt("x") + 0.5F, data.getInt("y") + 0.5F, data.getInt("z") + 0.5F);
final Particle particle = new Particle(BedrockProtocol.MAPPINGS.getJavaParticles().get("minecraft:sculk_charge_pop"));
PacketFactory.writeJavaLevelParticles(wrapper, position, new BedrockMappingData.JavaParticle(particle, 0F, 0F, 0F, 0.04F, 20));
}
case SonicExplosion -> {
final Position3f position = new Position3f(data.getFloat("x"), data.getFloat("y"), data.getFloat("z"));
final Particle particle = new Particle(BedrockProtocol.MAPPINGS.getJavaParticles().get("minecraft:sonic_boom"));
PacketFactory.writeJavaLevelParticles(wrapper, position, new BedrockMappingData.JavaParticle(particle, 0F, 0F, 0F, 0F, 0));
}
case DustPlume -> {
final Position3f position = new Position3f(data.getFloat("x"), data.getFloat("y"), data.getFloat("z"));
final Particle particle = new Particle(BedrockProtocol.MAPPINGS.getJavaParticles().get("minecraft:dust_plume"));
PacketFactory.writeJavaLevelParticles(wrapper, position, new BedrockMappingData.JavaParticle(particle, 0F, 0F, 0F, 0F, 7));
}
case SleepingPlayers -> {
// This shows the amount of players currently sleeping when in a bed
wrapper.cancel(); // TODO: Implement translation
}
case ParticleCreakingHeartTrail -> {
wrapper.cancel();
final Position3f creakingPosition = new Position3f(data.getFloat("CreakingX"), data.getFloat("CreakingY"), data.getFloat("CreakingZ"));
final Position3f heartPosition = new Position3f(data.getFloat("HeartX"), data.getFloat("HeartY"), data.getFloat("HeartZ"));
final int heartAmount = data.getInt("HeartAmount");
final int creakingAmount = data.getInt("CreakingAmount");
for (int i = 0; i < heartAmount; i++) {
final Particle particle = new Particle(BedrockProtocol.MAPPINGS.getJavaParticles().get("minecraft:trail"));
particle.add(Types.DOUBLE, (double) heartPosition.x() + ThreadLocalRandom.current().nextFloat()); // target x
particle.add(Types.DOUBLE, (double) heartPosition.y() + ThreadLocalRandom.current().nextFloat()); // target y
particle.add(Types.DOUBLE, (double) heartPosition.z() + ThreadLocalRandom.current().nextFloat()); // target z
particle.add(Types.INT, 6250335); // color
particle.add(Types.VAR_INT, ThreadLocalRandom.current().nextInt(40) + 10); // duration
PacketFactory.sendJavaLevelParticles(wrapper.user(), creakingPosition, new BedrockMappingData.JavaParticle(particle, 0.5F, 1F, 0.5F, 0F, 1));
}
for (int i = 0; i < creakingAmount; i++) {
final Particle particle = new Particle(BedrockProtocol.MAPPINGS.getJavaParticles().get("minecraft:trail"));
particle.add(Types.DOUBLE, (double) creakingPosition.x() + ThreadLocalRandom.current().nextFloat() * 2F); // target x
particle.add(Types.DOUBLE, (double) creakingPosition.y() + ThreadLocalRandom.current().nextFloat() * 2F); // target y
particle.add(Types.DOUBLE, (double) creakingPosition.z() + ThreadLocalRandom.current().nextFloat() * 2F); // target z
particle.add(Types.INT, 16545810); // color
particle.add(Types.VAR_INT, ThreadLocalRandom.current().nextInt(40) + 10); // duration
PacketFactory.sendJavaLevelParticles(wrapper.user(), heartPosition, new BedrockMappingData.JavaParticle(particle, 0.5F, 0.5F, 0.5F, 0F, 1));
}
}
default -> {
ViaBedrock.getPlatform().getLogger().log(Level.WARNING, "Unhandled generic level event: " + levelEvent + " (" + data + ")");
wrapper.cancel();
}
}
});
}
private static SoundDefinitions.ConfiguredSound tryFindSound(final UserConnection user, final SharedTypes_Legacy_LevelSoundEvent soundEvent, final int data, final String entityIdentifier, final boolean isBabyMob) {
if (soundEvent == null) {
return null;
}
final Map<String, SoundDefinitions.ConfiguredSound> soundEvents = BedrockProtocol.MAPPINGS.getBedrockLevelSoundEvents().get(soundEvent);
if (soundEvents == null) {
return null;
}
SoundDefinitions.ConfiguredSound configuredSound = null;
if (!entityIdentifier.isEmpty()) { // entity specific sound
configuredSound = soundEvents.get(Key.namespaced(entityIdentifier));
if (isBabyMob && configuredSound != null) {
configuredSound = new SoundDefinitions.ConfiguredSound(configuredSound.sound(), configuredSound.minVolume(), configuredSound.maxVolume(), configuredSound.minPitch() + 0.5F, configuredSound.maxPitch() + 0.5F);
}
}
if (configuredSound == null && data != -1) { // block specific sound
final BlockState blockState = user.get(BlockStateRewriter.class).blockState(data);
if (blockState != null) {
final String blockSound = BedrockProtocol.MAPPINGS.getBedrockBlockSounds().get(blockState.namespacedIdentifier());
if (blockSound != null) {
configuredSound = soundEvents.get(blockSound);
} else {
if (LEVEL_SOUND_DEBUG_LOG) {
ViaBedrock.getPlatform().getLogger().log(Level.WARNING, "Missing " + soundEvent.name() + " sound for " + blockState.namespacedIdentifier());
}
configuredSound = soundEvents.get("stone");
}
} else {
if (LEVEL_SOUND_DEBUG_LOG) {
ViaBedrock.getPlatform().getLogger().log(Level.WARNING, "Missing block state (" + soundEvent.name() + " level sound event): " + data);
}
configuredSound = soundEvents.get("stone");
}
}
if (configuredSound == null) {
configuredSound = soundEvents.get(null); // generic sound
}
return configuredSound;
}
}
| 0 | 0.728433 | 1 | 0.728433 | game-dev | MEDIA | 0.74785 | game-dev,networking | 0.908706 | 1 | 0.908706 |
latte-soft/datamodelpatch | 8,607 | src/PatchRoot/DataModelInstances/CoreGui/RobloxGui/Modules/InspectAndBuy/Components/DetailsText.luau | local l_CorePackages_0 = game:GetService("CorePackages");
local l_CoreGui_0 = game:GetService("CoreGui");
local l_Parent_0 = script.Parent.Parent;
local v3 = require(l_CorePackages_0.Roact);
local v4 = require(l_CorePackages_0.RoactRodux);
local v5 = require(l_CorePackages_0.Cryo);
local v6 = require(l_CorePackages_0.UIBlox);
local v7 = require(l_CorePackages_0.Workspace.Packages.VerifiedBadges);
local l_AppFonts_0 = require(l_CorePackages_0.Workspace.Packages.Style).AppFonts;
local l_Images_0 = v6.App.ImageSet.Images;
local l_IconSize_0 = v6.App.Constant.IconSize;
local v11 = require(l_Parent_0.Components.Notification);
local v12 = require(l_Parent_0.Components.Favorites);
local v13 = require(l_Parent_0.UtilityFunctions);
local v14 = require(l_Parent_0.Colors);
local v15 = require(l_Parent_0.Constants);
local v16 = require(l_CoreGui_0.RobloxGui.Modules.RobloxTranslator);
local v17 = require(l_Parent_0.getSelectionImageObjectRegular);
local v18 = require(l_Parent_0.Components.InspectAndBuyContext);
local v19 = require(l_Parent_0.Flags.FFlagAttributionInInspectAndBuy);
local v20 = require(l_Parent_0.Flags.GetFFlagIBEnableCollectiblesSystemSupport);
local v21 = require(l_Parent_0.Flags.GetFFlagIBEnableLimitedItemBugFixAndAlignment);
local v22 = require(l_Parent_0.Flags.GetFFlagIBEnableNewDataCollectionForCollectibleSystem);
local v23 = require(l_Parent_0.Flags.GetFFlagIBEnableLimitedBundle);
local v24 = l_Images_0["icons/status/premium"];
local v25 = v3.PureComponent:extend("DetailsText");
v25.init = function(v26)
v26.name = "";
v26.creator = "";
v26.selectedImage = v17();
end;
v25.setText = function(v27)
local v28 = v27.props.assetInfo or {};
local v29 = v28.bundlesAssetIsIn and #v28.bundlesAssetIsIn == 1;
if v22() then
v29 = v28.parentBundleId ~= nil;
end;
local v30 = v29 and not v28.isForSale;
if v23() then
v30 = v29;
end;
local v31 = v27.props.bundleInfo or {};
if not v30 then
if v28 then
v27.name = v28.name or "";
v27.creator = v28.creatorName or "";
end;
else
local v32 = v13.getBundleId(v28);
if v31[v32] then
v27.name = v31[v32].name or "";
v27.creator = v31[v32].creatorName or "";
return ;
end;
end;
end;
v25.render = function(v33)
v33:setText();
local l_view_0 = v33.props.view;
local l_locale_0 = v33.props.locale;
local l_showFavoritesCount_0 = v33.props.showFavoritesCount;
local v37 = v33.props.assetInfo or {};
local v38 = v37.bundlesAssetIsIn and #v37.bundlesAssetIsIn == 1;
local v39 = v37.bundlesAssetIsIn and #v37.bundlesAssetIsIn > 1;
if v22() then
v38 = v37.parentBundleId ~= nil;
v39 = v38 and #v33.props.assetBundles[v37.assetId] > 1;
end;
local v40 = v37.premiumPricing ~= nil;
local v41 = v37.creatorHasVerifiedBadge or false;
local v42 = not not v40 and l_IconSize_0.Regular + 5 or 0;
local v43 = false;
if v15.LayeredAssetTypes[v37.assetTypeId] ~= nil then
v43 = v33.props.localPlayerModel and v33.props.localPlayerModel.Humanoid.RigType == Enum.HumanoidRigType.R6;
end;
local v44 = v37.isLimited or v20() and v37.isLimitedUnique;
if v21() then
v44 = v13.isLimited1Point0(v37);
end;
local v45 = nil;
if not v39 then
if not v38 then
if not v44 then
if v43 then
v45 = v15.NotificationKeys.LayeredClothingOnR6Key;
end;
else
v45 = v15.NotificationKeys.LimitedItemNoticeKey;
end;
else
v45 = v15.NotificationKeys.SingleBundleNoticeKey;
end;
else
v45 = v15.NotificationKeys.MultipleBundleNoticeKey;
end;
return v3.createElement(v18.Consumer, {
render = function(v46)
return v3.createElement("Frame", {
Position = v46[l_view_0].DetailsFramePosition,
Size = UDim2.new(1, 0, 0, 131),
BackgroundTransparency = 1,
LayoutOrder = 1
}, {
Layout = v3.createElement("UIListLayout", {
SortOrder = Enum.SortOrder.LayoutOrder,
HorizontalAlignment = Enum.HorizontalAlignment.Left,
VerticalAlignment = Enum.VerticalAlignment.Top,
FillDirection = Enum.FillDirection.Vertical
}),
Notification = v45 and v3.createElement(v11, {
noticeKey = v45
}),
AssetName = v3.createElement("Frame", {
BackgroundTransparency = 1,
Size = UDim2.new(1, -10, 0, 50),
LayoutOrder = 1
}, {
PremiumIcon = not not v40 and v3.createElement("ImageLabel", v5.Dictionary.join(v24, {
AnchorPoint = Vector2.new(0, 0.5),
Position = UDim2.new(0, 0, 0.5, 0),
BackgroundTransparency = 1,
Size = UDim2.new(0, l_IconSize_0.Regular, 0, l_IconSize_0.Regular),
ImageColor3 = Color3.new(1, 1, 1)
})) or nil,
PlayerName = v3.createElement("TextLabel", {
BackgroundTransparency = 1,
Position = UDim2.new(0, v42, 0, 0),
Size = UDim2.new(1, v42, 0, 50),
LayoutOrder = 1,
Text = v33.name or "",
TextXAlignment = Enum.TextXAlignment.Left,
TextYAlignment = Enum.TextYAlignment.Center,
TextScaled = true,
TextSize = 20,
Font = l_AppFonts_0.default:getBold(),
TextColor3 = v14.White
}, {
UITextSizeConstraint = v3.createElement("UITextSizeConstraint", {
MaxTextSize = 32
})
})
}) or v3.createElement("TextLabel", {
BackgroundTransparency = 1,
Size = UDim2.new(1, -10, 0, 50),
LayoutOrder = 1,
Text = v33.name or "",
TextXAlignment = Enum.TextXAlignment.Left,
TextYAlignment = Enum.TextYAlignment.Center,
TextScaled = true,
TextSize = 20,
Font = l_AppFonts_0.default:getBold(),
TextColor3 = v14.White
}, {
UITextSizeConstraint = v3.createElement("UITextSizeConstraint", {
MaxTextSize = 32
})
}),
CreatorLabelContainer = if not v19 then v3.createElement("Frame", {
BackgroundTransparency = 1,
LayoutOrder = 2,
Size = UDim2.new(1, 0, 0, 20)
}, {
CreatorLabelWrapper = v3.createElement(v7.EmojiWrapper, {
emoji = not v41 and "" or v7.emoji.verified
}, {
CreatorLabel = v3.createElement("TextLabel", {
AutomaticSize = Enum.AutomaticSize.XY,
BackgroundTransparency = 1,
Text = v16:FormatByKeyForLocale("InGame.InspectMenu.Label.By", l_locale_0, {
CREATOR = v33.creator
}),
Font = l_AppFonts_0.default:getDefault(),
TextScaled = false,
TextSize = 12,
TextColor3 = v14.White,
TextXAlignment = Enum.TextXAlignment.Left,
TextYAlignment = Enum.TextYAlignment.Center
})
})
}) else nil,
FavoriteContainer = l_showFavoritesCount_0 and v3.createElement(v12)
});
end
});
end;
return v4.connect(function(v47, _)
return {
view = v47.view,
locale = v47.locale,
assetInfo = v47.assets[v47.detailsInformation.assetId],
bundleInfo = v47.bundles,
assetBundles = if not v22() then nil else v47.assetBundles,
showFavoritesCount = not v47.isSubjectToChinaPolicies
};
end)(v25);
| 0 | 0.826011 | 1 | 0.826011 | game-dev | MEDIA | 0.48301 | game-dev | 0.92234 | 1 | 0.92234 |
AU-Avengers/TOU-Mira | 3,826 | TownOfUs/Patches/Roles/MeetingHudTimerPatch.cs | using HarmonyLib;
using MiraAPI.GameOptions;
using MiraAPI.Modifiers;
using TownOfUs.Events;
using TownOfUs.Modifiers.Game;
using TownOfUs.Options;
using TownOfUs.Options.Roles.Crewmate;
using TownOfUs.Options.Roles.Impostor;
using TownOfUs.Options.Roles.Neutral;
using TownOfUs.Roles.Crewmate;
using TownOfUs.Roles.Impostor;
using TownOfUs.Roles.Neutral;
using TownOfUs.Utilities;
namespace TownOfUs.Patches.Roles;
[HarmonyPatch(typeof(MeetingHud))]
public static class MeetingHudTimerPatch
{
[HarmonyPostfix]
[HarmonyPatch(nameof(MeetingHud.UpdateTimerText))]
public static void TimerUpdatePostfix(MeetingHud __instance)
{
var newText = string.Empty;
if (PlayerControl.LocalPlayer == null || PlayerControl.LocalPlayer.Data == null || PlayerControl.LocalPlayer.HasDied()) return;
switch (PlayerControl.LocalPlayer.Data.Role)
{
case AmbassadorRole ambass:
var ambassOpt = OptionGroupSingleton<AmbassadorOptions>.Instance;
newText = $"\n{ambass.RetrainsAvailable} / {ambassOpt.MaxRetrains} Retrains Remaining";
if (DeathEventHandlers.CurrentRound < (int)ambassOpt.RoundWhenAvailable)
{
newText = $"{newText} | Retrain on Round {(int)ambassOpt.RoundWhenAvailable}";
}
else if (ambass.RoundsCooldown > 0)
{
newText = $"{newText} | Round Cooldown: {ambass.RoundsCooldown} / {(int)ambassOpt.RoundCooldown}";
}
break;
case ProsecutorRole pros:
var prosecutes = OptionGroupSingleton<ProsecutorOptions>.Instance.MaxProsecutions - pros.ProsecutionsCompleted;
newText = $"\n{prosecutes} / {OptionGroupSingleton<ProsecutorOptions>.Instance.MaxProsecutions} Prosecutions Remaining";
break;
case DeputyRole dep:
if (dep.Killer) newText = "\nShoot a player successfully if they were the killer!";
break;
case PoliticianRole:
newText = "\nReveal successfully if half the crewmates are campaigned!";
break;
case MayorRole mayor:
newText = mayor.Revealed ? "\nYou unleash 3 votes at once!" : "\nReveal yourself to get 3 total votes!";
break;
case DoomsayerRole doom:
var doomOpt = OptionGroupSingleton<DoomsayerOptions>.Instance;
newText = doomOpt.DoomsayerGuessAllAtOnce ? $"\nGuess the roles of {(int)doomOpt.DoomsayerGuessesToWin} players at once to win!" : $"\n{doom.NumberOfGuesses} / {(int)doomOpt.DoomsayerGuessesToWin} Successful Role Guesses to win!";
break;
case VigilanteRole vigi:
newText = $"\n{vigi.MaxKills} / {(int)OptionGroupSingleton<VigilanteOptions>.Instance.VigilanteKills} Guesses Remaining";
if ((int)OptionGroupSingleton<VigilanteOptions>.Instance.MultiShots > 0)
{
newText += $" | {vigi.SafeShotsLeft} / {(int)OptionGroupSingleton<VigilanteOptions>.Instance.MultiShots} Safe Shots";
}
break;
}
if (PlayerControl.LocalPlayer.TryGetModifier<AssassinModifier>(out var assassinMod))
{
newText += $"\n{assassinMod.maxKills} / {(int)OptionGroupSingleton<AssassinOptions>.Instance.AssassinKills} Guesses Remaining";
if ((PlayerControl.LocalPlayer.TryGetModifier<DoubleShotModifier>(out var doubleShotMod)))
{
newText += (doubleShotMod.Used) ? " | Double Shot Used" : " | Double Shot Available";
}
}
if (newText != string.Empty) __instance.TimerText.text += $"<color=#FFFFFF>{newText}</color>";
}
} | 0 | 0.98304 | 1 | 0.98304 | game-dev | MEDIA | 0.977437 | game-dev | 0.977577 | 1 | 0.977577 |
electronicarts/CnC_Generals_Zero_Hour | 33,143 | Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainTracks.cpp | /*
** Command & Conquer Generals(tm)
** Copyright 2025 Electronic Arts Inc.
**
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
////////////////////////////////////////////////////////////////////////////////
// //
// (c) 2001-2003 Electronic Arts Inc. //
// //
////////////////////////////////////////////////////////////////////////////////
// FILE: W3DTerrainTracks.cpp ////////////////////////////////////////////////
//-----------------------------------------------------------------------------
//
// Westwood Studios Pacific.
//
// Confidential Information
// Copyright (C) 2001 - All Rights Reserved
//
//-----------------------------------------------------------------------------
//
// Project: RTS3
//
// File name: W3DTerrainTracks.cpp
//
// Created: Mark Wilczynski, May 2001
//
// Desc: Draw track marks on the terrain. Uses a sequence of connected
// quads that are oriented to fit the terrain and updated when object
// moves.
//-----------------------------------------------------------------------------
#include "W3DDevice/GameClient/W3DTerrainTracks.h"
#include "W3DDevice/GameClient/heightmap.h"
#include "Common/PerfTimer.h"
#include "common/GlobalData.h"
#include "common/Debug.h"
#include "texture.h"
#include "colmath.h"
#include "coltest.h"
#include "rinfo.h"
#include "camera.h"
#include "assetmgr.h"
#include "WW3D2/DX8Wrapper.h"
#include "WW3D2/Scene.h"
#include "GameLogic/TerrainLogic.h"
#include "GameLogic/Object.h"
#include "GameClient/Drawable.h"
#ifdef _INTERNAL
// for occasional debugging...
//#pragma optimize("", off)
//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes")
#endif
#define BRIDGE_OFFSET_FACTOR 0.25f //amount to raise tracks above bridges.
//=============================================================================
// TerrainTracksRenderObjClass::~TerrainTracksRenderObjClass
//=============================================================================
/** Destructor. Releases w3d assets. */
//=============================================================================
TerrainTracksRenderObjClass::~TerrainTracksRenderObjClass(void)
{
freeTerrainTracksResources();
}
//=============================================================================
// TerrainTracksRenderObjClass::TerrainTracksRenderObjClass
//=============================================================================
/** Constructor. Just nulls out some variables. */
//=============================================================================
TerrainTracksRenderObjClass::TerrainTracksRenderObjClass(void)
{
m_stageZeroTexture=NULL;
m_lastAnchor=Vector3(0,1,2.25);
m_haveAnchor=false;
m_haveCap=true;
m_topIndex=0;
m_bottomIndex=0;
m_activeEdgeCount=0;
m_totalEdgesAdded=0;
m_bound=false;
m_ownerDrawable = NULL;
}
//=============================================================================
// TerrainTracksRenderObjClass::Get_Obj_Space_Bounding_Sphere
//=============================================================================
/** WW3D method that returns object bounding sphere used in frustum culling*/
//=============================================================================
void TerrainTracksRenderObjClass::Get_Obj_Space_Bounding_Sphere(SphereClass & sphere) const
{ /// @todo: Add code to cull track marks to screen by constantly updating bounding volumes
sphere=m_boundingSphere;
}
//=============================================================================
// TerrainTracksRenderObjClass::Get_Obj_Space_Bounding_Box
//=============================================================================
/** WW3D method that returns object bounding box used in collision detection*/
//=============================================================================
void TerrainTracksRenderObjClass::Get_Obj_Space_Bounding_Box(AABoxClass & box) const
{
box=m_boundingBox;
}
//=============================================================================
// MirrorRenderObjClass::Class_ID
//=============================================================================
/** returns the class id, so the scene can tell what kind of render object it has. */
//=============================================================================
Int TerrainTracksRenderObjClass::Class_ID(void) const
{
return RenderObjClass::CLASSID_IMAGE3D;
}
//=============================================================================
// TerrainTracksRenderObjClass::Clone
//=============================================================================
/** Not used, but required virtual method. */
//=============================================================================
RenderObjClass * TerrainTracksRenderObjClass::Clone(void) const
{
assert(false);
return NULL;
}
//=============================================================================
// TerrainTracksRenderObjClass::freeTerrainTracksResources
//=============================================================================
/** Free any W3D resources associated with this object */
//=============================================================================
Int TerrainTracksRenderObjClass::freeTerrainTracksResources(void)
{
REF_PTR_RELEASE(m_stageZeroTexture);
m_haveAnchor=false;
m_haveCap=true;
m_topIndex=0;
m_bottomIndex=0;
m_activeEdgeCount=0;
m_totalEdgesAdded=0;
m_ownerDrawable = NULL;
return 0;
}
//=============================================================================
// TerrainTracksRenderObjClass::init
//=============================================================================
/** Setup size settings and allocate W3D texture */
//=============================================================================
void TerrainTracksRenderObjClass::init( Real width, Real length, const Char *texturename)
{
freeTerrainTracksResources(); //free old data and ib/vb
m_boundingSphere.Init(Vector3(0,0,0),400*MAP_XY_FACTOR);
m_boundingBox.Center.Set(0.0f, 0.0f, 0.0f);
m_boundingBox.Extent.Set(400.0f*MAP_XY_FACTOR, 400.0f*MAP_XY_FACTOR, 1.0f);
m_width=width;
m_length=length;
//no sense culling these things since they have very irregular shape and fade
//out over time.
Set_Force_Visible(TRUE);
m_stageZeroTexture=WW3DAssetManager::Get_Instance()->Get_Texture(texturename);
}
//=============================================================================
// TerrainTracksRenderObjClass::addCapEdgeToTrack
//=============================================================================
/** Cap the current track (adding an feathered edge) so we're ready to resume
the track at a new location. Used by objects entering FOW where we need to
stop adding edges to the track when they enter the fog boundary but resume
elsewhere if they become visible again.
*/
//=============================================================================
void TerrainTracksRenderObjClass::addCapEdgeToTrack(Real x, Real y)
{
/// @todo: Have object pass its height and orientation so we can remove extra calls.
if (m_haveCap)
{ //we already have a cap or there are no segments to cap
return;
}
if (m_activeEdgeCount == 1)
{ //if we only have one edge, then it must be the current anchor edge.
//since achnors are caps, there is not point in adding another.
m_haveCap=TRUE;
m_haveAnchor=false; //recreate a new anchor when track resumes.
return;
}
Vector3 vPos,vZ;
Coord3D vZTmp;
PathfindLayerEnum objectLayer;
Real eHeight;
if (m_ownerDrawable && (objectLayer=m_ownerDrawable->getObject()->getLayer()) != LAYER_GROUND)
eHeight=BRIDGE_OFFSET_FACTOR+TheTerrainLogic->getLayerHeight(x,y,objectLayer,&vZTmp);
else
eHeight=TheTerrainLogic->getGroundHeight(x,y,&vZTmp);
vZ.X = vZTmp.x;
vZ.Y = vZTmp.y;
vZ.Z = vZTmp.z;
vPos.X=x;
vPos.Y=y;
vPos.Z=eHeight;
Vector3 vDir=Vector3(x,y,eHeight)-m_lastAnchor;
Int maxEdgeCount=TheTerrainTracksRenderObjClassSystem->m_maxTankTrackEdges;
//avoid sqrt() by checking distance squared since last track mark
if (vDir.Length2() < sqr(m_length))
{ //not far enough from anchor to add track
//since this is a cap, we'll force the previous segment to transparent
Int lastAddedEdge=m_topIndex-1;
if (lastAddedEdge < 0)
lastAddedEdge = maxEdgeCount-1;
m_edges[lastAddedEdge].alpha=0.0f; //force the last added edge to transparent.
m_haveCap=TRUE;
m_haveAnchor=false; //recreate a new anchor when track resumes.
return;
}
if (m_activeEdgeCount >= maxEdgeCount)
{ //no more room in buffer so release oldest edge
m_bottomIndex++;
m_activeEdgeCount--;
if (m_bottomIndex >= maxEdgeCount)
m_bottomIndex=0; //roll buffer back to start
}
if (m_topIndex >= maxEdgeCount)
m_topIndex=0; //roll around buffer
//we traveled far enough from last point.
//accept new point
vDir.Z=0; //ignore height
vDir.Normalize();
Vector3 vX;
Vector3::Cross_Product(vDir,vZ,&vX);
//calculate left end point
edgeInfo& topEdge = m_edges[m_topIndex];
topEdge.endPointPos[0]=vPos-(m_width*0.5f*vX); ///@todo: try getting height at endpoint
topEdge.endPointPos[0].Z += 0.2f * MAP_XY_FACTOR; //raise above terrain slightly
if (m_totalEdgesAdded&1) //every other edge has different set of UV's
{
topEdge.endPointUV[0].X=0.0f;
topEdge.endPointUV[0].Y=0.0f;
}
else
{
topEdge.endPointUV[0].X=0.0f;
topEdge.endPointUV[0].Y=1.0f;
}
//calculate right end point
topEdge.endPointPos[1]=vPos+(m_width*0.5f*vX); ///@todo: try getting height at endpoint
topEdge.endPointPos[1].Z += 0.2f * MAP_XY_FACTOR; //raise above terrain slightly
if (m_totalEdgesAdded&1) //every other edge has different set of UV's
{
topEdge.endPointUV[1].X=1.0f;
topEdge.endPointUV[1].Y=0.0f;
}
else
{
topEdge.endPointUV[1].X=1.0f;
topEdge.endPointUV[1].Y=1.0f;
}
topEdge.timeAdded=WW3D::Get_Sync_Time();
topEdge.alpha=0.0f; //fully transparent at cap.
m_lastAnchor=vPos;
m_activeEdgeCount++;
m_totalEdgesAdded++;
m_topIndex++; //make space for new edge
m_haveCap=TRUE;
m_haveAnchor=false;
}
//=============================================================================
// TerrainTracksRenderObjClass::addEdgeToTrack
//=============================================================================
/** Try to add an additional segment to track mark. Will do nothing if distance
* from last edge is too small. Will overwrite the oldest edge if maximum track
* length is reached. Oldest edges should by faded out by that time.
*/
//=============================================================================
void TerrainTracksRenderObjClass::addEdgeToTrack(Real x, Real y)
{
/// @todo: Have object pass its height and orientation so we can remove extra calls.
if (!m_haveAnchor)
{ //no anchor yet, make this point an anchor.
PathfindLayerEnum objectLayer;
if (m_ownerDrawable && (objectLayer=m_ownerDrawable->getObject()->getLayer()) != LAYER_GROUND)
m_lastAnchor=Vector3(x,y,TheTerrainLogic->getLayerHeight(x,y,objectLayer)+BRIDGE_OFFSET_FACTOR);
else
m_lastAnchor=Vector3(x,y,TheTerrainLogic->getGroundHeight(x,y));
m_haveAnchor=true;
m_airborne = true;
m_haveCap = true; //single segment tracks are always capped because nothing is drawn.
return;
}
m_haveCap = false; //have more than 1 segment now so will need to cap if it's interrupted.
Vector3 vPos,vZ;
Coord3D vZTmp;
Real eHeight;
PathfindLayerEnum objectLayer;
if (m_ownerDrawable && (objectLayer=m_ownerDrawable->getObject()->getLayer()) != LAYER_GROUND)
eHeight=BRIDGE_OFFSET_FACTOR+TheTerrainLogic->getLayerHeight(x,y,objectLayer,&vZTmp);
else
eHeight=TheTerrainLogic->getGroundHeight(x,y,&vZTmp);
vZ.X = vZTmp.x;
vZ.Y = vZTmp.y;
vZ.Z = vZTmp.z;
vPos.X=x;
vPos.Y=y;
vPos.Z=eHeight;
Vector3 vDir=Vector3(x,y,eHeight)-m_lastAnchor;
//avoid sqrt() by checking distance squared since last track mark
if (vDir.Length2() < sqr(m_length))
return; //not far enough from anchor to add track
Int maxEdgeCount=TheTerrainTracksRenderObjClassSystem->m_maxTankTrackEdges;
if (m_activeEdgeCount >= maxEdgeCount)
{ //no more room in buffer so release oldest edge
m_bottomIndex++;
m_activeEdgeCount--;
if (m_bottomIndex >= maxEdgeCount)
m_bottomIndex=0; //roll buffer back to start
}
if (m_topIndex >= maxEdgeCount)
m_topIndex=0; //roll around buffer
//we traveled far enough from last point.
//accept new point
vDir.Z=0; //ignore height
vDir.Normalize();
Vector3 vX;
Vector3::Cross_Product(vDir,vZ,&vX);
edgeInfo& topEdge = m_edges[m_topIndex];
//calculate left end point
topEdge.endPointPos[0]=vPos-(m_width*0.5f*vX); ///@todo: try getting height at endpoint
topEdge.endPointPos[0].Z += 0.2f * MAP_XY_FACTOR; //raise above terrain slightly
if (m_totalEdgesAdded&1) //every other edge has different set of UV's
{
topEdge.endPointUV[0].X=0.0f;
topEdge.endPointUV[0].Y=0.0f;
}
else
{
topEdge.endPointUV[0].X=0.0f;
topEdge.endPointUV[0].Y=1.0f;
}
//calculate right end point
topEdge.endPointPos[1]=vPos+(m_width*0.5f*vX); ///@todo: try getting height at endpoint
topEdge.endPointPos[1].Z += 0.2f * MAP_XY_FACTOR; //raise above terrain slightly
if (m_totalEdgesAdded&1) //every other edge has different set of UV's
{
topEdge.endPointUV[1].X=1.0f;
topEdge.endPointUV[1].Y=0.0f;
}
else
{
topEdge.endPointUV[1].X=1.0f;
topEdge.endPointUV[1].Y=1.0f;
}
topEdge.timeAdded=WW3D::Get_Sync_Time();
topEdge.alpha=1.0f; //fully opaque at start.
if (m_airborne || m_activeEdgeCount <= 1) {
topEdge.alpha=0.0f; //smooth out track restarts by setting transparent
}
m_airborne = false;
m_lastAnchor=vPos;
m_activeEdgeCount++;
m_totalEdgesAdded++;
m_topIndex++; //make space for new edge
}
//=============================================================================
// TerrainTracksRenderObjClass::Render
//=============================================================================
/** Does nothing. Just increments a counter of how many track edges were
* requested for rendering this frame. Actual rendering is done in flush().
*/
//=============================================================================
void TerrainTracksRenderObjClass::Render(RenderInfoClass & rinfo)
{ ///@todo: After adding track mark visibility tests, add visible marks to another list.
if (TheGlobalData->m_makeTrackMarks && m_activeEdgeCount >= 2)
TheTerrainTracksRenderObjClassSystem->m_edgesToFlush += m_activeEdgeCount;
}
#define DEFAULT_TRACK_SPACING (MAP_XY_FACTOR * 1.4f)
#define DEFAULT_TRACK_WIDTH 4.0f;
/**Find distance between the "trackfx" bones of the model. This tells us the correct
width for the trackmarks.
*/
static Real computeTrackSpacing(RenderObjClass *renderObj)
{
Real trackSpacing = DEFAULT_TRACK_SPACING;
Int leftTrack;
Int rightTrack;
if ((leftTrack=renderObj->Get_Bone_Index( "TREADFX01" )) != 0 && (rightTrack=renderObj->Get_Bone_Index( "TREADFX02" )) != 0)
{ //both bones found, determine distance between them.
Vector3 leftPos,rightPos;
leftPos=renderObj->Get_Bone_Transform( leftTrack ).Get_Translation();
rightPos=renderObj->Get_Bone_Transform( rightTrack ).Get_Translation();
rightPos -= leftPos; //get distance between centers of tracks
trackSpacing = rightPos.Length() + DEFAULT_TRACK_WIDTH; //add width of each track
///@todo: It's assumed that all tank treads have the same width.
};
return trackSpacing;
}
//=============================================================================
//TerrainTracksRenderObjClassSystem::bindTrack
//=============================================================================
/** Grab a track from the free store. If no free tracks exist, return NULL.
As long as a track is bound to an object (like a tank) it is ready to accept
updates with additional edges. Once it is unbound, it will expire and return
to the free store once all tracks have faded out.
Input: width in world units of each track edge (should probably width of vehicle).
length in world units between edges. Shorter lengths produce more edges and
smoother curves.
texture to use for the tracks - image should be symetrical and include alpha channel.
*/
//=============================================================================
TerrainTracksRenderObjClass *TerrainTracksRenderObjClassSystem::bindTrack( RenderObjClass *renderObject, Real length, const Char *texturename)
{
TerrainTracksRenderObjClass *mod;
mod = m_freeModules;
if( mod )
{
// take module off the free list
if( mod->m_nextSystem )
mod->m_nextSystem->m_prevSystem = mod->m_prevSystem;
if( mod->m_prevSystem )
mod->m_prevSystem->m_nextSystem = mod->m_nextSystem;
else
m_freeModules = mod->m_nextSystem;
// put module on the used list
mod->m_prevSystem = NULL;
mod->m_nextSystem = m_usedModules;
if( m_usedModules )
m_usedModules->m_prevSystem = mod;
m_usedModules = mod;
mod->init(computeTrackSpacing(renderObject),length,texturename);
mod->m_bound=true;
m_TerrainTracksScene->Add_Render_Object( mod);
} // end if
return mod;
} //end bindTrack
//=============================================================================
//TerrainTracksRenderObjClassSystem::unbindTrack
//=============================================================================
/** Called when an object (i.e Tank) will not lay down any more tracks and
doesn't need this object anymore. The track-laying object will be returned
to pool of available tracks as soon as any remaining track edges have faded out.
*/
//=============================================================================
void TerrainTracksRenderObjClassSystem::unbindTrack( TerrainTracksRenderObjClass *mod )
{
//this object should return to free store as soon as there is nothing
//left to render.
mod->m_bound=false;
mod->m_ownerDrawable = NULL;
}
//=============================================================================
//TerrainTracksRenderObjClassSystem::releaseTrack
//=============================================================================
/** Returns a track laying object to free store to be used again later.
*/
void TerrainTracksRenderObjClassSystem::releaseTrack( TerrainTracksRenderObjClass *mod )
{
if (mod==NULL)
return;
DEBUG_ASSERTCRASH(mod->m_bound == false, ("mod is bound."));
// remove module from used list
if( mod->m_nextSystem )
mod->m_nextSystem->m_prevSystem = mod->m_prevSystem;
if( mod->m_prevSystem )
mod->m_prevSystem->m_nextSystem = mod->m_nextSystem;
else
m_usedModules = mod->m_nextSystem;
// add module to free list
mod->m_prevSystem = NULL;
mod->m_nextSystem = m_freeModules;
if( m_freeModules )
m_freeModules->m_prevSystem = mod;
m_freeModules = mod;
mod->freeTerrainTracksResources();
m_TerrainTracksScene->Remove_Render_Object(mod);
}
//=============================================================================
// TerrainTracksRenderObjClassSystem::TerrainTracksRenderObjClassSystem
//=============================================================================
/** Constructor. Just nulls out some variables. */
//=============================================================================
TerrainTracksRenderObjClassSystem::TerrainTracksRenderObjClassSystem()
{
m_usedModules = NULL;
m_freeModules = NULL;
m_TerrainTracksScene = NULL;
m_edgesToFlush = 0;
m_indexBuffer = NULL;
m_vertexMaterialClass = NULL;
m_vertexBuffer = NULL;
m_maxTankTrackEdges=TheGlobalData->m_maxTankTrackEdges;
m_maxTankTrackOpaqueEdges=TheGlobalData->m_maxTankTrackOpaqueEdges;
m_maxTankTrackFadeDelay=TheGlobalData->m_maxTankTrackFadeDelay;
}
//=============================================================================
// TerrainTracksRenderObjClassSystem::~TerrainTracksRenderObjClassSystem
//=============================================================================
/** Destructor. Free all pre-allocated track laying render objects*/
//=============================================================================
TerrainTracksRenderObjClassSystem::~TerrainTracksRenderObjClassSystem( void )
{
// free all data
shutdown();
m_vertexMaterialClass=NULL;
m_TerrainTracksScene=NULL;
}
//=============================================================================
// TerrainTracksRenderObjClassSystem::ReAcquireResources
//=============================================================================
/** (Re)allocates all W3D assets after a reset.. */
//=============================================================================
void TerrainTracksRenderObjClassSystem::ReAcquireResources(void)
{
Int i;
const Int numModules=TheGlobalData->m_maxTerrainTracks;
// just for paranoia's sake.
REF_PTR_RELEASE(m_indexBuffer);
REF_PTR_RELEASE(m_vertexBuffer);
//Create static index buffers. These will index the vertex buffers holding the track segments
m_indexBuffer=NEW_REF(DX8IndexBufferClass,((m_maxTankTrackEdges-1)*6));
// Fill up the IB
{
DX8IndexBufferClass::WriteLockClass lockIdxBuffer(m_indexBuffer);
UnsignedShort *ib=lockIdxBuffer.Get_Index_Array();
for (i=0; i<(m_maxTankTrackEdges-1); i++)
{
ib[3]=ib[0]=i*2;
ib[1]=i*2+1;
ib[4]=ib[2]=(i+1)*2+1;
ib[5]=(i+1)*2;
ib+=6; //skip the 6 indices we just filled
}
}
DEBUG_ASSERTCRASH(numModules*m_maxTankTrackEdges*2 < 65535, ("Too many terrain track edges"));
m_vertexBuffer=NEW_REF(DX8VertexBufferClass,(DX8_FVF_XYZDUV1,numModules*m_maxTankTrackEdges*2,DX8VertexBufferClass::USAGE_DYNAMIC));
}
//=============================================================================
// TerrainTracksRenderObjClassSystem::ReleaseResources
//=============================================================================
/** (Re)allocates all W3D assets after a reset.. */
//=============================================================================
void TerrainTracksRenderObjClassSystem::ReleaseResources(void)
{
REF_PTR_RELEASE(m_indexBuffer);
REF_PTR_RELEASE(m_vertexBuffer);
// Note - it is ok to not release the material, as it is a w3d object that
// has no dx8 resources. jba.
}
//=============================================================================
// TerrainTracksRenderObjClassSystem::init
//=============================================================================
/** initialize the system, allocate all the render objects we will need */
//=============================================================================
void TerrainTracksRenderObjClassSystem::init( SceneClass *TerrainTracksScene )
{
const Int numModules=TheGlobalData->m_maxTerrainTracks;
Int i;
TerrainTracksRenderObjClass *mod;
m_TerrainTracksScene=TerrainTracksScene;
ReAcquireResources();
//go with a preset material for now.
m_vertexMaterialClass=VertexMaterialClass::Get_Preset(VertexMaterialClass::PRELIT_DIFFUSE);
//use a multi-texture shader: (text1*diffuse)*text2.
m_shaderClass = ShaderClass::_PresetAlphaShader;//_PresetATestSpriteShader;//_PresetOpaqueShader;
// we cannot initialize a system that is already initialized
if( m_freeModules || m_usedModules )
{
// system already online!
assert( 0 );
return;
} // end if
// allocate our modules for this system
for( i = 0; i < numModules; i++ )
{
mod = NEW_REF( TerrainTracksRenderObjClass, () );
if( mod == NULL )
{
// unable to allocate modules needed
assert( 0 );
return;
} // end if
mod->m_prevSystem = NULL;
mod->m_nextSystem = m_freeModules;
if( m_freeModules )
m_freeModules->m_prevSystem = mod;
m_freeModules = mod;
} // end for i
} // end init
//=============================================================================
// TerrainTracksRenderObjClassSystem::shutdown
//=============================================================================
/** Shutdown and free all memory for this system */
//=============================================================================
void TerrainTracksRenderObjClassSystem::shutdown( void )
{
TerrainTracksRenderObjClass *nextMod,*mod;
//release unbound tracks that may still be fading out
mod=m_usedModules;
while(mod)
{
nextMod=mod->m_nextSystem;
if (!mod->m_bound)
releaseTrack(mod);
mod = nextMod;
} // end while
// free all attached things and used modules
assert( m_usedModules == NULL );
// free all module storage
while( m_freeModules )
{
nextMod = m_freeModules->m_nextSystem;
REF_PTR_RELEASE (m_freeModules);
m_freeModules = nextMod;
} // end while
REF_PTR_RELEASE(m_indexBuffer);
REF_PTR_RELEASE(m_vertexMaterialClass);
REF_PTR_RELEASE(m_vertexBuffer);
} // end shutdown
//=============================================================================
// TerrainTracksRenderObjClassSystem::update
//=============================================================================
/** Update the state of all active track marks - fade, expire, etc. */
//=============================================================================
void TerrainTracksRenderObjClassSystem::update()
{
Int iTime=WW3D::Get_Sync_Time();
Real iDiff;
TerrainTracksRenderObjClass *mod=m_usedModules,*nextMod;
//first update all the tracks
while( mod )
{
Int i,index;
Vector3 *endPoint;
Vector2 *endPointUV;
nextMod = mod->m_nextSystem;
if (!TheGlobalData->m_makeTrackMarks)
mod->m_haveAnchor=false; //force a track restart next time around.
for (i=0,index=mod->m_bottomIndex; i<mod->m_activeEdgeCount; i++,index++)
{
if (index >= m_maxTankTrackEdges)
index=0;
endPoint=&mod->m_edges[index].endPointPos[0]; //left endpoint
endPointUV=&mod->m_edges[index].endPointUV[0];
iDiff=(float)(iTime-mod->m_edges[index].timeAdded);
iDiff = 1.0f - iDiff/(Real)m_maxTankTrackFadeDelay;
if (iDiff < 0.0)
iDiff=0.0f;
if (mod->m_edges[index].alpha>0.0f) {
mod->m_edges[index].alpha=iDiff;
}
if (iDiff == 0.0f)
{ //this edge was invisible, we can remove it
mod->m_bottomIndex++;
mod->m_activeEdgeCount--;
if (mod->m_bottomIndex >= m_maxTankTrackEdges)
mod->m_bottomIndex=0; //roll buffer back to start
}
if (mod->m_activeEdgeCount == 0 && !mod->m_bound)
releaseTrack(mod);
}
mod = nextMod;
} // end while
}
//=============================================================================
// TerrainTracksRenderObjClassSystem::flush
//=============================================================================
/** Draw all active track marks for this frame */
//=============================================================================
void TerrainTracksRenderObjClassSystem::flush()
{
/** @todo: Optimize system by drawing tracks as triangle strips and use dynamic vertex buffer access.
May also try rendering all tracks with one call to W3D/D3D by grouping them by texture.
Try improving the fit to vertical surfaces like cliffs.
*/
Int diffuseLight;
TerrainTracksRenderObjClass *mod=m_usedModules;
if (!mod)
return; //nothing to render
Int trackStartIndex;
Real distanceFade;
if (ShaderClass::Is_Backface_Culling_Inverted())
return; //don't render track marks in reflections.
// adjust shading for time of day.
Real shadeR, shadeG, shadeB;
shadeR = TheGlobalData->m_terrainAmbient[0].red;
shadeG = TheGlobalData->m_terrainAmbient[0].green;
shadeB = TheGlobalData->m_terrainAmbient[0].blue;
shadeR += TheGlobalData->m_terrainDiffuse[0].red/2;
shadeG += TheGlobalData->m_terrainDiffuse[0].green/2;
shadeB += TheGlobalData->m_terrainDiffuse[0].blue/2;
shadeR*=255.0f;
shadeG*=255.0f;
shadeB*=255.0f;
diffuseLight = REAL_TO_INT(shadeB) | (REAL_TO_INT(shadeG) << 8) | (REAL_TO_INT(shadeR) << 16);
Real numFadedEdges=m_maxTankTrackEdges-m_maxTankTrackOpaqueEdges;
//check if there is anything to draw and fill vertex buffer
if (m_edgesToFlush >= 2)
{
DX8VertexBufferClass::WriteLockClass lockVtxBuffer(m_vertexBuffer);
VertexFormatXYZDUV1 *verts = (VertexFormatXYZDUV1*)lockVtxBuffer.Get_Vertex_Array();
trackStartIndex=0;
mod=m_usedModules;
//Fill our vertex buffer with all the tracks
while( mod )
{
Int i,index;
Vector3 *endPoint;
Vector2 *endPointUV;
if (mod->m_activeEdgeCount >= 2 && mod->Is_Really_Visible())
{
for (i=0,index=mod->m_bottomIndex; i<mod->m_activeEdgeCount; i++,index++)
{
if (index >= m_maxTankTrackEdges)
index=0;
endPoint=&mod->m_edges[index].endPointPos[0]; //left endpoint
endPointUV=&mod->m_edges[index].endPointUV[0];
distanceFade=1.0f;
if ((mod->m_activeEdgeCount -1 -i) >= m_maxTankTrackOpaqueEdges)// && i < (MAX_PER_TRACK_EDGE_COUNT-FORCE_FADE_AT_EDGE))
{ //we're getting close to the limit on the number of track pieces allowed
//so force it to fade out.
distanceFade=1.0f-(float)((mod->m_activeEdgeCount -i)-m_maxTankTrackOpaqueEdges)/numFadedEdges;
}
distanceFade *= mod->m_edges[index].alpha; //adjust fade with distance from start of track
verts->x=endPoint->X;
verts->y=endPoint->Y;
verts->z=endPoint->Z;
verts->u1=endPointUV->X;
verts->v1=endPointUV->Y;
//fade the alpha channel with distance
verts->diffuse=diffuseLight | ( REAL_TO_INT(distanceFade*255.0f) <<24);
verts++;
endPoint=&mod->m_edges[index].endPointPos[1]; //right endpoint
endPointUV=&mod->m_edges[index].endPointUV[1];
verts->x=endPoint->X;
verts->y=endPoint->Y;
verts->z=endPoint->Z;
verts->u1=endPointUV->X;
verts->v1=endPointUV->Y; ///@todo: Add diffuse lighting.
verts->diffuse=diffuseLight | ( REAL_TO_INT(distanceFade*255.0f) <<24);
verts++;
}//for
}// mod has edges to render
mod = mod->m_nextSystem;
} //while (mod)
}//edges to flush
//draw the filled vertex buffers
if (m_edgesToFlush >= 2)
{
ShaderClass::Invalidate();
DX8Wrapper::Set_Material(m_vertexMaterialClass);
DX8Wrapper::Set_Shader(m_shaderClass);
DX8Wrapper::Set_Index_Buffer(m_indexBuffer,0);
DX8Wrapper::Set_Vertex_Buffer(m_vertexBuffer);
trackStartIndex=0;
mod=m_usedModules;
Matrix3D tm(mod->Transform);
DX8Wrapper::Set_Transform(D3DTS_WORLD,tm);
while (mod)
{
if (mod->m_activeEdgeCount >= 2 && mod->Is_Really_Visible())
{
DX8Wrapper::Set_Texture(0,mod->m_stageZeroTexture);
DX8Wrapper::Set_Index_Buffer_Index_Offset(trackStartIndex);
DX8Wrapper::Draw_Triangles( 0,(mod->m_activeEdgeCount-1)*2, 0, mod->m_activeEdgeCount*2);
trackStartIndex += mod->m_activeEdgeCount*2;
}
mod=mod->m_nextSystem;
}
} //there are some edges to render in pool.
m_edgesToFlush=0; //reset count for next flush
}
/**Removes all remaining tracks from the rendering system*/
void TerrainTracksRenderObjClassSystem::Reset(void)
{
TerrainTracksRenderObjClass *nextMod,*mod=m_usedModules;
while(mod)
{
nextMod=mod->m_nextSystem;
releaseTrack(mod);
mod = nextMod;
} // end while
// free all attached things and used modules
assert( m_usedModules == NULL );
m_edgesToFlush=0;
}
/**Clear the treads from each track laying object without freeing the objects.
Mostly used when user changed LOD level*/
void TerrainTracksRenderObjClassSystem::clearTracks(void)
{
TerrainTracksRenderObjClass *mod=m_usedModules;
while(mod)
{
mod->m_haveAnchor=false;
mod->m_haveCap=true;
mod->m_topIndex=0;
mod->m_bottomIndex=0;
mod->m_activeEdgeCount=0;
mod->m_totalEdgesAdded=0;
mod = mod->m_nextSystem;
} // end while
m_edgesToFlush=0;
}
/**Adjust various paremeters which affect the cost of rendering tracks on the map.
Parameters are passed via GlobalData*/
void TerrainTracksRenderObjClassSystem::setDetail(void)
{
//Remove all existing track segments from screen.
clearTracks();
ReleaseResources();
m_maxTankTrackEdges=TheGlobalData->m_maxTankTrackEdges;
m_maxTankTrackOpaqueEdges=TheGlobalData->m_maxTankTrackOpaqueEdges;
m_maxTankTrackFadeDelay=TheGlobalData->m_maxTankTrackFadeDelay;
//We changed the maximum number of visible edges so re-allocate our resources to match.
ReAcquireResources();
};
TerrainTracksRenderObjClassSystem *TheTerrainTracksRenderObjClassSystem=NULL; ///< singleton for track drawing system.
| 0 | 0.984331 | 1 | 0.984331 | game-dev | MEDIA | 0.930847 | game-dev | 0.788443 | 1 | 0.788443 |
Tanasittx/NetGuard-Unpacker-Public | 16,139 | NetGuard Deobfuscator 2/Protections/ProxyCalls/Delegates/Remover.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CawkEmulatorV4;
using de4dot.blocks.cflow;
using dnlib.DotNet;
using dnlib.DotNet.Emit;
using dnlib.DotNet.MD;
namespace NetGuard_Deobfuscator_2.Protections.ProxyCalls.Delegates
{
public static class MathResolver
{
public static int GetResult(int num, MethodDef targetMd)
{
InstructionEmulator em = new InstructionEmulator();
MethodDefUser dummy_method = new MethodDefUser();
dummy_method.Body = new dnlib.DotNet.Emit.CilBody();
em.Initialize(dummy_method);
List<Instruction> emuTargets = new List<Instruction>();
foreach (Instruction inst in targetMd.Body.Instructions)
{
if (inst.OpCode == OpCodes.Stfld || inst.OpCode == OpCodes.Ldarg_0 || inst.OpCode == OpCodes.Call || inst.OpCode == OpCodes.Ret)
{
continue;
}
if (inst.OpCode == OpCodes.Ldarg_1)
{
emuTargets.Add(Instruction.Create(OpCodes.Ldc_I4, num));
}
else if (inst.OpCode == OpCodes.Ldarg)
{
if (((Parameter)inst.Operand).Type.FullName == typeof(System.Int32).FullName && ((Parameter)inst.Operand).Index == 0x1)
{
emuTargets.Add(Instruction.Create(OpCodes.Ldc_I4, num));
}
}
else
{
emuTargets.Add(inst);
}
}
foreach (Instruction inst in emuTargets)
{
em.Emulate(inst);
}
var x = (Int32Value)em.Pop();
return x.Value.GetHashCode();
}
}
internal class DelegateInfo2
{
public FieldDef fieldDef;
public int byteVal;
public MethodDef callingMethodDef;
public uint mdtoken;
public MethodDef resolvedMethod;
public OpCode opcode;
}
class Remover : ProxyBase
{
public override void Deobfuscate()
{
ListedDelegateInfo2s = new List<DelegateInfo2>();
ScrapeCctor(ModuleDefMD);
ResolveCalls(ModuleDefMD);
delegateReplacer(ModuleDefMD);
}
public static List<DelegateInfo2> ListedDelegateInfo2s = new List<DelegateInfo2>();
public static void delegateReplacer(ModuleDefMD module)
{
int amoiunt = 0;
foreach (TypeDef types in module.GetTypes())
{
foreach (MethodDef methods in types.Methods)
{
if (!methods.HasBody) continue;
for (int i = 0; i < methods.Body.Instructions.Count; i++)
{
Instruction inst = methods.Body.Instructions[i];
if (inst.OpCode == OpCodes.Call && inst.Operand is MethodDef)
{
var mtd = (MethodDef)inst.Operand;
if (mtd.Name != "Invoke")
continue;
// Get ldsfld above
int x = i;
while (x >= 0)
{
Instruction xInst = methods.Body.Instructions[x];
if (xInst.OpCode == OpCodes.Ldsfld && xInst.Operand is FieldDef)
{
FieldDef fd = (FieldDef)xInst.Operand;
if (fd.FieldSig.Type.IsOptionalModifier)
break;
}
x--;
}
if (x < 0)
{
continue;
}
FieldDef fie = (FieldDef)methods.Body.Instructions[x].Operand;
foreach (DelegateInfo2 delegateInfo in ListedDelegateInfo2s)
{
if (delegateInfo.fieldDef == fie)
{
var abc = module.ResolveToken(delegateInfo.mdtoken);
if (abc != null)
{
methods.Body.Instructions[i].OpCode = delegateInfo.opcode;
methods.Body.Instructions[i].Operand = abc;
methods.Body.Instructions[x].OpCode = OpCodes.Nop;
amoiunt++;
}
break;
}
}
}
}
}
}
}
public static void fixer(TypeDef callingType, TypeDef newObjType)
{
if (callingType.IsSealed && newObjType.IsNestedPrivate)
{
newObjType.Attributes -= TypeAttributes.NestedPrivate;
newObjType.Attributes |= TypeAttributes.Public;
}
}
public static void ScrapeCctor(ModuleDefMD module)
{
var cctor = module.GlobalType.FindOrCreateStaticConstructor();
if (cctor.Body.Instructions[0].OpCode == OpCodes.Call &&
cctor.Body.Instructions[0].Operand.ToString().Contains("Koi"))
cctor = (MethodDef)cctor.Body.Instructions[0].Operand;
for (int i = 0; i < cctor.Body.Instructions.Count; i++)
{
if (cctor.Body.Instructions[i].OpCode == OpCodes.Ldtoken && cctor.Body.Instructions[i + 1].IsLdcI4() &&
cctor.Body.Instructions[i + 2].OpCode == OpCodes.Call)
{
FieldDef fieldDef = cctor.Body.Instructions[i].Operand as FieldDef;
var byteVal = cctor.Body.Instructions[i + 1].GetLdcI4Value();
var setMethod = cctor.Body.Instructions[i + 2].Operand as MethodDef;
DelegateInfo2 del = new DelegateInfo2
{
callingMethodDef = setMethod,
byteVal = byteVal,
fieldDef = fieldDef
};
ListedDelegateInfo2s.Add(del);
}
else if (cctor.Body.Instructions[i].OpCode == OpCodes.Ldtoken && cctor.Body.Instructions[i + 2].IsLdcI4() &&
cctor.Body.Instructions[i + 3].OpCode == OpCodes.Call)
{
FieldDef fieldDef = cctor.Body.Instructions[i].Operand as FieldDef;
var byteVal = cctor.Body.Instructions[i + 2].GetLdcI4Value();
var setMethod = cctor.Body.Instructions[i + 3].Operand as MethodDef;
DelegateInfo2 del = new DelegateInfo2
{
callingMethodDef = setMethod,
byteVal = byteVal,
fieldDef = fieldDef
};
ListedDelegateInfo2s.Add(del);
}
else if (cctor.Body.Instructions[i].OpCode == OpCodes.Ldtoken && cctor.Body.Instructions[i + 3].IsLdcI4() &&
cctor.Body.Instructions[i + 4].OpCode == OpCodes.Call)
{
FieldDef fieldDef = cctor.Body.Instructions[i].Operand as FieldDef;
var byteVal = cctor.Body.Instructions[i + 3].GetLdcI4Value();
var setMethod = cctor.Body.Instructions[i + 4].Operand as MethodDef;
DelegateInfo2 del = new DelegateInfo2
{
callingMethodDef = setMethod,
byteVal = byteVal,
fieldDef = fieldDef
};
ListedDelegateInfo2s.Add(del);
}
}
}
public static bool EncryptedDelegateMethod(MethodDef methods)
{
bool containsDelegate = false;
/*
* 2 000A ldsfld class AutoResetEvent modopt(SafeLsaLogonProcessHandle) '<Module>'::'N£ÿ\u0012\u0017'
3 000F ldarg A_0 (0)
4 0013 call instance object AutoResetEvent::Invoke(valuetype [mscorlib]System.RuntimeFieldHandle)
5 0018 stloc V_0 (0)
*/
for (int i = 0; i < methods.Body.Instructions.Count; i++)
{
if (methods.Body.Instructions[i].OpCode == OpCodes.Call && methods.Body.Instructions[i].Operand
.ToString().Contains("Invoke(System.RuntimeFieldHandle)"))
{
return true;
}
}
return false;
}
public static void ResolveCalls(ModuleDefMD module)
{
foreach (DelegateInfo2 info2 in ListedDelegateInfo2s)
{
MethodDef methods = info2.callingMethodDef;
FieldDef fields = info2.fieldDef;
int byteVal = info2.byteVal;
if (methods.MDToken.ToInt32() == 0x0600000A && byteVal == 9)
{
}
if (EncryptedDelegateMethod(methods))
{
continue;
}
var boolean = module.Metadata.TablesStream.TryReadFieldRow(fields.Rid, out RawFieldRow rw);
byte[] data = module.Metadata.BlobStream.Read(rw.Signature);
Emulation emu = new Emulation(methods);
var mdtoken = 0;
if (methods.MDToken.ToInt32() == 100663336 && byteVal == 4)
{
}
emu.ValueStack.Parameters[methods.Parameters[0]] = null;
emu.ValueStack.Parameters[methods.Parameters[1]] = (byte)byteVal;
emu.OnInstructionPrepared = (sender, e) =>
{
if (e.Instruction.OpCode != OpCodes.Callvirt || !e.Instruction.Operand.ToString()
.Contains("System.Reflection.MethodBase System.Reflection.Module::ResolveMethod(System.Int32)")) return;
mdtoken = sender.ValueStack.CallStack.Pop();
if (0x806EC032 == (uint)mdtoken)
{
}
e.Break = true;
};
emu.OnCallPrepared = (sender, e) =>
{
var ebc = e.Instruction;
if (ebc.Operand.ToString().Contains("System.Byte[] System.Reflection.Module::ResolveSignature(System.Int32)"))
{
sender.ValueStack.CallStack.Pop();
sender.ValueStack.CallStack.Pop();
sender.ValueStack.CallStack.Push(data);
e.bypassCall = true;
}
else if (ebc.Operand.ToString().Contains("System.Type[] System.Reflection.FieldInfo::GetOptionalCustomModifiers()"))
{
sender.ValueStack.CallStack.Pop();
sender.ValueStack.CallStack.Push(new Type[500]);
e.bypassCall = true;
}
else if (ebc.Operand.ToString().Contains("System.Int32 System.Reflection.MemberInfo::get_MetadataToken()"))
{
sender.ValueStack.CallStack.Pop();
CModOptSig sig = (CModOptSig)fields.FieldSig.Type;
int modToken = sig.Modifier.MDToken.ToInt32();
sender.ValueStack.CallStack.Push(modToken);
e.bypassCall = true;
}
else if (ebc.Operand.ToString().Contains("System.String System.Reflection.MemberInfo::get_Name()"))
{
sender.ValueStack.CallStack.Pop();
string sig = fields.Name;
sender.ValueStack.CallStack.Push(sig);
e.bypassCall = true;
}
else if (ebc.Operand.ToString().Contains("System.Char System.String::get_Chars(System.Int32)"))
{
var one = sender.ValueStack.CallStack.Pop();
var two = sender.ValueStack.CallStack.Pop();
sender.ValueStack.CallStack.Push(two[one]);
e.bypassCall = true;
}
else if (ebc.Operand.ToString().Contains("System.Object[] System.Reflection.MemberInfo::GetCustomAttributes(System.Boolean)"))
{
var one = sender.ValueStack.CallStack.Pop();
var two = sender.ValueStack.CallStack.Pop();
sender.ValueStack.CallStack.Push(new object[500]);
e.bypassCall = true;
}
else if (ebc.Operand.ToString().Contains("System.Int32 System.Object::GetHashCode()"))
{
var one = sender.ValueStack.CallStack.Pop();
// var two = sender.ValueStack.CallStack.Pop();
TypeDef caType = fields.CustomAttributes[0].AttributeType.ResolveTypeDef();
int caCtorNum = (int)fields.CustomAttributes[0].ConstructorArguments[0].Value;
MethodDef meth = First(caType.FindConstructors());
int caKey = MathResolver.GetResult(caCtorNum, meth);
sender.ValueStack.CallStack.Push(caKey);
e.bypassCall = true;
}
else
{
e.AllowCall = false;
e.bypassCall = false;
}
};
emu.Emulate();
info2.mdtoken = (uint)mdtoken;
var ins = findInstruction(methods);
var ab = fields.Name.String[ins] ^ byteVal;
var aa = OpCodes.Call.Value;
var v = OpCodes.Callvirt.Value;
var t = OpCodes.Newobj.Value;
OpCode te;
if (ab == aa)
te = OpCodes.Call;
else if (ab == v)
te = OpCodes.Callvirt;
else
te = OpCodes.Newobj;
info2.opcode = te;
}
}
private static int findInstruction(MethodDef methods)
{
int[] returns = new int[2];
methods.Body.OptimizeMacros();
for (int i = 0; i < methods.Body.Instructions.Count; i++)
{
if (methods.Body.Instructions[i].OpCode == OpCodes.Ldarg_1 && methods.Body.Instructions[i + 1].OpCode == OpCodes.Xor)
{
for (int z = 0; z < 10; z++)
{
if (methods.Body.Instructions[i - z].OpCode == OpCodes.Callvirt && methods.Body.Instructions[i - z].Operand.ToString().Contains("System.String System.Reflection.MemberInfo::get_Name()") && methods.Body.Instructions[i - z + 1].IsLdcI4())
{
var abc = methods.Body.Instructions[i - z + 1].GetLdcI4Value();
return abc;
}
}
}
}
return -1;
}
static T First<T>(IEnumerable<T> items)
{
using (IEnumerator<T> iter = items.GetEnumerator())
{
iter.MoveNext();
return iter.Current;
}
}
}
}
| 0 | 0.88242 | 1 | 0.88242 | game-dev | MEDIA | 0.439982 | game-dev | 0.730857 | 1 | 0.730857 |
folgerwang/UnrealEngine | 21,584 | Engine/Source/Runtime/Engine/Private/TimerManager.cpp | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
TickTaskManager.cpp: Manager for ticking tasks
=============================================================================*/
#include "TimerManager.h"
#include "HAL/IConsoleManager.h"
#include "Misc/CoreDelegates.h"
#include "Engine/World.h"
#include "UnrealEngine.h"
#include "Misc/TimeGuard.h"
#include "ProfilingDebugging/CsvProfiler.h"
#include "Algo/Transform.h"
DECLARE_CYCLE_STAT(TEXT("SetTimer"), STAT_SetTimer, STATGROUP_Engine);
DECLARE_CYCLE_STAT(TEXT("SetTimeForNextTick"), STAT_SetTimerForNextTick, STATGROUP_Engine);
DECLARE_CYCLE_STAT(TEXT("ClearTimer"), STAT_ClearTimer, STATGROUP_Engine);
DECLARE_CYCLE_STAT(TEXT("ClearAllTimers"), STAT_ClearAllTimers, STATGROUP_Engine);
CSV_DECLARE_CATEGORY_MODULE_EXTERN(CORE_API, Basic);
/** Track the last assigned handle globally */
uint64 FTimerManager::LastAssignedSerialNumber = 0;
namespace
{
void DescribeFTimerDataSafely(FOutputDevice& Ar, const FTimerData& Data)
{
Ar.Logf(
TEXT("TimerData %p : bLoop=%s, bRequiresDelegate=%s, Status=%d, Rate=%f, ExpireTime=%f"),
&Data,
Data.bLoop ? TEXT("true") : TEXT("false"),
Data.bRequiresDelegate ? TEXT("true") : TEXT("false"),
static_cast<int32>(Data.Status),
Data.Rate,
Data.ExpireTime
);
}
FString GetFTimerDataSafely(const FTimerData& Data)
{
FStringOutputDevice Output;
DescribeFTimerDataSafely(Output, Data);
return MoveTemp(Output);
}
}
struct FTimerHeapOrder
{
explicit FTimerHeapOrder(const TSparseArray<FTimerData>& InTimers)
: Timers(InTimers)
, NumTimers(InTimers.Num())
{
}
bool operator()(FTimerHandle LhsHandle, FTimerHandle RhsHandle) const
{
int32 LhsIndex = LhsHandle.GetIndex();
int32 RhsIndex = RhsHandle.GetIndex();
const FTimerData& LhsData = Timers[LhsIndex];
const FTimerData& RhsData = Timers[RhsIndex];
return LhsData.ExpireTime < RhsData.ExpireTime;
}
const TSparseArray<FTimerData>& Timers;
int32 NumTimers;
};
FTimerManager::FTimerManager()
: InternalTime(0.0)
, LastTickedFrame(static_cast<uint64>(-1))
, OwningGameInstance(nullptr)
{
if (IsRunningDedicatedServer())
{
// Off by default, renable if needed
//FCoreDelegates::OnHandleSystemError.AddRaw(this, &FTimerManager::OnCrash);
}
}
FTimerManager::~FTimerManager()
{
if (IsRunningDedicatedServer())
{
FCoreDelegates::OnHandleSystemError.RemoveAll(this);
}
}
void FTimerManager::OnCrash()
{
UE_LOG(LogEngine, Warning, TEXT("TimerManager %p on crashing delegate called, dumping extra information"), this);
UE_LOG(LogEngine, Log, TEXT("------- %d Active Timers (including expired) -------"), ActiveTimerHeap.Num());
int32 ExpiredActiveTimerCount = 0;
for (FTimerHandle Handle : ActiveTimerHeap)
{
const FTimerData& Timer = GetTimer(Handle);
if (Timer.Status == ETimerStatus::ActivePendingRemoval)
{
++ExpiredActiveTimerCount;
}
else
{
DescribeFTimerDataSafely(*GLog, Timer);
}
}
UE_LOG(LogEngine, Log, TEXT("------- %d Expired Active Timers -------"), ExpiredActiveTimerCount);
UE_LOG(LogEngine, Log, TEXT("------- %d Paused Timers -------"), PausedTimerSet.Num());
for (FTimerHandle Handle : PausedTimerSet)
{
const FTimerData& Timer = GetTimer(Handle);
DescribeFTimerDataSafely(*GLog, Timer);
}
UE_LOG(LogEngine, Log, TEXT("------- %d Pending Timers -------"), PendingTimerSet.Num());
for (FTimerHandle Handle : PendingTimerSet)
{
const FTimerData& Timer = GetTimer(Handle);
DescribeFTimerDataSafely(*GLog, Timer);
}
UE_LOG(LogEngine, Log, TEXT("------- %d Total Timers -------"), PendingTimerSet.Num() + PausedTimerSet.Num() + ActiveTimerHeap.Num() - ExpiredActiveTimerCount);
UE_LOG(LogEngine, Warning, TEXT("TimerManager %p dump ended"), this);
}
FString FTimerUnifiedDelegate::ToString() const
{
const UObject* Object = nullptr;
FName FunctionName = NAME_None;
bool bDynDelegate = false;
if (FuncDelegate.IsBound())
{
#if USE_DELEGATE_TRYGETBOUNDFUNCTIONNAME
FunctionName = FuncDelegate.TryGetBoundFunctionName();
#endif
}
else if (FuncDynDelegate.IsBound())
{
Object = FuncDynDelegate.GetUObject();
FunctionName = FuncDynDelegate.GetFunctionName();
bDynDelegate = true;
}
else
{
static FName NotBoundName(TEXT("NotBound!"));
FunctionName = NotBoundName;
}
return FString::Printf(TEXT("%s,%s,%s"), bDynDelegate ? TEXT("DELEGATE") : TEXT("DYN DELEGATE"), Object == nullptr ? TEXT("NO OBJ") : *Object->GetPathName(), *FunctionName.ToString());
}
// ---------------------------------
// Private members
// ---------------------------------
FTimerData& FTimerManager::GetTimer(FTimerHandle const& InHandle)
{
int32 Index = InHandle.GetIndex();
checkSlow(Index >= 0 && Index < Timers.GetMaxIndex() && Timers.IsAllocated(Index) && Timers[Index].Handle == InHandle);
FTimerData& Timer = Timers[Index];
return Timer;
}
FTimerData* FTimerManager::FindTimer(FTimerHandle const& InHandle)
{
if (!InHandle.IsValid())
{
return nullptr;
}
int32 Index = InHandle.GetIndex();
if (Index < 0 || Index >= Timers.GetMaxIndex() || !Timers.IsAllocated(Index))
{
return nullptr;
}
FTimerData& Timer = Timers[Index];
if (Timer.Handle != InHandle || Timer.Status == ETimerStatus::ActivePendingRemoval)
{
return nullptr;
}
return &Timer;
}
/** Finds a handle to a dynamic timer bound to a particular pointer and function name. */
FTimerHandle FTimerManager::K2_FindDynamicTimerHandle(FTimerDynamicDelegate InDynamicDelegate) const
{
FTimerHandle Result;
if (const void* Obj = InDynamicDelegate.GetUObject())
{
if (const TSet<FTimerHandle>* TimersForObject = ObjectToTimers.Find(Obj))
{
for (FTimerHandle Handle : *TimersForObject)
{
const FTimerData& Data = GetTimer(Handle);
if (Data.Status != ETimerStatus::ActivePendingRemoval && Data.TimerDelegate.FuncDynDelegate == InDynamicDelegate)
{
Result = Handle;
break;
}
}
}
}
return Result;
}
void FTimerManager::InternalSetTimer(FTimerHandle& InOutHandle, FTimerUnifiedDelegate&& InDelegate, float InRate, bool InbLoop, float InFirstDelay)
{
SCOPE_CYCLE_COUNTER(STAT_SetTimer);
// not currently threadsafe
check(IsInGameThread());
if (FindTimer(InOutHandle))
{
// if the timer is already set, just clear it and we'll re-add it, since
// there's no data to maintain.
InternalClearTimer(InOutHandle);
}
if (InRate > 0.f)
{
// set up the new timer
FTimerData NewTimerData;
NewTimerData.TimerDelegate = MoveTemp(InDelegate);
NewTimerData.Rate = InRate;
NewTimerData.bLoop = InbLoop;
NewTimerData.bRequiresDelegate = NewTimerData.TimerDelegate.IsBound();
// Set level collection
const UWorld* const OwningWorld = OwningGameInstance ? OwningGameInstance->GetWorld() : nullptr;
if (OwningWorld && OwningWorld->GetActiveLevelCollection())
{
NewTimerData.LevelCollection = OwningWorld->GetActiveLevelCollection()->GetType();
}
const float FirstDelay = (InFirstDelay >= 0.f) ? InFirstDelay : InRate;
FTimerHandle NewTimerHandle;
if (HasBeenTickedThisFrame())
{
NewTimerData.ExpireTime = InternalTime + FirstDelay;
NewTimerData.Status = ETimerStatus::Active;
NewTimerHandle = AddTimer(MoveTemp(NewTimerData));
ActiveTimerHeap.HeapPush(NewTimerHandle, FTimerHeapOrder(Timers));
}
else
{
// Store time remaining in ExpireTime while pending
NewTimerData.ExpireTime = FirstDelay;
NewTimerData.Status = ETimerStatus::Pending;
NewTimerHandle = AddTimer(MoveTemp(NewTimerData));
PendingTimerSet.Add(NewTimerHandle);
}
InOutHandle = NewTimerHandle;
}
}
FTimerHandle FTimerManager::InternalSetTimerForNextTick(FTimerUnifiedDelegate&& InDelegate)
{
SCOPE_CYCLE_COUNTER(STAT_SetTimerForNextTick);
// not currently threadsafe
check(IsInGameThread());
FTimerData NewTimerData;
NewTimerData.Rate = 0.f;
NewTimerData.bLoop = false;
NewTimerData.bRequiresDelegate = true;
NewTimerData.TimerDelegate = MoveTemp(InDelegate);
NewTimerData.ExpireTime = InternalTime;
NewTimerData.Status = ETimerStatus::Active;
// Set level collection
const UWorld* const OwningWorld = OwningGameInstance ? OwningGameInstance->GetWorld() : nullptr;
if (OwningWorld && OwningWorld->GetActiveLevelCollection())
{
NewTimerData.LevelCollection = OwningWorld->GetActiveLevelCollection()->GetType();
}
FTimerHandle NewTimerHandle = AddTimer(MoveTemp(NewTimerData));
ActiveTimerHeap.HeapPush(NewTimerHandle, FTimerHeapOrder(Timers));
return NewTimerHandle;
}
void FTimerManager::InternalClearTimer(FTimerHandle const& InHandle)
{
SCOPE_CYCLE_COUNTER(STAT_ClearTimer);
// not currently threadsafe
check(IsInGameThread());
FTimerData& Data = GetTimer(InHandle);
switch (Data.Status)
{
case ETimerStatus::Pending:
{
int32 NumRemoved = PendingTimerSet.Remove(InHandle);
check(NumRemoved == 1);
RemoveTimer(InHandle);
}
break;
case ETimerStatus::Active:
Data.Status = ETimerStatus::ActivePendingRemoval;
break;
case ETimerStatus::ActivePendingRemoval:
// Already removed
break;
case ETimerStatus::Paused:
{
int32 NumRemoved = PausedTimerSet.Remove(InHandle);
check(NumRemoved == 1);
RemoveTimer(InHandle);
}
break;
case ETimerStatus::Executing:
check(CurrentlyExecutingTimer == InHandle);
// Edge case. We're currently handling this timer when it got cleared. Clear it to prevent it firing again
// in case it was scheduled to fire multiple times.
CurrentlyExecutingTimer.Invalidate();
RemoveTimer(InHandle);
break;
default:
check(false);
}
}
void FTimerManager::InternalClearAllTimers(void const* Object)
{
SCOPE_CYCLE_COUNTER(STAT_ClearAllTimers);
if (!Object)
{
return;
}
TSet<FTimerHandle>* TimersToRemove = ObjectToTimers.Find(Object);
if (!TimersToRemove)
{
return;
}
TSet<FTimerHandle> LocalTimersToRemove = *TimersToRemove;
for (FTimerHandle TimerToRemove : LocalTimersToRemove)
{
InternalClearTimer(TimerToRemove);
}
}
float FTimerManager::InternalGetTimerRemaining(FTimerData const* const TimerData) const
{
if (TimerData)
{
switch (TimerData->Status)
{
case ETimerStatus::Active:
return TimerData->ExpireTime - InternalTime;
case ETimerStatus::Executing:
return 0.0f;
default:
// ExpireTime is time remaining for paused timers
return TimerData->ExpireTime;
}
}
return -1.f;
}
float FTimerManager::InternalGetTimerElapsed(FTimerData const* const TimerData) const
{
if (TimerData)
{
switch (TimerData->Status)
{
case ETimerStatus::Active:
case ETimerStatus::Executing:
return (TimerData->Rate - (TimerData->ExpireTime - InternalTime));
default:
// ExpireTime is time remaining for paused timers
return (TimerData->Rate - TimerData->ExpireTime);
}
}
return -1.f;
}
float FTimerManager::InternalGetTimerRate(FTimerData const* const TimerData) const
{
if (TimerData)
{
return TimerData->Rate;
}
return -1.f;
}
void FTimerManager::PauseTimer(FTimerHandle InHandle)
{
// not currently threadsafe
check(IsInGameThread());
FTimerData* TimerToPause = FindTimer(InHandle);
if (!TimerToPause || TimerToPause->Status == ETimerStatus::Paused)
{
return;
}
ETimerStatus PreviousStatus = TimerToPause->Status;
// Remove from previous TArray
switch( PreviousStatus )
{
case ETimerStatus::ActivePendingRemoval:
break;
case ETimerStatus::Active:
{
int32 IndexIndex = ActiveTimerHeap.Find(InHandle);
check(IndexIndex != INDEX_NONE);
ActiveTimerHeap.HeapRemoveAt(IndexIndex, FTimerHeapOrder(Timers), /*bAllowShrinking=*/ false);
}
break;
case ETimerStatus::Pending:
{
int32 NumRemoved = PendingTimerSet.Remove(InHandle);
check(NumRemoved == 1);
}
break;
case ETimerStatus::Executing:
check(CurrentlyExecutingTimer == InHandle);
CurrentlyExecutingTimer.Invalidate();
break;
default:
check(false);
}
// Don't pause the timer if it's currently executing and isn't going to loop
if( PreviousStatus == ETimerStatus::Executing && !TimerToPause->bLoop )
{
RemoveTimer(InHandle);
}
else
{
// Add to Paused list
PausedTimerSet.Add(InHandle);
// Set new status
TimerToPause->Status = ETimerStatus::Paused;
// Store time remaining in ExpireTime while paused. Don't do this if the timer is in the pending list.
if (PreviousStatus != ETimerStatus::Pending)
{
TimerToPause->ExpireTime -= InternalTime;
}
}
}
void FTimerManager::UnPauseTimer(FTimerHandle InHandle)
{
// not currently threadsafe
check(IsInGameThread());
FTimerData* TimerToUnPause = FindTimer(InHandle);
if (!TimerToUnPause || TimerToUnPause->Status != ETimerStatus::Paused)
{
return;
}
// Move it out of paused list and into proper TArray
if( HasBeenTickedThisFrame() )
{
// Convert from time remaining back to a valid ExpireTime
TimerToUnPause->ExpireTime += InternalTime;
TimerToUnPause->Status = ETimerStatus::Active;
ActiveTimerHeap.HeapPush(InHandle, FTimerHeapOrder(Timers));
}
else
{
TimerToUnPause->Status = ETimerStatus::Pending;
PendingTimerSet.Add(InHandle);
}
// remove from paused list
PausedTimerSet.Remove(InHandle);
}
// ---------------------------------
// Public members
// ---------------------------------
DECLARE_DWORD_COUNTER_STAT(TEXT("TimerManager Heap Size"),STAT_NumHeapEntries,STATGROUP_Game);
void FTimerManager::Tick(float DeltaTime)
{
CSV_SCOPED_TIMING_STAT_EXCLUSIVE(Tickables);
#if DO_TIMEGUARD && 0
TArray<FTimerUnifiedDelegate> RunTimerDelegates;
FTimerNameDelegate NameFunction = FTimerNameDelegate::CreateLambda([&] {
FString ActiveDelegates;
for ( const FTimerUnifiedDelegate& Descriptor : RunTimerDelegates )
{
ActiveDelegates += FString::Printf(TEXT("Delegate %s, "), *Descriptor.ToString() );
}
return FString::Printf(TEXT("UWorld::Tick - TimerManager, %s"), *ActiveDelegates);
});
// no delegate should take longer then 5ms to run
SCOPE_TIME_GUARD_DELEGATE_MS(NameFunction, 5);
#endif
// @todo, might need to handle long-running case
// (e.g. every X seconds, renormalize to InternalTime = 0)
INC_DWORD_STAT_BY(STAT_NumHeapEntries, ActiveTimerHeap.Num());
if (HasBeenTickedThisFrame())
{
return;
}
InternalTime += DeltaTime;
UWorld* const OwningWorld = OwningGameInstance ? OwningGameInstance->GetWorld() : nullptr;
UWorld* const LevelCollectionWorld = OwningWorld;
while (ActiveTimerHeap.Num() > 0)
{
FTimerHandle TopHandle = ActiveTimerHeap.HeapTop();
// Test for expired timers
int32 TopIndex = TopHandle.GetIndex();
FTimerData* Top = &Timers[TopIndex];
if (Top->Status == ETimerStatus::ActivePendingRemoval)
{
ActiveTimerHeap.HeapPop(TopHandle, FTimerHeapOrder(Timers), /*bAllowShrinking=*/ false);
RemoveTimer(TopHandle);
continue;
}
if (InternalTime > Top->ExpireTime)
{
// Timer has expired! Fire the delegate, then handle potential looping.
// Set the relevant level context for this timer
const int32 LevelCollectionIndex = OwningWorld ? OwningWorld->FindCollectionIndexByType(Top->LevelCollection) : INDEX_NONE;
FScopedLevelCollectionContextSwitch LevelContext(LevelCollectionIndex, LevelCollectionWorld);
// Remove it from the heap and store it while we're executing
ActiveTimerHeap.HeapPop(CurrentlyExecutingTimer, FTimerHeapOrder(Timers), /*bAllowShrinking=*/ false);
Top->Status = ETimerStatus::Executing;
// Determine how many times the timer may have elapsed (e.g. for large DeltaTime on a short looping timer)
int32 const CallCount = Top->bLoop ?
FMath::TruncToInt( (InternalTime - Top->ExpireTime) / Top->Rate ) + 1
: 1;
// Now call the function
for (int32 CallIdx=0; CallIdx<CallCount; ++CallIdx)
{
#if DO_TIMEGUARD && 0
FTimerNameDelegate NameFunction = FTimerNameDelegate::CreateLambda([&] {
return FString::Printf(TEXT("FTimerManager slowtick from delegate %s "), *Top->TimerDelegate.ToString());
});
// no delegate should take longer then 2ms to run
SCOPE_TIME_GUARD_DELEGATE_MS(NameFunction, 2);
#endif
#if DO_TIMEGUARD && 0
RunTimerDelegates.Add(Top->TimerDelegate);
#endif
Top->TimerDelegate.Execute();
// Update Top pointer, in case it has been invalidated by the Execute call
Top = FindTimer(CurrentlyExecutingTimer);
if (!Top || Top->Status != ETimerStatus::Executing)
{
break;
}
}
// test to ensure it didn't get cleared during execution
if (Top)
{
// if timer requires a delegate, make sure it's still validly bound (i.e. the delegate's object didn't get deleted or something)
if (Top->bLoop && (!Top->bRequiresDelegate || Top->TimerDelegate.IsBound()))
{
// Put this timer back on the heap
Top->ExpireTime += CallCount * Top->Rate;
Top->Status = ETimerStatus::Active;
ActiveTimerHeap.HeapPush(CurrentlyExecutingTimer, FTimerHeapOrder(Timers));
}
else
{
RemoveTimer(CurrentlyExecutingTimer);
}
CurrentlyExecutingTimer.Invalidate();
}
}
else
{
// no need to go further down the heap, we can be finished
break;
}
}
// Timer has been ticked.
LastTickedFrame = GFrameCounter;
// If we have any Pending Timers, add them to the Active Queue.
if( PendingTimerSet.Num() > 0 )
{
for (FTimerHandle Handle : PendingTimerSet)
{
FTimerData& TimerToActivate = GetTimer(Handle);
// Convert from time remaining back to a valid ExpireTime
TimerToActivate.ExpireTime += InternalTime;
TimerToActivate.Status = ETimerStatus::Active;
ActiveTimerHeap.HeapPush( Handle, FTimerHeapOrder(Timers) );
}
PendingTimerSet.Reset();
}
}
TStatId FTimerManager::GetStatId() const
{
RETURN_QUICK_DECLARE_CYCLE_STAT(FTimerManager, STATGROUP_Tickables);
}
void FTimerManager::ListTimers() const
{
TArray<const FTimerData*> ValidActiveTimers;
ValidActiveTimers.Reserve(ActiveTimerHeap.Num());
for (FTimerHandle Handle : ActiveTimerHeap)
{
if (const FTimerData* Data = FindTimer(Handle))
{
ValidActiveTimers.Add(Data);
}
}
UE_LOG(LogEngine, Log, TEXT("------- %d Active Timers -------"), ValidActiveTimers.Num());
for (const FTimerData* Data : ValidActiveTimers)
{
FString TimerString = Data->TimerDelegate.ToString();
UE_LOG(LogEngine, Log, TEXT("%s"), *TimerString);
}
UE_LOG(LogEngine, Log, TEXT("------- %d Paused Timers -------"), PausedTimerSet.Num());
for (FTimerHandle Handle : PausedTimerSet)
{
const FTimerData& Data = GetTimer(Handle);
FString TimerString = Data.TimerDelegate.ToString();
UE_LOG(LogEngine, Log, TEXT("%s"), *TimerString);
}
UE_LOG(LogEngine, Log, TEXT("------- %d Pending Timers -------"), PendingTimerSet.Num());
for (FTimerHandle Handle : PendingTimerSet)
{
const FTimerData& Data = GetTimer(Handle);
FString TimerString = Data.TimerDelegate.ToString();
UE_LOG(LogEngine, Log, TEXT("%s"), *TimerString);
}
UE_LOG(LogEngine, Log, TEXT("------- %d Total Timers -------"), PendingTimerSet.Num() + PausedTimerSet.Num() + ValidActiveTimers.Num());
}
FTimerHandle FTimerManager::AddTimer(FTimerData&& TimerData)
{
const void* TimerIndicesByObjectKey = TimerData.TimerDelegate.GetBoundObject();
TimerData.TimerIndicesByObjectKey = TimerIndicesByObjectKey;
int32 NewIndex = Timers.Add(MoveTemp(TimerData));
FTimerHandle Result = GenerateHandle(NewIndex);
Timers[NewIndex].Handle = Result;
if (TimerIndicesByObjectKey)
{
TSet<FTimerHandle>& HandleSet = ObjectToTimers.FindOrAdd(TimerIndicesByObjectKey);
bool bAlreadyExists = false;
HandleSet.Add(Result, &bAlreadyExists);
checkf(!bAlreadyExists, TEXT("A timer with this handle and object has already been added! (%s)"), *GetFTimerDataSafely(TimerData));
}
return Result;
}
void FTimerManager::RemoveTimer(FTimerHandle Handle)
{
const FTimerData& Data = GetTimer(Handle);
// Remove TimerIndicesByObject entry if necessary
if (const void* TimerIndicesByObjectKey = Data.TimerIndicesByObjectKey)
{
TSet<FTimerHandle>* TimersForObject = ObjectToTimers.Find(TimerIndicesByObjectKey);
checkf(TimersForObject, TEXT("Removed timer was bound to an object which is not tracked by ObjectToTimers! (%s)"), *GetFTimerDataSafely(Data));
int32 NumRemoved = TimersForObject->Remove(Handle);
checkf(NumRemoved == 1, TEXT("Removed timer was bound to an object which is not tracked by ObjectToTimers! (%s)"), *GetFTimerDataSafely(Data));
if (TimersForObject->Num() == 0)
{
ObjectToTimers.Remove(TimerIndicesByObjectKey);
}
}
Timers.RemoveAt(Handle.GetIndex());
}
FTimerHandle FTimerManager::GenerateHandle(int32 Index)
{
uint64 NewSerialNumber = ++LastAssignedSerialNumber;
if (!ensureMsgf(NewSerialNumber != FTimerHandle::MaxSerialNumber, TEXT("Timer serial number has wrapped around!")))
{
NewSerialNumber = (uint64)1;
}
FTimerHandle Test;
Test.SetIndexAndSerialNumber(FTimerHandle::MaxIndex - 1, FTimerHandle::MaxSerialNumber - 1);
check(Test.GetIndex() == FTimerHandle::MaxIndex - 1 && Test.GetSerialNumber() == FTimerHandle::MaxSerialNumber - 1);
FTimerHandle Result;
Result.SetIndexAndSerialNumber(Index, NewSerialNumber);
check(Result.GetIndex() == Index && Result.GetSerialNumber() == NewSerialNumber);
return Result;
}
// Handler for ListTimers console command
static void OnListTimers(UWorld* World)
{
if(World != nullptr)
{
World->GetTimerManager().ListTimers();
}
}
// Register ListTimers console command, needs a World context
FAutoConsoleCommandWithWorld ListTimersConsoleCommand(
TEXT("ListTimers"),
TEXT(""),
FConsoleCommandWithWorldDelegate::CreateStatic(OnListTimers)
);
| 0 | 0.968437 | 1 | 0.968437 | game-dev | MEDIA | 0.555709 | game-dev | 0.960795 | 1 | 0.960795 |
fictionalflaw/MMleo | 1,118 | agent/custom/action/consert.py | import os
import json
import time
from datetime import datetime
from PIL import Image
from utils import logger
from maa.agent.agent_server import AgentServer
from maa.custom_action import CustomAction
from maa.context import Context
@AgentServer.custom_action("SwitchConsertBP")
class SwitchConsertBP(CustomAction):
'''
用来调整演唱会的难度和BP
目前在占位状态,写完记得去init写调用
'''
def run(
self,
context: Context,
argv: CustomAction.RunArg,
) -> CustomAction.RunResult:
times = json.loads(argv.custom_action_param)["times"]
context.run_task("OpenReplaysTimes", {"OpenReplaysTimes": {"next": []}})
context.run_task(
"SetReplaysTimes",
{
"SetReplaysTimes": {
"template": [
f"Combat/SetReplaysTimesX{times}.png",
f"Combat/SetReplaysTimesX{times}_selected.png",
],
"order_by": "Score",
"next": [],
}
},
)
return CustomAction.RunResult(success=True)
| 0 | 0.797111 | 1 | 0.797111 | game-dev | MEDIA | 0.41014 | game-dev | 0.658939 | 1 | 0.658939 |
Fallen-Breath/tweakermore | 2,098 | src/main/java/me/fallenbreath/tweakermore/mixins/tweaks/mod_tweaks/serverDataSyncer/tweakermore/RenderVisitorWorldViewMixin.java | /*
* This file is part of the TweakerMore project, licensed under the
* GNU Lesser General Public License v3.0
*
* Copyright (C) 2023 Fallen_Breath and contributors
*
* TweakerMore is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* TweakerMore is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with TweakerMore. If not, see <https://www.gnu.org/licenses/>.
*/
package me.fallenbreath.tweakermore.mixins.tweaks.mod_tweaks.serverDataSyncer.tweakermore;
import com.llamalad7.mixinextras.sugar.Local;
import me.fallenbreath.tweakermore.config.TweakerMoreConfigs;
import me.fallenbreath.tweakermore.impl.features.infoView.cache.RenderVisitorWorldView;
import me.fallenbreath.tweakermore.impl.mod_tweaks.serverDataSyncer.ServerDataSyncer;
import net.minecraft.client.MinecraftClient;
import net.minecraft.util.math.BlockPos;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(RenderVisitorWorldView.class)
public abstract class RenderVisitorWorldViewMixin
{
@SuppressWarnings("UnresolvedMixinReference")
@Inject(method = "doSyncBlockEntity", at = @At("HEAD"), remap = false)
private void serverDataSyncer4CommandBlockinfoView(CallbackInfo ci, @Local(argsOnly = true) BlockPos blockPos)
{
if (TweakerMoreConfigs.SERVER_DATA_SYNCER.getBooleanValue())
{
if (!MinecraftClient.getInstance().isIntegratedServerRunning() && ServerDataSyncer.hasEnoughPermission())
{
ServerDataSyncer.getInstance().syncBlockEntityAt(blockPos);
}
}
}
}
| 0 | 0.734107 | 1 | 0.734107 | game-dev | MEDIA | 0.713059 | game-dev | 0.615393 | 1 | 0.615393 |
auQuiksilver/Apex-Framework | 2,124 | Apex_framework.terrain/code/functions/fn_clientMenuSupporters.sqf | /*
File: fn_clientMenuSupporters.sqf
Author:
Quiksilver
Last Modified:
15/04/2023 A3 2.12 by Quiksilver
Description:
Supporters Menu
__________________________________________*/
disableSerialization;
private ['_type','_display'];
_type = _this # 0;
if (_type isEqualTo 'onLoad') exitWith {
(findDisplay 2000) closeDisplay 1;
(findDisplay 3000) closeDisplay 1;
_display = _this # 1;
setMousePosition (uiNamespace getVariable ['QS_ui_mousePosition',getMousePosition]);
(_display displayCtrl 1804) ctrlEnable TRUE;
(_display displayCtrl 1807) ctrlEnable TRUE;
(_display displayCtrl 1808) ctrlEnable TRUE;
(_display displayCtrl 1809) ctrlSetText '- - -';
(_display displayCtrl 1809) ctrlSetToolTip '';
(_display displayCtrl 1809) ctrlEnable FALSE;
};
if (_type isEqualTo 'onUnload') exitWith {
uiNamespace setVariable ['QS_ui_mousePosition',getMousePosition];
};
if (_type isEqualTo 'B1') exitWith {
// Face Paint
closeDialog 2;
0 spawn {
uiSleep 0.1;
waitUntil {
closeDialog 2;
(!dialog)
};
createDialog 'QS_RD_client_dialog_menu_face';
};
};
if (_type isEqualTo 'B2') exitWith {
// Insignia
closeDialog 2;
0 spawn {
uiSleep 0.1;
waitUntil {
closeDialog 2;
(!dialog)
};
createDialog 'QS_RD_client_dialog_menu_insignia';
};
};
if (_type isEqualTo 'B3') exitWith {
// Uniform Textures
closeDialog 2;
0 spawn {
uiSleep 0.1;
waitUntil {
closeDialog 2;
(!dialog)
};
createDialog 'QS_RD_client_dialog_menu_utexture';
};
};
if (_type isEqualTo 'B4') exitWith {
// Vehicle Textures
closeDialog 2;
0 spawn {
uiSleep 0.1;
waitUntil {
closeDialog 2;
(!dialog)
};
createDialog 'QS_RD_client_dialog_menu_vtexture';
};
};
if (_type isEqualTo 'B5') exitWith {
// Lasers
closeDialog 2;
0 spawn {
uiSleep 0.1;
waitUntil {
closeDialog 2;
(!dialog)
};
createDialog 'QS_RD_client_dialog_menu_lasers';
};
};
if (_type isEqualTo 'B6') exitWith {
};
if (_type isEqualTo 'Back') exitWith {
closeDialog 2;
0 spawn {
uiSleep 0.1;
waitUntil {
closeDialog 2;
(!dialog)
};
createDialog 'QS_RD_client_dialog_menu_main';
};
}; | 0 | 0.805577 | 1 | 0.805577 | game-dev | MEDIA | 0.729659 | game-dev | 0.827397 | 1 | 0.827397 |
andanteyk/ElectronicObserver | 3,401 | ElectronicObserver/Data/DevelopmentData.cs | using DynaJson;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ElectronicObserver.Data
{
public class DevelopmentData : APIWrapper
{
// request
/// <summary> 投入燃料(1回分) </summary>
public int Fuel { get; private set; }
/// <summary> 投入弾薬(1回分) </summary>
public int Ammo { get; private set; }
/// <summary> 投入鋼材(1回分) </summary>
public int Steel { get; private set; }
/// <summary> 投入ボーキサイト(1回分) </summary>
public int Bauxite { get; private set; }
/// <summary> 開発の試行回数 </summary>
public int DevelopmentTrials { get; private set; }
// response
/// <summary> 開発に成功したか </summary>
public bool IsSucceeded { get; private set; }
/// <summary> 開発後の各種保有資源 </summary>
public ReadOnlyCollection<int> Materials { get; private set; }
public class DevelopmentResult
{
public readonly int MasterID;
public readonly int EquipmentID;
public bool IsSucceeded => MasterID != -1;
public EquipmentData Equipment => KCDatabase.Instance.Equipments[MasterID];
public EquipmentDataMaster MasterEquipment => Equipment?.MasterEquipment;
public DevelopmentResult() : this(null) { }
public DevelopmentResult(dynamic data)
{
MasterID = (int?)data?.api_id ?? -1;
EquipmentID = (int?)data?.api_slotitem_id ?? -1;
}
public override string ToString()
{
return IsSucceeded ? $"{MasterEquipment.CategoryTypeInstance.Name}「{MasterEquipment.Name}」" : "失敗";
}
}
/// <summary> 開発結果 </summary>
public ReadOnlyCollection<DevelopmentResult> Results { get; private set; }
public override void LoadFromRequest(string apiname, Dictionary<string, string> data)
{
base.LoadFromRequest(apiname, data);
Fuel = int.Parse(data["api_item1"]);
Ammo = int.Parse(data["api_item2"]);
Steel = int.Parse(data["api_item3"]);
Bauxite = int.Parse(data["api_item4"]);
if (data.ContainsKey("api_multiple_flag"))
DevelopmentTrials = int.Parse(data["api_multiple_flag"]) != 0 ? 3 : 1;
else
DevelopmentTrials = 1;
IsSucceeded = false;
Materials = null;
Results = null;
}
public override void LoadFromResponse(string apiname, dynamic data)
{
base.LoadFromResponse(apiname, (object)data);
IsSucceeded = (int)data.api_create_flag != 0;
Materials = Array.AsReadOnly((int[])data.api_material);
void AddToDatabase(dynamic equipmentData)
{
var eq = new EquipmentData();
eq.LoadFromResponse(apiname, JsonObject.Parse(equipmentData.ToString()));
KCDatabase.Instance.Equipments.Add(eq);
}
bool isOldAPI = data.api_shizai_flag();
if (isOldAPI)
{
// 旧 API フォーマット (-2019/09/30 12:00)
Results = Array.AsReadOnly(new[] {
IsSucceeded ?
new DevelopmentResult(data.api_slot_item) :
new DevelopmentResult()
});
if (IsSucceeded)
AddToDatabase(data.api_slot_item);
}
else
{
// 新 API フォーマット (2019/09/30 21:00-)
dynamic[] elems = data.api_get_items;
var results = new DevelopmentResult[elems.Length];
for (int i = 0; i < elems.Length; i++)
{
results[i] = new DevelopmentResult(elems[i]);
if (results[i].IsSucceeded)
AddToDatabase(elems[i]);
}
Results = Array.AsReadOnly(results);
}
KCDatabase.Instance.Material.LoadFromResponse(apiname, data.api_material);
}
}
}
| 0 | 0.761132 | 1 | 0.761132 | game-dev | MEDIA | 0.410784 | game-dev | 0.678653 | 1 | 0.678653 |
ProjectIgnis/CardScripts | 3,256 | official/c19942835.lua | --アンデット・リボーン
--Zombie Reborn
--Scripted by Hatter
local s,id=GetID()
function s.initial_effect(c)
--Special Summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetCategory(CATEGORY_REMOVE+CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCountLimit(1,id)
e1:SetTarget(s.sptg)
e1:SetOperation(s.spop)
c:RegisterEffect(e1)
--Set self from GY
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(id,1))
e2:SetCategory(CATEGORY_TODECK+CATEGORY_LEAVE_GRAVE)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_GRAVE)
e2:SetCountLimit(1,id)
e2:SetTarget(s.settg)
e2:SetOperation(s.setop)
c:RegisterEffect(e2)
end
function s.rmfilter(c,code)
return c:IsAbleToRemove() and c:IsCode(code)
end
function s.spfilter(c,e,tp)
return c:IsRace(RACE_ZOMBIE) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
and Duel.IsExistingMatchingCard(s.rmfilter,tp,LOCATION_DECK|LOCATION_EXTRA,0,1,nil,c:GetCode())
end
function s.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and s.spfilter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(s.spfilter,tp,LOCATION_GRAVE,LOCATION_GRAVE,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,s.spfilter,tp,LOCATION_GRAVE,LOCATION_GRAVE,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_REMOVE,nil,1,tp,LOCATION_DECK|LOCATION_EXTRA)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function s.spop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if not (tc and tc:IsRelateToEffect(e) and tc:IsRace(RACE_ZOMBIE)) then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,s.rmfilter,tp,LOCATION_DECK|LOCATION_EXTRA,0,1,1,nil,tc:GetCode())
if #g>0 and Duel.Remove(g,POS_FACEUP,REASON_EFFECT)>0 and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)
end
end
function s.setfilter(c)
return c:IsFaceup() and c:IsRace(RACE_ZOMBIE) and c:IsAbleToDeck()
end
function s.settg(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
if chk==0 then return c:IsSSetable() and Duel.IsExistingMatchingCard(s.setfilter,tp,LOCATION_REMOVED,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TODECK,nil,1,tp,LOCATION_REMOVED)
Duel.SetOperationInfo(0,CATEGORY_LEAVE_GRAVE,c,1,0,0)
end
function s.setop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g=Duel.SelectMatchingCard(tp,s.setfilter,tp,LOCATION_REMOVED,0,1,1,nil)
if #g==0 then return end
Duel.HintSelection(g,true)
if Duel.SendtoDeck(g,nil,SEQ_DECKSHUFFLE,REASON_EFFECT)>0 and g:GetFirst():IsLocation(LOCATION_DECK|LOCATION_EXTRA)
and c:IsRelateToEffect(e) and c:IsSSetable() then
Duel.SSet(tp,c)
--Banish it if it leaves the field
local e1=Effect.CreateEffect(c)
e1:SetDescription(3300)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_LEAVE_FIELD_REDIRECT)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_CLIENT_HINT)
e1:SetReset(RESET_EVENT|RESETS_REDIRECT)
e1:SetValue(LOCATION_REMOVED)
c:RegisterEffect(e1)
end
end | 0 | 0.926948 | 1 | 0.926948 | game-dev | MEDIA | 0.97801 | game-dev | 0.931804 | 1 | 0.931804 |
goblint/analyzer | 1,112 | tests/regression/56-witness/31-base-unassume-mem-ex.c | // PARAM: --enable ana.int.interval --set ana.activated[+] unassume --set witness.yaml.unassume 31-base-unassume-mem-ex.yml
#include <goblint.h>
int main() {
int i, j;
int *p;
int r; // rand
i = 0;
j = 0;
if (r)
p = &i;
else
p = &j;
switch (r) {
case 0:
__goblint_check(i == 0); // UNKNOWN (intentional by unassume)
__goblint_check(j == 0); // UNKNOWN (intentional by unassume)
__goblint_check(i >= 0);
__goblint_check(j >= 0);
__goblint_check(p == &i || p == &j);
break;
case 1:
__goblint_check(i == 0); // UNKNOWN (intentional by unassume)
__goblint_check(j == 0); // UNKNOWN (intentional by unassume)
__goblint_check(i >= 0);
__goblint_check(j >= 0);
__goblint_check(p == &i || p == &j);
break;
case 2:
__goblint_check(i == 0); // UNKNOWN (intentional by unassume)
__goblint_check(j == 0); // UNKNOWN (intentional by unassume)
__goblint_check(i >= 0);
__goblint_check(j >= 0);
__goblint_check(p == &i || p == &j);
break;
default:
break;
}
return 0;
} | 0 | 0.730897 | 1 | 0.730897 | game-dev | MEDIA | 0.869735 | game-dev,testing-qa | 0.629649 | 1 | 0.629649 |
eldexterr/ttyd64 | 7,045 | map/patch/tes_00.mpat | % I use this map to test a bunch of stuff
#new:Header $Header
{
[MainScript] $Script_Main
[Background] 80200000
[EntryList] $EntryList
[EntryCount] 4
}
#new:EntryList $EntryList
{
~Vec4f:Entry0
~Vec4f:Entry1
~Vec4f:Entry2
~Vec4f:Entry3
~Vec4f:Entry4
}
% Override texture package
#new:Function_Init $Function_Init
{
PUSH RA, A0, A1
LIA A0, 800B0CF0
LIA A1, "tst_tex"
JAL ~Func:sprintf
RESERVED
CLEAR V0
JPOP RA, A0, A1
}
#new:Script_Main $Script_Main
{
Call SetSpriteShading ( .Shading:None )
Call SetCamPerspective ( .Cam:Default 00000003 00000019 00000010 00001000 )
Call SetCamBGColor ( .Cam:Default 0 0 0 ) % black
Call SetCamEnabled ( .Cam:Default .True )
Call SetCamLeadPlayer ( .Cam:Default .False )
Exec $Script_MakeEntities
Call MakeNpcs ( 0 $NpcGroupList_tes00 )
Call GetEntryID ( *Var0 )
If *Var0 != 4
Set *Var0 $Script_MakeExits
Exec EnterWalk
Else
Exec $Script_MakeExits
EndIf
Bind $P1Trigger .Trigger:WallPressA ~Collider:cube 00000001 00000000
Return
End
}
#new:Script $P1Trigger
{
SetConst *MapVar[0] *Fixed[1.0]
Loop
Call $Function_ConvertFixedToFloat ( *MapVar[0] *MapVar[1] )
Wait 1
EndLoop
Call $Function_Test
Call GetPlayerPos ( *Var0 *Var1 *Var2 )
Loop
Call PlayEffect ( ~FX:StatChange:AttackPlus2 *Var0 *Var1 *Var2 *Fixed[1.0] 30` .False .False .False .False .False .False .False )
Wait 29`
EndLoop
Return
End
}
#new:Function $Function_ConvertIntToFixed
{
PUSH RA, A0, A1, A2, A3, V1, S0, S1
COPY S0, A0
LW A1, C (A0)
JAL ~Func:get_variable
LW A1, 0 (A1)
MTC1 V0, F12
CVT.S.W F12, F12
NOP
JAL ~Func:float_to_fixed_var
NOP
COPY A0, S0
LW A1, C (A0)
LW A1, 4 (A1)
JAL ~Func:set_variable
COPY A2, V0
POP RA, A0, A1, A2, A3, V1, S0, S1
JR RA
ORI V0, R0, 2
}
#new:Function $Function_ConvertFloatToFixed
{
PUSH RA, A0, A1, A2, A3, V1, S0, S1
COPY S0, A0
LW A1, C (A0)
JAL ~Func:get_variable
LW A1, 0 (A1)
MTC1 V0, F12
JAL ~Func:float_to_fixed_var
NOP
COPY A0, S0
LW A1, C (A0)
LW A1, 4 (A1)
JAL ~Func:set_variable
COPY A2, V0
POP RA, A0, A1, A2, A3, V1, S0, S1
JR RA
ORI V0, R0, 2
}
#new:Function $Function_ConvertFixedToFloat
{
PUSH RA, A0, A1, A2, A3, V1, S0, S1
COPY S0, A0
LW A1, C (A0)
JAL ~Func:get_float_variable
LW A1, 0 (A1)
COPY A0, S0
LW A1, C (A0)
LW A1, 4 (A1)
JAL ~Func:set_variable
MFC1 A2, F0
POP RA, A0, A1, A2, A3, V1, S0, S1
JR RA
ORI V0, R0, 2
}
#new:Function $Function_Test
{
LIF F0, 4.5
TRUNC.W.S F1, F0
MFC1 V0, F1
JR RA
ORI V0, R0, 2
}
% Entities
#new:Script $Script_MakeEntities
{
%Call MakeEntity ( .Entity:HealingBlock ~Vec4d:HealBlock 80000000 )
Call MakeEntity ( .Entity:SuperBlock ~Vec4d:HealBlock 80000000 )
Call AssignBlockFlag ( *Flag_EVT_11 )
Call AssignScript ( $Script_Entity_Shine1 )
Return
End
}
#new:Script $Script_Entity_Shine1
{
Set *Var0 0 % EntityID
SetConst *Var1 *Flag_EVT_11 % EntityFlag
ExecWait $Script_ShineBlock
Return
End
}
% Npcs
#new:NpcGroupList $NpcGroupList_tes00
{
00000001 $NpcGroup_Cheato 3C000000
00000001 $NpcGroup_Goomba 2F010000
00000000 00000000 00000000
}
#new:NpcGroup $NpcGroup_Cheato
{
00000001 $NpcSettings_Cheato ~vec3f:Npc_cheato
00A40D01 $NpcScript_Init_Cheato 00000000 00000000 00000000
~NoItems ~NoHP ~NoFP ~NoCoinBonus ~NoMovement
00AE0001 00AE0001 00AE0001 00AE0001 00AE0001 00AE0001 00AE0001 00AE0001
00AE0001 00AE0001 00AE0001 00AE0001 00AE0001 00AE0001 00AE0001 00AE0001
00000000 00000000 00000000 00000000
}
#new:NpcSettings $NpcSettings_Cheato
{
00000000 00200025 00000000 00000000 00000000 00000000 00000000 00000000
00000000 00000000 00630000
}
#new:Script $NpcScript_Init_Cheato
{
Call BindNpcInteract ( .Npc:Self $NpcScript_Interact_Cheato )
Return
End
}
#new:Script $NpcScript_Interact_Cheato
{
%Call SpeakToPlayer ( .Npc:Self 00AE0004 00AE0001 00000000 $String_Cheato_1 )
Call StartBossBattle ( .Song:SpecialBattle ) % Testing Purposes
Return%/
Return
End
}
#string $String_Cheato_1
{
[Style Right]
Hi!
[Wait][End]
}
#new:NpcGroup $NpcGroup_Goomba
{
00000000 $NpcSettings_Enemy1 ~Vec3f:Npc_enemy
00000400 $Script_Init_EnemyNPC 00000000 00000000 0000005A
~Items:5:Mushroom:A
~HP:20:80:2:60 ~HP:30:70:2:50 ~HP:50:60:2:50 ~HP:80:50:2:40 ~HP:100:30:2:30 ~HP:None ~HP:None ~HP:None
~FP:20:70:2:50 ~FP:30:60:2:50 ~FP:50:50:2:40 ~FP:80:40:2:40 ~FP:100:30:2:40 ~FP:None ~FP:None ~FP:None
~NoCoinBonus
~Vec3d:Npc_enemy 000000FF 00000014 FFFF8001 00000001 % defines the wandering volume
~Vec3d:Npc_enemy 00000078 00000082 FFFF8001 00000000 % defines the detection volume
00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
00000000 00000000
%animations
00260001 00260002 00260003 00260003 00260001 00260001 00260005 00260005
00260003 00260003 00260003 00260003 00260003 00260003 00260003 00260003
00000000 00000000 00000000 00000000
}
#new:NpcSettings $NpcSettings_Enemy1
{
00000000 00140017 00000000 00000000 $Script_EnemyAI 80077F70
00000000 00000000 00050000
}
#new:Script $Script_Init_EnemyNPC
{
Return
End
}
#new:Script $Script_EnemyAI
{
Call DoBasicAI ( $AISettings_Enemy )
Return
End
}
#new:AISettings $AISettings_Enemy
{
0.1 % move speed
300` % move time
30` % wait time
0.0 % alert radius
0.0
1`
0.1 % chase speed
180` % max turn rate (0 = enemy rushes at position where the player was detected and keeps going)
3`
0.0 % chase radius
0.0
1`
}
% Exits
#new:Script $Script_MakeExits
{
Bind $Script_Exit0 ( .Trigger:FloorAbove ~Collider:deilis 00000001 00000000 ) % 0
Bind $Script_Exit1 ( .Trigger:FloorAbove ~Collider:deiliw 00000001 00000000 ) % 1
Bind $Script_Exit2 ( .Trigger:FloorAbove ~Collider:deilin 00000001 00000000 ) % 2
Bind $Script_Exit3 ( .Trigger:FloorAbove ~Collider:deilie 00000001 00000000 ) % 3
Return
End
}
#new:Script $Script_Exit0
{
Call UseExitHeading ( 60` 0 )
Exec $Script_Exit
Return
End
}
#new:Script $Script_Exit1
{
Call UseExitHeading ( 60` 1 )
Exec $Script_Exit
Return
End
}
#new:Script $Script_Exit2
{
Call UseExitHeading ( 60` 2 )
Exec $Script_Exit
Return
End
}
#new:Script $Script_Exit3
{
Call UseExitHeading ( 60` 3 )
Exec $Script_Exit
Return
End
}
#new:Script $Script_Exit
{
Exec ExitWalk
Call GotoMap ( "mac_01" 1 )
Wait 100`
Return
End
}
| 0 | 0.911144 | 1 | 0.911144 | game-dev | MEDIA | 0.94641 | game-dev | 0.882645 | 1 | 0.882645 |
Cannoneers-of-Create/CreateBigCannons | 11,064 | src/main/java/rbasamoyai/createbigcannons/munitions/autocannon/AbstractAutocannonProjectile.java | package rbasamoyai.createbigcannons.munitions.autocannon;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import com.mojang.math.Constants;
import net.minecraft.core.BlockPos;
import net.minecraft.core.particles.ParticleOptions;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundSource;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.ai.targeting.TargetingConditions;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.Vec3;
import rbasamoyai.createbigcannons.CreateBigCannons;
import rbasamoyai.createbigcannons.block_armor_properties.BlockArmorPropertiesHandler;
import rbasamoyai.createbigcannons.block_armor_properties.BlockArmorPropertiesProvider;
import rbasamoyai.createbigcannons.config.CBCCfgMunitions;
import rbasamoyai.createbigcannons.config.CBCConfigs;
import rbasamoyai.createbigcannons.effects.particles.smoke.TrailSmokeParticleData;
import rbasamoyai.createbigcannons.index.CBCSoundEvents;
import rbasamoyai.createbigcannons.munitions.AbstractCannonProjectile;
import rbasamoyai.createbigcannons.munitions.ProjectileContext;
import rbasamoyai.createbigcannons.munitions.config.components.BallisticPropertiesComponent;
import rbasamoyai.createbigcannons.network.ClientboundPlayBlockHitEffectPacket;
import rbasamoyai.createbigcannons.utils.CBCUtils;
public abstract class AbstractAutocannonProjectile extends AbstractCannonProjectile {
protected double displacement = 0;
protected int ageRemaining;
protected final Map<Player, Integer> whooshedPlayers = new HashMap<>();
protected AbstractAutocannonProjectile(EntityType<? extends AbstractAutocannonProjectile> type, Level level) {
super(type, level);
}
@Override
protected void onTickRotate() {
this.yRotO = this.getYRot();
this.xRotO = this.getXRot();
if (!this.isInGround()) {
Vec3 vel = this.getDeltaMovement();
if (vel.lengthSqr() > 0.005d) {
this.setYRot((float) (Mth.atan2(vel.x, vel.z) * (double) Constants.RAD_TO_DEG));
this.setXRot((float) (Mth.atan2(vel.y, vel.horizontalDistance()) * (double) Constants.RAD_TO_DEG));
}
this.setYRot(this.getYRot());
this.setXRot(this.getXRot());
}
}
@Override
public void tick() {
Vec3 prevPos = this.position();
ChunkPos cpos = new ChunkPos(this.blockPosition());
Vec3 nextVelocity = this.nextVelocity;
if (this.level().isClientSide || this.level().hasChunk(cpos.x, cpos.z)) {
super.tick();
this.displacement += this.position().distanceTo(prevPos);
if (!this.level().isClientSide) {
this.ageRemaining--;
if (this.ageRemaining <= 0)
this.expireProjectile();
}
if (!this.isInGround()) {
TrailType trailType = CBCConfigs.server().munitions.autocannonTrailType.get();
if (trailType != TrailType.NONE) {
int lifetime = trailType == TrailType.SHORT ? 50 : 100 + this.level().random.nextInt(50);
ParticleOptions options = new TrailSmokeParticleData(lifetime);
for (int i = 0; i < 10; ++i) {
double partial = i * 0.1f;
double dx = Mth.lerp(partial, this.xOld, this.getX());
double dy = Mth.lerp(partial, this.yOld, this.getY());
double dz = Mth.lerp(partial, this.zOld, this.getZ());
double sx = this.level().random.nextDouble() * 0.004d - 0.002d;
double sy = this.level().random.nextDouble() * 0.004d - 0.002d;
double sz = this.level().random.nextDouble() * 0.004d - 0.002d;
this.level().addAlwaysVisibleParticle(options, true, dx, dy, dz, sx, sy, sz);
}
if (nextVelocity != null) {
ParticleOptions options1 = new TrailSmokeParticleData(lifetime - 1);
Vec3 nextPos = this.position().add(nextVelocity);
for (int i = 0; i < 20; ++i) {
double partial = i * 0.1f;
double dx = Mth.lerp(partial, this.getX(), nextPos.x);
double dy = Mth.lerp(partial, this.getY(), nextPos.y);
double dz = Mth.lerp(partial, this.getZ(), nextPos.z);
double sx = this.level().random.nextDouble() * 0.004d - 0.002d;
double sy = this.level().random.nextDouble() * 0.004d - 0.002d;
double sz = this.level().random.nextDouble() * 0.004d - 0.002d;
this.level().addAlwaysVisibleParticle(options1, true, dx, dy, dz, sx, sy, sz);
}
}
}
if (this.level().isClientSide && CBCConfigs.client().enableAutocannonFlybySounds.get()) {
for (Iterator<Map.Entry<Player, Integer>> iter = this.whooshedPlayers.entrySet().iterator(); iter.hasNext(); ) {
Map.Entry<Player, Integer> entry = iter.next();
if (entry.getKey().isRemoved() || !entry.getKey().isAlive()) {
iter.remove();
continue;
}
int v = entry.getValue();
if (v <= 0) {
iter.remove();
} else {
entry.setValue(v - 1);
}
}
SoundEvent soundEvent = this.getAutocannonRoundType() == AutocannonAmmoType.MACHINE_GUN
? CBCSoundEvents.MACHINE_GUN_ROUND_FLYBY.getMainEvent()
: CBCSoundEvents.AUTOCANNON_ROUND_FLYBY.getMainEvent();
Vec3 curPos = this.position();
Vec3 displacementVec = curPos.subtract(prevPos);
AABB path = this.getBoundingBox().expandTowards(displacementVec.reverse()).inflate(3);
for (Player player : this.level().getNearbyPlayers(TargetingConditions.forNonCombat(), null, path)) {
Vec3 diff = player.position().subtract(prevPos);
boolean flag = this.whooshedPlayers.containsKey(player);
this.whooshedPlayers.put(player, 3);
if (flag)
continue;
float volume = displacementVec.dot(diff) < 0 ? 0.25f : 1f;
float pitch = 0.95f + this.random.nextFloat() * 0.2f;
this.level().playSound(player,this.getX(), this.getY(), this.getZ(), soundEvent, SoundSource.NEUTRAL, volume, pitch);
}
}
}
}
}
protected void expireProjectile() {
this.discard();
}
@Override
public void remove(RemovalReason reason) {
super.remove(reason);
this.whooshedPlayers.clear();
}
public void setTracer(boolean tracer) {
if (tracer) {
this.entityData.set(ID_FLAGS, (byte)(this.entityData.get(ID_FLAGS) | 2));
} else {
this.entityData.set(ID_FLAGS, (byte)(this.entityData.get(ID_FLAGS) & 0b11111101));
}
}
public void setLifetime(int lifetime) { this.ageRemaining = lifetime; }
@Override
protected ImpactResult calculateBlockPenetration(ProjectileContext projectileContext, BlockState state, BlockHitResult blockHitResult) {
BlockPos pos = blockHitResult.getBlockPos();
Vec3 hitLoc = blockHitResult.getLocation();
BallisticPropertiesComponent ballistics = this.getBallisticProperties();
BlockArmorPropertiesProvider blockArmor = BlockArmorPropertiesHandler.getProperties(state);
boolean unbreakable = projectileContext.griefState() == CBCCfgMunitions.GriefState.NO_DAMAGE || state.getDestroySpeed(this.level(), pos) == -1;
Vec3 accel = this.getForces(this.position(), this.getDeltaMovement());
Vec3 curVel = this.getDeltaMovement().add(accel);
Vec3 normal = CBCUtils.getSurfaceNormalVector(this.level(), blockHitResult);
double incidence = Math.max(0, curVel.normalize().dot(normal.reverse()));
double velMag = curVel.length();
double mass = this.getProjectileMass();
double bonusMomentum = 1 + Math.max(0, (velMag - CBCConfigs.server().munitions.minVelocityForPenetrationBonus.getF())
* CBCConfigs.server().munitions.penetrationBonusScale.getF());
double momentum = mass * velMag * incidence * bonusMomentum;
double hardnessPenalty = Math.max(blockArmor.hardness(this.level(), state, pos, true) - ballistics.penetration(), 0);
double projectileDeflection = ballistics.deflection();
double baseChance = CBCConfigs.server().munitions.baseProjectileBounceChance.getF();
double bounceChance = projectileDeflection < 1e-2d || incidence > projectileDeflection ? 0 : Math.max(baseChance, 1 - incidence / projectileDeflection);
boolean surfaceImpact = this.lastPenetratedBlock.isAir();
boolean canBounce = CBCConfigs.server().munitions.projectilesCanBounce.get();
ImpactResult.KinematicOutcome outcome;
if (surfaceImpact && canBounce && this.level().getRandom().nextDouble() < bounceChance) {
outcome = ImpactResult.KinematicOutcome.BOUNCE;
} else {
outcome = ImpactResult.KinematicOutcome.STOP;
}
boolean shatter = surfaceImpact && outcome != ImpactResult.KinematicOutcome.BOUNCE && hardnessPenalty > ballistics.toughness();
if (!this.level().isClientSide) {
boolean bounced = outcome == ImpactResult.KinematicOutcome.BOUNCE;
Vec3 effectNormal;
if (bounced) {
double elasticity = 1.7f;
effectNormal = curVel.subtract(normal.scale(normal.dot(curVel) * elasticity));
} else {
effectNormal = curVel.reverse();
}
for (BlockState state1 : blockArmor.containedBlockStates(this.level(), state, pos.immutable(), true)) {
projectileContext.addPlayedEffect(new ClientboundPlayBlockHitEffectPacket(state1, this.getType(), bounced, true,
hitLoc.x, hitLoc.y, hitLoc.z, (float) effectNormal.x, (float) effectNormal.y, (float) effectNormal.z));
}
if (hardnessPenalty > 1e-2d) {
if (ballistics.toughness() < 1e-2d){
momentum = 0;
} else{
momentum *= Math.max(0.25, 1 - hardnessPenalty / ballistics.toughness());
}
}
if (!unbreakable)
CreateBigCannons.BLOCK_DAMAGE.damageBlock(pos.immutable(), Math.max(Mth.ceil(momentum), 0), state, this.level());
}
this.onImpact(blockHitResult, new ImpactResult(outcome, shatter), projectileContext);
return new ImpactResult(outcome, !this.level().isClientSide && (shatter || outcome != ImpactResult.KinematicOutcome.BOUNCE));
}
public boolean isTracer() { return (this.entityData.get(ID_FLAGS) & 2) != 0; }
public double getTotalDisplacement() { return this.displacement; }
public void setTotalDisplacement(double value) { this.displacement = value; }
@Override
public void addAdditionalSaveData(CompoundTag tag) {
super.addAdditionalSaveData(tag);
tag.putBoolean("Tracer", this.isTracer());
tag.putInt("Age", this.ageRemaining);
tag.putDouble("Displacement", this.displacement);
}
@Override
public void readAdditionalSaveData(CompoundTag tag) {
super.readAdditionalSaveData(tag);
this.setTracer(tag.getBoolean("Tracer"));
this.ageRemaining = tag.getInt("Age");
this.displacement = tag.getFloat("Displacement");
}
@Override
public void baseWriteSpawnData(FriendlyByteBuf buf) {
super.baseWriteSpawnData(buf);
buf.writeDouble(this.displacement);
}
@Override
public void baseReadSpawnData(FriendlyByteBuf buf) {
super.baseReadSpawnData(buf);
this.displacement = buf.readDouble();
}
public AutocannonAmmoType getAutocannonRoundType() { return AutocannonAmmoType.AUTOCANNON; }
public enum TrailType {
NONE,
LONG,
SHORT
}
}
| 0 | 0.905305 | 1 | 0.905305 | game-dev | MEDIA | 0.953468 | game-dev | 0.909943 | 1 | 0.909943 |
liangxiegame/QFramework | 7,800 | QFramework.Unity2018+/Assets/QFramework/Toolkits/_CoreKit/Internal/Guidline/Editor/Resources/EditorGuideline/2. 架构篇:QFramework.cs/04. 引入 Event.md | # 04. 引入 Event
我们看下当前的代码:
```csharp
using UnityEngine;
using UnityEngine.UI;
namespace QFramework.Example
{
// 1. 定义一个 Model 对象
public class CounterAppModel : AbstractModel
{
public int Count;
protected override void OnInit()
{
Count = 0;
}
}
// 2.定义一个架构(提供 MVC、分层、模块管理等)
public class CounterApp : Architecture<CounterApp>
{
protected override void Init()
{
// 注册 Model
this.RegisterModel(new CounterAppModel());
}
}
// 引入 Command
public class IncreaseCountCommand : AbstractCommand
{
protected override void OnExecute()
{
this.GetModel<CounterAppModel>().Count++;
}
}
public class DecreaseCountCommand : AbstractCommand
{
protected override void OnExecute()
{
this.GetModel<CounterAppModel>().Count--;
}
}
// Controller
public class CounterAppController : MonoBehaviour , IController /* 3.实现 IController 接口 */
{
// View
private Button mBtnAdd;
private Button mBtnSub;
private Text mCountText;
// 4. Model
private CounterAppModel mModel;
void Start()
{
// 5. 获取模型
mModel = this.GetModel<CounterAppModel>();
// View 组件获取
mBtnAdd = transform.Find("BtnAdd").GetComponent<Button>();
mBtnSub = transform.Find("BtnSub").GetComponent<Button>();
mCountText = transform.Find("CountText").GetComponent<Text>();
// 监听输入
mBtnAdd.onClick.AddListener(() =>
{
// 交互逻辑
this.SendCommand<IncreaseCountCommand>();
// 表现逻辑
UpdateView();
});
mBtnSub.onClick.AddListener(() =>
{
// 交互逻辑
this.SendCommand<DecreaseCountCommand>();
// 表现逻辑
UpdateView();
});
UpdateView();
}
void UpdateView()
{
mCountText.text = mModel.Count.ToString();
}
// 3.
public IArchitecture GetArchitecture()
{
return CounterApp.Interface;
}
private void OnDestroy()
{
// 8. 将 Model 设置为空
mModel = null;
}
}
}
```
我们通过引入了 Command 来帮助 Controller 分担了一部分的交互逻辑。
但是表现逻辑的代码目前看起来并不是很智能。
表现逻辑的代码如下:
```csharp
// 监听输入
mBtnAdd.onClick.AddListener(() =>
{
// 交互逻辑
this.SendCommand<IncreaseCountCommand>();
// 表现逻辑
UpdateView();
});
mBtnSub.onClick.AddListener(() =>
{
// 交互逻辑
this.SendCommand<DecreaseCountCommand>();
// 表现逻辑
UpdateView();
});
```
每次调用逻辑之后,表现逻辑部分都需要手动调用一次(UpdateView 方法)。
在一个项目中,表现逻辑的调用次数,至少会和交互逻辑的调用次数一样多。因为只要修改了数据,对应地就要把数据的biang在界面上表现出来。
而这部分嗲用表现逻辑的代码也会很多,所以我们引入一个事件机制来解决这个问题。
这个事件机制的使用其实是和 Command 一起使用的,这里有一个简单的小模式,如下图所示:

即通过 Command 修改数据,当数据发生修改后发送对应的数据变更事件。
这个是简化版本的 CQRS 原则,即 Command Query Responsibility Separiation,读写分离原则。
引入这项原则会很容易实现 事件驱动、数据驱动 架构。
在 QFramework 中,用法非常简单,代码如下:
```csharp
using UnityEngine;
using UnityEngine.UI;
namespace QFramework.Example
{
// 1. 定义一个 Model 对象
public class CounterAppModel : AbstractModel
{
public int Count;
protected override void OnInit()
{
Count = 0;
}
}
// 2.定义一个架构(提供 MVC、分层、模块管理等)
public class CounterApp : Architecture<CounterApp>
{
protected override void Init()
{
// 注册 Model
this.RegisterModel(new CounterAppModel());
}
}
// 定义数据变更事件
public struct CountChangeEvent // ++
{
}
// 引入 Command
public class IncreaseCountCommand : AbstractCommand
{
protected override void OnExecute()
{
this.GetModel<CounterAppModel>().Count++;
this.SendEvent<CountChangeEvent>(); // ++
}
}
public class DecreaseCountCommand : AbstractCommand
{
protected override void OnExecute()
{
this.GetModel<CounterAppModel>().Count--;
this.SendEvent<CountChangeEvent>(); // ++
}
}
// Controller
public class CounterAppController : MonoBehaviour , IController /* 3.实现 IController 接口 */
{
// View
private Button mBtnAdd;
private Button mBtnSub;
private Text mCountText;
// 4. Model
private CounterAppModel mModel;
void Start()
{
// 5. 获取模型
mModel = this.GetModel<CounterAppModel>();
// View 组件获取
mBtnAdd = transform.Find("BtnAdd").GetComponent<Button>();
mBtnSub = transform.Find("BtnSub").GetComponent<Button>();
mCountText = transform.Find("CountText").GetComponent<Text>();
// 监听输入
mBtnAdd.onClick.AddListener(() =>
{
// 交互逻辑
this.SendCommand<IncreaseCountCommand>();
});
mBtnSub.onClick.AddListener(() =>
{
// 交互逻辑
this.SendCommand(new DecreaseCountCommand(/* 这里可以传参(如果有) */));
});
UpdateView();
// 表现逻辑
this.RegisterEvent<CountChangeEvent>(e =>
{
UpdateView();
}).UnRegisterWhenGameObjectDestroyed(gameObject);
}
void UpdateView()
{
mCountText.text = mModel.Count.ToString();
}
// 3.
public IArchitecture GetArchitecture()
{
return CounterApp.Interface;
}
private void OnDestroy()
{
// 8. 将 Model 设置为空
mModel = null;
}
}
}
```
代码很简单。
流程图如下:

运行结果如下:

引入事件机制 和 CQRS 原则之后,我们的表现逻辑的代码变少了很多。
由原来的两次主动调用
``` csharp
// 监听输入
mBtnAdd.onClick.AddListener(() =>
{
// 交互逻辑
this.SendCommand<IncreaseCountCommand>(); // 没有参数构造的命令支持泛型
// 表现逻辑
UpdateView();
});
mBtnSub.onClick.AddListener(() =>
{
// 交互逻辑
this.SendCommand(new DecreaseCountCommand()); // 也支持直接传入对象(方便通过构造传参)
// 表现逻辑
UpdateView();
});
```
变成了一处监听事件,接收事件进行调用。
``` csharp
// 监听输入
mBtnAdd.onClick.AddListener(() =>
{
// 交互逻辑
this.SendCommand<IncreaseCountCommand>(); // 没有参数构造的命令支持泛型
});
mBtnSub.onClick.AddListener(() =>
{
// 交互逻辑
this.SendCommand(new DecreaseCountCommand()); // 也支持直接传入对象(方便通过构造传参)
});
UpdateView();
// 表现逻辑
this.RegisterEvent<CountChangeEvent>(e =>
{
UpdateView();
}).UnRegisterWhenGameObjectDestroyed(gameObject);
```
这样减缓了很多交互逻辑。
OK,到此,我们算是用上了还算合格的 MVC 的实现,而 QFramework 所提供的概念中,最重要的概念已经接触到了,即 CQRS,通过 Command 去修改数据,数据发生修改后发送数据变更事件。
当前的示意图如下:

学到这里,对于 QFramework 架构的使用算是真正的入门了。
不过接下来还有一些概念,我们下一篇继续。
本文由 QFramework 教程会员赞助,地址:[https://www.gamepixedu.com/vip/?levelId=1](https://www.gamepixedu.com/vip/?levelId=1)
* QFramework 主页:[qframework.cn](https://qframework.cn)
* QFramework 交流群: 541745166
* QFramework Github 地址: <https://github.com/liangxiegame/qframework>
* QFramework Gitee 地址:<https://gitee.com/liangxiegame/QFramework> | 0 | 0.900868 | 1 | 0.900868 | game-dev | MEDIA | 0.622087 | game-dev | 0.686259 | 1 | 0.686259 |
Auviotre/Enigmatic-Addons | 5,272 | src/main/java/auviotre/enigmatic/addon/contents/entities/DragonBreathArrow.java | package auviotre.enigmatic.addon.contents.entities;
import auviotre.enigmatic.addon.registries.EnigmaticAddonEffects;
import auviotre.enigmatic.addon.registries.EnigmaticAddonEntities;
import com.google.common.collect.Sets;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.util.Mth;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.entity.AreaEffectCloud;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.projectile.AbstractArrow;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.alchemy.PotionUtils;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.EntityHitResult;
import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec3;
import java.util.List;
import java.util.Set;
public class DragonBreathArrow extends AbstractArrow {
private final Set<MobEffectInstance> effects;
public DragonBreathArrow(EntityType<? extends DragonBreathArrow> type, Level world) {
super(type, world);
this.setBaseDamage(this.getBaseDamage() * 2);
this.effects = Sets.newHashSet();
}
public DragonBreathArrow(LivingEntity entity, Level world) {
super(EnigmaticAddonEntities.DRAGON_BREATH_ARROW, entity, world);
this.setBaseDamage(this.getBaseDamage() * 2);
this.effects = Sets.newHashSet();
}
public void tick() {
super.tick();
if (this.level().isClientSide) {
Vec3 movement = this.getDeltaMovement();
double dx = movement.x;
double dy = movement.y;
double dz = movement.z;
double length = movement.length() * 1.25D;
for (int i = 0; i < length; ++i) {
this.level().addParticle(ParticleTypes.DRAGON_BREATH, this.getRandomX(0.0F) + dx * (double) i / length, this.getRandomY() + dy * (double) i / length, this.getRandomZ(0.0F) + dz * (double) i / length, -dx * 0.1, -dy * 0.1, -dz * 0.1);
}
if (!this.isNoGravity() && !this.isNoPhysics())
this.setDeltaMovement(movement.x, movement.y + 0.02, movement.z);
} else if (this.inGround) this.summonAreaEffect();
}
protected void onHit(HitResult hitResult) {
super.onHit(hitResult);
if (!this.level().isClientSide && hitResult.getType() == HitResult.Type.ENTITY && !this.ownedBy(((EntityHitResult) hitResult).getEntity())) {
this.setPos(this.getPosition(0.0F).add(this.getDeltaMovement().scale(0.5F)));
this.summonAreaEffect();
}
}
protected void onHitEntity(EntityHitResult hitResult) {
super.onHitEntity(hitResult);
hitResult.getEntity().invulnerableTime = 0;
}
private void summonAreaEffect() {
float speed = (float) this.getDeltaMovement().length();
float dmg = Mth.ceil(Mth.clamp(Math.sqrt(speed) * this.getBaseDamage(), 0.0, 2.147483647E9)) / 4.0F;
List<LivingEntity> entities = this.level().getEntitiesOfClass(LivingEntity.class, this.getBoundingBox().inflate(4.0, 2.0, 4.0));
AreaEffectCloud effectCloud = new AreaEffectCloud(this.level(), this.getX(), this.getY(), this.getZ());
Entity owner = this.getOwner();
if (owner instanceof LivingEntity livingOwner) effectCloud.setOwner(livingOwner);
effectCloud.setParticle(ParticleTypes.DRAGON_BREATH);
effectCloud.setRadius(1.5F);
effectCloud.setDuration(100);
effectCloud.setRadiusOnUse(0.1F);
effectCloud.setDurationOnUse(-1);
effectCloud.setWaitTime(1);
effectCloud.addEffect(new MobEffectInstance(EnigmaticAddonEffects.DRAGON_BREATH_EFFECT, 1, Mth.floor(dmg)));
if (!this.effects.isEmpty()) for (MobEffectInstance effect : this.effects) {
MobEffectInstance effectInstance = new MobEffectInstance(effect.getEffect(), effect.getDuration() / 5, effect.getAmplifier());
effectCloud.addEffect(effectInstance);
}
if (!entities.isEmpty()) {
for (LivingEntity entity : entities) {
if (this.distanceToSqr(entity) < 12.0 && entity != this.getOwner()) {
effectCloud.setPos(entity.getX(), entity.getY(), entity.getZ());
break;
}
}
}
this.level().addFreshEntity(effectCloud);
this.discard();
}
protected ItemStack getPickupItem() {
return ItemStack.EMPTY;
}
public void addEffect(MobEffectInstance instance) {
this.effects.add(instance);
}
public void addAdditionalSaveData(CompoundTag tag) {
super.addAdditionalSaveData(tag);
if (!this.effects.isEmpty()) {
ListTag tags = new ListTag();
for (MobEffectInstance effect : this.effects) tags.add(effect.save(new CompoundTag()));
tag.put("CustomPotionEffects", tags);
}
}
public void readAdditionalSaveData(CompoundTag tag) {
super.readAdditionalSaveData(tag);
this.effects.addAll(PotionUtils.getCustomEffects(tag));
}
}
| 0 | 0.893911 | 1 | 0.893911 | game-dev | MEDIA | 0.983453 | game-dev | 0.946342 | 1 | 0.946342 |
Dimbreath/ArknightsData | 6,928 | ja-JP/gamedata/[uc]lua/hotfixes/advancedselectorhotfixer.lua |
local xutil = require('xlua.util')
local eutil = CS.Torappu.Lua.Util
local AdvancedSelectorHotfixer = Class("AdvancedSelectorHotfixer", HotfixBase)
local ShrinkEntity
local function CompareHatred(a, b)
if a.hatred < b.hatred then
return 1
end
if a.hatred > b.hatred then
return -1
end
return 0
end
local function CompareMass(selector, a, b)
local massLevelA = a.attributes:GetValueRoundToInt(CS.Torappu.AttributeType.MASS_LEVEL)
local massLevelB = b.attributes:GetValueRoundToInt(CS.Torappu.AttributeType.MASS_LEVEL)
if massLevelA < massLevelB then
return 1
end
if massLevelA > massLevelB then
return -1
end
return CompareHatred(a, b)
end
local function CompareTauntLevel(selector, a, b)
if a.tauntLevel < b.tauntLevel then
return 1
end
if a.tauntLevel > b.tauntLevel then
return -1
end
return 0
end
local function CompareDistFromSource(selector, a, b)
local disA = (selector.owner.mapPosition - a.mapPosition).sqrMagnitude
local disB = (selector.owner.mapPosition - b.mapPosition).sqrMagnitude
if CS.Torappu.MathUtil.GT(disA, disB) then
return -1
end
if CS.Torappu.MathUtil.GT(disB, disA) then
return 1
end
return CompareHatred(a, b)
end
local function CompareHpAsc(selector, a, b)
local hpA = a.hp
local hpB = b.hp
if CS.Torappu.MathUtil.GT(hpB, hpA) then
return -1
end
if CS.Torappu.MathUtil.GT(hpA, hpB) then
return 1
end
return CompareHatred(a, b)
end
local function CompareHpDes(selector, a, b)
local hpA = a.hp
local hpB = b.hp
if CS.Torappu.MathUtil.GT(hpB, hpA) then
return 1
end
if CS.Torappu.MathUtil.GT(hpA, hpB) then
return -1
end
return CompareHatred(a, b)
end
local function CompareForwardFirstManhattanAsc(selector, a, b)
local sourceDir = CS.Torappu.GridPosition.FromVectorPosition(CS.Torappu.SharedConsts.FOUR_WAYS[selector.owner.direction:GetHashCode()])
local offsetA = selector.owner.gridPosition - a.gridPosition
local offsetB = selector.owner.gridPosition - b.gridPosition
local dirA = CS.Torappu.GridPosition.Cross(sourceDir, offsetA)
local dirB = CS.Torappu.GridPosition.Cross(sourceDir, offsetB)
local manhattanA = (selector.owner.gridPosition - a.gridPosition).manhattan
local manhattanB = (selector.owner.gridPosition - b.gridPosition).manhattan
local weightA
local weightB
if dirA == 0 and dirB == 0 then
weightA = (selector.owner.gridPosition - a.gridPosition).manhattan - a.hatred:AsFloat() / 1000
weightB = (selector.owner.gridPosition - b.gridPosition).manhattan - b.hatred:AsFloat() / 1000
if weightA < weightB then
return -1
end
if weightA > weightB then
return 1
end
return 0
end
if dirA == 0 and dirB ~= 0 then
return -1
end
if dirA ~= 0 and dirB == 0 then
return 1
end
if manhattanA < manhattanB then
return -1
end
if manhattanA > manhattanB then
return 1
end
return CompareHatred(a, b)
end
local function BubbleSort(owner, A, compare)
local n = A.Count
local flag
for i = 0, n - 1 do
flag = true
for j = 0, n - 2 - i do
if compare(owner, A[j], A[j+1]) > 0 then
A[j],A[j+1] = A[j+1],A[j]
flag = false
end
end
if flag == true then
break
end
end
end
function OnPostFilterFix(self, candidates)
if candidates ~= nil and candidates.Count > 0 and candidates[0]:GetType() == typeof(CS.Torappu.Battle.Tile) then
self:OnPostFilter(candidates)
return
end
if self._postFilter == CS.Torappu.Battle.FilterUtil.FilterType.MASS_DES then
if self.isAlly == true and self._excludeOwner == true and self.owner ~= nil then
candidates:Remove(self.owner)
end
BubbleSort(self, candidates, CompareMass)
if self._sortByTauntAtLast == true then
BubbleSort(self, candidates, CompareTauntLevel)
end
ShrinkEntity (candidates, self.maxTargetNum)
return
end
if self._postFilter == CS.Torappu.Battle.FilterUtil.FilterType.HATRED_DES_DIST_FARTHER_FIRST then
if self.isAlly == true and self._excludeOwner == true and self.owner ~= nil then
candidates:Remove(self.owner)
end
BubbleSort(self, candidates, CompareDistFromSource)
if self._sortByTauntAtLast == true then
BubbleSort(self, candidates, CompareTaunt)
end
ShrinkEntity (candidates, self.maxTargetNum)
return
end
if self._postFilter == CS.Torappu.Battle.FilterUtil.FilterType.HP_ASC then
if self.isAlly == true and self._excludeOwner == true and self.owner ~= nil then
candidates:Remove(self.owner)
end
BubbleSort(self, candidates, CompareHpAsc)
if self._sortByTauntAtLast == true then
BubbleSort(self, candidates, CompareTaunt)
end
ShrinkEntity (candidates, self.maxTargetNum)
return
end
if self._postFilter == CS.Torappu.Battle.FilterUtil.FilterType.HP_DES then
if self.isAlly == true and self._excludeOwner == true and self.owner ~= nil then
candidates:Remove(self.owner)
end
BubbleSort(self, candidates, CompareHpDes)
if self._sortByTauntAtLast == true then
BubbleSort(self, candidates, CompareTaunt)
end
ShrinkEntity (candidates, self.maxTargetNum)
return
end
if self._postFilter == CS.Torappu.Battle.FilterUtil.FilterType.FORWARD_FIRST_MANHATTAN_ASC then
if self.isAlly == true and self._excludeOwner == true and self.owner ~= nil then
candidates:Remove(self.owner)
end
BubbleSort(self, candidates, CompareForwardFirstManhattanAsc)
if self._sortByTauntAtLast == true then
BubbleSort(self, candidates, CompareTaunt)
end
ShrinkEntity (candidates, self.maxTargetNum)
return
end
self:OnPostFilter(candidates)
end
function AdvancedSelectorHotfixer:OnInit()
xlua.private_accessible(CS.Torappu.Battle.AdvancedSelector)
local Shrink = xlua.get_generic_method(CS.Torappu.CollectionExtensions, "Shrink")
ShrinkEntity = Shrink(CS.Torappu.Battle.Entity)
self:Fix_ex(CS.Torappu.Battle.AdvancedSelector, "OnPostFilter", function(self, candidates)
local ok, errorInfo = xpcall(OnPostFilterFix,debug.traceback, self, candidates)
if not ok then
eutil.LogError("[AdvancedSelectorHotfixer] fix" .. errorInfo)
end
end)
end
function AdvancedSelectorHotfixer:OnDispose()
end
return AdvancedSelectorHotfixer | 0 | 0.87604 | 1 | 0.87604 | game-dev | MEDIA | 0.842586 | game-dev | 0.976957 | 1 | 0.976957 |
PotRooms/StarResonanceData | 30,225 | lua/ui/view/fashion_system_view.lua | local UI = Z.UI
local super = require("ui.ui_view_base")
local Fashion_systemView = class("Fashion_systemView", super)
E.EFashionFirstTab = {
EClothes = 1,
EOrnament = 2,
EWeaponSkin = 3
}
local regionDataDict = {
[E.EFashionFirstTab.EClothes] = {
[1] = {
region = E.FashionRegion.Suit,
icon = "ui/atlas/item/c_tab_icon/com_icon_tab_241",
IsFocus = false
},
[2] = {
region = E.FashionRegion.UpperClothes,
icon = "ui/atlas/item/c_tab_icon/com_icon_tab_242",
IsFocus = false
},
[3] = {
region = E.FashionRegion.Pants,
icon = "ui/atlas/item/c_tab_icon/com_icon_tab_232",
IsFocus = false
},
[4] = {
region = E.FashionRegion.Gloves,
icon = "ui/atlas/item/c_tab_icon/com_icon_tab_233",
IsFocus = false
},
[5] = {
region = E.FashionRegion.Shoes,
icon = "ui/atlas/item/c_tab_icon/com_icon_tab_234",
IsFocus = false
}
},
[E.EFashionFirstTab.EOrnament] = {
[1] = {
region = E.FashionRegion.Headwear,
icon = "ui/atlas/item/c_tab_icon/com_icon_tab_235",
IsFocus = true
},
[2] = {
region = E.FashionRegion.FaceMask,
icon = "ui/atlas/item/c_tab_icon/com_icon_tab_236",
IsFocus = true
},
[3] = {
region = E.FashionRegion.MouthMask,
icon = "ui/atlas/item/c_tab_icon/com_icon_tab_237",
IsFocus = true
},
[4] = {
region = E.FashionRegion.Back,
icon = "ui/atlas/item/c_tab_icon/com_icon_tab_30",
IsFocus = false
},
[5] = {
region = E.FashionRegion.Earrings,
icon = "ui/atlas/item/c_tab_icon/com_icon_tab_243",
IsFocus = true
},
[6] = {
region = E.FashionRegion.Necklace,
icon = "ui/atlas/item/c_tab_icon/com_icon_tab_240",
IsFocus = true
},
[7] = {
region = E.FashionRegion.Ring,
icon = "ui/atlas/item/c_tab_icon/com_icon_tab_238",
IsFocus = true
}
},
[E.EFashionFirstTab.EWeaponSkin] = {
[1] = {
region = E.FashionRegion.WeapoonSkin,
icon = "ui/atlas/item/c_tab_icon/com_icon_tab_208",
IsFocus = false
}
}
}
local loopListView = require("ui.component.loop_list_view")
local second_Item = require("ui.component.fashion.fashion_second_item")
function Fashion_systemView:ctor()
self.uiBinder = nil
super.ctor(self, "fashion_system")
end
function Fashion_systemView:OnActive()
Z.AudioMgr:Play("sys_player_wardrobe_in")
if self.uiBinder.cont_tail_tab then
self.uiBinder.Ref:SetVisible(self.uiBinder.cont_tail_tab.Ref, false)
end
Z.UIMgr:SetUIViewInputIgnore(self.viewConfigKey, 4294967293, true)
Z.UnrealSceneMgr:SwitchGroupReflection(true)
self:initVM()
self:initSubView()
self:preLoadTimeline()
self:refreshUIClick(true)
self:initFashionCamera()
self:initViewData()
self:initFashionData()
self:initPlayerModel()
self:initLoopTab()
self:initFirstTab()
self:initPlayerAction()
self:initFunc()
self:onInitRed()
self:refreshCollectPoint()
self:refreshMemberCenter()
self:refreshOptionBtnState()
self:startAnimatedShow()
self:BindEvents()
end
function Fashion_systemView:OnDeActive()
self:refreshUIClick(false)
Z.UIMgr:SetUIViewInputIgnore(self.viewConfigKey, 4294967293, false)
Z.UnrealSceneMgr:SetAutoChangeLook(false)
Z.UnrealSceneMgr:RestUnrealSceneCameraZoomRange()
self:clearFirstTab()
self:clearLoopTab()
self:clearTimeLine()
self:showOrHideEffect(self.currentSelect_, false)
self.curRegion_ = nil
self.curProfessionId_ = nil
self:clearFirstTab()
self:clearModel()
self.fashionData_:Clear()
self.fashionData_:ClearWearDict()
self.fashionData_:ClearOptionList()
Z.UIMgr:CloseView("wardrobe_collection_tips")
self.firstShowIdle_ = false
self:clearRed()
if self.curSubView_ then
self.curSubView_:DeActive()
end
self.settingView_:DeActive()
end
function Fashion_systemView:OnDestory()
Z.UnrealSceneMgr:CloseUnrealScene("fashion_system")
end
function Fashion_systemView:GetCacheData()
local viewData = {
firstTab = self.curFirstTab_,
region = self.curRegion_,
wear = table.zclone(self.fashionData_:GetWears()),
color = table.zclone(self.fashionData_:GetColors())
}
return viewData
end
function Fashion_systemView:SetScrollContent(trans)
self.uiBinder.scrollview_menu:ClearAll()
self.uiBinder.scrollview_menu.content = trans
self.uiBinder.scrollview_menu:RefreshContentEvent()
self.uiBinder.scrollview_menu:Init()
end
function Fashion_systemView:initSubView()
self.styleView_ = require("ui/view/fashion_style_select_view").new(self)
self.dyeingView_ = require("ui/view/fashion_dyeing_view").new(self)
self.customizedView_ = require("ui/view/fashion_customized_sub_view").new(self)
self.weaponSkinStyleView_ = require("ui/view/fashion_weapon_skin_select_view").new(self)
self.settingView_ = require("ui/view/fashion_setting_sub_view").new(self)
end
function Fashion_systemView:initVM()
self.fashionVM_ = Z.VMMgr.GetVM("fashion")
self.fashionData_ = Z.DataMgr.Get("fashion_data")
self.faceVM_ = Z.VMMgr.GetVM("face")
self.faceData_ = Z.DataMgr.Get("face_data")
self.switchVM_ = Z.VMMgr.GetVM("switch")
end
function Fashion_systemView:refreshUIClick(openClick)
if openClick then
Z.PlayerInputController.InputTouchCheckOverUICount = 1
Z.PlayerInputController:SetCameraStretchIgnoreCheckUI(true)
Z.PlayerInputController.IsCheckZoomClickingUI = false
else
Z.PlayerInputController.InputTouchCheckOverUICount = 0
Z.PlayerInputController:SetCameraStretchIgnoreCheckUI(false)
Z.PlayerInputController.IsCheckZoomClickingUI = true
end
end
function Fashion_systemView:initFashionCamera()
Z.UnrealSceneMgr:InitSceneCamera(true)
Z.UnrealSceneMgr:SetUnrealSceneCameraZoomRange(0.25, 0.88)
Z.UnrealSceneMgr:SetZoomAutoChangeLookAtZoomRange(0.88, 0.25)
Z.UnrealSceneMgr:SetUnrealCameraScreenXY(Vector2.New(0.4, 0.5))
Z.UnrealSceneMgr:SwitchGroupReflection(true)
self.offset_ = Z.UnrealSceneMgr:GetLookAtOffsetByModelId(self.faceData_:GetPlayerModelId())
self:refreshCameraFocus(0, true)
Z.UnrealSceneMgr:SetAutoChangeLook(true)
end
function Fashion_systemView:initViewData()
self.fashionData_:ClearOptionList()
self.fashionData_:ClearWearDict()
self.fashionData_:ClearAdvanceSelectData()
self.playerModel_ = nil
self.currentSelect_ = 1
self.firstShowIdle_ = Z.StageMgr.GetIsInSelectCharScene()
self.curSubView_ = nil
end
function Fashion_systemView:initFunc()
self.uiBinder.rayimg_unrealscene_drag.onDrag:AddListener(function(go, eventData)
if Z.TouchManager.TouchCount > 1 then
return
end
self:onModelDrag(eventData)
end)
self:AddClick(self.uiBinder.btn_close, function()
self:OnInputBack()
end)
if self.uiBinder.btn_member_center then
self:AddClick(self.uiBinder.btn_member_center, function()
Z.UIMgr:OpenView("collection_window")
end)
end
self:AddClick(self.uiBinder.btn_move, function()
self.fashionVM_.MoveEditorOperation()
end)
self:AddClick(self.uiBinder.btn_return, function()
self.fashionVM_.ReturnEditorOperation()
end)
self.uiBinder.tog_setting.isOn = false
self.uiBinder.tog_setting:AddListener(function(isOn)
if isOn then
self.settingView_:Active(nil, self.uiBinder.node_setting)
else
self.settingView_:DeActive()
end
end)
self.uiBinder.Ref:SetVisible(self.uiBinder.tog_setting, not Z.StageMgr.GetIsInLogin())
self:AddClick(self.uiBinder.btn_reset, function()
self.fashionVM_.RevertAllFashionWear()
self:OpenStyleView()
end)
self:AddClick(self.uiBinder.btn_ask, function()
local helpsysVM = Z.VMMgr.GetVM("helpsys")
helpsysVM.CheckAndShowView(30040)
end)
self:AddAsyncClick(self.uiBinder.btn_custom, function()
if not self.customFunc_ then
return
end
self.customFunc_(self.customView_)
end)
self.uiBinder.Ref:SetVisible(self.uiBinder.btn_ask, true)
Z.CoroUtil.create_coro_xpcall(function()
self:asyncCheckPersonalZone()
end)()
end
function Fashion_systemView:showSubView(subView, viewData, isOpenStyle)
if self.curSubView_ then
self.curSubView_:DeActive()
end
self:refreshCustomBtn(false)
self.isOpenStyle_ = isOpenStyle
self.curSubView_ = subView
self.curSubView_:Active(viewData, self.uiBinder.node_viewport)
end
function Fashion_systemView:OpenStyleView(isPreview)
self.uiBinder.node_viewport:SetAnchorPosition(0, 0)
if self.curFirstTab_ == E.EFashionFirstTab.EWeaponSkin then
self:showSubView(self.weaponSkinStyleView_, {
region = self.curRegion_,
professionId = self.curProfessionId_
}, true)
else
self:showSubView(self.styleView_, {
region = self.curRegion_,
isPreview = isPreview
}, true)
end
end
function Fashion_systemView:OpenDyeingView(fashionId, area)
self.uiBinder.node_viewport:SetAnchorPosition(0, 0)
self:showSubView(self.dyeingView_, {
fashionId = fashionId,
area = area,
isPreview = false
}, false)
end
function Fashion_systemView:OpenCustomizedView(fashionId)
self.uiBinder.node_viewport:SetAnchorPosition(0, 0)
self:showSubView(self.customizedView_, {
fashionId = fashionId,
region = self.curRegion_,
parentView = self
}, false)
end
function Fashion_systemView:refreshDpd()
if not self.uiBinder.node_dpd_screen_narrow then
return
end
if self.curFirstTab_ ~= E.EFashionFirstTab.EWeaponSkin then
self.uiBinder.Ref:SetVisible(self.uiBinder.node_dpd_screen_narrow, false)
return
end
self.uiBinder.Ref:SetVisible(self.uiBinder.node_dpd_screen_narrow, true)
local options_ = {}
local optionToProfessionId_ = {}
local index = 1
local professionData = Z.TableMgr.GetTable("ProfessionSystemTableMgr").GetDatas()
local weaponVm = Z.VMMgr.GetVM("weapon")
local dpdIndex = 1
if not self.curProfessionId_ then
self.curProfessionId_ = weaponVm.GetCurWeapon()
end
for _, value in pairs(professionData) do
if weaponVm.CheckWeaponUnlock(value.Id) and value.IsOpen then
if self.curProfessionId_ == value.Id then
dpdIndex = index
options_[index] = value.Name .. Lang("FilterCurrent")
else
options_[index] = value.Name
end
optionToProfessionId_[index] = value.Id
index = index + 1
end
end
self.uiBinder.dpd_screen_narrow:ClearAll()
self.uiBinder.dpd_screen_narrow:AddListener(function(index)
self.curProfessionId_ = optionToProfessionId_[index + 1]
self:showSubView(self.weaponSkinStyleView_, {
region = self.curRegion_,
professionId = self.curProfessionId_
})
end, true)
self.uiBinder.dpd_screen_narrow:AddOptions(options_)
self.uiBinder.dpd_screen_narrow.value = dpdIndex - 1
end
function Fashion_systemView:onModelDrag(eventData)
if not self.playerModel_ or not self.curTimelineId_ then
return
end
self.curRotation_ = self.curRotation_ - eventData.delta.x * Z.ConstValue.ModelRotationScaleValue
local quaternion = Quaternion.Euler(Vector3.New(0, self.curRotation_, 0))
Z.UITimelineDisplay:SetGoQuaternionByCutsceneId(self.curTimelineId_, quaternion.x, quaternion.y, quaternion.z, quaternion.w)
end
function Fashion_systemView:preLoadTimeline()
Z.UITimelineDisplay:ClearTimeLine()
self.timelineInfoList_ = {}
self.curTimelineId_ = nil
local fashionConfig
if self.faceData_:GetPlayerGender() == Z.PbEnum("EGender", "GenderMale") then
fashionConfig = Z.Global.FashionShowActionM
else
fashionConfig = Z.Global.FashionShowActionF
end
for _, timelineInfo in ipairs(fashionConfig) do
local region = timelineInfo[1]
local timelineId = timelineInfo[2]
self.timelineInfoList_[region] = timelineId
end
self.playerIdleId_ = Z.ConstValue.FaceGenderTimelineId[self.faceData_:GetPlayerGender()]
if Z.StageMgr.GetIsInGameScene() then
self.curRotation_ = 180
else
self.curRotation_ = Z.ConstValue.FaceGenderRotation[self.faceData_:GetPlayerGender()]
end
Z.UITimelineDisplay:AsyncPreLoadTimeline(self.playerIdleId_, self.cancelSource:CreateToken())
end
function Fashion_systemView:refreshCollectPoint()
if not self.uiBinder.node_schedule then
return
end
if self.switchVM_.CheckFuncSwitch(E.FunctionID.CollectionReward) then
Z.CollectionScoreHelper.RefreshCollectionScore(self.uiBinder.node_schedule, function()
if not self.uiBinder then
return
end
self:onClickFashionCollectionScoreRewardRed()
end)
self.uiBinder.node_schedule.Ref.UIComp:SetVisible(true)
else
self.uiBinder.node_schedule.Ref.UIComp:SetVisible(false)
end
end
function Fashion_systemView:refreshMemberCenter()
if not self.uiBinder.btn_member_center then
return
end
if not Z.StageMgr.GetIsInLogin() and self.switchVM_.CheckFuncSwitch(E.FunctionID.CollectionVipLevel) then
self.uiBinder.Ref:SetVisible(self.uiBinder.btn_member_center, true)
else
self.uiBinder.Ref:SetVisible(self.uiBinder.btn_member_center, false)
end
end
function Fashion_systemView:asyncCheckPersonalZone()
if not Z.StageMgr.GetIsInLogin() then
return
end
if not Z.ContainerMgr.CharSerialize.personalZone.fashionRefreshFlag then
return
end
self.fashionVM_.AsyncRefreshPersonalZoneFashionScore()
end
function Fashion_systemView:OnRefresh()
if self.viewData then
if self.viewData.gotoData then
self:onFashionSaveConfirmItemClick(self.viewData.gotoData)
else
self.fashionVM_.RefreshWearAttr()
end
end
end
function Fashion_systemView:clearModel()
Z.UnrealSceneMgr:ClearModel(self.playerModel_)
self.playerModel_ = nil
end
function Fashion_systemView:showOrHideEffect(tabIndex, isShow)
local effect = self.uiBinder[string.zconcat("eff_root", tabIndex)]
if effect then
effect:SetEffectGoVisible(isShow)
end
end
function Fashion_systemView:initLoopTab()
self.secondLoopListView_ = loopListView.new(self, self.uiBinder.loop_tab, second_Item, "fashion_item_tab", true)
self.secondLoopListView_:Init({})
end
function Fashion_systemView:clearLoopTab()
self.secondLoopListView_:UnInit()
end
function Fashion_systemView:clearTimeLine()
self.timelineInfoList_ = nil
if self.curTimelineId_ then
self.curRotation_ = Z.ConstValue.FaceGenderRotation[self.faceData_:GetPlayerGender()]
local quaternion = Quaternion.Euler(Vector3.New(0, self.curRotation_, 0))
Z.UITimelineDisplay:SetGoQuaternionByCutsceneId(self.curTimelineId_, quaternion.x, quaternion.y, quaternion.z, quaternion.w)
end
self.curTimelineId_ = nil
Z.UITimelineDisplay:ClearTimeLine()
end
function Fashion_systemView:initFirstTab()
self.uiBinder.tog_clothes.tog_tab_select.group = self.uiBinder.toggle_group
self.uiBinder.tog_ornament.tog_tab_select.group = self.uiBinder.toggle_group
self.uiBinder.tog_weapon.tog_tab_select.group = self.uiBinder.toggle_group
self.uiBinder.tog_clothes.tog_tab_select:AddListener(function(isOn)
if not isOn then
return
end
self.curFirstTab_ = E.EFashionFirstTab.EClothes
self.curProfessionId_ = nil
self:refreshSecondList()
self:refreshSecondListSelect(self.curRegion_)
self.uiBinder.Ref:SetVisible(self.uiBinder.loop_tab, true)
self:onClickClothesRed()
end)
self.uiBinder.tog_ornament.tog_tab_select:AddListener(function(isOn)
if not isOn then
return
end
self.curFirstTab_ = E.EFashionFirstTab.EOrnament
self.curProfessionId_ = nil
self:refreshSecondList()
self:refreshSecondListSelect(self.curRegion_)
self.uiBinder.Ref:SetVisible(self.uiBinder.loop_tab, true)
self:onClickOrnamentRed()
end)
self.uiBinder.tog_weapon.tog_tab_select:AddListener(function(isOn)
if not isOn then
return
end
self.curFirstTab_ = E.EFashionFirstTab.EWeaponSkin
self.uiBinder.Ref:SetVisible(self.uiBinder.loop_tab, false)
self:OnSwitchRegion(E.FashionRegion.WeapoonSkin)
end)
self.curFirstTab_ = E.EFashionFirstTab.EClothes
if self.viewData and self.viewData.firstTab then
self.curFirstTab_ = self.viewData.firstTab
end
local curRegion
if self.viewData and self.viewData.region then
curRegion = self.viewData.region
elseif self.curFirstTab_ == E.EFashionFirstTab.EClothes then
curRegion = E.FashionRegion.Suit
elseif self.curFirstTab_ == E.EFashionFirstTab.EOrnament then
curRegion = E.FashionRegion.Headwear
end
if self.curFirstTab_ == E.EFashionFirstTab.EClothes then
self.uiBinder.Ref:SetVisible(self.uiBinder.loop_tab, true)
self.uiBinder.tog_clothes.tog_tab_select:SetIsOnWithoutCallBack(true)
self:refreshSecondList()
self:refreshSecondListSelect(curRegion)
elseif self.curFirstTab_ == E.EFashionFirstTab.EOrnament then
self.uiBinder.Ref:SetVisible(self.uiBinder.loop_tab, true)
self.uiBinder.tog_ornament.tog_tab_select:SetIsOnWithoutCallBack(true)
self:refreshSecondList()
self:refreshSecondListSelect(curRegion)
elseif self.curFirstTab_ == E.EFashionFirstTab.EWeaponSkin then
self.uiBinder.Ref:SetVisible(self.uiBinder.loop_tab, false)
self.uiBinder.tog_weapon.tog_tab_select:SetIsOnWithoutCallBack(true)
end
self.uiBinder.tog_weapon.Ref.UIComp:SetVisible(not Z.StageMgr.GetIsInLogin())
self:OnSwitchRegion(curRegion)
end
function Fashion_systemView:refreshSecondListSelect(curRegion)
local index = self:getRegionIndex(regionDataDict[self.curFirstTab_], curRegion)
self.secondLoopListView_:ClearAllSelect()
self.secondLoopListView_:SetSelected(index)
end
function Fashion_systemView:refreshSecondList()
self.fashionVM_.RefreshFashionHideRegion()
self.secondLoopListView_:RefreshListView(regionDataDict[self.curFirstTab_], false)
end
function Fashion_systemView:refreshCustomBtn(isShowCustom, customlab, func, isDisable, view)
self.uiBinder.Ref:SetVisible(self.uiBinder.btn_custom, isShowCustom)
if isShowCustom then
self.uiBinder.lab_custom.text = Lang(customlab)
self.customFunc_ = func
self.customView_ = view
self.uiBinder.btn_custom.IsDisabled = isDisable
self.uiBinder.btn_custom.interactable = not isDisable
else
self.customFunc_ = nil
self.customView_ = nil
end
end
function Fashion_systemView:GetBtnCustomRef()
return self.uiBinder.node_custom_ref
end
function Fashion_systemView:getRegionIndex(list, region)
local index = 1
if region then
for i = 1, #list do
if list[i].region == region then
index = i
break
end
end
end
return index
end
function Fashion_systemView:clearFirstTab()
self.uiBinder.tog_clothes.tog_tab_select:RemoveAllListeners()
self.uiBinder.tog_ornament.tog_tab_select:RemoveAllListeners()
self.uiBinder.tog_weapon.tog_tab_select:RemoveAllListeners()
self.uiBinder.tog_clothes.tog_tab_select.group = nil
self.uiBinder.tog_ornament.tog_tab_select.group = nil
self.uiBinder.tog_weapon.tog_tab_select.group = nil
self.uiBinder.tog_clothes.tog_tab_select.isOn = false
self.uiBinder.tog_ornament.tog_tab_select.isOn = false
self.uiBinder.tog_weapon.tog_tab_select.isOn = false
end
function Fashion_systemView:initPlayerAction()
if not self.firstShowIdle_ then
return
end
self:playModelIdleAction()
local quaternion = Quaternion.Euler(Vector3.New(0, self.curRotation_, 0))
Z.UITimelineDisplay:SetGoQuaternionByCutsceneId(self.playerIdleId_, quaternion.x, quaternion.y, quaternion.z, quaternion.w)
end
function Fashion_systemView:OnSwitchRegion(region)
self.curRegion_ = region
self:refreshDpd()
self:OpenStyleView()
self:refreshViewTitle()
self:refreshModelAction()
self:changeCameraFocus()
self:refreshImgActionNarrow()
end
function Fashion_systemView:refreshImgActionNarrow()
self.uiBinder.Ref:SetVisible(self.uiBinder.img_action, false)
self.uiBinder.Ref:SetVisible(self.uiBinder.node_dpd_screen_narrow, self.curFirstTab_ == E.EFashionFirstTab.EWeaponSkin)
end
function Fashion_systemView:refreshViewTitle()
local regionName = self.fashionVM_.GetRegionName(self.curRegion_)
local commonVM = Z.VMMgr.GetVM("common")
local funcName = commonVM.GetTitleByConfig(E.FunctionID.Fashion)
local titleStr = funcName .. "/" .. regionName
self.uiBinder.lab_title.text = titleStr
end
function Fashion_systemView:initFashionData()
if self.viewData and self.viewData.gotoData and self.viewData.gotoData.FashionId then
local region = self.fashionVM_.GetFashionRegion(self.viewData.gotoData.FashionId)
self.fashionData_:SetWear(region, {
fashionId = self.viewData.gotoData.FashionId
})
if region == E.FashionRegion.WeapoonSkin then
local row = Z.TableMgr.GetTable("WeaponSkinTableMgr").GetRow(self.viewData.gotoData.FashionId, true)
if row then
self.curProfessionId_ = row.ProfessionId
end
end
end
self.fashionData_:InitFashionData()
if self.viewData and self.viewData.wear then
self.fashionData_:SetAllWear(self.viewData.wear)
end
if self.viewData and self.viewData.color then
self.fashionData_:SetAllColor(self.viewData.color)
end
end
function Fashion_systemView:initPlayerModel()
self.playerModel_ = Z.UnrealSceneMgr:GetCachePlayerModel(function(model)
Z.UnrealSceneMgr:SetModelCustomShadow(model, false)
model:SetAttrGoPosition(Z.UnrealSceneMgr:GetTransPos("pos"))
model:SetAttrGoRotation(Quaternion.Euler(Vector3.New(0, self.curRotation_, 0)))
model:SetLuaAttrLookAtEnable(true)
if self.curFirstTab_ ~= E.EFashionFirstTab.EWeaponSkin then
model:SetLuaAttr(Z.ModelAttr.EModelCMountWeaponL, "")
model:SetLuaAttr(Z.ModelAttr.EModelCMountWeaponR, "")
end
end, function(model)
Z.UIMgr:FadeOut()
local fashionVm = Z.VMMgr.GetVM("fashion")
fashionVm.SetModelAutoLookatCamera(model)
end)
end
function Fashion_systemView:ShowSaveBtn()
self:refreshCustomBtn(true, "Save", self.onClickSaveAll, false, self)
end
function Fashion_systemView:refreshModelAction()
if self.firstShowIdle_ then
self.firstShowIdle_ = false
return
end
local timelineId = self.timelineInfoList_[self.curRegion_]
if not timelineId then
return
end
Z.UITimelineDisplay:RemoveGoQuaternionByCutsceneId(timelineId)
if self.curTimelineId_ ~= timelineId then
Z.UITimelineDisplay:Stop()
if timelineId then
Z.UITimelineDisplay:BindModel(0, self.playerModel_)
Z.UITimelineDisplay:Play(timelineId, nil, function()
self:playModelIdleAction()
end)
end
self.curTimelineId_ = timelineId
end
local quaternion = Quaternion.Euler(Vector3.New(0, self.curRotation_, 0))
Z.UITimelineDisplay:SetGoQuaternionByCutsceneId(timelineId, quaternion.x, quaternion.y, quaternion.z, quaternion.w)
end
function Fashion_systemView:playModelIdleAction()
if not self.playerModel_ then
return
end
local quaternion = Quaternion.Euler(Vector3.New(0, self.curRotation_, 0))
Z.UITimelineDisplay:SetGoQuaternionByCutsceneId(self.playerIdleId_, quaternion.x, quaternion.y, quaternion.z, quaternion.w)
Z.UITimelineDisplay:BindModel(0, self.playerModel_)
Z.UITimelineDisplay:Play(self.playerIdleId_)
self.curTimelineId_ = self.playerIdleId_
end
function Fashion_systemView:changeCameraFocus()
local isOnHead = false
for i = 1, #regionDataDict[self.curFirstTab_] do
if regionDataDict[self.curFirstTab_][i].region == self.curRegion_ then
isOnHead = regionDataDict[self.curFirstTab_][i].IsFocus
break
end
end
if isOnHead then
Z.UnrealSceneMgr:DoCameraAnimLookAtOffset("faceFocusHead", Vector3.New(0, self.offset_.x, 0))
else
Z.UnrealSceneMgr:DoCameraAnimLookAtOffset("faceFocusBody", Vector3.New(0, self.offset_.y, 0))
end
end
function Fashion_systemView:OnInputBack()
if self.isOpenStyle_ then
local saveVM = Z.VMMgr.GetVM("fashion_save_tips")
if saveVM.IsFashionWearChange() then
Z.DialogViewDataMgr:CheckAndOpenPreferencesDialog(Lang("UnSaveFashionColor"), function()
self.fashionVM_.CloseFashionSystemView()
end, nil, E.DlgPreferencesType.Never, E.DlgPreferencesKeyType.UnSaveFashionColor)
else
self.fashionVM_.CloseFashionSystemView()
end
else
self:OpenStyleView()
end
end
function Fashion_systemView:onClickSaveAll()
local saveVM = Z.VMMgr.GetVM("fashion_save_tips")
local dataList = saveVM.GetFashionConfirmDataList()
if 0 < #dataList then
saveVM.OpenSaveTipsView()
elseif self.curFirstTab_ == E.EFashionFirstTab.EWeaponSkin then
local weaponSkillSkinVm = Z.VMMgr.GetVM("weapon_skill_skin")
local styleData = self.fashionData_:GetWear(self.curRegion_)
if styleData == nil then
return
end
weaponSkillSkinVm:AsyncUseProfessionSkin(self.curProfessionId_, styleData.fashionId, self.cancelSource:CreateToken())
else
self.fashionVM_.AsyncSaveAllFashion(self.cancelSource)
end
end
function Fashion_systemView:BindEvents()
Z.EventMgr:Add(Z.ConstValue.FashionAttrChange, self.onFashionAttrChange, self)
Z.EventMgr:Add(Z.ConstValue.FashionSaveConfirmItemClick, self.onFashionSaveConfirmItemClick, self)
Z.EventMgr:Add(Z.ConstValue.Fashion.ModelMatRaiseHeight, self.refreshCameraFocus, self)
Z.EventMgr:Add(Z.ConstValue.Collection.FashionCollectionPointChange, self.refreshCollectPoint, self)
Z.EventMgr:Add(Z.ConstValue.Fashion.FashionOptionStateChange, self.refreshOptionBtnState, self)
Z.EventMgr:Add(Z.ConstValue.Fashion.FashionWearChange, self.refreshSecondList, self)
Z.EventMgr:Add(Z.ConstValue.Fashion.FashionSettingChange, self.refreshSecondList, self)
Z.EventMgr:Add(Z.ConstValue.Fashion.FashionSystemShowCustomBtn, self.refreshCustomBtn, self)
end
function Fashion_systemView:onInitRed()
if self.uiBinder.node_schedule then
Z.RedPointMgr.LoadRedDotItem(E.RedType.FashionCollectionScoreRewardRed, self, self.uiBinder.node_schedule.node_red)
end
if self.uiBinder.btn_member_center_trans then
Z.RedPointMgr.LoadRedDotItem(E.RedType.FashionCollectionWindowRed, self, self.uiBinder.btn_member_center_trans)
end
Z.RedPointMgr.LoadRedDotItem(E.RedType.FashionClothes, self, self.uiBinder.tog_clothes.Trans)
Z.RedPointMgr.LoadRedDotItem(E.RedType.FashionOrnament, self, self.uiBinder.tog_ornament.Trans)
Z.RedPointMgr.LoadRedDotItem(E.RedType.FashionWeapon, self, self.uiBinder.tog_weapon.Trans)
end
function Fashion_systemView:onClickClothesRed()
Z.RedPointMgr.OnClickRedDot(E.RedType.FashionClothes)
end
function Fashion_systemView:onClickOrnamentRed()
Z.RedPointMgr.OnClickRedDot(E.RedType.FashionOrnament)
end
function Fashion_systemView:onClickFashionCollectionScoreRewardRed()
Z.RedPointMgr.OnClickRedDot(E.RedType.FashionCollectionScoreRewardRed)
end
function Fashion_systemView:clearRed()
Z.RedPointMgr.RemoveNodeItem(E.RedType.FashionCollectionScoreRewardRed)
Z.RedPointMgr.RemoveNodeItem(E.RedType.FashionCollectionWindowRed)
Z.RedPointMgr.RemoveNodeItem(E.RedType.FashionClothes)
Z.RedPointMgr.RemoveNodeItem(E.RedType.FashionOrnament)
Z.RedPointMgr.RemoveNodeItem(E.RedType.FashionWeapon)
end
function Fashion_systemView:refreshCameraFocus(value, init)
if not init then
return
end
local EModelPinchHeight = self.faceVM_.GetFaceOptionByAttrType(Z.ModelAttr.EModelPinchHeight)
local heightSliderValue = math.floor(EModelPinchHeight * 10 + 0.5)
local scale = self.faceVM_.GetLookAtOffsetScale(E.ELookAtScaleType.BodyHeight)
Z.UnrealSceneMgr:SetZoomAutoChangeLookAtByOffset(self.offset_.x + heightSliderValue / scale, self.offset_.y)
end
function Fashion_systemView:onFashionAttrChange(attrType, ...)
if not self.playerModel_ then
return
end
local arg = {
...
}
self:setAllModelAttr("SetLuaAttr", attrType, table.unpack(arg))
end
function Fashion_systemView:setAllModelAttr(funcName, ...)
local arg = {
...
}
self.playerModel_[funcName](self.playerModel_, table.unpack(arg))
end
function Fashion_systemView:SetLuaIntModelAttr(attrType, ...)
if not self.playerModel_ then
return
end
local arg = {
...
}
self.playerModel_:SetLuaIntAttr(attrType, table.unpack(arg))
end
function Fashion_systemView:onFashionSaveConfirmItemClick(confirmData)
local fashionId = confirmData.FashionId
if confirmData.FashionIdList and #confirmData.FashionIdList > 0 then
for i = 1, #confirmData.FashionIdList do
local itemId = confirmData.FashionIdList[i]
if self.fashionVM_.CheckIsFashion(itemId) then
self.fashionVM_.SetFashionWearByFashionId(itemId)
end
end
end
if fashionId then
self.curRegion_ = self.fashionVM_.GetFashionRegion(fashionId)
elseif confirmData.Region then
self.curRegion_ = confirmData.Region
else
self.curRegion_ = E.FashionRegion.Suit
end
if self:isListHaveRegion(regionDataDict[E.EFashionFirstTab.EClothes], self.curRegion_) then
if self.uiBinder.tog_clothes.tog_tab_select.isOn then
self:refreshSecondListSelect(self.curRegion_)
else
self.uiBinder.tog_clothes.tog_tab_select.isOn = true
end
elseif self:isListHaveRegion(regionDataDict[E.EFashionFirstTab.EOrnament], self.curRegion_) then
if self.uiBinder.tog_ornament.tog_tab_select.isOn then
self:refreshSecondListSelect(self.curRegion_)
else
self.uiBinder.tog_ornament.tog_tab_select.isOn = true
end
elseif self.curRegion_ == E.FashionRegion.WeapoonSkin then
self.uiBinder.tog_weapon.tog_tab_select.isOn = true
end
local reason = confirmData.Reason
if reason == E.FashionTipsReason.UnlockedColor and fashionId then
self:OpenDyeingView(fashionId, confirmData.AreaList[1])
end
end
function Fashion_systemView:isListHaveRegion(list, region)
for i = 1, #list do
if list[i].region == region then
return true
end
end
return false
end
function Fashion_systemView:refreshOptionBtnState()
local optionCount = #self.fashionData_:GetOptionList()
self.uiBinder.btn_move.IsDisabled = optionCount <= self.fashionData_.OptionIndex
self.uiBinder.btn_return.IsDisabled = self.fashionData_.OptionIndex <= 0
end
function Fashion_systemView:startPlaySelectAnim()
end
function Fashion_systemView:startPlaySelect2Anim()
end
function Fashion_systemView:startTabPlaySelectAnim()
end
function Fashion_systemView:startAnimatedShow()
end
function Fashion_systemView:startAnimatedHide()
end
function Fashion_systemView:CustomClose()
end
return Fashion_systemView
| 0 | 0.845676 | 1 | 0.845676 | game-dev | MEDIA | 0.676495 | game-dev | 0.963571 | 1 | 0.963571 |
woowacourse-teams/2024-pokerogue-helper | 7,289 | backend/pokerogue/src/main/java/com/pokerogue/external/extraction/weather.test.ts | // import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
//
// import { WeatherType } from "#app/enums/weather-type";
// import { arenaFlyout } from "#app/locales/ko/arena-flyout";
// import { weather } from "#app/locales/ko/weather.ts";
// import { Weather } from "#app/data/weather.ts";
// import * as fs from "fs";
// import * as path from 'path';
// import i18next, { init } from "i18next";
// import { exit } from "process";
// import GameManager from "#test/utils/gameManager";
//
// const filePath = path.join(__dirname, 'weather.txt');
// const logStream = fs.createWriteStream(filePath, { flags: 'w' });
// console.log = (...args: any[]) => {
// const message = args.map(arg => typeof arg === 'object' ? JSON.stringify(arg) : arg).join(' ');
// logStream.write(message + '\n');
// };
//
// describe("Weather", () => {
// let phaserGame: Phaser.Game;
// let game: GameManager;
// const TIMEOUT = 1000 * 20;
//
// beforeAll(() => {
// });
//
// afterEach(() => {
// });
//
// beforeEach(() => {
// });
//
// // const print = (((x: PokemonForm, sp: PokemonSpecies, pokemonId: integer, passive: Abilities, eggMoves, moves, biomes) => {
// // var ret = []
// // // id
// // ret.push(pokemonId)
// // ret.push(x.speciesId)
// // //name
// // ret.push(sp.name +"-"+ x.formName)
// // // type
// // ret.push(i18next.t(`pokemonInfo:Type.${Type[x.type2]}`))
// // ret.push(i18next.t(`pokemonInfo:Type.${Type[x.type1]}`))
// // // ability (todo: passive)
// // ret.push(new Ability(x.ability1, x.generation).name)
// // ret.push(new Ability(x.ability2, x.generation).name)
// // ret.push(new Ability(x.abilityHidden, x.generation).name)
// // ret.push(new Ability(passive, x.generation).name)
// // // metadata
// // ret.push(x.generation)
// // ret.push(sp.legendary)
// // ret.push(sp.subLegendary)
// // ret.push(sp.mythical)
// // // evolution (speciesId, level)
// // ret.push(sp.getEvolutionLevels())
// // // stats (baseHp, baseAtk, baseDef, baseSpatk, baseSpdef, baseSpd)
// // ret.push(x.baseTotal)
// // ret.push(x.baseStats)
// // ret.push(x.height)
// // ret.push(x.weight)
// // // form
// // ret.push(sp.canChangeForm)
// // // eggMoves
// // var tmp = []
// // for(let i =0; i < eggMoves.length; i++){
// // tmp.push(eggMoves[i].name)
// // }
// // ret.push(tmp)
// // // moves
// // tmp = []
// // for(let i =0; i < moves.length; i++){
// // tmp.push(moves[i][1].name)
// // }
// // ret.push(tmp)
//
//
// // tmp = []
// // for(let i =0; i < biomes.length; i++){
// // tmp.push(getBiomeName(biomes[i]))
// // }
// // ret.push(tmp)
//
// // console.log(ret.join(" / "))
// // }));
//
//
//
// // const print2 = (((x: PokemonSpecies, pokemonId: integer, passive: Abilities, eggMoves, moves, biomes
// // ) => {
// // var ret = []
// // // id
// // ret.push(pokemonId)
// // ret.push(x.speciesId)
// // //name
// // ret.push(x.name)
// // // type
// // ret.push(i18next.t(`pokemonInfo:Type.${Type[x.type2]}`))
// // ret.push(i18next.t(`pokemonInfo:Type.${Type[x.type1]}`))
// // // ability (todo: passive)
// // ret.push(new Ability(x.ability1, x.generation).name)
// // ret.push(new Ability(x.ability2, x.generation).name)
// // ret.push(new Ability(x.abilityHidden, x.generation).name)
// // ret.push(new Ability(passive, x.generation).name)
// // // metadata
// // ret.push(x.generation)
// // ret.push(x.legendary)
// // ret.push(x.subLegendary)
// // ret.push(x.mythical)
// // // evolution (speciesId, level)
// // ret.push(x.getEvolutionLevels())
// // // stats (baseHp, baseAtk, baseDef, baseSpatk, baseSpdef, baseSpd)
// // ret.push(x.baseTotal)
// // ret.push(x.baseStats)
// // ret.push(x.height)
// // ret.push(x.weight)
// // // form
// // ret.push(x.canChangeForm)
// // // eggMoves
// // var tmp = []
// // for(let i =0; i < eggMoves.length; i++){
// // tmp.push(eggMoves[i].name)
// // }
// // ret.push(tmp)
// // // moves
// // tmp = []
// // for(let i =0; i < moves.length; i++){
// // tmp.push(moves[i][1].name)
// // }
// // ret.push(tmp)
//
//
// // tmp = []
// // for(let i =0; i < biomes.length; i++){
// // tmp.push(getBiomeName(biomes[i]))
// // }
// // ret.push(tmp)
//
// // console.log(ret.join(" / "))
// // }));
//
// function getEnumValues<T>(enumObj: T): T[keyof T][] {
// return Object.values(enumObj).filter(value => typeof value === 'number') as T[keyof T][];
// }
//
// function toCamelCase(str: string): string {
// return str
// .toLowerCase()
// .replace(/_./g, match => match.charAt(1).toUpperCase());
// }
//
// it("날씨 정보 추출 테스트", async () => {
// console.log("이름 / 출력 메시지 / 효과")
// console.log()
// console.log("없음 / 없음 / 없음")
//
// const weatherTypes: WeatherType[] = getEnumValues(WeatherType);
// for (let i = 1; i < weatherTypes.length; i++) {
// var ret = []
// ret.push(i18next.t(`arenaFlyout:${toCamelCase(WeatherType[i])}`))
// ret.push(i18next.t(`weather:${toCamelCase(WeatherType[i]) + "LapseMessage"}`))
// if (i === 1) {
// ret.push("불꽃 타입 기술의 위력이 1.5배가 된다 , 물 타입 기술의 위력이 0.5배가 된다")
// }
// if (i === 2) {
// ret.push("물 타입 기술의 위력이 1.5배가 된다 , 불꽃 타입 기술의 위력이 0.5배가 된다")
// }
// if (i === 3) {
// ret.push("바위 또는 땅 또는 강철 타입 포켓몬이 아니면 매 턴마다 체력의 1/16의 데미지를 받는다 , 바위 타입 포켓몬의 특수방어가 1.5배가 된다")
// }
// if (i === 4) {
// ret.push("얼음 타입 포켓몬이 아니면 매 턴마다 체력의 1/16의 데미지를 받는다")
// }
// if (i === 5) {
// ret.push("얼음 타입 포켓몬의 방어가 1.5배 올라간다")
// }
// if (i === 6) {
// ret.push("모든 기술의 명중률이 0.9배가 된다")
// }
// if (i === 7) {
// ret.push("불타입 기술은 모두 실패한다 , 불꽃 타입 기술의 위력이 1.5배가 된다 , 물 타입 기술의 위력이 1.5배가 된다")
// }
// if (i === 8) {
// ret.push("물타입 기술은 모두 실패한다 , 불꽃 타입 기술의 위력이 1.5배가 된다 , 물 타입 기술의 위력이 0.5배가 된다")
// }
// if (i === 9) {
// ret.push("비행 타입의 약점을 없애준다")
// }
// console.log(ret.join(" / "))
// }
//
// // for (let i = 0; i < allSpecies.length; i++) {
// // let x = allSpecies[i]
//
// // var passive = starterPassiveAbilities[x.getRootSpeciesId()]
// // var eggMoves: Moves[] = speciesEggMoves[x.getRootSpeciesId()].map((value, index, arr) => allMoves[value])
// // var moves = pokemonSpeciesLevelMoves[x.getRootSpeciesId()].map((value, index, arr) => [value[0], allMoves[value[1]]])
// // var biomes = biomeMap.get(Species[x.speciesId])
// // print2(x, pokemonId++, passive, eggMoves, moves, biomes)
// // if (x.canChangeForm) {
// // for (var form of x.forms) {
// // // if(form.formName.toLowerCase() === "normal"){
// // // continue
// // // }
// // print(form, x, pokemonId++, passive, eggMoves, moves, biomes)
// // }
// // }
// // }
// });
// });
| 0 | 0.584529 | 1 | 0.584529 | game-dev | MEDIA | 0.909248 | game-dev | 0.596802 | 1 | 0.596802 |
DomCR/ACadSharp | 6,800 | src/ACadSharp.Tests/DxfMapTests.cs | using ACadSharp.Attributes;
using ACadSharp.Blocks;
using ACadSharp.Entities;
using ACadSharp.Tables;
using ACadSharp.Tests.Common;
using System;
using System.Collections.Generic;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Reflection;
using System.Text;
using Xunit;
namespace ACadSharp.Tests
{
public class DxfMapTests
{
public static readonly TheoryData<Type> Types;
static DxfMapTests()
{
Types = new TheoryData<Type>();
var d = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.ManifestModule.Name == "ACadSharp.dll");
foreach (var item in d.GetTypes().Where(i => !i.IsAbstract && i.IsPublic))
{
if (item.IsSubclassOf(typeof(Entity)) || item.IsSubclassOf(typeof(TableEntry)))
{
Types.Add(item);
}
}
}
[Theory(Skip = "Moved to internal")]
[MemberData(nameof(Types))]
public void CreateMapTest(Type t)
{
DxfNameAttribute att = t.GetCustomAttribute<DxfNameAttribute>();
DxfSubClassAttribute subclass = t.GetCustomAttribute<DxfSubClassAttribute>();
Assert.NotNull(att);
if (subclass != null)
{
CadObject obj = Factory.CreateObject(t);
Assert.True(obj.SubclassMarker == subclass.ClassName);
}
switch (att.Name)
{
case DxfFileToken.TableAppId:
DxfMap.Create<AppId>();
break;
case DxfFileToken.EntityAttribute:
DxfMap.Create<AttributeEntity>();
break;
case DxfFileToken.EntityAttributeDefinition:
DxfMap.Create<AttributeDefinition>();
return;
case DxfFileToken.EntityArc:
DxfMap.Create<Arc>();
break;
case DxfFileToken.Block:
DxfMap.Create<Block>();
break;
case DxfFileToken.EndBlock:
DxfMap.Create<BlockEnd>();
break;
case DxfFileToken.TableBlockRecord:
DxfMap.Create<BlockRecord>();
break;
case DxfFileToken.EntityCircle:
DxfMap.Create<Circle>();
break;
case DxfFileToken.TableDimstyle:
DxfMap.Create<DimensionStyle>();
break;
case DxfFileToken.EntityDimension:
Assert.NotNull(subclass);
switch (subclass.ClassName)
{
case DxfSubclassMarker.AlignedDimension:
DxfMap.Create<DimensionAligned>();
break;
case DxfSubclassMarker.Angular2LineDimension:
DxfMap.Create<DimensionAngular2Line>();
break;
case DxfSubclassMarker.Angular3PointDimension:
DxfMap.Create<DimensionAngular3Pt>();
break;
case DxfSubclassMarker.DiametricDimension:
DxfMap.Create<DimensionDiameter>();
break;
case DxfSubclassMarker.LinearDimension:
DxfMap.Create<DimensionLinear>();
break;
case DxfSubclassMarker.OrdinateDimension:
DxfMap.Create<DimensionOrdinate>();
break;
case DxfSubclassMarker.RadialDimension:
DxfMap.Create<DimensionRadius>();
break;
default:
throw new NotImplementedException($"Test not implemented for type {t.Name}");
}
break;
case DxfFileToken.EntityEllipse:
DxfMap.Create<Ellipse>();
break;
case DxfFileToken.Entity3DFace:
DxfMap.Create<Face3D>();
break;
case DxfFileToken.EntityHatch:
DxfMap.Create<Hatch>();
break;
case DxfFileToken.EntityInsert:
DxfMap.Create<Insert>();
break;
case DxfFileToken.TableLayer:
DxfMap.Create<Layer>();
break;
case DxfFileToken.EntityLeader:
DxfMap.Create<Leader>();
break;
case DxfFileToken.TableLinetype:
DxfMap.Create<LineType>();
break;
case DxfFileToken.EntityLine:
DxfMap.Create<Line>();
break;
case DxfFileToken.EntityLwPolyline:
DxfMap.Create<LwPolyline>();
break;
case DxfFileToken.EntityMesh:
DxfMap.Create<Mesh>();
break;
case DxfFileToken.EntityMLine:
DxfMap.Create<MLine>();
break;
case DxfFileToken.EntityMText:
DxfMap.Create<MText>();
break;
case DxfFileToken.EntityPoint:
DxfMap.Create<Point>();
break;
case DxfFileToken.EntityPolyFaceMesh:
DxfMap.Create<PolyfaceMesh>();
break;
case DxfFileToken.EntityPolyline:
switch (subclass.ClassName)
{
case DxfSubclassMarker.Polyline:
DxfMap.Create<Polyline2D>();
break;
case DxfSubclassMarker.Polyline3d:
DxfMap.Create<Polyline3D>();
break;
case DxfSubclassMarker.PolyfaceMesh:
DxfMap.Create<PolyfaceMesh>();
break;
default:
throw new NotImplementedException($"Test not implemented for type {t.Name}");
}
break;
case DxfFileToken.EntityRay:
DxfMap.Create<Ray>();
break;
case DxfFileToken.EntityShape:
DxfMap.Create<Shape>();
break;
case DxfFileToken.EntitySeqend:
DxfMap.Create<Seqend>();
break;
case DxfFileToken.EntitySolid:
DxfMap.Create<Solid>();
break;
case DxfFileToken.Entity3DSolid:
DxfMap.Create<Solid3D>();
break;
case DxfFileToken.EntitySpline:
DxfMap.Create<Spline>();
break;
case DxfFileToken.EntityText:
DxfMap.Create<TextEntity>();
break;
case DxfFileToken.TableStyle:
DxfMap.Create<TextStyle>();
break;
case DxfFileToken.TableUcs:
DxfMap.Create<UCS>();
break;
case DxfFileToken.EntityVertex:
Assert.NotNull(subclass);
switch (subclass.ClassName)
{
case DxfSubclassMarker.PolylineVertex:
DxfMap.Create<Vertex2D>();
break;
case DxfSubclassMarker.Polyline3dVertex:
DxfMap.Create<Vertex3D>();
break;
case DxfSubclassMarker.PolyfaceMeshVertex:
DxfMap.Create<VertexFaceMesh>();
break;
case DxfSubclassMarker.PolyfaceMeshFace:
DxfMap.Create<VertexFaceRecord>();
break;
default:
throw new NotImplementedException($"Test not implemented for type {t.Name}");
}
break;
case DxfFileToken.TableView:
DxfMap.Create<View>();
break;
case DxfFileToken.EntityViewport:
DxfMap.Create<Viewport>();
break;
case DxfFileToken.TableVport:
DxfMap.Create<VPort>();
break;
case DxfFileToken.EntityWipeout:
DxfMap.Create<Wipeout>();
break;
case DxfFileToken.EntityXline:
DxfMap.Create<XLine>();
break;
default:
throw new NotImplementedException($"Test not implemented for type {t.Name}");
}
}
[Fact]
public void TableEntryMapTest()
{
var map = DxfMap.Create<AppId>();
Assert.True(map.SubClasses.ContainsKey(DxfSubclassMarker.TableRecord));
Assert.True(map.SubClasses.ContainsKey(DxfSubclassMarker.ApplicationId));
}
[Fact]
public void PolylineMapTest()
{
var map = DxfMap.Create<Polyline2D>();
Assert.True(map.SubClasses.ContainsKey(DxfSubclassMarker.Entity));
Assert.True(map.SubClasses.ContainsKey(DxfSubclassMarker.Polyline));
}
}
}
| 0 | 0.783967 | 1 | 0.783967 | game-dev | MEDIA | 0.511984 | game-dev | 0.899672 | 1 | 0.899672 |
luceneplusplus/LucenePlusPlus | 1,634 | include/lucene++/HitQueueBase.h | /////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009-2014 Alan Wright. All rights reserved.
// Distributable under the terms of either the Apache License (Version 2.0)
// or the GNU Lesser General Public License.
/////////////////////////////////////////////////////////////////////////////
#ifndef HITQUEUEBASE_H
#define HITQUEUEBASE_H
#include "PriorityQueue.h"
namespace Lucene {
class LPPAPI HitQueueBase : public LuceneObject {
public:
HitQueueBase(int32_t size);
virtual ~HitQueueBase();
LUCENE_CLASS(HitQueueBase);
public:
virtual ScoreDocPtr add(const ScoreDocPtr& scoreDoc);
virtual ScoreDocPtr addOverflow(const ScoreDocPtr& scoreDoc);
virtual ScoreDocPtr top();
virtual ScoreDocPtr pop();
virtual ScoreDocPtr updateTop();
virtual int32_t size();
virtual bool empty();
virtual void clear();
protected:
PriorityQueueScoreDocsPtr queue;
int32_t queueSize;
public:
virtual void initialize();
protected:
virtual bool lessThan(const ScoreDocPtr& first, const ScoreDocPtr& second) = 0;
virtual ScoreDocPtr getSentinelObject();
friend class PriorityQueueScoreDocs;
};
class LPPAPI PriorityQueueScoreDocs : public PriorityQueue<ScoreDocPtr> {
public:
PriorityQueueScoreDocs(const HitQueueBasePtr& hitQueue, int32_t size);
virtual ~PriorityQueueScoreDocs();
LUCENE_CLASS(PriorityQueueScoreDocs);
protected:
HitQueueBaseWeakPtr _hitQueue;
protected:
virtual bool lessThan(const ScoreDocPtr& first, const ScoreDocPtr& second);
virtual ScoreDocPtr getSentinelObject();
};
}
#endif
| 0 | 0.965418 | 1 | 0.965418 | game-dev | MEDIA | 0.254112 | game-dev | 0.682795 | 1 | 0.682795 |
SoftbearStudios/kiomet | 2,148 | client/src/animation.rs | // SPDX-FileCopyrightText: 2024 Softbear, Inc.
// SPDX-License-Identifier: AGPL-3.0-or-later
use crate::color::Color;
use kodiak_client::glam::{Vec2, Vec3, Vec4};
pub struct Animation {
position: Vec2,
animation_type: AnimationType,
start_seconds: f32,
}
pub enum AnimationType {
Emp(Color),
NuclearExplosion,
ShellExplosion,
}
impl Animation {
pub fn new(position: Vec2, animation_type: AnimationType, time_seconds: f32) -> Self {
Self {
position,
animation_type,
start_seconds: time_seconds,
}
}
/// Returns a boolean of whether animation is *not* done.
pub fn render<F: FnMut(Vec2, f32, Vec4)>(
&self,
mut draw_filled_circle: F,
time_seconds: f32,
) -> bool {
let mut draw =
|time_delay: f32, time_scale: f32, max_radius: f32, max_alpha: f32, color: Vec3| {
let t = time_seconds - self.start_seconds;
let elapsed = if time_scale < 0.0 {
time_delay - t
} else {
t - time_delay
}
.max(0.0);
let s = time_scale.abs();
let radius = (elapsed * s * 4.0).min(max_radius);
let alpha = (1.0 - elapsed * s * 0.3).clamp(0.0, max_alpha);
if alpha > 0.0 {
draw_filled_circle(self.position, radius, color.extend(alpha));
true
} else {
false
}
};
let white = Vec3::ONE;
match self.animation_type {
AnimationType::Emp(color) => {
let (stroke, _) = color.colors(true, true, false);
let color = stroke.unwrap(); // TODO don't return option that's always Some.
draw(1.2, -0.5, 1.0, 0.3, color)
}
AnimationType::NuclearExplosion => {
draw(0.0, 0.33, 1.5, 0.6, white) | draw(0.0, 1.0, 1.0, 1.0, white)
}
AnimationType::ShellExplosion => draw(-0.25, 2.0, 0.3, 0.7, white),
}
}
}
| 0 | 0.954069 | 1 | 0.954069 | game-dev | MEDIA | 0.71304 | game-dev,graphics-rendering | 0.942379 | 1 | 0.942379 |
lua9520/source-engine-2018-hl2_src | 5,500 | game/server/portal/portal_mp_client.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
/*
===== portal_client.cpp ========================================================
Portal client/server game specific stuff
*/
#include "cbase.h"
#include "portal_player.h"
#include "portal_gamerules.h"
#include "gamerules.h"
#include "teamplay_gamerules.h"
#include "EntityList.h"
#include "physics.h"
#include "game.h"
#include "player_resource.h"
#include "engine/IEngineSound.h"
#include "team.h"
#include "tier0/vprof.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
void Host_Say( edict_t *pEdict, bool teamonly );
extern CBaseEntity* FindPickerEntityClass( CBasePlayer *pPlayer, char *classname );
extern bool g_fGameOver;
void FinishClientPutInServer( CPortal_Player *pPlayer )
{
pPlayer->InitialSpawn();
pPlayer->Spawn();
char sName[128];
Q_strncpy( sName, pPlayer->GetPlayerName(), sizeof( sName ) );
// First parse the name and remove any %'s
for ( char *pApersand = sName; pApersand != NULL && *pApersand != 0; pApersand++ )
{
// Replace it with a space
if ( *pApersand == '%' )
*pApersand = ' ';
}
// notify other clients of player joining the game
UTIL_ClientPrintAll( HUD_PRINTNOTIFY, "#Game_connected", sName[0] != 0 ? sName : "<unconnected>" );
if ( PortalMPGameRules()->IsTeamplay() == true )
{
ClientPrint( pPlayer, HUD_PRINTTALK, "You are on team %s1\n", pPlayer->GetTeam()->GetName() );
}
const ConVar *hostname = cvar->FindVar( "hostname" );
const char *title = (hostname) ? hostname->GetString() : "MESSAGE OF THE DAY";
KeyValues *data = new KeyValues("data");
data->SetString( "title", title ); // info panel title
data->SetString( "type", "1" ); // show userdata from stringtable entry
data->SetString( "msg", "motd" ); // use this stringtable entry
//pPlayer->ShowViewPortPanel( PANEL_INFO, true, data );
data->deleteThis();
}
/*
===========
ClientPutInServer
called each time a player is spawned into the game
============
*/
void ClientPutInServer( edict_t *pEdict, const char *playername )
{
// Allocate a CBasePlayer for pev, and call spawn
CPortal_Player *pPlayer = CPortal_Player::CreatePlayer( "player", pEdict );
pPlayer->PlayerData()->netname = AllocPooledString( playername );
}
void ClientActive( edict_t *pEdict, bool bLoadGame )
{
Assert( !bLoadGame );
CPortal_Player *pPlayer = dynamic_cast< CPortal_Player* >( CBaseEntity::Instance( pEdict ) );
Assert( pPlayer );
FinishClientPutInServer( pPlayer );
}
/*
===============
const char *GetGameDescription()
Returns the descriptive name of this .dll. E.g., Half-Life, or Team Fortress 2
===============
*/
const char *GetGameDescription()
{
if ( g_pGameRules ) // this function may be called before the world has spawned, and the game rules initialized
return g_pGameRules->GetGameDescription();
else
return "Half-Life 2";
}
//-----------------------------------------------------------------------------
// Purpose: Given a player and optional name returns the entity of that
// classname that the player is nearest facing
//
// Input :
// Output :
//-----------------------------------------------------------------------------
CBaseEntity* FindEntity( edict_t *pEdict, char *classname)
{
// If no name was given set bits based on the picked
if (FStrEq(classname,""))
{
return (FindPickerEntityClass( static_cast<CBasePlayer*>(GetContainingEntity(pEdict)), classname ));
}
return NULL;
}
//-----------------------------------------------------------------------------
// Purpose: Precache game-specific models & sounds
//-----------------------------------------------------------------------------
void ClientGamePrecache( void )
{
CBaseEntity::PrecacheModel("models/player.mdl");
CBaseEntity::PrecacheModel( "models/gibs/agibs.mdl" );
CBaseEntity::PrecacheModel("models/weapons/v_hands.mdl");
CBaseEntity::PrecacheScriptSound( "HUDQuickInfo.LowAmmo" );
CBaseEntity::PrecacheScriptSound( "HUDQuickInfo.LowHealth" );
CBaseEntity::PrecacheScriptSound( "FX_AntlionImpact.ShellImpact" );
CBaseEntity::PrecacheScriptSound( "Missile.ShotDown" );
CBaseEntity::PrecacheScriptSound( "Bullets.DefaultNearmiss" );
CBaseEntity::PrecacheScriptSound( "Bullets.GunshipNearmiss" );
CBaseEntity::PrecacheScriptSound( "Bullets.StriderNearmiss" );
CBaseEntity::PrecacheScriptSound( "Geiger.BeepHigh" );
CBaseEntity::PrecacheScriptSound( "Geiger.BeepLow" );
CBaseEntity::PrecacheModel( "models/portals/portal1.mdl" );
CBaseEntity::PrecacheModel( "models/portals/portal2.mdl" );
}
// called by ClientKill and DeadThink
void respawn( CBaseEntity *pEdict, bool fCopyCorpse )
{
if (gpGlobals->coop || gpGlobals->deathmatch)
{
if ( fCopyCorpse )
{
// make a copy of the dead body for appearances sake
((CPortal_Player *)pEdict)->CreateCorpse();
}
// respawn player
pEdict->Spawn();
}
else
{ // restart the entire server
engine->ServerCommand("reload\n");
}
}
void GameStartFrame( void )
{
VPROF("GameStartFrame()");
if ( g_fGameOver )
return;
gpGlobals->teamplay = (teamplay.GetInt() != 0);
}
//=========================================================
// instantiate the proper game rules object
//=========================================================
void InstallGameRules()
{
CreateGameRulesObject( "CPortalMPGameRules" );
}
| 0 | 0.916257 | 1 | 0.916257 | game-dev | MEDIA | 0.861574 | game-dev | 0.836409 | 1 | 0.836409 |
esmf-org/esmf | 7,433 | src/Infrastructure/Mesh/src/Legacy/ESMCI_MeshObjPack.C | // $Id$
//
// Earth System Modeling Framework
// Copyright (c) 2002-2025, University Corporation for Atmospheric Research,
// Massachusetts Institute of Technology, Geophysical Fluid Dynamics
// Laboratory, University of Michigan, National Centers for Environmental
// Prediction, Los Alamos National Laboratory, Argonne National Laboratory,
// NASA Goddard Space Flight Center.
// Licensed under the University of Illinois-NCSA License.
//
//==============================================================================
#include <Mesh/include/Legacy/ESMCI_MeshObjPack.h>
#include <Mesh/include/Legacy/ESMCI_ParEnv.h>
#include <Mesh/include/Legacy/ESMCI_MeshObjConn.h>
//-----------------------------------------------------------------------------
// leave the following line as-is; it will insert the cvs ident string
// into the object file for tracking purposes.
static const char *const version = "$Id$";
//-----------------------------------------------------------------------------
namespace ESMCI {
UInt MeshObjPackSize(MeshObj &obj) {
UInt sz = 0;
// Obj id;
sz += SparsePack<MeshObj::id_type>::size();
// Obj topo
sz += SparsePack<UInt>::size();
// Obj owner
sz += SparsePack<UInt>::size();
// Obj Attr
sz += SparsePack<Attr>::size();
// Size of relations
sz += SparsePack<UInt>::size();
// Relations
MeshObjRelationList::iterator ri = obj.Relations.begin(), re = obj.Relations.end();
for (; ri != re; ++ri) {
sz += SparsePack<MeshObj::Relation>::size();
}
return sz;
}
void MeshObjPack(SparseMsg::buffer &b, MeshObj &obj, bool ghosting) {
// Obj id;
SparsePack<MeshObj::id_type>(b, obj.get_id());
//Par::Out() << "Packingn id=" << obj.get_id() << std::endl;
// Obj topo
const MeshObjTopo *topo = GetMeshObjTopo(obj);
UInt tnum = topo ? topo->number : 0;
SparsePack<UInt>(b, tnum);
//Par::Out() << "Packingn tnum=" << tnum << std::endl;
// Pack owner
UInt owner = obj.get_owner();
SparsePack<UInt>(b, owner);
// Obj Attr
if (!ghosting)
SparsePack<Attr>(b, GetAttr(obj));
else {
// Set inactive bit for ghosted object; (found only through relations)
Attr a(GetAttr(obj));
Context &ctxt = a.GetContext();
ctxt.clear(Attr::ACTIVE_ID);
ctxt.set(Attr::SHARED_ID);
SparsePack<Attr>(b, a);
}
// Pack Relations size
MeshObjRelationList::iterator ri = obj.Relations.begin(), re = obj.Relations.end();
UInt nrel = obj.Relations.size();
SparsePack<UInt>(b, nrel);
// Pack Relations size
ri = obj.Relations.begin();
for (; ri != re; ++ri) {
SparsePack<MeshObj::Relation>(b, *ri);
}
}
void MeshObjUnpack(MeshDB &mesh, SparseMsg::buffer &b, MeshObj *&obj) {
Trace __trace("MeshObjUnpack(MeshDB &mesh, SparseMsg::buffer &b, MeshObj *&obj)");
// Obj id;
MeshObj::id_type id;
SparseUnpack<MeshObj::id_type>(b, id);
//Par::Out() << "Unpack id=" << id << std::endl;
// Obj topo
UInt tnum;
SparseUnpack<UInt>(b, tnum);
//Par::Out() << "Unpack tnum=" << tnum << std::endl;
const MeshObjTopo *topo = GetTopo(tnum);
// Obj owner
UInt owner;
SparseUnpack<UInt>(b, owner);
Attr attr;
// Obj Attr
SparseUnpack<Attr>(b, attr);
// First, See if the object is already there:
bool obj_exists = false;
MeshDB::MeshObjIDMap::iterator mi =
mesh.map_find(attr.GetType(), id);
if (mi != mesh.map_end(attr.GetType())) {
obj_exists = true;
// TODO: check that everything is the same
}
// We now have enough info to create the meshobj
if (!obj_exists) {
obj = new MeshObj(attr.GetType(), id, 0);
obj->set_owner(owner);
} else obj = &*mi;
// Relations
// unpack all relations
UInt nrel;
SparseUnpack<UInt>(b, nrel);
// If the object exists, just unpack the buffer; add any (potentially)
// new relations.
if (obj_exists) {
// May need to update owner. Any diagnostic check???
/*
Par::Out() << "obj " << MeshObjTypeString(obj->get_type()) << " " << obj->get_id() << " old owner:"
<< obj->get_owner() << " -> " << owner << std::endl;
*/
obj->set_owner(owner);
// If the object sent is active, make the local obj active. This is used (for instance)
// when sending objects to rendezvous and a ghosted object gets there first;
{
const Context &ctxt = GetMeshObjContext(*obj);
if (!ctxt.is_set(Attr::ACTIVE_ID) && attr.GetContext().is_set(Attr::ACTIVE_ID)) {
const Attr &oattr = GetAttr(*obj);
Context newctxt(ctxt);
newctxt.set(Attr::ACTIVE_ID);
Attr attr(oattr, newctxt);
mesh.update_obj(obj, attr);
}
}
for (UInt n = 0; n < nrel; n++) {
MeshObj::Relation r;
MeshObj::id_type obj_id;
UInt obj_type;
SparseUnpack<MeshObj::Relation>(b, r, obj_id, obj_type);
MeshObjRelationList::iterator ri =
MeshObjConn::find_relation(*obj, obj_type, r.ordinal, r.type);
// Might be a similar relation with to different obj (think USED_BY, ord 1)
if (ri != obj->Relations.end() && ri->obj->get_id() == obj_id) {
} else {
// Relation doesn't exist, so try to add it.
MeshDB::MeshObjIDMap::iterator mi =
mesh.map_find(obj_type, obj_id);
if (mi != mesh.map_end(obj_type)) {
// Got the object!
MeshObj &robj = *mi;
r.obj = &robj;
AddMeshObjRelation(*obj, r);
// Add the converse relation to other object
if ((r.type = MeshObjRelationConverse(r.type)) != 0) {
r.obj = obj;
AddMeshObjRelation(robj, r);
}
} // else obj not there, so leave well enough as well is.
}
}
} else {
obj->Relations.reserve(nrel);
for (UInt n = 0; n < nrel; n++) {
obj->Relations.push_back(MeshObj::Relation());
MeshObj::Relation &r = obj->Relations.back();
MeshObj::id_type obj_id;
UInt obj_type;
SparseUnpack<MeshObj::Relation>(b, r, obj_id, obj_type);
// Now go to mesh and recruit the obj_id fail if not found.
MeshDB::MeshObjIDMap::iterator mi =
mesh.map_find(obj_type, obj_id);
if (mi == mesh.map_end(obj_type)) {
obj->Relations.pop_back();
#ifdef NOT
// TODO: figure out a strategy of when to/not to forgive this
//if (obj_type != (UInt) mesh.side_type())
if (1)
Throw() << "P:" << Par::Rank() << " mesh =" << mesh.filename() << " unpack MeshObj:id=" << id << ",attr=" << attr << ", could not find object (type,id)="
<< MeshObjTypeString(obj_type) << ", " << obj_id << ", ordinal:" << r.ordinal
<< ", Meshside type=" << MeshObjTypeString(mesh.side_type())
<< std::endl;
#endif
}
// Else drop the object into the relation
r.obj = &*mi;
}
// Now add object to Mesh
//Par::Out() << "Unpacked object:" << MeshObjTypeString(obj->get_type()) << ", id=" << obj->get_id() << std::endl;
mesh.add_object(obj, attr, topo);
} // if !exists
// Make the locally owned consistent.
{
const Attr &oattr = GetAttr(*obj);
const Context &ctxt = GetMeshObjContext(*obj);
Context newctxt(ctxt);
if (obj->get_owner() == Par::Rank())
newctxt.set(Attr::OWNED_ID);
else
newctxt.clear(Attr::OWNED_ID);
if (newctxt != ctxt) {
Attr attr(oattr, newctxt);
mesh.update_obj(obj, attr);
}
}
}
} // namespace ESMCI
| 0 | 0.945762 | 1 | 0.945762 | game-dev | MEDIA | 0.242987 | game-dev | 0.936535 | 1 | 0.936535 |
SkyblockAPI/SkyblockAPI | 2,592 | src/common/main/kotlin/tech/thatgravyboat/skyblockapi/api/data/stored/ProfileStorage.kt | package tech.thatgravyboat.skyblockapi.api.data.stored
import tech.thatgravyboat.skyblockapi.api.data.SkyBlockRarity
import tech.thatgravyboat.skyblockapi.api.data.StoredPlayerData
import tech.thatgravyboat.skyblockapi.api.location.SkyBlockIsland
import tech.thatgravyboat.skyblockapi.api.profile.profile.ProfileAPI
import tech.thatgravyboat.skyblockapi.api.profile.profile.ProfileData
import tech.thatgravyboat.skyblockapi.api.profile.profile.ProfileType
internal object ProfileStorage {
// Todo: use StoredProfileData instead, basically the same just better here
private val PROFILE = StoredPlayerData(
{ ProfileData(bingoRank = null) },
ProfileData.CODEC,
"profiles.json",
)
private inline val data get(): ProfileData = PROFILE.get()
fun getProfileType(): ProfileType = data.profileType[ProfileAPI.profileName] ?: ProfileType.UNKNOWN
fun setProfileType(profileType: ProfileType) {
if (SkyBlockIsland.inAnyIsland(SkyBlockIsland.THE_CATACOMBS, SkyBlockIsland.KUUDRA)) {
// Don't allow changing profile type in dungeons or kuudra
// The Tablist is different and doesn't contain the profile type
// (At least Catacombs, I assume kuudra does the same)
return
}
if (profileType == getProfileType()) return
val profileName = ProfileAPI.profileName ?: return
data.profileType[profileName] = profileType
PROFILE.save()
}
fun getSkyBlockLevel(): Int = data.sbLevel[ProfileAPI.profileName] ?: 0
fun setSkyBlockLevel(level: Int) {
if (level == getSkyBlockLevel()) return
val profileName = ProfileAPI.profileName ?: return
data.sbLevel[profileName] = level
PROFILE.save()
}
fun getSkyBlockLevelProgress(): Int = data.sbLevelProgress[ProfileAPI.profileName] ?: 0
fun setSkyBlockLevelProgress(level: Int) {
if (level == getSkyBlockLevelProgress()) return
val profileName = ProfileAPI.profileName ?: return
data.sbLevelProgress[profileName] = level
PROFILE.save()
}
fun isCoop(): Boolean = data.coop[ProfileAPI.profileName] == true
fun setCoop(coop: Boolean) {
if (coop == isCoop()) return
val profileName = ProfileAPI.profileName ?: return
data.coop[profileName] = coop
PROFILE.save()
}
fun getBingoRank(): SkyBlockRarity? = data.bingoRank
fun setBingoRank(bingoRank: SkyBlockRarity?) {
if (bingoRank == getBingoRank()) return
data.bingoRank = bingoRank
PROFILE.save()
}
}
| 0 | 0.773237 | 1 | 0.773237 | game-dev | MEDIA | 0.655991 | game-dev | 0.672906 | 1 | 0.672906 |
antrad/Abuse_1996 | 5,691 | data/lisp/doors.lsp | ;; Copyright 1995 Crack dot Com, All Rights reserved
;; See licensing information for more details on usage rights
(defun general_door_ai (push?)
(select (aistate)
(0 (if (> (total_objects) 0) ; are we linked to a key?
(progn
(set_state blocking) ; don't let play pass
(if push?
(push_char (+ (picture_width) 8) (picture_height)))
)
(if (touching_bg) ; found key, wait till touching to open
(progn (set_state running) ; start opening animation
(play_sound SWISH 70 (x) (y))
(go_state 1))
nil)))
(1 (if (not (next_picture)) ; wait till open animation finishes
(progn
(set_state stopped) ; set opened animation
(go_state 2))))
(2 (if (> (total_objects) 0) ; wait till level editor links us to a key
(progn
(set_state blocking)
(go_state 0))
(next_picture))))
T)
(defun sdoor_ai ()
(general_sdoor_ai T))
(defun general_sdoor_ai (push?)
(select (aistate)
(0 ; closed, wait for signal
(if (> (total_objects) 0)
(if (not (eq (with_object (get_object 0) (aistate)) 0))
(progn (set_state running)
(play_sound SWISH 70 (x) (y))
(go_state 1))
(progn
(set_state stopped)
(if push?
(push_char (+ (picture_width) 8) (picture_height)))))))
(1 ; opening
(if (next_picture) nil
(progn
(set_state blocking)
(set_aistate 2))))
(2 (if (> (total_objects) 0)
(if (eq (with_object (get_object 0) (aistate)) 0)
(progn (set_state walking)
(play_sound SWISH 70 (x) (y))
(go_state 3)))))
(3 ; closing
(if (next_picture) nil
(progn
(set_state stopped)
(set_aistate 0))))
)
T)
(def_char SWITCH_DOOR
(funs (ai_fun sdoor_ai)
(reload_fun lower_reload))
(flags (can_block T))
(range 250 60)
(draw_range 30 50)
(abilities (push_xrange 1))
(states "art/chars/door.spe"
(stopped "door0006.pcx")
(running (seq "door" 6 1))
(walking (seq "door" 1 6))
(blocking "door0001.pcx")))
(defun ff_push (who xamount)
(if who
(progn
(let ((bgx (with_object who (x)) (x))
(bgy (with_object who (y)) (y)))
(if (and (>= bgy (y)) (<= bgy (+ end_y 20))
(< (abs (- bgx (x))) xamount))
(let ((amount (if (> bgx (x))
(- xamount (- bgx (x)))
(- (- (x) bgx) xamount))))
(with_object who (try_move amount 0)))))
(ff_push (next_focus who) xamount))))
(defun ff_ai ()
(shift_rand_table (random 80))
(if (activated)
(let ((nowx (x))
(nowy (y)))
(if (eq (mod (game_tick) 4) 0)
(play_sound FF_SND 127 (x) (y)))
(try_move 0 (+ (y) 200)) ;; find the floor
(setq end_y (y)) ;; save the position
(set_x nowx)
(set_y nowy)
(ff_push (first_focus) 35)))
T)
(defun ff_draw ()
(if (edit_mode) (draw))
(if (activated)
(progn
(ascatter_line (x) (y) (x) end_y (find_rgb 151 139 151) (find_rgb 75 69 75) 3)
(ascatter_line (x) (y) (x) end_y (find_rgb 139 147 191) (find_rgb 69 73 95) 2)
(ascatter_line (x) (y) (x) end_y (find_rgb 39 55 71) (find_rgb 19 27 35) 2)
(ascatter_line (x) (y) (x) end_y (find_rgb 39 55 71) (find_rgb 20 26 35) 2))))
(def_char FORCE_FIELD
(funs (ai_fun ff_ai)
(draw_fun ff_draw))
(range 10 500)
(vars end_y)
(states "art/misc.spe"
(stopped "force_field")))
(defun hwall_ai ()
(if (or (eq (hp) 0)
(and (eq (total_objects) 1)
(with_object (get_object 0) (not (eq (aistate) 0)))))
(progn
(add_object EXPLODE1 (+ (x) 15) (- (y) 7) 0)
(play_sound HWALL_SND 127 (x) (y))
(hurt_radius (+ (x) (* 15 (direction))) (- (y) 7) 50 60 (bg) 20)
nil)
T))
(defun big_wall_ai ()
(if (or (eq (hp) 0)
(and (eq (total_objects) 1)
(with_object (get_object 0) (not (eq (aistate) 0)))))
(progn
(add_object EXPLODE1 (- (x) 15) (- (y) 7) 0)
(add_object EXPLODE1 (+ (x) 15) (- (y) 22) 0)
(add_object EXPLODE1 (+ (x) (random 5)) (+ (+ (random 5) (y)) -20) 0)
(play_sound HWALL_SND 127 (x) (y))
(hurt_radius (x) (- (y) 15) 110 120 (bg) 20)
nil)
T))
(defun hwall_damage (amount from hitx hity push_xvel push_yvel)
(if (activated)
(progn
(damage_fun amount from hitx hity push_xvel push_yvel)
(let ((max_hp (get_ability start_hp)))
(if (and (not (eq (hp) 0)) (not (> (hp) max_hp)))
(set_current_frame (/ (* (total_frames) (- max_hp (hp))) max_hp)))))))
(defun hwall_reload () ;; we changed this , make sure this is reflected in all of the levels
(if (eq (hp) 60)
(set_hp 25)))
(defun make_hidden_wall_char (name start end ai)
(eval `(def_char ,name
(funs (ai_fun ,ai)
(reload_fun hwall_reload)
(damage_fun hwall_damage))
(abilities (start_hp 25))
(draw_range 80 80)
(flags (can_block T)
(unactive_shield T)
(hurtable T))
(states "art/chars/sect.spe"
(stopped (seq "sect" ,start ,end)))))) ; damn lisp is cool
(make_hidden_wall_char 'HIDDEN_WALL1 1 3 'hwall_ai)
(make_hidden_wall_char 'HIDDEN_WALL2 4 6 'hwall_ai)
(make_hidden_wall_char 'HIDDEN_WALL3 7 9 'hwall_ai)
(make_hidden_wall_char 'HIDDEN_WALL4 10 12 'hwall_ai)
(make_hidden_wall_char 'HIDDEN_WALL5 13 15 'hwall_ai)
(make_hidden_wall_char 'HIDDEN_WALL_2x2 16 18 'big_wall_ai)
(make_hidden_wall_char 'HIDDEN_WALL_3WAL 19 21 'big_wall_ai)
(make_hidden_wall_char 'HIDDEN_WALL_3FLR 22 24 'big_wall_ai)
(make_hidden_wall_char 'HIDDEN_WALL_3TOP 25 27 'big_wall_ai)
(make_hidden_wall_char 'HIDDEN_WALL_AFLR 28 30 'big_wall_ai)
(make_hidden_wall_char 'HIDDEN_RAMP1 31 33 'hwall_ai)
(make_hidden_wall_char 'HIDDEN_RAMP2 34 36 'hwall_ai)
| 0 | 0.947867 | 1 | 0.947867 | game-dev | MEDIA | 0.925105 | game-dev | 0.874705 | 1 | 0.874705 |
glKarin/com.n0n3m4.diii4a | 3,752 | Q3E/src/main/jni/source/game/server/NextBot/NextBot.h | // NextBotCombatCharacter.h
// Next generation bot system
// Author: Michael Booth, April 2005
//========= Copyright Valve Corporation, All rights reserved. ============//
#ifndef _NEXT_BOT_H_
#define _NEXT_BOT_H_
#include "NextBotInterface.h"
#include "NextBotManager.h"
#ifdef TERROR
#include "player_lagcompensation.h"
#endif
class NextBotCombatCharacter;
struct animevent_t;
extern ConVar NextBotStop;
//----------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------
/**
* A Next Bot derived from CBaseCombatCharacter
*/
class NextBotCombatCharacter : public CBaseCombatCharacter, public INextBot
{
public:
DECLARE_CLASS( NextBotCombatCharacter, CBaseCombatCharacter );
DECLARE_SERVERCLASS();
DECLARE_DATADESC();
NextBotCombatCharacter( void );
virtual ~NextBotCombatCharacter() { }
virtual void Spawn( void );
virtual Vector EyePosition( void );
virtual INextBot *MyNextBotPointer( void ) { return this; }
// Event hooks into NextBot system ---------------------------------------
virtual int OnTakeDamage_Alive( const CTakeDamageInfo &info );
virtual int OnTakeDamage_Dying( const CTakeDamageInfo &info );
virtual void Event_Killed( const CTakeDamageInfo &info );
virtual void HandleAnimEvent( animevent_t *event );
virtual void OnNavAreaChanged( CNavArea *enteredArea, CNavArea *leftArea ); // invoked (by UpdateLastKnownArea) when we enter a new nav area (or it is reset to NULL)
virtual void Touch( CBaseEntity *other );
virtual void SetModel( const char *szModelName );
virtual void Ignite( float flFlameLifetime, bool bNPCOnly = true, float flSize = 0.0f, bool bCalledByLevelDesigner = false );
virtual void Ignite( float flFlameLifetime, CBaseEntity *pAttacker );
//------------------------------------------------------------------------
virtual bool IsUseableEntity( CBaseEntity *entity, unsigned int requiredCaps = 0 );
void UseEntity( CBaseEntity *entity, USE_TYPE useType = USE_TOGGLE );
// Implement this if you use MOVETYPE_CUSTOM
virtual void PerformCustomPhysics( Vector *pNewPosition, Vector *pNewVelocity, QAngle *pNewAngles, QAngle *pNewAngVelocity );
virtual bool BecomeRagdoll( const CTakeDamageInfo &info, const Vector &forceVector );
// hook to INextBot update
void DoThink( void );
// expose to public
int GetLastHitGroup( void ) const; // where on our body were we injured last
virtual bool IsAreaTraversable( const CNavArea *area ) const; // return true if we can use the given area
virtual CBaseCombatCharacter *GetLastAttacker( void ) const; // return the character who last attacked me
// begin INextBot public interface ----------------------------------------------------------------
virtual NextBotCombatCharacter *GetEntity( void ) const { return const_cast< NextBotCombatCharacter * >( this ); }
virtual NextBotCombatCharacter *GetNextBotCombatCharacter( void ) const { return const_cast< NextBotCombatCharacter * >( this ); }
private:
EHANDLE m_lastAttacker;
bool m_didModelChange;
};
inline CBaseCombatCharacter *NextBotCombatCharacter::GetLastAttacker( void ) const
{
return ( m_lastAttacker.Get() == NULL ) ? NULL : m_lastAttacker->MyCombatCharacterPointer();
}
inline int NextBotCombatCharacter::GetLastHitGroup( void ) const
{
return LastHitGroup();
}
//-----------------------------------------------------------------------------------------------------
class NextBotDestroyer
{
public:
NextBotDestroyer( int team );
bool operator() ( INextBot *bot );
int m_team; // the team to delete bots from, or TEAM_ANY for any team
};
#endif // _NEXT_BOT_H_
| 0 | 0.967863 | 1 | 0.967863 | game-dev | MEDIA | 0.957249 | game-dev | 0.615014 | 1 | 0.615014 |
microsoft/MRDL_Unity_PeriodicTable | 30,468 | Assets/MRTK/Services/SceneSystem/MixedRealitySceneSystemEditorOperations.cs | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections.Generic;
using Microsoft.MixedReality.Toolkit.Utilities;
using System;
using System.Linq;
using System.Threading.Tasks;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.SceneManagement;
#endif
namespace Microsoft.MixedReality.Toolkit.SceneSystem
{
/// <summary>
/// The default implementation of the <see cref="Microsoft.MixedReality.Toolkit.SceneSystem.IMixedRealitySceneSystem"/>
/// This file handles the editor-oriented parts of the service.
/// </summary>
public partial class MixedRealitySceneSystem : BaseCoreSystem, IMixedRealitySceneSystem, IMixedRealitySceneSystemEditor
{
#if UNITY_EDITOR
/// <summary>
/// Detects asset modifications.
/// Used to detect when lighting cache may be out of date.
/// </summary>
internal sealed class FileModificationWarning : UnityEditor.AssetModificationProcessor
{
public static HashSet<string> ModifiedAssetPaths = new HashSet<string>();
public static string[] OnWillSaveAssets(string[] paths)
{
foreach (string path in paths) { ModifiedAssetPaths.Add(path); }
return paths;
}
}
/// <summary>
/// Returns the manager scene found in profile.
/// </summary>
public SceneInfo ManagerScene => Profile.ManagerScene;
/// <summary>
/// Returns all lighting scenes found in profile.
/// </summary>
public SceneInfo[] LightingScenes => contentTracker.SortedLightingScenes;
/// <summary>
/// Returns all content scenes found in profile.
/// </summary>
public SceneInfo[] ContentScenes => contentTracker.SortedContentScenes;
/// <summary>
/// Returns all content tags found in profile scenes.
/// </summary>
public IEnumerable<string> ContentTags => Profile.ContentTags;
// Cache these so we're not looking them up constantly
private EditorBuildSettingsScene[] cachedBuildScenes = Array.Empty<EditorBuildSettingsScene>();
// These get set to dirty based on what events have been received from the editor
private bool activeSceneDirty = false;
private bool buildSettingsDirty = false;
private bool heirarchyDirty = false;
// These get set based on what our update methods are doing in response to events
private bool updatingSettingsOnEditorChanged = false;
private bool updatingCachedLightingSettings = false;
// Checking for the manager scene via root game objects is very expensive
// So only do it once in a while
private const float lightingUpdateInterval = 5f;
private const float managerSceneInstanceCheckInterval = 2f;
private const int editorApplicationUpdateTickInterval = 10;
private float managerSceneInstanceCheckTime;
private int editorApplicationUpdateTicks;
// Used to track which instance of the service we're using (for debugging purposes)
private static int instanceIDCount;
private int instanceID = -1;
#region public editor methods
/// <summary>
/// Singly loads next content scene (if available) and unloads all other content scenes.
/// Useful for inspectors.
/// </summary>
public void EditorLoadNextContent(bool wrap = false)
{
string contentSceneName;
if (contentTracker.GetNextContent(wrap, out contentSceneName))
{
foreach (SceneInfo contentScene in ContentScenes)
{
if (contentScene.Name == contentSceneName)
{
EditorSceneUtils.LoadScene(contentScene, false, out Scene scene);
}
else
{
EditorSceneUtils.UnloadScene(contentScene, false);
}
}
}
contentTracker.RefreshLoadedContent();
}
/// <summary>
/// Singly loads previous content scene (if available) and unloads all other content scenes.
/// Useful for inspectors.
/// </summary>
public void EditorLoadPrevContent(bool wrap = false)
{
string contentSceneName;
if (contentTracker.GetPrevContent(wrap, out contentSceneName))
{
foreach (SceneInfo contentScene in ContentScenes)
{
if (contentScene.Name == contentSceneName)
{
EditorSceneUtils.LoadScene(contentScene, false, out Scene scene);
}
else
{
EditorSceneUtils.UnloadScene(contentScene, false);
}
}
}
contentTracker.RefreshLoadedContent();
}
#endregion
#region Initialization / Teardown
private void EditorOnInitialize()
{
instanceID = instanceIDCount++;
EditorSubscribeToEvents();
cachedBuildScenes = EditorBuildSettings.scenes;
activeSceneDirty = true;
buildSettingsDirty = true;
heirarchyDirty = true;
EditorCheckForChanges();
}
private void EditorOnEnable()
{
EditorSubscribeToEvents();
cachedBuildScenes = EditorBuildSettings.scenes;
activeSceneDirty = true;
buildSettingsDirty = true;
heirarchyDirty = true;
EditorCheckForChanges();
}
private void EditorOnDisable()
{
EditorUnsubscribeFromEvents();
}
private void EditorOnDestroy()
{
EditorUnsubscribeFromEvents();
}
private void EditorSubscribeToEvents()
{
EditorApplication.projectChanged += EditorApplicationProjectChanged;
EditorApplication.hierarchyChanged += EditorApplicationHeirarcyChanged;
EditorApplication.update += EditorApplicationUpdate;
EditorSceneManager.newSceneCreated += EditorSceneManagerNewSceneCreated;
EditorSceneManager.sceneOpened += EditorSceneManagerSceneOpened;
EditorSceneManager.sceneClosed += EditorSceneManagerSceneClosed;
EditorBuildSettings.sceneListChanged += EditorSceneListChanged;
}
private void EditorUnsubscribeFromEvents()
{
EditorApplication.projectChanged -= EditorApplicationProjectChanged;
EditorApplication.hierarchyChanged -= EditorApplicationHeirarcyChanged;
EditorApplication.update -= EditorApplicationUpdate;
EditorSceneManager.newSceneCreated += EditorSceneManagerNewSceneCreated;
EditorSceneManager.sceneOpened -= EditorSceneManagerSceneOpened;
EditorSceneManager.sceneClosed -= EditorSceneManagerSceneClosed;
EditorBuildSettings.sceneListChanged -= EditorSceneListChanged;
}
#endregion
#region update triggers from editor events
private void EditorApplicationUpdate()
{
editorApplicationUpdateTicks++;
if (editorApplicationUpdateTicks > editorApplicationUpdateTickInterval)
{
activeSceneDirty = true;
heirarchyDirty = true;
editorApplicationUpdateTicks = 0;
EditorCheckForChanges();
}
}
private void EditorApplicationHeirarcyChanged()
{
activeSceneDirty = true;
heirarchyDirty = true;
}
private void EditorApplicationProjectChanged()
{
buildSettingsDirty = true;
}
private void EditorSceneListChanged()
{
buildSettingsDirty = true;
EditorCheckForChanges();
}
private void EditorSceneManagerSceneClosed(Scene scene) { activeSceneDirty = true; }
private void EditorSceneManagerSceneOpened(Scene scene, OpenSceneMode mode) { activeSceneDirty = true; }
private void EditorSceneManagerNewSceneCreated(Scene scene, NewSceneSetup setup, NewSceneMode mode) { activeSceneDirty = true; }
#endregion
/// <summary>
/// Checks the state of service and profile based on changes made in editor and reacts accordingly.
/// </summary>
private async void EditorCheckForChanges()
{
if (!MixedRealityToolkit.IsInitialized || !MixedRealityToolkit.Instance.HasActiveProfile || !MixedRealityToolkit.Instance.ActiveProfile.IsSceneSystemEnabled)
{
return;
}
if (EditorSceneUtils.IsEditingPrefab())
{ // Never change scene settings while editing a prefab - it will boot you out of the prefab scene stage.
return;
}
if (updatingSettingsOnEditorChanged || EditorApplication.isPlayingOrWillChangePlaymode || EditorApplication.isCompiling)
{ // Make sure we don't double up on our updates via events we trigger during updates
return;
}
if (updatingCachedLightingSettings)
{ // This is a long operation, don't interrupt it
return;
}
// Update cached lighting settings, if the profile has requested it
if (Profile.EditorLightingCacheUpdateRequested)
{
updatingCachedLightingSettings = true;
updatingSettingsOnEditorChanged = true;
await EditorUpdateCachedLighting();
updatingSettingsOnEditorChanged = false;
updatingCachedLightingSettings = false;
// This is an async operation which may take a while to execute
// So exit when we're done - we'll pick up where we left off next time
heirarchyDirty = true;
return;
}
updatingSettingsOnEditorChanged = true;
// Update editor settings
if (FileModificationWarning.ModifiedAssetPaths.Count > 0)
{
EditorCheckIfCachedLightingOutOfDate();
FileModificationWarning.ModifiedAssetPaths.Clear();
}
if (buildSettingsDirty)
{
buildSettingsDirty = false;
EditorUpdateBuildSettings();
}
if (activeSceneDirty || heirarchyDirty)
{
heirarchyDirty = false;
activeSceneDirty = false;
EditorUpdateManagerScene();
EditorUpdateLightingScene(heirarchyDirty);
EditorUpdateContentScenes(activeSceneDirty);
contentTracker.RefreshLoadedContent();
}
EditorUtility.SetDirty(Profile);
updatingSettingsOnEditorChanged = false;
}
/// <summary>
/// Checks whether any of the save dates on our lighting scenes are later than the save date of our cached lighting data.
/// </summary>
private void EditorCheckIfCachedLightingOutOfDate()
{
DateTime cachedLightingTimestamp = Profile.GetEarliestLightingCacheTimestamp();
bool outOfDate = false;
foreach (SceneInfo lightingScene in Profile.LightingScenes)
{
if (FileModificationWarning.ModifiedAssetPaths.Contains(lightingScene.Path))
{
string lightingScenePath = System.IO.Path.Combine(Application.dataPath.Replace("/Assets", ""), lightingScene.Path);
DateTime lightingSceneTimestamp = System.IO.File.GetLastWriteTime(lightingScenePath);
if (lightingSceneTimestamp > cachedLightingTimestamp)
{
outOfDate = true;
break;
}
}
}
if (outOfDate)
{
Profile.SetLightingCacheDirty();
}
}
/// <summary>
/// Loads all lighting scenes, extracts their lighting data, then caches that data in the profile.
/// </summary>
private async Task EditorUpdateCachedLighting()
{
// Clear out our lighting cache
Profile.ClearLightingCache();
Profile.EditorLightingCacheUpdateRequested = false;
SceneInfo defaultLightingScene = Profile.DefaultLightingScene;
foreach (SceneInfo lightingScene in Profile.LightingScenes)
{
// Load all our lighting scenes
Scene scene;
EditorSceneUtils.LoadScene(lightingScene, false, out scene);
}
// Wait for a moment so all loaded scenes have time to get set up
await Task.Delay(100);
foreach (SceneInfo lightingScene in Profile.LightingScenes)
{
Scene scene;
EditorSceneUtils.GetSceneIfLoaded(lightingScene, out scene);
EditorSceneUtils.SetActiveScene(scene);
SerializedObject lightingSettingsObject;
SerializedObject renderSettingsObject;
EditorSceneUtils.GetLightingAndRenderSettings(out lightingSettingsObject, out renderSettingsObject);
// Copy the serialized objects into new structs
RuntimeLightingSettings lightingSettings = default(RuntimeLightingSettings);
RuntimeRenderSettings renderSettings = default(RuntimeRenderSettings);
RuntimeSunlightSettings sunlightSettings = default(RuntimeSunlightSettings);
lightingSettings = SerializedObjectUtils.CopySerializedObjectToStruct<RuntimeLightingSettings>(lightingSettingsObject, lightingSettings, "m_");
renderSettings = SerializedObjectUtils.CopySerializedObjectToStruct<RuntimeRenderSettings>(renderSettingsObject, renderSettings, "m_");
// Extract sunlight settings based on sunlight object
SerializedProperty sunProperty = renderSettingsObject.FindProperty("m_Sun");
if (sunProperty == null)
{
Debug.LogError("Sun settings may not be available in this version of Unity.");
}
else
{
Light sunLight = (Light)sunProperty.objectReferenceValue;
if (sunLight != null)
{
sunlightSettings.UseSunlight = true;
sunlightSettings.Color = sunLight.color;
sunlightSettings.Intensity = sunLight.intensity;
Vector3 eulerAngles = sunLight.transform.eulerAngles;
sunlightSettings.XRotation = eulerAngles.x;
sunlightSettings.YRotation = eulerAngles.y;
sunlightSettings.ZRotation = eulerAngles.z;
}
}
Profile.SetLightingCache(lightingScene, lightingSettings, renderSettings, sunlightSettings);
}
}
/// <summary>
/// Ensures that if a content scene is loaded, that scene is set active, rather than a lighting or manager scene.
/// </summary>
private void EditorUpdateContentScenes(bool activeSceneDirty)
{
if (!Profile.UseLightingScene || !Profile.EditorManageLoadedScenes)
{ // Nothing to do here
return;
}
if (!activeSceneDirty)
{ // Nothing to do here either
return;
}
bool contentSceneIsActive = false;
SceneInfo firstLoadedContentScene = SceneInfo.Empty;
foreach (SceneInfo contentScene in Profile.ContentScenes)
{
Scene scene;
if (EditorSceneUtils.GetSceneIfLoaded(contentScene, out scene))
{
if (firstLoadedContentScene.IsEmpty)
{ // If this is the first loaded content scene we've found, store it for later
firstLoadedContentScene = contentScene;
}
Scene activeScene = EditorSceneManager.GetActiveScene();
if (activeScene.name == contentScene.Name)
{
contentSceneIsActive = true;
}
}
}
if (!firstLoadedContentScene.IsEmpty)
{ // If at least one content scene is loaded
if (!contentSceneIsActive)
{ // And that content scene is NOT the active scene
// Set that content to be the active scene
Scene activeScene;
EditorSceneUtils.GetSceneIfLoaded(firstLoadedContentScene, out activeScene);
EditorSceneUtils.SetActiveScene(activeScene);
}
}
}
/// <summary>
/// If a manager scene is being used, this loads the scene in editor and ensures that an instance of the MRTK has been added to it.
/// </summary>
private void EditorUpdateManagerScene()
{
if (!Profile.UseManagerScene || !Profile.EditorManageLoadedScenes)
{ // Nothing to do here.
return;
}
if (EditorSceneUtils.LoadScene(Profile.ManagerScene, true, out Scene scene))
{
// If we're managing scene hierarchy, move this to the front
if (Profile.EditorEnforceSceneOrder)
{
Scene currentFirstScene = EditorSceneManager.GetSceneAt(0);
if (currentFirstScene.name != scene.name)
{
EditorSceneManager.MoveSceneBefore(scene, currentFirstScene);
}
}
if (Time.realtimeSinceStartup > managerSceneInstanceCheckTime)
{
managerSceneInstanceCheckTime = Time.realtimeSinceStartup + managerSceneInstanceCheckInterval;
// Check for an MRTK instance
bool foundToolkitInstance = false;
try
{
foreach (GameObject rootGameObject in scene.GetRootGameObjects())
{
MixedRealityToolkit instance = rootGameObject.GetComponent<MixedRealityToolkit>();
if (instance != null)
{
foundToolkitInstance = true;
// If we found an instance, and it's not the active instance, we probably want to activate it
if (instance != MixedRealityToolkit.Instance)
{ // The only exception would be if the new instance has a different profile than the current instance
// If that's the case, we could end up ping-ponging between two sets of manager scenes
if (!instance.HasActiveProfile)
{ // If it doesn't have a profile, set it to our current profile
instance.ActiveProfile = MixedRealityToolkit.Instance.ActiveProfile;
}
else if (instance.ActiveProfile != MixedRealityToolkit.Instance.ActiveProfile)
{
Debug.LogWarning("The active profile of the instance in your manager scene is different from the profile that loaded your scene. This is not recommended.");
}
else
{
Debug.LogWarning("Setting the manager scene MixedRealityToolkit instance to the active instance.");
MixedRealityToolkit.SetActiveInstance(instance);
}
}
break;
}
}
}
catch (Exception)
{
// This can happen if the scene isn't valid
// Not an issue - we'll take care of it on the next update.
return;
}
if (!foundToolkitInstance)
{
GameObject mrtkGo = new GameObject("MixedRealityToolkit");
MixedRealityToolkit toolkitInstance = mrtkGo.AddComponent<MixedRealityToolkit>();
try
{
SceneManager.MoveGameObjectToScene(mrtkGo, scene);
// Set the scene as dirty
EditorSceneManager.MarkSceneDirty(scene);
}
catch (Exception)
{
// This can happen if the scene isn't valid
// Not an issue - we'll take care of it on the next update.
// Destroy the new manager
GameObject.DestroyImmediate(mrtkGo);
return;
}
MixedRealityToolkit.SetActiveInstance(toolkitInstance);
Debug.LogWarning("Didn't find a MixedRealityToolkit instance in your manager scene. Creating one now.");
}
}
}
else
{
Debug.Log("Couldn't load manager scene!");
}
}
/// <summary>
/// If a lighting scene is being used, this ensures that at least one lighting scene is loaded in editor.
/// </summary>
private void EditorUpdateLightingScene(bool heirarchyDirty)
{
if (!Profile.UseLightingScene || !Profile.EditorManageLoadedScenes)
{
return;
}
if (string.IsNullOrEmpty(ActiveLightingScene))
{
ActiveLightingScene = Profile.DefaultLightingScene.Name;
}
else
{
foreach (SceneInfo lightingScene in Profile.LightingScenes)
{
if (lightingScene.Name == ActiveLightingScene)
{
Scene scene;
if (EditorSceneUtils.LoadScene(lightingScene, false, out scene))
{
EditorSceneUtils.CopyLightingSettingsToActiveScene(scene);
if (Profile.EditorEnforceLightingSceneTypes && heirarchyDirty)
{
EditorEnforceLightingSceneTypes(scene);
}
}
if (Profile.EditorEnforceSceneOrder)
{ // If we're enforcing scene order, make sure this scene comes after the current scene
Scene currentFirstScene = EditorSceneManager.GetSceneAt(0);
EditorSceneManager.MoveSceneAfter(scene, currentFirstScene);
}
}
else
{
EditorSceneUtils.UnloadScene(lightingScene, true);
}
}
}
}
/// <summary>
/// Ensures that only approved component types are present in lighting scenes.
/// </summary>
private void EditorEnforceLightingSceneTypes(Scene scene)
{
if (EditorSceneManager.sceneCount == 1)
{ // There's nowhere to move invalid objects to.
return;
}
List<Component> violations = new List<Component>();
if (EditorSceneUtils.EnforceSceneComponents(scene, Profile.PermittedLightingSceneComponentTypes, violations))
{
Scene targetScene = default(Scene);
for (int i = 0; i < EditorSceneManager.sceneCount; i++)
{
targetScene = EditorSceneManager.GetSceneAt(i);
if (targetScene.path != scene.path)
{ // We'll move invalid items to this scene
break;
}
}
if (!targetScene.IsValid() || !targetScene.isLoaded)
{ // Something's gone wrong - don't proceed
return;
}
HashSet<Transform> rootObjectsToMove = new HashSet<Transform>();
foreach (Component component in violations)
{
rootObjectsToMove.Add(component.transform.root);
}
List<string> rootObjectNames = new List<string>();
// Build a list of root objects so they know what's being moved
foreach (Transform rootObject in rootObjectsToMove)
{
rootObjectNames.Add(rootObject.name);
}
EditorUtility.DisplayDialog(
"Invalid components found in " + scene.name,
"Only lighting-related components are permitted. The following GameObjects will be moved to another scene:\n\n"
+ String.Join("\n", rootObjectNames)
+ "\n\nTo disable this warning, un-check 'EditorEnforceLightingSceneTypes' in your SceneSystem profile.", "OK");
try
{
foreach (Transform rootObject in rootObjectsToMove)
{
EditorSceneManager.MoveGameObjectToScene(rootObject.gameObject, targetScene);
}
EditorGUIUtility.PingObject(rootObjectsToMove.FirstOrDefault());
}
catch (Exception)
{
// This can happen if the move object operation fails. No big deal, we'll try again next time.
return;
}
}
}
/// <summary>
/// Adds all scenes from profile into build settings.
/// </summary>
private void EditorUpdateBuildSettings()
{
if (!Profile.EditorManageBuildSettings)
{ // Nothing to do here
return;
}
if (Profile.UseManagerScene)
{
if (EditorSceneUtils.AddSceneToBuildSettings(
Profile.ManagerScene,
cachedBuildScenes,
EditorSceneUtils.BuildIndexTarget.First))
{
cachedBuildScenes = EditorBuildSettings.scenes;
}
}
foreach (SceneInfo contentScene in Profile.ContentScenes)
{
if (EditorSceneUtils.AddSceneToBuildSettings(
contentScene,
cachedBuildScenes,
EditorSceneUtils.BuildIndexTarget.None))
{
cachedBuildScenes = EditorBuildSettings.scenes;
}
}
if (Profile.UseLightingScene)
{
foreach (SceneInfo lightingScene in Profile.LightingScenes)
{ // Make sure ALL lighting scenes are added to build settings
if (EditorSceneUtils.AddSceneToBuildSettings(
lightingScene,
cachedBuildScenes,
EditorSceneUtils.BuildIndexTarget.Last))
{
cachedBuildScenes = EditorBuildSettings.scenes;
}
}
}
EditorCheckForSceneNameDuplicates();
}
/// <summary>
/// Ensures that there are no scenes in build settings with duplicate names.
/// If any are found, a resolve duplicates window is launched.
/// </summary>
private void EditorCheckForSceneNameDuplicates()
{
List<SceneInfo> allScenes = new List<SceneInfo>();
Dictionary<string, List<int>> duplicates = new Dictionary<string, List<int>>();
foreach (SceneInfo sceneInfo in Profile.LightingScenes)
{
if (!sceneInfo.IsEmpty)
{ // Don't bother with empty scenes, they'll be handled elsewhere.
allScenes.Add(sceneInfo);
}
}
foreach (SceneInfo sceneInfo in Profile.ContentScenes)
{
if (!sceneInfo.IsEmpty)
{ // Don't bother with empty scenes, they'll be handled elsewhere.
allScenes.Add(sceneInfo);
}
}
if (Profile.UseManagerScene && !Profile.ManagerScene.IsEmpty)
{
allScenes.Add(Profile.ManagerScene);
}
if (EditorSceneUtils.CheckBuildSettingsForDuplicates(allScenes, duplicates))
{
// If it's already open, don't display
if (!ResolveDuplicateScenesWindow.IsOpen)
{
ResolveDuplicateScenesWindow window = EditorWindow.GetWindow<ResolveDuplicateScenesWindow>("Fix Duplicate Scene Names");
window.ResolveDuplicates(duplicates, allScenes);
}
}
else if (ResolveDuplicateScenesWindow.IsOpen)
{
// If we fixed the issue without the window, close the window
ResolveDuplicateScenesWindow.Instance.Close();
}
}
#endif
}
} | 0 | 0.780756 | 1 | 0.780756 | game-dev | MEDIA | 0.713315 | game-dev | 0.808393 | 1 | 0.808393 |
smcameron/space-nerds-in-space | 44,471 | entity.c | /*
Copyright (C) 2010 Stephen M. Cameron
Author: Stephen M. Cameron
This file is part of Spacenerds In Space.
Spacenerds in Space is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Spacenerds in Space is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Spacenerds in Space; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/* Need _GNU_SOURCE for qsort_r, must be defined before any include directives */
#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <limits.h>
#include "mtwist.h"
#include "mathutils.h"
#include "matrix.h"
#include "vertex.h"
#include "triangle.h"
#include "quat.h"
#include "mesh.h"
#include "stl_parser.h"
#include "snis_graph.h"
#include "material.h"
#include "entity.h"
#include "mathutils.h"
#include "my_point.h"
#include "snis_font.h"
#include "snis_typeface.h"
#include "snis_alloc.h"
#include "entity_private.h"
#include "graph_dev.h"
static int clip_line(struct mat41* vtx0, struct mat41* vtx1);
struct entity *add_entity(struct entity_context *cx,
struct mesh *m, float x, float y, float z, int color)
{
int n;
static int throttle = 0;
#if ADD_ENTITY_CHAOS_MONKEY
/* for testing that code can withstand add_entity failures */
if (snis_randn(1000) < 50)
return NULL;
#endif
n = snis_object_pool_alloc_obj(cx->entity_pool);
if (n < 0) {
if (throttle < 10 || (throttle & (0x3f)) == 0) { /* Throttle these messages */
printf("Out of entities at %s:%d\n", __FILE__, __LINE__);
fflush(stdout);
}
throttle++;
return NULL;
} else {
if (throttle > 0)
throttle--;
}
cx->entity_list[n].visible = 1;
cx->entity_list[n].e_visible = 1;
cx->entity_list[n].m = m;
cx->entity_list[n].high_poly = m;
cx->entity_list[n].low_poly = m;
cx->entity_list[n].x = x;
cx->entity_list[n].y = y;
cx->entity_list[n].z = z;
vec3_init(&cx->entity_list[n].e_pos, x, y, z);
vec3_init(&cx->entity_list[n].scale, 1, 1, 1);
vec3_init(&cx->entity_list[n].e_scale, 1, 1, 1);
cx->entity_list[n].color = color;
cx->entity_list[n].render_style = RENDER_NORMAL;
cx->entity_list[n].user_data = NULL;
cx->entity_list[n].shadecolor = 0;
cx->entity_list[n].orientation = identity_quat;
cx->entity_list[n].e_orientation = identity_quat;
cx->entity_list[n].material_ptr = 0;
cx->entity_list[n].parent = 0;
cx->entity_list[n].entity_child_index = -1;
cx->entity_list[n].emit_intensity = 1.0;
cx->entity_list[n].sx = -1;
cx->entity_list[n].sy = -1;
cx->entity_list[n].onscreen = 0;
if (m && m->material)
update_entity_material(&cx->entity_list[n], m->material);
return &cx->entity_list[n];
}
static void remove_entity_children(struct entity_context *cx, struct entity *e)
{
int entity_child_index = e->entity_child_index;
while (entity_child_index >= 0) {
struct entity_child *this_ec = &cx->entity_child_list[entity_child_index];
struct entity *this_child = &cx->entity_list[this_ec->child_entity_index];
if (this_child->entity_child_index >= 0)
remove_entity_children(cx, this_child);
snis_object_pool_free_object(cx->entity_pool, this_ec->child_entity_index);
int next_entity_child_index = this_ec->next_entity_child_index;
snis_object_pool_free_object(cx->entity_child_pool, entity_child_index);
entity_child_index = next_entity_child_index;
}
e->entity_child_index = -1;
}
void remove_entity(struct entity_context *cx, struct entity *e)
{
int index;
if (!e)
return;
if (e->entity_child_index >= 0)
remove_entity_children(cx, e);
index = e - &cx->entity_list[0];
snis_object_pool_free_object(cx->entity_pool, index);
}
void remove_all_entity(struct entity_context *cx)
{
snis_object_pool_free_all_objects(cx->entity_pool);
snis_object_pool_free_all_objects(cx->entity_child_pool);
}
void update_entity_parent(struct entity_context *cx, struct entity *child, struct entity *parent)
{
if (child->parent == parent)
return;
int new_entity_child_index = -1;
int child_index = child - &cx->entity_list[0];
if (parent) {
/* preallocate this so that in case we can't get one, at least we don't crash. */
new_entity_child_index = snis_object_pool_alloc_obj(cx->entity_child_pool);
if (new_entity_child_index < 0) {
printf("entity_child_pool exhausted at %s:%d\n", __FILE__, __LINE__);
return;
}
}
if (child->parent) {
/* remove this child out of the old parent child_entity_list */
int entity_child_index = child->parent->entity_child_index;
struct entity_child *last_ec = 0;
while (entity_child_index >= 0) {
struct entity_child *this_ec = &cx->entity_child_list[entity_child_index];
if (this_ec->child_entity_index == child_index) {
/* we found the child, fix the list */
if (!last_ec) /* first link */
child->parent->entity_child_index = this_ec->next_entity_child_index;
else
last_ec->next_entity_child_index = this_ec->next_entity_child_index;
snis_object_pool_free_object(cx->entity_child_pool, entity_child_index);
break; /* found the child, done */
}
entity_child_index = this_ec->next_entity_child_index;
last_ec = this_ec;
}
}
child->parent = parent;
if (parent) {
/* add child into new parent child_entity_list */
struct entity_child *new_ec = &cx->entity_child_list[new_entity_child_index];
/* insert entity_child at the front of the list */
new_ec->child_entity_index = child_index;
new_ec->next_entity_child_index = parent->entity_child_index;
parent->entity_child_index = new_entity_child_index;
}
}
void update_entity_pos(struct entity *e, float x, float y, float z)
{
vec3_init(&e->e_pos, x, y, z);
}
void update_entity_orientation(struct entity *e, const union quat *orientation)
{
e->e_orientation = *orientation;
}
float entity_get_scale(struct entity *e)
{
return vec3_cwise_max(&e->e_scale);
}
void update_entity_scale(struct entity *e, float scale)
{
vec3_init(&e->e_scale, scale, scale, scale);
}
void entity_get_non_uniform_scale(struct entity *e, float *x_scale, float *y_scale, float *z_scale)
{
*x_scale = e->e_scale.v.x;
*y_scale = e->e_scale.v.y;
*z_scale = e->e_scale.v.z;
}
void update_entity_non_uniform_scale(struct entity *e, float x_scale, float y_scale, float z_scale)
{
vec3_init(&e->e_scale, x_scale, y_scale, z_scale);
}
void update_entity_color(struct entity *e, int color)
{
e->color = color;
}
void update_entity_shadecolor(struct entity *e, int color)
{
e->shadecolor = color;
}
void update_entity_visibility(struct entity *e, int visible)
{
e->e_visible = visible;
}
int entity_get_visibility(struct entity *e)
{
return e->e_visible;
}
void update_entity_material(struct entity *e, struct material *material_ptr)
{
e->material_ptr = material_ptr;
}
struct material *entity_get_material(struct entity *e)
{
return e->material_ptr;
}
static inline float wx_screen(struct entity_context *cx, float wx)
{
struct camera_info *c = &cx->camera;
return (wx * c->xvpixels / 2) + c->xvpixels / 2 + cx->window_offset_x;
}
static inline float wy_screen(struct entity_context *cx, float wy)
{
struct camera_info *c = &cx->camera;
return (-wy * c->yvpixels / 2) + c->yvpixels / 2 + cx->window_offset_y;
}
static void calculate_model_matrices(struct camera_info *c, struct frustum *f, struct entity *e,
struct entity_transform *transform)
{
transform->v = &f->v_matrix;
transform->vp = &f->vp_matrix;
/* Model = (T*R)*S
T - translation matrix
R - rotation matrix
S - scale matrix
Combine for post multiply of vector */
struct mat44d mat_t = {{
{ 1, 0, 0, 0 },
{ 0, 1, 0, 0 },
{ 0, 0, 1, 0 },
{ e->x, e->y, e->z, 1 }}};
struct mat44d mat_s = {{
{ e->scale.v.x, 0, 0, 0 },
{ 0, e->scale.v.y, 0, 0 },
{ 0, 0, e->scale.v.z, 0 },
{ 0, 0, 0, 1 }}};
struct mat44d mat_r = {{
{ 1, 0, 0, 0 },
{ 0, 1, 0, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 0, 1 } } };
if (e->material_ptr && e->material_ptr->billboard_type != MATERIAL_BILLBOARD_TYPE_NONE) {
switch (e->material_ptr->billboard_type) {
/* aligned so that +y axis = camera up and normal parallel with camera look direction */
case MATERIAL_BILLBOARD_TYPE_SCREEN:
{
/* take the corner 3x3 from the view matrix, transpose, and pad back to 4x4 */
struct mat33d tm1, tm2;
mat44_to_mat33_dd(transform->v, &tm1);
mat33_transpose_dd(&tm1, &tm2);
mat33_to_mat44_dd(&tm2, &mat_r);
}
break;
/* aligned so that +y axis = camera up and normal is pointing to camera position */
case MATERIAL_BILLBOARD_TYPE_SPHERICAL:
{
union vec3 cam_up = { { c->ux, c->uy, c->uz } };
union vec3 look = { { c->x - e->x, c->y - e->y, c->z - e->z } };
vec3_normalize_self(&look);
union vec3 right;
vec3_cross(&right, &cam_up, &look);
vec3_normalize_self(&right);
union vec3 up;
vec3_cross(&up, &look, &right);
vec3_normalize_self(&up);
if (e->material_ptr->rotate_randomly) {
/* Rotate randomly about normal. */
union quat rotation;
float angle = (snis_randn(1000) % 360) * M_PI / 180.0;
quat_init_axis(&rotation, look.v.x, look.v.y, look.v.z, angle);
quat_rot_vec_self(&up, &rotation);
quat_rot_vec_self(&right, &rotation);
}
/* a rotation matrix to align with up, right, and look unit vectors
r.x r.y r.z 0
u.x u.y u.z 0
l.x l.y l.z 0
0 0 0 1 */
mat_r.m[0][0] = right.v.x;
mat_r.m[0][1] = right.v.y;
mat_r.m[0][2] = right.v.z;
mat_r.m[0][3] = 0;
mat_r.m[1][0] = up.v.x;
mat_r.m[1][1] = up.v.y;
mat_r.m[1][2] = up.v.z;
mat_r.m[1][3] = 0;
mat_r.m[2][0] = look.v.x;
mat_r.m[2][1] = look.v.y;
mat_r.m[2][2] = look.v.z;
mat_r.m[2][3] = 0;
mat_r.m[3][0] = 0;
mat_r.m[3][1] = 0;
mat_r.m[3][2] = 0;
mat_r.m[3][3] = 1;
}
break;
/* aligned so that +y axis = quaternion axis and normal is pointing in direction of camera position */
case MATERIAL_BILLBOARD_TYPE_AXIS:
{
union vec3 look_to_cam = { { c->x - e->x, c->y - e->y, c->z - e->z } };
vec3_normalize_self(&look_to_cam);
union vec3 up = { { 1, 0, 0 } };
quat_rot_vec_self(&up, &e->orientation);
vec3_normalize_self(&up);
union vec3 right;
vec3_cross(&right, &up, &look_to_cam);
vec3_normalize_self(&right);
union vec3 look;
vec3_cross(&look, &right, &up);
vec3_normalize_self(&look);
/* a rotation matrix to align with up, right, and look unit vectors
r.x r.y r.z 0
u.x u.y u.z 0
l.x l.y l.z 0
0 0 0 1 */
struct mat44d mat_r_y;
mat_r_y.m[0][0] = right.v.x;
mat_r_y.m[0][1] = right.v.y;
mat_r_y.m[0][2] = right.v.z;
mat_r_y.m[0][3] = 0;
mat_r_y.m[1][0] = up.v.x;
mat_r_y.m[1][1] = up.v.y;
mat_r_y.m[1][2] = up.v.z;
mat_r_y.m[1][3] = 0;
mat_r_y.m[2][0] = look.v.x;
mat_r_y.m[2][1] = look.v.y;
mat_r_y.m[2][2] = look.v.z;
mat_r_y.m[2][3] = 0;
mat_r_y.m[3][0] = 0;
mat_r_y.m[3][1] = 0;
mat_r_y.m[3][2] = 0;
mat_r_y.m[3][3] = 1;
/* rotate the model by 90 degrees so +x is up before applying
the billboarding matrix */
struct mat44d mat_y_to_x = { {
{ 0, 1, 0, 0 },
{ -1, 0, 0, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 0, 1 } } };
mat44_product_ddd(&mat_r_y, &mat_y_to_x, &mat_r);
}
break;
}
} else {
/* normal quaternion based rotation */
quat_to_rh_rot_matrix_fd(&e->orientation, &mat_r.m[0][0]);
}
mat44_product_ddd(&mat_t, &mat_r, &transform->m_no_scale);
mat44_product_ddd(&transform->m_no_scale, &mat_s, &transform->m);
/* calculate the final model-view-proj and model-view matrices */
mat44_product_ddf(transform->vp, &transform->m, &transform->mvp);
mat44_product_ddf(transform->v, &transform->m, &transform->mv);
/* normal transform is the inverse transpose of the upper left 3x3 of the model-view matrix */
struct mat33 mat_tmp33;
mat33_inverse_transpose_ff(mat44_to_mat33_ff(&transform->mv, &mat_tmp33), &transform->normal);
}
int transform_vertices(const struct mat44 *matrix, struct vertex *v, int len)
{
int total_clip_flag = 0x3f;
int i;
for (i = 0; i < len; i++) {
/* Set homogeneous coord to 1 */
v[i].w = 1.0;
/* Do the transformation... */
struct mat41 *m1 = (struct mat41 *) &v[i].x;
struct mat41 *m2 = (struct mat41 *) &v[i].wx;
mat44_x_mat41(matrix, m1, m2);
/* check all 6 clip planes for this vertex */
v[i].clip = 0;
v[i].clip |= (v[i].wx < -v[i].ww) ? (1<<0) : 0;
v[i].clip |= (v[i].wx > v[i].ww) ? (1<<1) : 0;
v[i].clip |= (v[i].wy < -v[i].ww) ? (1<<2) : 0;
v[i].clip |= (v[i].wy > v[i].ww) ? (1<<3) : 0;
v[i].clip |= (v[i].wz < -v[i].ww) ? (1<<4) : 0;
v[i].clip |= (v[i].wz > v[i].ww) ? (1<<5) : 0;
/* total is the intersection of all the vertices */
total_clip_flag &= v[i].clip;
}
/* if all vertices were clipped by the same plane then this set is all out */
return total_clip_flag > 0;
}
int transform_line(struct entity_context *cx, float x1, float y1, float z1, float x2, float y2, float z2,
float *sx1, float *sy1, float *sx2, float *sy2)
{
struct vertex v[2] = {
VERTEX_INIT(x1, y1, z1, 1),
VERTEX_INIT(x2, y2, z2, 1) };
/* there is no model transform on a point */
struct mat44 mat_vp;
mat44_convert_df(&cx->camera.frustum.vp_matrix, &mat_vp);
if (transform_vertices(&mat_vp, &v[0], 2)) {
/* both ends outside frustum */
*sx1 = -1;
*sy1 = -1;
*sx2 = -1;
*sy2 = -1;
return 1;
}
if (v[0].clip || v[1].clip) {
if (clip_line((struct mat41 *) &v[0].wx, (struct mat41 *) &v[1].wx)) {
/* both ends clipped */
return 1;
}
}
/* perspective divide */
v[0].wx /= v[0].ww;
v[0].wy /= v[0].ww;
v[1].wx /= v[1].ww;
v[1].wy /= v[1].ww;
/* convert to screen coordinates */
*sx1 = wx_screen(cx, v[0].wx);
*sy1 = wy_screen(cx, v[0].wy);
*sx2 = wx_screen(cx, v[1].wx);
*sy2 = wy_screen(cx, v[1].wy);
return 0;
}
static int transform_point_in_frustum(struct entity_context *cx, struct frustum *f,
float x, float y, float z, float *sx, float *sy)
{
struct vertex v = VERTEX_INIT(x, y, z, 1);
/* there is no model transform on a point */
struct mat44 mat_vp;
mat44_convert_df(&f->vp_matrix, &mat_vp);
if (transform_vertices(&mat_vp, &v, 1)) {
*sx = -1;
*sy = -1;
return 1;
}
v.wx /= v.ww;
v.wy /= v.ww;
*sx = wx_screen(cx, v.wx);
*sy = wy_screen(cx, v.wy);
return 0;
}
int transform_point(struct entity_context *cx, float x, float y, float z, float *sx, float *sy)
{
return transform_point_in_frustum(cx, &cx->camera.frustum, x, y, z, sx, sy);
}
static void render_entity(struct entity_context *cx, struct frustum *f, struct entity *e, union vec3 *camera_light_pos)
{
/* calculate screen coords of entity as a whole */
transform_point_in_frustum(cx, f, e->x, e->y, e->z, &e->sx, &e->sy);
if (e->sx >=0 && e->sy >= 0)
e->onscreen = 1;
/* Do not render entities with scale of zero. Doing so will lead to infinities
* in the model normal matrix, besides being pointless.
*/
if (e->scale.v.x == 0 && e->scale.v.y == 0 && e->scale.v.z == 0) {
e->onscreen = 0;
return;
}
struct entity_transform transform;
calculate_model_matrices(&cx->camera, f, e, &transform);
graph_dev_draw_entity(cx, e, camera_light_pos, &transform);
}
void render_line(struct entity_context *cx, float x1, float y1, float z1, float x2, float y2, float z2)
{
calculate_camera_transform(cx);
struct mat44 mat_vp;
mat44_convert_df(&cx->camera.frustum.vp_matrix, &mat_vp);
graph_dev_draw_3d_line(cx, &mat_vp, x1, y1, z1, x2, y2, z2);
}
void render_skybox(struct entity_context *cx)
{
graph_dev_draw_skybox(&cx->camera.frustum.vp_matrix_no_translate);
}
#if defined(__APPLE__) || defined(__FreeBSD__)
static int object_depth_compare_greater(void *vcx, const void *a, const void *b)
#else
static int object_depth_compare_greater(const void *a, const void *b, void *vcx)
#endif
{
struct entity_context *cx = vcx;
struct entity *A = &cx->entity_list[*(const int *) a];
struct entity *B = &cx->entity_list[*(const int *) b];
if (A->dist3dsqrd < B->dist3dsqrd)
return 1;
if (A->dist3dsqrd > B->dist3dsqrd)
return -1;
return 0;
}
#if defined(__APPLE__) || defined(__FreeBSD__)
static int object_depth_compare_less(void *vcx, const void *a, const void *b)
#else
static int object_depth_compare_less(const void *a, const void *b, void *vcx)
#endif
{
struct entity_context *cx = vcx;
struct entity *A = &cx->entity_list[*(const int *) a];
struct entity *B = &cx->entity_list[*(const int *) b];
if (A->dist3dsqrd > B->dist3dsqrd)
return 1;
if (A->dist3dsqrd < B->dist3dsqrd)
return -1;
return 0;
}
static void sort_entity_distances(struct entity_context *cx)
{
#if defined(__APPLE__) || defined(__FreeBSD__)
qsort_r(cx->far_to_near_entity_depth, cx->nfar_to_near_entity_depth, sizeof(cx->far_to_near_entity_depth[0]),
cx, object_depth_compare_greater);
qsort_r(cx->near_to_far_entity_depth, cx->nnear_to_far_entity_depth, sizeof(cx->near_to_far_entity_depth[0]),
cx, object_depth_compare_less);
#else
qsort_r(cx->far_to_near_entity_depth, cx->nfar_to_near_entity_depth, sizeof(cx->far_to_near_entity_depth[0]),
object_depth_compare_greater, cx);
qsort_r(cx->near_to_far_entity_depth, cx->nnear_to_far_entity_depth, sizeof(cx->near_to_far_entity_depth[0]),
object_depth_compare_less, cx);
#endif
}
/* from http://www.crownandcutlass.com/features/technicaldetails/frustum.html
This page and its contents are Copyright 2000 by Mark Morley
Unless otherwise noted, you may use any and all code examples provided herein in any way you want. */
int sphere_in_frustum(struct frustum *f, float x, float y, float z, float radius)
{
int p;
for (p = 0; p < 6; p++)
if (f->planes[p][0] * x + f->planes[p][1] * y + f->planes[p][2] * z + f->planes[p][3] <= -radius)
return 0;
return 1;
}
/* from http://www.crownandcutlass.com/features/technicaldetails/frustum.html
This page and its contents are Copyright 2000 by Mark Morley
Unless otherwise noted, you may use any and all code examples provided herein in any way you want. */
static void extract_frustum_planes(struct frustum *f)
{
const double *clip = &f->vp_matrix.m[0][0];
float t;
/* Extract the numbers for the RIGHT plane */
f->planes[0][0] = clip[3] - clip[0];
f->planes[0][1] = clip[7] - clip[4];
f->planes[0][2] = clip[11] - clip[8];
f->planes[0][3] = clip[15] - clip[12];
/* Normalize the result */
t = dist3d(f->planes[0][0], f->planes[0][1], f->planes[0][2]);
f->planes[0][0] /= t;
f->planes[0][1] /= t;
f->planes[0][2] /= t;
f->planes[0][3] /= t;
/* Extract the numbers for the LEFT plane */
f->planes[1][0] = clip[3] + clip[0];
f->planes[1][1] = clip[7] + clip[4];
f->planes[1][2] = clip[11] + clip[8];
f->planes[1][3] = clip[15] + clip[12];
/* Normalize the result */
t = dist3d(f->planes[1][0], f->planes[1][1], f->planes[1][2]);
f->planes[1][0] /= t;
f->planes[1][1] /= t;
f->planes[1][2] /= t;
f->planes[1][3] /= t;
/* Extract the BOTTOM plane */
f->planes[2][0] = clip[3] + clip[1];
f->planes[2][1] = clip[7] + clip[5];
f->planes[2][2] = clip[11] + clip[9];
f->planes[2][3] = clip[15] + clip[13];
/* Normalize the result */
t = dist3d(f->planes[2][0], f->planes[2][1], f->planes[2][2]);
f->planes[2][0] /= t;
f->planes[2][1] /= t;
f->planes[2][2] /= t;
f->planes[2][3] /= t;
/* Extract the TOP plane */
f->planes[3][0] = clip[3] - clip[1];
f->planes[3][1] = clip[7] - clip[5];
f->planes[3][2] = clip[11] - clip[9];
f->planes[3][3] = clip[15] - clip[13];
/* Normalize the result */
t = dist3d(f->planes[3][0], f->planes[3][1], f->planes[3][2]);
f->planes[3][0] /= t;
f->planes[3][1] /= t;
f->planes[3][2] /= t;
f->planes[3][3] /= t;
/* Extract the FAR plane */
f->planes[4][0] = clip[3] - clip[2];
f->planes[4][1] = clip[7] - clip[6];
f->planes[4][2] = clip[11] - clip[10];
f->planes[4][3] = clip[15] - clip[14];
/* Normalize the result */
t = dist3d(f->planes[4][0], f->planes[4][1], f->planes[4][2]);
f->planes[4][0] /= t;
f->planes[4][1] /= t;
f->planes[4][2] /= t;
f->planes[4][3] /= t;
/* Extract the NEAR plane */
f->planes[5][0] = clip[3] + clip[2];
f->planes[5][1] = clip[7] + clip[6];
f->planes[5][2] = clip[11] + clip[10];
f->planes[5][3] = clip[15] + clip[14];
/* Normalize the result */
t = dist3d(f->planes[5][0], f->planes[5][1], f->planes[5][2]);
f->planes[5][0] /= t;
f->planes[5][1] /= t;
f->planes[5][2] /= t;
f->planes[5][3] /= t;
}
static void calculate_camera_transform_near_far(struct camera_info *c, struct frustum *f, float near, float far)
{
f->near = near;
f->far = far;
/* based on gluPerspective to find the right, left, top, and bottom */
float scale = tan(c->angle_of_view * 0.5) * f->near;
f->right = ((float) c->xvpixels / (float) c->yvpixels * scale);
f->left = -f->right;
f->top = scale;
f->bottom = -f->top;
struct mat41 *v; /* camera relative y axis (up/down) */
struct mat41 *n; /* camera relative z axis (into view plane) */
struct mat41 *u; /* camera relative x axis (left/right) */
struct mat41 up;
up.m[0] = c->ux;
up.m[1] = c->uy;
up.m[2] = c->uz;
up.m[3] = 1;
/* Translate to camera position... */
struct mat44d cameratrans_transform = { { { 1, 0, 0, 0 },
{ 0, 1, 0, 0 },
{ 0, 0, 1, 0 },
{ -c->x, -c->y, -c->z, 1} } };
/* Calculate camera rotation based on look direction ...
http://ksimek.github.io/2012/08/22/extrinsic/ 'The "Look-At" Camera'
p = look at point, C = camera, u = up
L = p - C
s = L x u
u' = s x L
camera rotation = | s1 s2 s3 |
| u'1 u'2 u'3 |
| -L1 -L2 -L3 |
snis n = L
snis u = s
snis v = u' */
struct mat41 look_direction;
look_direction.m[0] = (c->lx - c->x);
look_direction.m[1] = (c->ly - c->y);
look_direction.m[2] = (c->lz - c->z);
look_direction.m[3] = 1.0;
normalize_vector(&look_direction, &look_direction);
n = &look_direction;
/* Calculate x direction relative to camera, "camera_x" */
struct mat41 camera_x;
mat41_cross_mat41(&look_direction, &up, &camera_x);
normalize_vector(&camera_x, &camera_x);
u = &camera_x;
/* Calculate camera relative x axis */
struct mat41 x_cross_look;
mat41_cross_mat41(&camera_x, &look_direction, &x_cross_look);
/* v should not need normalizing as n and u are already
* unit, and are perpendicular */
normalize_vector(&x_cross_look, &x_cross_look);
v = &x_cross_look;
/* Make a rotation matrix...
| ux uy uz 0 |
| vx vy vz 0 |
| -nx -ny -nz 0 |
| 0 0 0 1 |
*/
struct mat44d cameralook_transform;
cameralook_transform.m[0][0] = u->m[0];
cameralook_transform.m[0][1] = v->m[0];
cameralook_transform.m[0][2] = -n->m[0];
cameralook_transform.m[0][3] = 0.0;
cameralook_transform.m[1][0] = u->m[1];
cameralook_transform.m[1][1] = v->m[1];
cameralook_transform.m[1][2] = -n->m[1];
cameralook_transform.m[1][3] = 0.0;
cameralook_transform.m[2][0] = u->m[2];
cameralook_transform.m[2][1] = v->m[2];
cameralook_transform.m[2][2] = -n->m[2];
cameralook_transform.m[2][3] = 0.0;
cameralook_transform.m[3][0] = 0.0;
cameralook_transform.m[3][1] = 0.0;
cameralook_transform.m[3][2] = 0.0;
cameralook_transform.m[3][3] = 1.0;
/* Make perspective transform based on OpenGL frustum
http://www.scratchapixel.com/lessons/3d-advanced-lessons/perspective-and-orthographic-projection-matrix/opengl-perspective-projection-matrix/
*/
struct mat44d perspective_transform;
perspective_transform.m[0][0] = (2 * f->near) / (f->right - f->left);
perspective_transform.m[0][1] = 0.0;
perspective_transform.m[0][2] = 0.0;
perspective_transform.m[0][3] = 0.0;
perspective_transform.m[1][0] = 0.0;
perspective_transform.m[1][1] = (2.0 * f->near) / (f->top - f->bottom);
perspective_transform.m[1][2] = 0.0;
perspective_transform.m[1][3] = 0.0;
perspective_transform.m[2][0] = (f->right + f->left) / (f->right - f->left);
perspective_transform.m[2][1] = (f->top + f->bottom) / (f->top - f->bottom);
perspective_transform.m[2][2] = -(f->far + f->near) / (f->far - f->near);
perspective_transform.m[2][3] = -1.0;
perspective_transform.m[3][0] = 0.0;
perspective_transform.m[3][1] = 0.0;
perspective_transform.m[3][2] = (-2 * f->far * f->near) / (f->far - f->near);
perspective_transform.m[3][3] = 0.0;
/* save perspective */
f->p_matrix = perspective_transform;
/* make the view matrix, V = L * T */
mat44_product_ddd(&cameralook_transform, &cameratrans_transform, &f->v_matrix);
/* make the view-perspective matrix, VP = P * V */
mat44_product_ddd(&perspective_transform, &f->v_matrix, &f->vp_matrix);
/* save vp matrix without any camera translation */
mat44_product_ddf(&perspective_transform, &cameralook_transform, &f->vp_matrix_no_translate);
/* pull out the frustum planes for entity culling */
extract_frustum_planes(f);
}
void calculate_camera_transform(struct entity_context *cx)
{
/* calculate for the entire frustum */
calculate_camera_transform_near_far(&cx->camera, &cx->camera.frustum, cx->camera.near, cx->camera.far);
}
static void reposition_fake_star(struct entity_context *cx, struct vertex *fs, float radius);
static void update_entity_child_state(struct entity *e)
{
int visible = e->e_visible;
union vec3 pos = e->e_pos;
union vec3 scale = e->e_scale;
union quat orientation = e->e_orientation;
struct entity *parent = e->parent;
while (parent) {
visible = visible && parent->e_visible;
quat_rot_vec_self(&pos, &parent->e_orientation);
vec3_add_self(&pos, &parent->e_pos);
vec3_cwise_product_self(&scale, &parent->e_scale);
quat_mul_self_right(&parent->e_orientation, &orientation);
parent = parent->parent;
}
e->visible = visible;
e->x = pos.v.x;
e->y = pos.v.y;
e->z = pos.v.z;
e->scale = scale;
e->orientation = orientation;
}
void render_entities(struct entity_context *cx)
{
int i, j, k, n;
struct camera_info *c = &cx->camera;
sng_set_3d_viewport(cx->window_offset_x, cx->window_offset_y, c->xvpixels, c->yvpixels);
calculate_camera_transform(cx);
/* see if the fake stars have wandered outside of our immediate area */
if (cx->nfakestars > 0) {
float r2 = cx->fakestars_radius * cx->fakestars_radius;
for (i = 0; i < cx->nfakestars; i++) {
struct vertex *fs = &cx->fake_stars_mesh->v[i];
float dist2 = dist3dsqrd(c->x - fs->x, c->y - fs->y, c->z - fs->z);
if (dist2 > r2)
reposition_fake_star(cx, fs, cx->fakestars_radius);
}
mesh_graph_dev_init(cx->fake_stars_mesh);
}
/* For better depth buffer precision do the draw in multiple (two) passes based on the
* dynamic range of near/far, and clear the depth buffer between passes. A good rule of
* thumb is to have far / near < 10000 on 24-bit depth buffer. At the boundary between
* passes a slight seam can become visible. To avoid this visible seam we should try to
* avoid having the boundary between passes intersect any large objects. To this end we
* have 3 reasonable candidate boundary distances and choose the boundary distance which
* intersects the fewest large objects.
*/
float boundary_candidate[3] = { /* distance candidates for the boundary between passes */
cx->camera.near * 4000.0,
cx->camera.near * 7000.0,
cx->camera.near * 10000.0,
};
int boundary_intersects[3] = { 0, 0, 0 }; /* Count of objects intersecting each boundary distance plane */
int last_candidate, candidate = 0;
float render_pass_boundary = boundary_candidate[0];
union vec3 camera_pos, camera_look, camera_to_entity;
int n_passes;
struct frustum rendering_pass[2];
camera_pos.v.x = cx->camera.x;
camera_pos.v.y = cx->camera.y;
camera_pos.v.z = cx->camera.z;
camera_look.v.x = cx->camera.lx - cx->camera.x;
camera_look.v.y = cx->camera.ly - cx->camera.y;
camera_look.v.z = cx->camera.lz - cx->camera.z;
vec3_normalize_self(&camera_look);
if (cx->camera.far / cx->camera.near < render_pass_boundary) {
n_passes = 1;
rendering_pass[0] = c->frustum;
} else {
n_passes = 2;
calculate_camera_transform_near_far(&cx->camera, &rendering_pass[0],
render_pass_boundary, cx->camera.far);
calculate_camera_transform_near_far(&cx->camera, &rendering_pass[1],
cx->camera.near, render_pass_boundary + render_pass_boundary / 1000.0);
/* the additional 0.1% is to render a little farther to cover seam */
}
int pass;
for (pass = 0; pass < n_passes; pass++) {
struct frustum *f = &rendering_pass[pass];
/* find all entities in view frustum and sort them by distance */
n = snis_object_pool_highest_object(cx->entity_pool);
cx->nnear_to_far_entity_depth = 0;
cx->nfar_to_near_entity_depth = 0;
if (pass == 0) {
boundary_intersects[0] = 0;
boundary_intersects[1] = 0;
boundary_intersects[2] = 0;
}
for (j = 0; j <= n; j++) {
if (!snis_object_pool_is_allocated(cx->entity_pool, j))
continue;
struct entity *e = &cx->entity_list[j];
if (e->m == NULL)
continue;
/* clear on the first pass and accumulate the state */
if (pass == 0) {
update_entity_child_state(e);
e->onscreen = 0;
}
if (!e->visible)
continue;
float max_scale = vec3_cwise_max(&e->scale);
if (!sphere_in_frustum(f, e->x, e->y, e->z, e->m->radius * max_scale))
continue;
e->dist3dsqrd = dist3dsqrd(c->x - e->x, c->y - e->y, c->z - e->z);
/* See: http://stackoverflow.com/questions/3717226/radius-of-projected-sphere */
float approx_pixel_size = c->yvpixels * e->m->radius * max_scale /
tan(cx->camera.angle_of_view * 0.5) / sqrt(e->dist3dsqrd);
/* only cull stuff entirely that is too small on flat shader */
if (c->renderer & FLATSHADING_RENDERER && e->dist3dsqrd != 0 && approx_pixel_size < 2.0)
continue;
/* Choose low or high poly mesh based on on-screen size */
if (approx_pixel_size < cx->hi_lo_poly_pixel_threshold)
e->m = e->low_poly;
else
e->m = e->high_poly;
int render_order = graph_dev_entity_render_order(e);
switch (render_order) {
case GRAPH_DEV_RENDER_FAR_TO_NEAR:
cx->far_to_near_entity_depth[cx->nfar_to_near_entity_depth] = j;
cx->nfar_to_near_entity_depth++;
break;
case GRAPH_DEV_RENDER_NEAR_TO_FAR:
cx->near_to_far_entity_depth[cx->nnear_to_far_entity_depth] = j;
cx->nnear_to_far_entity_depth++;
break;
}
/* For each boundary candidate, count large object intersections */
if (pass == 0 && n_passes > 1) {
if (e->m->radius * max_scale < 500)
continue; /* ignore small objects in choosing render pass boundary */
camera_to_entity.v.x = e->x - camera_pos.v.x;
camera_to_entity.v.y = e->y - camera_pos.v.y;
camera_to_entity.v.z = e->z - camera_pos.v.z;
float zdist = vec3_dot(&camera_to_entity, &camera_look);
if (zdist < 0)
continue; /* behind camera, ignore (should already be frustum culled). */
if (e->m->geometry_mode == MESH_GEOMETRY_POINTS) /* Ignore fake stars, etc. */
continue;
if (e->m->radius * max_scale >= 299999.0)
continue; /* Hack to ignore warp tunnels (r=300000) */
/* Check each candidate boundary for intersection with this object */
for (k = 0; k < 3; k++)
if (fabsf(zdist - boundary_candidate[k]) < e->m->radius * max_scale)
boundary_intersects[k]++;
}
}
if (pass == 0 && n_passes > 1) {
/* Find the boundary candidate with the fewest large object intersections */
last_candidate = candidate;
candidate = 0;
if (boundary_intersects[candidate] != 0) {
/* Test for less than or *equal* so we choose the *farthest* among equals so
* that any resulting artifacts are more likely to occupy less screen space
* and be less obnoxious. With a little luck, it will even move it to a place
* that is invisible, like the back side of a planet.
*/
if (boundary_intersects[1] <= boundary_intersects[candidate])
candidate = 1;
if (boundary_intersects[2] <= boundary_intersects[candidate])
candidate = 2;
}
if (last_candidate != candidate) {
/* Recalculate the camera transforms if the render pass boundary was changed
to avoid some intersecting object */
render_pass_boundary = boundary_candidate[candidate];
calculate_camera_transform_near_far(&cx->camera, &rendering_pass[0],
render_pass_boundary, cx->camera.far);
calculate_camera_transform_near_far(&cx->camera, &rendering_pass[1],
cx->camera.near, render_pass_boundary + render_pass_boundary / 1000.0);
}
}
if (cx->nfar_to_near_entity_depth > 0 || cx->nnear_to_far_entity_depth > 0) {
/* need to reset the depth buffer between passes */
if (n_passes > 1 && pass != 0)
graph_dev_clear_depth_bit();
sort_entity_distances(cx);
/* find the position of our light in camera space */
struct mat41 camera_light_pos;
mat44_x_mat41_dff(&f->v_matrix, &cx->light, &camera_light_pos);
/* render the sorted entities */
/* near to far first, usually opaque geometry */
for (j = 0; j < cx->nnear_to_far_entity_depth; j++) {
struct entity *e = &cx->entity_list[cx->near_to_far_entity_depth[j]];
if (e)
render_entity(cx, f, e, (union vec3 *)&camera_light_pos.m[0]);
}
/* then far to near, usually blended geometry and software renderer */
for (j = 0; j < cx->nfar_to_near_entity_depth; j++) {
struct entity *e = &cx->entity_list[cx->far_to_near_entity_depth[j]];
if (e)
render_entity(cx, f, e, (union vec3 *)&camera_light_pos.m[0]);
}
}
}
}
void camera_set_pos(struct entity_context *cx, float x, float y, float z)
{
cx->camera.x = x;
cx->camera.y = y;
cx->camera.z = z;
}
void camera_get_pos(struct entity_context *cx, float *x, float *y, float *z)
{
*x = cx->camera.x;
*y = cx->camera.y;
*z = cx->camera.z;
}
void camera_look_at(struct entity_context *cx, float x, float y, float z)
{
cx->camera.lx = x;
cx->camera.ly = y;
cx->camera.lz = z;
}
void camera_get_look_at(struct entity_context *cx, float *x, float *y, float *z)
{
*x = cx->camera.lx;
*y = cx->camera.ly;
*z = cx->camera.lz;
}
void camera_assign_up_direction(struct entity_context *cx, float x, float y, float z)
{
cx->camera.ux = x;
cx->camera.uy = y;
cx->camera.uz = z;
}
void camera_get_up_direction(struct entity_context *cx, float *x, float *y, float *z)
{
*x = cx->camera.ux;
*y = cx->camera.uy;
*z = cx->camera.uz;
}
void camera_set_parameters(struct entity_context *cx, float near, float far,
int xvpixels, int yvpixels, float angle_of_view)
{
cx->camera.near = near;
cx->camera.far = far;
cx->camera.xvpixels = xvpixels;
cx->camera.yvpixels = yvpixels;
cx->camera.angle_of_view = angle_of_view;
}
void camera_get_parameters(struct entity_context *cx, float *near, float *far,
int *xvpixels, int *yvpixels, float *angle_of_view)
{
*near = cx->camera.near;
*far = cx->camera.far;
*xvpixels = cx->camera.xvpixels;
*yvpixels = cx->camera.yvpixels;
*angle_of_view = cx->camera.angle_of_view;
}
struct entity_context *entity_context_new(int maxobjs, int maxchildren)
{
struct entity_context *cx;
cx = malloc(sizeof(*cx));
memset(cx, 0, sizeof(*cx));
cx->entity_list = malloc(sizeof(cx->entity_list[0]) * maxobjs);
memset(cx->entity_list, 0, sizeof(cx->entity_list[0]) * maxobjs);
cx->far_to_near_entity_depth = malloc(sizeof(cx->far_to_near_entity_depth[0]) * maxobjs);
memset(cx->far_to_near_entity_depth, 0, sizeof(cx->far_to_near_entity_depth[0]) * maxobjs);
cx->near_to_far_entity_depth = malloc(sizeof(cx->near_to_far_entity_depth[0]) * maxobjs);
memset(cx->near_to_far_entity_depth, 0, sizeof(cx->near_to_far_entity_depth[0]) * maxobjs);
snis_object_pool_setup(&cx->entity_pool, maxobjs);
cx->maxobjs = maxobjs;
cx->entity_child_list = malloc(sizeof(cx->entity_child_list[0]) * maxchildren);
memset(cx->entity_child_list, 0, sizeof(cx->entity_child_list[0]) * maxchildren);
snis_object_pool_setup(&cx->entity_child_pool, maxchildren);
cx->maxchildren = maxchildren;
set_renderer(cx, FLATSHADING_RENDERER);
set_lighting(cx, 0, 0, 0);
camera_assign_up_direction(cx, 0.0, 1.0, 0.0);
set_window_offset(cx, 0.0, 0.0);
cx->nfakestars = 0;
cx->hi_lo_poly_pixel_threshold = 100.0;
return cx;
}
void entity_context_free(struct entity_context *cx)
{
free(cx->entity_list);
free(cx->far_to_near_entity_depth);
free(cx->near_to_far_entity_depth);
free(cx);
}
/* Re-position a star randomly on the surface of sphere of given radius */
static void reposition_fake_star(struct entity_context *cx, struct vertex *fs, float radius)
{
/* I tried "on" sphere here, but I like the look of "in" better. */
float dist3dsqrd;
random_point_in_sphere(radius, &fs->x, &fs->y, &fs->z, &dist3dsqrd);
fs->x += cx->camera.x;
fs->y += cx->camera.y;
fs->z += cx->camera.z;
}
/* fill a sphere of specified radius with randomly placed stars */
void entity_init_fake_stars(struct entity_context *cx, int nstars, float radius)
{
int i;
if (cx->nfakestars > 0)
entity_free_fake_stars(cx);
cx->nfakestars = nstars;
if (nstars == 0)
return;
cx->fakestars_radius = radius;
cx->fake_stars_mesh = calloc(1, sizeof(*cx->fake_stars_mesh));
cx->fake_stars_mesh->geometry_mode = MESH_GEOMETRY_POINTS;
cx->fake_stars_mesh->nvertices = nstars;
cx->fake_stars_mesh->v = calloc(1, sizeof(*cx->fake_stars_mesh->v) * nstars);
/* no good way to calculate this as the origin is always 0,0 and the stars move
in space relative to the camera */
cx->fake_stars_mesh->radius = INT_MAX;
for (i = 0; i < nstars; i++) {
reposition_fake_star(cx, &cx->fake_stars_mesh->v[i], radius);
}
mesh_graph_dev_init(cx->fake_stars_mesh);
cx->fake_stars_mesh->material = 0;
cx->fake_stars = add_entity(cx, cx->fake_stars_mesh, 0, 0, 0, GRAY75);
}
void entity_free_fake_stars(struct entity_context *cx)
{
cx->nfakestars = 0;
if (cx->fake_stars)
remove_entity(cx, cx->fake_stars);
cx->fake_stars = 0;
mesh_free(cx->fake_stars_mesh);
cx->fake_stars_mesh = 0;
}
void set_renderer(struct entity_context *cx, int renderer)
{
cx->camera.renderer = renderer;
}
int get_renderer(struct entity_context *cx)
{
return cx->camera.renderer;
}
void set_render_style(struct entity *e, int render_style)
{
if (e)
e->render_style = render_style;
}
void set_lighting(struct entity_context *cx, double x, double y, double z)
{
cx->light.m[0] = x;
cx->light.m[1] = y;
cx->light.m[2] = z;
cx->light.m[3] = 1;
}
void set_ambient_light(struct entity_context *cx, float ambient)
{
cx->ambient = ambient;
}
struct mesh *entity_get_mesh(struct entity *e)
{
return e->m;
}
void entity_set_mesh(struct entity *e, struct mesh *m)
{
e->m = m;
}
struct mesh *entity_get_low_poly_mesh(struct entity *e)
{
return e->low_poly;
}
void entity_set_low_poly_mesh(struct entity *e, struct mesh *m)
{
e->low_poly = m;
}
int get_entity_count(struct entity_context *cx)
{
return snis_object_pool_highest_object(cx->entity_pool);
}
struct entity *get_entity(struct entity_context *cx, int n)
{
return &cx->entity_list[n];
}
void entity_get_screen_coords(struct entity *e, float *x, float *y)
{
*x = e->sx;
*y = e->sy;
}
void entity_set_user_data(struct entity *e, void *user_data)
{
e->user_data = user_data;
}
void *entity_get_user_data(struct entity *e)
{
return e->user_data;
}
void camera_set_orientation(struct entity_context *cx, union quat *q)
{
union vec3 look, up;
look.v.x = 1;
look.v.y = 0;
look.v.z = 0;
up.v.x = 0;
up.v.y = 1;
up.v.z = 0;
quat_rot_vec_self(&look, q);
quat_rot_vec_self(&up, q);
camera_look_at(cx, cx->camera.x + look.v.x * 256,
cx->camera.y + look.v.y * 256,
cx->camera.z + look.v.z * 256);
camera_assign_up_direction(cx, up.v.x, up.v.y, up.v.z);
}
union quat *entity_get_orientation(struct entity *e)
{
return &e->e_orientation;
}
void entity_get_pos(struct entity *e, float *x, float *y, float *z)
{
*x = e->x;
*y = e->y;
*z = e->z;
}
struct mat44d get_camera_v_transform(struct entity_context *cx)
{
return cx->camera.frustum.v_matrix;
}
struct mat44d get_camera_vp_transform(struct entity_context *cx)
{
return cx->camera.frustum.vp_matrix;
}
void set_window_offset(struct entity_context *cx, float x, float y)
{
cx->window_offset_x = x;
cx->window_offset_y = y;
}
int entity_onscreen(struct entity *e)
{
return (int) e->onscreen;
}
/* clipping triangles to frustum taken from
http://simonstechblog.blogspot.com/2012/04/software-rasterizer-part-2.html
converted from javascript to c */
static const float ZERO_TOLERANCE = 0.000001f;
typedef float (*clip_line_fn)(float vtx0x, float vtx0w, float vtx1x, float vtx1w );
typedef float (*get_comp_fn)(const struct mat41 *m);
typedef int (*is_outside_fn)(float x, float w);
/* return a pareameter t for line segment within range [0, 1] is intersect */
static float clip_line_pos(float vtx0x, float vtx0w, float vtx1x, float vtx1w)
{
float denominator = vtx0w - vtx1w - vtx0x + vtx1x;
if (fabs(denominator) < ZERO_TOLERANCE)
return -1; /* line parallel to the plane... */
float t = (vtx0w - vtx0x) / denominator;
if (t >= 0.0 && t <= 1.0)
return t; /* intersect */
else
return -1; /* line segment not intersect */
}
static float clip_line_neg(float vtx0x, float vtx0w, float vtx1x, float vtx1w)
{
float denominator = vtx0w - vtx1w + vtx0x - vtx1x;
if (fabs(denominator) < ZERO_TOLERANCE)
return -1; /* line parallel to the plane... */
float t = (vtx0w + vtx0x) / denominator;
if (t >= 0.0 && t <= 1.0)
return t; /* intersect */
else
return -1; /* line segment not intersect */
}
static int is_outside_pos(float x, float w)
{
return x > w;
}
static int is_outside_neg(float x, float w)
{
return x < -w;
}
static float get_x(const struct mat41 *m) {
return m->m[0];
}
static float get_y(const struct mat41 *m)
{
return m->m[1];
}
static float get_z(const struct mat41* m) {
return m->m[2];
}
static void mat41_lerp(struct mat41 *out, struct mat41 *v1, struct mat41 *v2, float t)
{
float invT = 1.0-t;
out->m[0] = t * v2->m[0] + invT * v1->m[0];
out->m[1] = t * v2->m[1] + invT * v1->m[1];
out->m[2] = t * v2->m[2] + invT * v1->m[2];
out->m[3] = t * v2->m[3] + invT * v1->m[3];
}
/* the clip line to plane with interpolated varying */
static void clipped_line_from_plane(struct mat41 *out, float t, struct mat41 *vs_out0,
struct mat41 *vs_out1)
{
if (t<0)
printf("Assert: two vertex does not intersect plane\n");
mat41_lerp(out, vs_out0, vs_out1, t);
}
static int clip_line(struct mat41* vtx0, struct mat41* vtx1)
{
clip_line_fn clipping_func[] = {clip_line_pos, clip_line_neg, clip_line_pos,
clip_line_neg, clip_line_pos, clip_line_neg};
get_comp_fn get_component_func[] = {get_x, get_x, get_y, get_y, get_z, get_z};
is_outside_fn is_outside_func[] = {is_outside_pos, is_outside_neg, is_outside_pos,
is_outside_neg, is_outside_pos, is_outside_neg};
int plane;
for (plane = 0; plane < 6; plane++) {
float component0 = get_component_func[plane](vtx0);
float component1 = get_component_func[plane](vtx1);
float pos0w = vtx0->m[3];
float pos1w = vtx1->m[3];
int is_outside0 = is_outside_func[plane](component0, pos0w);
int is_outside1 = is_outside_func[plane](component1, pos1w);
if (is_outside0 && is_outside1)
return 1;
if (is_outside0 && !is_outside1) {
float line0_t = clipping_func[plane](component0, pos0w, component1, pos1w);
clipped_line_from_plane(vtx0, line0_t, vtx0, vtx1);
}
else if (!is_outside0 && is_outside1) {
float line1_t = clipping_func[plane](component1, pos1w, component0, pos0w);
clipped_line_from_plane(vtx1, line1_t, vtx1, vtx0);
}
}
return 0;
}
float entity_get_alpha(struct entity *e)
{
return e->alpha;
}
void entity_update_alpha(struct entity *e, float alpha)
{
e->alpha = alpha;
}
void entity_update_emit_intensity(struct entity *e, float intensity)
{
e->emit_intensity = intensity;
}
float entity_get_emit_intensity(struct entity *e)
{
return e->emit_intensity;
}
float entity_get_in_shade(struct entity *e)
{
return e->in_shade;
}
void entity_set_in_shade(struct entity *e, float in_shade)
{
e->in_shade = in_shade;
}
void entity_context_set_hi_lo_poly_pixel_threshold(struct entity_context *cx, float pixel_threshold)
{
cx->hi_lo_poly_pixel_threshold = pixel_threshold;
}
| 0 | 0.928539 | 1 | 0.928539 | game-dev | MEDIA | 0.464938 | game-dev | 0.958546 | 1 | 0.958546 |
raniejade/godot-kotlin | 11,502 | godot-kotlin/src/nativeGen/kotlin/godot/InputEventMIDI.kt | // DO NOT EDIT, THIS FILE IS GENERATED FROM api.json
package godot
import gdnative.godot_method_bind
import gdnative.godot_string
import godot.core.Allocator
import godot.core.Godot
import godot.core.Variant
import godot.core.VariantArray
import kotlin.Int
import kotlin.String
import kotlin.Suppress
import kotlin.reflect.KCallable
import kotlinx.cinterop.BooleanVar
import kotlinx.cinterop.CFunction
import kotlinx.cinterop.COpaquePointer
import kotlinx.cinterop.COpaquePointerVar
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.DoubleVar
import kotlinx.cinterop.IntVar
import kotlinx.cinterop.alloc
import kotlinx.cinterop.cstr
import kotlinx.cinterop.invoke
import kotlinx.cinterop.pointed
import kotlinx.cinterop.ptr
import kotlinx.cinterop.readValue
import kotlinx.cinterop.reinterpret
import kotlinx.cinterop.value
open class InputEventMIDI(
@Suppress("UNUSED_PARAMETER")
__ignore: String?
) : InputEvent(null) {
var channel: Int
get() {
return getChannel()
}
set(value) {
setChannel(value)
}
var controllerNumber: Int
get() {
return getControllerNumber()
}
set(value) {
setControllerNumber(value)
}
var controllerValue: Int
get() {
return getControllerValue()
}
set(value) {
setControllerValue(value)
}
var instrument: Int
get() {
return getInstrument()
}
set(value) {
setInstrument(value)
}
var message: Int
get() {
return getMessage()
}
set(value) {
setMessage(value)
}
var pitch: Int
get() {
return getPitch()
}
set(value) {
setPitch(value)
}
var pressure: Int
get() {
return getPressure()
}
set(value) {
setPressure(value)
}
var velocity: Int
get() {
return getVelocity()
}
set(value) {
setVelocity(value)
}
constructor() : this(null) {
if (Godot.shouldInitHandle()) {
_handle = __new()
}
}
fun getChannel(): Int {
val self = this
return Allocator.allocationScope {
val _ret = alloc<IntVar>()
val _retPtr = _ret.ptr
__method_bind.getChannel.call(self._handle, emptyList(), _retPtr)
_ret.value
}
}
fun getControllerNumber(): Int {
val self = this
return Allocator.allocationScope {
val _ret = alloc<IntVar>()
val _retPtr = _ret.ptr
__method_bind.getControllerNumber.call(self._handle, emptyList(), _retPtr)
_ret.value
}
}
fun getControllerValue(): Int {
val self = this
return Allocator.allocationScope {
val _ret = alloc<IntVar>()
val _retPtr = _ret.ptr
__method_bind.getControllerValue.call(self._handle, emptyList(), _retPtr)
_ret.value
}
}
fun getInstrument(): Int {
val self = this
return Allocator.allocationScope {
val _ret = alloc<IntVar>()
val _retPtr = _ret.ptr
__method_bind.getInstrument.call(self._handle, emptyList(), _retPtr)
_ret.value
}
}
fun getMessage(): Int {
val self = this
return Allocator.allocationScope {
val _ret = alloc<IntVar>()
val _retPtr = _ret.ptr
__method_bind.getMessage.call(self._handle, emptyList(), _retPtr)
_ret.value
}
}
fun getPitch(): Int {
val self = this
return Allocator.allocationScope {
val _ret = alloc<IntVar>()
val _retPtr = _ret.ptr
__method_bind.getPitch.call(self._handle, emptyList(), _retPtr)
_ret.value
}
}
fun getPressure(): Int {
val self = this
return Allocator.allocationScope {
val _ret = alloc<IntVar>()
val _retPtr = _ret.ptr
__method_bind.getPressure.call(self._handle, emptyList(), _retPtr)
_ret.value
}
}
fun getVelocity(): Int {
val self = this
return Allocator.allocationScope {
val _ret = alloc<IntVar>()
val _retPtr = _ret.ptr
__method_bind.getVelocity.call(self._handle, emptyList(), _retPtr)
_ret.value
}
}
fun setChannel(channel: Int) {
val self = this
return Allocator.allocationScope {
__method_bind.setChannel.call(self._handle, listOf(channel), null)
}
}
fun setControllerNumber(controllerNumber: Int) {
val self = this
return Allocator.allocationScope {
__method_bind.setControllerNumber.call(self._handle, listOf(controllerNumber), null)
}
}
fun setControllerValue(controllerValue: Int) {
val self = this
return Allocator.allocationScope {
__method_bind.setControllerValue.call(self._handle, listOf(controllerValue), null)
}
}
fun setInstrument(instrument: Int) {
val self = this
return Allocator.allocationScope {
__method_bind.setInstrument.call(self._handle, listOf(instrument), null)
}
}
fun setMessage(message: Int) {
val self = this
return Allocator.allocationScope {
__method_bind.setMessage.call(self._handle, listOf(message), null)
}
}
fun setPitch(pitch: Int) {
val self = this
return Allocator.allocationScope {
__method_bind.setPitch.call(self._handle, listOf(pitch), null)
}
}
fun setPressure(pressure: Int) {
val self = this
return Allocator.allocationScope {
__method_bind.setPressure.call(self._handle, listOf(pressure), null)
}
}
fun setVelocity(velocity: Int) {
val self = this
return Allocator.allocationScope {
__method_bind.setVelocity.call(self._handle, listOf(velocity), null)
}
}
companion object {
internal fun __new(): COpaquePointer = Allocator.allocationScope {
val fnPtr =
checkNotNull(Godot.gdnative.godot_get_class_constructor)("InputEventMIDI".cstr.ptr)
requireNotNull(fnPtr) { "No instance found for InputEventMIDI" }
val fn = fnPtr.reinterpret<CFunction<() -> COpaquePointer>>()
fn()
}
/**
* Container for method_bind pointers for InputEventMIDI
*/
private object __method_bind {
val getChannel: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr =
checkNotNull(Godot.gdnative.godot_method_bind_get_method)("InputEventMIDI".cstr.ptr,
"get_channel".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_channel" }
}
val getControllerNumber: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr =
checkNotNull(Godot.gdnative.godot_method_bind_get_method)("InputEventMIDI".cstr.ptr,
"get_controller_number".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_controller_number" }
}
val getControllerValue: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr =
checkNotNull(Godot.gdnative.godot_method_bind_get_method)("InputEventMIDI".cstr.ptr,
"get_controller_value".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_controller_value" }
}
val getInstrument: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr =
checkNotNull(Godot.gdnative.godot_method_bind_get_method)("InputEventMIDI".cstr.ptr,
"get_instrument".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_instrument" }
}
val getMessage: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr =
checkNotNull(Godot.gdnative.godot_method_bind_get_method)("InputEventMIDI".cstr.ptr,
"get_message".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_message" }
}
val getPitch: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr =
checkNotNull(Godot.gdnative.godot_method_bind_get_method)("InputEventMIDI".cstr.ptr,
"get_pitch".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_pitch" }
}
val getPressure: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr =
checkNotNull(Godot.gdnative.godot_method_bind_get_method)("InputEventMIDI".cstr.ptr,
"get_pressure".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_pressure" }
}
val getVelocity: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr =
checkNotNull(Godot.gdnative.godot_method_bind_get_method)("InputEventMIDI".cstr.ptr,
"get_velocity".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_velocity" }
}
val setChannel: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr =
checkNotNull(Godot.gdnative.godot_method_bind_get_method)("InputEventMIDI".cstr.ptr,
"set_channel".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_channel" }
}
val setControllerNumber: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr =
checkNotNull(Godot.gdnative.godot_method_bind_get_method)("InputEventMIDI".cstr.ptr,
"set_controller_number".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_controller_number" }
}
val setControllerValue: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr =
checkNotNull(Godot.gdnative.godot_method_bind_get_method)("InputEventMIDI".cstr.ptr,
"set_controller_value".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_controller_value" }
}
val setInstrument: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr =
checkNotNull(Godot.gdnative.godot_method_bind_get_method)("InputEventMIDI".cstr.ptr,
"set_instrument".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_instrument" }
}
val setMessage: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr =
checkNotNull(Godot.gdnative.godot_method_bind_get_method)("InputEventMIDI".cstr.ptr,
"set_message".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_message" }
}
val setPitch: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr =
checkNotNull(Godot.gdnative.godot_method_bind_get_method)("InputEventMIDI".cstr.ptr,
"set_pitch".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_pitch" }
}
val setPressure: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr =
checkNotNull(Godot.gdnative.godot_method_bind_get_method)("InputEventMIDI".cstr.ptr,
"set_pressure".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_pressure" }
}
val setVelocity: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr =
checkNotNull(Godot.gdnative.godot_method_bind_get_method)("InputEventMIDI".cstr.ptr,
"set_velocity".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_velocity" }
}}
}
}
| 0 | 0.757153 | 1 | 0.757153 | game-dev | MEDIA | 0.735765 | game-dev | 0.762173 | 1 | 0.762173 |
MoeMod/CSMoE | 3,279 | mainui_cpp/controls/ScrollView.cpp | #include "ScrollView.h"
#include "Scissor.h"
namespace ui {
CMenuScrollView::CMenuScrollView() : CMenuItemsHolder (),
m_bHoldingMouse1( false )
{
}
void CMenuScrollView::VidInit()
{
colorStroke.SetDefault( uiInputFgColor );
BaseClass::VidInit();
m_iMax = 0;
m_iPos = 0;
for( int i = 0; i < m_numItems; i++ )
{
Point pt = m_pItems[i]->pos;
Size sz = m_pItems[i]->size;
m_iMax += pt.y + sz.h;
}
m_bDisableScrolling = (m_iMax < size.h);
m_iMax *= uiStatic.scaleX;
}
const char *CMenuScrollView::Key( int key, int down )
{
// act when key is pressed or repeated
if( down )
{
if( !m_bDisableScrolling )
{
int newPos = m_iPos;
switch( key )
{
case K_MWHEELUP:
case K_UPARROW:
newPos -= 20;
break;
case K_MWHEELDOWN:
case K_DOWNARROW:
newPos += 20;
break;
case K_PGUP:
newPos -= 100;
break;
case K_PGDN:
newPos += 100;
break;
case K_MOUSE1:
// m_bHoldingMouse1 = down != 0;
// m_HoldingPoint = Point( uiStatic.cursorX, uiStatic.cursorY );
// drag & drop
// scrollbar
break;
}
// TODO: overscrolling
newPos = bound( 0, newPos, m_iMax - m_scSize.h );
// recalc
if( newPos != m_iPos )
{
m_iPos = newPos;
for( int i = 0; i < m_numItems; i++ )
{
CMenuBaseItem *pItem = m_pItems[i];
pItem->VidInit();
}
CMenuItemsHolder::MouseMove( uiStatic.cursorX, uiStatic.cursorY );
}
}
}
return CMenuItemsHolder::Key( key, down );
}
Point CMenuScrollView::GetPositionOffset() const
{
return Point( 0, -m_iPos ) + BaseClass::GetPositionOffset();
}
bool CMenuScrollView::MouseMove( int x, int y )
{
return CMenuItemsHolder::MouseMove( x, y );
}
bool CMenuScrollView::IsRectVisible(Point pt, Size sz)
{
bool x = isrange( m_scPos.x, pt.x, m_scPos.x + m_scSize.w ) ||
isrange( pt.x, m_scPos.x, pt.x + sz.w );
bool y = isrange( m_scPos.y, pt.y, m_scPos.y + m_scSize.h ) ||
isrange( pt.y, m_scPos.y, pt.y + sz.h );
return x && y;
}
void CMenuScrollView::Draw()
{
if( EngFuncs::KEY_IsDown( K_MOUSE1 ) )
{
if( !m_bHoldingMouse1 )
{
m_bHoldingMouse1 = true;
m_HoldingPoint = Point( uiStatic.cursorX, uiStatic.cursorY );
}
}
else
{
if( m_bHoldingMouse1 ) m_bHoldingMouse1 = false;
}
if( m_bHoldingMouse1 && !m_bDisableScrolling )
{
int newPos = m_iPos;
newPos -= ( uiStatic.cursorY - m_HoldingPoint.y ) / 2;
// TODO: overscrolling
newPos = bound( 0, newPos, m_iMax - m_scSize.h );
// recalc
if( newPos != m_iPos )
{
m_iPos = newPos;
for( int i = 0; i < m_numItems; i++ )
{
CMenuBaseItem *pItem = m_pItems[i];
pItem->VidInit();
}
}
m_HoldingPoint = Point( uiStatic.cursorX, uiStatic.cursorY );
}
if( bDrawStroke )
{
UI_DrawRectangleExt( m_scPos, m_scSize, colorStroke, iStrokeWidth );
}
int drawn = 0, skipped = 0;
for( int i = 0; i < m_numItems; i++ )
{
if( !IsRectVisible( m_pItems[i]->GetRenderPosition(), m_pItems[i]->GetRenderSize() ) )
{
m_pItems[i]->iFlags |= QMF_HIDDENBYPARENT;
skipped++;
}
else
{
m_pItems[i]->iFlags &= ~QMF_HIDDENBYPARENT;
drawn++;
}
}
Con_NPrintf( 0, "Drawn: %i Skipped: %i", drawn, skipped );
Scissor::PushScissor( m_scPos, m_scSize );
CMenuItemsHolder::Draw();
Scissor::PopScissor();
}
} | 0 | 0.969409 | 1 | 0.969409 | game-dev | MEDIA | 0.781126 | game-dev | 0.998948 | 1 | 0.998948 |
Gamemode4Dev/GM4_Datapacks | 1,146 | gm4_zauber_cauldrons/data/gm4_zauber_cauldrons/function/player/crystal/swap/replace_offhand.mcfunction | # converts a zauber crystal in the offhand into a firework star.
# @s = player who has moved a zauber crystal into their offhand
# at @s
# run from advancement gm4_zauber_cauldrons:equipment/crystal/moved_into_offhand
# the following code is a modified implementation stolen from BPR's Hotswap Hotbars (PR #850)
advancement revoke @s only gm4_zauber_cauldrons:equipment/crystal/moved_into_offhand
# get item data
data modify storage gm4_zauber_cauldrons:temp/item/crystal Item set from entity @s Inventory[{Slot:-106b}]
# TODO 1.20.5: disabled command, check why removing this was necessary
# data remove storage gm4_zauber_cauldrons:temp/item/crystal Item.tag.HideFlags
# set color
for effect_data in ctx.meta['crystal_effects']:
execute unless score $recipe_success gm4_zc_data matches 1.. if data storage gm4_zauber_cauldrons:temp/item/crystal {Item:{components:{"minecraft:custom_data":{gm4_zauber_cauldrons:{type:effect_data['effect']}}}}} run loot replace entity @s weapon.offhand loot f"gm4_zauber_cauldrons:technical/replace_offhand_crystal/{effect_data['effect']}"
data remove storage gm4_zauber_cauldrons:temp/item/crystal Item
| 0 | 0.800991 | 1 | 0.800991 | game-dev | MEDIA | 0.977007 | game-dev | 0.878239 | 1 | 0.878239 |
Insality/druid | 12,433 | api/druid_instance_api.md | # druid.instance API
> at /druid/system/druid_instance.lua
The Druid Factory used to create components
## Functions
- [create_druid_instance](#create_druid_instance)
- [new](#new)
- [final](#final)
- [remove](#remove)
- [update](#update)
- [on_input](#on_input)
- [on_message](#on_message)
- [on_window_event](#on_window_event)
- [set_whitelist](#set_whitelist)
- [set_blacklist](#set_blacklist)
- [new_widget](#new_widget)
- [new_button](#new_button)
- [new_blocker](#new_blocker)
- [new_back_handler](#new_back_handler)
- [new_hover](#new_hover)
- [new_text](#new_text)
- [new_grid](#new_grid)
- [new_scroll](#new_scroll)
- [new_drag](#new_drag)
- [new_swipe](#new_swipe)
- [new_lang_text](#new_lang_text)
- [new_slider](#new_slider)
- [new_input](#new_input)
- [new_data_list](#new_data_list)
- [new_timer](#new_timer)
- [new_progress](#new_progress)
- [new_layout](#new_layout)
- [new_container](#new_container)
- [new_hotkey](#new_hotkey)
- [new_rich_text](#new_rich_text)
- [new_rich_input](#new_rich_input)
### create_druid_instance
---
```lua
instance.create_druid_instance(context, [style])
```
Druid class constructor which used to create a Druid's components
- **Parameters:**
- `context` *(table)*: Druid context. Usually it is self of gui script
- `[style]` *(table?)*: Druid style table
- **Returns:**
- `instance` *(druid.instance)*: The new Druid instance
### new
---
```lua
instance:new(component, ...)
```
Create new Druid component instance
- **Parameters:**
- `component` *(<T:druid.component>)*: The component class to create
- `...` *(...)*: vararg
- **Returns:**
- `instance` *(<T:druid.component>)*: The new ready to use component
### final
---
```lua
instance:final()
```
Call this in gui_script final function.
### remove
---
```lua
instance:remove(component)
```
Remove created component from Druid instance.
Component `on_remove` function will be invoked, if exist.
- **Parameters:**
- `component` *(<T:druid.component>)*: Component instance
- **Returns:**
- `is_removed` *(boolean)*: True if component was removed
### update
---
```lua
instance:update(dt)
```
Call this in gui_script update function.
- **Parameters:**
- `dt` *(number)*: Delta time
### on_input
---
```lua
instance:on_input(action_id, action)
```
Call this in gui_script on_input function.
- **Parameters:**
- `action_id` *(hash)*: Action_id from on_input
- `action` *(table)*: Action from on_input
- **Returns:**
- `is_input_consumed` *(boolean)*: The boolean value is input was consumed
### on_message
---
```lua
instance:on_message(message_id, message, sender)
```
Call this in gui_script on_message function.
- **Parameters:**
- `message_id` *(hash)*: Message_id from on_message
- `message` *(table)*: Message from on_message
- `sender` *(url)*: Sender from on_message
### on_window_event
---
```lua
instance:on_window_event(window_event)
```
Called when the window event occurs
- **Parameters:**
- `window_event` *(number)*: The window event
### set_whitelist
---
```lua
instance:set_whitelist(whitelist_components)
```
Set whitelist components for input processing.
If whitelist is not empty and component not contains in this list,
component will be not processed on input step
- **Parameters:**
- `whitelist_components` *(table|druid.component[])*: The array of component to whitelist
- **Returns:**
- `self` *(druid.instance)*: The Druid instance
### set_blacklist
---
```lua
instance:set_blacklist(blacklist_components)
```
Set blacklist components for input processing.
If blacklist is not empty and component contains in this list,
component will be not processed on input step DruidInstance
- **Parameters:**
- `blacklist_components` *(table|druid.component[])*: The array of component to blacklist
- **Returns:**
- `self` *(druid.instance)*: The Druid instance
### new_widget
---
```lua
instance:new_widget(widget, [template], [nodes], ...)
```
Create new Druid widget instance
- **Parameters:**
- `widget` *(<T:druid.component>)*: The widget class to create
- `[template]` *(string|nil)*: The template name used by widget
- `[nodes]` *(string|node|table<hash, node>|nil)*: The nodes table from gui.clone_tree or prefab node to use for clone or node id to clone
- `...` *(...)*: vararg
- **Returns:**
- `widget` *(<T:druid.component>)*: The new ready to use widget
### new_button
---
```lua
instance:new_button(node, [callback], [params], [anim_node])
```
Create Button component
- **Parameters:**
- `node` *(string|node)*: The node_id or gui.get_node(node_id)
- `[callback]` *(function|event|nil)*: Button callback
- `[params]` *(any)*: Button callback params
- `[anim_node]` *(string|node|nil)*: Button anim node (node, if not provided)
- **Returns:**
- `button` *(druid.button)*: The new button component
### new_blocker
---
```lua
instance:new_blocker(node)
```
Create Blocker component
- **Parameters:**
- `node` *(string|node)*: The node_id or gui.get_node(node_id)
- **Returns:**
- `blocker` *(druid.blocker)*: The new blocker component
### new_back_handler
---
```lua
instance:new_back_handler([callback], [params])
```
Create BackHandler component
- **Parameters:**
- `[callback]` *(function|event|nil)*: The callback(self, custom_args) to call on back event
- `[params]` *(any)*: Callback argument
- **Returns:**
- `back_handler` *(druid.back_handler)*: The new back handler component
### new_hover
---
```lua
instance:new_hover(node, [on_hover_callback], [on_mouse_hover_callback])
```
Create Hover component
- **Parameters:**
- `node` *(string|node)*: The node_id or gui.get_node(node_id)
- `[on_hover_callback]` *(function|nil)*: Hover callback
- `[on_mouse_hover_callback]` *(function|nil)*: Mouse hover callback
- **Returns:**
- `hover` *(druid.hover)*: The new hover component
### new_text
---
```lua
instance:new_text(node, [value], [adjust_type])
```
Create Text component
- **Parameters:**
- `node` *(string|druid.text|node)*: The node_id or gui.get_node(node_id)
- `[value]` *(string|nil)*: Initial text. Default value is node text from GUI scene.
- `[adjust_type]` *(string|nil)*: Adjust type for text. By default is DOWNSCALE. Look const.TEXT_ADJUST for reference
- **Returns:**
- `text` *(druid.text)*: The new text component
### new_grid
---
```lua
instance:new_grid(parent_node, item, [in_row])
```
Create Grid component
- **Parameters:**
- `parent_node` *(string|node)*: The node_id or gui.get_node(node_id). Parent of all Grid items.
- `item` *(string|node)*: Item prefab. Required to get grid's item size. Can be adjusted separately.
- `[in_row]` *(number|nil)*: How many nodes in row can be placed
- **Returns:**
- `grid` *(druid.grid)*: The new grid component
### new_scroll
---
```lua
instance:new_scroll(view_node, content_node)
```
Create Scroll component
- **Parameters:**
- `view_node` *(string|node)*: The node_id or gui.get_node(node_id). Will used as user input node.
- `content_node` *(string|node)*: The node_id or gui.get_node(node_id). Will used as scrollable node inside view_node.
- **Returns:**
- `scroll` *(druid.scroll)*: The new scroll component
### new_drag
---
```lua
instance:new_drag(node, [on_drag_callback])
```
Create Drag component
- **Parameters:**
- `node` *(string|node)*: The node_id or gui.get_node(node_id). Will used as user input node.
- `[on_drag_callback]` *(function|nil)*: Callback for on_drag_event(self, dx, dy)
- **Returns:**
- `drag` *(druid.drag)*: The new drag component
### new_swipe
---
```lua
instance:new_swipe(node, [on_swipe_callback])
```
Create Swipe component
- **Parameters:**
- `node` *(string|node)*: The node_id or gui.get_node(node_id). Will used as user input node.
- `[on_swipe_callback]` *(function|nil)*: Swipe callback for on_swipe_end event
- **Returns:**
- `swipe` *(druid.swipe)*: The new swipe component
### new_lang_text
---
```lua
instance:new_lang_text(node, [locale_id], [adjust_type])
```
Create LangText component
- **Parameters:**
- `node` *(string|node)*: The_node id or gui.get_node(node_id)
- `[locale_id]` *(string|nil)*: Default locale id or text from node as default
- `[adjust_type]` *(string|nil)*: Adjust type for text node. Default: "downscale"
- **Returns:**
- `lang_text` *(druid.lang_text)*: The new lang text component
### new_slider
---
```lua
instance:new_slider(pin_node, end_pos, [callback])
```
Create Slider component
- **Parameters:**
- `pin_node` *(string|node)*: The_node id or gui.get_node(node_id).
- `end_pos` *(vector3)*: The end position of slider
- `[callback]` *(function|nil)*: On slider change callback
- **Returns:**
- `slider` *(druid.slider)*: The new slider component
### new_input
---
```lua
instance:new_input(click_node, text_node, [keyboard_type])
```
Create Input component
- **Parameters:**
- `click_node` *(string|node)*: Button node to enabled input component
- `text_node` *(string|druid.text|node)*: Text node what will be changed on user input
- `[keyboard_type]` *(number|nil)*: Gui keyboard type for input field
- **Returns:**
- `input` *(druid.input)*: The new input component
### new_data_list
---
```lua
instance:new_data_list(druid_scroll, druid_grid, create_function)
```
Create DataList component
- **Parameters:**
- `druid_scroll` *(druid.scroll)*: The Scroll instance for Data List component
- `druid_grid` *(druid.grid)*: The Grid instance for Data List component
- `create_function` *(function)*: The create function callback(self, data, index, data_list). Function should return (node, [component])
- **Returns:**
- `data_list` *(druid.data_list)*: The new data list component
### new_timer
---
```lua
instance:new_timer(node, [seconds_from], [seconds_to], [callback])
```
Create Timer component
- **Parameters:**
- `node` *(string|node)*: Gui text node
- `[seconds_from]` *(number|nil)*: Start timer value in seconds
- `[seconds_to]` *(number|nil)*: End timer value in seconds
- `[callback]` *(function|nil)*: Function on timer end
- **Returns:**
- `timer` *(druid.timer)*: The new timer component
### new_progress
---
```lua
instance:new_progress(node, key, [init_value])
```
Create Progress component
- **Parameters:**
- `node` *(string|node)*: Progress bar fill node or node name
- `key` *(string)*: Progress bar direction: "x" or "y"
- `[init_value]` *(number|nil)*: Initial value of progress bar. Default: 1
- **Returns:**
- `progress` *(druid.progress)*: The new progress component
### new_layout
---
```lua
instance:new_layout(node, [mode])
```
Create Layout component
- **Parameters:**
- `node` *(string|node)*: The_node id or gui.get_node(node_id).
- `[mode]` *(string|nil)*: vertical|horizontal|horizontal_wrap. Default: horizontal
- **Returns:**
- `layout` *(druid.layout)*: The new layout component
### new_container
---
```lua
instance:new_container(node, [mode], [callback])
```
Create Container component
- **Parameters:**
- `node` *(string|node)*: The_node id or gui.get_node(node_id).
- `[mode]` *(string|nil)*: Layout mode
- `[callback]` *(fun(self: druid.container, size: vector3)|nil)*: Callback on size changed
- **Returns:**
- `container` *(druid.container)*: The new container component
### new_hotkey
---
```lua
instance:new_hotkey(keys_array, [callback], [callback_argument])
```
Create Hotkey component
- **Parameters:**
- `keys_array` *(string|string[])*: Keys for trigger action. Should contains one action key and any amount of modificator keys
- `[callback]` *(function|event|nil)*: The callback function
- `[callback_argument]` *(any)*: The argument to pass into the callback function
- **Returns:**
- `hotkey` *(druid.hotkey)*: The new hotkey component
### new_rich_text
---
```lua
instance:new_rich_text(text_node, [value])
```
Create RichText component.
- **Parameters:**
- `text_node` *(string|node)*: The text node to make Rich Text
- `[value]` *(string|nil)*: The initial text value. Default will be gui.get_text(text_node)
- **Returns:**
- `rich_text` *(druid.rich_text)*: The new rich text component
### new_rich_input
---
```lua
instance:new_rich_input(template, [nodes])
```
Create RichInput component.
As a template please check rich_input.gui layout.
- **Parameters:**
- `template` *(string)*: The template string name
- `[nodes]` *(table|nil)*: Nodes table from gui.clone_tree
- **Returns:**
- `rich_input` *(druid.rich_input)*: The new rich input component
| 0 | 0.978652 | 1 | 0.978652 | game-dev | MEDIA | 0.752632 | game-dev | 0.87017 | 1 | 0.87017 |
dviglo/dviglo | 1,825 | source/third-party/bullet/bullet/BulletDynamics/Vehicle/btWheelInfo.cpp | /*
* Copyright (c) 2005 Erwin Coumans http://continuousphysics.com/Bullet/
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies.
* Erwin Coumans makes no representations about the suitability
* of this software for any purpose.
* It is provided "as is" without express or implied warranty.
*/
#include "btWheelInfo.h"
#include "BulletDynamics/Dynamics/btRigidBody.h" // for pointvelocity
btScalar btWheelInfo::getSuspensionRestLength() const
{
return m_suspensionRestLength1;
}
void btWheelInfo::updateWheel(const btRigidBody& chassis, RaycastInfo& raycastInfo)
{
(void)raycastInfo;
if (m_raycastInfo.m_isInContact)
{
btScalar project = m_raycastInfo.m_contactNormalWS.dot(m_raycastInfo.m_wheelDirectionWS);
btVector3 chassis_velocity_at_contactPoint;
btVector3 relpos = m_raycastInfo.m_contactPointWS - chassis.getCenterOfMassPosition();
chassis_velocity_at_contactPoint = chassis.getVelocityInLocalPoint(relpos);
btScalar projVel = m_raycastInfo.m_contactNormalWS.dot(chassis_velocity_at_contactPoint);
if (project >= btScalar(-0.1))
{
m_suspensionRelativeVelocity = btScalar(0.0);
m_clippedInvContactDotSuspension = btScalar(1.0) / btScalar(0.1);
}
else
{
btScalar inv = btScalar(-1.) / project;
m_suspensionRelativeVelocity = projVel * inv;
m_clippedInvContactDotSuspension = inv;
}
}
else // Not in contact : position wheel in a nice (rest length) position
{
m_raycastInfo.m_suspensionLength = this->getSuspensionRestLength();
m_suspensionRelativeVelocity = btScalar(0.0);
m_raycastInfo.m_contactNormalWS = -m_raycastInfo.m_wheelDirectionWS;
m_clippedInvContactDotSuspension = btScalar(1.0);
}
}
| 0 | 0.696989 | 1 | 0.696989 | game-dev | MEDIA | 0.922119 | game-dev | 0.920595 | 1 | 0.920595 |
ryzom/ryzomcore | 12,708 | ryzom/server/src/entities_game_service/shop_type/dynamic_items.cpp | // Ryzom - MMORPG Framework <http://dev.ryzom.com/projects/ryzom/>
// Copyright (C) 2010 Winch Gate Property Limited
//
// This source file has been modified by the following contributors:
// Copyright (C) 2019 Jan BOON (Kaetemi) <jan.boon@kaetemi.be>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU 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/>.
#include "stdpch.h"
#include "nel/misc/command.h"
#include "nel/misc/hierarchical_timer.h"
#include "nel/net/service.h"
#include "game_share/item_family.h"
#include "game_item_manager/game_item.h"
#include "egs_sheets/egs_sheets.h"
#include "../egs_variables.h"
#include "shop_type/shop_type_manager.h"
#include "dynamic_items.h"
#include "offline_character_command.h"
#include "player_manager/player_manager.h"
#include "player_manager/player.h"
using namespace std;
using namespace NLNET;
using namespace NLMISC;
#define PERSISTENT_TOKEN_FAMILY RyzomTokenFamily
NL_INSTANCE_COUNTER_IMPL(CDynamicItems);
CVariable<uint32> TotalNbItemsForSale("egs","TotalNbItemsForSale","Total number of items for sale (read-only)", 0, 0, false);
extern CVariable<bool> EGSLight;
//-----------------------------------------------------------------------------
// Persistent data for CItemsForSale
//-----------------------------------------------------------------------------
#define PERSISTENT_CLASS CDynamicItems
#define PERSISTENT_STORE_ARGS uint index
#define PERSISTENT_APPLY_ARGS uint index
#define PERSISTENT_DATA\
LSTRUCT_VECT(_DynamicItems,\
VECT_LOGIC(_DynamicItems[index]), \
((CItemForSale*)&*(_DynamicItems[index][ i ]))->store(pdr), \
{\
CItemForSale *item = new CItemForSale; \
item->apply(pdr); \
/* Determine the correct slot */ \
uint32 slot = getSubVectorIndex(item->getOwner()); \
_DynamicItems[slot].push_back(item);\
TotalNbItemsForSale = ++_TotalNbItemsForSale;\
}\
)\
//#pragma message( PERSISTENT_GENERATION_MESSAGE )
#include "game_share/persistent_data_template.h"
#undef PERSISTENT_DATA
#undef PERSISTENT_APPLY_ARGS
#undef PERSISTENT_STORE_ARGS
#undef PERSISTENT_CLASS
// CDynamicItems implementation
CDynamicItems * CDynamicItems::_Instance = 0;
//-----------------------------------------------------------------------------
CDynamicItems::CDynamicItems()
{
_NextVectorToCheck = 0;
_NextItemToCheck = 0;
_NextVectorToSave = 0;
_TotalNbItemsForSale = 0;
_InitOk = false;
}
//-----------------------------------------------------------------------------
CDynamicItems * CDynamicItems::getInstance()
{
if( _Instance == 0 )
{
_Instance = new CDynamicItems();
nlassert( _Instance != 0 );
}
return _Instance;
}
//-----------------------------------------------------------------------------
uint32 CDynamicItems::getSubVectorIndex(const NLMISC::CEntityId& characterId)
{
return PlayerManager.getPlayerId(characterId)&SUB_VECTOR_MASK;
}
//-----------------------------------------------------------------------------
uint32 CDynamicItems::getSubVectorIndex(const TItemTradePtr& item)
{
return PlayerManager.getPlayerId(item->getOwner())&SUB_VECTOR_MASK;
}
//-----------------------------------------------------------------------------
CDynamicItems::TItemTradeVector &CDynamicItems::getSubVector(const TItemTradePtr& item)
{
return _DynamicItems[getSubVectorIndex(item)];
}
//-----------------------------------------------------------------------------
bool CDynamicItems::addDynamicItemForSell( TItemTradePtr& item )
{
H_AUTO(CDynamicItems_addDynamicItemForSell);
//add item in right shop unit
if( CShopTypeManager::addItemInShopUnitDynamic( item ) )
{
// select the sub vector according to owner id
getSubVector(item).push_back( item );
TotalNbItemsForSale = ++_TotalNbItemsForSale;
return true;
}
return false;
}
//-----------------------------------------------------------------------------
void CDynamicItems::removeDynamicItemForSell( TItemTradePtr& item )
{
H_AUTO(CDynamicItems_removeDynamicItemForSell);
TItemTradeVector &subVec = getSubVector(item);
for (uint i=0; i<subVec.size(); ++i)
{
if( subVec[i] == item )
{
//remove item from right shop unit
if( CShopTypeManager::removeItemFromShopUnitDynamic( item ) )
{
subVec[ i ] = subVec.back();
subVec.pop_back();
TotalNbItemsForSale = --_TotalNbItemsForSale;
}
break;
}
}
}
//-----------------------------------------------------------------------------
void CDynamicItems::getSavePath(std::string &path)
{
path = toString("sale_store/");
}
//-----------------------------------------------------------------------------
void CDynamicItems::makeFileName(uint subIndex, std::string &fileName)
{
string path;
getSavePath(path);
fileName = path+toString("sale_store_%04u_pdr", subIndex);
if (XMLSave)
fileName += ".xml";
else
fileName += ".bin";
}
struct CItemsFileCb : public IBackupFileReceiveCallback
{
void callback(const CFileDescription& fileDescription, NLMISC::IStream& dataStream)
{
CDynamicItems::getInstance()->fileAvailable(fileDescription, dataStream);
}
};
void CDynamicItems::fileAvailable(const CFileDescription& fileDescription, NLMISC::IStream& dataStream)
{
static CPersistentDataRecord pdr;
pdr.clear();
pdr.fromBuffer(dataStream);
apply(pdr, 0);
}
//-----------------------------------------------------------------------------
void CDynamicItems::init()
{
nlinfo("Loading all sale store items...");
TTime start = NLMISC::CTime::getLocalTime();
// Check save directory
// string path;
// getSavePath(path);
// path = Bsi.getLocalPath() + path;
// if (!CFile::isExists(path))
// {
// // create the save directory
// CFile::createDirectoryTree(path);
// }
_NextVectorToCheck = 0;
_NextItemToCheck = 0;
_NextVectorToSave = 0;
_LastSaveTick = CTickEventHandler::getGameCycle();
if (EGSLight)
return;
CItemsFileCb *cb = new CItemsFileCb;
// build the file list
vector<string> fileNames;
for (uint i=0; i<NUM_SUB_VECTORS; ++i)
{
string fileName;
makeFileName(i, fileName);
// _CurrentLoadIndex = i;
fileNames.push_back(fileName);
}
/// load the files
Bsi.syncLoadFiles(fileNames, cb);
// post load treatment
for (uint i=0; i<NUM_SUB_VECTORS; ++i)
{
TItemTradeVector &subVec = _DynamicItems[i];
for( uint32 j = 0; j < subVec.size(); ++j )
{
//add item in right shop unit
CShopTypeManager::addItemInShopUnitDynamic( subVec[ j ] );
}
}
// Bsi.syncLoadFile(fileName, cb);
// fileName = Bsi.getLocalPath() + fileName;
//
// if (CFile::isExists(fileName))
// {
// static CPersistentDataRecord pdr;
// pdr.clear();
//
// pdr.readFromFile(fileName);
// apply(pdr, i);
//
// for( uint32 j = 0; j < subVec.size(); ++j )
// {
// //add item in right shop unit
// CShopTypeManager::addItemInShopUnitDynamic( subVec[ j ] );
// }
// }
// }
// ///////////////////////////////////////////////////////////
// /// Conversion/compatibility code
// /// This code initially write because the first storage mode
// /// concentrate item in only 5/16th of the 1024 storage file.
// ///////////////////////////////////////////////////////////
// string versionFile = path+"sale_store_version.bin";
// check version file for conversion
// if (!CFile::isExists(versionFile))
// {
// nlinfo("Converting sale store item from initial format to format 1");
// // no version file, this is the initial storage version
// vector<TItemTradePtr> allItems;
// for (uint i=0; i<NUM_SUB_VECTORS; ++i)
// {
// TItemTradeVector &tv = _DynamicItems[i];
//
// for (uint j=0; j<tv.size(); ++j)
// {
// allItems.push_back(tv[j]);
// }
// // cleanup vector
// tv.clear();
// }
//
// TotalNbItemsForSale = 0;
// _TotalNbItemsForSale = 0;
//
// // rebuild container
// for (uint i=0; i<allItems.size(); ++i)
// {
// // inset the item
// addDynamicItemForSell(allItems[i]);
// }
//
// // save the new container
// saveAll();
//
// // write the version file
//// COFile version(versionFile);
//// version.serialVersion(SALE_STORE_VERSION);
// }
// else
// {
// // version file exist, check correctness
// CIFile version(versionFile);
// uint v;
// v = version.serialVersion(SALE_STORE_VERSION);
//
// nlassert(v == SALE_STORE_VERSION);
// }
TTime end = NLMISC::CTime::getLocalTime();
nlinfo("All items loaded in %u ms", uint32(end-start) );
_InitOk = true;
}
//-----------------------------------------------------------------------------
void CDynamicItems::saveAll()
{
if( _InitOk )
{
nlinfo("Saving all sale store items...");
TTime start = NLMISC::CTime::getLocalTime();
for (uint i=0; i<NUM_SUB_VECTORS; ++i)
{
save(i);
}
TTime end = NLMISC::CTime::getLocalTime();
nlinfo("Save all items in %u ms", uint32(end-start) );
}
else
{
nlinfo("Sale store not saved because Dynamic item sale store not loaded" );
}
}
//-----------------------------------------------------------------------------
void CDynamicItems::save(uint subIndex)
{
H_AUTO(CDynamicItems_save);
static CPersistentDataRecordRyzomStore pdr;
pdr.clear();
store(pdr, subIndex);
string fileName;
makeFileName(subIndex, fileName);
CBackupMsgSaveFile msg( fileName, CBackupMsgSaveFile::SaveFile, Bsi );
if (XMLSave)
{
string s;
pdr.toString(s);
msg.DataMsg.serialBuffer((uint8*)&s[0], (uint)s.size());
}
else
{
uint size = pdr.totalDataSize();
vector<char> buffer(size);
pdr.toBuffer(&buffer[0], size);
msg.DataMsg.serialBuffer((uint8*)&buffer[0], size);
}
Bsi.sendFile( msg );
}
//-----------------------------------------------------------------------------
void CDynamicItems::tickUpdate()
{
H_AUTO(CDynamicItems_tickUpdate);
// check if item are reach maximum time in sale store
TItemTradeVector &subVec = _DynamicItems[_NextVectorToCheck];
enum TTradeItemStatus { ok = 0, time_expired = 1, not_available = 2 };
if( _NextItemToCheck < subVec.size() )
{
TTradeItemStatus status = ok;
if( CTickEventHandler::getGameCycle() - subVec[ _NextItemToCheck]->getStartSaleCycle() + subVec[ _NextItemToCheck]->getItemPtr()->getTotalSaleCycle() > MaxGameCycleSaleStore )
{
status = time_expired;
}
else if( subVec[ _NextItemToCheck]->isAvailable( 1 ) == false )
{
status = not_available;
}
if( status != ok )
{
// store quantity before remove item, else it's lost
uint32 quantity = subVec[ _NextItemToCheck]->getQuantity();
// must be removed before send offline command, because CMaximumShopStoreTimeReached class a method in CCharacter that checking quantity left
while ( ! CShopTypeManager::removeItemFromShopUnitDynamic( subVec[ _NextItemToCheck] ) );
// send offline command to character for inform it his item are reached maximum sell store time
if( status == time_expired )
{
string command;
CMaximumShopStoreTimeReached::makeStringCommande( command, subVec[ _NextItemToCheck]->getOwner(), subVec[ _NextItemToCheck]->getSheetId(), quantity, subVec[ _NextItemToCheck]->getIdentifier() );
COfflineCharacterCommand::getInstance()->addOfflineCommand( command );
}
TLogNoContext_Item noLog;
subVec[_NextItemToCheck] = subVec.back();
subVec.pop_back();
TotalNbItemsForSale = --_TotalNbItemsForSale;
}
else
{
// advance to next item in current vector
++_NextItemToCheck;
}
}
else
{
// advance to next vector
_NextVectorToCheck++;
_NextVectorToCheck &= SUB_VECTOR_MASK;
_NextItemToCheck = 0;
}
// +5 is used to desync guild and store save
if( ( (CTickEventHandler::getGameCycle()+5) - _LastSaveTick ) > StoreSavePeriod )
{
_LastSaveTick = CTickEventHandler::getGameCycle();
save(_NextVectorToSave++);
_NextVectorToSave &= SUB_VECTOR_MASK;
}
}
//-----------------------------------------------------------------------------
void CDynamicItems::getItemsOfCharacter( const NLMISC::CEntityId& charId, std::vector< TItemTradePtr >& itemsForSaleOfCharacter )
{
TItemTradeVector &subVec = _DynamicItems[getSubVectorIndex(charId)];
for( uint i = 0; i < subVec.size(); ++i )
{
if( subVec[ i ]->getOwner() == charId )
{
itemsForSaleOfCharacter.push_back( subVec[ i ] );
}
}
}
| 0 | 0.968658 | 1 | 0.968658 | game-dev | MEDIA | 0.810797 | game-dev | 0.988456 | 1 | 0.988456 |
Ravaelles/Atlantis | 1,994 | src/atlantis/util/PrintPositionsToFile.java | package atlantis.util;
import atlantis.game.A;
import atlantis.map.base.ABaseLocation;
import atlantis.map.position.HasPosition;
import java.util.List;
public class PrintPositionsToFile {
public static void printToFile(String file, List<? extends HasPosition> positions, HasPosition highlightThisOne) {
A.saveToFile(file, string(positions, highlightThisOne), true);
}
private static String string(List<? extends HasPosition> positions, HasPosition highlightThisOne) {
StringBuilder builder = new StringBuilder();
int txMax = positions.stream().mapToInt(HasPosition::tx).max().orElse(0);
int tyMax = positions.stream().mapToInt(HasPosition::ty).max().orElse(0);
for (int ty = 1; ty <= tyMax; ty++) {
for (int tx = 1; tx <= txMax; tx++) {
HasPosition position = getPositionHereIfPresent((List<HasPosition>) positions, tx, ty);
builder.append(
position != null ? positionToString(position, highlightThisOne) : " "
);
}
builder.append("\n");
}
return builder.toString();
}
private static String positionToString(HasPosition position, HasPosition highlightThisOne) {
String extra = "";
if (position instanceof ABaseLocation) {
ABaseLocation baseLocation = (ABaseLocation) position;
extra += baseLocation.isStartLocation() ? "(S)" : "";
}
if (position.equals(highlightThisOne)) {
extra += "<<<";
}
// return "[" + position.tx() + "," + position.ty() + "]";
return position.tx() + "," + position.ty() + extra;
}
private static HasPosition getPositionHereIfPresent(List<HasPosition> positions, int tx, int ty) {
for (HasPosition position : positions) {
if (position.tx() == tx && position.ty() == ty) {
return position;
}
}
return null;
}
}
| 0 | 0.75538 | 1 | 0.75538 | game-dev | MEDIA | 0.667799 | game-dev | 0.930675 | 1 | 0.930675 |
jsdf/goose64 | 1,185 | src/gameutils.c | #include "gameutils.h"
#include <math.h>
#include "game.h"
#include "vec2d.h"
#include "vec3d.h"
float GameUtils_lerpDegrees(float start, float end, float amount) {
float shortestAngle;
shortestAngle = fmodf((fmodf((end - start), 360) + 540), 360) - 180;
return start + fmodf((shortestAngle * amount), 360);
}
float GameUtils_fclamp(float x, float lower, float upper) {
return x > upper ? upper : x < lower ? lower : x;
}
float GameUtils_rotateTowardsClamped(float from,
float to,
float maxSpeed // must be positive
) {
float shortestAngle;
shortestAngle = fmodf((fmodf((to - from), 360.0F) + 540.0F), 360.0F) - 180.0F;
return from +
fmodf(GameUtils_fclamp(shortestAngle, -maxSpeed, maxSpeed), 360.0F);
}
void GameUtils_directionFromTopDownAngle(float angle, Vec3d* result) {
Vec2d direction2d;
Vec2d_fromAngle(&direction2d, angle);
result->x = direction2d.x;
result->y = 0;
result->z = -direction2d.y;
}
int GameUtils_inWater(GameObject* obj) {
Vec3d center;
Game_getObjCenter(obj, ¢er);
if (center.y < WATER_HEIGHT) {
return TRUE;
}
return FALSE;
}
| 0 | 0.625264 | 1 | 0.625264 | game-dev | MEDIA | 0.9407 | game-dev | 0.880332 | 1 | 0.880332 |
magefree/mage | 1,358 | Mage.Sets/src/mage/cards/w/WindDancer.java |
package mage.cards.w;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.SimpleActivatedAbility;
import mage.abilities.costs.common.TapSourceCost;
import mage.abilities.effects.common.continuous.GainAbilityTargetEffect;
import mage.abilities.keyword.FlyingAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.Duration;
import mage.constants.Zone;
import mage.target.common.TargetCreaturePermanent;
/**
*
* @author Loki
*/
public final class WindDancer extends CardImpl {
public WindDancer(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{1}{U}");
this.subtype.add(SubType.FAERIE);
this.power = new MageInt(1);
this.toughness = new MageInt(1);
this.addAbility(FlyingAbility.getInstance());
Ability ability = new SimpleActivatedAbility(new GainAbilityTargetEffect(FlyingAbility.getInstance(), Duration.EndOfTurn), new TapSourceCost());
ability.addTarget(new TargetCreaturePermanent());
this.addAbility(ability);
}
private WindDancer(final WindDancer card) {
super(card);
}
@Override
public WindDancer copy() {
return new WindDancer(this);
}
}
| 0 | 0.885134 | 1 | 0.885134 | game-dev | MEDIA | 0.949379 | game-dev | 0.973926 | 1 | 0.973926 |
gro-ove/actools | 11,652 | AcTools.ExtraKn5Utils/FbxUtils/FbxBinaryReader.cs | // https://www.nuget.org/packages/UkooLabs.FbxSharpie/
// https://github.com/UkooLabs/FBXSharpie
// License: MIT
using System;
using System.IO;
using System.IO.Compression;
using System.Text;
using AcTools.ExtraKn5Utils.FbxUtils.Tokens;
using AcTools.ExtraKn5Utils.FbxUtils.Tokens.Value;
using AcTools.ExtraKn5Utils.FbxUtils.Tokens.ValueArray;
namespace AcTools.ExtraKn5Utils.FbxUtils {
/// <summary>
/// Reads FBX nodes from a binary stream
/// </summary>
public class FbxBinaryReader : FbxBinary {
private readonly BinaryReader stream;
private readonly ErrorLevel errorLevel;
private delegate object ReadPrimitive(BinaryReader reader);
/// <summary>
/// Creates a new reader
/// </summary>
/// <param name="stream">The stream to read from</param>
/// <param name="errorLevel">When to throw an <see cref="FbxException"/></param>
/// <exception cref="ArgumentException"><paramref name="stream"/> does
/// not support seeking</exception>
public FbxBinaryReader(Stream stream, ErrorLevel errorLevel = ErrorLevel.Checked) {
if (stream == null) {
throw new ArgumentNullException(nameof(stream));
}
if (!stream.CanSeek) {
throw new ArgumentException(
"The stream must support seeking. Try reading the data into a buffer first");
}
this.stream = new BinaryReader(stream, Encoding.ASCII);
this.errorLevel = errorLevel;
}
// Reads a single property
Token ReadProperty() {
var dataType = (char)stream.ReadByte();
switch (dataType) {
case 'Y':
return new ShortToken(stream.ReadInt16());
case 'C':
return new BooleanToken(stream.ReadByte() == 'T');
case 'I':
return new IntegerToken(stream.ReadInt32());
case 'F':
return new FloatToken(stream.ReadSingle());
case 'D':
return new DoubleToken(stream.ReadDouble());
case 'L':
return new LongToken(stream.ReadInt64());
case 'f':
return new FloatArrayToken(ReadArray<float>(br => br.ReadSingle()));
case 'd':
return new DoubleArrayToken(ReadArray<double>(br => br.ReadDouble()));
case 'l':
return new LongArrayToken(ReadArray<long>(br => br.ReadInt64()));
case 'i':
return new IntegerArrayToken(ReadArray<int>(br => br.ReadInt32()));
case 'b':
return new BooleanArrayToken(ReadArray<bool>(br => br.ReadBoolean()));
case 'S':
var len = stream.ReadInt32();
var str = len == 0 ? "" : Encoding.ASCII.GetString(stream.ReadBytes(len));
// Convert \0\1 to '::' and reverse the tokens
if (str.Contains(binarySeparator)) {
var tokens = str.Split(new[] { binarySeparator }, StringSplitOptions.None);
var sb = new StringBuilder();
bool first = true;
for (int i = tokens.Length - 1; i >= 0; i--) {
if (!first) {
sb.Append(asciiSeparator);
}
sb.Append(tokens[i]);
first = false;
}
str = sb.ToString();
}
return new StringToken(str);
case 'R':
return new ByteArrayToken(stream.ReadBytes(stream.ReadInt32()));
default:
throw new FbxException(stream.BaseStream.Position - 1,
"Invalid property data type `" + dataType + "'");
}
}
// Reads an array, decompressing it if required
T[] ReadArray<T>(ReadPrimitive readPrimitive) {
var len = stream.ReadInt32();
var encoding = stream.ReadInt32();
var compressedLen = stream.ReadInt32();
var ret = new T[len];
var s = stream;
var endPos = stream.BaseStream.Position + compressedLen;
if (encoding == 0) {
for (int i = 0; i < len; i++) {
ret[i] = (T)readPrimitive(s);
}
return ret;
}
if (errorLevel >= ErrorLevel.Checked) {
if (encoding != 1) {
throw new FbxException(stream.BaseStream.Position - 1,
"Invalid compression encoding (must be 0 or 1)");
}
var cmf = stream.ReadByte();
if ((cmf & 0xF) != 8 || (cmf >> 4) > 7) {
throw new FbxException(stream.BaseStream.Position - 1,
"Invalid compression format " + cmf);
}
var flg = stream.ReadByte();
if (errorLevel >= ErrorLevel.Strict && ((cmf << 8) + flg) % 31 != 0) {
throw new FbxException(stream.BaseStream.Position - 1,
"Invalid compression FCHECK");
}
if ((flg & (1 << 5)) != 0) {
throw new FbxException(stream.BaseStream.Position - 1,
"Invalid compression flags; dictionary not supported");
}
} else {
stream.BaseStream.Position += 2;
}
using (var codec = new DeflateStream(stream.BaseStream, CompressionMode.Decompress, true))
using (var bs = new ChecksumBinaryReader(codec)) {
try {
for (int i = 0; i < len; i++) {
ret[i] = (T)readPrimitive(bs);
}
} catch (InvalidDataException) {
throw new FbxException(stream.BaseStream.Position - 1, "Compressed data was malformed");
}
if (errorLevel >= ErrorLevel.Checked) {
stream.BaseStream.Position = endPos - sizeof(int);
var checksumBytes = new byte[sizeof(int)];
stream.BaseStream.Read(checksumBytes, 0, checksumBytes.Length);
uint checksum = 0;
for (int i = 0; i < checksumBytes.Length; i++) {
checksum = (checksum << 8) + checksumBytes[i];
}
if (checksum != bs.Checksum) {
throw new FbxException(stream.BaseStream.Position, "Compressed data has invalid checksum");
}
} else {
stream.BaseStream.Position = endPos;
}
}
return ret;
}
/// <summary>
/// Reads a single node.
/// </summary>
/// <remarks>
/// This won't read the file header or footer, and as such will fail if the stream is a full FBX file
/// </remarks>
/// <returns>The node</returns>
/// <exception cref="FbxException">The FBX data was malformed
/// for the reader's error level</exception>
public FbxNode ReadNode(FbxDocument document) {
var endOffset = document.Version >= FbxVersion.v7_5 ? stream.ReadInt64() : stream.ReadInt32();
var numProperties = document.Version >= FbxVersion.v7_5 ? stream.ReadInt64() : stream.ReadInt32();
var propertyListLen = document.Version >= FbxVersion.v7_5 ? stream.ReadInt64() : stream.ReadInt32();
var nameLen = stream.ReadByte();
var name = nameLen == 0 ? "" : Encoding.ASCII.GetString(stream.ReadBytes(nameLen));
if (endOffset == 0) {
// The end offset should only be 0 in a null node
if (errorLevel >= ErrorLevel.Checked && (numProperties != 0 || propertyListLen != 0 || !string.IsNullOrEmpty(name))) {
throw new FbxException(stream.BaseStream.Position,
"Invalid node; expected NULL record");
}
return null;
}
var node = new FbxNode(new IdentifierToken(name));
var propertyEnd = stream.BaseStream.Position + propertyListLen;
// Read properties
for (int i = 0; i < numProperties; i++) {
node.AddProperty(ReadProperty());
}
if (errorLevel >= ErrorLevel.Checked && stream.BaseStream.Position != propertyEnd) {
throw new FbxException(stream.BaseStream.Position,
"Too many bytes in property list, end point is " + propertyEnd);
}
// Read nested nodes
var listLen = endOffset - stream.BaseStream.Position;
if (errorLevel >= ErrorLevel.Checked && listLen < 0) {
throw new FbxException(stream.BaseStream.Position,
"Node has invalid end point");
}
if (listLen > 0) {
FbxNode nested;
do {
nested = ReadNode(document);
node.AddNode(nested);
} while (nested != null);
if (errorLevel >= ErrorLevel.Checked && stream.BaseStream.Position != endOffset) {
throw new FbxException(stream.BaseStream.Position,
"Too many bytes in node, end point is " + endOffset);
}
}
return node;
}
/// <summary>
/// Reads an FBX document from the stream
/// </summary>
/// <returns>The top-level node</returns>
/// <exception cref="FbxException">The FBX data was malformed
/// for the reader's error level</exception>
public FbxDocument Read() {
// Read header
bool validHeader = ReadHeader(stream.BaseStream);
if (errorLevel >= ErrorLevel.Strict && !validHeader) {
throw new FbxException(stream.BaseStream.Position,
"Invalid header string");
}
var document = new FbxDocument { Version = (FbxVersion)stream.ReadInt32() };
// Read nodes
FbxNode nested;
do {
nested = ReadNode(document);
if (nested != null) {
document.AddNode(nested);
}
} while (nested != null);
// Read footer code
var footerCode = new byte[footerCodeSize];
stream.BaseStream.Read(footerCode, 0, footerCode.Length);
if (errorLevel >= ErrorLevel.Strict) {
var validCode = GenerateFooterCode(document);
if (!CheckEqual(footerCode, validCode)) {
throw new FbxException(stream.BaseStream.Position - footerCodeSize,
"Incorrect footer code");
}
}
// Read footer extension
var dataPos = stream.BaseStream.Position;
var validFooterExtension = CheckFooter(stream, document.Version);
if (errorLevel >= ErrorLevel.Strict && !validFooterExtension) {
throw new FbxException(dataPos, "Invalid footer");
}
return document;
}
}
} | 0 | 0.961885 | 1 | 0.961885 | game-dev | MEDIA | 0.195763 | game-dev | 0.988497 | 1 | 0.988497 |
PhoenixBladez/SpiritMod | 5,835 | Items/Sets/StarjinxSet/JinxprobeWand/Jinxprobe.cs | using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using SpiritMod.Buffs.Summon;
using SpiritMod.Projectiles.BaseProj;
using SpiritMod.Utilities;
using System;
using System.Linq;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace SpiritMod.Items.Sets.StarjinxSet.JinxprobeWand
{
[AutoloadMinionBuff("Tiny Jinxprobe", "The Jinxprobe will fight for you")]
public class Jinxprobe : BaseMinion
{
public Jinxprobe() : base(800, 1600, new Vector2(32, 32)) { }
public override void AbstractSetStaticDefaults() => DisplayName.SetDefault("Jinxprobe");
Vector2 truePosition = Vector2.Zero;
Vector2 newCenter = Vector2.Zero;
public override bool PreAI()
{
if (projectile.ai[0] == 0) //check for first tick
{
truePosition = projectile.position - Player.Center;
newCenter = Player.Center;
projectile.ai[0]++;
projectile.netUpdate = true;
}
if (Vector2.Distance(newCenter, Player.Center) > 500) //if too much distance from the center used for orbiting and the real player's center, set the new center to the player's center
newCenter = Player.Center;
else //otherwise slowly adjust it
newCenter = Vector2.Lerp(newCenter, Player.Center, 0.066f);
projectile.position -= projectile.velocity; //override default position updating, make it relative to player position
truePosition += projectile.velocity;
projectile.Center = newCenter + truePosition;
return base.PreAI();
}
public override bool MinionContactDamage() => false;
public override void IdleMovement(Player player)
{
OrbitingMovement();
projectile.rotation = projectile.AngleFrom(player.Center);
}
private const float MaxDistFromCenter = 100;
private void OrbitingMovement()
{
float distanceStrength = 0.002f;
float mindistance = 30;
if (projectile.Distance(newCenter) > mindistance)
projectile.velocity += projectile.DirectionTo(newCenter) * MathHelper.Clamp((projectile.Distance(newCenter) - mindistance) * distanceStrength, 0, 0.5f);
if (projectile.Distance(newCenter) > MaxDistFromCenter)
projectile.velocity = Vector2.Lerp(projectile.velocity, projectile.DirectionTo(newCenter) * 10, MathHelper.Clamp((projectile.Distance(newCenter) - MaxDistFromCenter) * distanceStrength * 0.05f, 0, 0.01f));
if (projectile.velocity.Length() < 8)
projectile.velocity *= 1.03f;
if (projectile.velocity.Length() > 11)
projectile.velocity *= 0.98f;
}
public override void TargettingBehavior(Player player, NPC target)
{
OrbitingMovement();
projectile.rotation = Utils.AngleLerp(projectile.rotation, projectile.AngleTo(target.Center), 0.05f);
projectile.ai[1]++;
if(projectile.ai[1] > 50 && Collision.CanHit(projectile.Center, 0, 0, target.Center, 0, 0))
{
if (Main.netMode != NetmodeID.Server)
Main.PlaySound(mod.GetLegacySoundSlot(SoundType.Custom, "Sounds/starCast").WithPitchVariance(0.3f).WithVolume(0.6f), projectile.position);
Vector2 vel = projectile.GetArcVel(target.Center, 0.1f, heightabovetarget : Main.rand.Next(50, 100));
projectile.velocity = projectile.DirectionFrom(target.Center).RotatedByRandom(MathHelper.PiOver2) * 8;
Projectile.NewProjectileDirect(projectile.Center, vel, ModContent.ProjectileType<JinxprobeEnergy>(), projectile.damage, projectile.knockBack, projectile.owner).netUpdate = true;
projectile.ai[1] = 0;
projectile.netUpdate = true;
}
}
public override bool PreDraw(SpriteBatch spriteBatch, Color lightColor)
{
Texture2D glow = mod.GetTexture(Texture.Remove(0, mod.Name.Length + 1) + "_glow");
Texture2D glow2 = mod.GetTexture(Texture.Remove(0, mod.Name.Length + 1) + "_glow2");
Rectangle rect = glow.Bounds;
//draw beam to player
Texture2D tex = mod.GetTexture("Textures/Medusa_Ray");
Color beamcolor = SpiritMod.StarjinxColor(Main.GlobalTime * 4) * 0.5f * ((float)Math.Sin(Main.GlobalTime * 3) / 4 + 0.75f);
Vector2 scale = new Vector2(projectile.Distance(Player.Center) / tex.Width, 1) * 0.75f;
spriteBatch.Draw(tex,
projectile.Center - Main.screenPosition + new Vector2(tex.Size().X * scale.X, 0).RotatedBy(projectile.AngleTo(Player.Center)) / 2,
null,
SpiritMod.StarjinxColor(Main.GlobalTime * 4) * 0.5f * ((float)Math.Sin(Main.GlobalTime * 3) / 4 + 0.75f),
projectile.AngleTo(Player.Center),
tex.Size() / 2,
scale,
SpriteEffects.None,
0);
float newrotation = (Math.Abs(projectile.rotation) > MathHelper.Pi/2) ? projectile.rotation - MathHelper.Pi : projectile.rotation;
SpriteEffects flip = (Math.Abs(projectile.rotation) > MathHelper.Pi / 2) ? SpriteEffects.FlipHorizontally : SpriteEffects.None;
//draw big glow underneath projectile
spriteBatch.Draw(glow2, projectile.Center - Main.screenPosition, glow2.Bounds, beamcolor, newrotation,
glow2.Size() / 2, projectile.scale * 1.1f, flip, 0);
spriteBatch.Draw(glow2, projectile.Center - Main.screenPosition, glow2.Bounds, beamcolor * 0.3f, newrotation,
glow2.Size() / 2, projectile.scale * ((float)Math.Sin(Main.GlobalTime * 3) / 6 + 1.2f), flip, 0);
//redraw projectile and glowmask
spriteBatch.Draw(Main.projectileTexture[projectile.type], projectile.Center - Main.screenPosition, rect, projectile.GetAlpha(lightColor), newrotation, rect.Size() / 2, projectile.scale, flip, 0);
spriteBatch.Draw(glow, projectile.Center - Main.screenPosition, rect, projectile.GetAlpha(Color.White), newrotation, rect.Size() / 2, projectile.scale, flip, 0);
spriteBatch.Draw(glow, projectile.Center - Main.screenPosition, rect, projectile.GetAlpha(Color.White * 0.5f), newrotation, rect.Size() / 2,
projectile.scale + (projectile.scale * (0.3f + (float)Math.Sin(Main.GlobalTime * 3)/6)), flip, 0);
return false;
}
}
} | 0 | 0.766179 | 1 | 0.766179 | game-dev | MEDIA | 0.974654 | game-dev | 0.981324 | 1 | 0.981324 |
Helion-Engine/Helion | 4,371 | Tests/Unit/GameAction/Id24/ColorMaps.cs | using FluentAssertions;
using Helion.Resources.IWad;
using Helion.World.Entities.Players;
using Helion.World.Geometry.Sectors;
using Helion.World.Impl.SinglePlayer;
using Helion.World.Physics;
using Xunit;
namespace Helion.Tests.Unit.GameAction.Id24;
[Collection("GameActions")]
public class ColorMaps
{
private readonly SinglePlayerWorld World;
private Player Player => World.Player;
public ColorMaps()
{
World = WorldAllocator.LoadMap("Resources/id24colormaps.zip", "id24colormaps.WAD", "MAP01", GetType().Name, (world) => { }, IWadType.Doom2, cacheWorld: false);
}
[Fact(DisplayName = "2075 - Set sector colormap")]
public void Action2075_SetSectorColorMap()
{
var sector = GameActions.GetSectorByTag(World, 1);
AssertColorMap(sector, "BLUMAP");
}
[Fact(DisplayName = "2076 - W1 Set sector colormap - Front")]
public void Action2076_SetSectorColorMapFront()
{
var sector = GameActions.GetSectorByTag(World, 2);
AssertColorMap(sector, "BLUMAP");
GameActions.GetLine(World, 24).Flags.Repeat.Should().BeFalse();
GameActions.ActivateLine(World, Player, 24, ActivationContext.CrossLine, fromFront: true).Should().BeTrue();
AssertColorMap(sector, "REDMAP");
}
[Fact(DisplayName = "2076 - W1 Set sector colormap - Back")]
public void Action2076_SetSectorColorMapBack()
{
var sector = GameActions.GetSectorByTag(World, 2);
AssertColorMap(sector, "BLUMAP");
GameActions.GetLine(World, 24).Flags.Repeat.Should().BeFalse();
GameActions.ActivateLine(World, Player, 24, ActivationContext.CrossLine, fromFront: false).Should().BeTrue();
AssertColorMap(sector, "CYAMAP");
}
[Fact(DisplayName = "2077 - WR Set sector colormap")]
public void Action2077_SetSectorColorMap()
{
var sector = GameActions.GetSectorByTag(World, 2);
AssertColorMap(sector, "BLUMAP");
GameActions.GetLine(World, 25).Flags.Repeat.Should().BeTrue();
GameActions.ActivateLine(World, Player, 25, ActivationContext.CrossLine).Should().BeTrue();
AssertColorMap(sector, null);
}
[Fact(DisplayName = "2078 - S1 Set sector colormap")]
public void Action2078_SetSectorColorMap()
{
var sector = GameActions.GetSectorByTag(World, 1);
AssertColorMap(sector, "BLUMAP");
GameActions.GetLine(World, 16).Flags.Repeat.Should().BeFalse();
GameActions.ActivateLine(World, Player, 16, ActivationContext.UseLine).Should().BeTrue();
AssertColorMap(sector, "YELMAP");
}
[Fact(DisplayName = "2079 - SR Set sector colormap")]
public void Action2079_SetSectorColorMap()
{
var sector = GameActions.GetSectorByTag(World, 1);
AssertColorMap(sector, "BLUMAP");
GameActions.GetLine(World, 12).Flags.Repeat.Should().BeTrue();
GameActions.ActivateLine(World, Player, 12, ActivationContext.UseLine).Should().BeTrue();
AssertColorMap(sector, null);
}
[Fact(DisplayName = "2080 - G1 Set sector colormap")]
public void Action2080_SetSectorColorMap()
{
var sector = GameActions.GetSectorByTag(World, 3);
AssertColorMap(sector, null);
GameActions.GetLine(World, 5).Flags.Repeat.Should().BeFalse();
GameActions.SetEntityToLine(World, Player, 5, Player.Radius * 2).Should().BeTrue();
GameActions.PlayerFirePistol(World, Player).Should().BeTrue();
AssertColorMap(sector, "CYAMAP");
}
[Fact(DisplayName = "2081 - GR Set sector colormap")]
public void Action2081_SetSectorColorMap()
{
var sector = GameActions.GetSectorByTag(World, 3);
AssertColorMap(sector, null);
GameActions.GetLine(World, 4).Flags.Repeat.Should().BeTrue();
GameActions.SetEntityToLine(World, Player, 4, Player.Radius * 2).Should().BeTrue();
GameActions.PlayerFirePistol(World, Player).Should().BeTrue();
AssertColorMap(sector, "VIOMAP");
}
private static void AssertColorMap(Sector sector, string? name)
{
if (name == null)
{
sector.Colormap.Should().BeNull();
return;
}
sector.Colormap.Should().NotBeNull();
sector.Colormap!.Entry.Should().NotBeNull();
sector.Colormap!.Entry!.Path.Name.Should().Be(name);
}
}
| 0 | 0.873584 | 1 | 0.873584 | game-dev | MEDIA | 0.882922 | game-dev | 0.749999 | 1 | 0.749999 |
hlrs-vis/covise | 10,409 | src/OpenCOVER/DrivingSim/fasi2/FWDAccelerationState.h | #ifndef __FWDAccelerationState_h
#define __FWDAccelerationState_h
class FWDAccelerationState
{
public:
FWDAccelerationState();
double aX;
double aY;
double aZ;
double aYaw;
double aRoll;
double aPitch;
double aSuspZFL;
double aSuspZFR;
double aSuspZRR;
double aSuspZRL;
double aOmegaYFL;
double aOmegaYFR;
double aOmegaYRR;
double aOmegaYRL;
double aOmegaZFL;
double aOmegaZFR;
double phiDotFL1;
double phiDotFL2;
double phiDotFL3;
double phiDotFR1;
double phiDotFR2;
double phiDotFR3;
double phiDotRR1;
double phiDotRR2;
double phiDotRR3;
double phiDotRL1;
double phiDotRL2;
double phiDotRL3;
double aEngineRPM;
double TcolumnCombined;
double Tclutch;
double TclutchMax;
double slipFL;
double slipFR;
double slipRR;
double slipRL;
double FweightedFL;
double FweightedFR;
double FweightedRR;
double FweightedRL;
double FtireFL;
double FtireFR;
double FtireRR;
double FtireRL;
double FxFL;
double FxFR;
double FxRR;
double FxRL;
double FyFL;
double FyFR;
double FyRR;
double FyRL;
double genericOut1;
double genericOut2;
double genericOut3;
double genericOut4;
double genericOut5;
double genericOut6;
double genericOut7;
double genericOut8;
double genericOut9;
double genericOut10;
double genericOut11;
double genericOut12;
double genericOut13;
double genericOut14;
double genericOut15;
double genericOut16;
FWDAccelerationState operator+(const FWDAccelerationState& other)
{
FWDAccelerationState resultState;
resultState.aX = aX + other.aX;
resultState.aY = aY + other.aY;
resultState.aZ = aZ + other.aZ;
resultState.aYaw = aYaw + other.aYaw;
resultState.aRoll = aRoll + other.aRoll;
resultState.aPitch = aPitch + other.aPitch;
resultState.aSuspZFL = aSuspZFL + other.aSuspZFL;
resultState.aSuspZFR = aSuspZFR + other.aSuspZFR;
resultState.aSuspZRR = aSuspZRR + other.aSuspZRR;
resultState.aSuspZRL = aSuspZRL + other.aSuspZRL;
resultState.aOmegaYFL = aOmegaYFL + other.aOmegaYFL;
resultState.aOmegaYFR = aOmegaYFR + other.aOmegaYFR;
resultState.aOmegaYRR = aOmegaYRR + other.aOmegaYRR;
resultState.aOmegaYRL = aOmegaYRL + other.aOmegaYRL;
resultState.aOmegaZFL = aOmegaZFL + other.aOmegaZFL;
resultState.aOmegaZFR = aOmegaZFR + other.aOmegaZFR;
/*resultState.phiDotFL1 = phiDotFL1 + other.phiDotFL1;
resultState.phiDotFL2 = phiDotFL2 + other.phiDotFL2;
resultState.phiDotFL3 = phiDotFL3 + other.phiDotFL3;
resultState.phiDotFR1 = phiDotFR1 + other.phiDotFR1;
resultState.phiDotFR2 = phiDotFR2 + other.phiDotFR2;
resultState.phiDotFR3 = phiDotFR3 + other.phiDotFR3;
resultState.phiDotRR1 = phiDotRR1 + other.phiDotRR1;
resultState.phiDotRR2 = phiDotRR2 + other.phiDotRR2;
resultState.phiDotRR3 = phiDotRR3 + other.phiDotRR3;
resultState.phiDotRL1 = phiDotRL1 + other.phiDotRL1;
resultState.phiDotRL2 = phiDotRL2 + other.phiDotRL2;
resultState.phiDotRL3 = phiDotRL3 + other.phiDotRL3;*/
resultState.aEngineRPM = aEngineRPM + other.aEngineRPM;
resultState.TcolumnCombined = TcolumnCombined + other.TcolumnCombined;
resultState.Tclutch = Tclutch + other.Tclutch;
resultState.TclutchMax = TclutchMax + other.TclutchMax;
resultState.slipFL = slipFL + other.slipFL;
resultState.slipFR = slipFR + other.slipFR;
resultState.slipRR = slipRR + other.slipRR;
resultState.slipRL = slipRL + other.slipRL;
resultState.FweightedFL = FweightedFL + other.FweightedFL;
resultState.FweightedFR = FweightedFR + other.FweightedFR;
resultState.FweightedRR = FweightedRR + other.FweightedRR;
resultState.FweightedRL = FweightedRL + other.FweightedRL;
resultState.FtireFL = FtireFL + other.FtireFL;
resultState.FtireFR = FtireFR + other.FtireFR;
resultState.FtireRR = FtireRR + other.FtireRR;
resultState.FtireRL = FtireRL + other.FtireRL;
resultState.FxFL = FxFL + other.FxFL;
resultState.FxFR = FxFR + other.FxFR;
resultState.FxRR = FxRR + other.FxRR;
resultState.FxRL = FxRL + other.FxRL;
resultState.FyFL = FyFL + other.FyFL;
resultState.FyFR = FyFR + other.FyFR;
resultState.FyRR = FyRR + other.FyRR;
resultState.FyRL = FyRL + other.FyRL;
resultState.genericOut1 = genericOut1 + other.genericOut1;
resultState.genericOut2 = genericOut2 + other.genericOut2;
resultState.genericOut3 = genericOut3 + other.genericOut3;
resultState.genericOut4 = genericOut4 + other.genericOut4;
resultState.genericOut5 = genericOut5 + other.genericOut5;
resultState.genericOut6 = genericOut6 + other.genericOut6;
resultState.genericOut7 = genericOut7 + other.genericOut7;
resultState.genericOut8 = genericOut8 + other.genericOut8;
resultState.genericOut9 = genericOut9 + other.genericOut9;
resultState.genericOut10 = genericOut10 + other.genericOut10;
resultState.genericOut11 = genericOut11 + other.genericOut11;
resultState.genericOut12 = genericOut12 + other.genericOut12;
resultState.genericOut13 = genericOut13 + other.genericOut13;
resultState.genericOut14 = genericOut14 + other.genericOut14;
resultState.genericOut15 = genericOut15 + other.genericOut15;
resultState.genericOut16 = genericOut16 + other.genericOut16;
return resultState;
};
FWDAccelerationState operator*(const double scalar)
{
FWDAccelerationState resultState;
resultState.aX = aX * scalar;
resultState.aY = aY * scalar;
resultState.aZ = aZ * scalar;
resultState.aYaw = aYaw * scalar;
resultState.aRoll = aRoll * scalar;
resultState.aPitch = aPitch * scalar;
resultState.aSuspZFL = aSuspZFL * scalar;
resultState.aSuspZFR = aSuspZFR * scalar;
resultState.aSuspZRR = aSuspZRR * scalar;
resultState.aSuspZRL = aSuspZRL * scalar;
resultState.aOmegaYFL = aOmegaYFL * scalar;
resultState.aOmegaYFR = aOmegaYFR * scalar;
resultState.aOmegaYRR = aOmegaYRR * scalar;
resultState.aOmegaYRL = aOmegaYRL * scalar;
resultState.aOmegaZFL = aOmegaZFL * scalar;
resultState.aOmegaZFR = aOmegaZFR * scalar;
/*resultState.phiDotFL1 = phiDotFL1 * scalar;
resultState.phiDotFL2 = phiDotFL2 * scalar;
resultState.phiDotFL3 = phiDotFL3 * scalar;
resultState.phiDotFR1 = phiDotFR1 * scalar;
resultState.phiDotFR2 = phiDotFR2 * scalar;
resultState.phiDotFR3 = phiDotFR3 * scalar;
resultState.phiDotRR1 = phiDotRR1 * scalar;
resultState.phiDotRR2 = phiDotRR2 * scalar;
resultState.phiDotRR3 = phiDotRR3 * scalar;
resultState.phiDotRL1 = phiDotRL1 * scalar;
resultState.phiDotRL2 = phiDotRL2 * scalar;
resultState.phiDotRL3 = phiDotRL3 * scalar;*/
resultState.aEngineRPM = aEngineRPM * scalar;
resultState.TcolumnCombined = TcolumnCombined * scalar;
resultState.Tclutch = Tclutch * scalar;
resultState.TclutchMax = TclutchMax * scalar;
resultState.slipFL = slipFL * scalar;
resultState.slipFR = slipFR * scalar;
resultState.slipRR = slipRR * scalar;
resultState.slipRL = slipRL * scalar;
resultState.FweightedFL = FweightedFL * scalar;
resultState.FweightedFR = FweightedFR * scalar;
resultState.FweightedRR = FweightedRR * scalar;
resultState.FweightedRL = FweightedRL * scalar;
resultState.FtireFL = FtireFL * scalar;
resultState.FtireFR = FtireFR * scalar;
resultState.FtireRR = FtireRR * scalar;
resultState.FtireRL = FtireRL * scalar;
resultState.FxFL = FxFL * scalar;
resultState.FxFR = FxFR * scalar;
resultState.FxRR = FxRR * scalar;
resultState.FxRL = FxRL * scalar;
resultState.FyFL = FyFL * scalar;
resultState.FyFR = FyFR * scalar;
resultState.FyRR = FyRR * scalar;
resultState.FyRL = FyRL * scalar;
resultState.genericOut1 = genericOut1 * scalar;
resultState.genericOut2 = genericOut2 * scalar;
resultState.genericOut3 = genericOut3 * scalar;
resultState.genericOut4 = genericOut4 * scalar;
resultState.genericOut5 = genericOut5 * scalar;
resultState.genericOut6 = genericOut6 * scalar;
resultState.genericOut7 = genericOut7 * scalar;
resultState.genericOut8 = genericOut8 * scalar;
resultState.genericOut9 = genericOut9 * scalar;
resultState.genericOut10 = genericOut10 * scalar;
resultState.genericOut11 = genericOut11 * scalar;
resultState.genericOut12 = genericOut12 * scalar;
resultState.genericOut13 = genericOut13 * scalar;
resultState.genericOut14 = genericOut14 * scalar;
resultState.genericOut15 = genericOut15 * scalar;
resultState.genericOut16 = genericOut16 * scalar;
return resultState;
};
FWDAccelerationState operator=(const FWDAccelerationState &other)
{
aX = other.aX;
aY = other.aY;
aZ = other.aZ;
aYaw = other.aYaw;
aRoll = other.aRoll;
aPitch = other.aPitch;
aSuspZFL = other.aSuspZFL;
aSuspZFR = other.aSuspZFR;
aSuspZRR = other.aSuspZRR;
aSuspZRL = other.aSuspZRL;
aOmegaYFL = other.aOmegaYFL;
aOmegaYFR = other.aOmegaYFR;
aOmegaYRR = other.aOmegaYRR;
aOmegaYRL = other.aOmegaYRL;
aOmegaZFL = other.aOmegaZFL;
aOmegaZFR = other.aOmegaZFR;
/*phiDotFL1 = other.phiDotFL1;
phiDotFL2 = other.phiDotFL2;
phiDotFL3 = other.phiDotFL3;
phiDotFR1 = other.phiDotFR1;
phiDotFR2 = other.phiDotFR2;
phiDotFR3 = other.phiDotFR3;
phiDotRR1 = other.phiDotRR1;
phiDotRR2 = other.phiDotRR2;
phiDotRR3 = other.phiDotRR3;
phiDotRL1 = other.phiDotRL1;
phiDotRL2 = other.phiDotRL2;
phiDotRL3 = other.phiDotRL3;*/
aEngineRPM = other.aEngineRPM;
TcolumnCombined = other.TcolumnCombined;
Tclutch = other.Tclutch;
TclutchMax = other.TclutchMax;
slipFL = other.slipFL;
slipFR = other.slipFR;
slipRR = other.slipRR;
slipRL = other.slipRL;
FweightedFL = other.FweightedFL;
FweightedFR = other.FweightedFR;
FweightedRR = other.FweightedRR;
FweightedRL = other.FweightedRL;
FtireFL = other.FtireFL;
FtireFR = other.FtireFR;
FtireRR = other.FtireRR;
FtireRL = other.FtireRL;
FxFL = other.FxFL;
FxFR = other.FxFR;
FxRR = other.FxRR;
FxRL = other.FxRL;
FyFL = other.FyFL;
FyFR = other.FyFR;
FyRR = other.FyRR;
FyRL = other.FyRL;
genericOut1 = other.genericOut1;
genericOut2 = other.genericOut2;
genericOut3 = other.genericOut3;
genericOut4 = other.genericOut4;
genericOut5 = other.genericOut5;
genericOut6 = other.genericOut6;
genericOut7 = other.genericOut7;
genericOut8 = other.genericOut8;
genericOut9 = other.genericOut9;
genericOut10 = other.genericOut10;
genericOut11 = other.genericOut11;
genericOut12 = other.genericOut12;
genericOut13 = other.genericOut13;
genericOut14 = other.genericOut14;
genericOut15 = other.genericOut15;
genericOut16 = other.genericOut16;
};
};
#endif
| 0 | 0.734874 | 1 | 0.734874 | game-dev | MEDIA | 0.391209 | game-dev | 0.942156 | 1 | 0.942156 |
lordofduct/spacepuppy-unity-framework-4.0 | 2,622 | Framework/com.spacepuppy.tween/Runtime/src/Dynamic/Accessors/BasicMemberAccessor.cs | using System.Reflection;
namespace com.spacepuppy.Dynamic.Accessors
{
public class BasicMemberAccessor : IMemberAccessor
{
#region Fields
private MemberInfo _memberInfo;
#endregion
#region CONSTRUCTOR
public BasicMemberAccessor(MemberInfo info)
{
_memberInfo = info;
}
#endregion
#region IMemberAccessor Interface
public string GetMemberName() { return _memberInfo?.Name; }
public System.Type GetMemberType() { return DynamicUtil.GetReturnType(_memberInfo); }
public object Get(object target)
{
if (_memberInfo is PropertyInfo)
{
return (_memberInfo as PropertyInfo).GetValue(target, null);
}
else if (_memberInfo is FieldInfo)
{
return (_memberInfo as FieldInfo).GetValue(target);
}
return null;
}
public void Set(object target, object value)
{
if (_memberInfo is PropertyInfo)
{
try
{
(_memberInfo as PropertyInfo).SetValue(target, value, null);
}
catch (System.InvalidCastException)
{
// This happens only if a float is being assigned to an int.
(_memberInfo as PropertyInfo).SetValue(target, (int)System.Math.Floor((double)(float)value), null);
}
catch (System.ArgumentException)
{
// This happens only on iOS if a float is being assigned to an int.
(_memberInfo as PropertyInfo).SetValue(target, (int)System.Math.Floor((double)(float)value), null);
}
}
else if (_memberInfo is FieldInfo)
{
try
{
(_memberInfo as FieldInfo).SetValue(target, value);
}
catch (System.InvalidCastException)
{
// This happens only if a float is being assigned to an int.
(_memberInfo as FieldInfo).SetValue(target, (int)System.Math.Floor((double)(float)value));
}
catch (System.ArgumentException)
{
// This happens only on iOS if a float is being assigned to an int.
(_memberInfo as FieldInfo).SetValue(target, (int)System.Math.Floor((double)(float)value));
}
}
}
#endregion
}
}
| 0 | 0.871789 | 1 | 0.871789 | game-dev | MEDIA | 0.84086 | game-dev | 0.979424 | 1 | 0.979424 |
oot-pc-port/oot-pc-port | 3,126 | asm/non_matchings/overlays/actors/ovl_En_Ma2/func_80AA21C8.s | glabel func_80AA21C8
/* 00828 80AA21C8 27BDFFE8 */ addiu $sp, $sp, 0xFFE8 ## $sp = FFFFFFE8
/* 0082C 80AA21CC AFBF0014 */ sw $ra, 0x0014($sp)
/* 00830 80AA21D0 84830208 */ lh $v1, 0x0208($a0) ## 00000208
/* 00834 80AA21D4 00803025 */ or $a2, $a0, $zero ## $a2 = 00000000
/* 00838 80AA21D8 8CA21C44 */ lw $v0, 0x1C44($a1) ## 00001C44
/* 0083C 80AA21DC 14600003 */ bne $v1, $zero, .L80AA21EC
/* 00840 80AA21E0 246EFFFF */ addiu $t6, $v1, 0xFFFF ## $t6 = FFFFFFFF
/* 00844 80AA21E4 10000003 */ beq $zero, $zero, .L80AA21F4
/* 00848 80AA21E8 00002025 */ or $a0, $zero, $zero ## $a0 = 00000000
.L80AA21EC:
/* 0084C 80AA21EC A4CE0208 */ sh $t6, 0x0208($a2) ## 00000208
/* 00850 80AA21F0 84C40208 */ lh $a0, 0x0208($a2) ## 00000208
.L80AA21F4:
/* 00854 80AA21F4 50800007 */ beql $a0, $zero, .L80AA2214
/* 00858 80AA21F8 84D901E0 */ lh $t9, 0x01E0($a2) ## 000001E0
/* 0085C 80AA21FC 8C4F0680 */ lw $t7, 0x0680($v0) ## 00000680
/* 00860 80AA2200 3C010080 */ lui $at, 0x0080 ## $at = 00800000
/* 00864 80AA2204 01E1C025 */ or $t8, $t7, $at ## $t8 = 00800000
/* 00868 80AA2208 10000013 */ beq $zero, $zero, .L80AA2258
/* 0086C 80AA220C AC580680 */ sw $t8, 0x0680($v0) ## 00000680
/* 00870 80AA2210 84D901E0 */ lh $t9, 0x01E0($a2) ## 000001E0
.L80AA2214:
/* 00874 80AA2214 3C01FFFE */ lui $at, 0xFFFE ## $at = FFFE0000
/* 00878 80AA2218 3421FFFF */ ori $at, $at, 0xFFFF ## $at = FFFEFFFF
/* 0087C 80AA221C 17200009 */ bne $t9, $zero, .L80AA2244
/* 00880 80AA2220 3C0C80AA */ lui $t4, %hi(func_80AA2018) ## $t4 = 80AA0000
/* 00884 80AA2224 8CC80004 */ lw $t0, 0x0004($a2) ## 00000004
/* 00888 80AA2228 3C010001 */ lui $at, 0x0001 ## $at = 00010000
/* 0088C 80AA222C 00A02025 */ or $a0, $a1, $zero ## $a0 = 00000000
/* 00890 80AA2230 01014825 */ or $t1, $t0, $at ## $t1 = 00010000
/* 00894 80AA2234 0C041B33 */ jal func_80106CCC
/* 00898 80AA2238 ACC90004 */ sw $t1, 0x0004($a2) ## 00000004
/* 0089C 80AA223C 10000007 */ beq $zero, $zero, .L80AA225C
/* 008A0 80AA2240 8FBF0014 */ lw $ra, 0x0014($sp)
.L80AA2244:
/* 008A4 80AA2244 8CCA0004 */ lw $t2, 0x0004($a2) ## 00000004
/* 008A8 80AA2248 258C2018 */ addiu $t4, $t4, %lo(func_80AA2018) ## $t4 = 00002018
/* 008AC 80AA224C ACCC0190 */ sw $t4, 0x0190($a2) ## 00000190
/* 008B0 80AA2250 01415824 */ and $t3, $t2, $at
/* 008B4 80AA2254 ACCB0004 */ sw $t3, 0x0004($a2) ## 00000004
.L80AA2258:
/* 008B8 80AA2258 8FBF0014 */ lw $ra, 0x0014($sp)
.L80AA225C:
/* 008BC 80AA225C 27BD0018 */ addiu $sp, $sp, 0x0018 ## $sp = 00000000
/* 008C0 80AA2260 03E00008 */ jr $ra
/* 008C4 80AA2264 00000000 */ nop
| 0 | 0.644199 | 1 | 0.644199 | game-dev | MEDIA | 0.977788 | game-dev | 0.735753 | 1 | 0.735753 |
ShuangYu1145/Faiths-Fix | 2,746 | src/main/java/com/github/stachelbeere1248/zombiesutils/game/GameMode.java | package com.github.stachelbeere1248.zombiesutils.game;
import com.github.stachelbeere1248.zombiesutils.game.enums.Difficulty;
import com.github.stachelbeere1248.zombiesutils.game.enums.Map;
public enum GameMode {
DEAD_END(Map.DEAD_END, Difficulty.NORMAL), DEAD_END_HARD(Map.DEAD_END, Difficulty.HARD), DEAD_END_RIP(Map.DEAD_END, Difficulty.RIP),
BAD_BLOOD(Map.BAD_BLOOD, Difficulty.NORMAL), BAD_BLOOD_HARD(Map.BAD_BLOOD, Difficulty.HARD), BAD_BLOOD_RIP(Map.BAD_BLOOD, Difficulty.RIP),
ALIEN_ARCADIUM(Map.ALIEN_ARCADIUM, Difficulty.NORMAL),
PRISON(Map.PRISON, Difficulty.NORMAL), PRISON_HARD(Map.PRISON, Difficulty.HARD), PRISON_RIP(Map.PRISON, Difficulty.RIP);
private final Map map;
private final Difficulty difficulty;
GameMode(final Map map, final Difficulty difficulty) {
this.map = map;
this.difficulty = difficulty;
}
public Map getMap() {
return this.map;
}
public Difficulty getDifficulty() {
return this.difficulty;
}
public GameMode appliedDifficulty(final Difficulty difficulty) {
switch (this.map) {
case DEAD_END:
switch (difficulty) {
case NORMAL:
return DEAD_END;
case HARD:
return DEAD_END_HARD;
case RIP:
return DEAD_END_RIP;
}
case BAD_BLOOD:
switch (difficulty) {
case NORMAL:
return BAD_BLOOD;
case HARD:
return BAD_BLOOD_HARD;
case RIP:
return BAD_BLOOD_RIP;
}
case PRISON:
switch (difficulty) {
case NORMAL:
return PRISON;
case HARD:
return PRISON_HARD;
case RIP:
return PRISON_RIP;
}
case ALIEN_ARCADIUM:
return ALIEN_ARCADIUM;
default:
throw new IllegalStateException("Invalid Map: " + this.map);
}
}
public boolean isMap(Map map) {
return this.getMap() == map;
}
public static GameMode getNormalForMap(final Map map) {
switch (map) {
case DEAD_END:
return DEAD_END;
case BAD_BLOOD:
return BAD_BLOOD;
case ALIEN_ARCADIUM:
return ALIEN_ARCADIUM;
case PRISON:
return PRISON;
default:
throw new IllegalStateException("Unexpected value: " + map);
}
}
}
| 0 | 0.720449 | 1 | 0.720449 | game-dev | MEDIA | 0.832556 | game-dev | 0.851943 | 1 | 0.851943 |
MadDeCoDeR/Classic-RBDOOM-3-BFG | 5,256 | neo/d3xp/menus/MenuWidget_PDA_Objective.cpp | /*
===========================================================================
Doom 3 BFG Edition GPL Source Code
Copyright (C) 1993-2012 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 BFG Edition GPL Source Code ("Doom 3 BFG Edition Source Code").
Doom 3 BFG Edition Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Doom 3 BFG Edition Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Doom 3 BFG Edition Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 BFG Edition Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 BFG Edition Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#pragma hdrstop
#include "precompiled.h"
#include "../Game_local.h"
/*
========================
idMenuWidget_PDA_Objective::Update
========================
*/
void idMenuWidget_PDA_Objective::Update()
{
if( GetSWFObject() == NULL )
{
return;
}
idSWFScriptObject& root = GetSWFObject()->GetRootObject();
if( !BindSprite( root ) || GetSprite() == NULL )
{
return;
}
idPlayer* player = game->GetLocalPlayer();
if( player == NULL )
{
return;
}
idSWFScriptObject* dataObj = GetSprite()->GetScriptObject()->GetNestedObj( "info" );
idSWFSpriteInstance* dataSprite = dataObj->GetSprite();
if( dataObj != NULL && dataSprite != NULL )
{
idSWFSpriteInstance* img = dataObj->GetNestedSprite( "objImg", "img" );
if( player->GetInventory().objectiveNames.Num() == 0 )
{
dataSprite->StopFrame( 1 );
}
else
{
int numObjectives = player->GetInventory().objectiveNames.Num();
int objStartIndex = 0;
if( numObjectives == 1 )
{
dataSprite->StopFrame( 2 );
objStartIndex = 0;
}
else
{
dataSprite->StopFrame( 3 );
objStartIndex = 1;
}
idSWFTextInstance* txtDesc = dataObj->GetNestedText( "txtDesc" );
int displayCount = 0;
for( int index = numObjectives - 1; displayCount < 2 && index >= 0; --index )
{
if( img != NULL )
{
if( player->GetInventory().objectiveNames[index].screenshot == NULL )
{
img->SetVisible( false );
}
else
{
img->SetVisible( true );
img->SetMaterial( player->GetInventory().objectiveNames[index].screenshot );
}
}
idSWFSpriteInstance* objSel = dataObj->GetNestedSprite( va( "obj%d", objStartIndex - displayCount ), "sel" );
idSWFTextInstance* txtNote = dataObj->GetNestedText( va( "obj%d", objStartIndex - displayCount ), "txtVal" );
if( objSel != NULL )
{
if( displayCount == 0 )
{
objSel->SetVisible( true );
}
else
{
objSel->SetVisible( false );
}
}
if( txtNote != NULL )
{
txtNote->SetText( player->GetInventory().objectiveNames[index].title.c_str() );
}
if( displayCount == 0 )
{
txtDesc->SetText( player->GetInventory().objectiveNames[index].text.c_str() );
}
displayCount++;
}
}
// Set the main objective text
idTarget_SetPrimaryObjective* mainObj = player->GetPrimaryObjective();
idSWFTextInstance* txtMainObj = dataObj->GetNestedText( "txtObj" );
if( txtMainObj != NULL )
{
if( mainObj != NULL )
{
txtMainObj->SetText( mainObj->spawnArgs.GetString( "text", idLocalization::GetString( "#str_04253" ) ) );
}
else
{
txtMainObj->SetText( idLocalization::GetString( "#str_02526" ) );
}
}
}
}
/*
========================
idMenuWidget_Help::ObserveEvent
========================
*/
void idMenuWidget_PDA_Objective::ObserveEvent( const idMenuWidget& widget, const idWidgetEvent& event )
{
const idMenuWidget_Button* const button = dynamic_cast< const idMenuWidget_Button* >( &widget );
if( button == NULL )
{
return;
}
const idMenuWidget* const listWidget = button->GetParent();
if( listWidget == NULL )
{
return;
}
switch( event.type )
{
case WIDGET_EVENT_FOCUS_ON:
{
const idMenuWidget_DynamicList* const list = dynamic_cast< const idMenuWidget_DynamicList* const >( listWidget );
if( GetSprite() != NULL )
{
if( list->GetViewIndex() == 0 )
{
GetSprite()->PlayFrame( "rollOn" );
}
else if( pdaIndex == 0 && list->GetViewIndex() != 0 )
{
GetSprite()->PlayFrame( "rollOff" );
}
}
pdaIndex = list->GetViewIndex();
Update();
break;
}
}
} | 0 | 0.934841 | 1 | 0.934841 | game-dev | MEDIA | 0.899371 | game-dev | 0.989595 | 1 | 0.989595 |
SonicEraZoR/Portal-Base | 157,767 | sp/src/game/server/sceneentity.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "cbase.h"
#include <stdarg.h>
#include "baseflex.h"
#include "entitylist.h"
#include "choreoevent.h"
#include "choreoactor.h"
#include "choreochannel.h"
#include "choreoscene.h"
#include "studio.h"
#include "networkstringtable_gamedll.h"
#include "ai_basenpc.h"
#include "engine/IEngineSound.h"
#include "ai_navigator.h"
#include "saverestore_utlvector.h"
#include "ai_baseactor.h"
#include "AI_Criteria.h"
#include "tier1/strtools.h"
#include "checksum_crc.h"
#include "SoundEmitterSystem/isoundemittersystembase.h"
#include "utlbuffer.h"
#include "tier0/icommandline.h"
#include "sceneentity.h"
#include "datacache/idatacache.h"
#include "dt_utlvector_send.h"
#include "ichoreoeventcallback.h"
#include "scenefilecache/ISceneFileCache.h"
#include "SceneCache.h"
#include "scripted.h"
#include "env_debughistory.h"
#ifdef HL2_EPISODIC
#include "npc_alyx_episodic.h"
#endif // HL2_EPISODIC
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
extern ISoundEmitterSystemBase *soundemitterbase;
extern ISceneFileCache *scenefilecache;
class CSceneEntity;
class CBaseFlex;
// VCDS are loaded from their compiled/binary format (much faster)
// Requies vcds be saved as compiled assets
//#define COMPILED_VCDS 1
static ConVar scene_forcecombined( "scene_forcecombined", "0", 0, "When playing back, force use of combined .wav files even in english." );
static ConVar scene_maxcaptionradius( "scene_maxcaptionradius", "1200", 0, "Only show closed captions if recipient is within this many units of speaking actor (0==disabled)." );
// Assume sound system is 100 msec lagged (only used if we can't find snd_mixahead cvar!)
#define SOUND_SYSTEM_LATENCY_DEFAULT ( 0.1f )
// Think every 50 msec (FIXME: Try 10hz?)
#define SCENE_THINK_INTERVAL 0.001 // FIXME: make scene's think in concert with their npc's
#define FINDNAMEDENTITY_MAX_ENTITIES 32 // max number of entities to be considered for random entity selection in FindNamedEntity
// List of the last 5 lines of speech from NPCs for bug reports
static recentNPCSpeech_t speechListSounds[ SPEECH_LIST_MAX_SOUNDS ] = { { 0, "", "" }, { 0, "", "" }, { 0, "", "" }, { 0, "", "" }, { 0, "", "" } };
static int speechListIndex = 0;
// Only allow scenes to change their pitch within a range of values
#define SCENE_MIN_PITCH 0.25f
#define SCENE_MAX_PITCH 2.5f
//===========================================================================================================
// SCENE LIST MANAGER
//===========================================================================================================
#define SCENE_LIST_MANAGER_MAX_SCENES 16
//-----------------------------------------------------------------------------
// Purpose: Entity that manages a list of scenes
//-----------------------------------------------------------------------------
class CSceneListManager : public CLogicalEntity
{
DECLARE_CLASS( CSceneListManager, CLogicalEntity );
public:
DECLARE_DATADESC();
virtual void Activate( void );
void ShutdownList( void );
void SceneStarted( CBaseEntity *pSceneOrManager );
void AddListManager( CSceneListManager *pManager );
void RemoveScene( int iIndex );
// Inputs
void InputShutdown( inputdata_t &inputdata );
private:
CUtlVector< CHandle< CSceneListManager > > m_hListManagers;
string_t m_iszScenes[SCENE_LIST_MANAGER_MAX_SCENES];
EHANDLE m_hScenes[SCENE_LIST_MANAGER_MAX_SCENES];
};
//-----------------------------------------------------------------------------
// Purpose: This class exists solely to call think on all scene entities in a deterministic order
//-----------------------------------------------------------------------------
class CSceneManager : public CBaseEntity
{
DECLARE_CLASS( CSceneManager, CBaseEntity );
DECLARE_DATADESC();
public:
virtual void Spawn()
{
BaseClass::Spawn();
SetNextThink( gpGlobals->curtime );
}
virtual int ObjectCaps( void ) { return BaseClass::ObjectCaps() | FCAP_DONT_SAVE; }
virtual void Think();
void ClearAllScenes();
void AddSceneEntity( CSceneEntity *scene );
void RemoveSceneEntity( CSceneEntity *scene );
void QueueRestoredSound( CBaseFlex *actor, char const *soundname, soundlevel_t soundlevel, float time_in_past );
void OnClientActive( CBasePlayer *player );
void RemoveActorFromScenes( CBaseFlex *pActor, bool bInstancedOnly, bool bNonIdleOnly, const char *pszThisSceneOnly );
void RemoveScenesInvolvingActor( CBaseFlex *pActor );
void PauseActorsScenes( CBaseFlex *pActor, bool bInstancedOnly );
bool IsInInterruptableScenes( CBaseFlex *pActor );
void ResumeActorsScenes( CBaseFlex *pActor, bool bInstancedOnly );
void QueueActorsScenesToResume( CBaseFlex *pActor, bool bInstancedOnly );
bool IsRunningScriptedScene( CBaseFlex *pActor, bool bIgnoreInstancedScenes );
bool IsRunningScriptedSceneAndNotPaused( CBaseFlex *pActor, bool bIgnoreInstancedScenes );
bool IsRunningScriptedSceneWithSpeech( CBaseFlex *pActor, bool bIgnoreInstancedScenes );
bool IsRunningScriptedSceneWithSpeechAndNotPaused( CBaseFlex *pActor, bool bIgnoreInstancedScenes );
private:
struct CRestoreSceneSound
{
CRestoreSceneSound()
{
actor = NULL;
soundname[ 0 ] = NULL;
soundlevel = SNDLVL_NORM;
time_in_past = 0.0f;
}
CHandle< CBaseFlex > actor;
char soundname[ 128 ];
soundlevel_t soundlevel;
float time_in_past;
};
CUtlVector< CHandle< CSceneEntity > > m_ActiveScenes;
CUtlVector< CRestoreSceneSound > m_QueuedSceneSounds;
};
//---------------------------------------------------------
// Save/Restore
//---------------------------------------------------------
BEGIN_DATADESC( CSceneManager )
DEFINE_UTLVECTOR( m_ActiveScenes, FIELD_EHANDLE ),
// DEFINE_FIELD( m_QueuedSceneSounds, CUtlVector < CRestoreSceneSound > ), // Don't save/restore this, it's created and used by OnRestore only
END_DATADESC()
#ifdef DISABLE_DEBUG_HISTORY
#define LocalScene_Printf Scene_Printf
#else
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pFormat -
// ... -
// Output : static void
//-----------------------------------------------------------------------------
void LocalScene_Printf( const char *pFormat, ... )
{
va_list marker;
char msg[8192];
va_start(marker, pFormat);
Q_vsnprintf(msg, sizeof(msg), pFormat, marker);
va_end(marker);
Scene_Printf( "%s", msg );
ADD_DEBUG_HISTORY( HISTORY_SCENE_PRINT, UTIL_VarArgs( "(%0.2f) %s", gpGlobals->curtime, msg ) );
}
#endif
//-----------------------------------------------------------------------------
// Purpose:
// Input : *filename -
// **buffer -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CopySceneFileIntoMemory( char const *pFilename, void **pBuffer, int *pSize )
{
size_t bufSize = scenefilecache->GetSceneBufferSize( pFilename );
if ( bufSize > 0 )
{
*pBuffer = new byte[bufSize];
*pSize = bufSize;
return scenefilecache->GetSceneData( pFilename, (byte *)(*pBuffer), bufSize );
}
*pBuffer = 0;
*pSize = 0;
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void FreeSceneFileMemory( void *buffer )
{
delete[] (byte*) buffer;
}
//-----------------------------------------------------------------------------
// Binary compiled VCDs get their strings from a pool
//-----------------------------------------------------------------------------
class CChoreoStringPool : public IChoreoStringPool
{
public:
short FindOrAddString( const char *pString )
{
// huh?, no compilation at run time, only fetches
Assert( 0 );
return -1;
}
bool GetString( short stringId, char *buff, int buffSize )
{
// fetch from compiled pool
const char *pString = scenefilecache->GetSceneString( stringId );
if ( !pString )
{
V_strncpy( buff, "", buffSize );
return false;
}
V_strncpy( buff, pString, buffSize );
return true;
}
};
CChoreoStringPool g_ChoreoStringPool;
//-----------------------------------------------------------------------------
// Purpose: Singleton scene manager. Created by first placed scene or recreated it it's deleted for some unknown reason
// Output : CSceneManager
//-----------------------------------------------------------------------------
CSceneManager *GetSceneManager()
{
// Create it if it doesn't exist
static CHandle< CSceneManager > s_SceneManager;
if ( s_SceneManager == NULL )
{
s_SceneManager = ( CSceneManager * )CreateEntityByName( "scene_manager" );
Assert( s_SceneManager );
if ( s_SceneManager )
{
s_SceneManager->Spawn();
}
}
Assert( s_SceneManager );
return s_SceneManager;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *player -
//-----------------------------------------------------------------------------
void SceneManager_ClientActive( CBasePlayer *player )
{
Assert( GetSceneManager() );
if ( GetSceneManager() )
{
GetSceneManager()->OnClientActive( player );
}
}
//-----------------------------------------------------------------------------
// Purpose: FIXME, need to deal with save/restore
//-----------------------------------------------------------------------------
class CSceneEntity : public CPointEntity, public IChoreoEventCallback
{
friend class CInstancedSceneEntity;
public:
enum
{
SCENE_ACTION_UNKNOWN = 0,
SCENE_ACTION_CANCEL,
SCENE_ACTION_RESUME,
};
enum
{
SCENE_BUSYACTOR_DEFAULT = 0,
SCENE_BUSYACTOR_WAIT,
SCENE_BUSYACTOR_INTERRUPT,
SCENE_BUSYACTOR_INTERRUPT_CANCEL,
};
DECLARE_CLASS( CSceneEntity, CPointEntity );
DECLARE_SERVERCLASS();
CSceneEntity( void );
~CSceneEntity( void );
// From IChoreoEventCallback
virtual void StartEvent( float currenttime, CChoreoScene *scene, CChoreoEvent *event );
virtual void EndEvent( float currenttime, CChoreoScene *scene, CChoreoEvent *event );
virtual void ProcessEvent( float currenttime, CChoreoScene *scene, CChoreoEvent *event );
virtual bool CheckEvent( float currenttime, CChoreoScene *scene, CChoreoEvent *event );
virtual int UpdateTransmitState();
virtual int ShouldTransmit( const CCheckTransmitInfo *pInfo );
void SetRecipientFilter( IRecipientFilter *filter );
virtual void Activate();
virtual void Precache( void );
virtual void Spawn( void );
virtual void UpdateOnRemove( void );
virtual void OnRestore();
virtual void OnLoaded();
DECLARE_DATADESC();
virtual void OnSceneFinished( bool canceled, bool fireoutput );
virtual void DoThink( float frametime );
virtual void PauseThink( void );
bool IsPlayingBack() const { return m_bIsPlayingBack; }
bool IsPaused() const { return m_bPaused; }
bool IsMultiplayer() const { return m_bMultiplayer; }
bool IsInterruptable();
virtual void ClearInterrupt();
virtual void CheckInterruptCompletion();
virtual bool InterruptThisScene( CSceneEntity *otherScene );
void RequestCompletionNotification( CSceneEntity *otherScene );
virtual void NotifyOfCompletion( CSceneEntity *interruptor );
void AddListManager( CSceneListManager *pManager );
void ClearActivatorTargets( void );
void SetBreakOnNonIdle( bool bBreakOnNonIdle ) { m_bBreakOnNonIdle = bBreakOnNonIdle; }
bool ShouldBreakOnNonIdle( void ) { return m_bBreakOnNonIdle; }
// Inputs
void InputStartPlayback( inputdata_t &inputdata );
void InputPausePlayback( inputdata_t &inputdata );
void InputResumePlayback( inputdata_t &inputdata );
void InputCancelPlayback( inputdata_t &inputdata );
void InputCancelAtNextInterrupt( inputdata_t &inputdata );
void InputPitchShiftPlayback( inputdata_t &inputdata );
void InputTriggerEvent( inputdata_t &inputdata );
// If the scene is playing, finds an actor in the scene who can respond to the specified concept token
void InputInterjectResponse( inputdata_t &inputdata );
// If this scene is waiting on an actor, give up and quit trying.
void InputStopWaitingForActor( inputdata_t &inputdata );
virtual void StartPlayback( void );
virtual void PausePlayback( void );
virtual void ResumePlayback( void );
virtual void CancelPlayback( void );
virtual void PitchShiftPlayback( float fPitch );
virtual void QueueResumePlayback( void );
bool ValidScene() const;
// Scene load/unload
static CChoreoScene *LoadScene( const char *filename, IChoreoEventCallback *pCallback );
void UnloadScene( void );
struct SpeakEventSound_t
{
CUtlSymbol m_Symbol;
float m_flStartTime;
};
static bool SpeakEventSoundLessFunc( const SpeakEventSound_t& lhs, const SpeakEventSound_t& rhs );
bool GetSoundNameForPlayer( CChoreoEvent *event, CBasePlayer *player, char *buf, size_t buflen, CBaseEntity *pActor );
void BuildSortedSpeakEventSoundsPrefetchList(
CChoreoScene *scene,
CUtlSymbolTable& table,
CUtlRBTree< SpeakEventSound_t >& soundnames,
float timeOffset );
void PrefetchSpeakEventSounds( CUtlSymbolTable& table, CUtlRBTree< SpeakEventSound_t >& soundnames );
// Event handlers
virtual void DispatchStartExpression( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event );
virtual void DispatchEndExpression( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event );
virtual void DispatchStartFlexAnimation( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event );
virtual void DispatchEndFlexAnimation( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event );
virtual void DispatchStartGesture( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event );
virtual void DispatchEndGesture( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event );
virtual void DispatchStartLookAt( CChoreoScene *scene, CBaseFlex *actor, CBaseEntity *actor2, CChoreoEvent *event );
virtual void DispatchEndLookAt( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event );
virtual void DispatchStartMoveTo( CChoreoScene *scene, CBaseFlex *actor, CBaseEntity *actor2, CChoreoEvent *event );
virtual void DispatchEndMoveTo( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event );
virtual void DispatchStartSpeak( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event, soundlevel_t iSoundlevel );
virtual void DispatchEndSpeak( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event );
virtual void DispatchStartFace( CChoreoScene *scene, CBaseFlex *actor, CBaseEntity *actor2, CChoreoEvent *event );
virtual void DispatchEndFace( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event );
virtual void DispatchStartSequence( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event );
virtual void DispatchEndSequence( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event );
virtual void DispatchStartSubScene( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event );
virtual void DispatchStartInterrupt( CChoreoScene *scene, CChoreoEvent *event );
virtual void DispatchEndInterrupt( CChoreoScene *scene, CChoreoEvent *event );
virtual void DispatchStartGeneric( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event );
virtual void DispatchEndGeneric( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event );
// NPC can play interstitial vcds (such as responding to the player doing something during a scene)
virtual void DispatchStartPermitResponses( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event );
virtual void DispatchEndPermitResponses( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event );
// Global events
virtual void DispatchProcessLoop( CChoreoScene *scene, CChoreoEvent *event );
virtual void DispatchPauseScene( CChoreoScene *scene, const char *parameters );
virtual void DispatchStopPoint( CChoreoScene *scene, const char *parameters );
virtual float EstimateLength( void );
void CancelIfSceneInvolvesActor( CBaseEntity *pActor );
bool InvolvesActor( CBaseEntity *pActor ); // NOTE: returns false if scene hasn't loaded yet
void GenerateSoundScene( CBaseFlex *pActor, const char *soundname );
virtual float GetPostSpeakDelay() { return 1.0; }
bool HasUnplayedSpeech( void );
bool HasFlexAnimation( void );
void SetCurrentTime( float t, bool forceClientSync );
void InputScriptPlayerDeath( inputdata_t &inputdata );
// Data
public:
string_t m_iszSceneFile;
string_t m_iszResumeSceneFile;
EHANDLE m_hWaitingForThisResumeScene;
bool m_bWaitingForResumeScene;
string_t m_iszTarget1;
string_t m_iszTarget2;
string_t m_iszTarget3;
string_t m_iszTarget4;
string_t m_iszTarget5;
string_t m_iszTarget6;
string_t m_iszTarget7;
string_t m_iszTarget8;
EHANDLE m_hTarget1;
EHANDLE m_hTarget2;
EHANDLE m_hTarget3;
EHANDLE m_hTarget4;
EHANDLE m_hTarget5;
EHANDLE m_hTarget6;
EHANDLE m_hTarget7;
EHANDLE m_hTarget8;
CNetworkVar( bool, m_bIsPlayingBack );
CNetworkVar( bool, m_bPaused );
CNetworkVar( bool, m_bMultiplayer );
CNetworkVar( float, m_flForceClientTime );
float m_flCurrentTime;
float m_flFrameTime;
bool m_bCancelAtNextInterrupt;
float m_fPitch;
bool m_bAutomated;
int m_nAutomatedAction;
float m_flAutomationDelay;
float m_flAutomationTime;
// A pause from an input requires another input to unpause (it's a hard pause)
bool m_bPausedViaInput;
// Waiting for the actor to be able to speak.
bool m_bWaitingForActor;
// Waiting for a point at which we can interrupt our actors
bool m_bWaitingForInterrupt;
bool m_bInterruptedActorsScenes;
bool m_bBreakOnNonIdle;
public:
virtual CBaseFlex *FindNamedActor( int index );
virtual CBaseFlex *FindNamedActor( CChoreoActor *pChoreoActor );
virtual CBaseFlex *FindNamedActor( const char *name );
virtual CBaseEntity *FindNamedEntity( const char *name, CBaseEntity *pActor = NULL, bool bBaseFlexOnly = false, bool bUseClear = false );
CBaseEntity *FindNamedTarget( string_t iszTarget, bool bBaseFlexOnly = false );
virtual CBaseEntity *FindNamedEntityClosest( const char *name, CBaseEntity *pActor = NULL, bool bBaseFlexOnly = false, bool bUseClear = false, const char *pszSecondary = NULL );
private:
CUtlVector< CHandle< CBaseFlex > > m_hActorList;
CUtlVector< CHandle< CBaseEntity > > m_hRemoveActorList;
private:
inline void SetRestoring( bool bRestoring );
// Prevent derived classed from using this!
virtual void Think( void ) {};
void ClearSceneEvents( CChoreoScene *scene, bool canceled );
void ClearSchedules( CChoreoScene *scene );
float GetSoundSystemLatency( void );
void PrecacheScene( CChoreoScene *scene );
CChoreoScene *GenerateSceneForSound( CBaseFlex *pFlexActor, const char *soundname );
bool CheckActors();
void PrefetchAnimBlocks( CChoreoScene *scene );
bool ShouldNetwork() const;
// Set if we tried to async the scene but the FS returned that the data was not loadable
bool m_bSceneMissing;
CChoreoScene *m_pScene;
CNetworkVar( int, m_nSceneStringIndex );
static const ConVar *m_pcvSndMixahead;
COutputEvent m_OnStart;
COutputEvent m_OnCompletion;
COutputEvent m_OnCanceled;
COutputEvent m_OnTrigger1;
COutputEvent m_OnTrigger2;
COutputEvent m_OnTrigger3;
COutputEvent m_OnTrigger4;
COutputEvent m_OnTrigger5;
COutputEvent m_OnTrigger6;
COutputEvent m_OnTrigger7;
COutputEvent m_OnTrigger8;
COutputEvent m_OnTrigger9;
COutputEvent m_OnTrigger10;
COutputEvent m_OnTrigger11;
COutputEvent m_OnTrigger12;
COutputEvent m_OnTrigger13;
COutputEvent m_OnTrigger14;
COutputEvent m_OnTrigger15;
COutputEvent m_OnTrigger16;
int m_nInterruptCount;
bool m_bInterrupted;
CHandle< CSceneEntity > m_hInterruptScene;
bool m_bCompletedEarly;
bool m_bInterruptSceneFinished;
CUtlVector< CHandle< CSceneEntity > > m_hNotifySceneCompletion;
CUtlVector< CHandle< CSceneListManager > > m_hListManagers;
bool m_bRestoring;
bool m_bGenerated;
string_t m_iszSoundName;
CHandle< CBaseFlex > m_hActor;
EHANDLE m_hActivator;
int m_BusyActor;
int m_iPlayerDeathBehavior;
CRecipientFilter *m_pRecipientFilter;
public:
void SetBackground( bool bIsBackground );
bool IsBackground( void );
};
LINK_ENTITY_TO_CLASS( logic_choreographed_scene, CSceneEntity );
LINK_ENTITY_TO_CLASS( scripted_scene, CSceneEntity );
IMPLEMENT_SERVERCLASS_ST_NOBASE( CSceneEntity, DT_SceneEntity )
SendPropInt(SENDINFO(m_nSceneStringIndex),MAX_CHOREO_SCENES_STRING_BITS,SPROP_UNSIGNED),
SendPropBool(SENDINFO(m_bIsPlayingBack)),
SendPropBool(SENDINFO(m_bPaused)),
SendPropBool(SENDINFO(m_bMultiplayer)),
SendPropFloat(SENDINFO(m_flForceClientTime)),
SendPropUtlVector(
SENDINFO_UTLVECTOR( m_hActorList ),
MAX_ACTORS_IN_SCENE, // max elements
SendPropEHandle( NULL, 0 ) ),
END_SEND_TABLE()
BEGIN_DATADESC( CSceneEntity )
// Keys
DEFINE_KEYFIELD( m_iszSceneFile, FIELD_STRING, "SceneFile" ),
DEFINE_KEYFIELD( m_iszResumeSceneFile, FIELD_STRING, "ResumeSceneFile" ),
DEFINE_FIELD( m_hWaitingForThisResumeScene, FIELD_EHANDLE ),
DEFINE_FIELD( m_bWaitingForResumeScene, FIELD_BOOLEAN ),
DEFINE_KEYFIELD( m_iszTarget1, FIELD_STRING, "target1" ),
DEFINE_KEYFIELD( m_iszTarget2, FIELD_STRING, "target2" ),
DEFINE_KEYFIELD( m_iszTarget3, FIELD_STRING, "target3" ),
DEFINE_KEYFIELD( m_iszTarget4, FIELD_STRING, "target4" ),
DEFINE_KEYFIELD( m_iszTarget5, FIELD_STRING, "target5" ),
DEFINE_KEYFIELD( m_iszTarget6, FIELD_STRING, "target6" ),
DEFINE_KEYFIELD( m_iszTarget7, FIELD_STRING, "target7" ),
DEFINE_KEYFIELD( m_iszTarget8, FIELD_STRING, "target8" ),
DEFINE_KEYFIELD( m_BusyActor, FIELD_INTEGER, "busyactor" ),
DEFINE_FIELD( m_hTarget1, FIELD_EHANDLE ),
DEFINE_FIELD( m_hTarget2, FIELD_EHANDLE ),
DEFINE_FIELD( m_hTarget3, FIELD_EHANDLE ),
DEFINE_FIELD( m_hTarget4, FIELD_EHANDLE ),
DEFINE_FIELD( m_hTarget5, FIELD_EHANDLE ),
DEFINE_FIELD( m_hTarget6, FIELD_EHANDLE ),
DEFINE_FIELD( m_hTarget7, FIELD_EHANDLE ),
DEFINE_FIELD( m_hTarget8, FIELD_EHANDLE ),
DEFINE_FIELD( m_bIsPlayingBack, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bPaused, FIELD_BOOLEAN ),
DEFINE_FIELD( m_flCurrentTime, FIELD_FLOAT ), // relative, not absolute time
DEFINE_FIELD( m_flForceClientTime, FIELD_FLOAT ),
DEFINE_FIELD( m_flFrameTime, FIELD_FLOAT ), // last frametime
DEFINE_FIELD( m_bCancelAtNextInterrupt, FIELD_BOOLEAN ),
DEFINE_FIELD( m_fPitch, FIELD_FLOAT ),
DEFINE_FIELD( m_bAutomated, FIELD_BOOLEAN ),
DEFINE_FIELD( m_nAutomatedAction, FIELD_INTEGER ),
DEFINE_FIELD( m_flAutomationDelay, FIELD_FLOAT ),
DEFINE_FIELD( m_flAutomationTime, FIELD_FLOAT ), // relative, not absolute time
DEFINE_FIELD( m_bPausedViaInput, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bWaitingForActor, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bWaitingForInterrupt, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bInterruptedActorsScenes, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bBreakOnNonIdle, FIELD_BOOLEAN ),
DEFINE_UTLVECTOR( m_hActorList, FIELD_EHANDLE ),
DEFINE_UTLVECTOR( m_hRemoveActorList, FIELD_EHANDLE ),
// DEFINE_FIELD( m_pScene, FIELD_XXXX ) // Special processing used for this
// These are set up in the constructor
// DEFINE_FIELD( m_pcvSndMixahead, FIELD_XXXXX ),
// DEFINE_FIELD( m_bRestoring, FIELD_BOOLEAN ),
DEFINE_FIELD( m_nInterruptCount, FIELD_INTEGER ),
DEFINE_FIELD( m_bInterrupted, FIELD_BOOLEAN ),
DEFINE_FIELD( m_hInterruptScene, FIELD_EHANDLE ),
DEFINE_FIELD( m_bCompletedEarly, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bInterruptSceneFinished, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bGenerated, FIELD_BOOLEAN ),
DEFINE_FIELD( m_iszSoundName, FIELD_STRING ),
DEFINE_FIELD( m_hActor, FIELD_EHANDLE ),
DEFINE_FIELD( m_hActivator, FIELD_EHANDLE ),
// DEFINE_FIELD( m_bSceneMissing, FIELD_BOOLEAN ),
DEFINE_UTLVECTOR( m_hNotifySceneCompletion, FIELD_EHANDLE ),
DEFINE_UTLVECTOR( m_hListManagers, FIELD_EHANDLE ),
DEFINE_FIELD( m_bMultiplayer, FIELD_BOOLEAN ),
// DEFINE_FIELD( m_nSceneStringIndex, FIELD_INTEGER ),
// DEFINE_FIELD( m_pRecipientFilter, IRecipientFilter* ), // Multiplayer only
// Inputs
DEFINE_INPUTFUNC( FIELD_VOID, "Start", InputStartPlayback ),
DEFINE_INPUTFUNC( FIELD_VOID, "Pause", InputPausePlayback ),
DEFINE_INPUTFUNC( FIELD_VOID, "Resume", InputResumePlayback ),
DEFINE_INPUTFUNC( FIELD_VOID, "Cancel", InputCancelPlayback ),
DEFINE_INPUTFUNC( FIELD_VOID, "CancelAtNextInterrupt", InputCancelAtNextInterrupt ),
DEFINE_INPUTFUNC( FIELD_FLOAT, "PitchShift", InputPitchShiftPlayback ),
DEFINE_INPUTFUNC( FIELD_STRING, "InterjectResponse", InputInterjectResponse ),
DEFINE_INPUTFUNC( FIELD_VOID, "StopWaitingForActor", InputStopWaitingForActor ),
DEFINE_INPUTFUNC( FIELD_INTEGER, "Trigger", InputTriggerEvent ),
DEFINE_KEYFIELD( m_iPlayerDeathBehavior, FIELD_INTEGER, "onplayerdeath" ),
DEFINE_INPUTFUNC( FIELD_VOID, "ScriptPlayerDeath", InputScriptPlayerDeath ),
// Outputs
DEFINE_OUTPUT( m_OnStart, "OnStart"),
DEFINE_OUTPUT( m_OnCompletion, "OnCompletion"),
DEFINE_OUTPUT( m_OnCanceled, "OnCanceled"),
DEFINE_OUTPUT( m_OnTrigger1, "OnTrigger1"),
DEFINE_OUTPUT( m_OnTrigger2, "OnTrigger2"),
DEFINE_OUTPUT( m_OnTrigger3, "OnTrigger3"),
DEFINE_OUTPUT( m_OnTrigger4, "OnTrigger4"),
DEFINE_OUTPUT( m_OnTrigger5, "OnTrigger5"),
DEFINE_OUTPUT( m_OnTrigger6, "OnTrigger6"),
DEFINE_OUTPUT( m_OnTrigger7, "OnTrigger7"),
DEFINE_OUTPUT( m_OnTrigger8, "OnTrigger8"),
DEFINE_OUTPUT( m_OnTrigger9, "OnTrigger9"),
DEFINE_OUTPUT( m_OnTrigger10, "OnTrigger10"),
DEFINE_OUTPUT( m_OnTrigger11, "OnTrigger11"),
DEFINE_OUTPUT( m_OnTrigger12, "OnTrigger12"),
DEFINE_OUTPUT( m_OnTrigger13, "OnTrigger13"),
DEFINE_OUTPUT( m_OnTrigger14, "OnTrigger14"),
DEFINE_OUTPUT( m_OnTrigger15, "OnTrigger15"),
DEFINE_OUTPUT( m_OnTrigger16, "OnTrigger16"),
END_DATADESC()
const ConVar *CSceneEntity::m_pcvSndMixahead = NULL;
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CSceneEntity::CSceneEntity( void )
{
m_bWaitingForActor = false;
m_bWaitingForInterrupt = false;
m_bInterruptedActorsScenes = false;
m_bIsPlayingBack = false;
m_bPaused = false;
m_bMultiplayer = false;
m_fPitch = 1.0f;
m_iszSceneFile = NULL_STRING;
m_iszResumeSceneFile = NULL_STRING;
m_hWaitingForThisResumeScene = NULL;
m_bWaitingForResumeScene = false;
SetCurrentTime( 0.0f, false );
m_bCancelAtNextInterrupt = false;
m_bAutomated = false;
m_nAutomatedAction = SCENE_ACTION_UNKNOWN;
m_flAutomationDelay = 0.0f;
m_flAutomationTime = 0.0f;
m_bPausedViaInput = false;
ClearInterrupt();
m_pScene = NULL;
m_bCompletedEarly = false;
if ( !m_pcvSndMixahead )
m_pcvSndMixahead = cvar->FindVar( "snd_mixahead" );
m_BusyActor = SCENE_BUSYACTOR_DEFAULT;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CSceneEntity::~CSceneEntity( void )
{
delete m_pRecipientFilter;
m_pRecipientFilter = NULL;
}
//-----------------------------------------------------------------------------
// Purpose: Resets time such that the client version of the .vcd is also updated, if appropriate
// Input : t -
// forceClientSync - forces new timestamp down to client .dll via networking
//-----------------------------------------------------------------------------
void CSceneEntity::SetCurrentTime( float t, bool bForceClientSync )
{
m_flCurrentTime = t;
if ( gpGlobals->maxClients == 1 || bForceClientSync )
{
m_flForceClientTime = t;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSceneEntity::UpdateOnRemove( void )
{
UnloadScene();
BaseClass::UpdateOnRemove();
if ( GetSceneManager() )
{
GetSceneManager()->RemoveSceneEntity( this );
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *actor -
// *soundname -
// Output : CChoreoScene
//-----------------------------------------------------------------------------
CChoreoScene *CSceneEntity::GenerateSceneForSound( CBaseFlex *pFlexActor, const char *soundname )
{
float duration = CBaseEntity::GetSoundDuration( soundname, pFlexActor ? STRING( pFlexActor->GetModelName() ) : NULL );
if( duration <= 0.0f )
{
Warning( "CSceneEntity::GenerateSceneForSound: Couldn't determine duration of %s\n", soundname );
return NULL;
}
CChoreoScene *scene = new CChoreoScene( this );
if ( !scene )
{
Warning( "CSceneEntity::GenerateSceneForSound: Failed to allocated new scene!!!\n" );
}
else
{
scene->SetPrintFunc( LocalScene_Printf );
CChoreoActor *actor = scene->AllocActor();
CChoreoChannel *channel = scene->AllocChannel();
CChoreoEvent *event = scene->AllocEvent();
Assert( actor );
Assert( channel );
Assert( event );
if ( !actor || !channel || !event )
{
Warning( "CSceneEntity::GenerateSceneForSound: Alloc of actor, channel, or event failed!!!\n" );
delete scene;
return NULL;
}
// Set us up the actorz
actor->SetName( "!self" ); // Could be pFlexActor->GetName()?
actor->SetActive( true );
// Set us up the channelz
channel->SetName( STRING( m_iszSceneFile ) );
channel->SetActor( actor );
// Add to actor
actor->AddChannel( channel );
// Set us up the eventz
event->SetType( CChoreoEvent::SPEAK );
event->SetName( soundname );
event->SetParameters( soundname );
event->SetStartTime( 0.0f );
event->SetUsingRelativeTag( false );
event->SetEndTime( duration );
event->SnapTimes();
// Add to channel
channel->AddEvent( event );
// Point back to our owners
event->SetChannel( channel );
event->SetActor( actor );
}
return scene;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSceneEntity::Activate()
{
if ( m_bGenerated && !m_pScene )
{
m_pScene = GenerateSceneForSound( m_hActor, STRING( m_iszSoundName ) );
}
BaseClass::Activate();
if ( GetSceneManager() )
{
GetSceneManager()->AddSceneEntity( this );
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : float
//-----------------------------------------------------------------------------
float CSceneEntity::GetSoundSystemLatency( void )
{
if ( m_pcvSndMixahead )
{
return m_pcvSndMixahead->GetFloat();
}
// Assume 100 msec sound system latency
return SOUND_SYSTEM_LATENCY_DEFAULT;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *scene -
//-----------------------------------------------------------------------------
void CSceneEntity::PrecacheScene( CChoreoScene *scene )
{
Assert( scene );
// Iterate events and precache necessary resources
for ( int i = 0; i < scene->GetNumEvents(); i++ )
{
CChoreoEvent *event = scene->GetEvent( i );
if ( !event )
continue;
// load any necessary data
switch (event->GetType() )
{
default:
break;
case CChoreoEvent::SPEAK:
{
// Defined in SoundEmitterSystem.cpp
// NOTE: The script entries associated with .vcds are forced to preload to avoid
// loading hitches during triggering
PrecacheScriptSound( event->GetParameters() );
if ( event->GetCloseCaptionType() == CChoreoEvent::CC_MASTER &&
event->GetNumSlaves() > 0 )
{
char tok[ CChoreoEvent::MAX_CCTOKEN_STRING ];
if ( event->GetPlaybackCloseCaptionToken( tok, sizeof( tok ) ) )
{
PrecacheScriptSound( tok );
}
}
}
break;
case CChoreoEvent::SUBSCENE:
{
// Only allow a single level of subscenes for now
if ( !scene->IsSubScene() )
{
CChoreoScene *subscene = event->GetSubScene();
if ( !subscene )
{
subscene = LoadScene( event->GetParameters(), this );
subscene->SetSubScene( true );
event->SetSubScene( subscene );
// Now precache it's resources, if any
PrecacheScene( subscene );
}
}
}
break;
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSceneEntity::Precache( void )
{
if ( m_bGenerated )
return;
if ( m_iszSceneFile == NULL_STRING )
return;
if ( m_iszResumeSceneFile != NULL_STRING )
{
PrecacheInstancedScene( STRING( m_iszResumeSceneFile ) );
}
PrecacheInstancedScene( STRING( m_iszSceneFile ) );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pActor -
// *soundname -
//-----------------------------------------------------------------------------
void CSceneEntity::GenerateSoundScene( CBaseFlex *pActor, const char *soundname )
{
m_bGenerated = true;
m_iszSoundName = MAKE_STRING( soundname );
m_hActor = pActor;
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CSceneEntity::HasUnplayedSpeech( void )
{
if ( m_pScene )
return m_pScene->HasUnplayedSpeech();
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CSceneEntity::HasFlexAnimation( void )
{
if ( m_pScene )
return m_pScene->HasFlexAnimation();
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
// Output :
//-----------------------------------------------------------------------------
void CSceneEntity::SetBackground( bool bIsBackground )
{
if ( m_pScene )
{
m_pScene->SetBackground( bIsBackground );
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CSceneEntity::IsBackground( void )
{
if ( m_pScene )
return m_pScene->IsBackground( );
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSceneEntity::OnRestore()
{
BaseClass::OnRestore();
// Fix saved games that have their pitch set to zero
if ( m_fPitch < SCENE_MIN_PITCH || m_fPitch > SCENE_MAX_PITCH )
m_fPitch = 1.0f;
if ( !m_bIsPlayingBack )
return;
if ( !m_pScene )
{
m_pScene = LoadScene( STRING( m_iszSceneFile ), this );
if ( !m_pScene )
{
m_bSceneMissing = true;
return;
}
OnLoaded();
if ( ShouldNetwork() )
{
m_nSceneStringIndex = g_pStringTableClientSideChoreoScenes->AddString( CBaseEntity::IsServer(), STRING( m_iszSceneFile ) );
}
UpdateTransmitState();
}
m_bSceneMissing = false;
int i;
for ( i = 0 ; i < m_pScene->GetNumActors(); i++ )
{
CBaseFlex *pTestActor = FindNamedActor( i );
if ( !pTestActor )
continue;
if ( !pTestActor->MyCombatCharacterPointer() )
continue;
// Needed?
//if ( !pTestActor->MyCombatCharacterPointer()->IsAlive() )
// return;
pTestActor->StartChoreoScene( m_pScene );
}
float dt = SCENE_THINK_INTERVAL;
bool paused = m_bPaused;
m_bPaused = false;
// roll back slightly so that pause events still trigger
m_pScene->ResetSimulation( true, m_flCurrentTime - SCENE_THINK_INTERVAL, m_flCurrentTime );
m_pScene->SetTime( m_flCurrentTime - SCENE_THINK_INTERVAL );
SetCurrentTime( m_flCurrentTime, true );
// Robin: This causes a miscount of any interrupt events in the scene.
// All the variables are saved/restored properly, so we can safely leave them alone.
//ClearInterrupt();
SetRestoring( true );
DoThink( dt );
SetRestoring( false );
if ( paused )
{
PausePlayback();
}
NetworkProp()->NetworkStateForceUpdate();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CSceneEntity::SetRestoring( bool bRestoring )
{
m_bRestoring = bRestoring;
if ( m_pScene )
{
m_pScene->SetRestoring( bRestoring );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSceneEntity::Spawn( void )
{
Precache();
}
void CSceneEntity::PauseThink( void )
{
if ( !m_pScene )
return;
// Stay paused if pause occurred from interrupt
if ( m_bInterrupted )
return;
// If entity I/O paused the scene, then it'll have to resume/cancel the scene...
if ( m_bPausedViaInput )
{
// If we're waiting for a resume scene to finish, continue when it's done
if ( m_bWaitingForResumeScene && !m_hWaitingForThisResumeScene )
{
// Resume scene has finished, stop waiting for it
m_bWaitingForResumeScene = false;
}
else
{
return;
}
}
if ( !m_bAutomated )
{
// FIXME: Game code should check for AI waiting conditions being met, etc.
//
//
//
bool bAllFinished = m_pScene->CheckEventCompletion( );
if ( bAllFinished )
{
// Perform action
switch ( m_nAutomatedAction )
{
case SCENE_ACTION_RESUME:
ResumePlayback();
break;
case SCENE_ACTION_CANCEL:
LocalScene_Printf( "%s : PauseThink canceling playback\n", STRING( m_iszSceneFile ) );
CancelPlayback();
break;
default:
ResumePlayback();
break;
}
// Reset
m_bAutomated = false;
m_nAutomatedAction = SCENE_ACTION_UNKNOWN;
m_flAutomationTime = 0.0f;
m_flAutomationDelay = 0.0f;
m_bPausedViaInput = false;
}
return;
}
// Otherwise, see if resume/cancel is automatic and act accordingly if enough time
// has passed
m_flAutomationTime += (gpGlobals->frametime);
if ( m_flAutomationDelay > 0.0f &&
m_flAutomationTime < m_flAutomationDelay )
return;
// Perform action
switch ( m_nAutomatedAction )
{
case SCENE_ACTION_RESUME:
LocalScene_Printf( "%s : Automatically resuming playback\n", STRING( m_iszSceneFile ) );
ResumePlayback();
break;
case SCENE_ACTION_CANCEL:
LocalScene_Printf( "%s : Automatically canceling playback\n", STRING( m_iszSceneFile ) );
CancelPlayback();
break;
default:
LocalScene_Printf( "%s : Unknown action %i, automatically resuming playback\n", STRING( m_iszSceneFile ), m_nAutomatedAction );
ResumePlayback();
break;
}
// Reset
m_bAutomated = false;
m_nAutomatedAction = SCENE_ACTION_UNKNOWN;
m_flAutomationTime = 0.0f;
m_flAutomationDelay = 0.0f;
m_bPausedViaInput = false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSceneEntity::DispatchPauseScene( CChoreoScene *scene, const char *parameters )
{
// Don't pause during restore, since we'll be restoring the pause state already
if ( m_bRestoring )
return;
// FIXME: Hook this up to AI, etc. somehow, perhaps poll each actor for conditions using
// scene resume condition iterator
PausePlayback();
char token[1024];
m_bPausedViaInput = false;
m_bAutomated = false;
m_nAutomatedAction = SCENE_ACTION_UNKNOWN;
m_flAutomationDelay = 0.0f;
m_flAutomationTime = 0.0f;
// Check for auto resume/cancel
const char *buffer = parameters;
buffer = engine->ParseFile( buffer, token, sizeof( token ) );
if ( !stricmp( token, "automate" ) )
{
buffer = engine->ParseFile( buffer, token, sizeof( token ) );
if ( !stricmp( token, "Cancel" ) )
{
m_nAutomatedAction = SCENE_ACTION_CANCEL;
}
else if ( !stricmp( token, "Resume" ) )
{
m_nAutomatedAction = SCENE_ACTION_RESUME;
}
if ( m_nAutomatedAction != SCENE_ACTION_UNKNOWN )
{
buffer = engine->ParseFile( buffer, token, sizeof( token ) );
m_flAutomationDelay = (float)atof( token );
if ( m_flAutomationDelay > 0.0f )
{
// Success
m_bAutomated = true;
m_flAutomationTime = 0.0f;
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *scene -
// *event -
//-----------------------------------------------------------------------------
void CSceneEntity::DispatchProcessLoop( CChoreoScene *scene, CChoreoEvent *event )
{
// Don't restore this event since it's implied in the current "state" of the scene timer, etc.
if ( m_bRestoring )
return;
Assert( scene );
Assert( event->GetType() == CChoreoEvent::LOOP );
float backtime = (float)atof( event->GetParameters() );
bool process = true;
int counter = event->GetLoopCount();
if ( counter != -1 )
{
int remaining = event->GetNumLoopsRemaining();
if ( remaining <= 0 )
{
process = false;
}
else
{
event->SetNumLoopsRemaining( --remaining );
}
}
if ( !process )
return;
scene->LoopToTime( backtime );
SetCurrentTime( backtime, true );
}
//-----------------------------------------------------------------------------
// Purpose: Flag the scene as already "completed"
// Input : *scene -
// *parameters -
//-----------------------------------------------------------------------------
void CSceneEntity::DispatchStopPoint( CChoreoScene *scene, const char *parameters )
{
if ( m_bCompletedEarly )
{
Assert( 0 );
Warning( "Scene '%s' with two stop point events!\n", STRING( m_iszSceneFile ) );
return;
}
// Fire completion trigger early
m_bCompletedEarly = true;
m_OnCompletion.FireOutput( this, this, 0 );
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CSceneEntity::IsInterruptable()
{
return ( m_nInterruptCount > 0 ) ? true : false;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *scene -
// *actor -
// *event -
//-----------------------------------------------------------------------------
void CSceneEntity::DispatchStartInterrupt( CChoreoScene *scene, CChoreoEvent *event )
{
// Don't re-interrupt during restore
if ( m_bRestoring )
return;
// If we're supposed to cancel at our next interrupt point, cancel now
if ( m_bCancelAtNextInterrupt )
{
m_bCancelAtNextInterrupt = false;
LocalScene_Printf( "%s : cancelled via interrupt\n", STRING( m_iszSceneFile ) );
CancelPlayback();
return;
}
++m_nInterruptCount;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *scene -
// *actor -
// *event -
//-----------------------------------------------------------------------------
void CSceneEntity::DispatchEndInterrupt( CChoreoScene *scene, CChoreoEvent *event )
{
// Don't re-interrupt during restore
if ( m_bRestoring )
return;
--m_nInterruptCount;
if ( m_nInterruptCount < 0 )
{
m_nInterruptCount = 0;
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *actor -
// *event -
//-----------------------------------------------------------------------------
void CSceneEntity::DispatchStartExpression( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event )
{
actor->AddSceneEvent( scene, event );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *actor -
// *event -
//-----------------------------------------------------------------------------
void CSceneEntity::DispatchEndExpression( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event )
{
actor->RemoveSceneEvent( scene, event, false );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *actor -
// *event -
//-----------------------------------------------------------------------------
void CSceneEntity::DispatchStartFlexAnimation( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event )
{
actor->AddSceneEvent( scene, event );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *actor -
// *event -
//-----------------------------------------------------------------------------
void CSceneEntity::DispatchEndFlexAnimation( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event )
{
actor->RemoveSceneEvent( scene, event, false );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *actor -
// *parameters -
//-----------------------------------------------------------------------------
void CSceneEntity::DispatchStartGesture( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event )
{
// Ingore null gestures
if ( !Q_stricmp( event->GetName(), "NULL" ) )
return;
actor->AddSceneEvent( scene, event);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *actor -
// *parameters -
//-----------------------------------------------------------------------------
void CSceneEntity::DispatchEndGesture( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event )
{
// Ingore null gestures
if ( !Q_stricmp( event->GetName(), "NULL" ) )
return;
actor->RemoveSceneEvent( scene, event, m_bRestoring );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *actor -
// *parameters -
//-----------------------------------------------------------------------------
void CSceneEntity::DispatchStartGeneric( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event )
{
CBaseEntity *pTarget = FindNamedEntity( event->GetParameters2( ) );
actor->AddSceneEvent( scene, event, pTarget );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *actor -
// *parameters -
//-----------------------------------------------------------------------------
void CSceneEntity::DispatchEndGeneric( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event )
{
actor->RemoveSceneEvent( scene, event, m_bRestoring );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *actor -
// *actor2 -
//-----------------------------------------------------------------------------
void CSceneEntity::DispatchStartLookAt( CChoreoScene *scene, CBaseFlex *actor, CBaseEntity *actor2, CChoreoEvent *event )
{
actor->AddSceneEvent( scene, event, actor2 );
}
void CSceneEntity::DispatchEndLookAt( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event )
{
actor->RemoveSceneEvent( scene, event, m_bRestoring );
}
//-----------------------------------------------------------------------------
// Purpose: Move to spot/actor
// FIXME: Need to allow this to take arbitrary amount of time and pause playback
// while waiting for actor to move into position
// Input : *actor -
// *parameters -
//-----------------------------------------------------------------------------
void CSceneEntity::DispatchStartMoveTo( CChoreoScene *scene, CBaseFlex *actor, CBaseEntity *actor2, CChoreoEvent *event )
{
actor->AddSceneEvent( scene, event, actor2 );
}
void CSceneEntity::DispatchEndMoveTo( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event )
{
actor->RemoveSceneEvent( scene, event, m_bRestoring );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *token -
// listener -
// soundorigins -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool AttenuateCaption( const char *token, const Vector& listener, CUtlVector< Vector >& soundorigins )
{
if ( scene_maxcaptionradius.GetFloat() <= 0.0f )
{
return false;
}
int c = soundorigins.Count();
if ( c <= 0 )
{
return false;
}
float maxdistSqr = scene_maxcaptionradius.GetFloat() * scene_maxcaptionradius.GetFloat();
for ( int i = 0; i < c; ++i )
{
const Vector& org = soundorigins[ i ];
float distSqr = ( org - listener ).LengthSqr();
if ( distSqr <= maxdistSqr )
{
return false;
}
}
// All sound sources too far, don't show caption...
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *event - which event
// player - which recipient
// buf, buflen: where to put the data
// Output : Returns true if the sound should be played/prefetched
//-----------------------------------------------------------------------------
bool CSceneEntity::GetSoundNameForPlayer( CChoreoEvent *event, CBasePlayer *player, char *buf, size_t buflen, CBaseEntity *pActor )
{
Assert( event );
Assert( player );
Assert( buf );
Assert( buflen > 0 );
bool ismasterevent = true;
char tok[ CChoreoEvent::MAX_CCTOKEN_STRING ];
bool validtoken = false;
tok[ 0 ] = 0;
if ( event->GetCloseCaptionType() == CChoreoEvent::CC_SLAVE ||
event->GetCloseCaptionType() == CChoreoEvent::CC_DISABLED )
{
ismasterevent = false;
}
else
{
validtoken = event->GetPlaybackCloseCaptionToken( tok, sizeof( tok ) );
}
const char* pchToken = "";
if ( pActor && pActor->IsPlayer() )
{
pchToken = dynamic_cast< CBasePlayer* >( pActor )->GetSceneSoundToken();
}
// Copy the sound name
CopySoundNameWithModifierToken( buf, event->GetParameters(), buflen, pchToken );
bool usingEnglish = true;
if ( !IsXbox() )
{
char const *cvarvalue = engine->GetClientConVarValue( player->entindex(), "english" );
if ( cvarvalue && *cvarvalue && Q_atoi( cvarvalue ) != 1 )
{
usingEnglish = false;
}
}
// This makes it like they are running in another language
if ( scene_forcecombined.GetBool() )
{
usingEnglish = false;
}
if ( usingEnglish )
{
// English sounds always play
return true;
}
if ( ismasterevent )
{
// Master event sounds always play too (master will be the combined .wav)
if ( validtoken )
{
Q_strncpy( buf, tok, buflen );
}
return true;
}
// Slave events don't play any sound...
return false;
}
//-----------------------------------------------------------------------------
// Purpose: Playback sound file that contains phonemes
// Input : *actor -
// *parameters -
//-----------------------------------------------------------------------------
void CSceneEntity::DispatchStartSpeak( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event, soundlevel_t iSoundlevel )
{
// Emit sound
if ( actor )
{
CPASAttenuationFilter filter( actor );
if ( m_pRecipientFilter )
{
int filterCount = filter.GetRecipientCount();
int recipientPlayerCount = m_pRecipientFilter->GetRecipientCount();
for ( int i = filterCount-1; i >= 0; --i )
{
int playerindex = filter.GetRecipientIndex( i );
bool bFound = false;
for ( int j = 0; j < recipientPlayerCount; ++j )
{
if ( m_pRecipientFilter->GetRecipientIndex(j) == playerindex )
{
bFound = true;
break;
}
}
if ( !bFound )
{
filter.RemoveRecipientByPlayerIndex( playerindex );
}
}
}
float time_in_past = m_flCurrentTime - event->GetStartTime() ;
float soundtime = gpGlobals->curtime - time_in_past;
if ( m_bRestoring )
{
// Need to queue sounds on restore because the player has not yet connected
GetSceneManager()->QueueRestoredSound( actor, event->GetParameters(), iSoundlevel, time_in_past );
return;
}
// Add padding to prevent any other talker talking right after I'm done, because I might
// be continuing speaking with another scene.
float flDuration = event->GetDuration() - time_in_past;
CAI_BaseActor *pBaseActor = dynamic_cast<CAI_BaseActor*>(actor);
if ( pBaseActor )
{
pBaseActor->NoteSpeaking( flDuration, GetPostSpeakDelay() );
}
else if ( actor->IsNPC() )
{
GetSpeechSemaphore( actor->MyNPCPointer() )->Acquire( flDuration + GetPostSpeakDelay(), actor );
}
EmitSound_t es;
es.m_nChannel = CHAN_VOICE;
es.m_flVolume = 1;
es.m_SoundLevel = iSoundlevel;
// Only specify exact delay in single player
es.m_flSoundTime = ( gpGlobals->maxClients == 1 ) ? soundtime : 0.0f;
if ( scene->ShouldIgnorePhonemes() )
{
es.m_nFlags |= SND_IGNORE_PHONEMES;
}
if ( actor->GetSpecialDSP() != 0 )
{
es.m_nSpecialDSP = actor->GetSpecialDSP();
}
// No CC since we do it manually
// FIXME: This will change
es.m_bEmitCloseCaption = false;
int c = filter.GetRecipientCount();
for ( int i = 0; i < c; ++i )
{
int playerindex = filter.GetRecipientIndex( i );
CBasePlayer *player = UTIL_PlayerByIndex( playerindex );
if ( !player )
continue;
CSingleUserRecipientFilter filter2( player );
char soundname[ 512 ];
if ( !GetSoundNameForPlayer( event, player, soundname, sizeof( soundname ), actor ) )
{
continue;
}
es.m_pSoundName = soundname;
// keep track of the last few sounds played for bug reports
speechListSounds[ speechListIndex ].time = gpGlobals->curtime;
Q_strncpy( speechListSounds[ speechListIndex ].name, soundname, sizeof( speechListSounds[ 0 ].name ) );
Q_strncpy( speechListSounds[ speechListIndex ].sceneName, ( scene ) ? scene->GetFilename() : "", sizeof( speechListSounds[ 0 ].sceneName ) );
speechListIndex++;
if ( speechListIndex >= SPEECH_LIST_MAX_SOUNDS )
{
speechListIndex = 0;
}
// Warning( "Speak %s\n", soundname );
if ( m_fPitch != 1.0f )
{
if ( es.m_nPitch )
es.m_nPitch = static_cast<float>( es.m_nPitch ) * m_fPitch;
else
es.m_nPitch = 100.0f * m_fPitch;
es.m_nFlags |= SND_CHANGE_PITCH;
}
EmitSound( filter2, actor->entindex(), es );
actor->AddSceneEvent( scene, event );
}
// Close captioning only on master token no matter what...
if ( event->GetCloseCaptionType() == CChoreoEvent::CC_MASTER )
{
char tok[ CChoreoEvent::MAX_CCTOKEN_STRING ];
bool validtoken = event->GetPlaybackCloseCaptionToken( tok, sizeof( tok ) );
if ( validtoken )
{
char lowercase[ 256 ];
Q_strncpy( lowercase, tok, sizeof( lowercase ) );
Q_strlower( lowercase );
// Remove any players who don't want close captions
CBaseEntity::RemoveRecipientsIfNotCloseCaptioning( filter );
// Certain events are marked "don't attenuate", (breencast), skip those here
if ( !event->IsSuppressingCaptionAttenuation() &&
( filter.GetRecipientCount() > 0 ) )
{
int c = filter.GetRecipientCount();
for ( int i = c - 1 ; i >= 0; --i )
{
CBasePlayer *player = UTIL_PlayerByIndex( filter.GetRecipientIndex( i ) );
if ( !player )
continue;
Vector playerOrigin = player->GetAbsOrigin();
if ( AttenuateCaption( lowercase, playerOrigin, es.m_UtlVecSoundOrigin ) )
{
// If the player has a view entity, measure the distance to that
if ( !player->GetViewEntity() || AttenuateCaption( lowercase, player->GetViewEntity()->GetAbsOrigin(), es.m_UtlVecSoundOrigin ) )
{
filter.RemoveRecipient( player );
}
}
}
}
// Anyone left?
if ( filter.GetRecipientCount() > 0 )
{
float endtime = event->GetLastSlaveEndTime();
float durationShort = event->GetDuration();
float durationLong = endtime - event->GetStartTime();
float duration = MAX( durationShort, durationLong );
byte byteflags = CLOSE_CAPTION_WARNIFMISSING; // warnifmissing
/*
// Never for .vcds...
if ( fromplayer )
{
byteflags |= CLOSE_CAPTION_FROMPLAYER;
}
*/
char const *pszActorModel = STRING( actor->GetModelName() );
gender_t gender = soundemitterbase->GetActorGender( pszActorModel );
if ( gender == GENDER_MALE )
{
byteflags |= CLOSE_CAPTION_GENDER_MALE;
}
else if ( gender == GENDER_FEMALE )
{
byteflags |= CLOSE_CAPTION_GENDER_FEMALE;
}
// Send caption and duration hint down to client
UserMessageBegin( filter, "CloseCaption" );
WRITE_STRING( lowercase );
WRITE_SHORT( MIN( 255, (int)( duration * 10.0f ) ) );
WRITE_BYTE( byteflags ); // warn on missing
MessageEnd();
}
}
}
}
}
void CSceneEntity::DispatchEndSpeak( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event )
{
actor->RemoveSceneEvent( scene, event, m_bRestoring );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *actor -
// *actor2 -
//-----------------------------------------------------------------------------
void CSceneEntity::DispatchStartFace( CChoreoScene *scene, CBaseFlex *actor, CBaseEntity *actor2, CChoreoEvent *event )
{
actor->AddSceneEvent( scene, event, actor2 );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *actor -
// *actor2 -
//-----------------------------------------------------------------------------
void CSceneEntity::DispatchEndFace( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event )
{
actor->RemoveSceneEvent( scene, event, m_bRestoring );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *actor -
//-----------------------------------------------------------------------------
void CSceneEntity::DispatchStartSequence( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event )
{
actor->AddSceneEvent( scene, event );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *actor -
//-----------------------------------------------------------------------------
void CSceneEntity::DispatchEndSequence( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event )
{
actor->RemoveSceneEvent( scene, event, m_bRestoring );
}
//-----------------------------------------------------------------------------
// Purpose: NPC can play interstitial vcds (such as responding to the player doing something during a scene)
// Input : *scene -
// *actor -
// *event -
//-----------------------------------------------------------------------------
void CSceneEntity::DispatchStartPermitResponses( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event )
{
actor->SetPermitResponse( gpGlobals->curtime + event->GetDuration() );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *scene -
// *actor -
// *event -
//-----------------------------------------------------------------------------
void CSceneEntity::DispatchEndPermitResponses( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event )
{
actor->SetPermitResponse( 0 );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
float CSceneEntity::EstimateLength( void )
{
if ( !m_pScene )
{
return GetSceneDuration( STRING( m_iszSceneFile ) );
}
return m_pScene->FindStopTime();
}
//-----------------------------------------------------------------------------
// Purpose:
// NOTE: returns false if scene hasn't loaded yet
//-----------------------------------------------------------------------------
void CSceneEntity::CancelIfSceneInvolvesActor( CBaseEntity *pActor )
{
if ( InvolvesActor( pActor ) )
{
LocalScene_Printf( "%s : cancelled for '%s'\n", STRING( m_iszSceneFile ), pActor->GetDebugName() );
CancelPlayback();
}
}
//-----------------------------------------------------------------------------
// Purpose:
// NOTE: returns false if scene hasn't loaded yet
//-----------------------------------------------------------------------------
bool CSceneEntity::InvolvesActor( CBaseEntity *pActor )
{
if ( !m_pScene )
return false;
int i;
for ( i = 0 ; i < m_pScene->GetNumActors(); i++ )
{
CBaseFlex *pTestActor = FindNamedActor( i );
if ( !pTestActor )
continue;
if ( pTestActor == pActor )
return true;
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSceneEntity::DoThink( float frametime )
{
CheckInterruptCompletion();
if ( m_bWaitingForActor || m_bWaitingForInterrupt )
{
// Try to start playback.
StartPlayback();
}
if ( !m_pScene )
return;
if ( !m_bIsPlayingBack )
return;
// catch bad pitch shifting from old save games
Assert( m_fPitch >= SCENE_MIN_PITCH && m_fPitch <= SCENE_MAX_PITCH );
m_fPitch = clamp( m_fPitch, SCENE_MIN_PITCH, SCENE_MAX_PITCH );
if ( m_bPaused )
{
PauseThink();
return;
}
// Msg("%.2f %s\n", gpGlobals->curtime, STRING( m_iszSceneFile ) );
//Msg( "SV: %d, %f for %s\n", gpGlobals->tickcount, m_flCurrentTime, m_pScene->GetFilename() );
m_flFrameTime = frametime;
m_pScene->SetSoundFileStartupLatency( GetSoundSystemLatency() );
// Tell scene to go
m_pScene->Think( m_flCurrentTime );
// Did we get to the end
if ( !m_bPaused )
{
// Drive simulation time for scene
SetCurrentTime( m_flCurrentTime + m_flFrameTime * m_fPitch, false );
if ( m_pScene->SimulationFinished() )
{
OnSceneFinished( false, true );
// Stop them from doing anything special
ClearSchedules( m_pScene );
}
}
else
{
// Drive simulation time for scene
SetCurrentTime( m_pScene->GetTime(), true );
}
}
//-----------------------------------------------------------------------------
// Purpose: Input handlers
//-----------------------------------------------------------------------------
void CSceneEntity::InputStartPlayback( inputdata_t &inputdata )
{
// Already playing, ignore
if ( m_bIsPlayingBack )
return;
// Already waiting on someone.
if ( m_bWaitingForActor || m_bWaitingForInterrupt )
return;
ClearActivatorTargets();
m_hActivator = inputdata.pActivator;
StartPlayback();
}
void CSceneEntity::InputPausePlayback( inputdata_t &inputdata )
{
PausePlayback();
m_bPausedViaInput = true;
}
void CSceneEntity::InputResumePlayback( inputdata_t &inputdata )
{
ResumePlayback();
}
void CSceneEntity::InputCancelPlayback( inputdata_t &inputdata )
{
LocalScene_Printf( "%s : cancelled via input\n", STRING( m_iszSceneFile ) );
CancelPlayback();
}
void CSceneEntity::InputScriptPlayerDeath( inputdata_t &inputdata )
{
if ( m_iPlayerDeathBehavior == SCRIPT_CANCEL )
{
LocalScene_Printf( "%s : cancelled via player death\n", STRING( m_iszSceneFile ) );
CancelPlayback();
}
}
void CSceneEntity::InputCancelAtNextInterrupt( inputdata_t &inputdata )
{
// If we're currently in an interruptable point, interrupt immediately
if ( IsInterruptable() )
{
LocalScene_Printf( "%s : cancelled via input at interrupt point\n", STRING( m_iszSceneFile ) );
CancelPlayback();
return;
}
// Otherwise, cancel when we next hit an interrupt point
m_bCancelAtNextInterrupt = true;
}
void CSceneEntity::InputPitchShiftPlayback( inputdata_t &inputdata )
{
PitchShiftPlayback( inputdata.value.Float() );
}
void CSceneEntity::InputTriggerEvent( inputdata_t &inputdata )
{
CBaseEntity *pActivator = this; // at some point, find this from the inputdata
switch ( inputdata.value.Int() )
{
case 1:
m_OnTrigger1.FireOutput( pActivator, this, 0 );
break;
case 2:
m_OnTrigger2.FireOutput( pActivator, this, 0 );
break;
case 3:
m_OnTrigger3.FireOutput( pActivator, this, 0 );
break;
case 4:
m_OnTrigger4.FireOutput( pActivator, this, 0 );
break;
case 5:
m_OnTrigger5.FireOutput( pActivator, this, 0 );
break;
case 6:
m_OnTrigger6.FireOutput( pActivator, this, 0 );
break;
case 7:
m_OnTrigger7.FireOutput( pActivator, this, 0 );
break;
case 8:
m_OnTrigger8.FireOutput( pActivator, this, 0 );
break;
case 9:
m_OnTrigger9.FireOutput( pActivator, this, 0 );
break;
case 10:
m_OnTrigger10.FireOutput( pActivator, this, 0 );
break;
case 11:
m_OnTrigger11.FireOutput( pActivator, this, 0 );
break;
case 12:
m_OnTrigger12.FireOutput( pActivator, this, 0 );
break;
case 13:
m_OnTrigger13.FireOutput( pActivator, this, 0 );
break;
case 14:
m_OnTrigger14.FireOutput( pActivator, this, 0 );
break;
case 15:
m_OnTrigger15.FireOutput( pActivator, this, 0 );
break;
case 16:
m_OnTrigger16.FireOutput( pActivator, this, 0 );
break;
}
}
struct NPCInterjection
{
AI_Response *response;
CAI_BaseActor *npc;
};
//-----------------------------------------------------------------------------
// Purpose:
// Input : &inputdata -
//-----------------------------------------------------------------------------
void CSceneEntity::InputInterjectResponse( inputdata_t &inputdata )
{
// Not currently playing a scene
if ( !m_pScene )
{
return;
}
CUtlVector< CAI_BaseActor * > candidates;
int i;
for ( i = 0 ; i < m_pScene->GetNumActors(); i++ )
{
CBaseFlex *pTestActor = FindNamedActor( i );
if ( !pTestActor )
continue;
CAI_BaseActor *pBaseActor = dynamic_cast<CAI_BaseActor*>(pTestActor);
if ( !pBaseActor )
continue;
if ( !pBaseActor->IsAlive() )
continue;
candidates.AddToTail( pBaseActor );
}
int c = candidates.Count();
if ( !c )
{
return;
}
int useIndex = 0;
if ( !m_bIsPlayingBack )
{
// Use any actor if not playing a scene
useIndex = RandomInt( 0, c - 1 );
}
else
{
CUtlVector< NPCInterjection > validResponses;
char modifiers[ 512 ];
Q_snprintf( modifiers, sizeof( modifiers ), "scene:%s", STRING( GetEntityName() ) );
for ( int i = 0; i < c; i++ )
{
CAI_BaseActor *npc = candidates[ i ];
Assert( npc );
AI_Response *response = npc->SpeakFindResponse( inputdata.value.String(), modifiers );
if ( !response )
continue;
float duration = npc->GetResponseDuration( response );
// Couldn't look it up
if ( duration <= 0.0f )
continue;
if ( !npc->PermitResponse( duration ) )
{
delete response;
continue;
}
//
NPCInterjection inter;
inter.response = response;
inter.npc = npc;
validResponses.AddToTail( inter );
}
int rcount = validResponses.Count();
if ( rcount >= 1 )
{
int slot = RandomInt( 0, rcount - 1 );
for ( int i = 0; i < rcount; i++ )
{
NPCInterjection *pInterjection = &validResponses[ i ];
if ( i == slot )
{
pInterjection->npc->SpeakDispatchResponse( inputdata.value.String(), pInterjection->response );
}
else
{
delete pInterjection->response;
}
}
}
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CSceneEntity::InputStopWaitingForActor( inputdata_t &inputdata )
{
if( m_bIsPlayingBack )
{
// Already started.
return;
}
m_bWaitingForActor = false;
}
bool CSceneEntity::CheckActors()
{
Assert( m_pScene );
if ( !m_pScene )
return false;
int i;
for ( i = 0 ; i < m_pScene->GetNumActors(); i++ )
{
CBaseFlex *pTestActor = FindNamedActor( i );
if ( !pTestActor )
continue;
if ( !pTestActor->MyCombatCharacterPointer() )
continue;
if ( !pTestActor->MyCombatCharacterPointer()->IsAlive() )
return false;
if ( m_BusyActor == SCENE_BUSYACTOR_WAIT )
{
CAI_BaseNPC *pActor = pTestActor->MyNPCPointer();
if ( pActor )
{
bool bShouldWait = false;
if ( hl2_episodic.GetBool() )
{
// Episodic waits until the NPC is fully finished with any .vcd with speech in it
if ( IsRunningScriptedSceneWithSpeech( pActor ) )
{
bShouldWait = true;
}
#ifdef HL2_EPISODIC
// HACK: Alyx cannot play scenes when she's in the middle of transitioning
if ( pActor->IsInAVehicle() )
{
CNPC_Alyx *pAlyx = dynamic_cast<CNPC_Alyx *>(pActor);
if ( pAlyx != NULL && ( pAlyx->GetPassengerState() == PASSENGER_STATE_ENTERING || pAlyx->GetPassengerState() == PASSENGER_STATE_EXITING ) )
{
bShouldWait = true;
}
}
#endif // HL2_EPISODIC
}
if ( pActor->GetExpresser() && pActor->GetExpresser()->IsSpeaking() )
{
bShouldWait = true;
}
if ( bShouldWait )
{
// One of the actors for this scene is talking already.
// Try again next think.
m_bWaitingForActor = true;
return false;
}
}
}
else if ( m_BusyActor == SCENE_BUSYACTOR_INTERRUPT || m_BusyActor == SCENE_BUSYACTOR_INTERRUPT_CANCEL )
{
CBaseCombatCharacter *pActor = pTestActor->MyCombatCharacterPointer();
if ( pActor && !IsInInterruptableScenes( pActor ) )
{
// One of the actors is in a scene that's not at an interrupt point.
// Wait until the scene finishes or an interrupt point is reached.
m_bWaitingForInterrupt = true;
return false;
}
if ( m_BusyActor == SCENE_BUSYACTOR_INTERRUPT_CANCEL )
{
// Cancel existing scenes
RemoveActorFromScriptedScenes( pActor, false );
}
else
{
// Pause existing scenes
PauseActorsScriptedScenes( pActor, false );
m_bInterruptedActorsScenes = true;
}
}
pTestActor->StartChoreoScene( m_pScene );
}
return true;
}
#if !defined( _RETAIL )
static ConVar scene_async_prefetch_spew( "scene_async_prefetch_spew", "0", 0, "Display async .ani file loading info." );
#endif
void CSceneEntity::PrefetchAnimBlocks( CChoreoScene *scene )
{
Assert( scene );
// Build a fast lookup, too
CUtlMap< CChoreoActor *, CBaseFlex *> actorMap( 0, 0, DefLessFunc( CChoreoActor * ) );
int spew =
#if !defined( _RETAIL )
scene_async_prefetch_spew.GetInt();
#else
0;
#endif
int resident = 0;
int checked = 0;
// Iterate events and precache necessary resources
for ( int i = 0; i < scene->GetNumEvents(); i++ )
{
CChoreoEvent *event = scene->GetEvent( i );
if ( !event )
continue;
// load any necessary data
switch ( event->GetType() )
{
default:
break;
case CChoreoEvent::SEQUENCE:
case CChoreoEvent::GESTURE:
{
CChoreoActor *actor = event->GetActor();
if ( actor )
{
CBaseFlex *pActor = NULL;
int idx = actorMap.Find( actor );
if ( idx == actorMap.InvalidIndex() )
{
pActor = FindNamedActor( actor );
idx = actorMap.Insert( actor, pActor );
}
else
{
pActor = actorMap[ idx ];
}
if ( pActor )
{
int seq = pActor->LookupSequence( event->GetParameters() );
if ( seq >= 0 )
{
CStudioHdr *pStudioHdr = pActor->GetModelPtr();
if ( pStudioHdr )
{
// Now look up the animblock
mstudioseqdesc_t &seqdesc = pStudioHdr->pSeqdesc( seq );
for ( int i = 0 ; i < seqdesc.groupsize[ 0 ] ; ++i )
{
for ( int j = 0; j < seqdesc.groupsize[ 1 ]; ++j )
{
int animation = seqdesc.anim( i, j );
int baseanimation = pStudioHdr->iRelativeAnim( seq, animation );
mstudioanimdesc_t &animdesc = pStudioHdr->pAnimdesc( baseanimation );
++checked;
if ( spew != 0 )
{
Msg( "%s checking block %d\n", pStudioHdr->pszName(), animdesc.animblock );
}
// Async load the animation
int iFrame = 0;
const mstudioanim_t *panim = animdesc.pAnim( &iFrame );
if ( panim )
{
++resident;
if ( spew > 1 )
{
Msg( "%s:%s[%i:%i] was resident\n", pStudioHdr->pszName(), animdesc.pszName(), i, j );
}
}
else
{
if ( spew != 0 )
{
Msg( "%s:%s[%i:%i] async load\n", pStudioHdr->pszName(), animdesc.pszName(), i, j );
}
}
}
}
}
}
}
}
}
break;
}
}
if ( !spew || checked <= 0 )
return;
Msg( "%d of %d animations resident\n", resident, checked );
}
void CSceneEntity::OnLoaded()
{
// Nothing
}
//-----------------------------------------------------------------------------
// Purpose: Initiate scene playback
//-----------------------------------------------------------------------------
void CSceneEntity::StartPlayback( void )
{
if ( !m_pScene )
{
if ( m_bSceneMissing )
return;
m_pScene = LoadScene( STRING( m_iszSceneFile ), this );
if ( !m_pScene )
{
DevMsg( "%s missing from scenes.image\n", STRING( m_iszSceneFile ) );
m_bSceneMissing = true;
return;
}
OnLoaded();
if ( ShouldNetwork() )
{
m_nSceneStringIndex = g_pStringTableClientSideChoreoScenes->AddString( CBaseEntity::IsServer(), STRING( m_iszSceneFile ) );
}
UpdateTransmitState();
}
if ( m_bIsPlayingBack )
return;
// Make sure actors are alive and able to handle this scene now, otherwise
// we'll wait for them to show up
if ( !CheckActors() )
{
return;
}
m_bCompletedEarly = false;
m_bWaitingForActor = false;
m_bWaitingForInterrupt = false;
m_bIsPlayingBack = true;
NetworkProp()->NetworkStateForceUpdate();
m_bPaused = false;
SetCurrentTime( 0.0f, true );
m_pScene->ResetSimulation();
ClearInterrupt();
// Put face back in neutral pose
ClearSceneEvents( m_pScene, false );
m_OnStart.FireOutput( this, this, 0 );
// Aysnchronously load speak sounds
CUtlSymbolTable prefetchSoundSymbolTable;
CUtlRBTree< SpeakEventSound_t > soundnames( 0, 0, SpeakEventSoundLessFunc );
BuildSortedSpeakEventSoundsPrefetchList( m_pScene, prefetchSoundSymbolTable, soundnames, 0.0f );
PrefetchSpeakEventSounds( prefetchSoundSymbolTable, soundnames );
// Tell any managers we're within that we've started
int c = m_hListManagers.Count();
for ( int i = 0; i < c; i++ )
{
if ( m_hListManagers[i] )
{
m_hListManagers[i]->SceneStarted( this );
}
}
PrefetchAnimBlocks( m_pScene );
}
//-----------------------------------------------------------------------------
// Purpose: Static method used to sort by event start time
//-----------------------------------------------------------------------------
bool CSceneEntity::SpeakEventSoundLessFunc( const SpeakEventSound_t& lhs, const SpeakEventSound_t& rhs )
{
return lhs.m_flStartTime < rhs.m_flStartTime;
}
//-----------------------------------------------------------------------------
// Purpose: Prefetches the list of sounds build by BuildSortedSpeakEventSoundsPrefetchList
//-----------------------------------------------------------------------------
void CSceneEntity::PrefetchSpeakEventSounds( CUtlSymbolTable& table, CUtlRBTree< SpeakEventSound_t >& soundnames )
{
for ( int i = soundnames.FirstInorder(); i != soundnames.InvalidIndex() ; i = soundnames.NextInorder( i ) )
{
SpeakEventSound_t& sound = soundnames[ i ];
// Look it up in the string table
char const *soundname = table.String( sound.m_Symbol );
// Warning( "Prefetch %s\n", soundname );
PrefetchScriptSound( soundname );
}
}
//-----------------------------------------------------------------------------
// Purpose: Builds list of sounds sorted by start time for prefetching
//-----------------------------------------------------------------------------
void CSceneEntity::BuildSortedSpeakEventSoundsPrefetchList(
CChoreoScene *scene,
CUtlSymbolTable& table,
CUtlRBTree< SpeakEventSound_t >& soundnames,
float timeOffset )
{
Assert( scene );
// Iterate events and precache necessary resources
for ( int i = 0; i < scene->GetNumEvents(); i++ )
{
CChoreoEvent *event = scene->GetEvent( i );
if ( !event )
continue;
// load any necessary data
switch (event->GetType() )
{
default:
break;
case CChoreoEvent::SPEAK:
{
// NOTE: The script entries associated with .vcds are forced to preload to avoid
// loading hitches during triggering
char soundname[ CChoreoEvent::MAX_CCTOKEN_STRING ];
Q_strncpy( soundname, event->GetParameters(), sizeof( soundname ) );
if ( event->GetCloseCaptionType() == CChoreoEvent::CC_MASTER )
{
event->GetPlaybackCloseCaptionToken( soundname, sizeof( soundname ) );
}
// In single player, try to use the combined or regular .wav files as needed
if ( gpGlobals->maxClients == 1 )
{
CBasePlayer *player = UTIL_GetLocalPlayer();
if ( player && !GetSoundNameForPlayer( event, player, soundname, sizeof( soundname ), player ) )
{
// Skip to next event
continue;
}
}
/*
else
{
// UNDONE: Probably need some other solution in multiplayer... (not sure how to "prefetch" on certain players
// with one sound, but not prefetch the same sound for others...)
}
*/
SpeakEventSound_t ses;
ses.m_Symbol = table.AddString( soundname );
ses.m_flStartTime = timeOffset + event->GetStartTime();
soundnames.Insert( ses );
}
break;
case CChoreoEvent::SUBSCENE:
{
// Only allow a single level of subscenes for now
if ( !scene->IsSubScene() )
{
CChoreoScene *subscene = event->GetSubScene();
if ( !subscene )
{
subscene = LoadScene( event->GetParameters(), this );
subscene->SetSubScene( true );
event->SetSubScene( subscene );
// Now precache it's resources, if any
BuildSortedSpeakEventSoundsPrefetchList( subscene, table, soundnames, event->GetStartTime() );
}
}
}
break;
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSceneEntity::PausePlayback( void )
{
if ( !m_bIsPlayingBack )
return;
if ( m_bPaused )
return;
m_bPaused = true;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSceneEntity::ResumePlayback( void )
{
if ( !m_bIsPlayingBack )
return;
if ( !m_bPaused )
return;
Assert( m_pScene );
if ( !m_pScene )
{
// This should never happen!!!!
return;
}
// FIXME: Iterate using m_pScene->IterateResumeConditionEvents and
// only resume if the event conditions have all been satisfied
// FIXME: Just resume for now
m_pScene->ResumeSimulation();
m_bPaused = false;
m_bPausedViaInput = false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSceneEntity::CancelPlayback( void )
{
if ( !m_bIsPlayingBack )
return;
m_bIsPlayingBack = false;
m_bPaused = false;
m_OnCanceled.FireOutput( this, this, 0 );
LocalScene_Printf( "%s : %8.2f: canceled\n", STRING( m_iszSceneFile ), m_flCurrentTime );
OnSceneFinished( true, false );
}
void CSceneEntity::PitchShiftPlayback( float fPitch )
{
fPitch = clamp( fPitch, SCENE_MIN_PITCH, SCENE_MAX_PITCH );
m_fPitch = fPitch;
if ( !m_pScene )
return;
for ( int iActor = 0 ; iActor < m_pScene->GetNumActors(); ++iActor )
{
CBaseFlex *pTestActor = FindNamedActor( iActor );
if ( !pTestActor )
continue;
char szBuff[ 256 ];
if ( m_pScene->GetPlayingSoundName( szBuff, sizeof( szBuff ) ) )
{
CPASAttenuationFilter filter( pTestActor );
EmitSound_t params;
params.m_pSoundName = szBuff;
params.m_nPitch = 100.0f * fPitch;
params.m_nFlags = SND_CHANGE_PITCH;
pTestActor->EmitSound( filter, pTestActor->entindex(), params );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Start a resume scene, if we have one, and resume playing when it finishes
//-----------------------------------------------------------------------------
void CSceneEntity::QueueResumePlayback( void )
{
// Do we have a resume scene?
if ( m_iszResumeSceneFile != NULL_STRING )
{
bool bStartedScene = false;
// If it has ".vcd" somewhere in the string, try using it as a scene file first
if ( Q_stristr( STRING(m_iszResumeSceneFile), ".vcd" ) )
{
bStartedScene = InstancedScriptedScene( NULL, STRING(m_iszResumeSceneFile), &m_hWaitingForThisResumeScene, 0, false ) != 0;
}
// HACKHACK: For now, get the first target, and see if we can find a response for him
if ( !bStartedScene )
{
CBaseFlex *pActor = FindNamedActor( 0 );
if ( pActor )
{
CAI_BaseActor *pBaseActor = dynamic_cast<CAI_BaseActor*>(pActor);
if ( pBaseActor )
{
AI_Response *result = pBaseActor->SpeakFindResponse( STRING(m_iszResumeSceneFile), NULL );
if ( result )
{
char response[ 256 ];
result->GetResponse( response, sizeof( response ) );
bStartedScene = InstancedScriptedScene( NULL, response, &m_hWaitingForThisResumeScene, 0, false ) != 0;
}
}
}
}
// If we started a scene/response, wait for it to finish
if ( bStartedScene )
{
m_bWaitingForResumeScene = true;
}
else
{
// Failed to create the scene. Resume immediately.
ResumePlayback();
}
}
else
{
// No resume scene, so just resume immediately
ResumePlayback();
}
}
//-----------------------------------------------------------------------------
// Purpose: Query whether the scene actually loaded. Only meaninful after Spawn()
//-----------------------------------------------------------------------------
bool CSceneEntity::ValidScene() const
{
return ( m_pScene != NULL );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pActor -
// *scene -
// *event -
//-----------------------------------------------------------------------------
void CSceneEntity::DispatchStartSubScene( CChoreoScene *scene, CBaseFlex *pActor, CChoreoEvent *event)
{
if ( !scene->IsSubScene() )
{
CChoreoScene *subscene = event->GetSubScene();
if ( !subscene )
{
Assert( 0 );
/*
subscene = LoadScene( event->GetParameters() );
subscene->SetSubScene( true );
event->SetSubScene( subscene );
*/
}
if ( subscene )
{
subscene->ResetSimulation();
}
}
}
//-----------------------------------------------------------------------------
// Purpose: All events are leading edge triggered
// Input : currenttime -
// *event -
//-----------------------------------------------------------------------------
void CSceneEntity::StartEvent( float currenttime, CChoreoScene *scene, CChoreoEvent *event )
{
Assert( event );
if ( !Q_stricmp( event->GetName(), "NULL" ) )
{
LocalScene_Printf( "%s : %8.2f: ignored %s\n", STRING( m_iszSceneFile ), currenttime, event->GetDescription() );
return;
}
CBaseFlex *pActor = NULL;
CChoreoActor *actor = event->GetActor();
if ( actor )
{
pActor = FindNamedActor( actor );
if (pActor == NULL)
{
Warning( "CSceneEntity %s unable to find actor named \"%s\"\n", STRING(GetEntityName()), actor->GetName() );
return;
}
}
LocalScene_Printf( "%s : %8.2f: start %s\n", STRING( m_iszSceneFile ), currenttime, event->GetDescription() );
switch ( event->GetType() )
{
case CChoreoEvent::SUBSCENE:
{
if ( pActor && !IsMultiplayer() )
{
DispatchStartSubScene( scene, pActor, event );
}
}
break;
case CChoreoEvent::EXPRESSION:
{
if ( pActor && !IsMultiplayer() )
{
DispatchStartExpression( scene, pActor, event );
}
}
break;
case CChoreoEvent::FLEXANIMATION:
{
if ( pActor && !IsMultiplayer() )
{
DispatchStartFlexAnimation( scene, pActor, event );
}
}
break;
case CChoreoEvent::LOOKAT:
{
if ( pActor && !IsMultiplayer() )
{
CBaseEntity *pActor2 = FindNamedEntity( event->GetParameters( ), pActor );
if ( pActor2 )
{
// Huh?
DispatchStartLookAt( scene, pActor, pActor2, event );
}
else
{
Warning( "CSceneEntity %s unable to find actor named \"%s\"\n", STRING(GetEntityName()), event->GetParameters() );
}
}
}
break;
case CChoreoEvent::SPEAK:
{
if ( pActor )
{
// Speaking is edge triggered
// FIXME: dB hack. soundlevel needs to be moved into inside of wav?
soundlevel_t iSoundlevel = SNDLVL_TALKING;
if (event->GetParameters2())
{
iSoundlevel = (soundlevel_t)atoi( event->GetParameters2() );
if (iSoundlevel == SNDLVL_NONE)
iSoundlevel = SNDLVL_TALKING;
}
DispatchStartSpeak( scene, pActor, event, iSoundlevel );
}
}
break;
case CChoreoEvent::MOVETO:
{
// FIXME: make sure moveto's aren't edge triggered
if ( !event->HasEndTime() )
{
event->SetEndTime( event->GetStartTime() + 1.0 );
}
if ( pActor && !IsMultiplayer() )
{
CBaseEntity *pActor2 = NULL;
if ( event->GetParameters3( ) && strlen( event->GetParameters3( ) ) > 0 )
{
pActor2 = FindNamedEntityClosest( event->GetParameters( ), pActor, false, true, event->GetParameters3( ) );
}
else
{
pActor2 = FindNamedEntity( event->GetParameters( ), pActor, false, true );
}
if ( pActor2 )
{
DispatchStartMoveTo( scene, pActor, pActor2, event );
}
else
{
Warning( "CSceneEntity %s unable to find actor named \"%s\"\n", STRING(GetEntityName()), event->GetParameters() );
}
}
}
break;
case CChoreoEvent::FACE:
{
if ( pActor && !IsMultiplayer() )
{
CBaseEntity *pActor2 = FindNamedEntity( event->GetParameters( ), pActor );
if ( pActor2 )
{
DispatchStartFace( scene, pActor, pActor2, event );
}
else
{
Warning( "CSceneEntity %s unable to find actor named \"%s\"\n", STRING(GetEntityName()), event->GetParameters() );
}
}
}
break;
case CChoreoEvent::GESTURE:
{
if ( pActor )
{
DispatchStartGesture( scene, pActor, event );
}
}
break;
case CChoreoEvent::GENERIC:
{
// If the first token in the parameters is "debugtext", print the rest of the text
if ( event->GetParameters() && !Q_strncmp( event->GetParameters(), "debugtext", 9 ) )
{
const char *pszText = event->GetParameters() + 10;
hudtextparms_s tTextParam;
tTextParam.x = -1;
tTextParam.y = 0.65;
tTextParam.effect = 0;
tTextParam.r1 = 255;
tTextParam.g1 = 170;
tTextParam.b1 = 0;
tTextParam.a1 = 255;
tTextParam.r2 = 255;
tTextParam.g2 = 170;
tTextParam.b2 = 0;
tTextParam.a2 = 255;
tTextParam.fadeinTime = 0;
tTextParam.fadeoutTime = 0;
tTextParam.holdTime = 3.1;
tTextParam.fxTime = 0;
tTextParam.channel = 1;
UTIL_HudMessageAll( tTextParam, pszText );
break;
}
if ( pActor )
{
DispatchStartGeneric( scene, pActor, event );
}
}
break;
case CChoreoEvent::FIRETRIGGER:
{
if ( IsMultiplayer() )
break;
// Don't re-fire triggers during restore, the entities should already reflect all such state...
if ( m_bRestoring )
{
break;
}
CBaseEntity *pActivator = pActor;
if (!pActivator)
{
pActivator = this;
}
// FIXME: how do I decide who fired it??
switch( atoi( event->GetParameters() ) )
{
case 1:
m_OnTrigger1.FireOutput( pActivator, this, 0 );
break;
case 2:
m_OnTrigger2.FireOutput( pActivator, this, 0 );
break;
case 3:
m_OnTrigger3.FireOutput( pActivator, this, 0 );
break;
case 4:
m_OnTrigger4.FireOutput( pActivator, this, 0 );
break;
case 5:
m_OnTrigger5.FireOutput( pActivator, this, 0 );
break;
case 6:
m_OnTrigger6.FireOutput( pActivator, this, 0 );
break;
case 7:
m_OnTrigger7.FireOutput( pActivator, this, 0 );
break;
case 8:
m_OnTrigger8.FireOutput( pActivator, this, 0 );
break;
case 9:
m_OnTrigger9.FireOutput( pActivator, this, 0 );
break;
case 10:
m_OnTrigger10.FireOutput( pActivator, this, 0 );
break;
case 11:
m_OnTrigger11.FireOutput( pActivator, this, 0 );
break;
case 12:
m_OnTrigger12.FireOutput( pActivator, this, 0 );
break;
case 13:
m_OnTrigger13.FireOutput( pActivator, this, 0 );
break;
case 14:
m_OnTrigger14.FireOutput( pActivator, this, 0 );
break;
case 15:
m_OnTrigger15.FireOutput( pActivator, this, 0 );
break;
case 16:
m_OnTrigger16.FireOutput( pActivator, this, 0 );
break;
}
}
break;
case CChoreoEvent::SEQUENCE:
{
if ( pActor )
{
DispatchStartSequence( scene, pActor, event );
}
}
break;
case CChoreoEvent::SECTION:
{
if ( IsMultiplayer() )
break;
// Pauses scene playback
DispatchPauseScene( scene, event->GetParameters() );
}
break;
case CChoreoEvent::LOOP:
{
DispatchProcessLoop( scene, event );
}
break;
case CChoreoEvent::INTERRUPT:
{
if ( IsMultiplayer() )
break;
DispatchStartInterrupt( scene, event );
}
break;
case CChoreoEvent::STOPPOINT:
{
if ( IsMultiplayer() )
break;
DispatchStopPoint( scene, event->GetParameters() );
}
break;
case CChoreoEvent::PERMIT_RESPONSES:
{
if ( IsMultiplayer() )
break;
DispatchStartPermitResponses( scene, pActor, event );
}
break;
default:
{
// FIXME: Unhandeled event
// Assert(0);
}
break;
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : currenttime -
// *event -
//-----------------------------------------------------------------------------
void CSceneEntity::EndEvent( float currenttime, CChoreoScene *scene, CChoreoEvent *event )
{
Assert( event );
if ( !Q_stricmp( event->GetName(), "NULL" ) )
{
return;
}
CBaseFlex *pActor = NULL;
CChoreoActor *actor = event->GetActor();
if ( actor )
{
pActor = FindNamedActor( actor );
}
LocalScene_Printf( "%s : %8.2f: finish %s\n", STRING( m_iszSceneFile ), currenttime, event->GetDescription() );
switch ( event->GetType() )
{
case CChoreoEvent::EXPRESSION:
{
if ( pActor && !IsMultiplayer() )
{
DispatchEndExpression( scene, pActor, event );
}
}
break;
case CChoreoEvent::SPEAK:
{
if ( pActor )
{
DispatchEndSpeak( scene, pActor, event );
}
}
break;
case CChoreoEvent::FLEXANIMATION:
{
if ( pActor && !IsMultiplayer() )
{
DispatchEndFlexAnimation( scene, pActor, event );
}
}
break;
case CChoreoEvent::LOOKAT:
{
if ( pActor && !IsMultiplayer() )
{
DispatchEndLookAt( scene, pActor, event );
}
}
break;
case CChoreoEvent::GESTURE:
{
if ( pActor )
{
DispatchEndGesture( scene, pActor, event );
}
}
break;
case CChoreoEvent::GENERIC:
{
// If the first token in the parameters is "debugtext", we printed it and we're done
if ( event->GetParameters() && !Q_strncmp( event->GetParameters(), "debugtext", 9 ) )
break;
if ( pActor )
{
DispatchEndGeneric( scene, pActor, event );
}
}
break;
case CChoreoEvent::SEQUENCE:
{
if ( pActor )
{
DispatchEndSequence( scene, pActor, event );
}
}
break;
case CChoreoEvent::FACE:
{
if ( pActor && !IsMultiplayer() )
{
DispatchEndFace( scene, pActor, event );
}
}
break;
case CChoreoEvent::MOVETO:
{
if ( pActor && !IsMultiplayer() )
{
DispatchEndMoveTo( scene, pActor, event );
}
}
break;
case CChoreoEvent::SUBSCENE:
{
if ( IsMultiplayer() )
break;
CChoreoScene *subscene = event->GetSubScene();
if ( subscene )
{
subscene->ResetSimulation();
}
}
break;
case CChoreoEvent::INTERRUPT:
{
if ( IsMultiplayer() )
break;
DispatchEndInterrupt( scene, event );
}
break;
case CChoreoEvent::PERMIT_RESPONSES:
{
if ( IsMultiplayer() )
break;
DispatchEndPermitResponses( scene, pActor, event );
}
break;
default:
break;
}
}
//-----------------------------------------------------------------------------
// Purpose: Only spew one time per missing scene!!!
// Input : *scenename -
//-----------------------------------------------------------------------------
void MissingSceneWarning( char const *scenename )
{
static CUtlSymbolTable missing;
// Make sure we only show the message once
if ( UTL_INVAL_SYMBOL == missing.Find( scenename ) )
{
missing.AddString( scenename );
Warning( "Scene '%s' missing!\n", scenename );
}
}
bool CSceneEntity::ShouldNetwork() const
{
if ( m_bMultiplayer )
{
if ( m_pScene &&
( m_pScene->HasEventsOfType( CChoreoEvent::FLEXANIMATION ) ||
m_pScene->HasEventsOfType( CChoreoEvent::EXPRESSION )||
m_pScene->HasEventsOfType( CChoreoEvent::GESTURE ) ||
m_pScene->HasEventsOfType( CChoreoEvent::SEQUENCE ) ) )
{
return true;
}
}
else
{
if ( m_pScene &&
( m_pScene->HasEventsOfType( CChoreoEvent::FLEXANIMATION ) ||
m_pScene->HasEventsOfType( CChoreoEvent::EXPRESSION ) ) )
{
return true;
}
}
return false;
}
CChoreoScene *CSceneEntity::LoadScene( const char *filename, IChoreoEventCallback *pCallback )
{
DevMsg( 2, "Blocking load of scene from '%s'\n", filename );
char loadfile[MAX_PATH];
Q_strncpy( loadfile, filename, sizeof( loadfile ) );
Q_SetExtension( loadfile, ".vcd", sizeof( loadfile ) );
Q_FixSlashes( loadfile );
// binary compiled vcd
void *pBuffer;
int fileSize;
if ( !CopySceneFileIntoMemory( loadfile, &pBuffer, &fileSize ) )
{
MissingSceneWarning( loadfile );
return NULL;
}
CChoreoScene *pScene = new CChoreoScene( NULL );
CUtlBuffer buf( pBuffer, fileSize, CUtlBuffer::READ_ONLY );
if ( !pScene->RestoreFromBinaryBuffer( buf, loadfile, &g_ChoreoStringPool ) )
{
Warning( "CSceneEntity::LoadScene: Unable to load binary scene '%s'\n", loadfile );
delete pScene;
pScene = NULL;
}
else
{
pScene->SetPrintFunc( LocalScene_Printf );
pScene->SetEventCallbackInterface( pCallback );
}
FreeSceneFileMemory( pBuffer );
return pScene;
}
CChoreoScene *BlockingLoadScene( const char *filename )
{
return CSceneEntity::LoadScene( filename, NULL );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSceneEntity::UnloadScene( void )
{
if ( m_pScene )
{
ClearSceneEvents( m_pScene, false );
for ( int i = 0 ; i < m_pScene->GetNumActors(); i++ )
{
CBaseFlex *pTestActor = FindNamedActor( i );
if ( !pTestActor )
continue;
pTestActor->RemoveChoreoScene( m_pScene );
}
}
delete m_pScene;
m_pScene = NULL;
}
//-----------------------------------------------------------------------------
// Purpose: Called every frame that an event is active (Start/EndEvent as also
// called)
// Input : *event -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
void CSceneEntity::ProcessEvent( float currenttime, CChoreoScene *scene, CChoreoEvent *event )
{
switch ( event->GetType() )
{
case CChoreoEvent::SUBSCENE:
{
Assert( event->GetType() == CChoreoEvent::SUBSCENE );
CChoreoScene *subscene = event->GetSubScene();
if ( !subscene )
return;
if ( subscene->SimulationFinished() )
return;
// Have subscenes think for appropriate time
subscene->Think( m_flFrameTime );
}
break;
default:
break;
}
return;
}
//-----------------------------------------------------------------------------
// Purpose: Called for events that are part of a pause condition
// Input : *event -
// Output : Returns true on event completed, false on non-completion.
//-----------------------------------------------------------------------------
bool CSceneEntity::CheckEvent( float currenttime, CChoreoScene *scene, CChoreoEvent *event )
{
switch ( event->GetType() )
{
case CChoreoEvent::SUBSCENE:
{
}
break;
default:
{
CBaseFlex *pActor = NULL;
CChoreoActor *actor = event->GetActor();
if ( actor )
{
pActor = FindNamedActor( actor );
if (pActor == NULL)
{
Warning( "CSceneEntity %s unable to find actor \"%s\"\n", STRING(GetEntityName()), actor->GetName() );
return true;
}
}
if (pActor)
{
return pActor->CheckSceneEvent( currenttime, scene, event );
}
}
break;
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Get a sticky version of a named actor
// Input : CChoreoActor
// Output : CBaseFlex
//-----------------------------------------------------------------------------
CBaseFlex *CSceneEntity::FindNamedActor( int index )
{
if (m_hActorList.Count() == 0)
{
m_hActorList.SetCount( m_pScene->GetNumActors() );
NetworkProp()->NetworkStateForceUpdate();
}
if ( !m_hActorList.IsValidIndex( index ) )
{
DevWarning( "Scene %s has %d actors, but scene entity only has %d actors\n", m_pScene->GetFilename(), m_pScene->GetNumActors(), m_hActorList.Size() );
return NULL;
}
CBaseFlex *pActor = m_hActorList[ index ];
if (pActor == NULL || !pActor->IsAlive() )
{
CChoreoActor *pChoreoActor = m_pScene->GetActor( index );
if ( !pChoreoActor )
return NULL;
pActor = FindNamedActor( pChoreoActor->GetName() );
if (pActor)
{
// save who we found so we'll use them again
m_hActorList[ index ] = pActor;
NetworkProp()->NetworkStateForceUpdate();
}
}
return pActor;
}
//-----------------------------------------------------------------------------
// Purpose: Get a sticky version of a named actor
// Input : CChoreoActor
// Output : CBaseFlex
//-----------------------------------------------------------------------------
CBaseFlex *CSceneEntity::FindNamedActor( CChoreoActor *pChoreoActor )
{
int index = m_pScene->FindActorIndex( pChoreoActor );
if (index >= 0)
{
return FindNamedActor( index );
}
return NULL;
}
//-----------------------------------------------------------------------------
// Purpose: Search for an actor by name, make sure it can do face poses
// Input : *name -
// Output : CBaseFlex
//-----------------------------------------------------------------------------
CBaseFlex *CSceneEntity::FindNamedActor( const char *name )
{
CBaseEntity *entity = FindNamedEntity( name, NULL, true );
if ( !entity )
{
// Couldn't find actor!
return NULL;
}
// Make sure it can actually do facial animation, etc.
CBaseFlex *flexEntity = dynamic_cast< CBaseFlex * >( entity );
if ( !flexEntity )
{
// That actor was not a CBaseFlex!
return NULL;
}
return flexEntity;
}
//-----------------------------------------------------------------------------
// Purpose: Find an entity specified by a target name
// Input : *name -
// Output : CBaseEntity
//-----------------------------------------------------------------------------
CBaseEntity *CSceneEntity::FindNamedTarget( string_t iszTarget, bool bBaseFlexOnly )
{
if ( !stricmp( STRING(iszTarget), "!activator" ) )
return m_hActivator;
// If we don't have a wildcard in the target, just return the first entity found
if ( !strchr( STRING(iszTarget), '*' ) )
return gEntList.FindEntityByName( NULL, iszTarget );
CBaseEntity *pTarget = NULL;
while ( (pTarget = gEntList.FindEntityByName( pTarget, iszTarget )) != NULL )
{
if ( bBaseFlexOnly )
{
// Make sure it can actually do facial animation, etc.
if ( dynamic_cast< CBaseFlex * >( pTarget ) )
return pTarget;
}
else
{
return pTarget;
}
}
// Failed to find one
return NULL;
}
//-----------------------------------------------------------------------------
// Purpose: Filters entities only if they're clear
//-----------------------------------------------------------------------------
class CSceneFindMarkFilter : public IEntityFindFilter
{
public:
void SetActor( CBaseEntity *pActor )
{
m_hActor = pActor;
}
bool ShouldFindEntity( CBaseEntity *pEntity )
{
if ( !m_hActor )
return true;
// If we find no truly valid marks, we'll just use the first.
if ( !m_hEntityFound.Get() )
{
m_hEntityFound = pEntity;
}
// We only want marks that are clear
trace_t tr;
Vector vecOrigin = pEntity->GetAbsOrigin();
AI_TraceHull( vecOrigin, vecOrigin, m_hActor->WorldAlignMins(), m_hActor->WorldAlignMaxs(), MASK_SOLID, m_hActor, COLLISION_GROUP_NONE, &tr );
if ( tr.startsolid )
{
return false;
}
m_hEntityFound = pEntity;
return true;
}
CBaseEntity *GetFilterResult( void )
{
return m_hEntityFound;
}
private:
EHANDLE m_hActor;
// To maintain backwards compatability, store off the first mark
// we find. If we find no truly valid marks, we'll just use the first.
EHANDLE m_hEntityFound;
};
//-----------------------------------------------------------------------------
// Purpose: Finds the entity nearest to both entities, and is clear
//-----------------------------------------------------------------------------
class CSceneFindNearestMarkFilter : public IEntityFindFilter
{
public:
CSceneFindNearestMarkFilter( const CBaseEntity *pActor, const Vector &vecPos2, float flMaxRadius = MAX_TRACE_LENGTH )
{
m_vecPos2 = vecPos2;
m_flMaxSegmentDistance = flMaxRadius;
m_flNearestToTarget = flMaxRadius;
m_pNearestToTarget = NULL;
m_flNearestToActor = flMaxRadius;
m_pNearestToActor = NULL;
m_hActor = pActor;
if (pActor)
{
m_vecPos1 = pActor->GetAbsOrigin();
m_flMaxSegmentDistance = MIN( flMaxRadius, (m_vecPos1 - m_vecPos2).Length() + 1.0 );
if (m_flMaxSegmentDistance <= 1.0)
{
// must be closest to self
m_flMaxSegmentDistance = MIN( flMaxRadius, MAX_TRACE_LENGTH );
}
}
}
bool ShouldFindEntity( CBaseEntity *pEntity )
{
if ( !m_hActor )
return true;
// If we find no truly valid marks, we'll just use the first.
if ( m_pNearestToActor == NULL )
{
m_pNearestToActor = pEntity;
}
// We only want marks that are clear
trace_t tr;
Vector vecOrigin = pEntity->GetAbsOrigin();
AI_TraceHull( vecOrigin, vecOrigin, m_hActor->WorldAlignMins(), m_hActor->WorldAlignMaxs(), MASK_SOLID, m_hActor, COLLISION_GROUP_NONE, &tr );
if ( !tr.startsolid || tr.m_pEnt == m_hActor)
{
float dist1 = (m_vecPos1 - pEntity->GetAbsOrigin()).Length();
float dist2 = (m_vecPos2 - pEntity->GetAbsOrigin()).Length();
/*
char text[256];
Q_snprintf( text, sizeof( text ), "%.0f : %.0f", dist1, dist2 );
NDebugOverlay::Text( pEntity->GetAbsOrigin() + Vector( 0, 0, 8 ), text, false, 5.0f );
*/
// find the point closest to the actor
if (dist1 <= m_flNearestToActor)
{
m_pNearestToActor = pEntity;
m_flNearestToActor = dist2;
}
// find that node that's closest to both, but the distance to it from the actor isn't farther than
// the distance to the second node. This should keep the actor from walking past their point of interest
if (dist1 <= m_flMaxSegmentDistance && dist2 <= m_flMaxSegmentDistance && dist2 < m_flNearestToTarget)
{
m_pNearestToTarget = pEntity;
m_flNearestToTarget = dist2;
}
}
return false;
}
CBaseEntity *GetFilterResult( void )
{
if (m_pNearestToTarget)
return m_pNearestToTarget;
return m_pNearestToActor;
}
private:
EHANDLE m_hActor;
Vector m_vecPos1;
Vector m_vecPos2;
float m_flMaxSegmentDistance;
float m_flNearestToTarget;
CBaseEntity *m_pNearestToTarget;
float m_flNearestToActor;
CBaseEntity *m_pNearestToActor;
};
//-----------------------------------------------------------------------------
// Purpose: Search for an actor by name, make sure it can do face poses
// Input : *name -
// Output : CBaseFlex
//-----------------------------------------------------------------------------
CBaseEntity *CSceneEntity::FindNamedEntity( const char *name, CBaseEntity *pActor, bool bBaseFlexOnly, bool bUseClear )
{
CBaseEntity *entity = NULL;
if ( !stricmp( name, "Player" ) || !stricmp( name, "!player" ))
{
entity = ( gpGlobals->maxClients == 1 ) ? ( CBaseEntity * )UTIL_GetLocalPlayer() : NULL;
}
else if ( !stricmp( name, "!target1" ) )
{
if (m_hTarget1 == NULL)
{
m_hTarget1 = FindNamedTarget( m_iszTarget1, bBaseFlexOnly );
}
return m_hTarget1;
}
else if ( !stricmp( name, "!target2" ) )
{
if (m_hTarget2 == NULL)
{
m_hTarget2 = FindNamedTarget( m_iszTarget2, bBaseFlexOnly );
}
return m_hTarget2;
}
else if ( !stricmp( name, "!target3" ) )
{
if (m_hTarget3 == NULL)
{
m_hTarget3 = FindNamedTarget( m_iszTarget3, bBaseFlexOnly );
}
return m_hTarget3;
}
else if ( !stricmp( name, "!target4" ) )
{
if (m_hTarget4 == NULL)
{
m_hTarget4 = FindNamedTarget( m_iszTarget4, bBaseFlexOnly );
}
return m_hTarget4;
}
else if ( !stricmp( name, "!target5" ) )
{
if (m_hTarget5 == NULL)
{
m_hTarget5 = FindNamedTarget( m_iszTarget5, bBaseFlexOnly );
}
return m_hTarget5;
}
else if ( !stricmp( name, "!target6" ) )
{
if (m_hTarget6 == NULL)
{
m_hTarget6 = FindNamedTarget( m_iszTarget6, bBaseFlexOnly );
}
return m_hTarget6;
}
else if ( !stricmp( name, "!target7" ) )
{
if (m_hTarget7 == NULL)
{
m_hTarget7 = FindNamedTarget( m_iszTarget7, bBaseFlexOnly );
}
return m_hTarget7;
}
else if ( !stricmp( name, "!target8" ) )
{
if (m_hTarget8 == NULL)
{
m_hTarget8 = FindNamedTarget( m_iszTarget8, bBaseFlexOnly );
}
return m_hTarget8;
}
else if (pActor && pActor->MyNPCPointer())
{
CSceneFindMarkFilter *pFilter = NULL;
if ( bUseClear )
{
pFilter = new CSceneFindMarkFilter();
pFilter->SetActor( pActor );
}
entity = pActor->MyNPCPointer()->FindNamedEntity( name, pFilter );
if ( !entity && pFilter )
{
entity = pFilter->GetFilterResult();
}
}
else
{
// search for up to 32 entities with the same name and choose one randomly
CBaseEntity *entityList[ FINDNAMEDENTITY_MAX_ENTITIES ];
int iCount;
entity = NULL;
for( iCount = 0; iCount < FINDNAMEDENTITY_MAX_ENTITIES; iCount++ )
{
entity = gEntList.FindEntityByName( entity, name, NULL, pActor );
if ( !entity )
{
break;
}
entityList[ iCount ] = entity;
}
if ( iCount > 0 )
{
entity = entityList[ RandomInt( 0, iCount - 1 ) ];
}
else
{
entity = NULL;
}
}
return entity;
}
//-----------------------------------------------------------------------------
// Purpose: Search for an actor by name, make sure it can do face poses
// Input : *name -
// Output : CBaseFlex
//-----------------------------------------------------------------------------
CBaseEntity *CSceneEntity::FindNamedEntityClosest( const char *name, CBaseEntity *pActor, bool bBaseFlexOnly, bool bUseClear, const char *pszSecondary )
{
CBaseEntity *entity = NULL;
if ( !stricmp( name, "!activator" ) )
{
return m_hActivator;
}
else if ( !stricmp( name, "Player" ) || !stricmp( name, "!player" ))
{
entity = ( gpGlobals->maxClients == 1 ) ? ( CBaseEntity * )UTIL_GetLocalPlayer() : NULL;
return entity;
}
else if ( !stricmp( name, "!target1" ) )
{
name = STRING( m_iszTarget1 );
}
else if ( !stricmp( name, "!target2" ) )
{
name = STRING( m_iszTarget2 );
}
else if ( !stricmp( name, "!target3" ) )
{
name = STRING( m_iszTarget3 );
}
else if ( !stricmp( name, "!target4" ) )
{
name = STRING( m_iszTarget4 );
}
else if ( !stricmp( name, "!target5" ) )
{
name = STRING( m_iszTarget5 );
}
else if ( !stricmp( name, "!target6" ) )
{
name = STRING( m_iszTarget6 );
}
else if ( !stricmp( name, "!target7" ) )
{
name = STRING( m_iszTarget7 );
}
if (pActor && pActor->MyNPCPointer())
{
if (pszSecondary && strlen( pszSecondary ) > 0)
{
CBaseEntity *pActor2 = FindNamedEntityClosest( pszSecondary, pActor, false, false, NULL );
if (pActor2)
{
CSceneFindNearestMarkFilter *pFilter = new CSceneFindNearestMarkFilter( pActor, pActor2->GetAbsOrigin() );
entity = pActor->MyNPCPointer()->FindNamedEntity( name, pFilter );
if (!entity && pFilter)
{
entity = pFilter->GetFilterResult();
}
}
}
if (!entity)
{
CSceneFindMarkFilter *pFilter = NULL;
if ( bUseClear )
{
pFilter = new CSceneFindMarkFilter();
pFilter->SetActor( pActor );
}
entity = pActor->MyNPCPointer()->FindNamedEntity( name, pFilter );
if (!entity && pFilter)
{
entity = pFilter->GetFilterResult();
}
}
}
else
{
// search for up to 32 entities with the same name and choose one randomly
int iCount;
entity = NULL;
CBaseEntity *current = NULL;
for( iCount = 0; iCount < FINDNAMEDENTITY_MAX_ENTITIES; iCount++ )
{
current = gEntList.FindEntityByName( current, name, NULL, pActor );
if ( current )
{
if (RandomInt( 0, iCount ) == 0)
entity = current;
}
}
entity = NULL;
}
return entity;
}
//-----------------------------------------------------------------------------
// Purpose: Remove all "scene" expressions from all actors in this scene
//-----------------------------------------------------------------------------
void CSceneEntity::ClearSceneEvents( CChoreoScene *scene, bool canceled )
{
if ( !m_pScene )
return;
LocalScene_Printf( "%s : %8.2f: clearing events\n", STRING( m_iszSceneFile ), m_flCurrentTime );
int i;
for ( i = 0 ; i < m_pScene->GetNumActors(); i++ )
{
CBaseFlex *pActor = FindNamedActor( i );
if ( !pActor )
continue;
// Clear any existing expressions
pActor->ClearSceneEvents( scene, canceled );
}
// Iterate events and precache necessary resources
for ( i = 0; i < scene->GetNumEvents(); i++ )
{
CChoreoEvent *event = scene->GetEvent( i );
if ( !event )
continue;
// load any necessary data
switch (event->GetType() )
{
default:
break;
case CChoreoEvent::SUBSCENE:
{
// Only allow a single level of subscenes for now
if ( !scene->IsSubScene() )
{
CChoreoScene *subscene = event->GetSubScene();
if ( subscene )
{
ClearSceneEvents( subscene, canceled );
}
}
}
break;
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Remove all imposed schedules from all actors in this scene
//-----------------------------------------------------------------------------
void CSceneEntity::ClearSchedules( CChoreoScene *scene )
{
if ( !m_pScene )
return;
int i;
for ( i = 0 ; i < m_pScene->GetNumActors(); i++ )
{
CBaseFlex *pActor = FindNamedActor( i );
if ( !pActor )
continue;
CAI_BaseNPC *pNPC = pActor->MyNPCPointer();
if ( pNPC )
{
/*
if ( pNPC->IsCurSchedule( SCHED_SCENE_GENERIC ) )
pNPC->ClearSchedule( "Scene entity clearing all actor schedules" );
*/
}
else
{
pActor->ResetSequence( pActor->SelectWeightedSequence( ACT_IDLE ) );
pActor->SetCycle( 0 );
}
// Clear any existing expressions
}
// Iterate events and precache necessary resources
for ( i = 0; i < scene->GetNumEvents(); i++ )
{
CChoreoEvent *event = scene->GetEvent( i );
if ( !event )
continue;
// load any necessary data
switch (event->GetType() )
{
default:
break;
case CChoreoEvent::SUBSCENE:
{
// Only allow a single level of subscenes for now
if ( !scene->IsSubScene() )
{
CChoreoScene *subscene = event->GetSubScene();
if ( subscene )
{
ClearSchedules( subscene );
}
}
}
break;
}
}
}
//-----------------------------------------------------------------------------
// Purpose: If we are currently interruptable, pause this scene and wait for the other
// scene to finish
// Input : *otherScene -
//-----------------------------------------------------------------------------
bool CSceneEntity::InterruptThisScene( CSceneEntity *otherScene )
{
Assert( otherScene );
if ( !IsInterruptable() )
{
return false;
}
// Already interrupted
if ( m_bInterrupted )
{
return false;
}
m_bInterrupted = true;
m_hInterruptScene = otherScene;
// Ask other scene to tell us when it's finished or canceled
otherScene->RequestCompletionNotification( this );
PausePlayback();
return true;
}
/*
void scene_interrupt( const CCommand &args )
{
if ( args.ArgC() != 3 )
return;
const char *scene1 = args[1];
const char *scene2 = args[2];
CSceneEntity *s1 = dynamic_cast< CSceneEntity * >( gEntList.FindEntityByName( NULL, scene1 ) );
CSceneEntity *s2 = dynamic_cast< CSceneEntity * >( gEntList.FindEntityByName( NULL, scene2 ) );
if ( !s1 || !s2 )
return;
if ( s1->InterruptThisScene( s2 ) )
{
s2->StartPlayback();
}
}
static ConCommand interruptscene( "int", scene_interrupt, "interrupt scene 1 with scene 2.", FCVAR_CHEAT );
*/
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSceneEntity::CheckInterruptCompletion()
{
if ( !m_bInterrupted )
return;
// If the interruptor goes away it's the same as having that scene finish up...
if ( m_hInterruptScene != NULL &&
!m_bInterruptSceneFinished )
{
return;
}
m_bInterrupted = false;
m_hInterruptScene = NULL;
ResumePlayback();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSceneEntity::ClearInterrupt()
{
m_nInterruptCount = 0;
m_bInterrupted = false;
m_hInterruptScene = NULL;
}
//-----------------------------------------------------------------------------
// Purpose: Another scene is asking us to notify upon completion
// Input : *notify -
//-----------------------------------------------------------------------------
void CSceneEntity::RequestCompletionNotification( CSceneEntity *notify )
{
CHandle< CSceneEntity > h;
h = notify;
// Only add it once
if ( m_hNotifySceneCompletion.Find( h ) == m_hNotifySceneCompletion.InvalidIndex() )
{
m_hNotifySceneCompletion.AddToTail( h );
}
}
//-----------------------------------------------------------------------------
// Purpose: An interrupt scene has finished or been canceled, we can resume once we pick up this state in CheckInterruptCompletion
// Input : *interruptor -
//-----------------------------------------------------------------------------
void CSceneEntity::NotifyOfCompletion( CSceneEntity *interruptor )
{
Assert( m_bInterrupted );
Assert( m_hInterruptScene == interruptor );
m_bInterruptSceneFinished = true;
CheckInterruptCompletion();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSceneEntity::AddListManager( CSceneListManager *pManager )
{
CHandle< CSceneListManager > h;
h = pManager;
// Only add it once
if ( m_hListManagers.Find( h ) == m_hListManagers.InvalidIndex() )
{
m_hListManagers.AddToTail( h );
}
}
//-----------------------------------------------------------------------------
// Purpose: Clear any targets that a referencing !activator
//-----------------------------------------------------------------------------
void CSceneEntity::ClearActivatorTargets( void )
{
if ( !stricmp( STRING(m_iszTarget1), "!activator" ) )
{
// We need to clear out actors so they're re-evaluated
m_hActorList.Purge();
NetworkProp()->NetworkStateForceUpdate();
m_hTarget1 = NULL;
}
if ( !stricmp( STRING(m_iszTarget2), "!activator" ) )
{
// We need to clear out actors so they're re-evaluated
m_hActorList.Purge();
NetworkProp()->NetworkStateForceUpdate();
m_hTarget2 = NULL;
}
if ( !stricmp( STRING(m_iszTarget3), "!activator" ) )
{
// We need to clear out actors so they're re-evaluated
m_hActorList.Purge();
NetworkProp()->NetworkStateForceUpdate();
m_hTarget3 = NULL;
}
if ( !stricmp( STRING(m_iszTarget4), "!activator" ) )
{
// We need to clear out actors so they're re-evaluated
m_hActorList.Purge();
NetworkProp()->NetworkStateForceUpdate();
m_hTarget4 = NULL;
}
if ( !stricmp( STRING(m_iszTarget5), "!activator" ) )
{
// We need to clear out actors so they're re-evaluated
m_hActorList.Purge();
NetworkProp()->NetworkStateForceUpdate();
m_hTarget5 = NULL;
}
if ( !stricmp( STRING(m_iszTarget6), "!activator" ) )
{
// We need to clear out actors so they're re-evaluated
m_hActorList.Purge();
NetworkProp()->NetworkStateForceUpdate();
m_hTarget6 = NULL;
}
if ( !stricmp( STRING(m_iszTarget7), "!activator" ) )
{
// We need to clear out actors so they're re-evaluated
m_hActorList.Purge();
NetworkProp()->NetworkStateForceUpdate();
m_hTarget7 = NULL;
}
if ( !stricmp( STRING(m_iszTarget8), "!activator" ) )
{
// We need to clear out actors so they're re-evaluated
m_hActorList.Purge();
NetworkProp()->NetworkStateForceUpdate();
m_hTarget8 = NULL;
}
}
//-----------------------------------------------------------------------------
// Purpose: Called when a scene is completed or canceled
//-----------------------------------------------------------------------------
void CSceneEntity::OnSceneFinished( bool canceled, bool fireoutput )
{
if ( !m_pScene )
return;
LocalScene_Printf( "%s : %8.2f: finished\n", STRING( m_iszSceneFile ), m_flCurrentTime );
// Notify any listeners
int c = m_hNotifySceneCompletion.Count();
int i;
for ( i = 0; i < c; i++ )
{
CSceneEntity *ent = m_hNotifySceneCompletion[ i ].Get();
if ( !ent )
continue;
ent->NotifyOfCompletion( this );
}
m_hNotifySceneCompletion.RemoveAll();
// Clear simulation
m_pScene->ResetSimulation();
m_bIsPlayingBack = false;
m_bPaused = false;
SetCurrentTime( 0.0f, false );
// Clear interrupt state if we were interrupted for some reason
ClearInterrupt();
if ( fireoutput && !m_bCompletedEarly)
{
m_OnCompletion.FireOutput( this, this, 0 );
}
// Put face back in neutral pose
ClearSceneEvents( m_pScene, canceled );
for ( i = 0 ; i < m_pScene->GetNumActors(); i++ )
{
CBaseFlex *pTestActor = FindNamedActor( i );
if ( !pTestActor )
continue;
pTestActor->RemoveChoreoScene( m_pScene, canceled );
// If we interrupted the actor's previous scenes, resume them
if ( m_bInterruptedActorsScenes )
{
QueueActorsScriptedScenesToResume( pTestActor, false );
}
}
}
//-----------------------------------------------------------------------------
// Should we transmit it to the client?
//-----------------------------------------------------------------------------
int CSceneEntity::UpdateTransmitState()
{
if ( !ShouldNetwork() )
{
return SetTransmitState( FL_EDICT_DONTSEND );
}
if ( m_pRecipientFilter )
{
return SetTransmitState( FL_EDICT_FULLCHECK );
}
return SetTransmitState( FL_EDICT_ALWAYS );
}
//-----------------------------------------------------------------------------
// Purpose: Which clients should we be transmitting to?
//-----------------------------------------------------------------------------
int CSceneEntity::ShouldTransmit( const CCheckTransmitInfo *pInfo )
{
int result = BaseClass::ShouldTransmit( pInfo );
// if we have excluded them via our recipient filter, don't send
if ( m_pRecipientFilter && result != FL_EDICT_DONTSEND )
{
bool bFound = false;
// If we can't find them in the recipient list, exclude
int i;
for ( i=0; i<m_pRecipientFilter->GetRecipientCount();i++ )
{
int iRecipient = m_pRecipientFilter->GetRecipientIndex(i);
CBasePlayer *player = static_cast< CBasePlayer * >( CBaseEntity::Instance( iRecipient ) );
if ( player && player->edict() == pInfo->m_pClientEnt )
{
bFound = true;
break;
}
}
if ( !bFound )
{
result = FL_EDICT_DONTSEND;
}
}
return result;
}
void CSceneEntity::SetRecipientFilter( IRecipientFilter *filter )
{
// create a copy of this filter
if ( filter )
{
m_pRecipientFilter = new CRecipientFilter();
m_pRecipientFilter->CopyFrom( (CRecipientFilter &)( *filter ) );
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output :
//-----------------------------------------------------------------------------
class CInstancedSceneEntity : public CSceneEntity
{
DECLARE_DATADESC();
DECLARE_CLASS( CInstancedSceneEntity, CSceneEntity );
public:
EHANDLE m_hOwner;
bool m_bHadOwner;
float m_flPostSpeakDelay;
float m_flPreDelay;
char m_szInstanceFilename[ CChoreoScene::MAX_SCENE_FILENAME ];
bool m_bIsBackground;
virtual void StartPlayback( void );
virtual void DoThink( float frametime );
virtual CBaseFlex *FindNamedActor( const char *name );
virtual CBaseEntity *FindNamedEntity( const char *name );
virtual float GetPostSpeakDelay() { return m_flPostSpeakDelay; }
virtual void SetPostSpeakDelay( float flDelay ) { m_flPostSpeakDelay = flDelay; }
virtual float GetPreDelay() { return m_flPreDelay; }
virtual void SetPreDelay( float flDelay ) { m_flPreDelay = flDelay; }
virtual void OnLoaded();
virtual void DispatchStartMoveTo( CChoreoScene *scene, CBaseFlex *actor, CBaseEntity *actor2, CChoreoEvent *event )
{
if (PassThrough( actor )) BaseClass::DispatchStartMoveTo( scene, actor, actor2, event );
};
virtual void DispatchEndMoveTo( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event )
{
if (PassThrough( actor )) BaseClass::DispatchEndMoveTo( scene, actor, event );
};
virtual void DispatchStartFace( CChoreoScene *scene, CBaseFlex *actor, CBaseEntity *actor2, CChoreoEvent *event )
{
if (PassThrough( actor )) BaseClass::DispatchStartFace( scene, actor, actor2, event );
};
virtual void DispatchEndFace( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event )
{
if (PassThrough( actor )) BaseClass::DispatchEndFace( scene, actor, event );
};
virtual void DispatchStartSequence( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event )
{
if ( IsMultiplayer() )
{
BaseClass::DispatchStartSequence( scene, actor, event );
}
};
virtual void DispatchEndSequence( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event )
{
if ( IsMultiplayer() )
{
BaseClass::DispatchEndSequence( scene, actor, event );
}
};
virtual void DispatchPauseScene( CChoreoScene *scene, const char *parameters ) { /* suppress */ };
void OnRestore();
virtual float EstimateLength( void );
private:
bool PassThrough( CBaseFlex *actor );
};
LINK_ENTITY_TO_CLASS( instanced_scripted_scene, CInstancedSceneEntity );
//---------------------------------------------------------
// Save/Restore
//---------------------------------------------------------
BEGIN_DATADESC( CInstancedSceneEntity )
DEFINE_FIELD( m_hOwner, FIELD_EHANDLE ),
DEFINE_FIELD( m_bHadOwner, FIELD_BOOLEAN ),
DEFINE_FIELD( m_flPostSpeakDelay, FIELD_FLOAT ),
DEFINE_FIELD( m_flPreDelay, FIELD_FLOAT ),
DEFINE_AUTO_ARRAY( m_szInstanceFilename, FIELD_CHARACTER ),
DEFINE_FIELD( m_bIsBackground, FIELD_BOOLEAN ),
END_DATADESC()
//-----------------------------------------------------------------------------
// Purpose: create a one-shot scene, no movement, sequences, etc.
// Input :
// Output :
//-----------------------------------------------------------------------------
float InstancedScriptedScene( CBaseFlex *pActor, const char *pszScene, EHANDLE *phSceneEnt,
float flPostDelay, bool bIsBackground, AI_Response *response,
bool bMultiplayer, IRecipientFilter *filter /* = NULL */ )
{
VPROF( "InstancedScriptedScene" );
CInstancedSceneEntity *pScene = (CInstancedSceneEntity *)CBaseEntity::CreateNoSpawn( "instanced_scripted_scene", vec3_origin, vec3_angle );
// This code expands any $gender tags into male or female tags based on the gender of the actor (based on his/her .mdl)
if ( pActor )
{
pActor->GenderExpandString( pszScene, pScene->m_szInstanceFilename, sizeof( pScene->m_szInstanceFilename ) );
}
else
{
Q_strncpy( pScene->m_szInstanceFilename, pszScene, sizeof( pScene->m_szInstanceFilename ) );
}
pScene->m_iszSceneFile = MAKE_STRING( pScene->m_szInstanceFilename );
// FIXME: I should set my output to fire something that kills me....
// FIXME: add a proper initialization function
pScene->m_hOwner = pActor;
pScene->m_bHadOwner = pActor != NULL;
pScene->m_bMultiplayer = bMultiplayer;
pScene->SetPostSpeakDelay( flPostDelay );
DispatchSpawn( pScene );
pScene->Activate();
pScene->m_bIsBackground = bIsBackground;
pScene->SetBackground( bIsBackground );
pScene->SetRecipientFilter( filter );
if ( response )
{
float flPreDelay = response->GetPreDelay();
if ( flPreDelay )
{
pScene->SetPreDelay( flPreDelay );
}
}
pScene->StartPlayback();
if ( response )
{
// If the response wants us to abort on NPC state switch, remember that
pScene->SetBreakOnNonIdle( response->ShouldBreakOnNonIdle() );
}
if ( phSceneEnt )
{
*phSceneEnt = pScene;
}
return pScene->EstimateLength();
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pActor -
// *soundnmame -
// *phSceneEnt -
// Output : float
//-----------------------------------------------------------------------------
float InstancedAutoGeneratedSoundScene( CBaseFlex *pActor, char const *soundname, EHANDLE *phSceneEnt /*= NULL*/ )
{
if ( !pActor )
{
Warning( "InstancedAutoGeneratedSoundScene: Expecting non-NULL pActor for sound %s\n", soundname );
return 0;
}
CInstancedSceneEntity *pScene = (CInstancedSceneEntity *)CBaseEntity::CreateNoSpawn( "instanced_scripted_scene", vec3_origin, vec3_angle );
Q_strncpy( pScene->m_szInstanceFilename, UTIL_VarArgs( "AutoGenerated(%s)", soundname ), sizeof( pScene->m_szInstanceFilename ) );
pScene->m_iszSceneFile = MAKE_STRING( pScene->m_szInstanceFilename );
pScene->m_hOwner = pActor;
pScene->m_bHadOwner = pActor != NULL;
pScene->GenerateSoundScene( pActor, soundname );
pScene->Spawn();
pScene->Activate();
pScene->StartPlayback();
if ( phSceneEnt )
{
*phSceneEnt = pScene;
}
return pScene->EstimateLength();
}
//-----------------------------------------------------------------------------
void StopScriptedScene( CBaseFlex *pActor, EHANDLE hSceneEnt )
{
CBaseEntity *pEntity = hSceneEnt;
CSceneEntity *pScene = dynamic_cast<CSceneEntity *>(pEntity);
if ( pScene )
{
LocalScene_Printf( "%s : stop scripted scene\n", STRING( pScene->m_iszSceneFile ) );
pScene->CancelPlayback();
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pszScene -
// Output : float
//-----------------------------------------------------------------------------
float GetSceneDuration( char const *pszScene )
{
unsigned int msecs = 0;
SceneCachedData_t cachedData;
if ( scenefilecache->GetSceneCachedData( pszScene, &cachedData ) )
{
msecs = cachedData.msecs;
}
return (float)msecs * 0.001f;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pszScene -
// Output : int
//-----------------------------------------------------------------------------
int GetSceneSpeechCount( char const *pszScene )
{
SceneCachedData_t cachedData;
if ( scenefilecache->GetSceneCachedData( pszScene, &cachedData ) )
{
return cachedData.numSounds;
}
return 0;
}
//-----------------------------------------------------------------------------
// Purpose: Used for precaching instanced scenes
// Input : *pszScene -
//-----------------------------------------------------------------------------
void PrecacheInstancedScene( char const *pszScene )
{
static int nMakingReslists = -1;
if ( nMakingReslists == -1 )
{
nMakingReslists = CommandLine()->FindParm( "-makereslists" ) > 0 ? 1 : 0;
}
if ( nMakingReslists == 1 )
{
// Just stat the file to add to reslist
g_pFullFileSystem->Size( pszScene );
}
// verify existence, cache is pre-populated, should be there
SceneCachedData_t sceneData;
if ( !scenefilecache->GetSceneCachedData( pszScene, &sceneData ) )
{
// Scenes are sloppy and don't always exist.
// A scene that is not in the pre-built cache image, but on disk, is a true error.
if ( developer.GetInt() && ( IsX360() && ( g_pFullFileSystem->GetDVDMode() != DVDMODE_STRICT ) && g_pFullFileSystem->FileExists( pszScene, "GAME" ) ) )
{
Warning( "PrecacheInstancedScene: Missing scene '%s' from scene image cache.\nRebuild scene image cache!\n", pszScene );
}
}
else
{
for ( int i = 0; i < sceneData.numSounds; ++i )
{
short stringId = scenefilecache->GetSceneCachedSound( sceneData.sceneId, i );
CBaseEntity::PrecacheScriptSound( scenefilecache->GetSceneString( stringId ) );
}
}
g_pStringTableClientSideChoreoScenes->AddString( CBaseEntity::IsServer(), pszScene );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CInstancedSceneEntity::StartPlayback( void )
{
// Wait until our pre delay is over
if ( GetPreDelay() )
return;
BaseClass::StartPlayback();
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output :
//-----------------------------------------------------------------------------
void CInstancedSceneEntity::DoThink( float frametime )
{
CheckInterruptCompletion();
if ( m_flPreDelay > 0 )
{
m_flPreDelay = MAX( 0, m_flPreDelay - frametime );
StartPlayback();
if ( !m_bIsPlayingBack )
return;
}
if ( !m_pScene || !m_bIsPlayingBack || ( m_bHadOwner && m_hOwner == NULL ) )
{
UTIL_Remove( this );
return;
}
// catch bad pitch shifting from old save games
Assert( m_fPitch >= SCENE_MIN_PITCH && m_fPitch <= SCENE_MAX_PITCH );
m_fPitch = clamp( m_fPitch, SCENE_MIN_PITCH, SCENE_MAX_PITCH );
if ( m_bPaused )
{
PauseThink();
return;
}
float dt = frametime;
m_pScene->SetSoundFileStartupLatency( GetSoundSystemLatency() );
// Tell scene to go
m_pScene->Think( m_flCurrentTime );
// Drive simulation time for scene
SetCurrentTime( m_flCurrentTime + dt * m_fPitch, false );
// Did we get to the end
if ( m_pScene->SimulationFinished() )
{
OnSceneFinished( false, false );
UTIL_Remove( this );
}
}
//-----------------------------------------------------------------------------
// Purpose: Search for an actor by name, make sure it can do face poses
// Input : *name -
// Output : CBaseFlex
//-----------------------------------------------------------------------------
CBaseFlex *CInstancedSceneEntity::FindNamedActor( const char *name )
{
if ( m_pScene->GetNumActors() == 1 || stricmp( name, "!self" ) == 0 )
{
if ( m_hOwner != NULL )
{
CBaseCombatCharacter *pCharacter = m_hOwner->MyCombatCharacterPointer();
if ( pCharacter )
{
return pCharacter;
}
}
}
return BaseClass::FindNamedActor( name );
}
//-----------------------------------------------------------------------------
// Purpose: Search for an actor by name, make sure it can do face poses
// Input : *name -
// Output : CBaseFlex
//-----------------------------------------------------------------------------
CBaseEntity *CInstancedSceneEntity::FindNamedEntity( const char *name )
{
CBaseEntity *pOther = NULL;
if (m_hOwner != NULL)
{
CAI_BaseNPC *npc = m_hOwner->MyNPCPointer();
if (npc)
{
pOther = npc->FindNamedEntity( name );
}
else if ( m_hOwner->MyCombatCharacterPointer() )
{
pOther = m_hOwner;
}
}
if (!pOther)
{
pOther = BaseClass::FindNamedEntity( name );
}
return pOther;
}
//-----------------------------------------------------------------------------
// Purpose: Suppress certain events when it's instanced since they're can cause odd problems
// Input : actor
// Output : true - the event should happen, false - it shouldn't
//-----------------------------------------------------------------------------
bool CInstancedSceneEntity::PassThrough( CBaseFlex *actor )
{
if (!actor)
return false;
CAI_BaseNPC *myNpc = actor->MyNPCPointer( );
if (!myNpc)
return false;
if (myNpc->IsCurSchedule( SCHED_SCENE_GENERIC ))
{
return true;
}
if (myNpc->GetCurSchedule())
{
CAI_ScheduleBits testBits;
myNpc->GetCurSchedule()->GetInterruptMask( &testBits );
if (testBits.IsBitSet( COND_IDLE_INTERRUPT ))
{
return true;
}
}
LocalScene_Printf( "%s : event suppressed\n", STRING( m_iszSceneFile ) );
return false;
}
//-----------------------------------------------------------------------------
void CInstancedSceneEntity::OnRestore()
{
if ( m_bHadOwner && !m_hOwner )
{
// probably just came back from a level transition
UTIL_Remove( this );
return;
}
// reset background state
if ( m_pScene )
{
m_pScene->SetBackground( m_bIsBackground );
}
BaseClass::OnRestore();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
float CInstancedSceneEntity::EstimateLength( void )
{
return (BaseClass::EstimateLength() + GetPreDelay());
}
void CInstancedSceneEntity::OnLoaded()
{
BaseClass::OnLoaded();
SetBackground( m_bIsBackground );
}
bool g_bClientFlex = true;
LINK_ENTITY_TO_CLASS( scene_manager, CSceneManager );
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSceneManager::Think()
{
// Latch this only once per frame...
g_bClientFlex = scene_clientflex.GetBool();
// The manager is always thinking at 20 hz
SetNextThink( gpGlobals->curtime + SCENE_THINK_INTERVAL );
float frameTime = ( gpGlobals->curtime - GetLastThink() );
frameTime = MIN( 0.1, frameTime );
// stop if AI is diabled
if (CAI_BaseNPC::m_nDebugBits & bits_debugDisableAI)
return;
bool needCleanupPass = false;
int c = m_ActiveScenes.Count();
for ( int i = 0; i < c; i++ )
{
CSceneEntity *scene = m_ActiveScenes[ i ].Get();
if ( !scene )
{
needCleanupPass = true;
continue;
}
scene->DoThink( frameTime );
if ( m_ActiveScenes.Count() < c )
{
// Scene removed self while thinking. Adjust iteration.
c = m_ActiveScenes.Count();
i--;
}
}
// Now delete any invalid ones
if ( needCleanupPass )
{
for ( int i = c - 1; i >= 0; i-- )
{
CSceneEntity *scene = m_ActiveScenes[ i ].Get();
if ( scene )
continue;
m_ActiveScenes.Remove( i );
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSceneManager::ClearAllScenes()
{
m_ActiveScenes.RemoveAll();
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *scene -
//-----------------------------------------------------------------------------
void CSceneManager::AddSceneEntity( CSceneEntity *scene )
{
CHandle< CSceneEntity > h;
h = scene;
// Already added/activated
if ( m_ActiveScenes.Find( h ) != m_ActiveScenes.InvalidIndex() )
{
return;
}
m_ActiveScenes.AddToTail( h );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *scene -
//-----------------------------------------------------------------------------
void CSceneManager::RemoveSceneEntity( CSceneEntity *scene )
{
CHandle< CSceneEntity > h;
h = scene;
m_ActiveScenes.FindAndRemove( h );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *player -
//-----------------------------------------------------------------------------
void CSceneManager::OnClientActive( CBasePlayer *player )
{
int c = m_QueuedSceneSounds.Count();
for ( int i = 0; i < c; i++ )
{
CRestoreSceneSound *sound = &m_QueuedSceneSounds[ i ];
if ( sound->actor == NULL )
continue;
// Blow off sounds too far in past to encode over networking layer
if ( fabs( 1000.0f * sound->time_in_past ) > MAX_SOUND_DELAY_MSEC )
continue;
CPASAttenuationFilter filter( sound->actor );
EmitSound_t es;
es.m_nChannel = CHAN_VOICE;
es.m_flVolume = 1;
es.m_pSoundName = sound->soundname;
es.m_SoundLevel = sound->soundlevel;
es.m_flSoundTime = gpGlobals->curtime - sound->time_in_past;
EmitSound( filter, sound->actor->entindex(), es );
}
m_QueuedSceneSounds.RemoveAll();
}
//-----------------------------------------------------------------------------
// Purpose: Deletes scenes involving the specified actor
//-----------------------------------------------------------------------------
void CSceneManager::RemoveScenesInvolvingActor( CBaseFlex *pActor )
{
if ( !pActor )
return;
int c = m_ActiveScenes.Count();
for ( int i = 0; i < c; i++ )
{
CSceneEntity *pScene = m_ActiveScenes[ i ].Get();
if ( !pScene )
{
continue;
}
if ( pScene->InvolvesActor( pActor ) ) // NOTE: returns false if scene hasn't loaded yet
{
LocalScene_Printf( "%s : removed for '%s'\n", STRING( pScene->m_iszSceneFile ), pActor ? pActor->GetDebugName() : "NULL" );
pScene->CancelPlayback();
}
else
{
CInstancedSceneEntity *pInstancedScene = dynamic_cast< CInstancedSceneEntity * >( pScene );
if ( pInstancedScene && pInstancedScene->m_hOwner )
{
if ( pInstancedScene->m_hOwner == pActor )
{
if ( pInstancedScene->m_bIsPlayingBack )
{
pInstancedScene->OnSceneFinished( true, false );
}
LocalScene_Printf( "%s : removed for '%s'\n", STRING( pInstancedScene->m_iszSceneFile ), pActor ? pActor->GetDebugName() : "NULL" );
UTIL_Remove( pInstancedScene );
}
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Stops scenes involving the specified actor
//-----------------------------------------------------------------------------
void CSceneManager::RemoveActorFromScenes( CBaseFlex *pActor, bool bInstancedOnly, bool bNonIdleOnly, const char *pszThisSceneOnly )
{
int c = m_ActiveScenes.Count();
for ( int i = 0; i < c; i++ )
{
CSceneEntity *pScene = m_ActiveScenes[ i ].Get();
if ( !pScene )
{
continue;
}
// If only stopping instanced scenes, then skip it if it can't cast to an instanced scene
if ( bInstancedOnly &&
( dynamic_cast< CInstancedSceneEntity * >( pScene ) == NULL ) )
{
continue;
}
if ( bNonIdleOnly && !pScene->ShouldBreakOnNonIdle() )
continue;
if ( pScene->InvolvesActor( pActor ) )
{
if ( pszThisSceneOnly && pszThisSceneOnly[0] )
{
if ( Q_strcmp( pszThisSceneOnly, STRING(pScene->m_iszSceneFile) ) )
continue;
}
LocalScene_Printf( "%s : removed for '%s'\n", STRING( pScene->m_iszSceneFile ), pActor ? pActor->GetDebugName() : "NULL" );
pScene->CancelPlayback();
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Pause scenes involving the specified actor
//-----------------------------------------------------------------------------
void CSceneManager::PauseActorsScenes( CBaseFlex *pActor, bool bInstancedOnly )
{
int c = m_ActiveScenes.Count();
for ( int i = 0; i < c; i++ )
{
CSceneEntity *pScene = m_ActiveScenes[ i ].Get();
if ( !pScene )
{
continue;
}
// If only stopping instanced scenes, then skip it if it can't cast to an instanced scene
if ( bInstancedOnly &&
( dynamic_cast< CInstancedSceneEntity * >( pScene ) == NULL ) )
{
continue;
}
if ( pScene->InvolvesActor( pActor ) && pScene->IsPlayingBack() )
{
LocalScene_Printf( "Pausing actor %s scripted scene: %s\n", pActor->GetDebugName(), STRING(pScene->m_iszSceneFile) );
variant_t emptyVariant;
pScene->AcceptInput( "Pause", pScene, pScene, emptyVariant, 0 );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Return true if this Actor is only in scenes that are interruptable right now
//-----------------------------------------------------------------------------
bool CSceneManager::IsInInterruptableScenes( CBaseFlex *pActor )
{
int c = m_ActiveScenes.Count();
for ( int i = 0; i < c; i++ )
{
CSceneEntity *pScene = m_ActiveScenes[ i ].Get();
if ( !pScene )
continue;
//Ignore background scenes since they're harmless.
if ( pScene->IsBackground() == true )
continue;
if ( pScene->InvolvesActor( pActor ) && pScene->IsPlayingBack() )
{
if ( pScene->IsInterruptable() == false )
return false;
}
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Resume any paused scenes involving the specified actor
//-----------------------------------------------------------------------------
void CSceneManager::ResumeActorsScenes( CBaseFlex *pActor, bool bInstancedOnly )
{
int c = m_ActiveScenes.Count();
for ( int i = 0; i < c; i++ )
{
CSceneEntity *pScene = m_ActiveScenes[ i ].Get();
if ( !pScene )
{
continue;
}
// If only stopping instanced scenes, then skip it if it can't cast to an instanced scene
if ( bInstancedOnly &&
( dynamic_cast< CInstancedSceneEntity * >( pScene ) == NULL ) )
{
continue;
}
if ( pScene->InvolvesActor( pActor ) && pScene->IsPlayingBack() )
{
LocalScene_Printf( "Resuming actor %s scripted scene: %s\n", pActor->GetDebugName(), STRING(pScene->m_iszSceneFile) );
variant_t emptyVariant;
pScene->AcceptInput( "Resume", pScene, pScene, emptyVariant, 0 );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Set all paused, in-playback scenes to resume when the actor is ready
//-----------------------------------------------------------------------------
void CSceneManager::QueueActorsScenesToResume( CBaseFlex *pActor, bool bInstancedOnly )
{
int c = m_ActiveScenes.Count();
for ( int i = 0; i < c; i++ )
{
CSceneEntity *pScene = m_ActiveScenes[ i ].Get();
if ( !pScene )
{
continue;
}
// If only stopping instanced scenes, then skip it if it can't cast to an instanced scene
if ( bInstancedOnly &&
( dynamic_cast< CInstancedSceneEntity * >( pScene ) == NULL ) )
{
continue;
}
if ( pScene->InvolvesActor( pActor ) && pScene->IsPlayingBack() && pScene->IsPaused() )
{
pScene->QueueResumePlayback();
}
}
}
//-----------------------------------------------------------------------------
// Purpose: returns if there are scenes involving the specified actor
//-----------------------------------------------------------------------------
bool CSceneManager::IsRunningScriptedScene( CBaseFlex *pActor, bool bIgnoreInstancedScenes )
{
int c = m_ActiveScenes.Count();
for ( int i = 0; i < c; i++ )
{
CSceneEntity *pScene = m_ActiveScenes[ i ].Get();
if ( !pScene ||
!pScene->IsPlayingBack() ||
( bIgnoreInstancedScenes && dynamic_cast<CInstancedSceneEntity *>(pScene) != NULL )
)
{
continue;
}
if ( pScene->InvolvesActor( pActor ) )
{
return true;
}
}
return false;
}
bool CSceneManager::IsRunningScriptedSceneAndNotPaused( CBaseFlex *pActor, bool bIgnoreInstancedScenes )
{
int c = m_ActiveScenes.Count();
for ( int i = 0; i < c; i++ )
{
CSceneEntity *pScene = m_ActiveScenes[ i ].Get();
if ( !pScene ||
!pScene->IsPlayingBack() ||
pScene->IsPaused() ||
( bIgnoreInstancedScenes && dynamic_cast<CInstancedSceneEntity *>(pScene) != NULL )
)
{
continue;
}
if ( pScene->InvolvesActor( pActor ) )
{
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pActor -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CSceneManager::IsRunningScriptedSceneWithSpeech( CBaseFlex *pActor, bool bIgnoreInstancedScenes )
{
int c = m_ActiveScenes.Count();
for ( int i = 0; i < c; i++ )
{
CSceneEntity *pScene = m_ActiveScenes[ i ].Get();
if ( !pScene ||
!pScene->IsPlayingBack() ||
( bIgnoreInstancedScenes && dynamic_cast<CInstancedSceneEntity *>(pScene) != NULL )
)
{
continue;
}
if ( pScene->InvolvesActor( pActor ) )
{
if ( pScene->HasUnplayedSpeech() )
return true;
}
}
return false;
}
bool CSceneManager::IsRunningScriptedSceneWithSpeechAndNotPaused( CBaseFlex *pActor, bool bIgnoreInstancedScenes )
{
int c = m_ActiveScenes.Count();
for ( int i = 0; i < c; i++ )
{
CSceneEntity *pScene = m_ActiveScenes[ i ].Get();
if ( !pScene ||
!pScene->IsPlayingBack() ||
pScene->IsPaused() ||
( bIgnoreInstancedScenes && dynamic_cast<CInstancedSceneEntity *>(pScene) != NULL )
)
{
continue;
}
if ( pScene->InvolvesActor( pActor ) )
{
if ( pScene->HasUnplayedSpeech() )
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *actor -
// *soundname -
// soundlevel -
// soundtime -
//-----------------------------------------------------------------------------
void CSceneManager::QueueRestoredSound( CBaseFlex *actor, char const *soundname, soundlevel_t soundlevel, float time_in_past )
{
CRestoreSceneSound e;
e.actor = actor;
Q_strncpy( e.soundname, soundname, sizeof( e.soundname ) );
e.soundlevel = soundlevel;
e.time_in_past = time_in_past;
m_QueuedSceneSounds.AddToTail( e );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void RemoveActorFromScriptedScenes( CBaseFlex *pActor, bool instancedscenesonly, bool nonidlescenesonly, const char *pszThisSceneOnly )
{
GetSceneManager()->RemoveActorFromScenes( pActor, instancedscenesonly, nonidlescenesonly, pszThisSceneOnly );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void RemoveAllScenesInvolvingActor( CBaseFlex *pActor )
{
GetSceneManager()->RemoveScenesInvolvingActor( pActor );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void PauseActorsScriptedScenes( CBaseFlex *pActor, bool instancedscenesonly )
{
GetSceneManager()->PauseActorsScenes( pActor, instancedscenesonly );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool IsInInterruptableScenes( CBaseFlex *pActor )
{
return GetSceneManager()->IsInInterruptableScenes( pActor );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void ResumeActorsScriptedScenes( CBaseFlex *pActor, bool instancedscenesonly )
{
GetSceneManager()->ResumeActorsScenes( pActor, instancedscenesonly );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void QueueActorsScriptedScenesToResume( CBaseFlex *pActor, bool instancedscenesonly )
{
GetSceneManager()->QueueActorsScenesToResume( pActor, instancedscenesonly );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool IsRunningScriptedScene( CBaseFlex *pActor, bool bIgnoreInstancedScenes )
{
return GetSceneManager()->IsRunningScriptedScene( pActor, bIgnoreInstancedScenes );
}
bool IsRunningScriptedSceneAndNotPaused( CBaseFlex *pActor, bool bIgnoreInstancedScenes )
{
return GetSceneManager()->IsRunningScriptedSceneAndNotPaused( pActor, bIgnoreInstancedScenes );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool IsRunningScriptedSceneWithSpeech( CBaseFlex *pActor, bool bIgnoreInstancedScenes )
{
return GetSceneManager()->IsRunningScriptedSceneWithSpeech( pActor, bIgnoreInstancedScenes );
}
bool IsRunningScriptedSceneWithSpeechAndNotPaused( CBaseFlex *pActor, bool bIgnoreInstancedScenes )
{
return GetSceneManager()->IsRunningScriptedSceneWithSpeechAndNotPaused( pActor, bIgnoreInstancedScenes );
}
//===========================================================================================================
// SCENE LIST MANAGER
//===========================================================================================================
LINK_ENTITY_TO_CLASS( logic_scene_list_manager, CSceneListManager );
BEGIN_DATADESC( CSceneListManager )
DEFINE_UTLVECTOR( m_hListManagers, FIELD_EHANDLE ),
// Keys
DEFINE_KEYFIELD( m_iszScenes[0], FIELD_STRING, "scene0" ),
DEFINE_KEYFIELD( m_iszScenes[1], FIELD_STRING, "scene1" ),
DEFINE_KEYFIELD( m_iszScenes[2], FIELD_STRING, "scene2" ),
DEFINE_KEYFIELD( m_iszScenes[3], FIELD_STRING, "scene3" ),
DEFINE_KEYFIELD( m_iszScenes[4], FIELD_STRING, "scene4" ),
DEFINE_KEYFIELD( m_iszScenes[5], FIELD_STRING, "scene5" ),
DEFINE_KEYFIELD( m_iszScenes[6], FIELD_STRING, "scene6" ),
DEFINE_KEYFIELD( m_iszScenes[7], FIELD_STRING, "scene7" ),
DEFINE_KEYFIELD( m_iszScenes[8], FIELD_STRING, "scene8" ),
DEFINE_KEYFIELD( m_iszScenes[9], FIELD_STRING, "scene9" ),
DEFINE_KEYFIELD( m_iszScenes[10], FIELD_STRING, "scene10" ),
DEFINE_KEYFIELD( m_iszScenes[11], FIELD_STRING, "scene11" ),
DEFINE_KEYFIELD( m_iszScenes[12], FIELD_STRING, "scene12" ),
DEFINE_KEYFIELD( m_iszScenes[13], FIELD_STRING, "scene13" ),
DEFINE_KEYFIELD( m_iszScenes[14], FIELD_STRING, "scene14" ),
DEFINE_KEYFIELD( m_iszScenes[15], FIELD_STRING, "scene15" ),
DEFINE_FIELD( m_hScenes[0], FIELD_EHANDLE ),
DEFINE_FIELD( m_hScenes[1], FIELD_EHANDLE ),
DEFINE_FIELD( m_hScenes[2], FIELD_EHANDLE ),
DEFINE_FIELD( m_hScenes[3], FIELD_EHANDLE ),
DEFINE_FIELD( m_hScenes[4], FIELD_EHANDLE ),
DEFINE_FIELD( m_hScenes[5], FIELD_EHANDLE ),
DEFINE_FIELD( m_hScenes[6], FIELD_EHANDLE ),
DEFINE_FIELD( m_hScenes[7], FIELD_EHANDLE ),
DEFINE_FIELD( m_hScenes[8], FIELD_EHANDLE ),
DEFINE_FIELD( m_hScenes[9], FIELD_EHANDLE ),
DEFINE_FIELD( m_hScenes[10], FIELD_EHANDLE ),
DEFINE_FIELD( m_hScenes[11], FIELD_EHANDLE ),
DEFINE_FIELD( m_hScenes[12], FIELD_EHANDLE ),
DEFINE_FIELD( m_hScenes[13], FIELD_EHANDLE ),
DEFINE_FIELD( m_hScenes[14], FIELD_EHANDLE ),
DEFINE_FIELD( m_hScenes[15], FIELD_EHANDLE ),
// Inputs
DEFINE_INPUTFUNC( FIELD_VOID, "Shutdown", InputShutdown ),
END_DATADESC()
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSceneListManager::Activate( void )
{
BaseClass::Activate();
// Hook up scenes, but not after loading a game because they're saved.
if ( gpGlobals->eLoadType != MapLoad_LoadGame )
{
for ( int i = 0; i < SCENE_LIST_MANAGER_MAX_SCENES; i++ )
{
if ( m_iszScenes[i] != NULL_STRING )
{
m_hScenes[i] = gEntList.FindEntityByName( NULL, STRING(m_iszScenes[i]) );
if ( m_hScenes[i] )
{
CSceneEntity *pScene = dynamic_cast<CSceneEntity*>(m_hScenes[i].Get());
if ( pScene )
{
pScene->AddListManager( this );
}
else
{
CSceneListManager *pList = dynamic_cast<CSceneListManager*>(m_hScenes[i].Get());
if ( pList )
{
pList->AddListManager( this );
}
else
{
Warning( "%s(%s) found an entity that wasn't a logic_choreographed_scene or logic_scene_list_manager in slot %d, named %s\n", GetDebugName(), GetClassname(), i, STRING(m_iszScenes[i]) );
m_hScenes[i] = NULL;
}
}
}
else
{
Warning( "%s(%s) could not find scene %d, named %s\n", GetDebugName(), GetClassname(), i, STRING(m_iszScenes[i]) );
}
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose: A scene or manager in our list has started playing.
// Remove all scenes earlier in the list.
//-----------------------------------------------------------------------------
void CSceneListManager::SceneStarted( CBaseEntity *pSceneOrManager )
{
// Move backwards and call remove on all scenes / managers earlier in the list to the fired one
bool bFoundStart = false;
for ( int i = SCENE_LIST_MANAGER_MAX_SCENES-1; i >= 0; i-- )
{
if ( !m_hScenes[i] )
continue;
if ( bFoundStart )
{
RemoveScene( i );
}
else if ( m_hScenes[i] == pSceneOrManager )
{
bFoundStart = true;
}
}
// Tell any managers we're within that we've started a scene
if ( bFoundStart )
{
int c = m_hListManagers.Count();
for ( int i = 0; i < c; i++ )
{
if ( m_hListManagers[i] )
{
m_hListManagers[i]->SceneStarted( this );
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSceneListManager::AddListManager( CSceneListManager *pManager )
{
CHandle< CSceneListManager > h;
h = pManager;
// Only add it once
if ( m_hListManagers.Find( h ) == m_hListManagers.InvalidIndex() )
{
m_hListManagers.AddToTail( h );
}
}
//-----------------------------------------------------------------------------
// Purpose: Shut down all scenes, and then remove this entity
//-----------------------------------------------------------------------------
void CSceneListManager::InputShutdown( inputdata_t &inputdata )
{
ShutdownList();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSceneListManager::ShutdownList( void )
{
for ( int i = 0; i < SCENE_LIST_MANAGER_MAX_SCENES; i++ )
{
if ( m_hScenes[i] )
{
RemoveScene(i);
}
}
UTIL_Remove( this );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSceneListManager::RemoveScene( int iIndex )
{
CSceneEntity *pScene = dynamic_cast<CSceneEntity*>(m_hScenes[iIndex].Get());
if ( pScene )
{
// Remove the scene
UTIL_Remove( pScene );
return;
}
// Tell the list manager to shut down all scenes
CSceneListManager *pList = dynamic_cast<CSceneListManager*>(m_hScenes[iIndex].Get());
if ( pList )
{
pList->ShutdownList();
}
}
void ReloadSceneFromDisk( CBaseEntity *ent )
{
CSceneEntity *scene = dynamic_cast< CSceneEntity * >( ent );
if ( !scene )
return;
Assert( 0 );
}
// Purpose:
// Input : *ent -
// Output : char const
//-----------------------------------------------------------------------------
char const *GetSceneFilename( CBaseEntity *ent )
{
CSceneEntity *scene = dynamic_cast< CSceneEntity * >( ent );
if ( !scene )
return "";
return STRING( scene->m_iszSceneFile );
}
//-----------------------------------------------------------------------------
// Purpose: Return a list of the last 5 lines of speech from NPCs for bug reports
// Input :
// Output : speech - last 5 sound files played as speech
// returns the number of sounds in the returned list
//-----------------------------------------------------------------------------
int GetRecentNPCSpeech( recentNPCSpeech_t speech[ SPEECH_LIST_MAX_SOUNDS ] )
{
int i;
int num;
int index;
// clear out the output list
for( i = 0; i < SPEECH_LIST_MAX_SOUNDS; i++ )
{
speech[ i ].time = 0.0f;
speech[ i ].name[ 0 ] = 0;
speech[ i ].sceneName[ 0 ] = 0;
}
// copy the sound names into the list in order they were played
num = 0;
index = speechListIndex;
for( i = 0; i < SPEECH_LIST_MAX_SOUNDS; i++ )
{
if ( speechListSounds[ index ].name[ 0 ] )
{
// only copy names that are not zero length
speech[ num ] = speechListSounds[ index ];
num++;
}
index++;
if ( index >= SPEECH_LIST_MAX_SOUNDS )
{
index = 0;
}
}
return num;
}
//-----------------------------------------------------------------------------
// Purpose: Displays a list of the last 5 lines of speech from NPCs
// Input :
// Output :
//-----------------------------------------------------------------------------
static void ListRecentNPCSpeech( void )
{
if ( !UTIL_IsCommandIssuedByServerAdmin() )
return;
recentNPCSpeech_t speech[ SPEECH_LIST_MAX_SOUNDS ];
int num;
int i;
// get any sounds that were spoken by NPCs recently
num = GetRecentNPCSpeech( speech );
Msg( "Recent NPC speech:\n" );
for( i = 0; i < num; i++ )
{
Msg( " time: %6.3f sound name: %s scene: %s\n", speech[ i ].time, speech[ i ].name, speech[ i ].sceneName );
}
Msg( "Current time: %6.3f\n", gpGlobals->curtime );
}
static ConCommand ListRecentNPCSpeechCmd( "listRecentNPCSpeech", ListRecentNPCSpeech, "Displays a list of the last 5 lines of speech from NPCs.", FCVAR_DONTRECORD|FCVAR_GAMEDLL );
CON_COMMAND( scene_flush, "Flush all .vcds from the cache and reload from disk." )
{
if ( !UTIL_IsCommandIssuedByServerAdmin() )
return;
Msg( "Reloading\n" );
scenefilecache->Reload();
Msg( " done\n" );
}
| 0 | 0.983519 | 1 | 0.983519 | game-dev | MEDIA | 0.901172 | game-dev | 0.768875 | 1 | 0.768875 |
EphemeralSpace/ephemeral-space | 2,067 | Content.Client/Movement/Systems/FloorOcclusionSystem.cs | using Content.Shared.Movement.Components;
using Content.Shared.Movement.Systems;
using Robust.Client.GameObjects;
using Robust.Client.Graphics;
using Robust.Shared.Prototypes;
namespace Content.Client.Movement.Systems;
public sealed class FloorOcclusionSystem : SharedFloorOcclusionSystem
{
private static readonly ProtoId<ShaderPrototype> HorizontalCut = "HorizontalCut";
[Dependency] private readonly IPrototypeManager _proto = default!;
private EntityQuery<SpriteComponent> _spriteQuery;
public override void Initialize()
{
base.Initialize();
_spriteQuery = GetEntityQuery<SpriteComponent>();
SubscribeLocalEvent<FloorOcclusionComponent, ComponentStartup>(OnOcclusionStartup);
SubscribeLocalEvent<FloorOcclusionComponent, ComponentShutdown>(OnOcclusionShutdown);
SubscribeLocalEvent<FloorOcclusionComponent, AfterAutoHandleStateEvent>(OnOcclusionAuto);
}
private void OnOcclusionAuto(Entity<FloorOcclusionComponent> ent, ref AfterAutoHandleStateEvent args)
{
SetShader(ent.Owner, ent.Comp.Enabled);
}
private void OnOcclusionStartup(Entity<FloorOcclusionComponent> ent, ref ComponentStartup args)
{
SetShader(ent.Owner, ent.Comp.Enabled);
}
private void OnOcclusionShutdown(Entity<FloorOcclusionComponent> ent, ref ComponentShutdown args)
{
SetShader(ent.Owner, false);
}
protected override void SetEnabled(Entity<FloorOcclusionComponent> entity)
{
SetShader(entity.Owner, entity.Comp.Enabled);
}
private void SetShader(Entity<SpriteComponent?> sprite, bool enabled)
{
if (!_spriteQuery.Resolve(sprite.Owner, ref sprite.Comp, false))
return;
var shader = _proto.Index(HorizontalCut).Instance();
if (sprite.Comp.PostShader is not null && sprite.Comp.PostShader != shader)
return;
if (enabled)
{
sprite.Comp.PostShader = shader;
}
else
{
sprite.Comp.PostShader = null;
}
}
}
| 0 | 0.705161 | 1 | 0.705161 | game-dev | MEDIA | 0.981624 | game-dev | 0.893881 | 1 | 0.893881 |
Hachimi-Hachimi/Hachimi | 2,383 | src/il2cpp/hook/umamusume/StoryTimelineBlockData.rs | use std::ptr::null_mut;
use crate::il2cpp::{
ext::Il2CppObjectExt, symbols::{get_field_from_name, get_field_object_value, get_field_value, set_field_value, IList}, types::*
};
use super::{StoryTimelineTextClipData, StoryTimelineTrackData};
// StoryTimelineTextTrackData (derived class of StoryTimelineTrackData)
static mut TEXTTRACK_FIELD: *mut FieldInfo = null_mut();
pub fn get_TextTrack(this: *mut Il2CppObject) -> *mut Il2CppObject {
get_field_object_value(this, unsafe { TEXTTRACK_FIELD })
}
static mut BLOCKLENGTH_FIELD: *mut FieldInfo = null_mut();
pub fn get_BlockLength(this: *mut Il2CppObject) -> i32 {
get_field_value(this, unsafe { BLOCKLENGTH_FIELD })
}
pub fn set_BlockLength(this: *mut Il2CppObject, value: i32) {
set_field_value(this, unsafe { BLOCKLENGTH_FIELD }, &value)
}
// List<StoryTimelineCharaTrackData>
static mut CHARACTERTRACKLIST_FIELD: *mut FieldInfo = null_mut();
pub fn get_CharacterTrackList(this: *mut Il2CppObject) -> *mut Il2CppObject {
get_field_object_value(this, unsafe { CHARACTERTRACKLIST_FIELD })
}
// List<StoryTimelineScreenEffectTrackData>
static mut SCREENEFFECTTRACKLIST_FIELD: *mut FieldInfo = null_mut();
pub fn get_ScreenEffectTrackList(this: *mut Il2CppObject) -> *mut Il2CppObject {
get_field_object_value(this, unsafe { SCREENEFFECTTRACKLIST_FIELD })
}
// Specialization
pub fn get_text_clip(this: *mut Il2CppObject) -> Option<*mut Il2CppObject> {
let text_track = get_TextTrack(this);
if text_track.is_null() {
return None;
}
let clip_list = <IList>::new(StoryTimelineTrackData::get_ClipList(text_track))?;
// There should be a single text clip per track
let clip_data = clip_list.get(0)?;
let class = unsafe { (*clip_data).klass() };
if class != StoryTimelineTextClipData::class() {
return None;
}
Some(clip_data)
}
pub fn init(umamusume: *const Il2CppImage) {
get_class_or_return!(umamusume, Gallop, StoryTimelineBlockData);
unsafe {
TEXTTRACK_FIELD = get_field_from_name(StoryTimelineBlockData, c"TextTrack");
BLOCKLENGTH_FIELD = get_field_from_name(StoryTimelineBlockData, c"BlockLength");
CHARACTERTRACKLIST_FIELD = get_field_from_name(StoryTimelineBlockData, c"CharacterTrackList");
SCREENEFFECTTRACKLIST_FIELD = get_field_from_name(StoryTimelineBlockData, c"ScreenEffectTrackList");
}
} | 0 | 0.943673 | 1 | 0.943673 | game-dev | MEDIA | 0.726217 | game-dev | 0.913778 | 1 | 0.913778 |
fulpstation/fulpstation | 2,379 | code/datums/components/reagent_refiller.dm | /**
* ## Reagent refiller
* Refills any drinks poured out of the reagent container (and is allowed within the whitelisted reagents).
*/
/datum/component/reagent_refiller
/// Time to refill
var/time_to_refill
/// Callback to consume power
var/datum/callback/power_draw_callback
/// Amount of power to use from the cell
var/power_to_draw
/// Whitelist of reagents allowed to be synthesized
var/list/whitelisted_reagents
/datum/component/reagent_refiller/Initialize(
time_to_refill = 60 SECONDS,
datum/callback/power_draw_callback,
power_to_draw = 30,
whitelisted_reagents = list(/datum/reagent/consumable)
)
if(!is_reagent_container(parent))
return COMPONENT_INCOMPATIBLE
src.time_to_refill = time_to_refill
src.power_draw_callback = power_draw_callback
src.power_to_draw = power_to_draw
src.whitelisted_reagents = whitelisted_reagents
return ..()
/datum/component/reagent_refiller/Destroy(force)
power_draw_callback = null
return ..()
/datum/component/reagent_refiller/RegisterWithParent()
RegisterSignal(parent, COMSIG_ITEM_INTERACTING_WITH_ATOM, PROC_REF(refill))
RegisterSignal(parent, COMSIG_ATOM_EXITED, PROC_REF(delete_self))
/datum/component/reagent_refiller/UnregisterFromParent()
UnregisterSignal(parent, list(COMSIG_ITEM_INTERACTING_WITH_ATOM, COMSIG_ATOM_EXITED))
/datum/component/reagent_refiller/proc/delete_self()
SIGNAL_HANDLER
qdel(src)
/// Preps the reagent container for being refilled
/datum/component/reagent_refiller/proc/refill()
SIGNAL_HANDLER
var/obj/item/reagent_containers/container = parent
var/amount = min((container.amount_per_transfer_from_this + container.reagents.total_volume), container.reagents.total_volume)
if (amount == 0)
return
var/datum/reagent/refill = container.reagents.get_master_reagent()
if (!is_path_in_list(refill?.type, whitelisted_reagents))
return
addtimer(CALLBACK(src, PROC_REF(add_reagents), container, container.loc, refill.type, amount), time_to_refill)
/// Refills the reagent container, and uses cell power if applicable
/datum/component/reagent_refiller/proc/add_reagents(obj/item/reagent_containers/target, oldloc, reagent_to_refill, amount)
if (QDELETED(src) || QDELETED(target))
return
if (target.loc != oldloc)
return
target.reagents.add_reagent(reagent_to_refill, amount)
if (!isnull(power_draw_callback))
power_draw_callback.Invoke(power_to_draw)
| 0 | 0.853698 | 1 | 0.853698 | game-dev | MEDIA | 0.910214 | game-dev | 0.865508 | 1 | 0.865508 |
iM4dCat/Alien | 2,563 | src/main/java/dev/luminous/mod/gui/elements/ArmorHUD.java | package dev.luminous.mod.gui.elements;
import dev.luminous.Alien;
import dev.luminous.mod.gui.clickgui.ClickGuiScreen;
import dev.luminous.mod.modules.impl.client.HUD;
import dev.luminous.core.impl.GuiManager;
import dev.luminous.api.utils.entity.EntityUtil;
import dev.luminous.api.utils.render.ColorUtil;
import dev.luminous.api.utils.render.Render2DUtil;
import dev.luminous.api.utils.render.TextUtil;
import dev.luminous.mod.gui.clickgui.tabs.Tab;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.item.ItemStack;
import java.awt.*;
public class ArmorHUD extends Tab {
public ArmorHUD() {
this.width = 80;
this.height = 34;
this.x = (int) Alien.CONFIG.getFloat("armor_x", 0);
this.y = (int) Alien.CONFIG.getFloat("armor_y", 200);
}
@Override
public void update(double mouseX, double mouseY) {
if (GuiManager.currentGrabbed == null && HUD.INSTANCE.armor.getValue()) {
if (mouseX >= (x) && mouseX <= (x + width)) {
if (mouseY >= (y) && mouseY <= (y + height)) {
if (ClickGuiScreen.clicked) {
GuiManager.currentGrabbed = this;
}
}
}
}
}
@Override
public void draw(DrawContext drawContext, float partialTicks, Color color) {
MatrixStack matrixStack = drawContext.getMatrices();
if (HUD.INSTANCE.armor.getValue()) {
if (Alien.GUI.isClickGuiOpen()) {
Render2DUtil.drawRect(drawContext.getMatrices(), x, y, width, height, new Color(0, 0, 0, 70));
}
int xOff = 0;
for (ItemStack armor : mc.player.getInventory().armor) {
xOff += 20;
if (armor.isEmpty()) continue;
matrixStack.push();
int damage = EntityUtil.getDamagePercent(armor);
int yOffset = height / 2;
drawContext.drawItem(armor, this.x + width - xOff, this.y + yOffset);
drawContext.drawItemInSlot(mc.textRenderer, armor, this.x + width - xOff, this.y + yOffset);
TextUtil.drawStringScale(drawContext, damage + "%",
(float) (x + width + 2 - xOff),
(float) (y + yOffset - mc.textRenderer.fontHeight / 4d),
ColorUtil.fadeColor(new Color(196, 0, 0), new Color(0, 227, 0), damage / 100f).getRGB(), 0.5F);
/* drawContext.drawText(mc.textRenderer,
String.valueOf(damage),
x + width + 8 - xOff - mc.textRenderer.getWidth(String.valueOf(damage)) / 2,
y + yOffset - mc.textRenderer.fontHeight - 2,
new Color((int) (255f * (1f - ((float) damage / 100f))), (int) (255f * ((float) damage / 100f)), 0).getRGB(),
true);*/
matrixStack.pop();
}
}
}
}
| 0 | 0.78634 | 1 | 0.78634 | game-dev | MEDIA | 0.813653 | game-dev | 0.980696 | 1 | 0.980696 |
Electrical-Age/ElectricalAge | 4,733 | src/main/java/mods/eln/transparentnode/thermaldissipatoractive/ThermalDissipatorActiveElement.java | package mods.eln.transparentnode.thermaldissipatoractive;
import mods.eln.Eln;
import mods.eln.i18n.I18N;
import mods.eln.misc.Direction;
import mods.eln.misc.LRDU;
import mods.eln.misc.Utils;
import mods.eln.node.NodePeriodicPublishProcess;
import mods.eln.node.transparent.TransparentNode;
import mods.eln.node.transparent.TransparentNodeDescriptor;
import mods.eln.node.transparent.TransparentNodeElement;
import mods.eln.sim.ElectricalLoad;
import mods.eln.sim.ThermalLoad;
import mods.eln.sim.mna.component.Resistor;
import mods.eln.sim.nbt.NbtElectricalLoad;
import mods.eln.sim.nbt.NbtThermalLoad;
import mods.eln.sim.process.destruct.ThermalLoadWatchDog;
import mods.eln.sim.process.destruct.VoltageStateWatchDog;
import mods.eln.sim.process.destruct.WorldExplosion;
import net.minecraft.entity.player.EntityPlayer;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class ThermalDissipatorActiveElement extends TransparentNodeElement {
ThermalDissipatorActiveDescriptor descriptor;
NbtThermalLoad thermalLoad = new NbtThermalLoad("thermalLoad");
NbtElectricalLoad positiveLoad = new NbtElectricalLoad("positiveLoad");
ThermalDissipatorActiveSlowProcess slowProcess = new ThermalDissipatorActiveSlowProcess(this);
Resistor powerResistor = new Resistor(positiveLoad, null);
public ThermalDissipatorActiveElement(TransparentNode transparentNode,
TransparentNodeDescriptor descriptor) {
super(transparentNode, descriptor);
thermalLoadList.add(thermalLoad);
electricalLoadList.add(positiveLoad);
electricalComponentList.add(powerResistor);
slowProcessList.add(slowProcess);
this.descriptor = (ThermalDissipatorActiveDescriptor) descriptor;
slowProcessList.add(new NodePeriodicPublishProcess(node, 4f, 2f));
slowProcessList.add(thermalWatchdog);
thermalWatchdog
.set(thermalLoad)
.setTMax(this.descriptor.warmLimit)
.set(new WorldExplosion(this).machineExplosion());
WorldExplosion exp = new WorldExplosion(this).machineExplosion();
slowProcessList.add(voltageWatchdog.set(positiveLoad).setUNominal(this.descriptor.nominalElectricalU).set(exp));
}
VoltageStateWatchDog voltageWatchdog = new VoltageStateWatchDog();
ThermalLoadWatchDog thermalWatchdog = new ThermalLoadWatchDog();
@Override
public ElectricalLoad getElectricalLoad(Direction side, LRDU lrdu) {
if (side == front || side == front.getInverse()) return positiveLoad;
return null;
}
@Override
public ThermalLoad getThermalLoad(Direction side, LRDU lrdu) {
if (side == Direction.YN || side == Direction.YP || lrdu != lrdu.Down) return null;
if (side == front || side == front.getInverse()) return null;
return thermalLoad;
}
@Override
public int getConnectionMask(Direction side, LRDU lrdu) {
if (side == Direction.YN || side == Direction.YP || lrdu != lrdu.Down) return 0;
if (side == front || side == front.getInverse()) return node.maskElectricalPower;
return node.maskThermal;
}
@Override
public String multiMeterString(Direction side) {
return Utils.plotVolt("U : ", positiveLoad.getU()) + Utils.plotAmpere("I : ", positiveLoad.getCurrent());
}
@Override
public String thermoMeterString(Direction side) {
return Utils.plotCelsius("T : ", thermalLoad.Tc) + Utils.plotPower("P : ", thermalLoad.getPower());
}
@Override
public void initialize() {
descriptor.applyTo(thermalLoad);
descriptor.applyTo(positiveLoad, powerResistor);
connect();
}
@Override
public boolean onBlockActivated(EntityPlayer entityPlayer, Direction side,
float vx, float vy, float vz) {
return false;
}
@Override
public void networkSerialize(DataOutputStream stream) {
super.networkSerialize(stream);
try {
stream.writeFloat(lastPowerFactor = (float) (powerResistor.getP() / descriptor.electricalNominalP));
} catch (IOException e) {
e.printStackTrace();
}
//Utils.println("DISIP");
}
public float lastPowerFactor;
@Override
public Map<String, String> getWaila() {
Map<String, String> info = new HashMap<String, String>();
info.put(I18N.tr("Temperature"), Utils.plotCelsius("", thermalLoad.Tc));
if (Eln.wailaEasyMode) {
info.put(I18N.tr("Thermal power"), Utils.plotPower("", thermalLoad.getPower()));
}
return info;
}
}
| 0 | 0.83914 | 1 | 0.83914 | game-dev | MEDIA | 0.739065 | game-dev | 0.962268 | 1 | 0.962268 |
mekanism/Mekanism | 17,611 | src/datagen/main/java/mekanism/common/loot/table/BaseBlockLootTables.java | package mekanism.common.loot.table;
import it.unimi.dsi.fastutil.objects.ReferenceArraySet;
import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import mekanism.api.annotations.NothingNullByDefault;
import mekanism.common.Mekanism;
import mekanism.common.attachments.containers.ContainerType;
import mekanism.common.block.BlockPersonalStorage;
import mekanism.common.block.attribute.Attribute;
import mekanism.common.block.attribute.Attributes.AttributeInventory;
import mekanism.common.lib.frequency.FrequencyType;
import mekanism.common.lib.frequency.IFrequencyHandler;
import mekanism.common.lib.frequency.IFrequencyItem;
import mekanism.common.registries.MekanismBlocks;
import mekanism.common.resource.ore.OreBlockType;
import mekanism.common.tile.base.TileEntityMekanism;
import mekanism.common.tile.base.TileEntityUpdateable;
import net.minecraft.advancements.critereon.StatePropertiesPredicate;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.component.DataComponentType;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.data.loot.BlockLootSubProvider;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.flag.FeatureFlags;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.enchantment.Enchantments;
import net.minecraft.world.level.ItemLike;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.EntityBlock;
import net.minecraft.world.level.block.SlabBlock;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.properties.SlabType;
import net.minecraft.world.level.storage.loot.LootPool;
import net.minecraft.world.level.storage.loot.LootTable;
import net.minecraft.world.level.storage.loot.LootTable.Builder;
import net.minecraft.world.level.storage.loot.entries.LootItem;
import net.minecraft.world.level.storage.loot.entries.LootPoolEntryContainer;
import net.minecraft.world.level.storage.loot.functions.ApplyBonusCount;
import net.minecraft.world.level.storage.loot.functions.CopyComponentsFunction;
import net.minecraft.world.level.storage.loot.functions.CopyNameFunction;
import net.minecraft.world.level.storage.loot.functions.FunctionUserBuilder;
import net.minecraft.world.level.storage.loot.functions.LootItemFunction;
import net.minecraft.world.level.storage.loot.functions.SetItemCountFunction;
import net.minecraft.world.level.storage.loot.predicates.ConditionUserBuilder;
import net.minecraft.world.level.storage.loot.predicates.ExplosionCondition;
import net.minecraft.world.level.storage.loot.predicates.LootItemBlockStatePropertyCondition;
import net.minecraft.world.level.storage.loot.predicates.LootItemCondition;
import net.minecraft.world.level.storage.loot.providers.number.ConstantValue;
import net.minecraft.world.level.storage.loot.providers.number.NumberProvider;
import net.minecraft.world.level.storage.loot.providers.number.UniformGenerator;
import net.neoforged.neoforge.registries.DeferredHolder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public abstract class BaseBlockLootTables extends BlockLootSubProvider {
private final Set<Block> knownBlocks = new ReferenceOpenHashSet<>();
//Note: We use an array set as we never expect this to have more than a few elements (in reality it only ever has one)
private final Set<Block> toSkip = new ReferenceArraySet<>();
protected BaseBlockLootTables(HolderLookup.Provider provider) {
//Note: We manually handle explosion resistance on a case by case basis dynamically
super(Collections.emptySet(), FeatureFlags.VANILLA_SET, provider);
}
@Override
protected void add(@NotNull Block block, @NotNull LootTable.Builder table) {
//Overwrite the core register method to add to our list of known blocks
super.add(block, table);
knownBlocks.add(block);
}
@NotNull
@Override
protected Iterable<Block> getKnownBlocks() {
return knownBlocks;
}
@SafeVarargs
protected final void skip(Holder<Block>... blockProviders) {
for (Holder<Block> blockProvider : blockProviders) {
toSkip.add(blockProvider.value());
}
}
protected boolean skipBlock(Holder<Block> holder) {
Block block = holder.value();
//Skip any blocks that we already registered a table for or have marked to skip
return knownBlocks.contains(block) || toSkip.contains(block);
}
protected void add(Holder<Block> block, Function<Block, LootTable.Builder> factory) {
add(block.value(), factory);
}
protected LootTable.Builder createOreDrop(Block block, Holder<Item> item) {
return createSilkTouchDispatchTable(block, applyExplosionDecay(block, LootItem.lootTableItem(item.value())
.apply(ApplyBonusCount.addOreBonusCount(this.registries.holderOrThrow(Enchantments.FORTUNE)))
));
}
protected LootTable.Builder droppingWithFortuneOrRandomly(Block block, Holder<Item> item, UniformGenerator range) {
return createSilkTouchDispatchTable(block, applyExplosionDecay(block, LootItem.lootTableItem(item.value())
.apply(SetItemCountFunction.setCount(range))
.apply(ApplyBonusCount.addOreBonusCount(this.registries.holderOrThrow(Enchantments.FORTUNE)))
));
}
//Holder versions of BlockLootTable methods, modified to support varargs/lists
protected void dropSelf(Collection<? extends Holder<Block>> blocks) {
for (Holder<Block> block : blocks) {
if (!skipBlock(block)) {
dropSelf(block.value());
}
}
}
protected void add(Function<Block, Builder> factory, Collection<? extends Holder<Block>> blockProviders) {
for (Holder<Block> blockProvider : blockProviders) {
add(blockProvider.value(), factory);
}
}
@SafeVarargs
protected final void add(Function<Block, Builder> factory, Holder<Block>... blockProviders) {
for (Holder<Block> blockProvider : blockProviders) {
add(blockProvider.value(), factory);
}
}
protected void add(Function<Block, Builder> factory, OreBlockType... oreTypes) {
for (OreBlockType oreType : oreTypes) {
add(oreType.stone(), factory);
add(oreType.deepslate(), factory);
}
}
protected void dropSelfWithContents(Collection<? extends DeferredHolder<Block, ?>> blockProviders) {
//TODO: See if there is other stuff we want to be transferring which we currently do not
// For example, when writing this we added dump mode for chemical tanks to getting transferred to the item
for (DeferredHolder<Block, ?> blockProvider : blockProviders) {
if (skipBlock(blockProvider)) {
continue;
}
Block block = blockProvider.value();
boolean hasComponents = false;
CopyComponentsFunction.Builder componentsBuilder = CopyComponentsFunction.copyComponents(CopyComponentsFunction.Source.BLOCK_ENTITY);
boolean hasContents = false;
ItemStack stack = new ItemStack(block);
LootItem.Builder<?> itemLootPool = LootItem.lootTableItem(block);
//delayed items until after other copies are added, for cases like referencing the owner
DelayedLootItemBuilder delayedPool = new DelayedLootItemBuilder();
@Nullable
BlockEntity tile = null;
if (block instanceof EntityBlock entityBlock) {
tile = entityBlock.newBlockEntity(BlockPos.ZERO, block.defaultBlockState());
}
if (tile instanceof IFrequencyHandler frequencyHandler) {
Set<FrequencyType<?>> customFrequencies = frequencyHandler.getFrequencyComponent().getCustomFrequencies();
if (!customFrequencies.isEmpty() && stack.getItem() instanceof IFrequencyItem frequencyItem) {
FrequencyType<?> frequencyType = frequencyItem.getFrequencyType();
if (!customFrequencies.contains(frequencyType)) {
Mekanism.logger.warn("Block missing frequency type '{}' expected by item: {}", frequencyType.getName(), blockProvider.getId());
}
}
}
if (tile instanceof TileEntityUpdateable tileEntity) {
List<DataComponentType<?>> components = tileEntity.getRemapEntries();
if (!components.isEmpty()) {
Set<DataComponentType<?>> skipTypes = ContainerType.TYPES.stream().map(type -> type.getComponentType().get()).collect(Collectors.toSet());
hasComponents = true;
//Sort the components so that the order is consistent when writing to json
components.sort(Comparator.comparing(BuiltInRegistries.DATA_COMPONENT_TYPE::getKey, ResourceLocation::compareNamespaced));
for (DataComponentType<?> remapEntry : components) {
//Allow containers to be handled below where we do extra validation that the stack actually supports it
if (!skipTypes.contains(remapEntry)) {
componentsBuilder.include(remapEntry);
}
}
}
}
if (tile instanceof TileEntityMekanism tileEntity) {
if (tileEntity.isNameable()) {
itemLootPool.apply(CopyNameFunction.copyName(CopyNameFunction.NameSource.BLOCK_ENTITY));
}
for (ContainerType<?, ?, ?> type : ContainerType.TYPES) {
List<?> containers = tileEntity.persists(type) ? type.getContainers(tileEntity) : Collections.emptyList();
int attachmentContainers = type.getContainerCount(stack);
if (containers.size() == attachmentContainers) {
if (!containers.isEmpty()) {
componentsBuilder.include(type.getComponentType().get());
hasComponents = true;
if (type != ContainerType.ENERGY && type != ContainerType.HEAT) {
hasContents = true;
}
}
} else if (attachmentContainers == 0) {
//TODO: Improve how we handle skipping warnings for known missing types
if (type == ContainerType.ITEM && block instanceof BlockPersonalStorage<?, ?>) {
//We don't want explosions causing personal storage items to be directly destroyed. It is also known that the attachment is missing
hasContents = true;
} else if (type != ContainerType.CHEMICAL || !MekanismBlocks.RADIOACTIVE_WASTE_BARREL.keyMatches(blockProvider)) {
Mekanism.logger.warn("Container type: {}, item missing attachments: {}", type.getComponentName(), blockProvider.getId());
}
} else if (containers.isEmpty()) {
Mekanism.logger.warn("Container type: {}, item has attachments but block doesn't have containers: {}", type.getComponentName(), blockProvider.getId());
} else {
Mekanism.logger.warn("Container type: {}, has {} item attachments and block has {} containers: {}", type.getComponentName(), attachmentContainers,
containers.size(), blockProvider.getId());
}
}
}
@SuppressWarnings("unchecked")
AttributeInventory<DelayedLootItemBuilder> attributeInventory = Attribute.get(blockProvider, AttributeInventory.class);
if (attributeInventory != null) {
hasContents |= attributeInventory.applyLoot(delayedPool);
}
if (hasComponents) {
itemLootPool.apply(componentsBuilder);
}
//apply the delayed ones last, so that NBT funcs have happened first
for (LootItemFunction.Builder function : delayedPool.functions) {
itemLootPool.apply(function);
}
for (LootItemCondition.Builder condition : delayedPool.conditions) {
itemLootPool.when(condition);
}
add(block, LootTable.lootTable().withPool(applyExplosionCondition(hasContents, LootPool.lootPool()
.name("main")
.setRolls(ConstantValue.exactly(1))
.add(itemLootPool)
)));
}
}
/**
* Like vanilla's {@link BlockLootSubProvider#applyExplosionCondition(ItemLike, ConditionUserBuilder)} except with a boolean for if it is explosion resistant.
*/
private static <T extends ConditionUserBuilder<T>> T applyExplosionCondition(boolean explosionResistant, ConditionUserBuilder<T> condition) {
return explosionResistant ? condition.unwrap() : condition.when(ExplosionCondition.survivesExplosion());
}
/**
* Like vanilla's {@link BlockLootSubProvider#createSlabItemTable(Block)} except with a named pool
*/
@NotNull
@Override
protected LootTable.Builder createSlabItemTable(@NotNull Block slab) {
return LootTable.lootTable().withPool(LootPool.lootPool()
.name("main")
.setRolls(ConstantValue.exactly(1))
.add(applyExplosionDecay(slab, LootItem.lootTableItem(slab)
.apply(SetItemCountFunction.setCount(ConstantValue.exactly(2))
.when(LootItemBlockStatePropertyCondition.hasBlockStateProperties(slab)
.setProperties(StatePropertiesPredicate.Builder.properties().hasProperty(SlabBlock.TYPE, SlabType.DOUBLE)))
)
)
)
);
}
/**
* Like vanilla's {@link BlockLootSubProvider#dropOther(Block, ItemLike)} except with a named pool
*/
@Override
public void dropOther(@NotNull Block block, @NotNull ItemLike drop) {
add(block, createSingleItemTable(drop));
}
/**
* Like vanilla's {@link BlockLootSubProvider#createSingleItemTable(ItemLike)} except with a named pool
*/
@NotNull
@Override
public LootTable.Builder createSingleItemTable(@NotNull ItemLike item) {
return LootTable.lootTable().withPool(applyExplosionCondition(item, LootPool.lootPool()
.name("main")
.setRolls(ConstantValue.exactly(1))
.add(LootItem.lootTableItem(item))
));
}
/**
* Like vanilla's {@link BlockLootSubProvider#createSingleItemTableWithSilkTouch(Block, ItemLike, NumberProvider)} except with a named pool
*/
@NotNull
@Override
protected LootTable.Builder createSingleItemTableWithSilkTouch(@NotNull Block block, @NotNull ItemLike item, @NotNull NumberProvider range) {
return createSilkTouchDispatchTable(block, applyExplosionDecay(block, LootItem.lootTableItem(item).apply(SetItemCountFunction.setCount(range))));
}
/**
* Like vanilla's {@link BlockLootSubProvider#createSilkTouchDispatchTable(Block, LootPoolEntryContainer.Builder)} except with a named pool
*/
@NotNull
@Override
protected LootTable.Builder createSilkTouchDispatchTable(@NotNull Block block, @NotNull LootPoolEntryContainer.Builder<?> builder) {
return createSelfDropDispatchTable(block, hasSilkTouch(), builder);
}
/**
* Like vanilla's {@link BlockLootSubProvider#createSelfDropDispatchTable(Block, LootItemCondition.Builder, LootPoolEntryContainer.Builder)} except with a named pool
*/
@NotNull
protected static LootTable.Builder createSelfDropDispatchTable(@NotNull Block block, @NotNull LootItemCondition.Builder conditionBuilder,
@NotNull LootPoolEntryContainer.Builder<?> entry) {
return LootTable.lootTable().withPool(LootPool.lootPool()
.name("main")
.setRolls(ConstantValue.exactly(1))
.add(LootItem.lootTableItem(block)
.when(conditionBuilder)
.otherwise(entry)
)
);
}
@NothingNullByDefault
public static class DelayedLootItemBuilder implements ConditionUserBuilder<DelayedLootItemBuilder>, FunctionUserBuilder<DelayedLootItemBuilder> {
private final List<LootItemFunction.Builder> functions = new ArrayList<>();
private final List<LootItemCondition.Builder> conditions = new ArrayList<>();
@Override
public DelayedLootItemBuilder apply(LootItemFunction.Builder pFunctionBuilder) {
functions.add(pFunctionBuilder);
return this;
}
@Override
public DelayedLootItemBuilder when(LootItemCondition.Builder pConditionBuilder) {
conditions.add(pConditionBuilder);
return this;
}
@Override
public DelayedLootItemBuilder unwrap() {
return this;
}
}
} | 0 | 0.957078 | 1 | 0.957078 | game-dev | MEDIA | 0.998849 | game-dev | 0.941255 | 1 | 0.941255 |
dufernst/LegionCore-7.3.5 | 25,850 | src/server/game/Handlers/AuctionHouseHandler.cpp | /*
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "AuctionHousePackets.h"
#include "AuctionHouseMgr.h"
#include "DatabaseEnv.h"
#include "ObjectMgr.h"
void WorldSession::HandleAuctionHelloRequest(WorldPackets::AuctionHouse::AuctionHelloRequest& packet)
{
Creature* unit = GetPlayer()->GetNPCIfCanInteractWith(packet.Guid, UNIT_NPC_FLAG_AUCTIONEER);
if (!unit)
{
TC_LOG_DEBUG(LOG_FILTER_NETWORKIO, "WORLD: HandleAuctionHelloRequest - Unit (GUID: %u) not found or you can't interact with him.", uint32(packet.Guid.GetGUIDLow()));
return;
}
if (GetPlayer()->HasUnitState(UNIT_STATE_DIED))
GetPlayer()->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH);
SendAuctionHello(packet.Guid, unit);
}
void WorldSession::SendAuctionHello(ObjectGuid guid, Creature* unit)
{
if (GetPlayer()->getLevel() < sWorld->getIntConfig(CONFIG_AUCTION_LEVEL_REQ))
{
SendNotification(GetTrinityString(LANG_AUCTION_REQ), sWorld->getIntConfig(CONFIG_AUCTION_LEVEL_REQ));
return;
}
AuctionHouseEntry const* ahEntry = AuctionHouseMgr::GetAuctionHouseEntry(unit->getFaction(), nullptr);
if (!ahEntry)
return;
WorldPackets::AuctionHouse::AuctionHelloResponse auctionHelloResponse;
auctionHelloResponse.Guid = guid;
auctionHelloResponse.OpenForBusiness = true; // 3.3.3: 1 - AH enabled, 0 - AH disabled
SendPacket(auctionHelloResponse.Write());
}
void WorldSession::SendAuctionCommandResult(AuctionEntry* auction, uint32 action, uint32 errorCode, uint32 /*bidError = 0*/)
{
WorldPackets::AuctionHouse::AuctionCommandResult auctionCommandResult;
auctionCommandResult.InitializeAuction(auction);
auctionCommandResult.Command = action;
auctionCommandResult.ErrorCode = errorCode;
SendPacket(auctionCommandResult.Write());
}
void WorldSession::SendAuctionOutBidNotification(AuctionEntry const* auction, Item const* item)
{
WorldPackets::AuctionHouse::AuctionOutBidNotification packet;
packet.BidAmount = auction->bid;
packet.MinIncrement = auction->GetAuctionOutBid();
packet.Info.Initialize(auction, item);
SendPacket(packet.Write());
}
void WorldSession::SendAuctionClosedNotification(AuctionEntry const* auction, float mailDelay, bool sold, Item const* item)
{
WorldPackets::AuctionHouse::AuctionClosedNotification packet;
packet.Info.Initialize(auction, item);
packet.ProceedsMailDelay = mailDelay;
packet.Sold = sold;
SendPacket(packet.Write());
}
void WorldSession::SendAuctionWonNotification(AuctionEntry const* auction, Item const* item)
{
WorldPackets::AuctionHouse::AuctionWonNotification packet;
packet.Info.Initialize(auction, item);
SendPacket(packet.Write());
}
void WorldSession::SendAuctionOwnerBidNotification(AuctionEntry const* auction, Item const* item)
{
WorldPackets::AuctionHouse::AuctionOwnerBidNotification packet;
packet.Info.Initialize(auction, item);
packet.Bidder = ObjectGuid::Create<HighGuid::Player>(auction->bidder);
packet.MinIncrement = auction->GetAuctionOutBid();
SendPacket(packet.Write());
}
void WorldSession::HandleAuctionSellItem(WorldPackets::AuctionHouse::AuctionSellItem& packet)
{
for (auto const& item : packet.Items)
if (!item.Guid || !item.UseCount || item.UseCount > 1000)
return;
if (!packet.MinBid || !packet.RunTime)
return;
if (packet.MinBid > MAX_MONEY_AMOUNT || packet.BuyoutPrice > MAX_MONEY_AMOUNT)
{
SendAuctionCommandResult(nullptr, AUCTION_SELL_ITEM, ERR_AUCTION_DATABASE_ERROR);
return;
}
Creature* creature = GetPlayer()->GetNPCIfCanInteractWith(packet.Auctioneer, UNIT_NPC_FLAG_AUCTIONEER);
if (!creature)
{
TC_LOG_DEBUG(LOG_FILTER_NETWORKIO, "WORLD: HandleAuctionSellItem - Unit (GUID: %u) not found or you can't interact with him.", packet.Auctioneer.GetGUIDLow());
return;
}
uint32 houseId = 0;
AuctionHouseEntry const* auctionHouseEntry = AuctionHouseMgr::GetAuctionHouseEntry(creature->getFaction(), &houseId);
if (!auctionHouseEntry)
{
TC_LOG_DEBUG(LOG_FILTER_NETWORKIO, "WORLD: HandleAuctionSellItem - Unit (GUID: %u) has wrong faction.", packet.Auctioneer.GetGUIDLow());
return;
}
packet.RunTime *= MINUTE;
switch (packet.RunTime)
{
case 1 * MIN_AUCTION_TIME:
case 2 * MIN_AUCTION_TIME:
case 4 * MIN_AUCTION_TIME:
break;
default:
return;
}
if (GetPlayer()->HasUnitState(UNIT_STATE_DIED))
GetPlayer()->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH);
uint32 finalCount = 0;
for (auto const& packetItem : packet.Items)
{
Item* item = _player->GetItemByGuid(packetItem.Guid);
if (!item)
{
SendAuctionCommandResult(nullptr, AUCTION_SELL_ITEM, ERR_AUCTION_ITEM_NOT_FOUND);
return;
}
if (sAuctionMgr->GetAItem(item->GetGUIDLow()) || !item->CanBeTraded() || item->IsNotEmptyBag() ||
item->GetTemplate()->GetFlags() & ITEM_FLAG_CONJURED || item->GetUInt32Value(ITEM_FIELD_EXPIRATION) ||
item->GetCount() < packetItem.UseCount || _player->GetItemCount(item->GetEntry(), false) < packetItem.UseCount)
{
SendAuctionCommandResult(nullptr, AUCTION_SELL_ITEM, ERR_AUCTION_DATABASE_ERROR);
return;
}
if (packet.Items.empty() && (packetItem.Guid.GetEntry() != item->GetEntry() || packetItem.Guid.GetGUIDLow() == item->GetGUIDLow()))
{
sWorld->BanAccount(BAN_CHARACTER, _player->GetName(), "45d", "Dupe Auction mop", "System");
return;
}
finalCount += packetItem.UseCount;
}
if (packet.Items.empty())
{
SendAuctionCommandResult(nullptr, AUCTION_SELL_ITEM, ERR_AUCTION_DATABASE_ERROR);
return;
}
if (!finalCount)
{
SendAuctionCommandResult(nullptr, AUCTION_SELL_ITEM, ERR_AUCTION_DATABASE_ERROR);
return;
}
for (size_t i = 0; i < packet.Items.size() - 1; ++i)
{
for (size_t j = i + 1; j < packet.Items.size(); ++j)
{
if (packet.Items[i].Guid == packet.Items[j].Guid)
{
SendAuctionCommandResult(nullptr, AUCTION_SELL_ITEM, ERR_AUCTION_DATABASE_ERROR);
return;
}
}
}
for (auto const& packetItem : packet.Items)
{
Item* item = _player->GetItemByGuid(packetItem.Guid);
if (item->GetMaxStackCount() < finalCount)
{
SendAuctionCommandResult(nullptr, AUCTION_SELL_ITEM, ERR_AUCTION_DATABASE_ERROR);
return;
}
}
for (auto const& packetItem : packet.Items)
{
Item* item = _player->GetItemByGuid(packetItem.Guid);
auto auctionTime = uint32(packet.RunTime * sWorld->getRate(RATE_AUCTION_TIME));
AuctionHouseObject* auctionHouse = sAuctionMgr->GetAuctionsMap(creature->getFaction());
uint32 deposit = sAuctionMgr->GetAuctionDeposit(auctionHouseEntry, packet.RunTime, item, finalCount);
if (!_player->HasEnoughMoney(static_cast<uint64>(deposit)))
{
SendAuctionCommandResult(nullptr, AUCTION_SELL_ITEM, ERR_AUCTION_NOT_ENOUGHT_MONEY);
return;
}
_player->ModifyMoney(-int32(deposit));
auto AH = new AuctionEntry;
AH->Id = sObjectMgr->GenerateAuctionID();
if (sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION))
AH->auctioneer = 35606;
else
AH->auctioneer = packet.Auctioneer.GetEntry();
// Required stack size of auction matches to current item stack size, just move item to auctionhouse
if (packet.Items.size() == 1 && item->GetCount() == packet.Items[0].UseCount)
{
if (GetSecurity() > SEC_PLAYER && sWorld->getBoolConfig(CONFIG_GM_LOG_TRADE))
{
sLog->outCommand(GetAccountId(), "GM %s (Account: %u) create auction: %s (Entry: %u Count: %u)",
GetPlayerName().c_str(), GetAccountId(), item->GetTemplate()->GetName()->Str[_player->GetSession()->GetSessionDbLocaleIndex()], item->GetEntry(), item->GetCount());
}
AH->itemGUIDLow = item->GetGUIDLow();
AH->itemEntry = item->GetEntry();
AH->itemCount = item->GetCount();
AH->owner = _player->GetGUIDLow();
AH->startbid = packet.MinBid;
AH->bidder = 0;
AH->bid = 0;
AH->buyout = packet.BuyoutPrice;
AH->expire_time = time(nullptr) + auctionTime;
AH->deposit = deposit;
AH->auctionHouseEntry = auctionHouseEntry;
sAuctionMgr->AddAItem(item);
auctionHouse->AddAuction(AH);
_player->MoveItemFromInventory(item, true);
SQLTransaction trans = CharacterDatabase.BeginTransaction();
item->DeleteFromInventoryDB(trans);
item->SaveToDB(trans);
AH->SaveToDB(trans);
_player->SaveInventoryAndGoldToDB(trans);
CharacterDatabase.CommitTransaction(trans);
SendAuctionCommandResult(AH, AUCTION_SELL_ITEM, ERR_AUCTION_OK);
GetPlayer()->UpdateAchievementCriteria(CRITERIA_TYPE_CREATE_AUCTION, 1);
return;
}
// Required stack size of auction does not match to current item stack size, clone item and set correct stack size
Item* newItem = item->CloneItem(finalCount, _player);
if (!newItem)
{
SendAuctionCommandResult(nullptr, AUCTION_SELL_ITEM, ERR_AUCTION_DATABASE_ERROR);
return;
}
//if (newItem->GetEntry() == 38186)
// TC_LOG_DEBUG(LOG_FILTER_EFIR, "HandleAuctionSellItem - CloneItem of item %u; finalCount = %u playerGUID %u, itemGUID %u", newItem->GetEntry(), finalCount, _player->GetGUID().GetCounter(), newItem->GetGUID().GetCounter());
if (GetSecurity() > SEC_PLAYER && sWorld->getBoolConfig(CONFIG_GM_LOG_TRADE))
{
sLog->outCommand(GetAccountId(), "GM %s (Account: %u) create auction: %s (Entry: %u Count: %u)",
GetPlayerName().c_str(), GetAccountId(), newItem->GetTemplate()->GetName()->Str[_player->GetSession()->GetSessionDbLocaleIndex()], newItem->GetEntry(), newItem->GetCount());
}
AH->itemGUIDLow = newItem->GetGUIDLow();
AH->itemEntry = newItem->GetEntry();
AH->itemCount = newItem->GetCount();
AH->owner = _player->GetGUIDLow();
AH->startbid = packet.MinBid;
AH->bidder = 0;
AH->bid = 0;
AH->buyout = packet.BuyoutPrice;
AH->expire_time = time(nullptr) + auctionTime;
AH->deposit = deposit;
AH->auctionHouseEntry = auctionHouseEntry;
sAuctionMgr->AddAItem(newItem);
auctionHouse->AddAuction(AH);
SQLTransaction trans = CharacterDatabase.BeginTransaction();
for (auto const& v : packet.Items)
{
Item* item2 = _player->GetItemByGuid(v.Guid);
// Item stack count equals required count, ready to delete item - cloned item will be used for auction
if (item2->GetCount() == v.UseCount)
{
_player->MoveItemFromInventory(item2, true);
item2->DeleteFromInventoryDB(trans);
item2->DeleteFromDB(trans);
delete item2;
}
else // Item stack count is bigger than required count, update item stack count and save to database - cloned item will be used for auction
{
item2->SetCount(item2->GetCount() - v.UseCount);
item2->SetState(ITEM_CHANGED, _player);
_player->ItemRemovedQuestCheck(item2->GetEntry(), v.UseCount);
item2->SendUpdateToPlayer(_player);
item2->SaveToDB(trans);
}
}
newItem->SaveToDB(trans);
AH->SaveToDB(trans);
_player->SaveInventoryAndGoldToDB(trans);
CharacterDatabase.CommitTransaction(trans);
SendAuctionCommandResult(AH, AUCTION_SELL_ITEM, ERR_AUCTION_OK);
GetPlayer()->UpdateAchievementCriteria(CRITERIA_TYPE_CREATE_AUCTION, 1);
return;
}
}
void WorldSession::HandleAuctionPlaceBid(WorldPackets::AuctionHouse::AuctionPlaceBid& packet)
{
if (!packet.AuctionItemID || !packet.BidAmount)
return;
// check for cheaters
Player* player = GetPlayer();
Creature* creature = player->GetNPCIfCanInteractWith(packet.Auctioneer, UNIT_NPC_FLAG_AUCTIONEER);
if (!creature)
{
TC_LOG_DEBUG(LOG_FILTER_NETWORKIO, "WORLD: HandleAuctionPlaceBid - Unit (GUID: %u) not found or you can't interact with him.", uint32(packet.Auctioneer.GetGUIDLow()));
return;
}
if (player->HasUnitState(UNIT_STATE_DIED))
player->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH);
AuctionHouseObject* auctionHouse = sAuctionMgr->GetAuctionsMap(creature->getFaction());
AuctionEntry* auction = auctionHouse->GetAuction(packet.AuctionItemID);
if (!auction || auction->owner == player->GetGUIDLow())
{
//you cannot bid your own auction:
SendAuctionCommandResult(nullptr, AUCTION_PLACE_BID, ERR_AUCTION_BID_OWN);
return;
}
// impossible have online own another character (use this for speedup check in case online owner)
/*Player* auction_owner = ObjectAccessor::FindPlayer(MAKE_NEW_GUID(auction->owner, 0, HighGuid::Player));
if (!auction_owner && ObjectMgr::GetPlayerAccountIdByGUID(MAKE_NEW_GUID(auction->owner, 0, HighGuid::Player)) == player->GetSession()->GetAccountId())
{
//you cannot bid your another character auction:
SendAuctionCommandResult(NULL, AUCTION_PLACE_BID, ERR_AUCTION_BID_OWN);
return;
}*/
// cheating
if (packet.BidAmount <= auction->bid || packet.BidAmount < auction->startbid)
return;
// BidAmount too low for next bid if not buyout
if ((packet.BidAmount < auction->buyout || auction->buyout == 0) &&
packet.BidAmount < auction->bid + auction->GetAuctionOutBid())
{
// client already test it but just in case ...
SendAuctionCommandResult(auction, AUCTION_PLACE_BID, ERR_AUCTION_HIGHER_BID);
return;
}
if (!player->HasEnoughMoney(packet.BidAmount))
{
// client already test it but just in case ...
SendAuctionCommandResult(auction, AUCTION_PLACE_BID, ERR_AUCTION_NOT_ENOUGHT_MONEY);
return;
}
SQLTransaction trans = CharacterDatabase.BeginTransaction();
if (packet.BidAmount < auction->buyout || auction->buyout == 0)
{
if (auction->bidder > 0)
{
if (auction->bidder == player->GetGUIDLow())
player->ModifyMoney(-int64(packet.BidAmount - auction->bid));
else
{
// mail to last bidder and return money
sAuctionMgr->SendAuctionOutbiddedMail(auction, packet.BidAmount, player, trans);
player->ModifyMoney(-int64(packet.BidAmount));
}
}
else
player->ModifyMoney(-int64(packet.BidAmount));
auction->bidder = player->GetGUIDLow();
auction->bid = packet.BidAmount;
player->UpdateAchievementCriteria(CRITERIA_TYPE_HIGHEST_AUCTION_BID, packet.BidAmount);
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_AUCTION_BID);
stmt->setUInt32(0, auction->bidder);
stmt->setUInt32(1, auction->bid);
stmt->setUInt32(2, auction->Id);
trans->Append(stmt);
SendAuctionCommandResult(auction, AUCTION_PLACE_BID, ERR_AUCTION_OK);
}
else
{
//buyout:
if (player->GetGUIDLow() == auction->bidder)
player->ModifyMoney(-int64(auction->buyout - auction->bid));
else
{
player->ModifyMoney(-int64(auction->buyout));
if (auction->bidder) //buyout for bidded auction ..
sAuctionMgr->SendAuctionOutbiddedMail(auction, auction->buyout, player, trans);
}
auction->bidder = player->GetGUIDLow();
auction->bid = auction->buyout;
player->UpdateAchievementCriteria(CRITERIA_TYPE_HIGHEST_AUCTION_BID, auction->buyout);
SendAuctionCommandResult(auction, AUCTION_PLACE_BID, ERR_AUCTION_OK);
//- Mails must be under transaction control too to prevent data loss
sAuctionMgr->SendAuctionSalePendingMail(auction, trans);
sAuctionMgr->SendAuctionSuccessfulMail(auction, trans);
sAuctionMgr->SendAuctionWonMail(auction, trans);
auction->DeleteFromDB(trans);
uint32 itemEntry = auction->itemEntry;
sAuctionMgr->RemoveAItem(auction->itemGUIDLow);
auctionHouse->RemoveAuction(auction, itemEntry);
}
player->SaveInventoryAndGoldToDB(trans);
CharacterDatabase.CommitTransaction(trans);
}
void WorldSession::HandleAuctionRemoveItem(WorldPackets::AuctionHouse::AuctionRemoveItem& packet)
{
Player* player = GetPlayer();
Creature* creature = player->GetNPCIfCanInteractWith(packet.Auctioneer, UNIT_NPC_FLAG_AUCTIONEER);
if (!creature)
{
TC_LOG_DEBUG(LOG_FILTER_NETWORKIO, "WORLD: HandleAuctionRemoveItem - Unit (GUID: %u) not found or you can't interact with him.", uint32(packet.Auctioneer.GetGUIDLow()));
return;
}
if (player->HasUnitState(UNIT_STATE_DIED))
player->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH);
AuctionHouseObject* auctionHouse = sAuctionMgr->GetAuctionsMap(creature->getFaction());
AuctionEntry* auction = auctionHouse->GetAuction(packet.AuctionItemID);
SQLTransaction trans = CharacterDatabase.BeginTransaction();
if (auction && auction->owner == player->GetGUIDLow())
{
Item* pItem = sAuctionMgr->GetAItem(auction->itemGUIDLow);
if (pItem)
{
if (auction->bidder > 0) // If we have a bidder, we have to send him the money he paid
{
uint32 auctionCut = auction->GetAuctionCut();
if (!player->HasEnoughMoney(static_cast<uint64>(auctionCut))) //player doesn't have enough money, maybe message needed
return;
sAuctionMgr->SendAuctionCancelledToBidderMail(auction, trans, pItem);
player->ModifyMoney(-int64(auctionCut));
}
// item will deleted or added to received mail list
MailDraft(auction->BuildAuctionMailSubject(AUCTION_CANCELED), AuctionEntry::BuildAuctionMailBody(0, 0, auction->buyout, auction->deposit, 0))
.AddItem(pItem)
.SendMailTo(trans, player, auction, MAIL_CHECK_MASK_COPIED);
}
else
{
TC_LOG_ERROR(LOG_FILTER_NETWORKIO, "Auction id: %u got non existing item (item guid : %u)!", auction->Id, auction->itemGUIDLow);
SendAuctionCommandResult(nullptr, AUCTION_CANCEL, ERR_AUCTION_DATABASE_ERROR);
return;
}
}
else
{
SendAuctionCommandResult(nullptr, AUCTION_CANCEL, ERR_AUCTION_DATABASE_ERROR);
//this code isn't possible ... maybe there should be assert
TC_LOG_ERROR(LOG_FILTER_NETWORKIO, "CHEATER: %u tried to cancel auction (id: %u) of another player or auction is NULL", player->GetGUIDLow(), packet.AuctionItemID);
return;
}
//inform player, that auction is removed
SendAuctionCommandResult(auction, AUCTION_CANCEL, ERR_AUCTION_OK);
// Now remove the auction
player->SaveInventoryAndGoldToDB(trans);
auction->DeleteFromDB(trans);
CharacterDatabase.CommitTransaction(trans);
uint32 itemEntry = auction->itemEntry;
sAuctionMgr->RemoveAItem(auction->itemGUIDLow);
auctionHouse->RemoveAuction(auction, itemEntry);
}
void WorldSession::HandleAuctionListBidderItems(WorldPackets::AuctionHouse::AuctionListBidderItems& packet)
{
Player* player = GetPlayer();
Creature* creature = player->GetNPCIfCanInteractWith(packet.Auctioneer, UNIT_NPC_FLAG_AUCTIONEER);
if (!creature)
{
TC_LOG_DEBUG(LOG_FILTER_NETWORKIO, "WORLD: HandleAuctionListBidderItems - Unit (GUID: %u) not found or you can't interact with him.", uint32(packet.Auctioneer.GetGUIDLow()));
return;
}
if (player->HasUnitState(UNIT_STATE_DIED))
player->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH);
AuctionHouseObject* auctionHouse = sAuctionMgr->GetAuctionsMap(creature->getFaction());
WorldPackets::AuctionHouse::AuctionListBidderItemsResult result;
auctionHouse->BuildListBidderItems(result, player, result.TotalCount);
result.DesiredDelay = 300;
SendPacket(result.Write());
}
void WorldSession::HandleAuctionListOwnerItems(WorldPackets::AuctionHouse::AuctionListOwnerItems& packet)
{
Player* player = GetPlayer();
Creature* creature = player->GetNPCIfCanInteractWith(packet.Auctioneer, UNIT_NPC_FLAG_AUCTIONEER);
if (!creature)
{
TC_LOG_DEBUG(LOG_FILTER_NETWORKIO, "WORLD: HandleAuctionListOwnerItems - Unit (GUID: %u) not found or you can't interact with him.", uint32(packet.Auctioneer.GetGUIDLow()));
return;
}
if (player->HasUnitState(UNIT_STATE_DIED))
player->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH);
AuctionHouseObject* auctionHouse = sAuctionMgr->GetAuctionsMap(creature->getFaction());
WorldPackets::AuctionHouse::AuctionListOwnerItemsResult result;
auctionHouse->BuildListOwnerItems(result, player, result.TotalCount);
result.DesiredDelay = 300;
SendPacket(result.Write());
}
void WorldSession::HandleAuctionListItems(WorldPackets::AuctionHouse::AuctionListItems& packet)
{
Player* player = GetPlayer();
Creature* creature = player->GetNPCIfCanInteractWith(packet.Auctioneer, UNIT_NPC_FLAG_AUCTIONEER);
if (!creature)
{
TC_LOG_DEBUG(LOG_FILTER_NETWORKIO, "WORLD: HandleAuctionListItems - Unit (GUID: %u) not found or you can't interact with him.", uint32(packet.Auctioneer.GetGUIDLow()));
return;
}
if (player->HasUnitState(UNIT_STATE_DIED))
player->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH);
std::wstring wsearchedname;
if (!Utf8toWStr(packet.Name, wsearchedname))
return;
wstrToLower(wsearchedname);
Optional<AuctionSearchFilters> filters;
WorldPackets::AuctionHouse::AuctionListItemsResult result;
if (!packet.ClassFilters.empty())
{
filters = boost::in_place();
for (auto const& classFilter : packet.ClassFilters)
{
if (!classFilter.SubClassFilters.empty())
{
for (auto const& subClassFilter : classFilter.SubClassFilters)
{
if (classFilter.ItemClass < MAX_ITEM_CLASS)
{
filters->Classes[classFilter.ItemClass].SubclassMask |= 1 << subClassFilter.ItemSubclass;
if (subClassFilter.ItemSubclass < 21)
filters->Classes[classFilter.ItemClass].InvTypes[subClassFilter.ItemSubclass] = subClassFilter.InvTypeMask;
}
}
}
else
filters->Classes[classFilter.ItemClass].SubclassMask = AuctionSearchFilters::FILTER_SKIP_SUBCLASS;
}
}
sAuctionMgr->GetAuctionsMap(creature->getFaction())->BuildListAuctionItems(result, _player, wsearchedname, packet.Offset, packet.MinLevel, packet.MaxLevel, packet.OnlyUsable, filters, packet.Quality);
result.DesiredDelay = 300;
result.OnlyUsable = packet.OnlyUsable;
SendPacket(result.Write());
}
void WorldSession::HandleAuctionListPendingSales(WorldPackets::AuctionHouse::AuctionListPendingSales& /*packet*/)
{
uint32 count = 0;
WorldPackets::AuctionHouse::AuctionListPendingSalesResult result;
for (auto itr = _player->GetMailBegin(); itr != _player->GetMailEnd(); ++itr)
{
if ((*itr)->state == MAIL_STATE_DELETED || (*itr)->messageType == MAIL_AUCTION)
continue;
++count;
if (count < 50)
result.Mails.emplace_back(*itr, _player);
break;
}
result.TotalNumRecords = count;
SendPacket(result.Write());
}
void WorldSession::HandleReplicateItems(WorldPackets::AuctionHouse::AuctionReplicateItems& packet)
{
Creature* creature = GetPlayer()->GetNPCIfCanInteractWith(packet.Auctioneer, UNIT_NPC_FLAG_AUCTIONEER);
if (!creature)
return;
if (GetPlayer()->HasUnitState(UNIT_STATE_DIED))
GetPlayer()->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH);
WorldPackets::AuctionHouse::AuctionReplicateResponse response;
sAuctionMgr->GetAuctionsMap(creature->getFaction())->BuildReplicate(response, GetPlayer(), packet.ChangeNumberGlobal, packet.ChangeNumberCursor, packet.ChangeNumberTombstone, packet.Count);
response.DesiredDelay = 300 * 5;
response.Result = 0;
SendPacket(response.Write());
}
| 0 | 0.941903 | 1 | 0.941903 | game-dev | MEDIA | 0.926179 | game-dev | 0.950298 | 1 | 0.950298 |
Wurst-Imperium/Wurst7 | 2,450 | src/main/java/net/wurstclient/hacks/NameTagsHack.java | /*
* Copyright (c) 2014-2025 Wurst-Imperium and contributors.
*
* This source code is subject to the terms of the GNU General Public
* License, version 3. If a copy of the GPL was not distributed with this
* file, You can obtain one at: https://www.gnu.org/licenses/gpl-3.0.txt
*/
package net.wurstclient.hacks;
import net.wurstclient.Category;
import net.wurstclient.SearchTags;
import net.wurstclient.hack.Hack;
import net.wurstclient.settings.CheckboxSetting;
import net.wurstclient.settings.SliderSetting;
@SearchTags({"name tags"})
public final class NameTagsHack extends Hack
{
private final SliderSetting scale =
new SliderSetting("Scale", "How large the nametags should be.", 1, 0.05,
5, 0.05, SliderSetting.ValueDisplay.PERCENTAGE);
private final CheckboxSetting unlimitedRange =
new CheckboxSetting("Unlimited range",
"Removes the 64 block distance limit for nametags.", true);
private final CheckboxSetting seeThrough = new CheckboxSetting(
"See-through mode",
"Renders nametags on the see-through text layer. This makes them"
+ " easier to read behind walls, but causes some graphical glitches"
+ " with water and other transparent things.",
false);
private final CheckboxSetting forceMobNametags = new CheckboxSetting(
"Always show named mobs", "Displays the nametags of named mobs even"
+ " when you are not looking directly at them.",
true);
private final CheckboxSetting forcePlayerNametags =
new CheckboxSetting("Always show player names",
"Displays your own nametag as well as any player names that would"
+ " normally be disabled by scoreboard team settings.",
false);
public NameTagsHack()
{
super("NameTags");
setCategory(Category.RENDER);
addSetting(scale);
addSetting(unlimitedRange);
addSetting(seeThrough);
addSetting(forceMobNametags);
addSetting(forcePlayerNametags);
}
public float getScale()
{
return scale.getValueF();
}
public boolean isUnlimitedRange()
{
return isEnabled() && unlimitedRange.isChecked();
}
public boolean isSeeThrough()
{
return isEnabled() && seeThrough.isChecked();
}
public boolean shouldForceMobNametags()
{
return isEnabled() && forceMobNametags.isChecked();
}
public boolean shouldForcePlayerNametags()
{
return isEnabled() && forcePlayerNametags.isChecked();
}
// See EntityRenderCommandQueueImpl, EntityRendererMixin,
// LivingEntityRendererMixin, MobEntityRendererMixin
}
| 0 | 0.872195 | 1 | 0.872195 | game-dev | MEDIA | 0.44358 | game-dev | 0.855527 | 1 | 0.855527 |
The-Legion-Preservation-Project/LegionCore-7.3.5 | 13,983 | src/server/scripts/Legion/HallsofValor/instance_halls_of_valor.cpp | /*
Dungeon : Halls of Valor 100-110
*/
#include "Group.h"
#include "halls_of_valor.h"
#include "ScriptPCH.h"
#include "WorldPacket.h"
#include "InstancePackets.h"
DoorData const doorData[] =
{
{GO_HYMDALL_ENTER_DOOR, DATA_HYMDALL, DOOR_TYPE_ROOM, BOUNDARY_NONE},
{GO_HYMDALL_EXIT_DOOR, DATA_HYMDALL, DOOR_TYPE_PASSAGE, BOUNDARY_NONE},
{GO_HYRJA_DOOR, DATA_HYRJA, DOOR_TYPE_ROOM, BOUNDARY_NW},
{GO_GATES_OF_GLORY_DOOR, DATA_HYRJA, DOOR_TYPE_PASSAGE, BOUNDARY_NONE},
{GO_GATES_OF_GLORY_DOOR, DATA_FENRYR, DOOR_TYPE_PASSAGE, BOUNDARY_NONE},
{GO_ODYN_AND_SKOVALD_DOOR, DATA_SKOVALD, DOOR_TYPE_ROOM, BOUNDARY_NONE},
{GO_ODYN_AND_SKOVALD_DOOR, DATA_ODYN, DOOR_TYPE_ROOM, BOUNDARY_NONE},
};
class instance_halls_of_valor : public InstanceMapScript
{
public:
instance_halls_of_valor() : InstanceMapScript("instance_halls_of_valor", 1477) { }
InstanceScript* GetInstanceScript(InstanceMap* map) const override
{
return new instance_halls_of_valor_InstanceMapScript(map);
}
struct instance_halls_of_valor_InstanceMapScript : public InstanceScript
{
instance_halls_of_valor_InstanceMapScript(InstanceMap* map) : InstanceScript(map) {}
WorldLocation loc_res_pla;
ObjectGuid HymdallChestGUID;
ObjectGuid hyrjaGUID;
ObjectGuid feryrGUID;
ObjectGuid skovaldGUID;
ObjectGuid aegisGUID;
ObjectGuid OdynGUID;
ObjectGuid OdynChestGUID;
ObjectGuid HymdallGUID;
std::map<uint32, ObjectGuid> runicBrandGUIDconteiner;
bool StartEvent;
uint32 fenryrEventDone;
uint32 skovaldEventDone;
uint32 PlayerCount;
uint32 GoRunicColour[5];
uint32 checkTimer = 1000;
uint32 checkTimerAura = 1000;
void Initialize() override
{
SetHeaders(DataHeader);
SetBossNumber(MAX_ENCOUNTER);
LoadDoorData(doorData);
StartEvent = false;
PlayerCount = 0;
fenryrEventDone = 0;
skovaldEventDone = 0;
}
void OnCreatureCreate(Creature* creature) override
{
switch (creature->GetEntry())
{
case NPC_HYRJA:
hyrjaGUID = creature->GetGUID();
break;
case NPC_BOSS_FENRYR:
feryrGUID = creature->GetGUID();
break;
case NPC_GOD_KING_SKOVALD:
skovaldGUID = creature->GetGUID();
break;
case NPC_AEGIS_OF_AGGRAMAR:
aegisGUID = creature->GetGUID();
break;
case NPC_ODYN:
OdynGUID = creature->GetGUID();
break;
case NPC_HYMDALL:
HymdallGUID = creature->GetGUID();
break;
}
}
void OnGameObjectCreate(GameObject* go) override
{
switch (go->GetEntry())
{
case GO_HYMDALL_ENTER_DOOR:
case GO_HYMDALL_EXIT_DOOR:
case GO_HYRJA_DOOR:
case GO_GATES_OF_GLORY_DOOR:
case GO_ODYN_AND_SKOVALD_DOOR:
AddDoor(go, true);
break;
case GO_HYMDALL_CHEST:
HymdallChestGUID = go->GetGUID();
break;
case GO_ODYN_CHEST:
OdynChestGUID = go->GetGUID();
break;
case GO_RUNIC_BRAND_PURE:
GoRunicColour[0] = go->GetEntry();
runicBrandGUIDconteiner[go->GetEntry()] = go->GetGUID();
break;
case GO_RUNIC_BRAND_RED:
GoRunicColour[1] = go->GetEntry();
runicBrandGUIDconteiner[go->GetEntry()] = go->GetGUID();
break;
case GO_RUNIC_BRAND_YELLOW:
GoRunicColour[2] = go->GetEntry();
runicBrandGUIDconteiner[go->GetEntry()] = go->GetGUID();
break;
case GO_RUNIC_BRAND_BLUE:
GoRunicColour[3] = go->GetEntry();
runicBrandGUIDconteiner[go->GetEntry()] = go->GetGUID();
break;
case GO_RUNIC_BRAND_GREEN:
GoRunicColour[4] = go->GetEntry();
runicBrandGUIDconteiner[go->GetEntry()] = go->GetGUID();
break;
default:
break;
}
}
bool SetBossState(uint32 type, EncounterState state) override
{
if (!InstanceScript::SetBossState(type, state))
return false;
switch (type)
{
case DATA_HYMDALL:
if (state == DONE)
{
if (instance->GetDifficultyID() != DIFFICULTY_MYTHIC_KEYSTONE)
if (GameObject* chest = instance->GetGameObject(HymdallChestGUID))
chest->SetRespawnTime(86400);
instance->ApplyOnEveryPlayer([&](Player* player)
{
if (auto hymdall = instance->GetCreature(HymdallGUID))
{
uint16 encounterId = sObjectMgr->GetDungeonEncounterByCreature(hymdall->GetEntry());
instance->UpdateEncounterState(ENCOUNTER_CREDIT_KILL_CREATURE, NPC_HYMDALL, hymdall, player);
hymdall->GetMap()->SendToPlayers(WorldPackets::Instance::BossKillCredit(encounterId).Write());
}
instance->ToInstanceMap()->PermBindAllPlayers(player);
player->getHostileRefManager().deleteReferences();
});
}
break;
case DATA_SKOVALD:
{
if (state != IN_PROGRESS)
if (Creature* aegis = instance->GetCreature(aegisGUID))
aegis->DespawnOrUnsummon();
if (state == DONE)
if (Creature* odyn = instance->GetCreature(OdynGUID))
odyn->AI()->DoAction(true);
break;
}
case DATA_ODYN:
{
if (state != IN_PROGRESS)
for (uint8 i = 0; i < 5; i++)
if (GameObject* rune = instance->GetGameObject(runicBrandGUIDconteiner[GoRunicColour[i]]))
rune->SetGoState(GO_STATE_READY);
if (state == DONE)
{
if (instance->GetDifficultyID() != DIFFICULTY_MYTHIC_KEYSTONE)
if (GameObject* chest = instance->GetGameObject(OdynChestGUID))
chest->SetRespawnTime(86400);
instance->SummonCreature(NPC_SPOILS_CHEST_VISUAL, spoilsPos);
instance->ApplyOnEveryPlayer([&](Player* player)
{
if (auto odyn = instance->GetCreature(OdynGUID))
{
uint16 encounterId = sObjectMgr->GetDungeonEncounterByCreature(odyn->GetEntry());
instance->UpdateEncounterState(ENCOUNTER_CREDIT_KILL_CREATURE, NPC_ODYN, odyn, player);
odyn->GetMap()->SendToPlayers(WorldPackets::Instance::BossKillCredit(encounterId).Write());
}
instance->ToInstanceMap()->PermBindAllPlayers(player);
player->getHostileRefManager().deleteReferences();
});
}
break;
}
default:
break;
}
if (type == DATA_HYRJA || type == DATA_FENRYR)
if (GetBossState(DATA_HYRJA) == DONE && GetBossState(DATA_FENRYR) == DONE)
DoCastSpellOnPlayers(202160); //Odyn's Blessing - Speed buff
return true;
}
void SetData(uint32 type, uint32 data) override
{
switch (type)
{
case DATA_FENRYR_EVENT:
{
fenryrEventDone = data;
if (data == DONE)
{
if (Creature* fen = instance->GetCreature(feryrGUID))
{
fen->SetVisible(true);
fen->SetReactState(REACT_AGGRESSIVE);
}
SaveToDB();
}
break;
}
case DATA_SKOVALD_EVENT:
skovaldEventDone = data;
if (data == DONE)
SaveToDB();
break;
case DATA_RUNES_ACTIVATED:
if (GameObject* rune = instance->GetGameObject(runicBrandGUIDconteiner[GoRunicColour[data]]))
rune->SetGoState(GO_STATE_ACTIVE);
break;
case DATA_RUNES_DEACTIVATED:
if (GameObject* rune = instance->GetGameObject(runicBrandGUIDconteiner[GoRunicColour[data]]))
rune->SetGoState(GO_STATE_READY);
if (Creature* odyn = instance->GetCreature(OdynGUID))
odyn->AI()->SetData(1, data);
break;
default:
break;
}
}
ObjectGuid GetGuidData(uint32 type) const override
{
switch (type)
{
case DATA_HYRJA:
return hyrjaGUID;
case DATA_SKOVALD:
return skovaldGUID;
case DATA_ODYN:
return OdynGUID;
}
return ObjectGuid::Empty;
}
uint32 GetData(uint32 type) const override
{
switch (type)
{
case DATA_FENRYR_EVENT:
return fenryrEventDone;
case DATA_SKOVALD_EVENT:
return skovaldEventDone;
}
return 0;
}
void OnPlayerEnter(Player* player) override
{
if (!StartEvent)
{
if (PlayerCount < 5)
{
PlayerCount++;
}
else
{
StartEvent = true;
if (Group *g = player->GetGroup())
if (Player* leader = ObjectAccessor::GetPlayer(*player, g->GetLeaderGUID()))
leader->CastSpell(leader, 202036);
}
}
}
void Update(uint32 diff) override
{
if (checkTimer <= diff)
{
checkTimer = 1000;
instance->ApplyOnEveryPlayer([&](Player* player)
{
if (player->GetCurrentAreaID() == 7672)
{
if (player->GetPositionZ() <= 600.00f)
{
player->Kill(player);
player->RepopAtGraveyard();
}
}
});
}
else
checkTimer -= diff;
if (checkTimerAura <= diff)
{
checkTimerAura = 1000;
instance->ApplyOnEveryPlayer([&](Player* player)
{
if (player->GetCurrentAreaID() == 7672 && player->HasAura(192635))
if (player->GetPositionX() <= 2590.00f || player->GetPositionX() >= 3175.61f)
player->RemoveAura(192635);
});
}
else
checkTimerAura -= diff;
}
void WriteSaveDataMore(std::ostringstream& data) override
{
data << fenryrEventDone << " " << skovaldEventDone;
}
void ReadSaveDataMore(std::istringstream& data) override
{
data >> fenryrEventDone;
data >> skovaldEventDone;
}
WorldLocation* GetClosestGraveYard(float x, float y, float z) override
{
loc_res_pla.WorldRelocate(1477, x, y, z);
uint32 graveyardId = 5098;
if (instance->GetDifficultyID() != DIFFICULTY_MYTHIC_KEYSTONE)
{
if (GetBossState(DATA_HYRJA) == DONE && GetBossState(DATA_FENRYR) == DONE)
graveyardId = 5289;
else if (GetBossState(DATA_FENRYR) != DONE && GetData(DATA_FENRYR_EVENT) == DONE)
graveyardId = 5226;
else if (GetBossState(DATA_HYRJA) == DONE)
graveyardId = 5225;
}
if (graveyardId)
{
if (WorldSafeLocsEntry const* gy = sWorldSafeLocsStore.LookupEntry(graveyardId))
{
loc_res_pla.WorldRelocate(gy->MapID, gy->Loc.X, gy->Loc.Y, gy->Loc.Z);
}
}
return &loc_res_pla;
}
/* void Update(uint32 diff)
{
InstanceScript::Update(diff);
} */
};
};
void AddSC_instance_halls_of_valor()
{
new instance_halls_of_valor();
} | 0 | 0.982933 | 1 | 0.982933 | game-dev | MEDIA | 0.944824 | game-dev | 0.994976 | 1 | 0.994976 |
Demigiant/demilib | 1,501 | _Demigiant.Libraries/DeEditorTools/Hierarchy/DeHierarchyComponentInspector.cs | // Author: Daniele Giardini - http://www.demigiant.com
// Created: 2017/02/04 15:08
// License Copyright (c) Daniele Giardini
using DG.DemiEditor;
using DG.DemiLib;
using DG.DemiLib.External;
using UnityEditor;
using UnityEngine;
namespace DG.DeEditorTools.Hierarchy
{
[CustomEditor(typeof(DeHierarchyComponent))]
public class DeHierarchyComponentInspector : Editor
{
static GUIStyle _infoStyle;
#region Unity and GUI Methods
public override void OnInspectorGUI()
{
SetStyles();
using (new DeGUI.ColorScope(new DeSkinColor(0.1f))) {
GUILayout.Label(
"This is an object created by <b>DeEditorTools' DeHierarchy</b>, in order to evidence Hierarchy elements with colors etc." +
"\n\n<b>It will not be included in your build</b>, and you can delete it at any time to remove all evidences from a given scene." +
"\n\nNote that <b>you can hide it</b>, by using Unity's Preferences > DeEditorTools, if you want.",
_infoStyle
);
}
using (new EditorGUI.DisabledScope(true)) {
DrawDefaultInspector();
}
}
static void SetStyles()
{
if (_infoStyle != null) return;
_infoStyle = DeGUI.styles.box.flat.Clone(new DeSkinColor(0.75f), TextAnchor.MiddleLeft, 11, Format.RichText).Padding(14);
}
#endregion
}
} | 0 | 0.907227 | 1 | 0.907227 | game-dev | MEDIA | 0.472293 | game-dev | 0.90702 | 1 | 0.90702 |
roy-t/MiniRTS | 4,395 | src/MiniEngine.Systems/Components/ComponentContainer.cs | using System;
using System.Collections.Generic;
using MiniEngine.Configuration;
namespace MiniEngine.Systems.Components
{
public interface IComponentContainer
{
public Type ComponentType { get; }
public abstract int Count { get; }
public abstract void Flush();
public AComponent GetComponent(int index);
public AComponent GetComponent(Entity entity);
public abstract bool Contains(Entity entity);
public IComponentContainer<T> Specialize<T>()
where T : AComponent
=> (IComponentContainer<T>)this;
}
public interface IComponentContainer<T> : IComponentContainer
where T : AComponent
{
public IReadOnlyList<T> All { get; }
public IReadOnlyList<T> New { get; }
public IReadOnlyList<T> Changed { get; }
public IReadOnlyList<T> Unchanged { get; }
public IReadOnlyList<T> Removed { get; }
public T Get(int index);
public T Get(Entity entity);
public void Add(T component);
}
[ComponentContainer]
public sealed class ComponentContainer<T> : IComponentContainer<T>
where T : AComponent
{
private readonly List<T> AllComponents;
private readonly List<T> NewComponents;
private readonly List<T> ChangedComponents;
private readonly List<T> UnchangedComponents;
private readonly List<T> RemovedComponents;
private readonly Dictionary<Entity, T> Components;
public ComponentContainer()
{
this.AllComponents = new List<T>();
this.NewComponents = new List<T>();
this.ChangedComponents = new List<T>();
this.UnchangedComponents = new List<T>();
this.RemovedComponents = new List<T>();
this.Components = new Dictionary<Entity, T>();
}
public Type ComponentType => typeof(T);
public IReadOnlyList<T> All => this.AllComponents;
public IReadOnlyList<T> New => this.NewComponents;
public IReadOnlyList<T> Changed => this.ChangedComponents;
public IReadOnlyList<T> Unchanged => this.UnchangedComponents;
public IReadOnlyList<T> Removed => this.RemovedComponents;
public T Get(int index)
=> this.AllComponents[index];
public T Get(Entity entity)
=> this.Components[entity];
public AComponent GetComponent(int index) => this.Get(index);
public AComponent GetComponent(Entity entity) => this.Get(entity);
public int Count => this.AllComponents.Count;
public void Flush()
{
this.NewComponents.Clear();
this.ChangedComponents.Clear();
this.UnchangedComponents.Clear();
for (var i = this.AllComponents.Count - 1; i >= 0; i--)
{
var component = this.AllComponents[i];
if (component.ChangeState.CurrentState == LifetimeState.Removed)
{
this.AllComponents.RemoveAt(i);
this.Components.Remove(component.Entity);
}
else
{
component.ChangeState.Next();
switch (component.ChangeState.CurrentState)
{
case LifetimeState.Created:
throw new InvalidOperationException();
case LifetimeState.New:
this.NewComponents.Add(component);
break;
case LifetimeState.Changed:
this.ChangedComponents.Add(component);
break;
case LifetimeState.Unchanged:
this.UnchangedComponents.Add(component);
break;
case LifetimeState.Removed:
this.RemovedComponents.Add(component);
break;
}
}
}
}
public void Add(T component)
{
this.AllComponents.Add(component);
this.Components.Add(component.Entity, component);
}
public bool Contains(Entity entity)
=> this.Components.ContainsKey(entity);
}
}
| 0 | 0.71131 | 1 | 0.71131 | game-dev | MEDIA | 0.776102 | game-dev | 0.857155 | 1 | 0.857155 |
Solarint/SAIN | 6,776 | Classes/Player/BodyPartsClass.cs | using EFT;
using SAIN.Components.PlayerComponentSpace;
using SAIN.Models.Structs;
using SAIN.SAINComponent;
using System.Collections.Generic;
namespace SAIN.Components
{
public class BodyPartsClass : PlayerComponentBase
{
public PartDictionary Parts { get; } = [];
public SAINBodyPart[] PartsArray { get; private set; }
public BodyPartsClass(PlayerComponent component) : base(component)
{
createParts(component.Player);
PartsArray = [.. Parts.Values];
}
private void createParts(Player player)
{
PlayerBones playerBones = Player.PlayerBones;
foreach (var part in PartToBoneTypes.PartsToCollidersTypes)
{
EBodyPart bodyPartType = part.Key;
SAINBodyPart bodyPart = createPart(bodyPartType, playerBones, part.Value);
Parts.Add(bodyPartType, bodyPart);
}
//StringBuilder stringBuilder = new StringBuilder();
//stringBuilder.AppendLine($"Got Parts:");
//foreach (var part in Parts) {
// stringBuilder.AppendLine($"{part.Key} : {part.Value.Colliders.Count}");
//}
//Logger.LogDebug(stringBuilder.ToString());
}
private BifacialTransform getTransform(EBodyPart bodyPart, PlayerBones bones)
{
switch (bodyPart)
{
case EBodyPart.Head:
return bones.Head;
case EBodyPart.Chest:
return bones.Ribcage;
case EBodyPart.Stomach:
return bones.Pelvis;
case EBodyPart.LeftArm:
return bones.LeftShoulder;
case EBodyPart.RightArm:
return bones.RightShoulder;
case EBodyPart.LeftLeg:
return bones.LeftThigh1;
default:
return bones.RightThigh1;
}
}
private SAINBodyPart createPart(EBodyPart bodyPartType, PlayerBones playerBones, EBodyPartColliderType[] colliderTypes)
{
BifacialTransform transform = getTransform(bodyPartType, playerBones);
#if DEBUG
if (transform == null)
{
Logger.LogDebug($"{bodyPartType} has null bifacial transform");
}
#endif
List<BodyPartCollider> colliders = getColliders(playerBones, colliderTypes);
if (colliders?.Count == 0)
{
#if DEBUG
#endif
#if DEBUG
Logger.LogWarning($"No Colliders for {bodyPartType}!");
#endif
}
return new SAINBodyPart(bodyPartType, transform, colliders);
}
private List<BodyPartCollider> getColliders(PlayerBones playerBones, EBodyPartColliderType[] colliderTypes)
{
var colliderList = new List<BodyPartCollider>();
if (playerBones == null)
{
#if DEBUG
Logger.LogError("Player bones null");
#endif
return colliderList;
}
if (colliderTypes == null)
{
#if DEBUG
Logger.LogError("colliderTypes null");
#endif
return colliderList;
}
var bodyParts = playerBones.BodyPartCollidersDictionary;
foreach (var type in colliderTypes)
{
if (!bodyParts.TryGetValue(type, out BodyPartCollider collider))
{
#if DEBUG
Logger.LogDebug($"{type} not in collider dictionary");
#endif
}
else if (collider == null || collider.Collider == null)
{
#if DEBUG
Logger.LogDebug($"{type} has null collider");
#endif
}
else if (collider.transform == null)
{
#if DEBUG
Logger.LogDebug($"{type} has null transform");
#endif
}
else
{
#if DEBUG
if (collider.Collider.transform == null)
{
Logger.LogDebug($"{type} collider.Collider has null transform");
}
#endif
colliderList.Add(collider);
}
}
return colliderList;
}
private static class PartToBoneTypes
{
private static readonly EBodyPartColliderType[] _headParts = [
//EBodyPartColliderType.ParietalHead,
EBodyPartColliderType.BackHead,
EBodyPartColliderType.Jaw,
EBodyPartColliderType.HeadCommon,
EBodyPartColliderType.NeckFront,
EBodyPartColliderType.NeckBack,
];
private static readonly EBodyPartColliderType[] _upperBodyParts = [
EBodyPartColliderType.SpineTop,
EBodyPartColliderType.RibcageUp,
EBodyPartColliderType.RightSideChestUp,
EBodyPartColliderType.LeftSideChestUp,
];
private static readonly EBodyPartColliderType[] _lowerBodyParts = [
EBodyPartColliderType.SpineDown,
EBodyPartColliderType.RibcageLow,
EBodyPartColliderType.RightSideChestDown,
EBodyPartColliderType.LeftSideChestDown,
EBodyPartColliderType.Pelvis,
];
private static readonly EBodyPartColliderType[] _leftArmParts = [
EBodyPartColliderType.LeftUpperArm,
EBodyPartColliderType.LeftForearm,
];
private static readonly EBodyPartColliderType[] _rightArmParts = [
EBodyPartColliderType.RightUpperArm,
EBodyPartColliderType.RightForearm,
];
private static readonly EBodyPartColliderType[] _leftLegParts = [
EBodyPartColliderType.LeftCalf,
EBodyPartColliderType.LeftThigh,
];
private static readonly EBodyPartColliderType[] _rightLegParts = [
EBodyPartColliderType.RightCalf,
EBodyPartColliderType.RightThigh,
];
public static readonly Dictionary<EBodyPart, EBodyPartColliderType[]> PartsToCollidersTypes = new()
{
{EBodyPart.Head, _headParts },
{EBodyPart.Chest, _upperBodyParts },
{EBodyPart.Stomach, _lowerBodyParts },
{EBodyPart.LeftArm, _leftArmParts },
{EBodyPart.LeftLeg, _leftLegParts },
{EBodyPart.RightArm, _rightArmParts },
{EBodyPart.RightLeg, _rightLegParts },
};
}
}
} | 0 | 0.858588 | 1 | 0.858588 | game-dev | MEDIA | 0.95281 | game-dev | 0.926347 | 1 | 0.926347 |
AppliedEnergistics/Applied-Energistics-2 | 11,478 | src/main/java/appeng/block/AEBaseEntityBlock.java | /*
* This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved.
*
* Applied Energistics 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Applied Energistics 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.block;
import java.util.ArrayList;
import java.util.List;
import org.jetbrains.annotations.Nullable;
import net.minecraft.core.BlockPos;
import net.minecraft.core.component.DataComponentMap;
import net.minecraft.network.chat.contents.PlainTextContents;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.ItemInteractionResult;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.EntityBlock;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityTicker;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.storage.loot.LootParams;
import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets;
import net.minecraft.world.level.storage.loot.parameters.LootContextParams;
import net.minecraft.world.phys.BlockHitResult;
import appeng.api.ids.AEComponents;
import appeng.api.implementations.items.IMemoryCard;
import appeng.api.implementations.items.MemoryCardMessages;
import appeng.block.networking.CableBusBlock;
import appeng.blockentity.AEBaseBlockEntity;
import appeng.blockentity.AEBaseInvBlockEntity;
import appeng.items.tools.MemoryCardItem;
import appeng.util.InteractionUtil;
import appeng.util.Platform;
import appeng.util.SettingsFrom;
/**
* Base class for blocks that have a {@link BlockEntity}.
*
* @param <T> The type of {@link BlockEntity} or this block.
*/
public abstract class AEBaseEntityBlock<T extends AEBaseBlockEntity> extends AEBaseBlock implements EntityBlock {
private Class<T> blockEntityClass;
private BlockEntityType<T> blockEntityType;
@Nullable
private BlockEntityTicker<T> serverTicker;
@Nullable
private BlockEntityTicker<T> clientTicker;
public AEBaseEntityBlock(Properties props) {
super(props);
}
// TODO : Was this change needed?
public void setBlockEntity(Class<T> blockEntityClass,
BlockEntityType<T> blockEntityType,
BlockEntityTicker<T> clientTicker,
BlockEntityTicker<T> serverTicker) {
this.blockEntityClass = blockEntityClass;
this.blockEntityType = blockEntityType;
this.serverTicker = serverTicker;
this.clientTicker = clientTicker;
}
@Nullable
public T getBlockEntity(BlockGetter level, int x, int y, int z) {
return this.getBlockEntity(level, new BlockPos(x, y, z));
}
@Nullable
public T getBlockEntity(BlockGetter level, BlockPos pos) {
final BlockEntity te = level.getBlockEntity(pos);
// FIXME: This gets called as part of building the block state cache
if (this.blockEntityClass != null && this.blockEntityClass.isInstance(te)) {
return this.blockEntityClass.cast(te);
}
return null;
}
public BlockEntityType<T> getBlockEntityType() {
return blockEntityType;
}
@Nullable
@Override
public BlockEntity newBlockEntity(BlockPos pos, BlockState state) {
return blockEntityType.create(pos, state);
}
@SuppressWarnings("unchecked")
@Nullable
@Override
public <T extends BlockEntity> BlockEntityTicker<T> getTicker(Level level, BlockState blockState,
BlockEntityType<T> type) {
return (BlockEntityTicker<T>) (level.isClientSide() ? clientTicker : serverTicker);
}
@Override
public void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
// Drop internal BE content
if (!level.isClientSide() && !newState.is(state.getBlock())) {
var be = this.getBlockEntity(level, pos);
if (be != null) {
var drops = new ArrayList<ItemStack>();
be.addAdditionalDrops(level, pos, drops);
Platform.spawnDrops(level, pos, drops);
}
}
// super will remove the TE, as it is not an instance of BlockContainer
super.onRemove(state, level, pos, newState, isMoving);
}
@Override
public boolean hasAnalogOutputSignal(BlockState state) {
return AEBaseInvBlockEntity.class.isAssignableFrom(blockEntityClass);
}
@Override
public int getAnalogOutputSignal(BlockState state, Level level, BlockPos pos) {
var te = this.getBlockEntity(level, pos);
if (te instanceof AEBaseInvBlockEntity invBlockEntity) {
if (!invBlockEntity.getInternalInventory().isEmpty()) {
return invBlockEntity.getInternalInventory().getRedstoneSignal();
}
}
return 0;
}
@Override
public boolean triggerEvent(BlockState state, Level level, BlockPos pos, int eventID,
int eventParam) {
super.triggerEvent(state, level, pos, eventID, eventParam);
final BlockEntity blockEntity = level.getBlockEntity(pos);
return blockEntity != null ? blockEntity.triggerEvent(eventID, eventParam) : false;
}
@Override
public void setPlacedBy(Level level, BlockPos pos, BlockState state, @Nullable LivingEntity placer,
ItemStack is) {
// Inherit the item stack's display name, but only if it's a user defined string rather than a translation
// component, since our custom naming cannot handle untranslated I18N strings and we would translate it using
// the server's locale :-(
var blockEntity = this.getBlockEntity(level, pos);
if (blockEntity == null) {
return;
}
if (blockEntity instanceof IOwnerAwareBlockEntity ownerAware && placer instanceof Player player) {
ownerAware.setOwner(player);
}
var hoverName = is.getHoverName();
if (hoverName.getContents() instanceof PlainTextContents text) {
blockEntity.setName(text.text());
}
Player player = null;
if (placer instanceof Player) {
player = (Player) placer;
}
blockEntity.importSettings(SettingsFrom.DISMANTLE_ITEM, is.getComponents(), player);
}
@Override
protected ItemInteractionResult useItemOn(ItemStack heldItem, BlockState state, Level level, BlockPos pos,
Player player,
InteractionHand hand, BlockHitResult hit) {
if (heldItem.getItem() instanceof IMemoryCard memoryCard && !(this instanceof CableBusBlock)) {
final AEBaseBlockEntity blockEntity = this.getBlockEntity(level, pos);
if (blockEntity == null) {
return ItemInteractionResult.FAIL;
}
if (InteractionUtil.isInAlternateUseMode(player)) {
var builder = DataComponentMap.builder();
blockEntity.exportSettings(SettingsFrom.MEMORY_CARD, builder, player);
var settings = builder.build();
if (!settings.isEmpty()) {
MemoryCardItem.clearCard(heldItem);
heldItem.applyComponents(settings);
memoryCard.notifyUser(player, MemoryCardMessages.SETTINGS_SAVED);
}
} else {
var savedName = heldItem.get(AEComponents.EXPORTED_SETTINGS_SOURCE);
if (this.getName().equals(savedName)) {
blockEntity.importSettings(SettingsFrom.MEMORY_CARD, heldItem.getComponents(), player);
memoryCard.notifyUser(player, MemoryCardMessages.SETTINGS_LOADED);
} else {
MemoryCardItem.importGenericSettingsAndNotify(blockEntity, heldItem.getComponents(), player);
}
}
return ItemInteractionResult.sidedSuccess(level.isClientSide());
}
return super.useItemOn(heldItem, state, level, pos, player, hand, hit);
}
@Override
protected InteractionResult useWithoutItem(BlockState state, Level level, BlockPos pos, Player player,
BlockHitResult hitResult) {
return super.useWithoutItem(state, level, pos, player, hitResult);
}
/**
* Returns the BlockState based on the given BlockState while considering the state of the given block entity.
* <p>
* If the given block entity is not of the right type for this block, the state is returned unchanged, this is also
* the case if the given block state does not belong to this block.
*/
public final BlockState getBlockEntityBlockState(BlockState current, BlockEntity te) {
if (current.getBlock() != this || !blockEntityClass.isInstance(te)) {
return current;
}
return updateBlockStateFromBlockEntity(current, blockEntityClass.cast(te));
}
/**
* Reimplement this in subclasses to allow block entities to update the state of their block when their own state
* changes.
* <p>
* It is guaranteed that be is not-null and the block of the given block state is this exact block instance.
*/
protected BlockState updateBlockStateFromBlockEntity(BlockState currentState, T be) {
return currentState;
}
/**
* Exports settings of the block entity when it is broken.
*/
@Override
public List<ItemStack> getDrops(BlockState state, LootParams.Builder builder) {
var drops = super.getDrops(state, builder);
for (var drop : drops) {
if (drop.getItem() instanceof BlockItem blockItem && blockItem.getBlock() == this) {
var lootContext = builder.withParameter(LootContextParams.BLOCK_STATE, state)
.create(LootContextParamSets.BLOCK);
var be = lootContext.getParamOrNull(LootContextParams.BLOCK_ENTITY);
if (be instanceof AEBaseBlockEntity aeBaseBlockEntity) {
var looter = lootContext.getParamOrNull(LootContextParams.THIS_ENTITY);
Player player = null;
if (looter instanceof Player) {
player = (Player) looter;
}
var settings = aeBaseBlockEntity.exportSettings(SettingsFrom.DISMANTLE_ITEM, player);
drop.applyComponents(settings);
}
// Export settings at most for one item
break;
}
}
return drops;
}
}
| 0 | 0.946021 | 1 | 0.946021 | game-dev | MEDIA | 0.996387 | game-dev | 0.955459 | 1 | 0.955459 |
Critters/TWANG | 22,682 | TWANG.ino | // Required libs
#include "FastLED.h"
#include "I2Cdev.h"
#include "MPU6050.h"
#include "Wire.h"
#include "toneAC.h"
#include "iSin.h"
#include "RunningMedian.h"
// Included libs
#include "Enemy.h"
#include "Particle.h"
#include "Spawner.h"
#include "Lava.h"
#include "Boss.h"
#include "Conveyor.h"
// MPU
MPU6050 accelgyro;
int16_t ax, ay, az;
int16_t gx, gy, gz;
// LED setup
#define NUM_LEDS 475
#define DATA_PIN 3
#define CLOCK_PIN 4
#define LED_COLOR_ORDER BGR //if colours aren't working, try GRB or GBR
#define BRIGHTNESS 150 //Use a lower value for lower current power supplies(<2 amps)
#define DIRECTION 1 // 0 = right to left, 1 = left to right
#define MIN_REDRAW_INTERVAL 16 // Min redraw interval (ms) 33 = 30fps / 16 = 63fps
#define USE_GRAVITY 1 // 0/1 use gravity (LED strip going up wall)
#define BEND_POINT 550 // 0/1000 point at which the LED strip goes up the wall
#define LED_TYPE APA102//type of LED strip to use(APA102 - DotStar, WS2811 - NeoPixel) For Neopixels, uncomment line #108 and comment out line #106
// GAME
long previousMillis = 0; // Time of the last redraw
int levelNumber = 0;
long lastInputTime = 0;
#define TIMEOUT 30000
#define LEVEL_COUNT 9
#define MAX_VOLUME 10
iSin isin = iSin();
// JOYSTICK
#define JOYSTICK_ORIENTATION 1 // 0, 1 or 2 to set the angle of the joystick
#define JOYSTICK_DIRECTION 1 // 0/1 to flip joystick direction
#define ATTACK_THRESHOLD 30000 // The threshold that triggers an attack
#define JOYSTICK_DEADZONE 5 // Angle to ignore
int joystickTilt = 0; // Stores the angle of the joystick
int joystickWobble = 0; // Stores the max amount of acceleration (wobble)
// WOBBLE ATTACK
#define ATTACK_WIDTH 70 // Width of the wobble attack, world is 1000 wide
#define ATTACK_DURATION 500 // Duration of a wobble attack (ms)
long attackMillis = 0; // Time the attack started
bool attacking = 0; // Is the attack in progress?
#define BOSS_WIDTH 40
// PLAYER
#define MAX_PLAYER_SPEED 10 // Max move speed of the player
char* stage; // what stage the game is at (PLAY/DEAD/WIN/GAMEOVER)
long stageStartTime; // Stores the time the stage changed for stages that are time based
int playerPosition; // Stores the player position
int playerPositionModifier; // +/- adjustment to player position
bool playerAlive;
long killTime;
int lives = 3;
// POOLS
int lifeLEDs[3] = {52, 50, 40};
Enemy enemyPool[10] = {
Enemy(), Enemy(), Enemy(), Enemy(), Enemy(), Enemy(), Enemy(), Enemy(), Enemy(), Enemy()
};
int const enemyCount = 10;
Particle particlePool[40] = {
Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle(), Particle()
};
int const particleCount = 40;
Spawner spawnPool[2] = {
Spawner(), Spawner()
};
int const spawnCount = 2;
Lava lavaPool[4] = {
Lava(), Lava(), Lava(), Lava()
};
int const lavaCount = 4;
Conveyor conveyorPool[2] = {
Conveyor(), Conveyor()
};
int const conveyorCount = 2;
Boss boss = Boss();
CRGB leds[NUM_LEDS];
RunningMedian MPUAngleSamples = RunningMedian(5);
RunningMedian MPUWobbleSamples = RunningMedian(5);
void setup() {
Serial.begin(9600);
while (!Serial);
// MPU
Wire.begin();
accelgyro.initialize();
// Fast LED
FastLED.addLeds<LED_TYPE, DATA_PIN, CLOCK_PIN, LED_COLOR_ORDER>(leds, NUM_LEDS);
//If using Neopixels, use
//FastLED.addLeds<LED_TYPE, DATA_PIN, LED_COLOR_ORDER>(leds, NUM_LEDS);
FastLED.setBrightness(BRIGHTNESS);
FastLED.setDither(1);
// Life LEDs
for(int i = 0; i<3; i++){
pinMode(lifeLEDs[i], OUTPUT);
digitalWrite(lifeLEDs[i], HIGH);
}
loadLevel();
}
void loop() {
long mm = millis();
int brightness = 0;
if(stage == "PLAY"){
if(attacking){
SFXattacking();
}else{
SFXtilt(joystickTilt);
}
}else if(stage == "DEAD"){
SFXdead();
}
if (mm - previousMillis >= MIN_REDRAW_INTERVAL) {
getInput();
long frameTimer = mm;
previousMillis = mm;
if(abs(joystickTilt) > JOYSTICK_DEADZONE){
lastInputTime = mm;
if(stage == "SCREENSAVER"){
levelNumber = -1;
stageStartTime = mm;
stage = "WIN";
}
}else{
if(lastInputTime+TIMEOUT < mm){
stage = "SCREENSAVER";
}
}
if(stage == "SCREENSAVER"){
screenSaverTick();
}else if(stage == "PLAY"){
// PLAYING
if(attacking && attackMillis+ATTACK_DURATION < mm) attacking = 0;
// If not attacking, check if they should be
if(!attacking && joystickWobble > ATTACK_THRESHOLD){
attackMillis = mm;
attacking = 1;
}
// If still not attacking, move!
playerPosition += playerPositionModifier;
if(!attacking){
int moveAmount = (joystickTilt/6.0);
if(DIRECTION) moveAmount = -moveAmount;
moveAmount = constrain(moveAmount, -MAX_PLAYER_SPEED, MAX_PLAYER_SPEED);
playerPosition -= moveAmount;
if(playerPosition < 0) playerPosition = 0;
if(playerPosition >= 1000 && !boss.Alive()) {
// Reached exit!
levelComplete();
return;
}
}
if(inLava(playerPosition)){
die();
}
// Ticks and draw calls
FastLED.clear();
tickConveyors();
tickSpawners();
tickBoss();
tickLava();
tickEnemies();
drawPlayer();
drawAttack();
drawExit();
}else if(stage == "DEAD"){
// DEAD
FastLED.clear();
if(!tickParticles()){
loadLevel();
}
}else if(stage == "WIN"){
// LEVEL COMPLETE
FastLED.clear();
if(stageStartTime+500 > mm){
int n = max(map(((mm-stageStartTime)), 0, 500, NUM_LEDS, 0), 0);
for(int i = NUM_LEDS; i>= n; i--){
brightness = 255;
leds[i] = CRGB(0, brightness, 0);
}
SFXwin();
}else if(stageStartTime+1000 > mm){
int n = max(map(((mm-stageStartTime)), 500, 1000, NUM_LEDS, 0), 0);
for(int i = 0; i< n; i++){
brightness = 255;
leds[i] = CRGB(0, brightness, 0);
}
SFXwin();
}else if(stageStartTime+1200 > mm){
leds[0] = CRGB(0, 255, 0);
}else{
nextLevel();
}
}else if(stage == "COMPLETE"){
FastLED.clear();
SFXcomplete();
if(stageStartTime+500 > mm){
int n = max(map(((mm-stageStartTime)), 0, 500, NUM_LEDS, 0), 0);
for(int i = NUM_LEDS; i>= n; i--){
brightness = (sin(((i*10)+mm)/500.0)+1)*255;
leds[i].setHSV(brightness, 255, 50);
}
}else if(stageStartTime+5000 > mm){
for(int i = NUM_LEDS; i>= 0; i--){
brightness = (sin(((i*10)+mm)/500.0)+1)*255;
leds[i].setHSV(brightness, 255, 50);
}
}else if(stageStartTime+5500 > mm){
int n = max(map(((mm-stageStartTime)), 5000, 5500, NUM_LEDS, 0), 0);
for(int i = 0; i< n; i++){
brightness = (sin(((i*10)+mm)/500.0)+1)*255;
leds[i].setHSV(brightness, 255, 50);
}
}else{
nextLevel();
}
}else if(stage == "GAMEOVER"){
// GAME OVER!
FastLED.clear();
stageStartTime = 0;
}
Serial.print(millis()-mm);
Serial.print(" - ");
FastLED.show();
Serial.println(millis()-mm);
}
}
// ---------------------------------
// ------------ LEVELS -------------
// ---------------------------------
void loadLevel(){
updateLives();
cleanupLevel();
playerPosition = 0;
playerAlive = 1;
switch(levelNumber){
case 0:
// Left or right?
playerPosition = 200;
spawnEnemy(1, 0, 0, 0);
break;
case 1:
// Slow moving enemy
spawnEnemy(900, 0, 1, 0);
break;
case 2:
// Spawning enemies at exit every 2 seconds
spawnPool[0].Spawn(1000, 3000, 2, 0, 0);
break;
case 3:
// Lava intro
spawnLava(400, 490, 2000, 2000, 0, "OFF");
spawnPool[0].Spawn(1000, 5500, 3, 0, 0);
break;
case 4:
// Sin enemy
spawnEnemy(700, 1, 7, 275);
spawnEnemy(500, 1, 5, 250);
break;
case 5:
// Conveyor
spawnConveyor(100, 600, -1);
spawnEnemy(800, 0, 0, 0);
break;
case 6:
// Conveyor of enemies
spawnConveyor(50, 1000, 1);
spawnEnemy(300, 0, 0, 0);
spawnEnemy(400, 0, 0, 0);
spawnEnemy(500, 0, 0, 0);
spawnEnemy(600, 0, 0, 0);
spawnEnemy(700, 0, 0, 0);
spawnEnemy(800, 0, 0, 0);
spawnEnemy(900, 0, 0, 0);
break;
case 7:
// Lava run
spawnLava(195, 300, 2000, 2000, 0, "OFF");
spawnLava(350, 455, 2000, 2000, 0, "OFF");
spawnLava(510, 610, 2000, 2000, 0, "OFF");
spawnLava(660, 760, 2000, 2000, 0, "OFF");
spawnPool[0].Spawn(1000, 3800, 4, 0, 0);
break;
case 8:
// Sin enemy #2
spawnEnemy(700, 1, 7, 275);
spawnEnemy(500, 1, 5, 250);
spawnPool[0].Spawn(1000, 5500, 4, 0, 3000);
spawnPool[1].Spawn(0, 5500, 5, 1, 10000);
spawnConveyor(100, 900, -1);
break;
case 9:
// Boss
spawnBoss();
break;
}
stageStartTime = millis();
stage = "PLAY";
}
void spawnBoss(){
boss.Spawn();
moveBoss();
}
void moveBoss(){
int spawnSpeed = 2500;
if(boss._lives == 2) spawnSpeed = 2000;
if(boss._lives == 1) spawnSpeed = 1500;
spawnPool[0].Spawn(boss._pos, spawnSpeed, 3, 0, 0);
spawnPool[1].Spawn(boss._pos, spawnSpeed, 3, 1, 0);
}
void spawnEnemy(int pos, int dir, int sp, int wobble){
for(int e = 0; e<enemyCount; e++){
if(!enemyPool[e].Alive()){
enemyPool[e].Spawn(pos, dir, sp, wobble);
enemyPool[e].playerSide = pos > playerPosition?1:-1;
return;
}
}
}
void spawnLava(int left, int right, int ontime, int offtime, int offset, char* state){
for(int i = 0; i<lavaCount; i++){
if(!lavaPool[i].Alive()){
lavaPool[i].Spawn(left, right, ontime, offtime, offset, state);
return;
}
}
}
void spawnConveyor(int startPoint, int endPoint, int dir){
for(int i = 0; i<conveyorCount; i++){
if(!conveyorPool[i]._alive){
conveyorPool[i].Spawn(startPoint, endPoint, dir);
return;
}
}
}
void cleanupLevel(){
for(int i = 0; i<enemyCount; i++){
enemyPool[i].Kill();
}
for(int i = 0; i<particleCount; i++){
particlePool[i].Kill();
}
for(int i = 0; i<spawnCount; i++){
spawnPool[i].Kill();
}
for(int i = 0; i<lavaCount; i++){
lavaPool[i].Kill();
}
for(int i = 0; i<conveyorCount; i++){
conveyorPool[i].Kill();
}
boss.Kill();
}
void levelComplete(){
stageStartTime = millis();
stage = "WIN";
if(levelNumber == LEVEL_COUNT) stage = "COMPLETE";
lives = 3;
updateLives();
}
void nextLevel(){
levelNumber ++;
if(levelNumber > LEVEL_COUNT) levelNumber = 0;
loadLevel();
}
void gameOver(){
levelNumber = 0;
loadLevel();
}
void die(){
playerAlive = 0;
if(levelNumber > 0) lives --;
updateLives();
if(lives == 0){
levelNumber = 0;
lives = 3;
}
for(int p = 0; p < particleCount; p++){
particlePool[p].Spawn(playerPosition);
}
stageStartTime = millis();
stage = "DEAD";
killTime = millis();
}
// ----------------------------------
// -------- TICKS & RENDERS ---------
// ----------------------------------
void tickEnemies(){
for(int i = 0; i<enemyCount; i++){
if(enemyPool[i].Alive()){
enemyPool[i].Tick();
// Hit attack?
if(attacking){
if(enemyPool[i]._pos > playerPosition-(ATTACK_WIDTH/2) && enemyPool[i]._pos < playerPosition+(ATTACK_WIDTH/2)){
enemyPool[i].Kill();
SFXkill();
}
}
if(inLava(enemyPool[i]._pos)){
enemyPool[i].Kill();
SFXkill();
}
// Draw (if still alive)
if(enemyPool[i].Alive()) {
leds[getLED(enemyPool[i]._pos)] = CRGB(255, 0, 0);
}
// Hit player?
if(
(enemyPool[i].playerSide == 1 && enemyPool[i]._pos <= playerPosition) ||
(enemyPool[i].playerSide == -1 && enemyPool[i]._pos >= playerPosition)
){
die();
return;
}
}
}
}
void tickBoss(){
// DRAW
if(boss.Alive()){
boss._ticks ++;
for(int i = getLED(boss._pos-BOSS_WIDTH/2); i<=getLED(boss._pos+BOSS_WIDTH/2); i++){
leds[i] = CRGB::DarkRed;
leds[i] %= 100;
}
// CHECK COLLISION
if(getLED(playerPosition) > getLED(boss._pos - BOSS_WIDTH/2) && getLED(playerPosition) < getLED(boss._pos + BOSS_WIDTH)){
die();
return;
}
// CHECK FOR ATTACK
if(attacking){
if(
(getLED(playerPosition+(ATTACK_WIDTH/2)) >= getLED(boss._pos - BOSS_WIDTH/2) && getLED(playerPosition+(ATTACK_WIDTH/2)) <= getLED(boss._pos + BOSS_WIDTH/2)) ||
(getLED(playerPosition-(ATTACK_WIDTH/2)) <= getLED(boss._pos + BOSS_WIDTH/2) && getLED(playerPosition-(ATTACK_WIDTH/2)) >= getLED(boss._pos - BOSS_WIDTH/2))
){
boss.Hit();
if(boss.Alive()){
moveBoss();
}else{
spawnPool[0].Kill();
spawnPool[1].Kill();
}
}
}
}
}
void drawPlayer(){
leds[getLED(playerPosition)] = CRGB(0, 255, 0);
}
void drawExit(){
if(!boss.Alive()){
leds[NUM_LEDS-1] = CRGB(0, 0, 255);
}
}
void tickSpawners(){
long mm = millis();
for(int s = 0; s<spawnCount; s++){
if(spawnPool[s].Alive() && spawnPool[s]._activate < mm){
if(spawnPool[s]._lastSpawned + spawnPool[s]._rate < mm || spawnPool[s]._lastSpawned == 0){
spawnEnemy(spawnPool[s]._pos, spawnPool[s]._dir, spawnPool[s]._sp, 0);
spawnPool[s]._lastSpawned = mm;
}
}
}
}
void tickLava(){
int A, B, p, i, brightness, flicker;
long mm = millis();
Lava LP;
for(i = 0; i<lavaCount; i++){
flicker = random8(5);
LP = lavaPool[i];
if(LP.Alive()){
A = getLED(LP._left);
B = getLED(LP._right);
if(LP._state == "OFF"){
if(LP._lastOn + LP._offtime < mm){
LP._state = "ON";
LP._lastOn = mm;
}
for(p = A; p<= B; p++){
leds[p] = CRGB(3+flicker, (3+flicker)/1.5, 0);
}
}else if(LP._state == "ON"){
if(LP._lastOn + LP._ontime < mm){
LP._state = "OFF";
LP._lastOn = mm;
}
for(p = A; p<= B; p++){
leds[p] = CRGB(150+flicker, 100+flicker, 0);
}
}
}
lavaPool[i] = LP;
}
}
bool tickParticles(){
bool stillActive = false;
for(int p = 0; p < particleCount; p++){
if(particlePool[p].Alive()){
particlePool[p].Tick(USE_GRAVITY);
leds[getLED(particlePool[p]._pos)] += CRGB(particlePool[p]._power, 0, 0);
stillActive = true;
}
}
return stillActive;
}
void tickConveyors(){
int b, dir, n, i, ss, ee, led;
long m = 10000+millis();
playerPositionModifier = 0;
for(i = 0; i<conveyorCount; i++){
if(conveyorPool[i]._alive){
dir = conveyorPool[i]._dir;
ss = getLED(conveyorPool[i]._startPoint);
ee = getLED(conveyorPool[i]._endPoint);
for(led = ss; led<ee; led++){
b = 5;
n = (-led + (m/100)) % 5;
if(dir == -1) n = (led + (m/100)) % 5;
b = (5-n)/2.0;
if(b > 0) leds[led] = CRGB(0, 0, b);
}
if(playerPosition > conveyorPool[i]._startPoint && playerPosition < conveyorPool[i]._endPoint){
if(dir == -1){
playerPositionModifier = -(MAX_PLAYER_SPEED-4);
}else{
playerPositionModifier = (MAX_PLAYER_SPEED-4);
}
}
}
}
}
void drawAttack(){
if(!attacking) return;
int n = map(millis() - attackMillis, 0, ATTACK_DURATION, 100, 5);
for(int i = getLED(playerPosition-(ATTACK_WIDTH/2))+1; i<=getLED(playerPosition+(ATTACK_WIDTH/2))-1; i++){
leds[i] = CRGB(0, 0, n);
}
if(n > 90) {
n = 255;
leds[getLED(playerPosition)] = CRGB(255, 255, 255);
}else{
n = 0;
leds[getLED(playerPosition)] = CRGB(0, 255, 0);
}
leds[getLED(playerPosition-(ATTACK_WIDTH/2))] = CRGB(n, n, 255);
leds[getLED(playerPosition+(ATTACK_WIDTH/2))] = CRGB(n, n, 255);
}
int getLED(int pos){
// The world is 1000 pixels wide, this converts world units into an LED number
return constrain((int)map(pos, 0, 1000, 0, NUM_LEDS-1), 0, NUM_LEDS-1);
}
bool inLava(int pos){
// Returns if the player is in active lava
int i;
Lava LP;
for(i = 0; i<lavaCount; i++){
LP = lavaPool[i];
if(LP.Alive() && LP._state == "ON"){
if(LP._left < pos && LP._right > pos) return true;
}
}
return false;
}
void updateLives(){
// Updates the life LEDs to show how many lives the player has left
for(int i = 0; i<3; i++){
digitalWrite(lifeLEDs[i], lives>i?HIGH:LOW);
}
}
// ---------------------------------
// --------- SCREENSAVER -----------
// ---------------------------------
void screenSaverTick(){
int n, b, c, i;
long mm = millis();
int mode = (mm/20000)%2;
for(i = 0; i<NUM_LEDS; i++){
leds[i].nscale8(250);
}
if(mode == 0){
// Marching green <> orange
n = (mm/250)%10;
b = 10+((sin(mm/500.00)+1)*20.00);
c = 20+((sin(mm/5000.00)+1)*33);
for(i = 0; i<NUM_LEDS; i++){
if(i%10 == n){
leds[i] = CHSV( c, 255, 150);
}
}
}else if(mode == 1){
// Random flashes
randomSeed(mm);
for(i = 0; i<NUM_LEDS; i++){
if(random8(200) == 0){
leds[i] = CHSV( 25, 255, 100);
}
}
}
}
// ---------------------------------
// ----------- JOYSTICK ------------
// ---------------------------------
void getInput(){
// This is responsible for the player movement speed and attacking.
// You can replace it with anything you want that passes a -90>+90 value to joystickTilt
// and any value to joystickWobble that is greater than ATTACK_THRESHOLD (defined at start)
// For example you could use 3 momentery buttons:
// if(digitalRead(leftButtonPinNumber) == HIGH) joystickTilt = -90;
// if(digitalRead(rightButtonPinNumber) == HIGH) joystickTilt = 90;
// if(digitalRead(attackButtonPinNumber) == HIGH) joystickWobble = ATTACK_THRESHOLD;
accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
int a = (JOYSTICK_ORIENTATION == 0?ax:(JOYSTICK_ORIENTATION == 1?ay:az))/166;
int g = (JOYSTICK_ORIENTATION == 0?gx:(JOYSTICK_ORIENTATION == 1?gy:gz));
if(abs(a) < JOYSTICK_DEADZONE) a = 0;
if(a > 0) a -= JOYSTICK_DEADZONE;
if(a < 0) a += JOYSTICK_DEADZONE;
MPUAngleSamples.add(a);
MPUWobbleSamples.add(g);
joystickTilt = MPUAngleSamples.getMedian();
if(JOYSTICK_DIRECTION == 1) {
joystickTilt = 0-joystickTilt;
}
joystickWobble = abs(MPUWobbleSamples.getHighest());
}
// ---------------------------------
// -------------- SFX --------------
// ---------------------------------
void SFXtilt(int amount){
int f = map(abs(amount), 0, 90, 80, 900)+random8(100);
if(playerPositionModifier < 0) f -= 500;
if(playerPositionModifier > 0) f += 200;
toneAC(f, min(min(abs(amount)/9, 5), MAX_VOLUME));
}
void SFXattacking(){
int freq = map(sin(millis()/2.0)*1000.0, -1000, 1000, 500, 600);
if(random8(5)== 0){
freq *= 3;
}
toneAC(freq, MAX_VOLUME);
}
void SFXdead(){
int freq = max(1000 - (millis()-killTime), 10);
freq += random8(200);
int vol = max(10 - (millis()-killTime)/200, 0);
toneAC(freq, MAX_VOLUME);
}
void SFXkill(){
toneAC(2000, MAX_VOLUME, 1000, true);
}
void SFXwin(){
int freq = (millis()-stageStartTime)/3.0;
freq += map(sin(millis()/20.0)*1000.0, -1000, 1000, 0, 20);
int vol = 10;//max(10 - (millis()-stageStartTime)/200, 0);
toneAC(freq, MAX_VOLUME);
}
void SFXcomplete(){
noToneAC();
}
| 0 | 0.599508 | 1 | 0.599508 | game-dev | MEDIA | 0.624066 | game-dev,embedded-firmware | 0.88458 | 1 | 0.88458 |
cataclysmbnteam/Cataclysm-BN | 24,107 | src/activity_actor_definitions.h | #pragma once
#include "activity_actor.h"
#include <optional>
#include "coordinates.h"
#include "crafting.h"
#include "item_handling_util.h"
#include "location_ptr.h"
#include "locations.h"
#include "memory_fast.h"
#include "pickup_token.h"
#include "point.h"
#include "type_id.h"
#include "units_energy.h"
class Creature;
class vehicle;
struct partial_con;
class aim_activity_actor : public activity_actor
{
private:
location_ptr<item> fake_weapon;
units::energy bp_cost_per_shot = 0_J;
int stamina_cost_per_shot = 0;
std::vector<tripoint> fin_trajectory;
public:
std::string action;
int aif_duration = 0; // Counts aim-and-fire duration
bool aiming_at_critter = false; // Whether aiming at critter or a tile
bool snap_to_target = false;
bool shifting_view = false;
tripoint initial_view_offset;
/** Target UI requested to abort aiming */
bool aborted = false;
/** RELOAD_AND_SHOOT weapon is kept loaded by the activity */
bool loaded_RAS_weapon = false;
/** Item location for RAS weapon reload */
safe_reference<item> reload_loc;
/** if true abort if no targets are available when re-entering aiming ui after shooting */
bool abort_if_no_targets = false;
/**
* Target UI requested to abort aiming and reload weapon
* Implies aborted = true
*/
bool reload_requested = false;
/**
* A friendly creature may enter line of fire during aim-and-shoot,
* and that generates a warning to proceed/abort. If player decides to
* proceed, that creature is saved in this vector to prevent the same warning
* from popping up on the following turn(s).
*/
std::vector<weak_ptr_fast<Creature>> acceptable_losses;
aim_activity_actor();
/** Aiming wielded gun */
static std::unique_ptr<aim_activity_actor> use_wielded();
/** Aiming fake gun provided by a bionic */
static std::unique_ptr<aim_activity_actor> use_bionic( detached_ptr<item> &&fake_gun,
const units::energy &cost_per_shot );
/** Aiming fake gun provided by a mutation */
static std::unique_ptr<aim_activity_actor> use_mutation( detached_ptr<item> &&fake_gun );
activity_id get_type() const override {
return activity_id( "ACT_AIM" );
}
void start( player_activity &act, Character &who ) override;
void do_turn( player_activity &act, Character &who ) override;
void finish( player_activity &act, Character &who ) override;
void canceled( player_activity &act, Character &who ) override;
void serialize( JsonOut &jsout ) const override;
static std::unique_ptr<activity_actor> deserialize( JsonIn &jsin );
item *get_weapon();
void restore_view();
// Load/unload a RELOAD_AND_SHOOT weapon
bool load_RAS_weapon();
void unload_RAS_weapon();
};
class autodrive_activity_actor : public activity_actor
{
private:
vehicle *player_vehicle = nullptr;
public:
autodrive_activity_actor() = default;
activity_id get_type() const override {
return activity_id( "ACT_AUTODRIVE" );
}
void start( player_activity &act, Character & ) override;
void do_turn( player_activity &, Character & ) override;
void canceled( player_activity &, Character & ) override;
void finish( player_activity &act, Character & ) override;
void serialize( JsonOut &jsout ) const override;
static std::unique_ptr<activity_actor> deserialize( JsonIn &jsin );
};
class dig_activity_actor : public activity_actor
{
private:
int moves_total;
/** location of the dig **/
tripoint location;
std::string result_terrain;
tripoint byproducts_location;
std::string byproducts_item_group;
/**
* Returns true if @p other and `this` are "equivalent" in the sense that
* `this` can be resumed instead of starting @p other.
*/
bool equivalent_activity( const dig_activity_actor &other ) const {
return location == other.location &&
result_terrain == other.result_terrain &&
byproducts_location == other.byproducts_location &&
byproducts_item_group == other.byproducts_item_group;
}
/**
* @pre @p other is a `dig_activity_actor`
*/
bool can_resume_with_internal( const activity_actor &other, const Character & ) const override {
const dig_activity_actor &d_actor = static_cast<const dig_activity_actor &>( other );
return equivalent_activity( d_actor );
}
public:
dig_activity_actor(
int dig_moves, const tripoint &dig_loc,
const std::string &resulting_ter, const tripoint &dump_loc,
const std::string &dump_item_group
):
moves_total( dig_moves ), location( dig_loc ),
result_terrain( resulting_ter ),
byproducts_location( dump_loc ),
byproducts_item_group( dump_item_group ) {}
activity_id get_type() const override {
return activity_id( "ACT_DIG" );
}
void start( player_activity &act, Character & ) override;
void do_turn( player_activity &, Character & ) override;
void finish( player_activity &act, Character &who ) override;
void serialize( JsonOut &jsout ) const override;
static std::unique_ptr<activity_actor> deserialize( JsonIn &jsin );
};
class dig_channel_activity_actor : public activity_actor
{
private:
int moves_total;
/** location of the dig **/
tripoint location;
std::string result_terrain;
tripoint byproducts_location;
std::string byproducts_item_group;
/**
* Returns true if @p other and `this` are "equivalent" in the sense that
* `this` can be resumed instead of starting @p other.
*/
bool equivalent_activity( const dig_channel_activity_actor &other ) const {
return location == other.location &&
result_terrain == other.result_terrain &&
byproducts_location == other.byproducts_location &&
byproducts_item_group == other.byproducts_item_group;
}
/**
* @pre @p other is a `dig_activity_actor`
*/
bool can_resume_with_internal( const activity_actor &other, const Character & ) const override {
const dig_channel_activity_actor &dc_actor = static_cast<const dig_channel_activity_actor &>
( other );
return equivalent_activity( dc_actor );
}
public:
dig_channel_activity_actor(
int dig_moves, const tripoint &dig_loc,
const std::string &resulting_ter, const tripoint &dump_loc,
const std::string &dump_item_group
):
moves_total( dig_moves ), location( dig_loc ),
result_terrain( resulting_ter ),
byproducts_location( dump_loc ),
byproducts_item_group( dump_item_group ) {}
activity_id get_type() const override {
return activity_id( "ACT_DIG_CHANNEL" );
}
void start( player_activity &act, Character & ) override;
void do_turn( player_activity &, Character & ) override;
void finish( player_activity &act, Character &who ) override;
void serialize( JsonOut &jsout ) const override;
static std::unique_ptr<activity_actor> deserialize( JsonIn &jsin );
};
class disassemble_activity_actor : public activity_actor
{
private:
std::vector<iuse_location> targets;
tripoint_abs_ms pos;
bool recursive = false;
public:
disassemble_activity_actor() = default;
disassemble_activity_actor(
std::vector<iuse_location> &&targets,
tripoint_abs_ms pos,
bool recursive
) : targets( std::move( targets ) ), pos( pos ), recursive( recursive ) {}
~disassemble_activity_actor() = default;
activity_id get_type() const override {
return activity_id( "ACT_DISASSEMBLE" );
}
void calc_all_moves( player_activity &act, Character &who ) override;
void start( player_activity &act, Character &who ) override;
void do_turn( player_activity &, Character & ) override;
void finish( player_activity &act, Character &who ) override;
void serialize( JsonOut &jsout ) const override;
static std::unique_ptr<activity_actor> deserialize( JsonIn &jsin );
bool try_start_single( player_activity &act, Character &who );
void process_target( player_activity &, iuse_location &target );
};
class drop_activity_actor : public activity_actor
{
private:
std::list<pickup::act_item> items;
bool force_ground = false;
tripoint relpos;
public:
drop_activity_actor() = default;
drop_activity_actor( Character &ch, const drop_locations &items,
bool force_ground, const tripoint &relpos );
activity_id get_type() const override {
return activity_id( "ACT_DROP" );
}
void start( player_activity &, Character & ) override;
void do_turn( player_activity &, Character &who ) override;
void finish( player_activity &, Character & ) override {};
void serialize( JsonOut &jsout ) const override;
static std::unique_ptr<activity_actor> deserialize( JsonIn &jsin );
};
class hacking_activity_actor : public activity_actor
{
private:
bool using_bionic = false;
public:
struct use_bionic {};
hacking_activity_actor() = default;
hacking_activity_actor( use_bionic );
activity_id get_type() const override {
return activity_id( "ACT_HACKING" );
}
void start( player_activity &act, Character &who ) override;
void do_turn( player_activity &, Character & ) override;
void finish( player_activity &act, Character &who ) override;
void serialize( JsonOut &jsout ) const override;
static std::unique_ptr<activity_actor> deserialize( JsonIn &jsin );
};
class hacksaw_activity_actor : public activity_actor
{
public:
explicit hacksaw_activity_actor( const tripoint &target,
const safe_reference<item> &tool ) : target( target ), tool( tool ) {};
activity_id get_type() const override {
return activity_id( "ACT_HACKSAW" );
}
void start( player_activity &act, Character &who ) override;
void do_turn( player_activity &/*act*/, Character &who ) override;
void finish( player_activity &act, Character &who ) override;
void serialize( JsonOut &jsout ) const override;
static std::unique_ptr<activity_actor> deserialize( JsonIn &jsin );
// debugmsg causes a backtrace when fired during cata_test
bool testing = false; // NOLINT(cata-serialize)
private:
tripoint target;
safe_reference<item> tool;
bool can_resume_with_internal( const activity_actor &other,
const Character &/*who*/ ) const override {
const hacksaw_activity_actor &actor = static_cast<const hacksaw_activity_actor &>
( other );
return actor.target == target;
}
};
class boltcutting_activity_actor : public activity_actor
{
public:
explicit boltcutting_activity_actor( const tripoint &target,
const safe_reference<item> tool ) : target( target ), tool( tool ) {};
activity_id get_type() const override {
return activity_id( "ACT_BOLTCUTTING" );
}
void start( player_activity &act, Character &/*who*/ ) override;
void do_turn( player_activity &/*act*/, Character &who ) override;
void finish( player_activity &act, Character &who ) override;
void serialize( JsonOut &jsout ) const override;
static std::unique_ptr<activity_actor> deserialize( JsonIn &jsin );
// debugmsg causes a backtrace when fired during cata_test
bool testing = false;
private:
tripoint target;
safe_reference<item> tool;
bool can_resume_with_internal( const activity_actor &other,
const Character &/*who*/ ) const override {
const boltcutting_activity_actor &actor = static_cast<const boltcutting_activity_actor &>
( other );
return actor.target == target && actor.tool == tool;
}
};
class lockpick_activity_actor : public activity_actor
{
private:
int moves_total;
safe_reference<item> lockpick;
location_ptr<item> fake_lockpick;
tripoint target;
lockpick_activity_actor(
int moves_total,
safe_reference<item> lockpick,
detached_ptr<item> &&fake_lockpick,
const tripoint &target
) : moves_total( moves_total ), lockpick( lockpick ), fake_lockpick( new fake_item_location() ),
target( target ) {
this->fake_lockpick = std::move( fake_lockpick );
};
public:
/** Use regular lockpick. 'target' is in global coords */
static std::unique_ptr<lockpick_activity_actor> use_item(
int moves_total,
item &lockpick,
const tripoint &target
);
/** Use bionic lockpick. 'target' is in global coords */
static std::unique_ptr<lockpick_activity_actor> use_bionic(
detached_ptr<item> &&fake_lockpick,
const tripoint &target
);
activity_id get_type() const override {
return activity_id( "ACT_LOCKPICK" );
}
void start( player_activity &act, Character & ) override;
void do_turn( player_activity &, Character & ) override;
void finish( player_activity &act, Character &who ) override;
static bool is_pickable( const tripoint &p );
static std::optional<tripoint> select_location( avatar &you );
void serialize( JsonOut &jsout ) const override;
static std::unique_ptr<activity_actor> deserialize( JsonIn &jsin );
};
class migration_cancel_activity_actor : public activity_actor
{
public:
migration_cancel_activity_actor() = default;
activity_id get_type() const override {
return activity_id( "ACT_MIGRATION_CANCEL" );
}
void start( player_activity &, Character & ) override {};
void do_turn( player_activity &act, Character &who ) override;
void finish( player_activity &, Character & ) override {};
void serialize( JsonOut &jsout ) const override;
static std::unique_ptr<activity_actor> deserialize( JsonIn &jsin );
};
class move_items_activity_actor : public activity_actor
{
private:
std::vector<safe_reference<item>> target_items;
std::vector<int> quantities;
bool to_vehicle;
tripoint relative_destination;
public:
move_items_activity_actor( std::vector<item *> items, std::vector<int> quantities,
bool to_vehicle, tripoint relative_destination ) :
quantities( quantities ), to_vehicle( to_vehicle ),
relative_destination( relative_destination ) {
for( item *&it : items ) {
target_items.emplace_back( it );
}
}
activity_id get_type() const override {
return activity_id( "ACT_MOVE_ITEMS" );
}
void start( player_activity &, Character & ) override {};
void do_turn( player_activity &act, Character &who ) override;
void finish( player_activity &, Character & ) override {};
void serialize( JsonOut &jsout ) const override;
static std::unique_ptr<activity_actor> deserialize( JsonIn &jsin );
};
class toggle_gate_activity_actor : public activity_actor
{
private:
int moves_total;
tripoint placement;
/**
* @pre @p other is a toggle_gate_activity_actor
*/
bool can_resume_with_internal( const activity_actor &other, const Character & ) const override {
const toggle_gate_activity_actor &og_actor = static_cast<const toggle_gate_activity_actor &>
( other );
return placement == og_actor.placement;
}
public:
toggle_gate_activity_actor( int gate_moves, const tripoint &gate_placement ) :
moves_total( gate_moves ), placement( gate_placement ) {}
activity_id get_type() const override {
return activity_id( "ACT_TOGGLE_GATE" );
}
void start( player_activity &act, Character & ) override;
void do_turn( player_activity &, Character & ) override;
void finish( player_activity &act, Character & ) override;
void serialize( JsonOut &jsout ) const override;
static std::unique_ptr<activity_actor> deserialize( JsonIn &jsin );
};
class pickup_activity_actor : public activity_actor
{
private:
/** Target items and the quantities thereof */
std::vector<pickup::pick_drop_selection> target_items;
/**
* Position of the character when the activity is started. This is
* stored so that we can cancel the activity if the player moves
* (e.g. if the player is in a moving vehicle). This should be null
* if not grabbing from the ground.
*/
std::optional<tripoint> starting_pos;
public:
pickup_activity_actor( const std::vector<pickup::pick_drop_selection> &target_items,
const std::optional<tripoint> &starting_pos )
: target_items( target_items )
, starting_pos( starting_pos ) {}
activity_id get_type() const override {
return activity_id( "ACT_PICKUP" );
}
void start( player_activity &, Character & ) override {};
void do_turn( player_activity &act, Character &who ) override;
void finish( player_activity &, Character & ) override {};
void serialize( JsonOut &jsout ) const override;
static std::unique_ptr<activity_actor> deserialize( JsonIn &jsin );
};
class stash_activity_actor : public activity_actor
{
private:
std::list<pickup::act_item> items;
tripoint relpos;
public:
stash_activity_actor() = default;
stash_activity_actor( Character &ch, const drop_locations &items, const tripoint &relpos );
activity_id get_type() const override {
return activity_id( "ACT_STASH" );
}
void start( player_activity &, Character & ) override;
void do_turn( player_activity &, Character &who ) override;
void finish( player_activity &, Character & ) override {};
void serialize( JsonOut &jsout ) const override;
static std::unique_ptr<activity_actor> deserialize( JsonIn &jsin );
};
class throw_activity_actor : public activity_actor
{
private:
safe_reference<item> target;
std::optional<tripoint> blind_throw_from_pos;
public:
throw_activity_actor() = default;
throw_activity_actor(
item &target,
std::optional<tripoint> blind_throw_from_pos
) : target( &target ),
blind_throw_from_pos( blind_throw_from_pos ) {}
~throw_activity_actor() = default;
activity_id get_type() const override {
return activity_id( "ACT_THROW" );
}
void start( player_activity &, Character & ) override {};
void do_turn( player_activity &act, Character &who ) override;
void finish( player_activity &, Character & ) override {};
void serialize( JsonOut &jsout ) const override;
static std::unique_ptr<activity_actor> deserialize( JsonIn &jsin );
};
class oxytorch_activity_actor : public activity_actor
{
public:
explicit oxytorch_activity_actor( const tripoint &target,
const safe_reference<item> &tool ) : target( target ), tool( tool ) {};
activity_id get_type() const override {
return activity_id( "ACT_OXYTORCH" );
}
void start( player_activity &act, Character &who ) override;
void do_turn( player_activity &/*act*/, Character &who ) override;
void finish( player_activity &act, Character &who ) override;
void serialize( JsonOut &jsout ) const override;
static std::unique_ptr<activity_actor> deserialize( JsonIn &jsin );
// debugmsg causes a backtrace when fired during cata_test
bool testing = false; // NOLINT(cata-serialize)
private:
tripoint target;
safe_reference<item> tool;
bool can_resume_with_internal( const activity_actor &other,
const Character &/*who*/ ) const override {
const oxytorch_activity_actor &actor = static_cast<const oxytorch_activity_actor &>
( other );
return actor.target == target;
}
};
class construction_activity_actor : public activity_actor
{
private:
tripoint_abs_ms target;
partial_con *pc;
public:
explicit construction_activity_actor( const tripoint_abs_ms &target ) : target( target ) {
};
activity_id get_type() const override {
return activity_id( "ACT_BUILD" );
}
void calc_all_moves( player_activity &act, Character &who ) override;
void start( player_activity &act, Character &who ) override;
void do_turn( player_activity &act, Character &who ) override;
void finish( player_activity &act, Character &who ) override;
void serialize( JsonOut &jsout ) const override;
static std::unique_ptr<activity_actor> deserialize( JsonIn &jsin );
};
class assist_activity_actor : public activity_actor
{
public:
explicit assist_activity_actor() {
};
activity_id get_type() const override {
return activity_id( "ACT_ASSIST" );
}
void calc_all_moves( player_activity & /*act*/, Character &/*who*/ ) override {};
void start( player_activity &act, Character &who ) override;
void do_turn( player_activity &/*act*/, Character &/*who*/ ) override {};
void finish( player_activity &/*act*/, Character &/*who*/ ) override {};
void serialize( JsonOut &jsout ) const override;
static std::unique_ptr<activity_actor> deserialize( JsonIn &jsin );
};
class salvage_activity_actor : public activity_actor
{
private:
iuse_locations targets;
tripoint_abs_ms pos;
bool mute_prompts = false;
public:
salvage_activity_actor() = default;
salvage_activity_actor(
iuse_locations &&targets,
tripoint_abs_ms pos
) : targets( std::move( targets ) ), pos( pos ) {}
~salvage_activity_actor() = default;
activity_id get_type() const override {
return activity_id( "ACT_LONGSALVAGE" );
}
void calc_all_moves( player_activity & /*act*/, Character &/*who*/ ) override;
void start( player_activity &act, Character &who ) override;
void do_turn( player_activity &/*act*/, Character &/*who*/ ) override;
void finish( player_activity &/*act*/, Character &/*who*/ ) override;
void serialize( JsonOut &jsout ) const override;
static std::unique_ptr<activity_actor> deserialize( JsonIn &jsin );
};
| 0 | 0.851974 | 1 | 0.851974 | game-dev | MEDIA | 0.889496 | game-dev | 0.778706 | 1 | 0.778706 |
tqjxlm/Sparkle | 1,912 | frameworks/source/android/AndroidFileManager.cpp | #if FRAMEWORK_ANDROID
#include "android/AndroidFileManager.h"
#include <android/asset_manager.h>
namespace sparkle
{
std::unique_ptr<FileManager> FileManager::CreateNativeFileManager()
{
ASSERT(!native_file_manager_);
auto instance = std::make_unique<AndroidFileManager>();
native_file_manager_ = instance.get();
return instance;
}
std::vector<char> AndroidFileManager::ReadResource(const std::string &filepath)
{
const auto &resource_path = ResourceRoot + filepath;
AAsset *asset = AAssetManager_open(asset_manager_, resource_path.c_str(), AASSET_MODE_BUFFER);
if (!asset)
{
return {};
}
auto size = AAsset_getLength64(asset);
std::vector<char> buffer;
buffer.resize(size);
AAsset_read(asset, buffer.data(), size);
AAsset_close(asset);
return buffer;
}
size_t AndroidFileManager::GetResourceSize(const std::string &filepath)
{
const auto &resource_path = ResourceRoot + filepath;
AAsset *asset = AAssetManager_open(asset_manager_, resource_path.c_str(), AASSET_MODE_UNKNOWN);
if (!asset)
{
return std::numeric_limits<size_t>::max();
}
auto size = AAsset_getLength64(asset);
AAsset_close(asset);
return size;
}
bool AndroidFileManager::ResourceExists(const std::string &filepath)
{
const auto &resource_path = ResourceRoot + filepath;
AAsset *asset = AAssetManager_open(asset_manager_, resource_path.c_str(), AASSET_MODE_UNKNOWN);
bool exists = (asset != nullptr);
if (asset)
{
AAsset_close(asset);
}
return exists;
}
void AndroidFileManager::Setup(AAssetManager *asset_manager, const std::string &interal_file_path,
const std::string &external_file_path)
{
asset_manager_ = asset_manager;
internal_file_path_ = interal_file_path;
external_file_path_ = external_file_path;
}
} // namespace sparkle
#endif
| 0 | 0.978187 | 1 | 0.978187 | game-dev | MEDIA | 0.714153 | game-dev | 0.896545 | 1 | 0.896545 |
folium-app/Cytrus | 1,038 | Core/include/common/scope_exit.h | // Copyright 2014 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include <utility>
#include "common/common_funcs.h"
namespace detail {
template <typename Func>
struct ScopeExitHelper {
explicit ScopeExitHelper(Func&& func) : func(std::move(func)) {}
~ScopeExitHelper() {
func();
}
Func func;
};
template <typename Func>
ScopeExitHelper<Func> ScopeExit(Func&& func) {
return ScopeExitHelper<Func>(std::forward<Func>(func));
}
} // namespace detail
/**
* This macro allows you to conveniently specify a block of code that will run on scope exit. Handy
* for doing ad-hoc clean-up tasks in a function with multiple returns.
*
* Example usage:
* \code
* const int saved_val = g_foo;
* g_foo = 55;
* SCOPE_EXIT({ g_foo = saved_val; });
*
* if (Bar()) {
* return 0;
* } else {
* return 20;
* }
* \endcode
*/
#define SCOPE_EXIT(body) auto CONCAT2(scope_exit_helper_, __LINE__) = detail::ScopeExit([&]() body)
| 0 | 0.904869 | 1 | 0.904869 | game-dev | MEDIA | 0.19817 | game-dev | 0.70742 | 1 | 0.70742 |
gnosygnu/xowa | 2,160 | 400_xowa/src/gplx/xowa/xtns/pfuncs/wikis/Pfunc_wiki_props.java | /*
XOWA: the XOWA Offline Wiki Application
Copyright (C) 2012-2017 gnosygnu@gmail.com
XOWA is licensed under the terms of the General Public License (GPL) Version 3,
or alternatively under the terms of the Apache License Version 2.0.
You may use XOWA according to either of these licenses as is most appropriate
for your project on a case-by-case basis.
The terms of each license can be found in the source code repository:
GPLv3 License: https://github.com/gnosygnu/xowa/blob/master/LICENSE-GPLv3.txt
Apache License: https://github.com/gnosygnu/xowa/blob/master/LICENSE-APACHE2.txt
*/
package gplx.xowa.xtns.pfuncs.wikis; import gplx.*; import gplx.xowa.*; import gplx.xowa.xtns.*; import gplx.xowa.xtns.pfuncs.*;
import gplx.xowa.langs.*; import gplx.xowa.langs.kwds.*;
import gplx.xowa.parsers.*; import gplx.xowa.parsers.tmpls.*;
import gplx.xowa.wikis.metas.*;
public class Pfunc_wiki_props extends Pf_func_base {
public Pfunc_wiki_props(int id) {this.id = id;}
@Override public int Id() {return id;} private int id;
@Override public void Func_evaluate(Bry_bfr bfr, Xop_ctx ctx, Xot_invk caller, Xot_invk self, byte[] src) {
Xow_wiki_props props = ctx.Wiki().Props();
switch (id) {
case Xol_kwd_grp_.Id_site_sitename: bfr.Add(props.Site_name()); break;
case Xol_kwd_grp_.Id_site_server: bfr.Add(props.Server()); break;
case Xol_kwd_grp_.Id_site_servername: bfr.Add(props.Server_name()); break;
case Xol_kwd_grp_.Id_site_articlepath: bfr.Add(props.Article_path()); break;
case Xol_kwd_grp_.Id_site_scriptpath: bfr.Add(props.Script_path()); break;
case Xol_kwd_grp_.Id_site_stylepath: bfr.Add(props.Style_path()); break;
case Xol_kwd_grp_.Id_site_directionmark: bfr.Add(props.Direction_mark()); break;
case Xol_kwd_grp_.Id_site_currentversion: bfr.Add(props.Current_version()); break;
case Xol_kwd_grp_.Id_site_contentlanguage: bfr.Add(ctx.Page().Lang().Key_bry()); break;
default: throw Err_.new_unhandled(id);
}
}
@Override public Pf_func New(int id, byte[] name) {return new Pfunc_wiki_props(id).Name_(name);}
public static final Pfunc_wiki_props Instance = new Pfunc_wiki_props(-1);
}
| 0 | 0.504825 | 1 | 0.504825 | game-dev | MEDIA | 0.380979 | game-dev | 0.592931 | 1 | 0.592931 |
Gaby-Station/Gaby-Station | 5,967 | Content.Goobstation.Shared/Traits/Systems/LegsParalyzedSystem.cs | // SPDX-FileCopyrightText: 2023 Morb <14136326+Morb0@users.noreply.github.com>
// SPDX-FileCopyrightText: 2023 Ray <vigersray@gmail.com>
// SPDX-FileCopyrightText: 2024 Aiden <aiden@djkraz.com>
// SPDX-FileCopyrightText: 2024 Alice "Arimah" Heurlin <30327355+arimah@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 Chief-Engineer <119664036+Chief-Engineer@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 DrSmugleaf <10968691+DrSmugleaf@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 Ed <96445749+TheShuEd@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 Errant <35878406+Errant-4@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 Flareguy <78941145+Flareguy@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 HS <81934438+HolySSSS@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 IProduceWidgets <107586145+IProduceWidgets@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 Leon Friedrich <60421075+ElectroJr@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 Mr. 27 <45323883+Dutch-VanDerLinde@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 Nemanja <98561806+EmoGarbage404@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 PJBot <pieterjan.briers+bot@gmail.com>
// SPDX-FileCopyrightText: 2024 Pieter-Jan Briers <pieterjan.briers+git@gmail.com>
// SPDX-FileCopyrightText: 2024 Piras314 <p1r4s@proton.me>
// SPDX-FileCopyrightText: 2024 Plykiya <58439124+Plykiya@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 Rouge2t7 <81053047+Sarahon@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 Scruq445 <storchdamien@gmail.com>
// SPDX-FileCopyrightText: 2024 Tayrtahn <tayrtahn@gmail.com>
// SPDX-FileCopyrightText: 2024 Truoizys <153248924+Truoizys@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 TsjipTsjip <19798667+TsjipTsjip@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 Ubaser <134914314+UbaserB@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 Vasilis <vasilis@pikachu.systems>
// SPDX-FileCopyrightText: 2024 beck-thompson <107373427+beck-thompson@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 deltanedas <39013340+deltanedas@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 deltanedas <@deltanedas:kde.org>
// SPDX-FileCopyrightText: 2024 lzk <124214523+lzk228@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 metalgearsloth <31366439+metalgearsloth@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 osjarw <62134478+osjarw@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 plykiya <plykiya@protonmail.com>
// SPDX-FileCopyrightText: 2024 Арт <123451459+JustArt1m@users.noreply.github.com>
// SPDX-FileCopyrightText: 2025 Aiden <28298836+Aidenkrz@users.noreply.github.com>
// SPDX-FileCopyrightText: 2025 Misandry <mary@thughunt.ing>
// SPDX-FileCopyrightText: 2025 gus <august.eymann@gmail.com>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
using Content.Goobstation.Common.Traits;
using Content.Shared.Body.Systems;
using Content.Shared.Buckle.Components;
using Content.Shared.Movement.Events;
using Content.Shared.Movement.Systems;
using Content.Shared.Standing;
using Content.Shared.Throwing;
using Content.Shared.Popups;
namespace Content.Goobstation.Shared.Traits.Assorted;
public sealed class LegsParalyzedSystem : EntitySystem
{
[Dependency] private readonly MovementSpeedModifierSystem _movementSpeedModifierSystem = default!;
[Dependency] private readonly StandingStateSystem _standingSystem = default!;
[Dependency] private readonly SharedBodySystem _bodySystem = default!;
[Dependency] private readonly SharedPopupSystem _popupSystem = default!;
public override void Initialize()
{
SubscribeLocalEvent<LegsParalyzedComponent, ComponentStartup>(OnStartup);
SubscribeLocalEvent<LegsParalyzedComponent, ComponentShutdown>(OnShutdown);
SubscribeLocalEvent<LegsParalyzedComponent, BuckledEvent>(OnBuckled);
SubscribeLocalEvent<LegsParalyzedComponent, UnbuckledEvent>(OnUnbuckled);
SubscribeLocalEvent<LegsParalyzedComponent, ThrowPushbackAttemptEvent>(OnThrowPushbackAttempt);
SubscribeLocalEvent<LegsParalyzedComponent, StandAttemptEvent>(OnStandTry);
SubscribeLocalEvent<LegsParalyzedComponent, DownedEvent>(OnDowned);
}
private void OnStartup(EntityUid uid, LegsParalyzedComponent component, ComponentStartup args)
{
// Completely paralyzed: cannot walk or run.
_movementSpeedModifierSystem.ChangeBaseSpeed(uid, 0, 0, 20);
}
private void OnShutdown(EntityUid uid, LegsParalyzedComponent component, ComponentShutdown args)
{
_standingSystem.Stand(uid);
_bodySystem.UpdateMovementSpeed(uid);
}
private void OnBuckled(EntityUid uid, LegsParalyzedComponent component, ref BuckledEvent args)
{
_standingSystem.Stand(uid);
_movementSpeedModifierSystem.ChangeBaseSpeed(
uid,
component.CrawlMoveSpeed,
component.CrawlMoveSpeed,
component.CrawlMoveAcceleration);
}
private void OnUnbuckled(EntityUid uid, LegsParalyzedComponent component, ref UnbuckledEvent args)
{
_standingSystem.Down(uid);
}
private void OnDowned(EntityUid uid, LegsParalyzedComponent component, DownedEvent args)
{
_movementSpeedModifierSystem.ChangeBaseSpeed(
uid,
component.CrawlMoveSpeed,
component.CrawlMoveSpeed,
component.CrawlMoveAcceleration);
}
private void OnStandTry(EntityUid uid, LegsParalyzedComponent component, StandAttemptEvent args)
{
args.Cancel();
_popupSystem.PopupClient(Loc.GetString("paralyzed-no-stand"), uid, uid, PopupType.Medium);
_standingSystem.Down(uid);
}
private void OnThrowPushbackAttempt(EntityUid uid, LegsParalyzedComponent component, ThrowPushbackAttemptEvent args)
{
args.Cancel();
}
}
| 0 | 0.750976 | 1 | 0.750976 | game-dev | MEDIA | 0.59526 | game-dev | 0.680306 | 1 | 0.680306 |
TastSong/GameProgrammerStudyNotes | 2,553 | GameProgrammingPatterns/Library/PackageCache/com.unity.textmeshpro@2.1.4/Scripts/Editor/TMP_SubMesh_Editor.cs | using UnityEngine;
using UnityEditor;
using System.Collections;
namespace TMPro.EditorUtilities
{
[CustomEditor(typeof(TMP_SubMesh)), CanEditMultipleObjects]
public class TMP_SubMesh_Editor : Editor
{
private struct m_foldout
{ // Track Inspector foldout panel states, globally.
//public static bool textInput = true;
public static bool fontSettings = true;
//public static bool extraSettings = false;
//public static bool shadowSetting = false;
//public static bool materialEditor = true;
}
private SerializedProperty fontAsset_prop;
private SerializedProperty spriteAsset_prop;
private TMP_SubMesh m_SubMeshComponent;
private Renderer m_Renderer;
private string[] m_SortingLayerNames;
public void OnEnable()
{
fontAsset_prop = serializedObject.FindProperty("m_fontAsset");
spriteAsset_prop = serializedObject.FindProperty("m_spriteAsset");
m_SubMeshComponent = target as TMP_SubMesh;
m_Renderer = m_SubMeshComponent.renderer;
m_SortingLayerNames = SortingLayerHelper.sortingLayerNames;
}
public override void OnInspectorGUI()
{
EditorGUI.indentLevel = 0;
GUI.enabled = false;
EditorGUILayout.PropertyField(fontAsset_prop);
EditorGUILayout.PropertyField(spriteAsset_prop);
GUI.enabled = true;
EditorGUI.BeginChangeCheck();
// Look up the layer name using the current layer ID
string oldName = SortingLayer.IDToName(m_Renderer.sortingLayerID);
// Use the name to look up our array index into the names list
int oldLayerIndex = System.Array.IndexOf(m_SortingLayerNames, oldName);
// Show the pop-up for the names
int newLayerIndex = EditorGUILayout.Popup("Sorting Layer", oldLayerIndex, m_SortingLayerNames);
// If the index changes, look up the ID for the new index to store as the new ID
if (newLayerIndex != oldLayerIndex)
m_Renderer.sortingLayerID = SortingLayer.NameToID(m_SortingLayerNames[newLayerIndex]);
// Expose the manual sorting order
int newSortingLayerOrder = EditorGUILayout.IntField("Order in Layer", m_Renderer.sortingOrder);
if (newSortingLayerOrder != m_Renderer.sortingOrder)
m_Renderer.sortingOrder = newSortingLayerOrder;
}
}
}
| 0 | 0.765752 | 1 | 0.765752 | game-dev | MEDIA | 0.893263 | game-dev | 0.883611 | 1 | 0.883611 |
dufernst/LegionCore-7.3.5 | 4,043 | src/server/game/Handlers/TicketHandler.cpp | /*
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Common.h"
#include "Language.h"
#include "ObjectMgr.h"
#include "Player.h"
#include "TicketMgr.h"
#include "TicketPackets.h"
#include "Util.h"
#include "World.h"
#include "WorldPacket.h"
#include "WorldSession.h"
#include "DatabaseEnv.h"
#include "WordFilterMgr.h"
void WorldSession::HandleComplaint(WorldPackets::Ticket::Complaint& packet)
{
uint64 complaintId = sObjectMgr->GenerateReportComplaintID();
if (sWordFilterMgr->AddComplaintForUser(packet.Offender.PlayerGuid, GetPlayer()->GetGUID(), complaintId, packet.Chat.MessageLog))
{
uint8 index = 0;
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARACTER_COMPLAINTS);
stmt->setUInt64(index++, complaintId);
stmt->setUInt64(index++, GetPlayer()->GetGUIDLow());
stmt->setUInt32(index++, GetAccountId());
stmt->setUInt32(index++, time(NULL));
stmt->setUInt64(index++, packet.Offender.PlayerGuid.GetGUIDLow());
stmt->setUInt8(index++, packet.ComplaintType);
stmt->setUInt32(index++, packet.MailID);
stmt->setUInt32(index++, packet.Offender.TimeSinceOffence);
stmt->setString(index++, packet.Chat.MessageLog);
CharacterDatabase.Execute(stmt);
}
WorldPackets::Ticket::ComplaintResult result;
result.ComplaintType = packet.ComplaintType;
result.Result = 0;
SendPacket(result.Write());
}
void WorldSession::HandleSupportTicketSubmitBug(WorldPackets::Ticket::SupportTicketSubmitBug& packet)
{
// Don't accept tickets if the ticket queue is disabled. (Ticket UI is greyed out but not fully dependable)
if (!sTicketMgr->GetStatus())
return;
if (GetPlayer()->getLevel() < sWorld->getIntConfig(CONFIG_TICKET_LEVEL_REQ))
{
SendNotification(GetTrinityString(LANG_TICKET_REQ), sWorld->getIntConfig(CONFIG_TICKET_LEVEL_REQ));
return;
}
// Player must not have ticket
if (!sTicketMgr->GetTicketByPlayer(GetPlayer()->GetGUID()))
{
GmTicket* ticket = new GmTicket(GetPlayer(), packet);
sTicketMgr->AddTicket(ticket);
sTicketMgr->UpdateLastChange();
sWorld->SendGMText(LANG_COMMAND_TICKETNEW, GetPlayer()->GetName(), ticket->GetId());
}
}
void WorldSession::HandleGMTicketGetSystemStatus(WorldPackets::Ticket::GMTicketGetSystemStatus& /*packet*/)
{
// Note: This only disables the ticket UI at client side and is not fully reliable
WorldPackets::Ticket::GMTicketSystemStatus response;
response.Status = sTicketMgr->GetStatus() ? GMTICKET_QUEUE_STATUS_ENABLED : GMTICKET_QUEUE_STATUS_DISABLED;
SendPacket(response.Write());
}
void WorldSession::HandleGMTicketAcknowledgeSurvey(WorldPackets::Ticket::GMTicketAcknowledgeSurvey& /*packet*/)
{ }
void WorldSession::HandleGMTicketGetCaseStatus(WorldPackets::Ticket::GMTicketGetCaseStatus& /*packet*/)
{
// TODO: Implement GmCase and handle this packet properly
WorldPackets::Ticket::GMTicketCaseStatus status;
SendPacket(status.Write());
}
void WorldSession::HandleSupportTicketSubmitComplaint(WorldPackets::Ticket::SupportTicketSubmitComplaint& /*packet*/)
{ }
void WorldSession::HandleSupportTicketSubmitSuggestion(WorldPackets::Ticket::SupportTicketSubmitSuggestion& /*packet*/)
{ }
| 0 | 0.901029 | 1 | 0.901029 | game-dev | MEDIA | 0.425836 | game-dev | 0.73995 | 1 | 0.73995 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.