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 | 5,263 | Chapter06/Include/bullet/LinearMath/btQuickprof.h |
/***************************************************************************************************
**
** Real-Time Hierarchical Profiling for Game Programming Gems 3
**
** by Greg Hjelstrom & Byon Garrabrant
**
***************************************************************************************************/
// Credits: The Clock class was inspired by the Timer classes in
// Ogre (www.ogre3d.org).
#ifndef BT_QUICK_PROF_H
#define BT_QUICK_PROF_H
#include "btScalar.h"
#define USE_BT_CLOCK 1
#ifdef USE_BT_CLOCK
///The btClock is a portable basic clock that measures accurate time in seconds, use for profiling.
class btClock
{
public:
btClock();
btClock(const btClock& other);
btClock& operator=(const btClock& other);
~btClock();
/// Resets the initial reference time.
void reset();
/// Returns the time in ms since the last call to reset or since
/// the btClock was created.
unsigned long int getTimeMilliseconds();
/// Returns the time in us since the last call to reset or since
/// the Clock was created.
unsigned long int getTimeMicroseconds();
/// Returns the time in s since the last call to reset or since
/// the Clock was created.
btScalar getTimeSeconds();
private:
struct btClockData* m_data;
};
#endif //USE_BT_CLOCK
//To disable built-in profiling, please comment out next line
#define BT_NO_PROFILE 1
#ifndef BT_NO_PROFILE
#include <stdio.h>//@todo remove this, backwards compatibility
#include "btAlignedAllocator.h"
#include <new>
///A node in the Profile Hierarchy Tree
class CProfileNode {
public:
CProfileNode( const char * name, CProfileNode * parent );
~CProfileNode( void );
CProfileNode * Get_Sub_Node( const char * name );
CProfileNode * Get_Parent( void ) { return Parent; }
CProfileNode * Get_Sibling( void ) { return Sibling; }
CProfileNode * Get_Child( void ) { return Child; }
void CleanupMemory();
void Reset( void );
void Call( void );
bool Return( void );
const char * Get_Name( void ) { return Name; }
int Get_Total_Calls( void ) { return TotalCalls; }
float Get_Total_Time( void ) { return TotalTime; }
void* GetUserPointer() const {return m_userPtr;}
void SetUserPointer(void* ptr) { m_userPtr = ptr;}
protected:
const char * Name;
int TotalCalls;
float TotalTime;
unsigned long int StartTime;
int RecursionCounter;
CProfileNode * Parent;
CProfileNode * Child;
CProfileNode * Sibling;
void* m_userPtr;
};
///An iterator to navigate through the tree
class CProfileIterator
{
public:
// Access all the children of the current parent
void First(void);
void Next(void);
bool Is_Done(void);
bool Is_Root(void) { return (CurrentParent->Get_Parent() == 0); }
void Enter_Child( int index ); // Make the given child the new parent
void Enter_Largest_Child( void ); // Make the largest child the new parent
void Enter_Parent( void ); // Make the current parent's parent the new parent
// Access the current child
const char * Get_Current_Name( void ) { return CurrentChild->Get_Name(); }
int Get_Current_Total_Calls( void ) { return CurrentChild->Get_Total_Calls(); }
float Get_Current_Total_Time( void ) { return CurrentChild->Get_Total_Time(); }
void* Get_Current_UserPointer( void ) { return CurrentChild->GetUserPointer(); }
void Set_Current_UserPointer(void* ptr) {CurrentChild->SetUserPointer(ptr);}
// Access the current parent
const char * Get_Current_Parent_Name( void ) { return CurrentParent->Get_Name(); }
int Get_Current_Parent_Total_Calls( void ) { return CurrentParent->Get_Total_Calls(); }
float Get_Current_Parent_Total_Time( void ) { return CurrentParent->Get_Total_Time(); }
protected:
CProfileNode * CurrentParent;
CProfileNode * CurrentChild;
CProfileIterator( CProfileNode * start );
friend class CProfileManager;
};
///The Manager for the Profile system
class CProfileManager {
public:
static void Start_Profile( const char * name );
static void Stop_Profile( void );
static void CleanupMemory(void)
{
Root.CleanupMemory();
}
static void Reset( void );
static void Increment_Frame_Counter( void );
static int Get_Frame_Count_Since_Reset( void ) { return FrameCounter; }
static float Get_Time_Since_Reset( void );
static CProfileIterator * Get_Iterator( void )
{
return new CProfileIterator( &Root );
}
static void Release_Iterator( CProfileIterator * iterator ) { delete ( iterator); }
static void dumpRecursive(CProfileIterator* profileIterator, int spacing);
static void dumpAll();
private:
static CProfileNode Root;
static CProfileNode * CurrentNode;
static int FrameCounter;
static unsigned long int ResetTime;
};
///ProfileSampleClass is a simple way to profile a function's scope
///Use the BT_PROFILE macro at the start of scope to time
class CProfileSample {
public:
CProfileSample( const char * name )
{
CProfileManager::Start_Profile( name );
}
~CProfileSample( void )
{
CProfileManager::Stop_Profile();
}
};
#define BT_PROFILE( name ) CProfileSample __profile( name )
#else
#define BT_PROFILE( name )
#endif //#ifndef BT_NO_PROFILE
#endif //BT_QUICK_PROF_H
| 0 | 0.97278 | 1 | 0.97278 | game-dev | MEDIA | 0.777482 | game-dev | 0.891557 | 1 | 0.891557 |
Secrets-of-Sosaria/World | 1,669 | Data/Scripts/Mobiles/Animals/Felines/BlackCat.cs | using System;
using Server;
using Server.Items;
namespace Server.Mobiles
{
[CorpseName( "a cat corpse" )]
public class BlackCat : BaseCreature
{
[Constructable]
public BlackCat () : base( AIType.AI_Mage, FightMode.Aggressor, 10, 1, 0.2, 0.4 )
{
Name = "a cat";
Body = 0xC9;
BaseSoundID = 0x69;
Hue = 0x497;
SetStr( 96, 125 );
SetDex( 86, 105 );
SetInt( 141, 165 );
SetHits( 58, 75 );
SetDamage( 5, 10 );
SetDamageType( ResistanceType.Physical, 100 );
SetResistance( ResistanceType.Physical, 35, 40 );
SetResistance( ResistanceType.Fire, 40, 50 );
SetResistance( ResistanceType.Cold, 20, 30 );
SetResistance( ResistanceType.Poison, 10, 20 );
SetResistance( ResistanceType.Energy, 20, 30 );
SetSkill( SkillName.Psychology, 50.1, 65.0 );
SetSkill( SkillName.Magery, 50.1, 65.0 );
SetSkill( SkillName.MagicResist, 60.1, 75.0 );
SetSkill( SkillName.Tactics, 50.1, 70.0 );
SetSkill( SkillName.FistFighting, 50.1, 70.0 );
Fame = 0;
Karma = 3500;
VirtualArmor = 36;
PackReg( Utility.RandomMinMax( 5, 15 ) );
PackReg( Utility.RandomMinMax( 5, 15 ) );
PackReg( Utility.RandomMinMax( 5, 15 ) );
}
public override void GenerateLoot()
{
AddLoot( LootPack.Average );
AddLoot( LootPack.LowPotions );
}
public override int Meat{ get{ return 1; } }
public BlackCat( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
} | 0 | 0.865484 | 1 | 0.865484 | game-dev | MEDIA | 0.981136 | game-dev | 0.852239 | 1 | 0.852239 |
goldeneye-source/ges-code | 11,378 | game/client/sdk/sdk_hud_ammo.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "cbase.h"
#include "hud.h"
#include "hudelement.h"
#include "hud_macros.h"
#include "hud_numericdisplay.h"
#include "iclientmode.h"
#include "iclientvehicle.h"
#include <vgui_controls/AnimationController.h>
#include <vgui/ILocalize.h>
#include "ihudlcd.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
//-----------------------------------------------------------------------------
// Purpose: Displays current ammunition level
//-----------------------------------------------------------------------------
class CHudAmmo : public CHudNumericDisplay, public CHudElement
{
DECLARE_CLASS_SIMPLE( CHudAmmo, CHudNumericDisplay );
public:
CHudAmmo( const char *pElementName );
void Init( void );
void VidInit( void );
void Reset();
void SetAmmo(int ammo, bool playAnimation);
void SetAmmo2(int ammo2, bool playAnimation);
protected:
virtual void OnThink();
void UpdateAmmoDisplays();
void UpdatePlayerAmmo( C_BasePlayer *player );
private:
CHandle< C_BaseCombatWeapon > m_hCurrentActiveWeapon;
CHandle< C_BaseEntity > m_hCurrentVehicle;
int m_iAmmo;
int m_iAmmo2;
};
DECLARE_HUDELEMENT( CHudAmmo );
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CHudAmmo::CHudAmmo( const char *pElementName ) : BaseClass(NULL, "HudAmmo"), CHudElement( pElementName )
{
SetHiddenBits( HIDEHUD_HEALTH | HIDEHUD_PLAYERDEAD | HIDEHUD_NEEDSUIT | HIDEHUD_WEAPONSELECTION );
hudlcd->SetGlobalStat( "(ammo_primary)", "0" );
hudlcd->SetGlobalStat( "(ammo_secondary)", "0" );
hudlcd->SetGlobalStat( "(weapon_print_name)", "" );
hudlcd->SetGlobalStat( "(weapon_name)", "" );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHudAmmo::Init( void )
{
m_iAmmo = -1;
m_iAmmo2 = -1;
wchar_t *tempString = g_pVGuiLocalize->Find("#Valve_Hud_AMMO");
if (tempString)
{
SetLabelText(tempString);
}
else
{
SetLabelText(L"AMMO");
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHudAmmo::VidInit( void )
{
}
//-----------------------------------------------------------------------------
// Purpose: Resets hud after save/restore
//-----------------------------------------------------------------------------
void CHudAmmo::Reset()
{
BaseClass::Reset();
m_hCurrentActiveWeapon = NULL;
m_hCurrentVehicle = NULL;
m_iAmmo = 0;
m_iAmmo2 = 0;
UpdateAmmoDisplays();
}
//-----------------------------------------------------------------------------
// Purpose: called every frame to get ammo info from the weapon
//-----------------------------------------------------------------------------
void CHudAmmo::UpdatePlayerAmmo( C_BasePlayer *player )
{
// Clear out the vehicle entity
m_hCurrentVehicle = NULL;
C_BaseCombatWeapon *wpn = GetActiveWeapon();
hudlcd->SetGlobalStat( "(weapon_print_name)", wpn ? wpn->GetPrintName() : " " );
hudlcd->SetGlobalStat( "(weapon_name)", wpn ? wpn->GetName() : " " );
if ( !wpn || !player || !wpn->UsesPrimaryAmmo() )
{
hudlcd->SetGlobalStat( "(ammo_primary)", "n/a" );
hudlcd->SetGlobalStat( "(ammo_secondary)", "n/a" );
SetPaintEnabled(false);
SetPaintBackgroundEnabled(false);
return;
}
SetPaintEnabled(true);
SetPaintBackgroundEnabled(true);
// get the ammo in our clip
int ammo1 = wpn->Clip1();
int ammo2;
if (ammo1 < 0)
{
// we don't use clip ammo, just use the total ammo count
ammo1 = player->GetAmmoCount(wpn->GetPrimaryAmmoType());
ammo2 = 0;
}
else
{
// we use clip ammo, so the second ammo is the total ammo
ammo2 = player->GetAmmoCount(wpn->GetPrimaryAmmoType());
}
hudlcd->SetGlobalStat( "(ammo_primary)", VarArgs( "%d", ammo1 ) );
hudlcd->SetGlobalStat( "(ammo_secondary)", VarArgs( "%d", ammo2 ) );
if (wpn == m_hCurrentActiveWeapon)
{
// same weapon, just update counts
SetAmmo(ammo1, true);
SetAmmo2(ammo2, true);
}
else
{
// diferent weapon, change without triggering
SetAmmo(ammo1, false);
SetAmmo2(ammo2, false);
// update whether or not we show the total ammo display
if (wpn->UsesClipsForAmmo1())
{
SetShouldDisplaySecondaryValue(true);
g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("WeaponUsesClips");
}
else
{
g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("WeaponDoesNotUseClips");
SetShouldDisplaySecondaryValue(false);
}
g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("WeaponChanged");
m_hCurrentActiveWeapon = wpn;
}
}
/*
void CHudAmmo::UpdateVehicleAmmo( C_BasePlayer *player, IClientVehicle *pVehicle )
{
m_hCurrentActiveWeapon = NULL;
CBaseEntity *pVehicleEnt = pVehicle->GetVehicleEnt();
if ( !pVehicleEnt || pVehicle->GetPrimaryAmmoType() < 0 )
{
SetPaintEnabled(false);
SetPaintBackgroundEnabled(false);
return;
}
SetPaintEnabled(true);
SetPaintBackgroundEnabled(true);
// get the ammo in our clip
int ammo1 = pVehicle->GetPrimaryAmmoClip();
int ammo2;
if (ammo1 < 0)
{
// we don't use clip ammo, just use the total ammo count
ammo1 = pVehicle->GetPrimaryAmmoCount();
ammo2 = 0;
}
else
{
// we use clip ammo, so the second ammo is the total ammo
ammo2 = pVehicle->GetPrimaryAmmoCount();
}
if (pVehicleEnt == m_hCurrentVehicle)
{
// same weapon, just update counts
SetAmmo(ammo1, true);
SetAmmo2(ammo2, true);
}
else
{
// diferent weapon, change without triggering
SetAmmo(ammo1, false);
SetAmmo2(ammo2, false);
// update whether or not we show the total ammo display
if (pVehicle->PrimaryAmmoUsesClips())
{
SetShouldDisplaySecondaryValue(true);
g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("WeaponUsesClips");
}
else
{
g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("WeaponDoesNotUseClips");
SetShouldDisplaySecondaryValue(false);
}
g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("WeaponChanged");
m_hCurrentVehicle = pVehicleEnt;
}
}
*/
//-----------------------------------------------------------------------------
// Purpose: called every frame to get ammo info from the weapon
//-----------------------------------------------------------------------------
void CHudAmmo::OnThink()
{
UpdateAmmoDisplays();
}
//-----------------------------------------------------------------------------
// Purpose: updates the ammo display counts
//-----------------------------------------------------------------------------
void CHudAmmo::UpdateAmmoDisplays()
{
C_BasePlayer *player = C_BasePlayer::GetLocalPlayer();
UpdatePlayerAmmo( player );
}
//-----------------------------------------------------------------------------
// Purpose: Updates ammo display
//-----------------------------------------------------------------------------
void CHudAmmo::SetAmmo(int ammo, bool playAnimation)
{
if (ammo != m_iAmmo)
{
if (ammo == 0)
{
g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("AmmoEmpty");
}
else if (ammo < m_iAmmo)
{
// ammo has decreased
g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("AmmoDecreased");
}
else
{
// ammunition has increased
g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("AmmoIncreased");
}
m_iAmmo = ammo;
}
SetDisplayValue(ammo);
}
//-----------------------------------------------------------------------------
// Purpose: Updates 2nd ammo display
//-----------------------------------------------------------------------------
void CHudAmmo::SetAmmo2(int ammo2, bool playAnimation)
{
if (ammo2 != m_iAmmo2)
{
if (ammo2 == 0)
{
g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("Ammo2Empty");
}
else if (ammo2 < m_iAmmo2)
{
// ammo has decreased
g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("Ammo2Decreased");
}
else
{
// ammunition has increased
g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("Ammo2Increased");
}
m_iAmmo2 = ammo2;
}
SetSecondaryValue(ammo2);
}
//-----------------------------------------------------------------------------
// Purpose: Displays the secondary ammunition level
//-----------------------------------------------------------------------------
class CHudSecondaryAmmo : public CHudNumericDisplay, public CHudElement
{
DECLARE_CLASS_SIMPLE( CHudSecondaryAmmo, CHudNumericDisplay );
public:
CHudSecondaryAmmo( const char *pElementName ) : BaseClass( NULL, "HudAmmoSecondary" ), CHudElement( pElementName )
{
m_iAmmo = -1;
SetHiddenBits( HIDEHUD_HEALTH | HIDEHUD_WEAPONSELECTION | HIDEHUD_PLAYERDEAD | HIDEHUD_NEEDSUIT );
}
void Init( void )
{
}
void VidInit( void )
{
}
void SetAmmo( int ammo )
{
if (ammo != m_iAmmo)
{
if (ammo == 0)
{
g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("AmmoSecondaryEmpty");
}
else if (ammo < m_iAmmo)
{
// ammo has decreased
g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("AmmoSecondaryDecreased");
}
else
{
// ammunition has increased
g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("AmmoSecondaryIncreased");
}
m_iAmmo = ammo;
}
SetDisplayValue( ammo );
}
void Reset()
{
// hud reset, update ammo state
BaseClass::Reset();
m_iAmmo = 0;
m_hCurrentActiveWeapon = NULL;
SetAlpha( 0 );
UpdateAmmoState();
}
protected:
virtual void OnThink()
{
// set whether or not the panel draws based on if we have a weapon that supports secondary ammo
C_BaseCombatWeapon *wpn = GetActiveWeapon();
C_BasePlayer *player = C_BasePlayer::GetLocalPlayer();
IClientVehicle *pVehicle = player ? player->GetVehicle() : NULL;
if (!wpn || !player || pVehicle)
{
m_hCurrentActiveWeapon = NULL;
SetPaintEnabled(false);
SetPaintBackgroundEnabled(false);
return;
}
else
{
SetPaintEnabled(true);
SetPaintBackgroundEnabled(true);
}
UpdateAmmoState();
}
void UpdateAmmoState()
{
C_BaseCombatWeapon *wpn = GetActiveWeapon();
C_BasePlayer *player = C_BasePlayer::GetLocalPlayer();
if (player && wpn && wpn->UsesSecondaryAmmo())
{
SetAmmo(player->GetAmmoCount(wpn->GetSecondaryAmmoType()));
}
if ( m_hCurrentActiveWeapon != wpn )
{
if ( wpn->UsesSecondaryAmmo() )
{
// we've changed to a weapon that uses secondary ammo
g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("WeaponUsesSecondaryAmmo");
}
else
{
// we've changed away from a weapon that uses secondary ammo
g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("WeaponDoesNotUseSecondaryAmmo");
}
m_hCurrentActiveWeapon = wpn;
}
}
private:
CHandle< C_BaseCombatWeapon > m_hCurrentActiveWeapon;
int m_iAmmo;
};
DECLARE_HUDELEMENT( CHudSecondaryAmmo );
| 0 | 0.849067 | 1 | 0.849067 | game-dev | MEDIA | 0.971298 | game-dev | 0.830713 | 1 | 0.830713 |
fulpstation/fulpstation | 5,198 | code/modules/mining/lavaland/mining_loot/clothing.dm | // Memento Mori
/obj/item/clothing/neck/necklace/memento_mori
name = "Memento Mori"
desc = "A mysterious pendant. An inscription on it says: \"Certain death tomorrow means certain life today.\""
icon = 'icons/obj/mining_zones/artefacts.dmi'
icon_state = "memento_mori"
worn_icon_state = "memento"
actions_types = list(/datum/action/item_action/hands_free/memento_mori)
resistance_flags = INDESTRUCTIBLE | LAVA_PROOF | FIRE_PROOF | UNACIDABLE | ACID_PROOF
var/mob/living/carbon/human/active_owner
/obj/item/clothing/neck/necklace/memento_mori/item_action_slot_check(slot)
return (slot & ITEM_SLOT_NECK)
/obj/item/clothing/neck/necklace/memento_mori/dropped(mob/user)
. = ..()
if(active_owner)
mori()
// Just in case
/obj/item/clothing/neck/necklace/memento_mori/Destroy()
if(active_owner)
mori()
return ..()
/obj/item/clothing/neck/necklace/memento_mori/proc/memento(mob/living/carbon/human/user)
to_chat(user, span_warning("You feel your life being drained by the pendant..."))
if (!do_after(user, 4 SECONDS, target = user))
return
to_chat(user, span_notice("Your lifeforce is now linked to the pendant! You feel like removing it would kill you, and yet you instinctively know that until then, you won't die."))
user.add_traits(list(TRAIT_NODEATH, TRAIT_NOHARDCRIT, TRAIT_NOCRITDAMAGE), CLOTHING_TRAIT)
RegisterSignal(user, COMSIG_LIVING_HEALTH_UPDATE, PROC_REF(check_health))
icon_state = "memento_mori_active"
active_owner = user
/obj/item/clothing/neck/necklace/memento_mori/proc/mori()
icon_state = "memento_mori"
if (!active_owner)
return
UnregisterSignal(active_owner, COMSIG_LIVING_HEALTH_UPDATE)
var/mob/living/carbon/human/stored_owner = active_owner //to avoid infinite looping when dust unequips the pendant
active_owner = null
to_chat(stored_owner, span_userdanger("You feel your life rapidly slipping away from you!"))
stored_owner.dust(TRUE, TRUE)
/obj/item/clothing/neck/necklace/memento_mori/proc/check_health(mob/living/source)
SIGNAL_HANDLER
var/list/guardians = source.get_all_linked_holoparasites()
if (!length(guardians))
return
if (source.health <= HEALTH_THRESHOLD_DEAD)
for (var/mob/guardian in guardians)
if(guardian.loc == src)
continue
consume_guardian(guardian)
else if (source.health > HEALTH_THRESHOLD_CRIT)
for (var/mob/guardian in guardians)
if(guardian.loc != src)
continue
regurgitate_guardian(guardian)
/obj/item/clothing/neck/necklace/memento_mori/proc/consume_guardian(mob/living/basic/guardian/guardian)
new /obj/effect/temp_visual/guardian/phase/out(get_turf(guardian))
guardian.locked = TRUE
guardian.forceMove(src)
to_chat(guardian, span_userdanger("You have been locked away in your summoner's pendant!"))
guardian.playsound_local(get_turf(guardian), 'sound/effects/magic/summonitems_generic.ogg', 50, TRUE)
/obj/item/clothing/neck/necklace/memento_mori/proc/regurgitate_guardian(mob/living/basic/guardian/guardian)
guardian.locked = FALSE
guardian.recall(forced = TRUE)
to_chat(guardian, span_notice("You have been returned back from your summoner's pendant!"))
guardian.playsound_local(get_turf(guardian), 'sound/effects/magic/repulse.ogg', 50, TRUE)
/datum/action/item_action/hands_free/memento_mori
check_flags = NONE
name = "Memento Mori"
desc = "Bind your life to the pendant."
/datum/action/item_action/hands_free/memento_mori/do_effect(trigger_flags)
var/obj/item/clothing/neck/necklace/memento_mori/memento = target
if(memento.active_owner || !ishuman(owner))
return FALSE
memento.memento(owner)
Remove(memento.active_owner) //Remove the action button, since there's no real use in having it now.
return TRUE
// Concussive Gauntlets
/obj/item/clothing/gloves/gauntlets
name = "concussive gauntlets"
desc = "Pickaxes... for your hands!"
icon_state = "concussive_gauntlets"
inhand_icon_state = null
toolspeed = 0.1
strip_delay = 40
equip_delay_other = 20
cold_protection = HANDS
min_cold_protection_temperature = GLOVES_MIN_TEMP_PROTECT
heat_protection = HANDS
max_heat_protection_temperature = GLOVES_MAX_TEMP_PROTECT
body_parts_covered = HANDS|ARMS
resistance_flags = LAVA_PROOF | FIRE_PROOF //they are from lavaland after all
armor_type = /datum/armor/gloves_gauntlets
/datum/armor/gloves_gauntlets
melee = 15
bullet = 25
laser = 15
energy = 15
bomb = 100
fire = 100
acid = 30
/obj/item/clothing/gloves/gauntlets/equipped(mob/user, slot)
. = ..()
if(slot & ITEM_SLOT_GLOVES)
tool_behaviour = TOOL_MINING
RegisterSignal(user, COMSIG_LIVING_UNARMED_ATTACK, PROC_REF(rocksmash))
RegisterSignal(user, COMSIG_MOVABLE_BUMP, PROC_REF(rocksmash))
else
stopmining(user)
/obj/item/clothing/gloves/gauntlets/dropped(mob/user)
. = ..()
stopmining(user)
/obj/item/clothing/gloves/gauntlets/proc/stopmining(mob/user)
tool_behaviour = initial(tool_behaviour)
UnregisterSignal(user, list(COMSIG_LIVING_UNARMED_ATTACK, COMSIG_MOVABLE_BUMP))
/obj/item/clothing/gloves/gauntlets/proc/rocksmash(mob/living/carbon/human/user, atom/rocks, proximity)
SIGNAL_HANDLER
if(!proximity)
return NONE
if(!ismineralturf(rocks) && !isasteroidturf(rocks))
return NONE
rocks.attackby(src, user)
return COMPONENT_CANCEL_ATTACK_CHAIN
| 0 | 0.764532 | 1 | 0.764532 | game-dev | MEDIA | 0.980937 | game-dev | 0.700322 | 1 | 0.700322 |
CorvetteCole/blur-provider | 4,932 | src/tracking.js | const Meta = imports.gi.Meta;
const GLib = imports.gi.GLib;
const Shell = imports.gi.Shell;
const Clutter = imports.gi.Clutter;
const Extension = imports.misc.extensionUtils.getCurrentExtension();
const Blur = Extension.imports.blur;
var settings = null;
let _blurActorMap = new Map();
let _actorMap = new Map();
let _windowMap = new Map();
let _on_mutter_hint_changedMap = new Map();
let _on_window_unmanagedMap = new Map();
let _on_actor_destroyedMap = new Map();
let _on_actor_visibleMap = new Map();
let _uses_default_blur = new Set();
function get_window(pid) {
return _windowMap.get(pid);
}
function get_actor(pid) {
return _actorMap.get(pid);
}
function set_blur_actor(pid, blurActor) {
_blurActorMap.set(pid, blurActor);
}
function get_blur_actor(pid) {
return _blurActorMap.get(pid);
}
function has_window(pid) {
return _windowMap.has(pid);
}
function has_actor(pid) {
return _actorMap.has(pid);
}
function has_blur_actor(pid) {
return _blurActorMap.has(pid);
}
function set_uses_default_blur(pid) {
_uses_default_blur.add(pid);
}
function remove_uses_default_blur(pid) {
if (_uses_default_blur.has(pid)) {
_uses_default_blur.delete(pid);
}
}
function track_new(actor, window) {
let pid = new Date().valueOf();
if (!_actorMap.has(pid)) {
actor['blur_provider_pid'] = pid;
window['blur_provider_pid'] = pid;
_actorMap.set(pid, actor);
_windowMap.set(pid, window);
_on_actor_destroyedMap.set(pid, actor.connect('destroy', _actor_destroyed));
_on_mutter_hint_changedMap.set(pid, window.connect('notify::mutter-hints', _mutter_hint_changed));
_on_window_unmanagedMap.set(pid, window.connect('unmanaged', _window_unmanaged));
}
Blur.update_blur(window, pid);
}
function connect_actor_visible(pid) {
if (!_on_actor_visibleMap.has(pid)) {
_on_actor_visibleMap.set(pid, _actorMap.get(pid).connect('notify::visible', _actor_visibility_changed))
}
}
function remove_blur_tracking(pid) {
_blurActorMap.delete(pid);
_actorMap.get(pid).disconnect(_on_actor_visibleMap.get(pid));
_on_actor_visibleMap.delete(pid);
}
function cleanup_windows() {
_windowMap.forEach(((value, key) => {
_cleanup_window(key);
}));
}
function cleanup_actors() {
_actorMap.forEach(((value, key) => {
_cleanup_actor(key);
}));
}
function print_map_info() {
log("map sizes, _actorMap: " + _actorMap.size + " _blurActorMap: " + _blurActorMap.size + " _windowMap: " + _windowMap.size + "_on_mutter_hint_changedMap: " + _on_mutter_hint_changedMap.size + "_on_window_unmanagedMap: " + _on_window_unmanagedMap.size + " _on_actor_destroyedMap: " + _on_actor_destroyedMap.size + " _on_actor_visibleMap: " + _on_actor_visibleMap.size);
}
function focus_changed() {
//log("focus_changed");
if (_blurActorMap.size > 0) {
let callbackId = Meta.later_add(Meta.LaterType.BEFORE_REDRAW, _fix_blur);
//log("callback id: " + callbackId);
}
}
function blur_setting_changed() {
_uses_default_blur.forEach((value => {
if (_blurActorMap.has(value)){
Blur.update_blur(_windowMap.get(value), value);
}
}));
}
function _cleanup_window(pid) {
//log("cleanup_window");
_windowMap.get(pid).disconnect(_on_mutter_hint_changedMap.get(pid));
_windowMap.get(pid).disconnect(_on_window_unmanagedMap.get(pid));
_on_mutter_hint_changedMap.delete(pid);
_windowMap.delete(pid);
}
function _cleanup_actor(pid) {
//log("cleanup_actor, disconnecting listeners");
if (_blurActorMap.has(pid)) {
Blur.remove_blur(pid);
}
_actorMap.get(pid).disconnect(_on_actor_destroyedMap.get(pid));
if (_on_actor_visibleMap.has(pid)) {
_actorMap.get(pid).disconnect(_on_actor_visibleMap.get(pid));
_on_actor_visibleMap.delete(pid);
}
_on_actor_destroyedMap.delete(pid);
_actorMap.delete(pid);
}
function _actor_visibility_changed(window_actor) {
//log("visibility change");
let pid = window_actor.blur_provider_pid;
if (window_actor.visible) {
//log("actor visible");
_blurActorMap.get(pid).show();
} else {
//log("actor not visible");
_blurActorMap.get(pid).hide();
}
}
function _fix_blur() {
_blurActorMap.forEach((blurActor, pid) => {
//log("fix_blur")
let actor = _actorMap.get(pid);
Blur.set_blur_behind(blurActor, actor);
});
}
function _mutter_hint_changed(meta_window) {
log("mutter_hint_changed")
Blur.update_blur(meta_window, meta_window.blur_provider_pid);
}
function _window_unmanaged(meta_window) {
//log("window_unmanaged");
let pid = meta_window.blur_provider_pid;
_cleanup_window(pid);
}
function _actor_destroyed(window_actor) {
//log("actor_destroyed");
let pid = window_actor.blur_provider_pid;
_cleanup_actor(pid);
}
| 0 | 0.752837 | 1 | 0.752837 | game-dev | MEDIA | 0.6745 | game-dev,desktop-app | 0.928612 | 1 | 0.928612 |
everbuild-org/blocks-and-stuff | 2,005 | blocksandstuff-blocks/src/main/kotlin/org/everbuild/blocksandstuff/blocks/placement/FencePlacementRule.kt | package org.everbuild.blocksandstuff.blocks.placement
import org.everbuild.blocksandstuff.blocks.placement.util.States.getAxis
import org.everbuild.blocksandstuff.blocks.placement.util.States.getFacing
import org.everbuild.blocksandstuff.blocks.placement.util.States.rotateYClockwise
import net.minestom.server.coordinate.Point
import net.minestom.server.instance.block.Block
import net.minestom.server.instance.block.BlockFace
import net.kyori.adventure.key.Key
import org.everbuild.blocksandstuff.blocks.placement.common.AbstractConnectingBlockPlacementRule
class FencePlacementRule(block: Block) : AbstractConnectingBlockPlacementRule(block) {
private val fences = tagManager.getTag(Key.key("minecraft:fences"))!!
private val woodenFences = tagManager.getTag(Key.key("minecraft:wooden_fences"))!!
private val fenceGates = tagManager.getTag(Key.key("minecraft:fence_gates"))!!
override fun canConnect(instance: Block.Getter, pos: Point, blockFace: BlockFace): Boolean {
val instanceBlock = instance.getBlock(pos)
val isBlockNetherBrickFence: Boolean = block.name().endsWith("_brick_fence")
val isInstanceBlockNetherBrickFence = instanceBlock.name().endsWith("_brick_fence")
val canConnectToFence = canConnectToFence(instanceBlock)
val canFenceGateConnect =
fenceGates.contains(instanceBlock) && getAxis(getFacing(instanceBlock).toDirection()) == getAxis(
rotateYClockwise(blockFace.toDirection())
)
val isFaceFull = instanceBlock.registry()!!.collisionShape().isFaceFull(blockFace)
return !cannotConnect.contains(block) && isFaceFull || (canConnectToFence && !isBlockNetherBrickFence) || canFenceGateConnect || (isBlockNetherBrickFence && isInstanceBlockNetherBrickFence)
}
private fun canConnectToFence(block: Block): Boolean {
val isFence = fences.contains(block)
val isWoodenFence = woodenFences.contains(block)
return isFence && isWoodenFence
}
} | 0 | 0.860677 | 1 | 0.860677 | game-dev | MEDIA | 0.968293 | game-dev | 0.954996 | 1 | 0.954996 |
beyond-aion/aion-server | 2,878 | game-server/data/handlers/admincommands/CustomInstance.java | package admincommands;
import com.aionemu.gameserver.custom.instance.CustomInstanceRankEnum;
import com.aionemu.gameserver.custom.instance.CustomInstanceService;
import com.aionemu.gameserver.model.gameobjects.VisibleObject;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.utils.PacketSendUtility;
import com.aionemu.gameserver.utils.chathandlers.AdminCommand;
/**
* @author Estrayl
*/
public class CustomInstance extends AdminCommand {
public CustomInstance() {
super("cinstance", "Utility command for the custom instance.");
// @formatter:off
setSyntaxInfo(
"<removecd> - Removes the custom instance cooldown of selected player.",
"<getrank> - Gets the current custom instance rank of selected player.",
"<setrank> [newRank] - Changes the custom instance rank of selected player to given value."
);
// @formatter:on
}
@Override
protected void execute(Player player, String... params) {
if (params.length < 1) {
sendInfo(player);
return;
}
switch (params[0].toLowerCase()) {
case "removecd":
if (player.getTarget() instanceof Player targetPlayer) {
if (CustomInstanceService.getInstance().resetEntryCooldown(targetPlayer.getObjectId())) {
PacketSendUtility.sendMessage(player, "Successfully removed custom instance cooldown for " + targetPlayer.getName() + ".");
} else {
PacketSendUtility.sendMessage(player, "Player " + targetPlayer.getName() + " does not need a reset.");
}
} else {
PacketSendUtility.sendMessage(player, "Please select a player first.");
}
break;
case "getrank":
if (player.getTarget() instanceof Player targetPlayer) {
int rank = CustomInstanceService.getInstance().loadOrCreateRank(targetPlayer.getObjectId()).getRank();
PacketSendUtility.sendMessage(player,
targetPlayer.getName() + "'s current rank is " + CustomInstanceRankEnum.getRankDescription(rank) + "(" + rank + ").");
} else {
PacketSendUtility.sendMessage(player, "Please select a player first.");
}
break;
case "setrank":
if (params.length < 2) {
sendInfo(player);
return;
}
setNewRank(player, params[1]);
break;
}
}
private void setNewRank(Player player, String newRank) {
int rank;
try {
rank = Integer.parseInt(newRank);
} catch (NumberFormatException e) {
sendInfo(player, "The new rank have to be a number.");
return;
}
VisibleObject target = player.getTarget();
if (player.getTarget() instanceof Player targetPlayer) {
CustomInstanceService.getInstance().changePlayerRank(targetPlayer.getObjectId(), rank, 0);
PacketSendUtility.sendMessage(player,
"Changed " + target.getName() + " to " + rank + " which is equivalent to " + CustomInstanceRankEnum.getRankDescription(rank));
} else {
sendInfo(player, "Select a player first.");
}
}
}
| 0 | 0.922927 | 1 | 0.922927 | game-dev | MEDIA | 0.797279 | game-dev,web-backend | 0.89592 | 1 | 0.89592 |
Unity-Technologies/GenericFrameRecorder | 1,346 | source/FrameRecorder/Inputs/ScreenCapture/Editor/ScreenCaptureInputEditor.cs | #if UNITY_2017_3_OR_NEWER
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Recorder;
using UnityEngine.Recorder.Input;
namespace UnityEditor.Recorder.Input
{
[CustomEditor(typeof(ScreenCaptureInputSettings))]
public class ScreenCaptureInputEditor : InputEditor
{
SerializedProperty m_RenderSize;
SerializedProperty m_RenderAspect;
ResolutionSelector m_ResSelector;
protected void OnEnable()
{
if (target == null)
return;
var pf = new PropertyFinder<ScreenCaptureInputSettings>(serializedObject);
m_RenderSize = pf.Find(w => w.m_OutputSize);
m_RenderAspect = pf.Find(w => w.m_AspectRatio);
m_ResSelector = new ResolutionSelector();
}
public override void OnInspectorGUI()
{
AddProperty(m_RenderSize, () =>
{
m_ResSelector.OnInspectorGUI((target as ImageInputSettings).maxSupportedSize, m_RenderSize);
});
if (m_RenderSize.intValue > (int)EImageDimension.Window)
{
AddProperty(m_RenderAspect, () => EditorGUILayout.PropertyField(m_RenderAspect, new GUIContent("Aspect Ratio")));
}
serializedObject.ApplyModifiedProperties();
}
}
}
#endif | 0 | 0.856015 | 1 | 0.856015 | game-dev | MEDIA | 0.841298 | game-dev | 0.966534 | 1 | 0.966534 |
Arkania/ArkCORE-NG | 22,183 | src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_archimonde.cpp | /*
* Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2011-2016 ArkCORE <http://www.arkania.net/>
* Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
*
* 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/>.
*/
/* ScriptData
SDName: Boss_Archimonde
SD%Complete: 85
SDComment: Doomfires not completely offlike due to core limitations for random moving. Tyrande and second phase not fully implemented.
SDCategory: Caverns of Time, Mount Hyjal
EndScriptData */
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "hyjal.h"
#include "SpellAuras.h"
#include "hyjal_trash.h"
#include "Player.h"
enum Texts
{
SAY_AGGRO = 1,
SAY_DOOMFIRE = 2,
SAY_AIR_BURST = 3,
SAY_SLAY = 4,
SAY_ENRAGE = 5,
SAY_DEATH = 6,
SAY_SOUL_CHARGE = 7,
};
enum Spells
{
SPELL_DENOUEMENT_WISP = 32124,
SPELL_ANCIENT_SPARK = 39349,
SPELL_PROTECTION_OF_ELUNE = 38528,
SPELL_DRAIN_WORLD_TREE = 39140,
SPELL_DRAIN_WORLD_TREE_TRIGGERED = 39141,
SPELL_FINGER_OF_DEATH = 31984,
SPELL_HAND_OF_DEATH = 35354,
SPELL_AIR_BURST = 32014,
SPELL_GRIP_OF_THE_LEGION = 31972,
SPELL_DOOMFIRE_STRIKE = 31903, //summons two creatures
SPELL_DOOMFIRE_SPAWN = 32074,
SPELL_DOOMFIRE = 31945,
SPELL_SOUL_CHARGE_YELLOW = 32045,
SPELL_SOUL_CHARGE_GREEN = 32051,
SPELL_SOUL_CHARGE_RED = 32052,
SPELL_UNLEASH_SOUL_YELLOW = 32054,
SPELL_UNLEASH_SOUL_GREEN = 32057,
SPELL_UNLEASH_SOUL_RED = 32053,
SPELL_FEAR = 31970,
};
enum Summons
{
CREATURE_DOOMFIRE = 18095,
CREATURE_DOOMFIRE_SPIRIT = 18104,
CREATURE_ANCIENT_WISP = 17946,
CREATURE_CHANNEL_TARGET = 22418,
};
Position const NordrassilLoc = {5503.713f, -3523.436f, 1608.781f, 0.0f};
class npc_ancient_wisp : public CreatureScript
{
public:
npc_ancient_wisp() : CreatureScript("npc_ancient_wisp") { }
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<npc_ancient_wispAI>(creature);
}
struct npc_ancient_wispAI : public ScriptedAI
{
npc_ancient_wispAI(Creature* creature) : ScriptedAI(creature)
{
instance = creature->GetInstanceScript();
ArchimondeGUID = 0;
}
InstanceScript* instance;
uint64 ArchimondeGUID;
uint32 CheckTimer;
void Reset() override
{
CheckTimer = 1000;
ArchimondeGUID = instance->GetData64(DATA_ARCHIMONDE);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
}
void EnterCombat(Unit* /*who*/) override { }
void DamageTaken(Unit* /*done_by*/, uint32 &damage) override
{
damage = 0;
}
void UpdateAI(uint32 diff) override
{
if (CheckTimer <= diff)
{
if (Unit* Archimonde = ObjectAccessor::GetUnit(*me, ArchimondeGUID))
{
if (Archimonde->HealthBelowPct(2) || !Archimonde->IsAlive())
DoCast(me, SPELL_DENOUEMENT_WISP);
else
DoCast(Archimonde, SPELL_ANCIENT_SPARK);
}
CheckTimer = 1000;
} else CheckTimer -= diff;
}
};
};
/* This script is merely a placeholder for the Doomfire that triggers Doomfire spell. It will
MoveChase the Doomfire Spirit always, until despawn (AttackStart is called upon it's spawn) */
class npc_doomfire : public CreatureScript
{
public:
npc_doomfire() : CreatureScript("npc_doomfire") { }
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_doomfireAI(creature);
}
struct npc_doomfireAI : public ScriptedAI
{
npc_doomfireAI(Creature* creature) : ScriptedAI(creature) { }
void Reset() override { }
void MoveInLineOfSight(Unit* /*who*/) override { }
void EnterCombat(Unit* /*who*/) override { }
void DamageTaken(Unit* /*done_by*/, uint32 &damage) override
{
damage = 0;
}
};
};
/* This is the script for the Doomfire Spirit Mob. This mob simply follow players or
travels in random directions if target cannot be found. */
class npc_doomfire_targetting : public CreatureScript
{
public:
npc_doomfire_targetting() : CreatureScript("npc_doomfire_targetting") { }
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_doomfire_targettingAI(creature);
}
struct npc_doomfire_targettingAI : public ScriptedAI
{
npc_doomfire_targettingAI(Creature* creature) : ScriptedAI(creature) { }
uint64 TargetGUID;
uint32 ChangeTargetTimer;
void Reset() override
{
TargetGUID = 0;
ChangeTargetTimer = 5000;
}
void MoveInLineOfSight(Unit* who) override
{
//will update once TargetGUID is 0. In case noone actually moves(not likely) and this is 0
//when UpdateAI needs it, it will be forced to select randomPoint
if (!TargetGUID && who->GetTypeId() == TYPEID_PLAYER)
TargetGUID = who->GetGUID();
}
void EnterCombat(Unit* /*who*/) override { }
void DamageTaken(Unit* /*done_by*/, uint32 &damage) override
{
damage = 0;
}
void UpdateAI(uint32 diff) override
{
if (ChangeTargetTimer <= diff)
{
if (Unit* temp = ObjectAccessor::GetUnit(*me, TargetGUID))
{
me->GetMotionMaster()->MoveFollow(temp, 0.0f, 0.0f);
TargetGUID = 0;
}
else
{
Position pos = me->GetRandomNearPosition(40);
me->GetMotionMaster()->MovePoint(0, pos.m_positionX, pos.m_positionY, pos.m_positionZ);
}
ChangeTargetTimer = 5000;
} else ChangeTargetTimer -= diff;
}
};
};
/* Finally, Archimonde's script. His script isn't extremely complex, most are simply spells on timers.
The only complicated aspect of the battle is Finger of Death and Doomfire, with Doomfire being the
hardest bit to code. Finger of Death is simply a distance check - if no one is in melee range, then
select a random target and cast the spell on them. However, if someone IS in melee range, and this
is NOT the main tank (creature's victim), then we aggro that player and they become the new victim.
For Doomfire, we summon a mob (Doomfire Spirit) for the Doomfire mob to follow. It's spirit will
randomly select it's target to follow and then we create the random movement making it unpredictable. */
class boss_archimonde : public CreatureScript
{
public:
boss_archimonde() : CreatureScript("boss_archimonde") { }
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<boss_archimondeAI>(creature);
}
struct boss_archimondeAI : public hyjal_trashAI
{
boss_archimondeAI(Creature* creature) : hyjal_trashAI(creature)
{
instance = creature->GetInstanceScript();
}
InstanceScript* instance;
uint64 DoomfireSpiritGUID;
uint64 WorldTreeGUID;
uint32 DrainNordrassilTimer;
uint32 FearTimer;
uint32 AirBurstTimer;
uint32 GripOfTheLegionTimer;
uint32 DoomfireTimer;
uint32 SoulChargeTimer;
uint8 SoulChargeCount;
uint32 MeleeRangeCheckTimer;
uint32 HandOfDeathTimer;
uint32 SummonWispTimer;
uint8 WispCount;
uint32 EnrageTimer;
uint32 CheckDistanceTimer;
bool Enraged;
bool BelowTenPercent;
bool HasProtected;
bool IsChanneling;
void Reset() override
{
instance->SetData(DATA_ARCHIMONDEEVENT, NOT_STARTED);
DoomfireSpiritGUID = 0;
damageTaken = 0;
WorldTreeGUID = 0;
DrainNordrassilTimer = 0;
FearTimer = 42000;
AirBurstTimer = 30000;
GripOfTheLegionTimer = urand(5000, 25000);
DoomfireTimer = 20000;
SoulChargeTimer = urand(2000, 30000);
SoulChargeCount = 0;
MeleeRangeCheckTimer = 15000;
HandOfDeathTimer = 2000;
WispCount = 0; // When ~30 wisps are summoned, Archimonde dies
EnrageTimer = 600000; // 10 minutes
CheckDistanceTimer = 30000; // This checks if he's too close to the World Tree (75 yards from a point on the tree), if true then he will enrage
SummonWispTimer = 0;
Enraged = false;
BelowTenPercent = false;
HasProtected = false;
IsChanneling = false;
}
void EnterCombat(Unit* /*who*/) override
{
me->InterruptSpell(CURRENT_CHANNELED_SPELL);
Talk(SAY_AGGRO);
DoZoneInCombat();
instance->SetData(DATA_ARCHIMONDEEVENT, IN_PROGRESS);
}
void KilledUnit(Unit* victim) override
{
Talk(SAY_SLAY);
if (victim && victim->GetTypeId() == TYPEID_PLAYER)
GainSoulCharge(victim->ToPlayer());
}
void GainSoulCharge(Player* victim)
{
switch (victim->getClass())
{
case CLASS_PRIEST:
case CLASS_PALADIN:
case CLASS_WARLOCK:
victim->CastSpell(me, SPELL_SOUL_CHARGE_RED, true);
break;
case CLASS_MAGE:
case CLASS_ROGUE:
case CLASS_WARRIOR:
victim->CastSpell(me, SPELL_SOUL_CHARGE_YELLOW, true);
break;
case CLASS_DRUID:
case CLASS_SHAMAN:
case CLASS_HUNTER:
victim->CastSpell(me, SPELL_SOUL_CHARGE_GREEN, true);
break;
}
SoulChargeTimer = urand(2000, 30000);
++SoulChargeCount;
}
void JustDied(Unit* killer) override
{
hyjal_trashAI::JustDied(killer);
Talk(SAY_DEATH);
instance->SetData(DATA_ARCHIMONDEEVENT, DONE);
}
bool CanUseFingerOfDeath()
{
// First we check if our current victim is in melee range or not.
Unit* victim = me->GetVictim();
if (victim && me->IsWithinDistInMap(victim, me->GetAttackDistance(victim)))
return false;
ThreatContainer::StorageType const &threatlist = me->getThreatManager().getThreatList();
if (threatlist.empty())
return false;
std::list<Unit*> targets;
ThreatContainer::StorageType::const_iterator itr = threatlist.begin();
for (; itr != threatlist.end(); ++itr)
{
Unit* unit = ObjectAccessor::GetUnit(*me, (*itr)->getUnitGuid());
if (unit && unit->IsAlive())
targets.push_back(unit);
}
if (targets.empty())
return false;
targets.sort(Trinity::ObjectDistanceOrderPred(me));
Unit* target = targets.front();
if (target)
{
if (!me->IsWithinDistInMap(target, me->GetAttackDistance(target)))
return true; // Cast Finger of Death
else // This target is closest, he is our new tank
me->AddThreat(target, me->getThreatManager().getThreat(me->GetVictim()));
}
return false;
}
void JustSummoned(Creature* summoned) override
{
if (summoned->GetEntry() == CREATURE_ANCIENT_WISP)
summoned->AI()->AttackStart(me);
else
{
summoned->setFaction(me->getFaction());
summoned->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
summoned->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
}
if (summoned->GetEntry() == CREATURE_DOOMFIRE_SPIRIT)
{
DoomfireSpiritGUID = summoned->GetGUID();
}
if (summoned->GetEntry() == CREATURE_DOOMFIRE)
{
summoned->CastSpell(summoned, SPELL_DOOMFIRE_SPAWN, false);
summoned->CastSpell(summoned, SPELL_DOOMFIRE, true, 0, 0, me->GetGUID());
if (Unit* DoomfireSpirit = ObjectAccessor::GetUnit(*me, DoomfireSpiritGUID))
{
summoned->GetMotionMaster()->MoveFollow(DoomfireSpirit, 0.0f, 0.0f);
DoomfireSpiritGUID = 0;
}
}
}
//this is code doing close to what the summoning spell would do (spell 31903)
void SummonDoomfire(Unit* target)
{
me->SummonCreature(CREATURE_DOOMFIRE_SPIRIT,
target->GetPositionX()+15.0f, target->GetPositionY()+15.0f, target->GetPositionZ(), 0,
TEMPSUMMON_TIMED_DESPAWN, 27000);
me->SummonCreature(CREATURE_DOOMFIRE,
target->GetPositionX()-15.0f, target->GetPositionY()-15.0f, target->GetPositionZ(), 0,
TEMPSUMMON_TIMED_DESPAWN, 27000);
}
void UnleashSoulCharge()
{
me->InterruptNonMeleeSpells(false);
bool HasCast = false;
uint32 chargeSpell = 0;
uint32 unleashSpell = 0;
switch (urand(0, 2))
{
case 0:
chargeSpell = SPELL_SOUL_CHARGE_RED;
unleashSpell = SPELL_UNLEASH_SOUL_RED;
break;
case 1:
chargeSpell = SPELL_SOUL_CHARGE_YELLOW;
unleashSpell = SPELL_UNLEASH_SOUL_YELLOW;
break;
case 2:
chargeSpell = SPELL_SOUL_CHARGE_GREEN;
unleashSpell = SPELL_UNLEASH_SOUL_GREEN;
break;
}
if (me->HasAura(chargeSpell))
{
me->RemoveAuraFromStack(chargeSpell);
DoCastVictim(unleashSpell);
HasCast = true;
SoulChargeCount--;
}
if (HasCast)
SoulChargeTimer = urand(2000, 30000);
}
void UpdateAI(uint32 diff) override
{
if (!me->IsInCombat())
{
// Do not let the raid skip straight to Archimonde. Visible and hostile ONLY if Azagalor is finished.
if ((instance->GetData(DATA_AZGALOREVENT) < DONE) && (me->IsVisible() || (me->getFaction() != 35)))
{
me->SetVisible(false);
me->setFaction(35);
}
else if ((instance->GetData(DATA_AZGALOREVENT) >= DONE) && (!me->IsVisible() || (me->getFaction() == 35)))
{
me->setFaction(1720);
me->SetVisible(true);
}
if (DrainNordrassilTimer <= diff)
{
if (!IsChanneling)
{
Creature* temp = me->SummonCreature(CREATURE_CHANNEL_TARGET, NordrassilLoc, TEMPSUMMON_TIMED_DESPAWN, 1200000);
if (temp)
WorldTreeGUID = temp->GetGUID();
if (Unit* Nordrassil = ObjectAccessor::GetUnit(*me, WorldTreeGUID))
{
Nordrassil->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
Nordrassil->SetDisplayId(11686);
DoCast(Nordrassil, SPELL_DRAIN_WORLD_TREE);
IsChanneling = true;
}
}
if (Unit* Nordrassil = ObjectAccessor::GetUnit(*me, WorldTreeGUID))
{
Nordrassil->CastSpell(me, SPELL_DRAIN_WORLD_TREE_TRIGGERED, true);
DrainNordrassilTimer = 1000;
}
} else DrainNordrassilTimer -= diff;
}
if (!UpdateVictim())
return;
if (me->HealthBelowPct(10) && !BelowTenPercent && !Enraged)
BelowTenPercent = true;
if (!Enraged)
{
if (EnrageTimer <= diff)
{
if (HealthAbovePct(10))
{
me->GetMotionMaster()->Clear(false);
me->GetMotionMaster()->MoveIdle();
Enraged = true;
Talk(SAY_ENRAGE);
}
} else EnrageTimer -= diff;
if (CheckDistanceTimer <= diff)
{
// To simplify the check, we simply summon a Creature in the location and then check how far we are from the creature
Creature* Check = me->SummonCreature(CREATURE_CHANNEL_TARGET, NordrassilLoc, TEMPSUMMON_TIMED_DESPAWN, 2000);
if (Check)
{
Check->SetVisible(false);
if (me->IsWithinDistInMap(Check, 75))
{
me->GetMotionMaster()->Clear(false);
me->GetMotionMaster()->MoveIdle();
Enraged = true;
Talk(SAY_ENRAGE);
}
}
CheckDistanceTimer = 5000;
} else CheckDistanceTimer -= diff;
}
if (BelowTenPercent)
{
if (!HasProtected)
{
me->GetMotionMaster()->Clear(false);
me->GetMotionMaster()->MoveIdle();
//all members of raid must get this buff
DoCastVictim(SPELL_PROTECTION_OF_ELUNE, true);
HasProtected = true;
Enraged = true;
}
if (SummonWispTimer <= diff)
{
DoSpawnCreature(CREATURE_ANCIENT_WISP, float(rand()%40), float(rand()%40), 0, 0, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 15000);
SummonWispTimer = 1500;
++WispCount;
} else SummonWispTimer -= diff;
if (WispCount >= 30)
me->DealDamage(me, me->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
}
if (Enraged)
{
if (HandOfDeathTimer <= diff)
{
DoCastVictim(SPELL_HAND_OF_DEATH);
HandOfDeathTimer = 2000;
} else HandOfDeathTimer -= diff;
return; // Don't do anything after this point.
}
if (SoulChargeCount)
{
if (SoulChargeTimer <= diff)
UnleashSoulCharge();
else SoulChargeTimer -= diff;
}
if (GripOfTheLegionTimer <= diff)
{
DoCast(SelectTarget(SELECT_TARGET_RANDOM, 0), SPELL_GRIP_OF_THE_LEGION);
GripOfTheLegionTimer = urand(5000, 25000);
} else GripOfTheLegionTimer -= diff;
if (AirBurstTimer <= diff)
{
Talk(SAY_AIR_BURST);
DoCast(SelectTarget(SELECT_TARGET_RANDOM, 1), SPELL_AIR_BURST);//not on tank
AirBurstTimer = urand(25000, 40000);
} else AirBurstTimer -= diff;
if (FearTimer <= diff)
{
DoCastVictim(SPELL_FEAR);
FearTimer = 42000;
} else FearTimer -= diff;
if (DoomfireTimer <= diff)
{
Talk(SAY_DOOMFIRE);
Unit* temp = SelectTarget(SELECT_TARGET_RANDOM, 1);
if (!temp)
temp = me->GetVictim();
//replace with spell cast 31903 once implicitTarget 73 implemented
SummonDoomfire(temp);
//supposedly three doomfire can be up at the same time
DoomfireTimer = 20000;
} else DoomfireTimer -= diff;
if (MeleeRangeCheckTimer <= diff)
{
if (CanUseFingerOfDeath())
{
DoCast(SelectTarget(SELECT_TARGET_RANDOM, 0), SPELL_FINGER_OF_DEATH);
MeleeRangeCheckTimer = 1000;
}
MeleeRangeCheckTimer = 5000;
} else MeleeRangeCheckTimer -= diff;
DoMeleeAttackIfReady();
}
void WaypointReached(uint32 /*waypointId*/) override { }
};
};
void AddSC_boss_archimonde()
{
new boss_archimonde();
new npc_doomfire();
new npc_doomfire_targetting();
new npc_ancient_wisp();
}
| 0 | 0.986329 | 1 | 0.986329 | game-dev | MEDIA | 0.993463 | game-dev | 0.904678 | 1 | 0.904678 |
EsreverWoW/ShestakUI_Classic | 2,204 | ShestakUI/Modules/Trade/Merchant.lua | local T, C, L = unpack(ShestakUI)
----------------------------------------------------------------------------------------
-- Alt+Click to buy a stack
----------------------------------------------------------------------------------------
hooksecurefunc("MerchantItemButton_OnModifiedClick", function(self)
if IsAltKeyDown() then
local id = self:GetID()
local itemLink = GetMerchantItemLink(id)
if not itemLink then return end
local maxStack = select(8, GetItemInfo(itemLink))
if maxStack and maxStack > 1 then
local numAvailable = select(5, GetMerchantItemInfo(id))
if numAvailable > -1 then
BuyMerchantItem(id, numAvailable)
else
BuyMerchantItem(id, GetMerchantItemMaxStack(id))
end
end
end
end)
ITEM_VENDOR_STACK_BUY = _G.ITEM_VENDOR_STACK_BUY.."\n|cff00ff00<"..L_MISC_BUY_STACK..">|r"
----------------------------------------------------------------------------------------
-- Show item level for weapons and armor in merchant
----------------------------------------------------------------------------------------
if C.trade.merchant_itemlevel ~= true then return end
local function MerchantItemlevel()
local numItems = GetMerchantNumItems()
for i = 1, MERCHANT_ITEMS_PER_PAGE do
local index = (MerchantFrame.page - 1) * MERCHANT_ITEMS_PER_PAGE + i
if index > numItems then return end
local button = _G["MerchantItem"..i.."ItemButton"]
if button and button:IsShown() then
if not button.text then
button.text = button:CreateFontString(nil, "OVERLAY", "SystemFont_Outline_Small")
if T.Classic then
button.text:SetPoint("BOTTOMRIGHT", 0, 0)
else
button.text:SetPoint("TOPLEFT", 1, -1)
end
button.text:SetTextColor(1, 1, 0)
else
button.text:SetText("")
end
local itemLink = GetMerchantItemLink(index)
if itemLink then
local _, _, quality, itemlevel, _, _, _, _, _, _, _, itemClassID = GetItemInfo(itemLink)
if (itemlevel and itemlevel > 1) and (quality and quality > 1) and (itemClassID == Enum.ItemClass.Weapon or itemClassID == Enum.ItemClass.Armor) then
button.text:SetText(itemlevel)
end
end
end
end
end
hooksecurefunc("MerchantFrame_UpdateMerchantInfo", MerchantItemlevel)
| 0 | 0.762798 | 1 | 0.762798 | game-dev | MEDIA | 0.720006 | game-dev | 0.919333 | 1 | 0.919333 |
fholger/openvr_fsr | 4,337 | samples/unity_keyboard_sample/Assets/SteamVR/Editor/SteamVR_Update.cs | //========= Copyright 2015, Valve Corporation, All rights reserved. ===========
//
// Purpose: Notify developers when a new version of the plugin is available.
//
//=============================================================================
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Text.RegularExpressions;
[InitializeOnLoad]
public class SteamVR_Update : EditorWindow
{
const string currentVersion = "1.0.8";
const string versionUrl = "http://media.steampowered.com/apps/steamvr/unitypluginversion.txt";
const string notesUrl = "http://media.steampowered.com/apps/steamvr/unityplugin-v{0}.txt";
const string pluginUrl = "http://u3d.as/content/valve-corporation/steam-vr-plugin";
const string doNotShowKey = "SteamVR.DoNotShow.v{0}";
static WWW wwwVersion, wwwNotes;
static string version, notes;
static SteamVR_Update window;
static SteamVR_Update()
{
wwwVersion = new WWW(versionUrl);
EditorApplication.update += Update;
}
static void Update()
{
if (wwwVersion != null)
{
if (!wwwVersion.isDone)
return;
if (UrlSuccess(wwwVersion))
version = wwwVersion.text;
wwwVersion = null;
if (ShouldDisplay())
{
var url = string.Format(notesUrl, version);
wwwNotes = new WWW(url);
window = GetWindow<SteamVR_Update>(true);
window.minSize = new Vector2(320, 440);
//window.title = "SteamVR";
}
}
if (wwwNotes != null)
{
if (!wwwNotes.isDone)
return;
if (UrlSuccess(wwwNotes))
notes = wwwNotes.text;
wwwNotes = null;
if (notes != "")
window.Repaint();
}
EditorApplication.update -= Update;
}
static bool UrlSuccess(WWW www)
{
if (!string.IsNullOrEmpty(www.error))
return false;
if (Regex.IsMatch(www.text, "404 not found", RegexOptions.IgnoreCase))
return false;
return true;
}
static bool ShouldDisplay()
{
if (string.IsNullOrEmpty(version))
return false;
if (version == currentVersion)
return false;
if (EditorPrefs.HasKey(string.Format(doNotShowKey, version)))
return false;
// parse to see if newer (e.g. 1.0.4 vs 1.0.3)
var versionSplit = version.Split('.');
var currentVersionSplit = currentVersion.Split('.');
for (int i = 0; i < versionSplit.Length && i < currentVersionSplit.Length; i++)
{
int versionValue, currentVersionValue;
if (int.TryParse(versionSplit[i], out versionValue) &&
int.TryParse(currentVersionSplit[i], out currentVersionValue))
{
if (versionValue > currentVersionValue)
return true;
if (versionValue < currentVersionValue)
return false;
}
}
// same up to this point, now differentiate based on number of sub values (e.g. 1.0.4.1 vs 1.0.4)
if (versionSplit.Length <= currentVersionSplit.Length)
return false;
return true;
}
Vector2 scrollPosition;
bool toggleState;
string GetResourcePath()
{
var ms = MonoScript.FromScriptableObject(this);
var path = AssetDatabase.GetAssetPath(ms);
path = Path.GetDirectoryName(path);
return path.Substring(0, path.Length - "Editor".Length) + "Textures/";
}
public void OnGUI()
{
EditorGUILayout.HelpBox("A new version of the SteamVR plugin is available!", MessageType.Warning);
var resourcePath = GetResourcePath();
#if UNITY_5_0
var logo = Resources.LoadAssetAtPath<Texture2D>(resourcePath + "logo.png");
#else
var logo = AssetDatabase.LoadAssetAtPath<Texture2D>(resourcePath + "logo.png");
#endif
var rect = GUILayoutUtility.GetRect(position.width, 150, GUI.skin.box);
if (logo)
GUI.DrawTexture(rect, logo, ScaleMode.ScaleToFit);
scrollPosition = GUILayout.BeginScrollView(scrollPosition);
GUILayout.Label("Current version: " + currentVersion);
GUILayout.Label("New version: " + version);
if (notes != "")
{
GUILayout.Label("Release notes:");
EditorGUILayout.HelpBox(notes, MessageType.Info);
}
GUILayout.EndScrollView();
GUILayout.FlexibleSpace();
if (GUILayout.Button("Get Latest Version"))
{
Application.OpenURL(pluginUrl);
}
EditorGUI.BeginChangeCheck();
var doNotShow = GUILayout.Toggle(toggleState, "Do not prompt for this version again.");
if (EditorGUI.EndChangeCheck())
{
toggleState = doNotShow;
var key = string.Format(doNotShowKey, version);
if (doNotShow)
EditorPrefs.SetBool(key, true);
else
EditorPrefs.DeleteKey(key);
}
}
}
| 0 | 0.889823 | 1 | 0.889823 | game-dev | MEDIA | 0.514985 | game-dev,desktop-app | 0.978997 | 1 | 0.978997 |
KgDW/NullPoint-Fabric | 5,042 | src/main/java/me/nullpoint/api/utils/entity/MovementUtil.java | package me.nullpoint.api.utils.entity;
import me.nullpoint.api.utils.Wrapper;
import me.nullpoint.asm.accessors.IVec3d;
import me.nullpoint.mod.modules.impl.movement.HoleSnap;
import net.minecraft.entity.effect.StatusEffects;
import net.minecraft.util.math.Vec3d;
public class MovementUtil implements Wrapper {
public static boolean isMoving() {
return mc.player.input.movementForward != 0.0 || mc.player.input.movementSideways != 0.0 || HoleSnap.INSTANCE.isOn();
}
public static double getDistance2D() {
double xDist = mc.player.getX() - mc.player.prevX;
double zDist = mc.player.getZ() - mc.player.prevZ;
return Math.sqrt(xDist * xDist + zDist * zDist);
}
public static double getJumpSpeed() {
double defaultSpeed = 0.0;
if (mc.player.hasStatusEffect(StatusEffects.JUMP_BOOST)) {
//noinspection ConstantConditions
int amplifier = mc.player.getActiveStatusEffects().get(StatusEffects.JUMP_BOOST).getAmplifier();
defaultSpeed += (amplifier + 1) * 0.1;
}
return defaultSpeed;
}
public static float getMoveForward() {
return mc.player.input.movementForward;
}
public static float getMoveStrafe() {
return mc.player.input.movementSideways;
}
private static final double diagonal = 1 / Math.sqrt(2);
private static final Vec3d horizontalVelocity = new Vec3d(0, 0, 0);
public static Vec3d getHorizontalVelocity(double bps) {
float yaw = mc.player.getYaw();
Vec3d forward = Vec3d.fromPolar(0, yaw);
Vec3d right = Vec3d.fromPolar(0, yaw + 90);
double velX = 0;
double velZ = 0;
boolean a = false;
if (mc.player.input.pressingForward) {
velX += forward.x / 20 * bps;
velZ += forward.z / 20 * bps;
a = true;
}
if (mc.player.input.pressingBack) {
velX -= forward.x / 20 * bps;
velZ -= forward.z / 20 * bps;
a = true;
}
boolean b = false;
if (mc.player.input.pressingRight) {
velX += right.x / 20 * bps;
velZ += right.z / 20 * bps;
b = true;
}
if (mc.player.input.pressingLeft) {
velX -= right.x / 20 * bps;
velZ -= right.z / 20 * bps;
b = true;
}
if (a && b) {
velX *= diagonal;
velZ *= diagonal;
}
((IVec3d) horizontalVelocity).setX(velX);
((IVec3d) horizontalVelocity).setZ(velZ);
return horizontalVelocity;
}
public static double[] directionSpeed(double speed) {
float forward = mc.player.input.movementForward;
float side = mc.player.input.movementSideways;
float yaw = mc.player.prevYaw + (mc.player.getYaw() - mc.player.prevYaw) * mc.getTickDelta();
if (forward != 0.0f) {
if (side > 0.0f) {
yaw += ((forward > 0.0f) ? -45 : 45);
} else if (side < 0.0f) {
yaw += ((forward > 0.0f) ? 45 : -45);
}
side = 0.0f;
if (forward > 0.0f) {
forward = 1.0f;
} else if (forward < 0.0f) {
forward = -1.0f;
}
}
final double sin = Math.sin(Math.toRadians(yaw + 90.0f));
final double cos = Math.cos(Math.toRadians(yaw + 90.0f));
final double posX = forward * speed * cos + side * speed * sin;
final double posZ = forward * speed * sin - side * speed * cos;
return new double[]{posX, posZ};
}
public static double getMotionX() {
return mc.player.getVelocity().x;
}
public static double getMotionY() {
return mc.player.getVelocity().y;
}
public static double getMotionZ() {
return mc.player.getVelocity().z;
}
public static void setMotionX(double x) {
((IVec3d) mc.player.getVelocity()).setX(x);
}
public static void setMotionY(double y) {
((IVec3d) mc.player.getVelocity()).setY(y);
}
public static void setMotionZ(double z) {
((IVec3d) mc.player.getVelocity()).setZ(z);
}
public static double getSpeed(boolean slowness) {
double defaultSpeed = 0.2873;
return getSpeed(slowness, defaultSpeed);
}
public static double getSpeed(boolean slowness, double defaultSpeed) {
if (mc.player.hasStatusEffect(StatusEffects.SPEED)) {
int amplifier = mc.player.getActiveStatusEffects().get(StatusEffects.SPEED)
.getAmplifier();
defaultSpeed *= 1.0 + 0.2 * (amplifier + 1);
}
if (slowness && mc.player.hasStatusEffect(StatusEffects.SLOWNESS)) {
int amplifier = mc.player.getActiveStatusEffects().get(StatusEffects.SLOWNESS)
.getAmplifier();
defaultSpeed /= 1.0 + 0.2 * (amplifier + 1);
}
if (mc.player.isSneaking()) defaultSpeed /= 5;
return defaultSpeed;
}
}
| 0 | 0.853691 | 1 | 0.853691 | game-dev | MEDIA | 0.942506 | game-dev | 0.989408 | 1 | 0.989408 |
DeltaV-Station/Delta-v | 4,956 | Content.Shared/_DV/Waddle/SharedWaddleAnimationSystem.cs | using Content.Shared.ActionBlocker;
using Content.Shared.Buckle;
using Content.Shared.Buckle.Components;
using Content.Shared.Gravity;
using Content.Shared.Mobs;
using Content.Shared.Mobs.Systems;
using Content.Shared.Movement.Components;
using Content.Shared.Movement.Events;
using Content.Shared.Movement.Systems;
using Content.Shared.Standing;
using Content.Shared.Stunnable;
using Robust.Shared.Timing;
namespace Content.Shared._DV.Waddle;
public abstract class SharedWaddleAnimationSystem : EntitySystem
{
[Dependency] private readonly ActionBlockerSystem _actionBlocker = default!;
[Dependency] private readonly IGameTiming _timing = default!;
[Dependency] private readonly MobStateSystem _mob = default!;
[Dependency] private readonly SharedBuckleSystem _buckle = default!;
[Dependency] private readonly SharedGravitySystem _gravity = default!;
[Dependency] private readonly StandingStateSystem _standing = default!;
public override void Initialize()
{
// Startup
SubscribeLocalEvent<WaddleAnimationComponent, ComponentStartup>(OnComponentStartup);
// Start moving possibilities
SubscribeLocalEvent<WaddleAnimationComponent, MoveInputEvent>(OnMovementInput);
SubscribeLocalEvent<WaddleAnimationComponent, StoodEvent>(OnStood);
// Stop moving possibilities
SubscribeLocalEvent((Entity<WaddleAnimationComponent> ent, ref StunnedEvent _) => StopWaddling(ent));
SubscribeLocalEvent((Entity<WaddleAnimationComponent> ent, ref DownedEvent _) => StopWaddling(ent));
SubscribeLocalEvent((Entity<WaddleAnimationComponent> ent, ref BuckledEvent _) => StopWaddling(ent));
SubscribeLocalEvent((Entity<WaddleAnimationComponent> ent, ref MobStateChangedEvent _) => StopWaddling(ent));
SubscribeLocalEvent<WaddleAnimationComponent, GravityChangedEvent>(OnGravityChanged);
}
private void OnGravityChanged(Entity<WaddleAnimationComponent> ent, ref GravityChangedEvent args)
{
if (!args.HasGravity)
StopWaddling(ent);
}
private void OnComponentStartup(Entity<WaddleAnimationComponent> ent, ref ComponentStartup args)
{
if (!TryComp<InputMoverComponent>(ent, out var mover))
return;
// If the waddler is currently moving, make them start waddling
if ((mover.HeldMoveButtons & MoveButtons.AnyDirection) != MoveButtons.None)
SetWaddling(ent, true);
}
private void OnMovementInput(Entity<WaddleAnimationComponent> ent, ref MoveInputEvent args)
{
// Only start waddling if we're actually moving.
SetWaddling(ent, args.HasDirectionalMovement);
}
private void OnStood(Entity<WaddleAnimationComponent> ent, ref StoodEvent args)
{
if (!TryComp<InputMoverComponent>(ent, out var mover))
return;
// only resume waddling if they are trying to move
if ((mover.HeldMoveButtons & MoveButtons.AnyDirection) == MoveButtons.None)
return;
SetWaddling(ent, true);
}
private void StopWaddling(Entity<WaddleAnimationComponent> ent)
{
SetWaddling(ent, false);
}
/// <summary>
/// Enables or disables waddling for a entity, including the animation.
/// Unless force is true, prevents dead people etc from waddling using <see cref="CanWaddle">.
/// </summary>
public void SetWaddling(Entity<WaddleAnimationComponent> ent, bool waddling, bool force = false)
{
// it makes your sprite rotation stutter when moving, bad
if (!_timing.IsFirstTimePredicted)
return;
if (waddling && !force && !CanWaddle(ent))
waddling = false;
if (ent.Comp.IsWaddling == waddling)
return;
ent.Comp.IsWaddling = waddling;
DirtyField(ent, ent.Comp, nameof(WaddleAnimationComponent.IsWaddling));
UpdateAnimation(ent);
}
/// <summary>
/// Returns true if an entity is allowed to waddle at all.
/// </summary>
public bool CanWaddle(EntityUid uid)
{
// can't waddle when dead
return _mob.IsAlive(uid) &&
// bouncy shoes should make you spin in 0G really but definitely not bounce up and down
!_gravity.IsWeightless(uid) &&
// can't waddle if your legs are broken etc
_actionBlocker.CanMove(uid) &&
// can't waddle when buckled, if you are really strong/on meth the chair/bed should waddle instead
!_buckle.IsBuckled(uid) &&
// animation doesn't take being downed into account :(
!_standing.IsDown(uid) &&
// can't waddle in space... 1984
Transform(uid).GridUid != null;
}
/// <summary>
/// Updates the waddling animation on the client.
/// Does nothing on server.
/// </summary>
protected virtual void UpdateAnimation(Entity<WaddleAnimationComponent> ent)
{
}
}
| 0 | 0.933505 | 1 | 0.933505 | game-dev | MEDIA | 0.978226 | game-dev | 0.974413 | 1 | 0.974413 |
GregTech6/gregtech6 | 53,192 | src/main/java/gregtech/GT6_Main.java | /**
* Copyright (c) 2025 GregTech-6 Team
*
* This file is part of GregTech.
*
* GregTech 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.
*
* GregTech 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 GregTech. If not, see <http://www.gnu.org/licenses/>.
*/
package gregtech;
import cpw.mods.fml.common.*;
import cpw.mods.fml.common.event.*;
import cpw.mods.fml.common.registry.EntityRegistry;
import gregapi.api.Abstract_Mod;
import gregapi.api.Abstract_Proxy;
import gregapi.block.prefixblock.PrefixBlockItem;
import gregapi.code.ArrayListNoNulls;
import gregapi.code.IItemContainer;
import gregapi.code.ItemStackContainer;
import gregapi.code.TagData;
import gregapi.compat.CompatMods;
import gregapi.data.*;
import gregapi.item.multiitem.MultiItem;
import gregapi.item.multiitem.MultiItemRandom;
import gregapi.item.multiitem.behaviors.Behavior_Turn_Into;
import gregapi.item.multiitem.behaviors.IBehavior;
import gregapi.item.prefixitem.PrefixItem;
import gregapi.network.NetworkHandler;
import gregapi.oredict.OreDictManager;
import gregapi.oredict.OreDictMaterial;
import gregapi.oredict.OreDictMaterialStack;
import gregapi.oredict.configurations.IOreDictConfigurationComponent;
import gregapi.recipes.Recipe;
import gregapi.recipes.maps.RecipeMapReplicator;
import gregapi.util.CR;
import gregapi.util.OM;
import gregapi.util.ST;
import gregapi.util.UT;
import gregtech.blocks.fluids.BlockOcean;
import gregtech.blocks.fluids.BlockRiver;
import gregtech.blocks.fluids.BlockSwamp;
import gregtech.compat.*;
import gregtech.entities.projectiles.EntityArrow_Material;
import gregtech.entities.projectiles.EntityArrow_Potion;
import gregtech.items.tools.early.GT_Tool_Scoop;
import gregtech.loaders.a.*;
import gregtech.loaders.b.*;
import gregtech.loaders.c.*;
import ic2.core.Ic2Items;
import net.minecraft.block.Block;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraftforge.common.ChestGenHooks;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidContainerRegistry.FluidContainerData;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.oredict.OreDictionary;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map.Entry;
import static gregapi.data.CS.*;
/**
* @author Gregorius Techneticies
*/
@Mod(modid=ModIDs.GT, name="GregTech", version="GT6-MC1710", dependencies="required-after:"+ModIDs.GAPI_POST)
public class GT6_Main extends Abstract_Mod {
@SidedProxy(modId = ModIDs.GT, clientSide = "gregtech.GT_Client", serverSide = "gregtech.GT_Server")
public static GT_Proxy gt_proxy;
public GT6_Main() {
GT = this;
NW_GT = new NetworkHandler(MD.GT.mID, "GREG");
}
@Override
public void onModPreInit2(FMLPreInitializationEvent aEvent) {
try {
LoadController tLoadController = ((LoadController)UT.Reflection.getFieldContent(Loader.instance(), "modController", T, T));
List<ModContainer> tModList = tLoadController.getActiveModList(), tNewModsList = new ArrayList<>(tModList.size());
ModContainer tGregTech = null;
for (short i = 0; i < tModList.size(); i++) {
ModContainer tMod = tModList.get(i);
if (tMod.getModId().equalsIgnoreCase(MD.GT.mID)) tGregTech = tMod; else tNewModsList.add(tMod);
}
if (tGregTech != null) tNewModsList.add(tGregTech);
UT.Reflection.setFieldContent(tLoadController, "activeModList", tNewModsList);
} catch(Throwable e) {
e.printStackTrace(ERR);
}
gt_proxy.mSkeletonsShootGTArrows = ConfigsGT.GREGTECH.get("general", "SkeletonsShootGTArrows", 16);
gt_proxy.mFlintChance = (int)UT.Code.bind(1, 100, ConfigsGT.GREGTECH.get("general", "FlintAndSteelChance", 30));
gt_proxy.mDisableVanillaOres = ConfigsGT.GREGTECH.get("general", "DisableVanillaOres" , T);
gt_proxy.mDisableVanillaLakes = ConfigsGT.GREGTECH.get("general", "DisableVanillaLakes" , T);
mDisableIC2Ores = ConfigsGT.GREGTECH.get("general", "DisableIC2Ores" , T);
BlockOcean.SPREAD_TO_AIR = ConfigsGT.GREGTECH.get("general", "OceanBlocksSpreadToAir", F);
BlockOcean.FLOWS_OUT = ConfigsGT.GREGTECH.get("general", "OceanBlocksFlowOutFar" , F);
BlockSwamp.FLOWS_OUT = ConfigsGT.GREGTECH.get("general", "SwampBlocksFlowOutFar" , F);
BlockRiver.FLOWS_OUT = ConfigsGT.GREGTECH.get("general", "RiverBlocksFlowOutFar" , F);
if (COMPAT_IC2 != null && !MD.IC2C.mLoaded) {
OUT.println(getModNameForLog() + ": Removing all original Scrapbox Drops.");
try {
UT.Reflection.getField("ic2.core.item.ItemScrapbox$Drop", "topChance", T, T).set(null, 0);
((List<?>)UT.Reflection.getFieldContent(UT.Reflection.getFieldContent("ic2.api.recipe.Recipes", "scrapboxDrops", T, T), "drops", T, T)).clear();
} catch(Throwable e) {
e.printStackTrace(ERR);
}
OUT.println(getModNameForLog() + ": Adding Scrap with a Weight of 200.0F to the Scrapbox Drops.");
COMPAT_IC2.scrapbox(200.0F, IL.IC2_Scrap.get(1));
}
EntityRegistry.registerModEntity(EntityArrow_Material.class, "GT_Entity_Arrow" , 1, GT, 160, 1, T);
EntityRegistry.registerModEntity(EntityArrow_Potion.class , "GT_Entity_Arrow_Potion", 2, GT, 160, 1, T);
for (OreDictMaterial tWood : ANY.Wood.mToThis) OP.plate.disableItemGeneration(tWood);
OP.blockDust .disableItemGeneration(MT.OREMATS.Magnetite, MT.OREMATS.GraniticMineralSand, MT.OREMATS.BasalticMineralSand);
OP.ingot .disableItemGeneration(MT.Butter, MT.ButterSalted, MT.Chocolate, MT.Cheese, MT.MeatRaw, MT.MeatCooked, MT.FishRaw, MT.FishCooked, MT.Tofu, MT.SoylentGreen);
OP.gemChipped .disableItemGeneration(MT.EnergiumRed, MT.EnergiumCyan);
OP.gemFlawed .disableItemGeneration(MT.EnergiumRed, MT.EnergiumCyan);
OP.gem .disableItemGeneration(MT.EnergiumRed, MT.EnergiumCyan);
OP.gemFlawless .disableItemGeneration(MT.EnergiumRed, MT.EnergiumCyan);
OP.gemExquisite .disableItemGeneration(MT.EnergiumRed, MT.EnergiumCyan);
OP.gemLegendary .disableItemGeneration(MT.EnergiumRed, MT.EnergiumCyan);
OP.crushed .disableItemGeneration(MT.Ad, MT.Fe, MT.Si, MT.Al, MT.Ti, MT.W, MT.F, MT.Ta, MT.Nb, MT.Dilithium);
OP.crushedTiny .disableItemGeneration(MT.Ad, MT.Fe, MT.Si, MT.Al, MT.Ti, MT.W, MT.F, MT.Ta, MT.Nb, MT.Dilithium);
OP.crushedPurified .disableItemGeneration(MT.Ad, MT.Fe, MT.Si, MT.Al, MT.Ti, MT.W, MT.F, MT.Ta, MT.Nb, MT.Dilithium);
OP.crushedPurifiedTiny .disableItemGeneration(MT.Ad, MT.Fe, MT.Si, MT.Al, MT.Ti, MT.W, MT.F, MT.Ta, MT.Nb, MT.Dilithium);
OP.crushedCentrifuged .disableItemGeneration(MT.Ad, MT.Fe, MT.Si, MT.Al, MT.Ti, MT.W, MT.F, MT.Ta, MT.Nb, MT.Dilithium);
OP.crushedCentrifugedTiny.disableItemGeneration(MT.Ad, MT.Fe, MT.Si, MT.Al, MT.Ti, MT.W, MT.F, MT.Ta, MT.Nb, MT.Dilithium);
RM.pulverizing(ST.make(Blocks.cobblestone, 1, W), ST.make(Blocks.sand, 1, 0), null, 0, F);
RM.pulverizing(ST.make(Blocks.stone , 1, W), ST.make(Blocks.cobblestone, 1, 0), null, 0, F);
RM.pulverizing(ST.make(Blocks.gravel , 1, W), ST.make(Items.flint, 2, 0), OP.dust.mat(MT.Flint, 1), 10, F);
RM.pulverizing(ST.make(Blocks.furnace , 1, W), ST.make(Blocks.sand, 6, 0), null, 0, F);
RM.pulverizing(ST.make(Blocks.lit_furnace, 1, W), ST.make(Blocks.sand, 6, 0), null, 0, F);
RM.pulverizing(ST.make(Items.bone , 1, W), IL.Dye_Bonemeal.get(2), IL.Dye_Bonemeal.get(1), 50, T);
RM.pulverizing(ST.make(Items.blaze_rod , 1, W), ST.make(Items.blaze_powder, 3, 0), ST.make(Items.blaze_powder, 1, 0), 50, T);
RM.pulverizing(ST.make(Blocks.pumpkin , 1, W), ST.make(Items.pumpkin_seeds, 4, 0), null, 0, F);
RM.pulverizing(ST.make(Items.melon , 1, W), ST.make(Items.melon_seeds, 1, 0), null, 0, F);
RM.pulverizing(ST.make(Blocks.wool , 1, W), ST.make(Items.string, 2, 0), ST.make(Items.string, 1, 0), 50, F);
new Loader_Fluids().run();
new Loader_Tools().run();
new Loader_Items().run();
new Loader_PrefixBlocks().run();
new Loader_Blocks().run();
new Loader_Rocks().run();
new Loader_Woods().run();
new Loader_Rails().run();
new Loader_Ores().run();
new Loader_Others().run();
// new Loader_CircuitBehaviors().run();
// new Loader_CoverBehaviors().run();
// new Loader_Sonictron().run();
new CompatMods(MD.MC, this) {@Override public void onPostLoad(FMLPostInitializationEvent aInitEvent) {
// We ain't got Water in that Water Bottle. That would be an infinite Water Exploit.
for (FluidContainerData tData : FluidContainerRegistry.getRegisteredFluidContainerData()) if (tData.filledContainer.getItem() == Items.potionitem && ST.meta_(tData.filledContainer) == 0) {tData.fluid.amount = 0; break;}
ArrayListNoNulls<Runnable> tList = new ArrayListNoNulls<>(F,
new Loader_BlockResistance(),
new Loader_Fuels(),
new Loader_Loot(),
new Loader_Recipes_Furnace(), // has to be before everything else!
new Loader_Recipes_Woods(), // has to be before Vanilla!
new Loader_Recipes_Vanilla(), // has to be after Woods!
new Loader_Recipes_Temporary(),
new Loader_Recipes_Chem(),
new Loader_Recipes_Crops(),
new Loader_Recipes_Potions(),
new Loader_Recipes_Food(),
new Loader_Recipes_Ores(),
new Loader_Recipes_Alloys(),
new Loader_Recipes_Other(),
new Loader_Recipes_Extruder(),
new Loader_Recipes_Hints()
);
for (Runnable tRunnable : tList) try {tRunnable.run();} catch(Throwable e) {e.printStackTrace(ERR);}
}};
new Compat_Recipes_Ganys (MD.GAPI , this);
new Compat_Recipes_Chisel (MD.CHSL , this);
new Compat_Recipes_FunkyLocomotion (MD.FUNK , this);
new Compat_Recipes_BetterBeginnings (MD.BB , this);
new Compat_Recipes_IndustrialCraft (MD.IC2 , this);
new Compat_Recipes_IndustrialCraft_Scrap(MD.IC2 , this);
new Compat_Recipes_BuildCraft (MD.BC , this);
new Compat_Recipes_Railcraft (MD.RC , this); // has to be before MFR!
new Compat_Recipes_ThermalExpansion (MD.TE_FOUNDATION , this);
new Compat_Recipes_Forestry (MD.FR , this);
new Compat_Recipes_MagicBees (MD.FRMB , this);
new Compat_Recipes_Binnie (MD.BINNIE , this);
new Compat_Recipes_BetterRecords (MD.BETTER_RECORDS, this);
new Compat_Recipes_BalkonsWeaponMod (MD.BWM , this);
new Compat_Recipes_OpenModularTurrets (MD.OMT , this);
new Compat_Recipes_TechGuns (MD.TG , this);
new Compat_Recipes_Atum (MD.ATUM , this);
new Compat_Recipes_Tropicraft (MD.TROPIC , this);
new Compat_Recipes_CandyCraft (MD.CANDY , this);
new Compat_Recipes_JABBA (MD.JABBA , this);
new Compat_Recipes_Factorization (MD.FZ , this);
new Compat_Recipes_Steamcraft2 (MD.SC2 , this);
new Compat_Recipes_MineFactoryReloaded (MD.MFR , this); // Has to be after RC!
new Compat_Recipes_AppliedEnergistics (MD.AE , this);
new Compat_Recipes_Bluepower (MD.BP , this);
new Compat_Recipes_ProjectRed (MD.PR , this);
new Compat_Recipes_ProjectE (MD.PE , this);
new Compat_Recipes_OpenComputers (MD.OC , this);
new Compat_Recipes_GrowthCraft (MD.GrC , this);
new Compat_Recipes_HarvestCraft (MD.HaC , this);
new Compat_Recipes_SaltyMod (MD.Salt , this);
new Compat_Recipes_MoCreatures (MD.MoCr , this);
new Compat_Recipes_Lycanites (MD.LycM , this);
new Compat_Recipes_Erebus (MD.ERE , this);
new Compat_Recipes_Betweenlands (MD.BTL , this);
new Compat_Recipes_TwilightForest (MD.TF , this);
new Compat_Recipes_Enviromine (MD.ENVM , this);
new Compat_Recipes_ExtraBiomesXL (MD.EBXL , this);
new Compat_Recipes_BiomesOPlenty (MD.BoP , this);
new Compat_Recipes_Highlands (MD.HiL , this);
new Compat_Recipes_Mariculture (MD.MaCu , this);
new Compat_Recipes_ImmersiveEngineering (MD.IE , this);
new Compat_Recipes_HBM (MD.HBM , this);
new Compat_Recipes_Reika (MD.DRGN , this);
new Compat_Recipes_Voltz (MD.VOLTZ , this);
new Compat_Recipes_Mekanism (MD.Mek , this);
new Compat_Recipes_GalactiCraft (MD.GC , this);
new Compat_Recipes_Mystcraft (MD.MYST , this);
new Compat_Recipes_Witchery (MD.WTCH , this);
new Compat_Recipes_Thaumcraft (MD.TC , this);
new Compat_Recipes_ForbiddenMagic (MD.TCFM , this);
new Compat_Recipes_ArsMagica (MD.ARS , this);
new Compat_Recipes_Botania (MD.BOTA , this);
new Compat_Recipes_Aether (MD.AETHER , this);
new Compat_Recipes_Aether_Legacy (MD.AETHEL , this);
new Compat_Recipes_RandomThings (MD.RT , this);
new Compat_Recipes_ActuallyAdditions (MD.AA , this);
new Compat_Recipes_ExtraUtilities (MD.ExU , this);
new Compat_Recipes_WRCBE (MD.WR_CBE_C , this);
new CompatMods(MD.GT, this) {@Override public void onPostLoad(FMLPostInitializationEvent aInitEvent) {
ArrayListNoNulls<Runnable> tList = new ArrayListNoNulls<>(F,
new Loader_Recipes_Replace(),
new Loader_Recipes_Foreign(),
new Loader_Recipes_Decomp(),
new Loader_Recipes_Handlers()
);
for (Runnable tRunnable : tList) try {tRunnable.run();} catch(Throwable e) {e.printStackTrace(ERR);}
}};
}
@Override
public void onModInit2(FMLInitializationEvent aEvent) {
for (FluidContainerData tData : FluidContainerRegistry.getRegisteredFluidContainerData()) if (tData.filledContainer.getItem() == Items.potionitem && ST.meta_(tData.filledContainer) == 0) {tData.fluid.amount = 0; break;}
new Loader_Late_Items_And_Blocks().run();
if (MD.IC2C.mLoaded) for (int i = 0; i <= 6; i++) FMLInterModComms.sendMessage(MD.IC2C.mID, "generatorDrop", ST.save(UT.NBT.makeInt("Key", i), "Value", IL.IC2_Machine.get(1)));
ArrayListNoNulls<Runnable> tList = new ArrayListNoNulls<>(F,
new Loader_MultiTileEntities(),
new Loader_Books(),
new Loader_OreProcessing(),
new Loader_Worldgen(),
new Loader_ItemIterator()
);
if (MD.MO.mLoaded) try {ST.block(MD.MO, "molten_tritanium").setBlockTextureName(MD.MO.mID + ":" + "molten_tritanium_still");} catch(Throwable e) {e.printStackTrace(ERR);}
for (Runnable tRunnable : tList) try {tRunnable.run();} catch(Throwable e) {e.printStackTrace(ERR);}
}
@Override
public void onModPostInit2(FMLPostInitializationEvent aEvent) {
ItemStack tLignite = ST.make(MD.UB, "ligniteCoal", 1, 0);
if (ST.valid(tLignite)) CR.remove(tLignite, tLignite, tLignite, tLignite, tLignite, tLignite, tLignite, tLignite, tLignite);
Block tBlock = ST.block(MD.FR, "beehives", NB);
if (tBlock != NB) {tBlock.setHarvestLevel("scoop", 0); GT_Tool_Scoop.sBeeHiveMaterial = tBlock.getMaterial();}
// if (IL.FR_Butterfly .get(1) != null) RecipeMap.sScannerFakeRecipes.addFakeRecipe(F, ST.array(IL.FR_Butterfly .getWildcard(1)} , ST.array(IL.FR_Butterfly .getWithName(1, "Scanned Butterfly" )}, null , FL.array(MT.Honey.liquid(U/20, T)}, null, 500, 2, 0);
// if (IL.FR_Larvae .get(1) != null) RecipeMap.sScannerFakeRecipes.addFakeRecipe(F, ST.array(IL.FR_Larvae .getWildcard(1)} , ST.array(IL.FR_Larvae .getWithName(1, "Scanned Larvae" )}, null , FL.array(MT.Honey.liquid(U/20, T)}, null, 500, 2, 0);
// if (IL.FR_Serum .get(1) != null) RecipeMap.sScannerFakeRecipes.addFakeRecipe(F, ST.array(IL.FR_Serum .getWildcard(1)} , ST.array(IL.FR_Serum .getWithName(1, "Scanned Serum" )}, null , FL.array(MT.Honey.liquid(U/20, T)}, null, 500, 2, 0);
// if (IL.FR_Caterpillar .get(1) != null) RecipeMap.sScannerFakeRecipes.addFakeRecipe(F, ST.array(IL.FR_Caterpillar .getWildcard(1)} , ST.array(IL.FR_Caterpillar .getWithName(1, "Scanned Caterpillar" )}, null , FL.array(MT.Honey.liquid(U/20, T)}, null, 500, 2, 0);
// if (IL.FR_PollenFertile .get(1) != null) RecipeMap.sScannerFakeRecipes.addFakeRecipe(F, ST.array(IL.FR_PollenFertile .getWildcard(1)} , ST.array(IL.FR_PollenFertile .getWithName(1, "Scanned Pollen" )}, null , FL.array(MT.Honey.liquid(U/20, T)}, null, 500, 2, 0);
// RecipeMap.sScannerFakeRecipes.addFakeRecipe(F, ST.array(IL.Tool_DataOrb .getWithName(1, "Orb to overwrite")} , ST.array(IL.Tool_DataOrb .getWithName(1, "Copy of the Orb" )}, IL.Tool_DataOrb.getWithName(0, "Orb to copy") , null, null, 512, 32, 0);
// RecipeMap.sScannerFakeRecipes.addFakeRecipe(F, ST.array(IL.Tool_DataStick .getWithName(1, "Stick to overwrite")} , ST.array(IL.Tool_DataStick .getWithName(1, "Copy of the Stick" )}, IL.Tool_DataStick.getWithName(0, "Stick to copy") , null, null, 128, 32, 0);
for (IItemContainer tBee : new IItemContainer[] {IL.FR_Bee_Drone, IL.FR_Bee_Princess, IL.FR_Bee_Queen}) if (tBee.exists()) {
for (String tFluid : FluidsGT.HONEY) if (FL.exists(tFluid))
RM.Bumblelyzer.addFakeRecipe(F, ST.array(tBee.wild(1)), ST.array(tBee.getWithName(1, "Scanned Bee")), null, null, FL.array(FL.make(tFluid, 50)) , null, 64, 16, 0);
RM.Bumblelyzer.addFakeRecipe(F, ST.array(tBee.wild(1)), ST.array(tBee.getWithName(1, "Scanned Bee")), null, null, FL.array(FL.Honeydew.make(50)), null, 64, 16, 0);
}
for (IItemContainer tPlant : new IItemContainer[] {IL.FR_Tree_Sapling, IL.IC2_Crop_Seeds}) if (tPlant.exists()) {
RM.Plantalyzer.addFakeRecipe(F, ST.array(tPlant.wild(1)), ST.array(tPlant.getWithName(1, "Scanned Plant")), null, null, null, null, 64, 16, 0);
}
for (ItemStack tStack : OreDictManager.getOres("bookWritten", F))
RM.ScannerVisuals.addFakeRecipe(F, ST.array(tStack, IL.USB_Stick_1.get(1)) , ST.array(IL.USB_Stick_1.getWithName(1, "Containing scanned Book" ), tStack), null, null, ZL_FS, ZL_FS, 512, 16, 0);
RM.ScannerVisuals.addFakeRecipe(F, ST.array(IL.Paper_Printed_Pages.get(1), IL.USB_Stick_1.get(1)) , ST.array(IL.USB_Stick_1.getWithName(1, "Containing scanned Book" ), IL.Paper_Printed_Pages.get(1)), null, null, ZL_FS, ZL_FS, 512, 16, 0);
RM.ScannerVisuals.addFakeRecipe(F, ST.array(IL.Paper_Printed_Pages_Many.get(1), IL.USB_Stick_1.get(1)) , ST.array(IL.USB_Stick_1.getWithName(1, "Containing large scanned Book" ), IL.Paper_Printed_Pages_Many.get(1)), null, null, ZL_FS, ZL_FS, 512, 16, 0);
for (ItemStack tStack : OreDictManager.getOres("gt:canvas", F))
RM.ScannerVisuals.addFakeRecipe(F, ST.array(tStack, IL.USB_Stick_1.get(1)) , ST.array(IL.USB_Stick_1.getWithName(1, "Containing scanned Block" ), tStack), null, null, ZL_FS, ZL_FS, 64, 16, 0);
RM.ScannerVisuals.addFakeRecipe(F, ST.array(ST.make(Blocks.crafting_table, 1, 0, "ANY BLOCK"), IL.USB_Stick_1.get(1)) , ST.array(IL.USB_Stick_1.getWithName(1, "Containing scanned Block" ), ST.make(Blocks.crafting_table, 1, 0, "ANY BLOCK")), null, null, ZL_FS, ZL_FS, 512, 16, 0);
RM.ScannerVisuals.addFakeRecipe(F, ST.array(ST.make(Items.filled_map, 1, W), IL.USB_Stick_1.get(1)) , ST.array(IL.USB_Stick_1.getWithName(1, "Containing scanned Map" ), ST.make(Items.filled_map, 1, W)), null, null, ZL_FS, ZL_FS, 64, 16, 0);
if (IL.TF_Magic_Map.exists())
RM.ScannerVisuals.addFakeRecipe(F, ST.array(IL.TF_Magic_Map.wild(1), IL.USB_Stick_1.get(1)) , ST.array(IL.USB_Stick_1.getWithName(1, "Containing scanned Magic Map" ), IL.TF_Magic_Map.wild(1)), null, null, ZL_FS, ZL_FS, 64, 16, 0);
if (IL.TF_Maze_Map.exists())
RM.ScannerVisuals.addFakeRecipe(F, ST.array(IL.TF_Maze_Map .wild(1), IL.USB_Stick_1.get(1)) , ST.array(IL.USB_Stick_1.getWithName(1, "Containing scanned Maze Map" ), IL.TF_Maze_Map .wild(1)), null, null, ZL_FS, ZL_FS, 64, 16, 0);
if (IL.TF_Ore_Map.exists())
RM.ScannerVisuals.addFakeRecipe(F, ST.array(IL.TF_Ore_Map .wild(1), IL.USB_Stick_1.get(1)) , ST.array(IL.USB_Stick_1.getWithName(1, "Containing scanned Ore Map" ), IL.TF_Ore_Map .wild(1)), null, null, ZL_FS, ZL_FS, 64, 16, 0);
RM.ScannerVisuals.addFakeRecipe(F, ST.array(IL.Paper_Blueprint_Used.get(1), IL.USB_Stick_1.get(1)) , ST.array(IL.USB_Stick_1.getWithName(1, "Containing scanned Blueprint" ), IL.Paper_Blueprint_Used.get(1)), null, null, ZL_FS, ZL_FS, 64, 16, 0);
if (IL.GC_Schematic_1.exists())
RM.ScannerVisuals.addFakeRecipe(F, ST.array(IL.GC_Schematic_1.wild(1), IL.USB_Stick_1.get(1)) , ST.array(IL.USB_Stick_1.getWithName(1, "Containing scanned Schematics" ), IL.GC_Schematic_1.wild(1)), null, null, ZL_FS, ZL_FS, 1024, 16, 0);
if (IL.GC_Schematic_2.exists())
RM.ScannerVisuals.addFakeRecipe(F, ST.array(IL.GC_Schematic_2.wild(1), IL.USB_Stick_1.get(1)) , ST.array(IL.USB_Stick_1.getWithName(1, "Containing scanned Schematics" ), IL.GC_Schematic_2.wild(1)), null, null, ZL_FS, ZL_FS, 1024, 16, 0);
if (IL.GC_Schematic_3.exists())
RM.ScannerVisuals.addFakeRecipe(F, ST.array(IL.GC_Schematic_3.wild(1), IL.USB_Stick_1.get(1)) , ST.array(IL.USB_Stick_1.getWithName(1, "Containing scanned Schematics" ), IL.GC_Schematic_3.wild(1)), null, null, ZL_FS, ZL_FS, 1024, 16, 0);
if (IL.IE_Blueprint_Projectiles_Common.exists())
RM.ScannerVisuals.addFakeRecipe(F, ST.array(IL.IE_Blueprint_Projectiles_Common.wild(1), IL.USB_Stick_1.get(1)) , ST.array(IL.USB_Stick_1.getWithName(1, "Containing scanned Engineer's Blueprint" ), IL.IE_Blueprint_Projectiles_Common.wild(1)), null, null, ZL_FS, ZL_FS, 1024, 16, 0);
RM.Boxinator.addRecipe2(T, 16, 16, ST.make(Items.paper, 8, W), ST.make(Items.compass, 1, W), NF, NF, ST.make(Items.map, 1, 0));
RM.Printer.addRecipe1(T, 16, 256, ST.make(Items.book, 1, W), DYE_FLUIDS_CHEMICAL[DYE_INDEX_Black], NF, ST.book("Manual_Printer", ST.make(ItemsGT.BOOKS, 1, 8)));
for (ItemStack tStack : OreDictManager.getOres("gt:canvas", F))
RM.Printer.addFakeRecipe(F, ST.array(tStack , IL.USB_Stick_1.getWithName(0, "Containing scanned Block" )), ST.array(tStack ), null, null, FL.array(FL.mul(DYE_FLUIDS_CHEMICAL[DYE_INDEX_Yellow], 1, 9, T), FL.mul(DYE_FLUIDS_CHEMICAL[DYE_INDEX_Magenta], 1, 9, T), FL.mul(DYE_FLUIDS_CHEMICAL[DYE_INDEX_Cyan], 1, 9, T), FL.mul(DYE_FLUIDS_CHEMICAL[DYE_INDEX_Black], 1, 9, T)), ZL_FS, 64, 16, 0);
// RM.Printer.addFakeRecipe(F, ST.array(IL.Paper_Punch_Card_Empty .get(1), IL.USB_Stick_1.getWithName(0, "Containing scanned Punchcard" )), ST.array(IL.Paper_Punch_Card_Encoded.get(1) ), null, null, FL.array( FL.mul(DYE_FLUIDS_CHEMICAL[DYE_INDEX_Black], 1, 9, T)), ZL_FS, 32, 16, 0);
RM.Printer.addFakeRecipe(F, ST.array(IL.Paper_Blueprint_Empty .get(1), IL.USB_Stick_1.getWithName(0, "Containing scanned Blueprint" )), ST.array(IL.Paper_Blueprint_Used.get(1) ), null, null, FL.array( FL.mul(DYE_FLUIDS_CHEMICAL[DYE_INDEX_White], 1, 9, T)), ZL_FS, 32, 16, 0);
RM.Printer.addFakeRecipe(F, ST.array(ST.make(Items.paper, 1, W) , IL.USB_Stick_1.getWithName(0, "Containing scanned Blueprint" )), ST.array(IL.Paper_Blueprint_Used.get(1) ), null, null, FL.array( FL.mul(DYE_FLUIDS_CHEMICAL[DYE_INDEX_Blue ], 1, 1, T)), ZL_FS, 128, 16, 0);
RM.Printer.addFakeRecipe(F, ST.array(ST.make(Items.paper, 3, W) , IL.USB_Stick_1.getWithName(0, "Containing scanned Book" )), ST.array(IL.Paper_Printed_Pages.get(1) ), null, null, FL.array( FL.mul(DYE_FLUIDS_CHEMICAL[DYE_INDEX_Black], 1, 2, T)), ZL_FS, 512, 16, 0);
RM.Printer.addFakeRecipe(F, ST.array(ST.make(Items.paper, 6, W) , IL.USB_Stick_1.getWithName(0, "Containing large scanned Book" )), ST.array(IL.Paper_Printed_Pages_Many.get(1) ), null, null, FL.array( FL.mul(DYE_FLUIDS_CHEMICAL[DYE_INDEX_Black], 1, 1, T)), ZL_FS, 1024, 16, 0);
RM.Printer.addFakeRecipe(F, ST.array(ST.make(Items.map, 1, W) , IL.USB_Stick_1.getWithName(0, "Containing scanned Map" )), ST.array(ST.make(Items.filled_map, 1, 0) ), null, null, FL.array(FL.mul(DYE_FLUIDS_CHEMICAL[DYE_INDEX_Yellow], 1, 9, T), FL.mul(DYE_FLUIDS_CHEMICAL[DYE_INDEX_Magenta], 1, 9, T), FL.mul(DYE_FLUIDS_CHEMICAL[DYE_INDEX_Cyan], 1, 9, T), FL.mul(DYE_FLUIDS_CHEMICAL[DYE_INDEX_Black], 1, 9, T)), ZL_FS, 64, 16, 0);
if (IL.TF_Magic_Map.exists())
RM.Printer.addFakeRecipe(F, ST.array(IL.TF_Magic_Map_Empty .wild(1), IL.USB_Stick_1.getWithName(0, "Containing scanned Magic Map" )), ST.array(IL.TF_Magic_Map .get(1)), null, null, FL.array(FL.mul(DYE_FLUIDS_CHEMICAL[DYE_INDEX_Yellow], 1, 9, T), FL.mul(DYE_FLUIDS_CHEMICAL[DYE_INDEX_Magenta], 1, 9, T), FL.mul(DYE_FLUIDS_CHEMICAL[DYE_INDEX_Cyan], 1, 9, T), FL.mul(DYE_FLUIDS_CHEMICAL[DYE_INDEX_Black], 1, 9, T)), ZL_FS, 64, 16, 0);
if (IL.TF_Maze_Map.exists())
RM.Printer.addFakeRecipe(F, ST.array(IL.TF_Maze_Map_Empty .wild(1), IL.USB_Stick_1.getWithName(0, "Containing scanned Maze Map" )), ST.array(IL.TF_Maze_Map .get(1)), null, null, FL.array(FL.mul(DYE_FLUIDS_CHEMICAL[DYE_INDEX_Yellow], 1, 9, T), FL.mul(DYE_FLUIDS_CHEMICAL[DYE_INDEX_Magenta], 1, 9, T), FL.mul(DYE_FLUIDS_CHEMICAL[DYE_INDEX_Cyan], 1, 9, T), FL.mul(DYE_FLUIDS_CHEMICAL[DYE_INDEX_Black], 1, 9, T)), ZL_FS, 64, 16, 0);
if (IL.TF_Ore_Map.exists())
RM.Printer.addFakeRecipe(F, ST.array(IL.TF_Ore_Map_Empty .wild(1), IL.USB_Stick_1.getWithName(0, "Containing scanned Maze Map" )), ST.array(IL.TF_Ore_Map .get(1)), null, null, FL.array(FL.mul(DYE_FLUIDS_CHEMICAL[DYE_INDEX_Yellow], 1, 9, T), FL.mul(DYE_FLUIDS_CHEMICAL[DYE_INDEX_Magenta], 1, 9, T), FL.mul(DYE_FLUIDS_CHEMICAL[DYE_INDEX_Cyan], 1, 9, T), FL.mul(DYE_FLUIDS_CHEMICAL[DYE_INDEX_Black], 1, 9, T)), ZL_FS, 64, 16, 0);
if (IL.GC_Schematic_1.exists())
RM.Printer.addFakeRecipe(F, ST.array(ST.make(Items.paper, 8, W) , IL.USB_Stick_1.getWithName(0, "Containing scanned Schematics" )), ST.array(IL.GC_Schematic_1.wild(1) ), null, null, FL.array( FL.mul(DYE_FLUIDS_CHEMICAL[DYE_INDEX_Black], 4, 1, T)), ZL_FS, 2048, 16, 0);
if (IL.GC_Schematic_2.exists())
RM.Printer.addFakeRecipe(F, ST.array(ST.make(Items.paper, 8, W) , IL.USB_Stick_1.getWithName(0, "Containing scanned Schematics" )), ST.array(IL.GC_Schematic_2.wild(1) ), null, null, FL.array( FL.mul(DYE_FLUIDS_CHEMICAL[DYE_INDEX_Black], 4, 1, T)), ZL_FS, 2048, 16, 0);
if (IL.GC_Schematic_3.exists())
RM.Printer.addFakeRecipe(F, ST.array(ST.make(Items.paper, 8, W) , IL.USB_Stick_1.getWithName(0, "Containing scanned Schematics" )), ST.array(IL.GC_Schematic_3.wild(1) ), null, null, FL.array( FL.mul(DYE_FLUIDS_CHEMICAL[DYE_INDEX_Black], 4, 1, T)), ZL_FS, 2048, 16, 0);
if (IL.IE_Blueprint_Projectiles_Common.exists())
RM.Printer.addFakeRecipe(F, ST.array(ST.make(Items.paper, 3, W) , IL.USB_Stick_1.getWithName(0, "Containing scanned Engineer's Blueprint")), ST.array(IL.IE_Blueprint_Projectiles_Common.wild(1)), null, null, FL.array( FL.mul(DYE_FLUIDS_CHEMICAL[DYE_INDEX_Blue ], 3, 1, T)), ZL_FS, 2048, 16, 0);
if (IL.IE_Treated_Stairs.exists()) RM.Bath.addFakeRecipe(F, ST.array(ST.make(Blocks.oak_stairs , 1, W)), ST.array(IL.IE_Treated_Stairs.get(1 )), null, null, FL.array(FL.Oil_Creosote.make( 75)), ZL_FS, 102, 0, 0);
RM.Bath.addFakeRecipe(F, ST.array(ST.make(Blocks.wooden_slab , 1, W)), ST.array(IL.IE_Treated_Slab .get(1, IL.Treated_Planks_Slab.get(1))), null, null, FL.array(FL.Oil_Creosote.make( 50)), ZL_FS, 72, 0, 0);
RM.Bath.addFakeRecipe(F, ST.array(IL.Plank_Slab .get(1)), ST.array(IL.IE_Treated_Slab .get(1, IL.Treated_Planks_Slab.get(1))), null, null, FL.array(FL.Oil_Creosote.make( 50)), ZL_FS, 72, 0, 0);
if (IL.ERE_White_Planks.exists()) RM.Bath.addFakeRecipe(F, ST.array(IL.Plank .get(1)), ST.array(IL.ERE_White_Planks .get(1 )), null, null, FL.array( DYE_FLUIDS_WATER[DYE_INDEX_White] ), ZL_FS, 144, 0, 0);
if (IL.ERE_White_Slab.exists()) RM.Bath.addFakeRecipe(F, ST.array(IL.Plank_Slab .get(1)), ST.array(IL.ERE_White_Slab .get(1 )), null, null, FL.array(FL.mul(DYE_FLUIDS_WATER[DYE_INDEX_White], 1, 2, T)), ZL_FS, 72, 0, 0);
if (IL.ERE_White_Planks.exists()) RM.Bath.addFakeRecipe(F, ST.array(ST.make(Blocks.planks , 1, W)), ST.array(IL.ERE_White_Planks .get(1 )), null, null, FL.array( DYE_FLUIDS_WATER[DYE_INDEX_White] ), ZL_FS, 144, 0, 0);
if (IL.ERE_White_Stairs.exists()) RM.Bath.addFakeRecipe(F, ST.array(ST.make(Blocks.oak_stairs , 1, W)), ST.array(IL.ERE_White_Stairs .get(1 )), null, null, FL.array(FL.mul(DYE_FLUIDS_WATER[DYE_INDEX_White], 3, 4, T)), ZL_FS, 102, 0, 0);
if (IL.ERE_White_Slab.exists()) RM.Bath.addFakeRecipe(F, ST.array(ST.make(Blocks.wooden_slab , 1, W)), ST.array(IL.ERE_White_Slab .get(1 )), null, null, FL.array(FL.mul(DYE_FLUIDS_WATER[DYE_INDEX_White], 1, 2, T)), ZL_FS, 72, 0, 0);
RM.Unboxinator.addFakeRecipe(F, ST.array(IL.Crate_Loot .get(1)), ST.array(IL.Crate_Loot .getWithName(1, "1 Vanilla Loot Table Stack" ), IL.Crate.get(1)), null, ZL_LONG, ZL_FS, ZL_FS, 16, 16, 0);
RM.Unboxinator.addFakeRecipe(F, ST.array(IL.Book_Loot_Guide .get(1)), ST.array(IL.Book_Loot_Guide .getWithName(1, "1 Guide Book or Manual" ), ST.make(ItemsGT.BOOKS, 1, 32000), ST.make(ItemsGT.BOOKS, 1, 32001), ST.make(ItemsGT.BOOKS, 1, 32004), ST.make(ItemsGT.BOOKS, 1, 32005)), null, ZL_LONG, ZL_FS, ZL_FS, 16, 16, 0);
RM.Unboxinator.addFakeRecipe(F, ST.array(IL.Book_Loot_MatDict.get(1)), ST.array(IL.Book_Loot_MatDict.getWithName(1, "1 Material Dictionary" ), ST.make(ItemsGT.BOOKS, 1, 32002), ST.make(ItemsGT.BOOKS, 1, 32003)), null, ZL_LONG, ZL_FS, ZL_FS, 16, 16, 0);
RM.Unboxinator.addFakeRecipe(F, ST.array(IL.Bottle_Loot .get(1)), ST.array(IL.Bottle_Loot .getWithName(1, "Random Bottle of something" ), ST.make(Items.experience_bottle, 1, 0), ST.make(Items.potionitem, 1, 0), IL.Bottle_Holy_Water.get(1), IL.Bottle_Slime_Green.get(1), IL.Bottle_Ink.get(1), IL.Bottle_Indigo.get(1), IL.Bottle_Purple_Drink.get(1), IL.Bottle_Empty.get(1)), null, ZL_LONG, ZL_FS, ZL_FS, 16, 16, 0);
RM.Unboxinator.addFakeRecipe(F, ST.array(IL.Bag_Loot_Sapling .get(1)), ST.array(IL.Bag_Loot_Sapling .getWithName(1, "Enough Saplings to plant one Tree" ), ST.make(Blocks.sapling, 1, 0), ST.make(Blocks.sapling, 1, 1), ST.make(Blocks.sapling, 1, 2), ST.make(Blocks.sapling, 4, 3), ST.make(Blocks.sapling, 1, 4), ST.make(Blocks.sapling, 4, 5), IL.TC_Silverwood_Sapling.get(1)), null, ZL_LONG, ZL_FS, ZL_FS, 16, 16, 0);
RM.Unboxinator.addFakeRecipe(F, ST.array(IL.Bag_Loot_Seeds .get(1)), ST.array(IL.Bag_Loot_Seeds .getWithName(1, "A lot of one type of Seeds" ), ST.make(Items.wheat_seeds, 1, 0), ST.make(Items.pumpkin_seeds, 1, 0), ST.make(Items.melon_seeds, 1, 0), IL.EtFu_Beet_Seeds.get(1), ST.make(MD.RoC, "rotarycraft_item_canola", 1, 0)), null, ZL_LONG, ZL_FS, ZL_FS, 16, 16, 0);
RM.Unboxinator.addFakeRecipe(F, ST.array(IL.Bag_Loot_Gems .get(1)), ST.array(IL.Bag_Loot_Gems .getWithName(1, "1 Flawless Gem and some other Gems"), OP.gemFlawless.mat(MT.Diamond, 1), OP.gem.mat(MT.Emerald, 1)), null, ZL_LONG, ZL_FS, ZL_FS, 16, 16, 0);
RM.Unboxinator.addFakeRecipe(F, ST.array(IL.Bag_Loot_Misc .get(1)), ST.array(IL.Bag_Loot_Misc .getWithName(1, "Misc Item" ), IL.Tool_MatchBox_Full.get(1), IL.Dynamite.get(1), IL.Food_Can_Chum_4.get(1), OP.chemtube.mat(MT.Mcg, 1), IL.Pill_Cure_All.get(1), OP.rockGt.mat(MT.STONES.SkyStone, 1), OP.dust.mat(MT.OREMATS.Zeolite, 1)), null, ZL_LONG, ZL_FS, ZL_FS, 16, 16, 0);
if (IL.TC_Loot_Common .exists()) RM.Unboxinator.addFakeRecipe(F, ST.array(IL.TC_Loot_Common .get(1)), ST.array(IL.TC_Loot_Common .getWithName(1, "8 to 12 Singular Items"), NI, NI, ST.make(Items.diamond, 1, 0), ST.make(Items.emerald, 1, 0), ST.make(Items.ender_pearl, 1, 0), IL.TC_Gold_Coin.get(1), ST.make(Items.golden_apple, 1, 0), ST.make(Items.golden_apple, 1, 1), ST.make(Items.experience_bottle, 1, 0), ST.make(Items.enchanted_book, 1, 0), IL.TC_Knowledge_Fragment.get(1)), null, ZL_LONG, ZL_FS, ZL_FS, 16, 16, 0);
if (IL.TC_Loot_Uncommon.exists()) RM.Unboxinator.addFakeRecipe(F, ST.array(IL.TC_Loot_Uncommon .get(1)), ST.array(IL.TC_Loot_Uncommon.getWithName(1, "8 to 12 Singular Items"), NI, NI, ST.make(Items.diamond, 1, 0), ST.make(Items.emerald, 1, 0), ST.make(Items.ender_pearl, 1, 0), IL.TC_Gold_Coin.get(1), ST.make(Items.golden_apple, 1, 0), ST.make(Items.golden_apple, 1, 1), ST.make(Items.experience_bottle, 1, 0), ST.make(Items.enchanted_book, 1, 0), IL.TC_Knowledge_Fragment.get(1)), null, ZL_LONG, ZL_FS, ZL_FS, 16, 16, 0);
if (IL.TC_Loot_Rare .exists()) RM.Unboxinator.addFakeRecipe(F, ST.array(IL.TC_Loot_Rare .get(1)), ST.array(IL.TC_Loot_Rare .getWithName(1, "8 to 12 Singular Items"), IL.TC_Primordial_Pearl.get(1), ST.make(Items.nether_star, 1, 0), ST.make(Items.diamond, 1, 0), ST.make(Items.emerald, 1, 0), ST.make(Items.ender_pearl, 1, 0), IL.TC_Gold_Coin.get(1), ST.make(Items.golden_apple, 1, 0), ST.make(Items.golden_apple, 1, 1), ST.make(Items.experience_bottle, 1, 0), ST.make(Items.enchanted_book, 1, 0), IL.TC_Knowledge_Fragment.get(1)), null, ZL_LONG, ZL_FS, ZL_FS, 16, 16, 0);
if (IL.LOOTBAGS_Bag_0.exists()) RM.Unboxinator.addFakeRecipe(F, ST.array(IL.LOOTBAGS_Bag_0 .get(1)), ST.array(IL.LOOTBAGS_Bag_0.getWithName(1, "Drops depending on Config")), null, ZL_LONG, ZL_FS, ZL_FS, 16, 16, 0);
if (IL.LOOTBAGS_Bag_1.exists()) RM.Unboxinator.addFakeRecipe(F, ST.array(IL.LOOTBAGS_Bag_1 .get(1)), ST.array(IL.LOOTBAGS_Bag_1.getWithName(1, "Drops depending on Config")), null, ZL_LONG, ZL_FS, ZL_FS, 16, 16, 0);
if (IL.LOOTBAGS_Bag_2.exists()) RM.Unboxinator.addFakeRecipe(F, ST.array(IL.LOOTBAGS_Bag_2 .get(1)), ST.array(IL.LOOTBAGS_Bag_2.getWithName(1, "Drops depending on Config")), null, ZL_LONG, ZL_FS, ZL_FS, 16, 16, 0);
if (IL.LOOTBAGS_Bag_3.exists()) RM.Unboxinator.addFakeRecipe(F, ST.array(IL.LOOTBAGS_Bag_3 .get(1)), ST.array(IL.LOOTBAGS_Bag_3.getWithName(1, "Drops depending on Config")), null, ZL_LONG, ZL_FS, ZL_FS, 16, 16, 0);
if (IL.LOOTBAGS_Bag_4.exists()) RM.Unboxinator.addFakeRecipe(F, ST.array(IL.LOOTBAGS_Bag_4 .get(1)), ST.array(IL.LOOTBAGS_Bag_4.getWithName(1, "Drops depending on Config")), null, ZL_LONG, ZL_FS, ZL_FS, 16, 16, 0);
RM.BedrockOreList.addFakeRecipe(F, ST.array(ST.make(Blocks.bedrock, 1, W)), ST.array(ST.make(Blocks.cobblestone, 1, 0, "Various Cobblestone Types"), OP.dust.mat(MT.Bedrock, 1)), null, new long[] {9990, 10}, FL.array(FL.lube(100)), null, 0, 0, 0);
if (IL.BTL_Bedrock.exists()) RM.BedrockOreList.addFakeRecipe(F, ST.array(IL.BTL_Bedrock .get(1)), ST.array(ST.make(Blocks.cobblestone, 1, 0, "Various Cobblestone Types"), OP.dust.mat(MT.Bedrock, 1)), null, new long[] {9990, 10}, FL.array(FL.lube(100)), null, 0, 0, 0);
RM.ByProductList.mRecipeMachineList.add(ST.make(Items .cauldron, 1, 0));
RM.ByProductList.mRecipeMachineList.add(ST.make(Blocks.cauldron, 1, 0));
if (ConfigsGT.GREGTECH.get("general", "IncreaseDungeonLoot", T)) {
ChestGenHooks tChest;
tChest = ChestGenHooks.getInfo(ChestGenHooks.BONUS_CHEST ); tChest.setMax(tChest.getMax()+ 8); tChest.setMin(tChest.getMin()+ 4);
tChest = ChestGenHooks.getInfo(ChestGenHooks.DUNGEON_CHEST ); tChest.setMax(tChest.getMax()+12); tChest.setMin(tChest.getMin()+ 6);
tChest = ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_DESERT_CHEST ); tChest.setMax(tChest.getMax()+ 8); tChest.setMin(tChest.getMin()+ 4);
tChest = ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_JUNGLE_CHEST ); tChest.setMax(tChest.getMax()+16); tChest.setMin(tChest.getMin()+ 8);
tChest = ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_JUNGLE_DISPENSER); tChest.setMax(tChest.getMax()+ 2); tChest.setMin(tChest.getMin()+ 1);
tChest = ChestGenHooks.getInfo(ChestGenHooks.MINESHAFT_CORRIDOR ); tChest.setMax(tChest.getMax()+ 4); tChest.setMin(tChest.getMin()+ 2);
tChest = ChestGenHooks.getInfo(ChestGenHooks.VILLAGE_BLACKSMITH ); tChest.setMax(tChest.getMax()+12); tChest.setMin(tChest.getMin()+ 6);
tChest = ChestGenHooks.getInfo(ChestGenHooks.STRONGHOLD_CROSSING ); tChest.setMax(tChest.getMax()+ 8); tChest.setMin(tChest.getMin()+ 4);
tChest = ChestGenHooks.getInfo(ChestGenHooks.STRONGHOLD_CORRIDOR ); tChest.setMax(tChest.getMax()+ 6); tChest.setMin(tChest.getMin()+ 3);
tChest = ChestGenHooks.getInfo(ChestGenHooks.STRONGHOLD_LIBRARY ); tChest.setMax(tChest.getMax()+16); tChest.setMin(tChest.getMin()+ 8);
}
if (ConfigsGT.GREGTECH.get("general", "SmallerVanillaToolDurability", T)) {
Items.wooden_sword .setMaxDamage( 8);
Items.wooden_pickaxe .setMaxDamage( 8);
Items.wooden_shovel .setMaxDamage( 8);
Items.wooden_axe .setMaxDamage( 8);
Items.wooden_hoe .setMaxDamage( 8);
Items.stone_sword .setMaxDamage( 16);
Items.stone_pickaxe .setMaxDamage( 16);
Items.stone_shovel .setMaxDamage( 16);
Items.stone_axe .setMaxDamage( 16);
Items.stone_hoe .setMaxDamage( 16);
Items.golden_sword .setMaxDamage( 32);
Items.golden_pickaxe .setMaxDamage( 32);
Items.golden_shovel .setMaxDamage( 32);
Items.golden_axe .setMaxDamage( 32);
Items.golden_hoe .setMaxDamage( 32);
Items.iron_sword .setMaxDamage(128);
Items.iron_pickaxe .setMaxDamage(128);
Items.iron_shovel .setMaxDamage(128);
Items.iron_axe .setMaxDamage(128);
Items.iron_hoe .setMaxDamage(128);
Items.diamond_sword .setMaxDamage(512);
Items.diamond_pickaxe.setMaxDamage(512);
Items.diamond_shovel .setMaxDamage(512);
Items.diamond_axe .setMaxDamage(512);
Items.diamond_hoe .setMaxDamage(512);
}
if (CODE_CLIENT) {
for (OreDictMaterial aMaterial : OreDictMaterial.ALLOYS) {
for (IOreDictConfigurationComponent tAlloy : aMaterial.mAlloyCreationRecipes) {
boolean temp = T, tAddSpecial = F;
ArrayListNoNulls<ItemStack> tDusts = ST.arraylist(), tIngots = ST.arraylist(), tSpecial = ST.arraylist();
ArrayListNoNulls<Long> tMeltingPoints = new ArrayListNoNulls<>();
for (OreDictMaterialStack tMaterial : tAlloy.getUndividedComponents()) {
boolean tAddedSpecial = F;
if (tMaterial.mMaterial.mHidden) {temp = F; break;}
if (tMaterial.mMaterial == MT.Air) {
tDusts .add(FL.Air.display(UT.Code.units(tMaterial.mAmount, U, 1000, T)));
tIngots .add(FL.Air.display(UT.Code.units(tMaterial.mAmount, U, 1000, T)));
tSpecial.add(FL.Air.display(UT.Code.units(tMaterial.mAmount, U, 1000, T)));
continue;
}
if (tMaterial.mMaterial == MT.C ) {tAddedSpecial = tSpecial.add(OM.dustOrIngot(MT.Coal , tMaterial.mAmount * 2));}
if (tMaterial.mMaterial == MT.CaCO3 ) {tAddedSpecial = tSpecial.add(OM.dustOrIngot(MT.STONES.Limestone, tMaterial.mAmount * 2));}
tMeltingPoints.add(tMaterial.mMaterial.mMeltingPoint);
ItemStack tDust = OM.dustOrIngot(tMaterial.mMaterial, tMaterial.mAmount);
if (!tDusts.add(tDust)) {temp = F; break;}
tIngots.add(OM.ingotOrDust(tMaterial.mMaterial, tMaterial.mAmount));
if (tAddedSpecial) tAddSpecial = T; else tSpecial.add(tDust);
}
Collections.sort(tMeltingPoints);
if (temp) {
RM.CrucibleAlloying.addFakeRecipe(F, tDusts .toArray(ZL_IS), ST.array(OM.ingotOrDust(aMaterial, tAlloy.getCommonDivider() * U)), null, null, null, null, 0, 0, tMeltingPoints.size()>1?Math.max(tMeltingPoints.get(tMeltingPoints.size()-2), aMaterial.mMeltingPoint):aMaterial.mMeltingPoint);
RM.CrucibleAlloying.addFakeRecipe(F, tIngots .toArray(ZL_IS), ST.array(OM.ingotOrDust(aMaterial, tAlloy.getCommonDivider() * U)), null, null, null, null, 0, 0, tMeltingPoints.size()>1?Math.max(tMeltingPoints.get(tMeltingPoints.size()-2), aMaterial.mMeltingPoint):aMaterial.mMeltingPoint);
if (tAddSpecial)
RM.CrucibleAlloying.addFakeRecipe(F, tSpecial.toArray(ZL_IS), ST.array(OM.ingotOrDust(aMaterial, tAlloy.getCommonDivider() * U)), null, null, null, null, 0, 0, tMeltingPoints.size()>1?Math.max(tMeltingPoints.get(tMeltingPoints.size()-2), aMaterial.mMeltingPoint):aMaterial.mMeltingPoint);
}
}
}
for (OreDictMaterial aMaterial : OreDictMaterial.MATERIAL_ARRAY) if (aMaterial != null) {
Recipe tRecipe = RecipeMapReplicator.getReplicatorRecipe(aMaterial, IL.USB_Stick_3.getWithName(0, "Mat Data: "+aMaterial.getLocal()));
if (tRecipe != null) RM.Replicator.addFakeRecipe(F, tRecipe);
}
}
for (MultiItemRandom tItem : ItemsGT.ALL_MULTI_ITEMS) for (Entry<Short, ArrayList<IBehavior<MultiItem>>> tEntry : tItem.mItemBehaviors.entrySet()) for (IBehavior<MultiItem> tBehavior : tEntry.getValue()) if (tBehavior instanceof Behavior_Turn_Into) if (((Behavior_Turn_Into)tBehavior).mTurnInto.exists()) tItem.mVisibleItems.set(tEntry.getKey(), F);
}
@Override
public void onModServerStarting2(FMLServerStartingEvent aEvent) {
for (FluidContainerData tData : FluidContainerRegistry.getRegisteredFluidContainerData()) if (tData.filledContainer.getItem() == Items.potionitem && ST.meta_(tData.filledContainer) == 0) {tData.fluid.amount = 0; break;}
ORD.println("============================");
ORD.println("Outputting Unknown Materials");
ORD.println("============================");
for (String tUnknown : OreDictManager.INSTANCE.getUnknownMaterials()) ORD.println(tUnknown);
ORD.println("============================");
if (CODE_CLIENT) {try {
ORD.println("============================");
ORD.println("Outputting Colors of unknown Materials");
ORD.println("============================");
for (OreDictMaterial tUnknown : OreDictMaterial.MATERIAL_MAP.values()) if (tUnknown != null && tUnknown.contains(TD.Properties.UNUSED_MATERIAL) && !tUnknown.contains(TD.Properties.IGNORE_IN_COLOR_LOG)) {
for (ItemStackContainer aStack : tUnknown.mRegisteredItems) {
ItemStack tStack = aStack.toStack();
if (ST.valid(tStack) && ST.block(tStack) == NB && !(tStack.getItem() instanceof PrefixItem) && !(tStack.getItem() instanceof PrefixBlockItem)) {
short[] tRGB = UT.Code.color(tStack);
if (tRGB != null && tRGB != UNCOLOURED) ORD.println(tUnknown.mNameInternal + " - RGB: " + tRGB[0]+", "+tRGB[1]+", "+tRGB[2] + " - " + ST.names(tStack));
}
}
}
ORD.println("============================");
} catch(Throwable e) {e.printStackTrace(ERR);}}
ORD.println("================================");
ORD.println("Outputting Unknown OreDict Names");
ORD.println("================================");
for (String tUnknown : OreDictManager.INSTANCE.getUnknownNames()) ORD.println(tUnknown);
ORD.println("================================");
/*
try {((CommandHandler)aEvent.getServer().getCommandManager()).registerCommand(new CommandBase() {
@Override public String getCommandName() {return "xyzd";}
@Override public String getCommandUsage(ICommandSender aSender) {return E;}
@Override public int getRequiredPermissionLevel() {return 0;}
@Override public boolean canCommandSenderUseCommand(ICommandSender aSender) {return T;}
@Override public void processCommand(ICommandSender aSender, String[] aParameters) {
if (aParameters.length >= 3) {
EntityPlayerMP aPlayer = getCommandSenderAsPlayer(aSender);
if (aPlayer != null && (aPlayer.username.equals("GregoriusT") || aPlayer.username.equals("Player"))) {
try {
if (aPlayer.ridingEntity != null) aPlayer.mountEntity(null);
if (aPlayer.riddenByEntity != null) aPlayer.riddenByEntity.mountEntity(null);
if (aParameters.length >= 4) {
GT_Utility.moveEntityToDimensionAtCoords(aPlayer, Integer.parseInt(aParameters[3]), Integer.parseInt(aParameters[0])+0.5, Integer.parseInt(aParameters[1])+0.5, Integer.parseInt(aParameters[2])+0.5);
} else {
aPlayer.setPositionAndUpdate(Integer.parseInt(aParameters[0]), Integer.parseInt(aParameters[1]), Integer.parseInt(aParameters[2]));
}
} catch(Throwable e) {/*Do nothing}
}
}
}
});} catch(Throwable e) {/*Do nothing}
*/
if (MD.IC2.mLoaded && !MD.IC2C.mLoaded) try {if (mDisableIC2Ores) Ic2Items.tinOre = Ic2Items.leadOre = Ic2Items.copperOre = Ic2Items.uraniumOre = null;} catch (Throwable e) {e.printStackTrace(ERR);}
if (MD.TE.mLoaded) {
ItemStack tPyrotheum = OP.dust.mat(MT.Pyrotheum, 1);
for (ItemStackContainer tStack : OP.ore.mRegisteredItems) CR.remove(tStack.toStack(), tPyrotheum);
}
}
public boolean mDisableIC2Ores = T;
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public void onModServerStopping2(FMLServerStoppingEvent aEvent) {
try {
if (D1 || ORD != System.out) {
ORD.println("*");
ORD.println("TagData:");
ORD.println("*"); ORD.println("*"); ORD.println("*");
for (TagData tData : TagData.TAGS) ORD.println(tData.mName);
ORD.println("*");
ORD.println("ItemRegistry:");
ORD.println("*"); ORD.println("*"); ORD.println("*");
List tList = UT.Code.getWithoutNulls(Item.itemRegistry.getKeys().toArray(ZL_STRING));
Collections.sort(tList);
for (Object tItemName : tList) ORD.println(tItemName);
ORD.println("*");
ORD.println("OreDictionary:");
ORD.println("*"); ORD.println("*"); ORD.println("*");
tList = UT.Code.getWithoutNulls(OreDictionary.getOreNames());
Collections.sort(tList);
for (Object tOreName : tList) {
int tAmount = OreDictionary.getOres(tOreName.toString()).size();
if (tAmount > 0) ORD.println((tAmount<10?" ":"") + tAmount + "x " + tOreName);
}
ORD.println("*");
ORD.println("Materials:");
ORD.println("*"); ORD.println("*"); ORD.println("*");
for (int i = 0; i < OreDictMaterial.MATERIAL_ARRAY.length; i++) {
OreDictMaterial tMaterial = OreDictMaterial.MATERIAL_ARRAY[i];
if (tMaterial == null) {
if (i >= 8000 && i < 10000) {
ORD.println(i + ": <RESERVED>");
}
} else {
if (tMaterial.mToolTypes > 0) {
ORD.println(i + ": " + tMaterial.mNameInternal + "; T:" + tMaterial.mToolTypes + "; Q:" + tMaterial.mToolQuality + "; D:" + tMaterial.mToolDurability + "; S:" + tMaterial.mToolSpeed);
} else {
ORD.println(i + ": " + tMaterial.mNameInternal);
}
}
}
ORD.println("*");
ORD.println("Fluids:");
ORD.println("*"); ORD.println("*"); ORD.println("*");
tList = UT.Code.getWithoutNulls(FluidRegistry.getRegisteredFluids().keySet().toArray(ZL_STRING));
Collections.sort(tList);
for (Object tFluidName : tList) ORD.println(tFluidName);
ORD.println("*"); ORD.println("*"); ORD.println("*");
ORD.println("Biomes:");
ORD.println("*"); ORD.println("*"); ORD.println("*");
for (int i = 0; i < BiomeGenBase.getBiomeGenArray().length; i++) {
if (BiomeGenBase.getBiomeGenArray()[i] != null) ORD.println(BiomeGenBase.getBiomeGenArray()[i].biomeID + " = " + BiomeGenBase.getBiomeGenArray()[i].biomeName);
}
ORD.println("*"); ORD.println("*"); ORD.println("*");
ORD.println("Enchantments:");
ORD.println("*"); ORD.println("*"); ORD.println("*");
for (int i = 0; i < Enchantment.enchantmentsList.length; i++) {
if (Enchantment.enchantmentsList[i] != null) ORD.println(i + " = " + Enchantment.enchantmentsList[i].getName());
}
ORD.println("*"); ORD.println("*"); ORD.println("*");
ORD.println("END GregTech-Debug");
ORD.println("*"); ORD.println("*"); ORD.println("*");
}
} catch(Throwable e) {e.printStackTrace(ERR);}
}
@Override public void onModServerStarted2(FMLServerStartedEvent aEvent) {/**/}
@Override public void onModServerStopped2(FMLServerStoppedEvent aEvent) {/**/}
@Override public String getModID() {return MD.GT.mID;}
@Override public String getModName() {return MD.GT.mName;}
@Override public String getModNameForLog() {return "GT_Mod";}
@Override public Abstract_Proxy getProxy() {return gt_proxy;}
@Mod.EventHandler public void onPreLoad (FMLPreInitializationEvent aEvent) {onModPreInit(aEvent);}
@Mod.EventHandler public void onLoad (FMLInitializationEvent aEvent) {onModInit(aEvent);}
@Mod.EventHandler public void onPostLoad (FMLPostInitializationEvent aEvent) {onModPostInit(aEvent);}
@Mod.EventHandler public void onServerStarting (FMLServerStartingEvent aEvent) {onModServerStarting(aEvent);}
@Mod.EventHandler public void onServerStarted (FMLServerStartedEvent aEvent) {onModServerStarted(aEvent);}
@Mod.EventHandler public void onServerStopping (FMLServerStoppingEvent aEvent) {onModServerStopping(aEvent);}
@Mod.EventHandler public void onServerStopped (FMLServerStoppedEvent aEvent) {onModServerStopped(aEvent);}
}
| 0 | 0.902505 | 1 | 0.902505 | game-dev | MEDIA | 0.837246 | game-dev | 0.953563 | 1 | 0.953563 |
MrsRina/onepop | 3,894 | src/main/java/rina/onepop/club/client/module/misc/bettermine/ModuleBetterMine.java | package rina.onepop.club.client.module.misc.bettermine;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import rina.onepop.club.api.module.Module;
import rina.onepop.club.api.module.impl.ModuleCategory;
import rina.onepop.club.api.module.registry.Registry;
import rina.onepop.club.api.setting.value.ValueColor;
import rina.onepop.club.api.setting.value.ValueNumber;
import rina.onepop.club.api.util.render.RenderUtil;
import rina.onepop.club.client.event.client.RunTickEvent;
import rina.onepop.club.client.event.entity.PlayerDamageBlockEvent;
import team.stiff.pomelo.impl.annotated.handler.annotation.Listener;
import java.awt.*;
/**
* @author SrRina
* @since 15/01/2022 at 23:41
**/
@Registry(name = "Better Mine", tag = "BetterMine", description = "Improve mining at game.", category = ModuleCategory.MISC)
public class ModuleBetterMine extends Module {
public static ModuleBetterMine INSTANCE;
/* Misc */
public static ValueNumber settingOffTicksInteger = new ValueNumber("Off Ticks", "OffTicks", "Ticks you do not send packets.", 23, 0, 100);
public static ValueNumber settingUpdateDistance = new ValueNumber("Distance", "Distance", "Distance to stop break.", 4.5, 2.0, 6.0);
public static ValueColor settingQueueColor = new ValueColor("Queue", "Queue", "Sets queue color.", Color.red);
public static ValueColor settingBreakColor = new ValueColor("Break", "Break", "Sets break color.", Color.green);
/*
* Processor to break block.
*/
protected BlockBreakProcessor processor;
/*
* Add blocks in a queue and adorable manage them.
*/
protected BlockEventCollector collector;
public ModuleBetterMine() {
INSTANCE = this;
this.onInit();
}
public void onInit() {
this.processor = new BlockBreakProcessor(this);
this.collector = new BlockEventCollector(this);
}
public BlockEventCollector getCollector() {
return collector;
}
@Listener
public void onBlockDamageEvent(PlayerDamageBlockEvent event) {
IBlockState state = mc.world.getBlockState(event.getPos());
Block block = state.getBlock();
float hardness = state.getBlockHardness(mc.world, event.getPos());
if (hardness == -1f || block == Blocks.WEB || block == Blocks.AIR) {
return;
}
this.collector.add(event);
}
@Override
public void onRender3D() {
if (mc.player == null || mc.world == null || this.collector.getCurrentEvent() == null) {
return;
}
for (PlayerDamageBlockEvent event : this.collector.getQueue()) {
if (mc.world.getBlockState(event.getPos()).getBlock() == Blocks.AIR) {
continue;
}
if (event == this.collector.getCurrentEvent()) {
RenderUtil.drawSolidBlock(camera, event.getPos(), settingBreakColor.getColor());
} else {
RenderUtil.drawSolidBlock(camera, event.getPos(), settingQueueColor.getColor());
}
}
}
@Listener
public void onTick(RunTickEvent event) {
if (mc.player == null || mc.world == null) {
return;
}
if (this.collector.getCurrentEvent() != null && (this.processor.getBreakingBlockPosition() == null || !this.collector.contains(this.processor.getBreakingBlockPosition()))) {
this.processor.setBreaking(this.collector.getCurrentEvent().getPos(), mc.world.getBlockState(this.collector.getCurrentEvent().getPos()).getBlock(), this.collector.getCurrentEvent().getFacing());
}
this.processor.onUpdate();
this.collector.onUpdate();
}
} | 0 | 0.937132 | 1 | 0.937132 | game-dev | MEDIA | 0.978499 | game-dev | 0.967136 | 1 | 0.967136 |
sandstorm/serious-game-legacy | 1,209 | app/src/CoreGameLogic/Feature/Spielzug/State/ModifierCalculator.php | <?php
declare(strict_types=1);
namespace Domain\CoreGameLogic\Feature\Spielzug\State;
use Domain\CoreGameLogic\EventStore\GameEvents;
use Domain\CoreGameLogic\Feature\Spielzug\Event\Behavior\ProvidesModifiers;
use Domain\CoreGameLogic\Feature\Spielzug\Modifier\ModifierCollection;
use Domain\CoreGameLogic\PlayerId;
class ModifierCalculator
{
private function __construct(private GameEvents $stream)
{
}
public static function forStream(GameEvents $stream): self
{
return new self($stream);
}
public function forPlayer(PlayerId $playerId): ModifierCollection
{
return $this->stream->findAllOfType(ProvidesModifiers::class)->reduce(function (ModifierCollection $state, ProvidesModifiers $event) use ($playerId) {
return $state->withAdditional($event->getModifiers($playerId));
}, new ModifierCollection([]));
}
public function withoutPlayer(): ModifierCollection
{
return $this->stream->findAllOfType(ProvidesModifiers::class)->reduce(function (ModifierCollection $state, ProvidesModifiers $event) {
return $state->withAdditional($event->getModifiers());
}, new ModifierCollection([]));
}}
| 0 | 0.838936 | 1 | 0.838936 | game-dev | MEDIA | 0.965484 | game-dev | 0.775562 | 1 | 0.775562 |
liquidbounceplusreborn/LiquidbouncePlus-Reborn | 17,360 | src/main/java/net/ccbluex/liquidbounce/features/module/modules/movement/Step.kt | /*
* LiquidBounce+ Hacked Client
* A free open source mixin-based injection hacked client for Minecraft using Minecraft Forge.
* https://github.com/WYSI-Foundation/LiquidBouncePlus/
*/
package net.ccbluex.liquidbounce.features.module.modules.movement
import net.ccbluex.liquidbounce.LiquidBounce
import net.ccbluex.liquidbounce.event.*
import net.ccbluex.liquidbounce.features.module.Module
import net.ccbluex.liquidbounce.features.module.ModuleCategory
import net.ccbluex.liquidbounce.features.module.ModuleInfo
import net.ccbluex.liquidbounce.features.module.modules.exploit.Phase
import net.ccbluex.liquidbounce.utils.MovementUtils
import net.ccbluex.liquidbounce.utils.timer.MSTimer
import net.ccbluex.liquidbounce.value.FloatValue
import net.ccbluex.liquidbounce.value.IntegerValue
import net.ccbluex.liquidbounce.value.ListValue
import net.minecraft.network.play.client.C03PacketPlayer
import net.minecraft.stats.StatList
import net.minecraft.util.MathHelper
import kotlin.math.ceil
import kotlin.math.cos
import kotlin.math.sin
@ModuleInfo(name = "Step", description = "Allows you to step up blocks.", category = ModuleCategory.MOVEMENT)
class Step : Module() {
/**
* OPTIONS
*/
private val modeValue = ListValue("Mode", arrayOf(
"Vanilla", "Jump","NCPPacket", "NCP", "MotionNCP", "OldNCP", "Vulcan","Verus","NewNCP","AAC", "LAAC", "AAC3.3.4", "Spartan", "Rewinside", "1.5Twillight",
), "NCP")
private val heightValue = FloatValue("Height", 1F, 0.6F, 10F)
private val timerValue = FloatValue("Timer", 1F, 0.3F, 10F, "x")
private val jumpHeightValue = FloatValue("JumpHeight", 0.42F, 0.37F, 0.42F)
private val delayValue = IntegerValue("Delay", 0, 0, 500, "ms")
/**
* VALUES
*/
private var isStep = false
private var stepX = 0.0
private var stepY = 0.0
private var stepZ = 0.0
private var ncpNextStep = 0
private var spartanSwitch = false
private var isAACStep = false
private var ticks = 0
private val timer = MSTimer()
private var usedTimer = false
private val ncp1Values = arrayOf(0.425, 0.821, 0.699, 0.599, 1.022, 1.372, 1.652, 1.869, 2.019, 1.919)
private val ncp2Values = arrayOf(0.42, 0.7532, 1.01, 1.093, 1.015)
override fun onDisable() {
mc.thePlayer ?: return
// Change step height back to default (0.5 is default)
mc.thePlayer.stepHeight = 0.5F
mc.timer.timerSpeed = 1.0F
mc.thePlayer.speedInAir = 0.02F
}
@EventTarget
fun onUpdate(event: UpdateEvent) {
if (usedTimer) {
mc.timer.timerSpeed = 1F
usedTimer = false
}
val mode = modeValue.get()
// Motion steps
when {
mode.equals("jump", true) && mc.thePlayer.isCollidedHorizontally && mc.thePlayer.onGround
&& !mc.gameSettings.keyBindJump.isKeyDown -> {
fakeJump()
mc.thePlayer.motionY = jumpHeightValue.get().toDouble()
}
mode.equals("laac", true) -> if (mc.thePlayer.isCollidedHorizontally && !mc.thePlayer.isOnLadder
&& !mc.thePlayer.isInWater && !mc.thePlayer.isInLava && !mc.thePlayer.isInWeb) {
if (mc.thePlayer.onGround && timer.hasTimePassed(delayValue.get().toLong())) {
isStep = true
fakeJump()
mc.thePlayer.motionY += 0.620000001490116
val f = mc.thePlayer.rotationYaw * 0.017453292F
mc.thePlayer.motionX -= MathHelper.sin(f) * 0.2
mc.thePlayer.motionZ += MathHelper.cos(f) * 0.2
timer.reset()
}
mc.thePlayer.onGround = true
} else
isStep = false
mode.equals("aac3.3.4", true) -> if (mc.thePlayer.isCollidedHorizontally
&& MovementUtils.isMoving()) {
if (mc.thePlayer.onGround && couldStep()) {
mc.thePlayer.motionX *= 1.26
mc.thePlayer.motionZ *= 1.26
mc.thePlayer.jump()
isAACStep = true
}
if (isAACStep) {
mc.thePlayer.motionY -= 0.015
if (!mc.thePlayer.isUsingItem && mc.thePlayer.movementInput.moveStrafe == 0F)
mc.thePlayer.jumpMovementFactor = 0.3F
}
} else
isAACStep = false
mode.equals("1.5Twillight", true) -> if (MovementUtils.isMoving() &&
mc.thePlayer.isCollidedHorizontally) {
ticks++
if (ticks == 1) mc.thePlayer.motionY = 0.4399
if (ticks == 12) mc.thePlayer.motionY = 0.4399
if (ticks >= 40) ticks = 0
} else if (mc.thePlayer.onGround) {
ticks = 0
}
}
}
@EventTarget
fun onMove(event: MoveEvent) {
val mode = modeValue.get()
// Motion steps
when {
mode.equals("motionncp", true) && mc.thePlayer.isCollidedHorizontally && !mc.gameSettings.keyBindJump.isKeyDown -> {
when {
mc.thePlayer.onGround && couldStep() -> {
fakeJump()
mc.thePlayer.motionY = 0.0
event.y = 0.41999998688698
ncpNextStep = 1
}
ncpNextStep == 1 -> {
event.y = 0.7531999805212 - 0.41999998688698
ncpNextStep = 2
}
ncpNextStep == 2 -> {
val yaw = MovementUtils.getDirection()
event.y = 1.001335979112147 - 0.7531999805212
event.x = -sin(yaw) * 0.7
event.z = cos(yaw) * 0.7
ncpNextStep = 0
}
}
}
}
}
@EventTarget
fun onStep(event: StepEvent) {
mc.thePlayer ?: return
val phaseMod = LiquidBounce.moduleManager.getModule(Phase::class.java)!!
// Phase should disable step (except hypixel one)
if (phaseMod.state && !phaseMod.modeValue.get().equals("hypixel", true)) {
event.stepHeight = 0F
return
}
// Some fly modes should disable step
val fly = LiquidBounce.moduleManager[Fly::class.java] as Fly
if (fly.state) {
val flyMode = fly.modeValue.get()
if (flyMode.equals("Rewinside", true)) {
event.stepHeight = 0F
return
}
}
val mode = modeValue.get()
// Set step to default in some cases
if (!mc.thePlayer.onGround || !timer.hasTimePassed(delayValue.get().toLong()) ||
mode.equals("Jump", true) || mode.equals("MotionNCP", true)
|| mode.equals("LAAC", true) || mode.equals("AAC3.3.4", true)
|| mode.equals("AACv4", true) || mode.equals("1.5Twillight", true)) {
mc.thePlayer.stepHeight = 0.5F
event.stepHeight = 0.5F
return
}
// Set step height
val height = heightValue.get()
mc.thePlayer.stepHeight = height
mc.timer.timerSpeed = timerValue.get()
usedTimer = true
event.stepHeight = height
// Detect possible step
if (event.stepHeight > 0.5F) {
isStep = true
stepX = mc.thePlayer.posX
stepY = mc.thePlayer.posY
stepZ = mc.thePlayer.posZ
}
}
@EventTarget(ignoreCondition = true)
fun onStepConfirm(event: StepConfirmEvent) {
if (mc.thePlayer == null || !isStep) // Check if step
return
if (mc.thePlayer.entityBoundingBox.minY - stepY > 0.5) { // Check if full block step
val mode = modeValue.get()
when {
mode.equals("NCPPacket", true) -> {
val rHeight = mc.thePlayer.entityBoundingBox.minY - stepY
when {
rHeight > 2.019 -> {
ncp1Values.forEach {
mc.netHandler.addToSendQueue(C03PacketPlayer.C04PacketPlayerPosition(stepX, stepY + it, stepZ, false))
}
mc.thePlayer.motionX = 0.0
mc.thePlayer.motionZ = 0.0
}
rHeight > 1.869 -> {
for (i in 0..7)
mc.netHandler.addToSendQueue(C03PacketPlayer.C04PacketPlayerPosition(stepX, stepY + ncp1Values[i], stepZ, false))
mc.thePlayer.motionX = 0.0
mc.thePlayer.motionZ = 0.0
}
rHeight > 1.5 -> {
for (i in 0..6)
mc.netHandler.addToSendQueue(C03PacketPlayer.C04PacketPlayerPosition(stepX, stepY + ncp1Values[i], stepZ, false))
mc.thePlayer.motionX = 0.0
mc.thePlayer.motionZ = 0.0
}
rHeight > 1.015 -> {
ncp2Values.forEach {
mc.netHandler.addToSendQueue(C03PacketPlayer.C04PacketPlayerPosition(stepX, stepY + it, stepZ, false))
}
mc.thePlayer.motionX = 0.0
mc.thePlayer.motionZ = 0.0
}
rHeight > 0.875 -> {
mc.netHandler.addToSendQueue(C03PacketPlayer.C04PacketPlayerPosition(stepX,
stepY + 0.41999998688698, stepZ, false))
mc.netHandler.addToSendQueue(C03PacketPlayer.C04PacketPlayerPosition(stepX,
stepY + 0.7531999805212, stepZ, false))
mc.thePlayer.motionX = 0.0
mc.thePlayer.motionZ = 0.0
}
rHeight > 0.6 -> {
mc.netHandler.addToSendQueue(C03PacketPlayer.C04PacketPlayerPosition(stepX,
stepY + 0.39, stepZ, false))
mc.netHandler.addToSendQueue(C03PacketPlayer.C04PacketPlayerPosition(stepX,
stepY + 0.6938, stepZ, false))
mc.thePlayer.motionX = 0.0
mc.thePlayer.motionZ = 0.0
}
}
}
mode.equals("NCP", true) || mode.equals("AAC", true) -> {
fakeJump()
// Half legit step (1 packet missing) [COULD TRIGGER TOO MANY PACKETS]
mc.netHandler.addToSendQueue(C03PacketPlayer.C04PacketPlayerPosition(stepX,
stepY + 0.41999998688698, stepZ, false))
mc.netHandler.addToSendQueue(C03PacketPlayer.C04PacketPlayerPosition(stepX,
stepY + 0.7531999805212, stepZ, false))
timer.reset()
}
mode.equals("Spartan", true) -> {
fakeJump()
if (spartanSwitch) {
// Vanilla step (3 packets) [COULD TRIGGER TOO MANY PACKETS]
mc.netHandler.addToSendQueue(C03PacketPlayer.C04PacketPlayerPosition(stepX,
stepY + 0.41999998688698, stepZ, false))
mc.netHandler.addToSendQueue(C03PacketPlayer.C04PacketPlayerPosition(stepX,
stepY + 0.7531999805212, stepZ, false))
mc.netHandler.addToSendQueue(C03PacketPlayer.C04PacketPlayerPosition(stepX,
stepY + 1.001335979112147, stepZ, false))
} else // Force step
mc.netHandler.addToSendQueue(C03PacketPlayer.C04PacketPlayerPosition(stepX,
stepY + 0.6, stepZ, false))
// Spartan allows one unlegit step so just swap between legit and unlegit
spartanSwitch = !spartanSwitch
// Reset timer
timer.reset()
}
mode.equals("Rewinside", true) -> {
fakeJump()
// Vanilla step (3 packets) [COULD TRIGGER TOO MANY PACKETS]
mc.netHandler.addToSendQueue(C03PacketPlayer.C04PacketPlayerPosition(stepX,
stepY + 0.41999998688698, stepZ, false))
mc.netHandler.addToSendQueue(C03PacketPlayer.C04PacketPlayerPosition(stepX,
stepY + 0.7531999805212, stepZ, false))
mc.netHandler.addToSendQueue(C03PacketPlayer.C04PacketPlayerPosition(stepX,
stepY + 1.001335979112147, stepZ, false))
// Reset timer
timer.reset()
}
mode.equals("Vulcan", true) -> {
val rstepHeight = mc.thePlayer.entityBoundingBox.minY - stepY
fakeJump()
when {
rstepHeight > 2.0 -> {
val stpPacket = arrayOf(0.5, 1.0, 1.5, 2.0)
stpPacket.forEach {
mc.thePlayer.sendQueue.addToSendQueue(C03PacketPlayer.C04PacketPlayerPosition(stepX,
stepY + it, stepZ, true))
}
}
rstepHeight <= 2.0 && rstepHeight > 1.5 -> {
val stpPacket = arrayOf(0.5, 1.0, 1.5)
stpPacket.forEach {
mc.thePlayer.sendQueue.addToSendQueue(C03PacketPlayer.C04PacketPlayerPosition(stepX,
stepY + it, stepZ, true))
}
}
rstepHeight <= 1.5 && rstepHeight > 1.0 -> {
val stpPacket = arrayOf(0.5, 1.0)
stpPacket.forEach {
mc.thePlayer.sendQueue.addToSendQueue(C03PacketPlayer.C04PacketPlayerPosition(stepX,
stepY + it, stepZ, true))
}
}
rstepHeight <= 1.0 && rstepHeight > 0.6 -> {
val stpPacket = arrayOf(0.5)
stpPacket.forEach {
mc.thePlayer.sendQueue.addToSendQueue(C03PacketPlayer.C04PacketPlayerPosition(stepX,
stepY + it, stepZ, true))
}
}
}
timer.reset()
}
mode.equals("Verus", true) -> {
val rstepHeight = mc.thePlayer.entityBoundingBox.minY - stepY
mc.timer.timerSpeed = 1f / ceil(rstepHeight * 2.0).toFloat()
var stpHight = 0.0
fakeJump()
repeat ((ceil(rstepHeight * 2.0) - 1.0).toInt()) {
stpHight += 0.5
mc.thePlayer.sendQueue.addToSendQueue(C03PacketPlayer.C04PacketPlayerPosition(stepX, stepY + stpHight, stepZ, true))
}
timer.reset()
}
mode.equals("NewNCP",true) -> {
fakeJump()
mc.netHandler.addToSendQueue(C03PacketPlayer.C04PacketPlayerPosition(stepX,
stepY + 0.41999998688698, stepZ, false))
mc.netHandler.addToSendQueue(C03PacketPlayer.C04PacketPlayerPosition(stepX,
stepY + 0.7531999805212, stepZ, false))
mc.netHandler.addToSendQueue(C03PacketPlayer.C04PacketPlayerPosition(stepX,
stepY + 1, stepZ, true))
// Reset timer
timer.reset()
}
}
}
isStep = false
stepX = 0.0
stepY = 0.0
stepZ = 0.0
}
@EventTarget(ignoreCondition = true)
fun onPacket(event: PacketEvent) {
val packet = event.packet
if (packet is C03PacketPlayer && isStep && modeValue.get().equals("OldNCP", true)) {
packet.y += 0.07
isStep = false
}
}
// There could be some anti cheats which tries to detect step by checking for achievements and stuff
private fun fakeJump() {
mc.thePlayer.isAirBorne = true
mc.thePlayer.triggerAchievement(StatList.jumpStat)
}
private fun couldStep(): Boolean {
val yaw = MovementUtils.getDirection()
val x = -sin(yaw) * 0.4
val z = cos(yaw) * 0.4
return mc.theWorld.getCollisionBoxes(mc.thePlayer.entityBoundingBox.offset(x, 1.001335979112147, z))
.isEmpty()
}
override val tag: String
get() = modeValue.get()
}
| 0 | 0.883379 | 1 | 0.883379 | game-dev | MEDIA | 0.897214 | game-dev | 0.974969 | 1 | 0.974969 |
latte-soft/builtinplugins | 1,891 | src/BuiltInPlugins/EventEmulator/Src/Components/RepopulatableHistory.luau | local l_Parent_0 = script.Parent.Parent.Parent;
local v1 = require(l_Parent_0.Packages.Roact);
local v2 = require(l_Parent_0.Packages.RoactRodux);
local v3 = require(l_Parent_0.Packages.Framework);
local l_ContextServices_0 = v3.ContextServices;
local l_withContext_0 = l_ContextServices_0.withContext;
local v6 = require(l_Parent_0.Src.Components.RepopulatableHistoryItem);
local l_UI_0 = v3.UI;
local l_Pane_0 = l_UI_0.Pane;
local l_TextLabel_0 = l_UI_0.TextLabel;
local l_ScrollingFrame_0 = l_UI_0.ScrollingFrame;
local v11 = v1.PureComponent:extend("RepopulatableHistory");
v11.init = function(v12)
v12.createChildren = function()
local l_props_0 = v12.props;
local l_HistoryItems_0 = l_props_0.HistoryItems;
local v15 = {
Layout = v1.createElement("UIListLayout", l_props_0.Stylizer.Layout.Vertical.Vertical)
};
for _, v17 in pairs(l_HistoryItems_0) do
table.insert(v15, 1, v1.createElement(v6, {
View = v17.View,
Name = v17.Name,
Data = v17.Data
}));
end;
return v15;
end;
end;
v11.render = function(v18)
return v1.createElement(l_Pane_0, {
Style = "RoundBox",
Layout = Enum.FillDirection.Vertical
}, {
Header = v1.createElement(l_TextLabel_0, {
AutomaticSize = Enum.AutomaticSize.Y,
TextXAlignment = Enum.TextXAlignment.Center,
Style = "Bold",
Text = "History"
}),
ScrollingContainer = v1.createElement(l_ScrollingFrame_0, {
Size = UDim2.new(1, 0, 1, -v18.props.Stylizer.Text.BrightText.Size)
}, v18.createChildren())
});
end;
return v2.connect(function(v19, _)
return {
HistoryItems = v19.History.HistoryItems
};
end)((l_withContext_0({
Stylizer = l_ContextServices_0.Stylizer
})(v11)));
| 0 | 0.848479 | 1 | 0.848479 | game-dev | MEDIA | 0.512433 | game-dev | 0.968542 | 1 | 0.968542 |
Community-A-4E/community-a4e-c | 23,152 | A-4E-C/Cockpit/Scripts/ControlsIndicator/ControlsIndicator_page.lua | dofile(LockOn_Options.common_script_path.."elements_defs.lua")
dofile(LockOn_Options.script_path.."EFM_Data_Bus.lua")
dofile(LockOn_Options.script_path.."/ControlsIndicator/ControlsIndicator_api.lua")
-- set color values are r, g, b, a, with a min-max of 0, 255
local draw_background = MakeMaterial("arcade.tga", {128, 0, 0, 128})
local draw_transparent = MakeMaterial("arcade.tga", {0, 0, 0, 0})
local draw_percentile = MakeMaterial("arcade.tga", {255, 0, 0, 32})
local draw_percentile_strong = MakeMaterial("arcade.tga", {255, 0, 0, 128})
local draw_axis = MakeMaterial("arcade.tga", {255, 0, 0, 255})
local draw_hidden = MakeMaterial("arcade.tga", {255, 0, 0, 0})
local draw_input = MakeMaterial("arcade.tga", {255, 255, 0, 255})
local draw_indicator = MakeMaterial("arcade.tga", {255, 0, 0, 255})
local draw_gear = MakeMaterial("arcade.tga", {255, 0, 0, 255})
local draw_debug = MakeMaterial("arcade.tga", {0, 255, 255, 255})
local draw_on = MakeMaterial("arcade.tga", {128, 0, 0, 255})
local draw_off = MakeMaterial("arcade.tga", {255, 0, 0, 255})
SetCustomScale(1.0)
function AddElement(object)
object.screenspace = ScreenType.SCREENSPACE_TRUE
object.use_mipfilter = true
Add(object)
end
local aspect = LockOn_Options.screen.aspect
local sizeX = 0.15
local sizeY = 0.2
local tex_scale = 0.25 / sizeX
local ds = 0.05 * sizeX
local line_width = (4.5 / 512) / tex_scale
local throttle_offset = 5.0 * ds
local rudder_offset = 3.0 * ds
local stick_index_sz = 0.1 * sizeX
-- =============================
-- BACKGROUND
-- =============================
-- draw BACKGROUND
base = CreateElement "ceMeshPoly"
base.name = "base"
base.primitivetype = "triangles"
base.material = draw_background
base.vertices = {
{-(sizeX + throttle_offset + rudder_offset + 3.0 * line_width + ds), -sizeY},
{-(sizeX + throttle_offset + rudder_offset + 3.0 * line_width + ds), sizeY},
{sizeX + ds, sizeY},
{sizeX + ds, -sizeY}
}
base.indices = default_box_indices
base.init_pos = {(-1 * aspect + 1.5 * sizeX), -(1 - 1.3 * sizeX)}
base.element_params = {"SHOW_CONTROLS"}
base.controllers = {{"parameter_in_range", 0, 1}}
base.h_clip_relation = h_clip_relations.REWRITE_LEVEL
base.level = 8
AddElement(base)
-- =================================
-- AXES ands GRIDS
-- =================================
-- scale PITCH
pitch_scale = CreateElement "ceTexPoly"
pitch_scale.name = "pitch_scale"
pitch_scale.init_pos = {-1.0 * ds, 3.0 * ds}
pitch_scale.vertices = {
{-sizeX,-line_width},
{-sizeX, line_width},
{sizeX, line_width},
{sizeX, -line_width}
}
pitch_scale.indices = default_box_indices
pitch_scale.material = draw_axis
pitch_scale.init_rot = {90, 0, 0}
pitch_scale.tex_params = {256 / 512, 176.5 / 512, 0.5 * tex_scale, 2 * tex_scale}
pitch_scale.parent_element = base.name
AddElement(pitch_scale)
-- scale PITCH PERCENTILE grid
pitch_scale_p100 = Copy(pitch_scale)
pitch_scale_p100.vertices = {
{0, -0.5 * line_width},
{0, 0.5 * line_width},
{2.0 * sizeX, 0.5 * line_width},
{2.0 * sizeX, -0.5 * line_width}
}
pitch_scale_p100.init_pos = {1.00 * sizeX, -sizeX}
pitch_scale_p100.material = draw_percentile_strong
pitch_scale_p100.parent_element = pitch_scale.name
AddElement(pitch_scale_p100)
pitch_scale_p075 = Copy(pitch_scale_p100)
pitch_scale_p075.init_pos = {0.75 * sizeX, -sizeX}
pitch_scale_p075.material = draw_percentile
AddElement(pitch_scale_p075)
pitch_scale_p050 = Copy(pitch_scale_p100)
pitch_scale_p050.init_pos = {0.50 * sizeX, -sizeX}
pitch_scale_p050.material = draw_percentile_strong
AddElement(pitch_scale_p050)
pitch_scale_p025 = Copy(pitch_scale_p100)
pitch_scale_p025.init_pos = {0.25 * sizeX, -sizeX}
pitch_scale_p025.material = draw_percentile
AddElement(pitch_scale_p025)
pitch_scale_n100 = Copy(pitch_scale_p100)
pitch_scale_n100.init_pos = {-1.00 * sizeX, -sizeX}
pitch_scale_n100.material = draw_percentile_strong
AddElement(pitch_scale_n100)
pitch_scale_n075 = Copy(pitch_scale_p100)
pitch_scale_n075.init_pos = {-0.75 * sizeX, -sizeX}
pitch_scale_n075.material = draw_percentile
AddElement(pitch_scale_n075)
pitch_scale_n050 = Copy(pitch_scale_p100)
pitch_scale_n050.init_pos = {-0.50 * sizeX, -sizeX}
pitch_scale_p100.material = draw_percentile_strong
AddElement(pitch_scale_n050)
pitch_scale_n025 = Copy(pitch_scale_p100)
pitch_scale_n025.init_pos = {-0.25 * sizeX, -sizeX}
pitch_scale_n025.material = draw_percentile
AddElement(pitch_scale_n025)
-- scale ROLL
roll_scale = Copy(pitch_scale)
roll_scale.name = "roll_scale"
roll_scale.init_pos = {0, 0}
roll_scale.init_rot = {90, 0, 0}
roll_scale.parent_element = pitch_scale.name
AddElement(roll_scale)
-- scale ROLL PERCENTILE grid
roll_scale_p100 = Copy(roll_scale)
pitch_scale_p100.vertices = {
{0, -0.5 * line_width},
{0, 0.5 * line_width},
{2.0 * sizeX, 0.5 * line_width},
{2.0 * sizeX, -0.5 * line_width}
}
roll_scale_p100.init_pos = {-(1.00 * sizeX), 0}
roll_scale_p100.init_rot = {90, 0, 0}
roll_scale_p100.material = draw_percentile_strong
roll_scale_p100.parent_element = roll_scale.name
AddElement(roll_scale_p100)
roll_scale_p075 = Copy(roll_scale_p100)
roll_scale_p075.init_pos = {-(0.75 * sizeX), 0}
roll_scale_p075.material = draw_percentile
AddElement(roll_scale_p075)
roll_scale_p050 = Copy(roll_scale_p100)
roll_scale_p050.init_pos = {-(0.50 * sizeX), 0}
roll_scale_p050.material = draw_percentile_strong
AddElement(roll_scale_p050)
roll_scale_p025 = Copy(roll_scale_p100)
roll_scale_p025.init_pos = {-(0.25 * sizeX), 0}
roll_scale_p025.material = draw_percentile
AddElement(roll_scale_p025)
roll_scale_n025 = Copy(roll_scale_p100)
roll_scale_n025.init_pos = {(0.25 * sizeX), 0}
roll_scale_n025.material = draw_percentile
AddElement(roll_scale_n025)
roll_scale_n050 = Copy(roll_scale_p100)
roll_scale_n050.init_pos = {(0.50 * sizeX), 0}
roll_scale_n050.material = draw_percentile_strong
AddElement(roll_scale_n050)
roll_scale_n075 = Copy(roll_scale_p100)
roll_scale_n075.init_pos = {(0.75 * sizeX), 0}
roll_scale_n075.material = draw_percentile
AddElement(roll_scale_n075)
roll_scale_n100 = Copy(roll_scale_p100)
roll_scale_n100.init_pos = {(1.00 * sizeX), 0}
roll_scale_n100.material = draw_percentile_strong
AddElement(roll_scale_n100)
-- scale THROTTLE
throttle_scale = Copy(pitch_scale)
throttle_scale.vertices = {
{0, -line_width},
{0, line_width},
{2.0 * sizeX, line_width},
{2.0 * sizeX, -line_width}
}
throttle_scale.init_pos = {-sizeX, (sizeX + throttle_offset)}
throttle_scale.init_rot = {0, 0, 0}
throttle_scale.parent_element = pitch_scale.name
AddElement(throttle_scale)
-- =============================
-- INDICATORS
-- =============================
-- draw GEAR NOSE position
gearc_index = Copy(roll_scale)
gearc_index.vertices = {
{-4.0 * line_width, -5.0 * line_width},
{-4.0 * line_width, 5.0 * line_width},
{4.0 * line_width, 5.0 * line_width},
{4.0 * line_width, -5.0 * line_width}
}
gearc_index.element_params = {"FM_GEAR_NOSE"}
gearc_index.controllers = {{"move_up_down_using_parameter", sizeX, sizeX}}
gearc_index.tex_params = {256 / 512, 176.5 / 512, 0.5 * tex_scale / 3, 2 * tex_scale / 3}
gearc_index.init_rot = {-90, 0, 0}
gearc_index.material = draw_gear
gearc_index.parent_element = pitch_scale.name
AddElement(gearc_index)
-- draw GEAR LEFT position
gearl_index = Copy(gearc_index)
gearl_index.element_params = {"FM_GEAR_LEFT"}
gearl_index.init_pos = {0, (0.50 * sizeX)}
gearl_index.controllers = {{"move_up_down_using_parameter", -sizeX, -sizeX}}
AddElement(gearl_index)
-- draw GEAR RIGHT position
gearr_index = Copy(gearc_index)
gearr_index.element_params = {"FM_GEAR_RIGHT"}
gearr_index.init_pos = {0, -(0.50 * sizeX)}
gearr_index.controllers = {{"move_up_down_using_parameter", -sizeX, -sizeX}}
AddElement(gearr_index)
-- draw SLAT LEFT position
slatl_index = Copy(roll_scale)
slatl_index.vertices = {
{-2.5 * line_width, -2.5 * line_width},
{-2.5 * line_width, 2.5 * line_width},
{2.5 * line_width, 2.5 * line_width},
{2.5 * line_width, -2.5 * line_width}
}
slatl_index.element_params = {"FM_SLAT_LEFT"}
slatl_index.init_pos = {-sizeX, sizeX}
slatl_index.controllers = {{"move_up_down_using_parameter", 0, 2.0 * sizeX}}
slatl_index.tex_params = {179.5 / 512, 256.5 / 512, 3 * tex_scale, 3 * tex_scale}
slatl_index.init_rot = {-90, 0, 0}
slatl_index.material = draw_gear
slatl_index.parent_element = pitch_scale.name
AddElement(slatl_index)
-- draw SLAT RIGHT position
slatr_index = Copy(slatl_index)
slatr_index.element_params = {"FM_SLAT_RIGHT"}
slatr_index.init_pos = {-sizeX, -sizeX}
AddElement(slatr_index)
-- draw GEAR NOSE position
gearc_index = Copy(roll_scale)
gearc_index.vertices = {
{-4.0 * line_width, -5.0 * line_width},
{-4.0 * line_width, 5.0 * line_width},
{4.0 * line_width, 5.0 * line_width},
{4.0 * line_width, -5.0 * line_width}
}
gearc_index.element_params = {"FM_GEAR_NOSE"}
gearc_index.controllers = {{"move_up_down_using_parameter", sizeX, sizeX}}
gearc_index.tex_params = {256 / 512, 176.5 / 512, 0.5 * tex_scale / 3, 2 * tex_scale / 3}
gearc_index.init_rot = {-90, 0, 0}
gearc_index.material = draw_gear
gearc_index.parent_element = pitch_scale.name
AddElement(gearc_index)
-- draw FLAPS position
flaps_index = Copy(pitch_scale)
flaps_index.init_pos = {0, 0}
flaps_index.element_params = {"FM_FLAPS"}
flaps_index.controllers = {{"move_up_down_using_parameter", 0, -sizeX}}
flaps_index.init_rot = {-90, 0, 0}
flaps_index.material = draw_indicator
flaps_index.parent_element = pitch_scale.name
AddElement(flaps_index)
-- draw SPOILER position
spoiler_index = Copy(flaps_index)
spoiler_index.element_params = {"FM_SPOILERS"}
spoiler_index.init_rot = {90, 0, 0}
AddElement(spoiler_index)
-- draw AIRBRAKE1 position
abrake1_index = Copy(roll_scale)
abrake1_index.init_pos = {0, 0}
abrake1_index.element_params = {"FM_BRAKES"}
abrake1_index.controllers = {{"move_up_down_using_parameter", 0, sizeX}}
abrake1_index.init_rot = {-90, 0, 0}
abrake1_index.material = draw_indicator
abrake1_index.parent_element = roll_scale.name
AddElement(abrake1_index)
abrake2_index = Copy(abrake1_index)
abrake2_index.init_rot = {90, 0, 0}
AddElement(abrake2_index)
-- draw RPM position
rpm_index = Copy(roll_scale)
rpm_index.vertices = {
{-4.0 * line_width, -5.0 * line_width},
{-4.0 * line_width, 5.0 * line_width},
{4.0 * line_width, 5.0 * line_width},
{4.0 * line_width, -5.0 * line_width}
}
rpm_index.element_params = {"RPM"}
rpm_index.controllers = {{"move_up_down_using_parameter", 0, sizeX / 50}}
rpm_index.tex_params = {256 / 512, 176.5 / 512, 0.5 * tex_scale / 3, 2 * tex_scale / 3}
rpm_index.init_rot = {-90, 0, 0}
rpm_index.material = draw_indicator
rpm_index.parent_element = throttle_scale.name
AddElement(rpm_index)
-- =============================
-- INPUT INDICATORS
-- =============================
-- scale WHEELBRAKE LEFT position
wbrakel_scale = Copy(pitch_scale)
wbrakel_scale.vertices = {
{0.0, -line_width},
{0.0, line_width},
{2.0 * sizeX, line_width},
{2.0 * sizeX, -line_width}
}
wbrakel_scale.init_pos = {-sizeX, -0.5 * sizeX}
wbrakel_scale.init_rot = {0, 0, 0}
wbrakel_scale.material = draw_transparent
wbrakel_scale.parent_element = pitch_scale.name
AddElement(wbrakel_scale)
-- scale WHEELBRAKE RIGHT position
wbraker_scale = Copy(wbrakel_scale)
wbrakel_scale.init_pos = {-sizeX, 0.5 * sizeX}
AddElement(wbraker_scale)
-- draw WHEELBRAKE LEFT position
wbrakel_index = Copy(roll_scale)
wbrakel_index.vertices = {
{-2.0 * line_width, -line_width},
{-2.0 * line_width, line_width},
{2.0 * line_width, line_width},
{2.0 * line_width, -line_width}
}
wbrakel_index.element_params = {"LEFT_BRAKE_PEDAL"}
wbrakel_index.controllers = {{"move_up_down_using_parameter", 0, 2.0 * sizeX}}
wbrakel_index.tex_params = {256 / 512, 176.5 / 512, 0.5 * tex_scale / 3, 2 * tex_scale / 3}
wbrakel_index.init_rot = {-90, 0, 0}
wbrakel_index.material = draw_input
wbrakel_index.parent_element = wbrakel_scale.name
AddElement(wbrakel_index)
-- draw WHEELBRAKE RIGHT position
wbraker_index = Copy(wbrakel_index)
wbraker_index.element_params = {"RIGHT_BRAKE_PEDAL"}
wbraker_index.parent_element = wbraker_scale.name
AddElement(wbraker_index)
-- draw THROTTLE STEP positions
throttle_pos1 = Copy(roll_scale)
throttle_pos1.vertices = {
{-2.25 * ds, -2.25 * ds},
{-2.25 * ds, 2.25 * ds},
{2.25 * ds, 2.25 * ds},
{2.25 * ds, -2.25 * ds}
}
throttle_pos1.init_pos = {-rudder_offset, 1.5 * ds}
throttle_pos1.tex_params = {179.5 / 512, 256.5 / 512, 3 * tex_scale, 3 * tex_scale}
throttle_pos1.init_rot = {0, 0, 0}
throttle_pos1.material = draw_axis
throttle_pos1.parent_element = throttle_scale.name
AddElement(throttle_pos1)
throttle_pos2 = Copy(throttle_pos1)
throttle_pos2.init_pos = {0, -1.0 * ds}
throttle_pos2.parent_element = throttle_pos1.name
AddElement(throttle_pos2)
throttle_pos3 = Copy(throttle_pos1)
throttle_pos3.init_pos = {0, -3.0 * ds}
throttle_pos3.parent_element = throttle_pos1.name
AddElement(throttle_pos3)
-- draw THROTTLE STEP status
throttle_p_index = Copy(throttle_pos1)
throttle_p_index.init_pos = {0, -3.0 * ds}
throttle_p_index.init_rot = {0, 0, 0}
throttle_p_index.material = draw_input
throttle_p_index.element_params = {ControlsIndicator_api.throttle_fm_step_param_string}
throttle_p_index.controllers = {{"move_up_down_using_parameter", 0, -3.0 * ds}}
throttle_p_index.parent_element = throttle_pos1.name
AddElement(throttle_p_index)
-- draw NOSEWHEEL CENTER position
nws_center = Copy(pitch_scale)
nws_center.vertices = {
{-2.25 * ds, -2.25 * ds},
{-2.25 * ds, 2.25 * ds},
{2.25 * ds, 2.25 * ds},
{2.25 * ds, -2.25 * ds}
}
nws_center.init_pos = {sizeX, 0}
nws_center.tex_params = {179.5 / 512, 256.5 / 512, 3 * tex_scale, 3 * tex_scale}
nws_center.init_rot = {0, 0, 0}
nws_center.material = draw_axis
nws_center.parent_element = pitch_scale.name
AddElement(nws_center)
-- draw NOSEWHEEL CASTER status
nosewheel_pos = Copy(nws_center)
nosewheel_pos.tex_params = {394.5 / 512, 256.5 / 512, 2 * tex_scale, 2 * tex_scale}
nosewheel_pos.material = draw_input
nosewheel_pos.element_params = {ControlsIndicator_api.nosewheel_pos_param_string}
nosewheel_pos.controllers = {{"move_up_down_using_parameter", 0, 1.5 * sizeX}}
AddElement(nosewheel_pos)
--[[
-- nosewheel steering indicator (deprecated)
nws_index = Copy(nws_center)
nws_index.init_pos = {-(sizeX + rudder_offset), 0}
nws_index.tex_params = {394.5 / 512, 256.5 / 512, 2 * tex_scale, 2 * tex_scale}
nws_index.init_rot = {-90, 0, 0}
nws_index.material = draw_input
nws_index.element_params = {"FM_NWS"}
nws_index.controllers = {{"move_up_down_using_parameter", 0, 2.0 * sizeX + rudder_offset}}
AddElement(nws_index)
nws_mask = Copy(nws_center)
nws_mask.init_pos = {-(sizeX + rudder_offset), 0}
AddElement(nws_mask)
]]
-- draw PITCH AND ROLL (STICK) position
stick_position = CreateElement "ceTexPoly"
stick_position.name = "stick_position"
stick_position.vertices = {
{-stick_index_sz, -stick_index_sz},
{-stick_index_sz, stick_index_sz},
{stick_index_sz, stick_index_sz},
{stick_index_sz, -stick_index_sz}
}
stick_position.indices = default_box_indices
stick_position.material = draw_input
stick_position.tex_params = {330 / 512, 365.5 / 512, 2 * tex_scale, 2 * tex_scale / 0.8}
stick_position.element_params = {"STICK_PITCH", "STICK_ROLL"}
stick_position.controllers = {
{"move_left_right_using_parameter", 1, sizeX},
{"move_up_down_using_parameter", 0, -sizeX}
}
stick_position.init_pos = {0, 0}
stick_position.init_rot = {-90, 0}
stick_position.parent_element = pitch_scale.name
AddElement(stick_position)
-- mark RUDDER center
rudder_center = Copy(roll_scale)
rudder_center.init_pos = {-(sizeX + rudder_offset), 0}
rudder_center.vertices = {
{-2.0 * line_width, -line_width},
{-2.0 * line_width, line_width},
{2.0 * line_width, line_width},
{2.0 * line_width, -line_width}
}
rudder_center.init_rot = {0, 0}
AddElement(rudder_center)
-- scale RUDDER
rudder_scale = Copy(roll_scale)
rudder_scale.init_pos = {-(sizeX + rudder_offset), 0}
AddElement(rudder_scale)
-- draw RUDDER position
rudder_index = Copy(roll_scale)
rudder_index.vertices = {
{-2.0 * line_width, -line_width},
{-2.0 * line_width, line_width},
{2.0 * line_width, line_width},
{2.0 * line_width, -line_width}
}
rudder_index.element_params = {"RUDDER_PEDALS"}
rudder_index.controllers = {{"move_up_down_using_parameter", 0, sizeX}}
rudder_index.parent_element = rudder_scale.name
rudder_index.tex_params = {256 / 512, 176.5 / 512, 0.5 * tex_scale / 3, 2 * tex_scale / 3}
rudder_index.material = draw_input
AddElement(rudder_index)
-- draw THROTTLE position (input)
throttle_index = Copy(roll_scale)
throttle_index.vertices = {
{-2.0 * line_width, -line_width},
{-2.0 * line_width, line_width},
{2.0 * line_width, line_width},
{2.0 * line_width, -line_width}
}
throttle_index.element_params = {"FM_THROTTLE_POSITION"}
throttle_index.controllers = {{"move_up_down_using_parameter", 0, -2.0 * sizeX}}
throttle_index.tex_params = {256 / 512, 176.5 / 512, 0.5 * tex_scale / 3, 2 * tex_scale / 3}
throttle_index.init_rot = {90, 0, 0}
throttle_index.material = draw_percentile_strong
throttle_index.parent_element = throttle_scale.name
AddElement(throttle_index)
-- draw THROTTLE position (actual)
throttlefm_index = Copy(throttle_index)
throttlefm_index.element_params = {ControlsIndicator_api.throttle_fm_move_param_string}
throttlefm_index.material = draw_input
throttlefm_index.parent_element = throttle_scale.name
AddElement(throttlefm_index)
| 0 | 0.903031 | 1 | 0.903031 | game-dev | MEDIA | 0.592067 | game-dev | 0.948204 | 1 | 0.948204 |
DustinHLand/vkDOOM3 | 7,562 | neo/d3xp/ai/AAS.h | /*
===========================================================================
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.
===========================================================================
*/
#ifndef __AAS_H__
#define __AAS_H__
class idReachability;
class idAASSettings;
/*
===============================================================================
Area Awareness System
===============================================================================
*/
enum {
PATHTYPE_WALK,
PATHTYPE_WALKOFFLEDGE,
PATHTYPE_BARRIERJUMP,
PATHTYPE_JUMP
};
typedef struct aasPath_s {
int type; // path type
idVec3 moveGoal; // point the AI should move towards
int moveAreaNum; // number of the area the AI should move towards
idVec3 secondaryGoal; // secondary move goal for complex navigation
const idReachability * reachability; // reachability used for navigation
} aasPath_t;
typedef struct aasGoal_s {
int areaNum; // area the goal is in
idVec3 origin; // position of goal
} aasGoal_t;
typedef struct aasObstacle_s {
idBounds absBounds; // absolute bounds of obstacle
idBounds expAbsBounds; // expanded absolute bounds of obstacle
} aasObstacle_t;
class idAASCallback {
public:
virtual ~idAASCallback() {};
virtual bool TestArea( const class idAAS *aas, int areaNum ) = 0;
};
typedef int aasHandle_t;
class idAAS {
public:
static idAAS * Alloc();
virtual ~idAAS() = 0;
// Initialize for the given map.
virtual bool Init( const idStr &mapName, unsigned int mapFileCRC ) = 0;
// Print AAS stats.
virtual void Stats() const = 0;
// Test from the given origin.
virtual void Test( const idVec3 &origin ) = 0;
// Get the AAS settings.
virtual const idAASSettings *GetSettings() const = 0;
// Returns the number of the area the origin is in.
virtual int PointAreaNum( const idVec3 &origin ) const = 0;
// Returns the number of the nearest reachable area for the given point.
virtual int PointReachableAreaNum( const idVec3 &origin, const idBounds &bounds, const int areaFlags ) const = 0;
// Returns the number of the first reachable area in or touching the bounds.
virtual int BoundsReachableAreaNum( const idBounds &bounds, const int areaFlags ) const = 0;
// Push the point into the area.
virtual void PushPointIntoAreaNum( int areaNum, idVec3 &origin ) const = 0;
// Returns a reachable point inside the given area.
virtual idVec3 AreaCenter( int areaNum ) const = 0;
// Returns the area flags.
virtual int AreaFlags( int areaNum ) const = 0;
// Returns the travel flags for traveling through the area.
virtual int AreaTravelFlags( int areaNum ) const = 0;
// Trace through the areas and report the first collision.
virtual bool Trace( aasTrace_t &trace, const idVec3 &start, const idVec3 &end ) const = 0;
// Get a plane for a trace.
virtual const idPlane & GetPlane( int planeNum ) const = 0;
// Get wall edges.
virtual int GetWallEdges( int areaNum, const idBounds &bounds, int travelFlags, int *edges, int maxEdges ) const = 0;
// Sort the wall edges to create continuous sequences of walls.
virtual void SortWallEdges( int *edges, int numEdges ) const = 0;
// Get the vertex numbers for an edge.
virtual void GetEdgeVertexNumbers( int edgeNum, int verts[2] ) const = 0;
// Get an edge.
virtual void GetEdge( int edgeNum, idVec3 &start, idVec3 &end ) const = 0;
// Find all areas within or touching the bounds with the given contents and disable/enable them for routing.
virtual bool SetAreaState( const idBounds &bounds, const int areaContents, bool disabled ) = 0;
// Add an obstacle to the routing system.
virtual aasHandle_t AddObstacle( const idBounds &bounds ) = 0;
// Remove an obstacle from the routing system.
virtual void RemoveObstacle( const aasHandle_t handle ) = 0;
// Remove all obstacles from the routing system.
virtual void RemoveAllObstacles() = 0;
// Returns the travel time towards the goal area in 100th of a second.
virtual int TravelTimeToGoalArea( int areaNum, const idVec3 &origin, int goalAreaNum, int travelFlags ) const = 0;
// Get the travel time and first reachability to be used towards the goal, returns true if there is a path.
virtual bool RouteToGoalArea( int areaNum, const idVec3 origin, int goalAreaNum, int travelFlags, int &travelTime, idReachability **reach ) const = 0;
// Creates a walk path towards the goal.
virtual bool WalkPathToGoal( aasPath_t &path, int areaNum, const idVec3 &origin, int goalAreaNum, const idVec3 &goalOrigin, int travelFlags ) const = 0;
// Returns true if one can walk along a straight line from the origin to the goal origin.
virtual bool WalkPathValid( int areaNum, const idVec3 &origin, int goalAreaNum, const idVec3 &goalOrigin, int travelFlags, idVec3 &endPos, int &endAreaNum ) const = 0;
// Creates a fly path towards the goal.
virtual bool FlyPathToGoal( aasPath_t &path, int areaNum, const idVec3 &origin, int goalAreaNum, const idVec3 &goalOrigin, int travelFlags ) const = 0;
// Returns true if one can fly along a straight line from the origin to the goal origin.
virtual bool FlyPathValid( int areaNum, const idVec3 &origin, int goalAreaNum, const idVec3 &goalOrigin, int travelFlags, idVec3 &endPos, int &endAreaNum ) const = 0;
// Show the walk path from the origin towards the area.
virtual void ShowWalkPath( const idVec3 &origin, int goalAreaNum, const idVec3 &goalOrigin ) const = 0;
// Show the fly path from the origin towards the area.
virtual void ShowFlyPath( const idVec3 &origin, int goalAreaNum, const idVec3 &goalOrigin ) const = 0;
// Find the nearest goal which satisfies the callback.
virtual bool FindNearestGoal( aasGoal_t &goal, int areaNum, const idVec3 origin, const idVec3 &target, int travelFlags, aasObstacle_t *obstacles, int numObstacles, idAASCallback &callback ) const = 0;
};
#endif /* !__AAS_H__ */
| 0 | 0.908458 | 1 | 0.908458 | game-dev | MEDIA | 0.964795 | game-dev | 0.74302 | 1 | 0.74302 |
magefree/mage | 2,528 | Mage.Sets/src/mage/cards/d/Disorder.java | package mage.cards.d;
import mage.ObjectColor;
import mage.abilities.Ability;
import mage.abilities.effects.OneShotEffect;
import mage.abilities.effects.common.DamageAllEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Outcome;
import mage.filter.FilterPermanent;
import mage.filter.common.FilterCreaturePermanent;
import mage.filter.predicate.mageobject.ColorPredicate;
import mage.game.Controllable;
import mage.game.Game;
import mage.players.Player;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;
/**
* @author LoneFox
*/
public final class Disorder extends CardImpl {
private static final FilterCreaturePermanent filter = new FilterCreaturePermanent("white creature");
static {
filter.add(new ColorPredicate(ObjectColor.WHITE));
}
public Disorder(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{1}{R}");
// Disorder deals 2 damage to each white creature and each player who controls a white creature.
this.getSpellAbility().addEffect(new DamageAllEffect(2, filter));
this.getSpellAbility().addEffect(new DisorderEffect());
}
private Disorder(final Disorder card) {
super(card);
}
@Override
public Disorder copy() {
return new Disorder(this);
}
}
class DisorderEffect extends OneShotEffect {
private static final FilterPermanent filter = new FilterCreaturePermanent("white creature");
static {
filter.add(new ColorPredicate(ObjectColor.WHITE));
}
public DisorderEffect() {
super(Outcome.Damage);
this.staticText = "and each player who controls a white creature";
}
private DisorderEffect(final DisorderEffect effect) {
super(effect);
}
@Override
public DisorderEffect copy() {
return new DisorderEffect(this);
}
@Override
public boolean apply(Game game, Ability source) {
for (Player player : game
.getBattlefield()
.getActivePermanents(filter, source.getControllerId(), source, game)
.stream()
.filter(Objects::nonNull)
.map(Controllable::getControllerId)
.distinct()
.map(game::getPlayer)
.collect(Collectors.toList())) {
player.damage(2, source.getSourceId(), source, game);
}
return true;
}
}
| 0 | 0.950141 | 1 | 0.950141 | game-dev | MEDIA | 0.887954 | game-dev | 0.995899 | 1 | 0.995899 |
pathea-games/planetexplorers | 24,815 | Assets/Scripts/PuJi/RandomDungen/RandomDungenMgr.cs | //------------------------------------------------------------------------------
// by Pugee
//------------------------------------------------------------------------------
using System;
using System.Collections;
using UnityEngine;
using Pathea;
using DunGen;
using System.Collections.Generic;
using ItemAsset;
using DunGen.Graph;
using System.Linq;
//using UnityEditor;
public class RandomDungenMgr:MonoBehaviour
{
static RandomDungenMgr mInstance;
public static RandomDungenMgr Instance{
get{return mInstance;}
}
void Awake(){
mInstance=this;
}
void Start(){
}
//[AddComponentMenu("DunGen/Runtime Dungeon")]
//public DungeonGenerator generator = new DungeonGenerator ();
const string dungeonFlowPath = "Prefab/Item/Rdungeon/DungeonFlow_Main";
DungeonGenerator generator;
public bool isActive = false;
public GameObject manager;
//entrance
UnityEngine.Object entrancePrefab0;
const string EntrancePath0 ="Prefab/RandomDunGen/RandomDunEntrance_Native";
UnityEngine.Object entrancePrefab1;
const string EntrancePath1 ="Prefab/RandomDunGen/RandomDunEntrance_Cave";
GameObject dungeonWaterPrefab;
const string dungeonWaterPath = "Prefab/RandomDunGen/DungeonWater";
GameObject dungeonWater;
public static List<Vector3> entrancesToAdd = new List<Vector3> ();
//bool isAdding = false;
public void Init(){
manager=gameObject;
entrancePrefab0 = Resources.Load(EntrancePath0);
entrancePrefab1 = Resources.Load(EntrancePath1);
dungeonWaterPrefab= Resources.Load(dungeonWaterPath) as GameObject;
allEntrance = new Dictionary<Vector3, DunEntranceObj>();
entranceArea = new Dictionary<IntVector2,DunEntranceObj>();
}
public void CreateInitTaskEntrance(){
if(RandomDungenMgrData.initTaskEntrance.Count>0)
foreach(KeyValuePair<IntVector2,int> kvp in RandomDungenMgrData.initTaskEntrance)
GenTaskEntrance(kvp.Key,kvp.Value);
}
public void EnterDungen(Vector3 entrancePos,int dungeonDataId){
RandomDungenMgrData.Clear();
MissionManager.Instance.m_PlayerMission.AbortFollowMission();
RandomDungenMgrData.AddServants();
LoadDataFromId(dungeonDataId);
SetWaterType(entrancePos);
if(PeGameMgr.IsMulti){
MessageBox_N.ShowMaskBox(MsgInfoType.DungeonGeneratingMask,"Generating",20f);
RandomDungenMgrData.entrancePos = entrancePos;
RandomDungenMgrData.enterPos = PeCreature.Instance.mainPlayer.position;
PlayerNetwork.mainPlayer.RequestEnterDungeon(entrancePos);
}
else{
isActive =true;
//UILoadScenceEffect.Instance.EnableProgress(false);
MissionManager.Instance.yirdName = AdventureScene.Dungen.ToString();
//origin
RandomDungenMgrData.SetPosByEnterPos(entrancePos);
MissionManager.Instance.transPoint = RandomDungenMgrData.revivePos;
//test
// MissionManager.Instance.transPoint = new Vector3(enterPos.x,-100,enterPos.z);
// RandomDungenMgrData.RevivePos = MissionManager.Instance.transPoint;
// RandomDungenMgrData.genPos = RandomDungenMgrData.RevivePos+new Vector3 (0,0,-2);
//TransFollower(RandomDungenMgrData.enterPos);
MissionManager.Instance.SceneTranslate();
}
}
public void SaveInDungeon(){
MissionManager.Instance.TransPlayerAndMissionFollower(RandomDungenMgrData.enterPos);
TransFollower(RandomDungenMgrData.enterPos);
SinglePlayerTypeLoader singlePlayerTypeLoader = SinglePlayerTypeArchiveMgr.Instance.singleScenario;
singlePlayerTypeLoader.SetYirdName(AdventureScene.MainAdventure.ToString());
}
public void TransFromDungeon(Vector3 pos){
MissionManager.Instance.TransMissionFollower(pos);
TransFollower(pos);
SinglePlayerTypeLoader singlePlayerTypeLoader = SinglePlayerTypeArchiveMgr.Instance.singleScenario;
singlePlayerTypeLoader.SetYirdName(AdventureScene.MainAdventure.ToString());
}
public void TransBackToDungeon(Vector3 pos){
PeTrans view = PeCreature.Instance.mainPlayer.peTrans;
if (view == null)
return;
view.position = pos;
MissionManager.Instance.TransMissionFollower(pos);
TransFollower(pos);
SinglePlayerTypeLoader singlePlayerTypeLoader = SinglePlayerTypeArchiveMgr.Instance.singleScenario;
singlePlayerTypeLoader.SetYirdName(AdventureScene.Dungen.ToString());
}
public void TransFromDungeonMultiMode(Vector3 pos){
MissionManager.Instance.TransMissionFollower(pos);
TransFollower(pos);
}
public void TransFollower(Vector3 pos){
List<PeEntity> follower = GetAllFollower();
if(PeGameMgr.IsSingle){
foreach(PeEntity pe in follower){
pe.position = pos;
}
}
else{
foreach(PeEntity pe in follower){
pe.position = pos;
}
}
}
List<PeEntity> GetAllFollower(){
List<PeEntity> allFollowers = new List<PeEntity> ();
NpcCmpt[] servants = PeCreature.Instance.mainPlayer.GetComponent<ServantLeaderCmpt>().GetServants();
foreach (NpcCmpt nc in servants)
{
if (nc != null)
allFollowers.Add(nc.Entity);
}
return allFollowers;
}
public void ExitDungen(){
if(PeGameMgr.IsMulti){
if(allEntrance.ContainsKey(RandomDungenMgrData.entrancePos))
{
DunEntranceObj rde = allEntrance[RandomDungenMgrData.entrancePos];
rde.ShowEnterOrNot = true;
}
PlayerNetwork.mainPlayer.RequestExitDungeon();
}else{
isActive =true;
//UILoadScenceEffect.Instance.EnableProgress(false);
MissionManager.Instance.yirdName = AdventureScene.MainAdventure.ToString();
MissionManager.Instance.transPoint = RandomDungenMgrData.enterPos;
// Debug.Log(MissionManager.Instance.yirdName);
// GenDungen(PeCreature.Instance.mainPlayer.position+new Vector3 (0,20,0));
// PeCreature.Instance.mainPlayer.position = manager.transform.position+new Vector3(0,2,0);
TransFollower(RandomDungenMgrData.enterPos);
DestroyDungeon();
MissionManager.Instance.SceneTranslate();
}
}
public void LoadPathFinding()
{
StartCoroutine(LoadPathFinder());
}
public void ResetPathFinding()
{
StartCoroutine(ResetPathFinder());
}
IEnumerator ResetPathFinder()
{
if (AstarPath.active != null)
{
if (AstarPath.active.transform.parent != null)
GameObject.Destroy(AstarPath.active.transform.parent.gameObject);
else
GameObject.Destroy(AstarPath.active.gameObject);
}
yield return null;
GameObject obj = Resources.Load("Prefab/PathfinderStd") as GameObject;
if (obj != null)
{
Instantiate(obj);
}
yield return null;
long tickStart = System.DateTime.UtcNow.Ticks;
if(AstarPath.active != null)
{
AstarPath.active.Scan();
Debug.Log("AstarPath.active.Scan(): " + (System.DateTime.UtcNow.Ticks - tickStart) / 10000L + "ms");
}
}
IEnumerator LoadPathFinder()
{
if(AstarPath.active != null)
{
if (AstarPath.active.transform.parent != null)
GameObject.Destroy(AstarPath.active.transform.parent.gameObject);
else
GameObject.Destroy(AstarPath.active.gameObject);
}
yield return null;
GameObject obj = Resources.Load("Prefab/Pathfinder_Dungeon") as GameObject;
if (obj != null)
{
Instantiate(obj);
}
yield return null;
long tickStart = System.DateTime.UtcNow.Ticks;
if(AstarPath.active != null){
AstarPath.active.Scan();
Debug.Log("AstarPath.active.Scan(): "+(System.DateTime.UtcNow.Ticks-tickStart) / 10000L +"ms");
}
}
public bool GenDungeon(int seed =-1){
if(PeGameMgr.IsSingle)
RandomDungenMgrData.DungeonId++;
generator = new DungeonGenerator(dungeonData.dungeonFlowPath);
manager.transform.position = RandomDungenMgrData.genDunPos;
if(manager==null||manager.transform==null)
{
Debug.LogError("manager==null||manager.transform==null!");
return false;
}
bool genSuccess = false;
if(seed==-1){
genSuccess = generator.Generate(manager);//new
if(!genSuccess)
return false;
Debug.Log("gen success without seed");
GenWater_SafeBottom(RandomDungenMgrData.waterType);
GeneralSet(true);
GenContent();
}
else{
genSuccess = generator.GenerateWithSeed(manager,seed);
if(!genSuccess)
return false;
Debug.Log("gen success with seed");
GenWater_SafeBottom(RandomDungenMgrData.waterType);
GeneralSet(true);
}
if(PeGameMgr.IsSingle){
}
if(PeGameMgr.IsMulti){
seed = generator.ChosenSeed;
PlayerNetwork.mainPlayer.RequestUploadDungeonSeed(RandomDungenMgrData.entrancePos,seed);
Debug.Log("dun Seed: "+seed);
ChangeOther(true);
}
Debug.Log("RemoveTerrainDependence");
SceneMan.RemoveTerrainDependence();
return genSuccess;
}
public void GenContent(){
int seed = (int)(System.DateTime.UtcNow.Ticks%Int32.MaxValue);
System.Random rand = new System.Random(seed);
RandomDungenMgrData.allMonsters = manager.GetComponentsInChildren<MonsterGenerator>().ToList();
// foreach(MonsterGenerator mgm in RandomDungenMgrData.allMonsters){
// MonsterGenerator.GenMonsters(mgm);
// }
GenMonsters(RandomDungenMgrData.allMonsters,rand);
RandomDungenMgrData.allMinBoss = manager.GetComponentsInChildren<MinBossGenerator>().ToList();
GenMinBoss(RandomDungenMgrData.allMinBoss,rand);
RandomDungenMgrData.allBoss = manager.GetComponentsInChildren<BossMonsterGenerator>().ToList();
GenBoss(RandomDungenMgrData.allBoss,rand);
RandomDungenMgrData.allItems = manager.GetComponentsInChildren<DunItemGenerator>().ToList();
// foreach(DunItemGeneratorMgr digm in RandomDungenMgrData.allItems){
// DunItemGeneratorMgr.GenItem(digm);
// }
GenItems(RandomDungenMgrData.allItems,rand);
RandomDungenMgrData.allRareItems = manager.GetComponentsInChildren<DunRareItemGenerator>().ToList();
List<ItemIdCount> specifiedItems = RandomDungenMgrData.dungeonBaseData.specifiedItems;
List<IdWeight> rareItemTags = RandomDungenMgrData.dungeonBaseData.rareItemTags;
GenRareItem(RandomDungenMgrData.allRareItems,rareItemTags,rand,specifiedItems);
}
public void DestroyDungeon(){
GeneralSet(false);
SceneMan.AddTerrainDependence();
if(generator!=null&&generator.CurrentDungeon!=null&&generator.CurrentDungeon.gameObject!=null)
UnityUtil.Destroy(generator.CurrentDungeon.gameObject);
RandomDungenMgrData.Clear();
if (PeGameMgr.IsMulti)
{
ChangeOther(false);
ResetPathFinding();
}
if(dungeonWater!=null)
GameObject.Destroy(dungeonWater);
FBSafePlane.instance.DeleteCol();
DragItemAgent.DestroyAllInDungeon();
}
void GeneralSet(bool enter){
if(enter)
{
if(PeGameMgr.IsSingle)
{
SaveOutOfDungeon();
}
PeEnv.CanRain(false);
if(dungeonWater!=null)
RandomMapConfig.SetGlobalFogHeight(dungeonWater.transform.position.y);
}else{
PeEnv.CanRain(true);
RandomMapConfig.SetGlobalFogHeight();
}
}
public void SaveOutOfDungeon(){
PeTrans view = PeCreature.Instance.mainPlayer.peTrans;
if (view == null)
return;
Vector3 pos = view.position;
SaveInDungeon();
ArchiveMgr.Instance.Save(ArchiveMgr.ESave.Auto1);
TransBackToDungeon(pos);
}
//single
void DeactiveObjNotUse()
{
List<int> followers = RandomDungenMgrData.GetAllFollowers();
int mainPlayerId = PeCreature.Instance.mainPlayerId;
IEnumerable<PeEntity> allEntities = EntityMgr.Instance.All;
foreach(PeEntity pe in allEntities){
if(pe.Id!=mainPlayerId&&!followers.Contains(pe.Id)){
if(pe.gameObject!=null){
pe.gameObject.SetActive(false);
MapCmpt mc = pe.GetCmpt<MapCmpt>();
pe.Remove(mc);
}
}
}
List<PeMap.ILabel> RemoveList = PeMap.LabelMgr.Instance.FindAll(itr => itr.GetType()==PeMap.ELabelType.Mission);
foreach (PeMap.ILabel _ilabel in RemoveList)
{
PeMap.LabelMgr.Instance.Remove(_ilabel);
}
}
//multimode
public void ChangeOther(bool isEnter){
UIMinMapCtrl.Instance.UpdateCameraPos();
if(isEnter)
{
UIMinMapCtrl.Instance.CameraNear = 200;
UIMinMapCtrl.Instance.CameraFar = 400;
}else{
UIMinMapCtrl.Instance.CameraNear = 1;
UIMinMapCtrl.Instance.CameraFar=1000;
}
}
public void ReceiveIsoObj(int dungeonId,ulong isoCode,int instanceId){
//--to do: iosList
//update randomRareItem
RandomDungenMgrData.RareItemReady(instanceId,dungeonId);
}
public void OpenLockedDoor(SkillSystem.SkEntity caster,SkillSystem.SkEntity monster){
LockedDoor ld = generator.CurrentDungeon.LockedDoorList.Find(it=>it.IsOpen==false);
if(ld!=null)
ld.Open();
}
public void PickUpKey(int keyId){
RandomDungenMgrData.pickedKeys.Add(keyId);
}
public bool HasKey(int keyId){
return RandomDungenMgrData.pickedKeys.Contains(keyId);
}
public void RemoveKey(int keyId){
RandomDungenMgrData.pickedKeys.Remove(keyId);
}
#region LoadDataBase
DungeonBaseData dungeonData{
get{return RandomDungenMgrData.dungeonBaseData;}
set{RandomDungenMgrData.dungeonBaseData = value;}
}
public bool IsInIronDungeon{
get{return dungeonData.IsIron;}
}
public DungeonType Dungeontype{
get{return dungeonData.Type;}
}
public void LoadDataFromDataBase(int level){
DungeonBaseData dbd = RandomDungeonDataBase.GetDataFromLevel(level);
DungeonFlow df =Resources.Load(dbd.dungeonFlowPath) as DungeonFlow;
if(df==null){
Debug.LogError("flow null: "+dbd.dungeonFlowPath );
dbd.dungeonFlowPath = dungeonFlowPath;
}
dungeonData=dbd;
}
public void LoadDataFromId(int id){
DungeonBaseData dbd = RandomDungeonDataBase.GetDataFromId(id);
DungeonFlow df =Resources.Load(dbd.dungeonFlowPath) as DungeonFlow;
if(df==null){
Debug.LogError("flow null: "+dbd.dungeonFlowPath );
dbd.dungeonFlowPath = dungeonFlowPath;
}
dungeonData=dbd;
}
public void GenMonsters(List<MonsterGenerator> allPoints,System.Random rand){
//test
// allPoints[0].GenerateMonster(dungeonData.landMonsterId,dungeonData.waterMonsterId,dungeonData.monsterBuff,rand);
//origin
if(allPoints==null||allPoints.Count==0)
return;
float jumpIndex = 1/dungeonData.monsterAmount;
if(jumpIndex<1)
jumpIndex=1;
for(float i=0;i<allPoints.Count;i+=jumpIndex){
int index = Mathf.FloorToInt(i);
allPoints[index].GenerateMonster(dungeonData.landMonsterId,dungeonData.waterMonsterId,dungeonData.monsterBuff,rand,dungeonData.IsTaskDungeon);
}
}
public void GenItems(List<DunItemGenerator> allPoints,System.Random rand){
//test
// allPoints[0].GenItem(dungeonData.itemId,rand);
//origin
if(allPoints==null||allPoints.Count==0)
return;
float jumpIndex = 1/dungeonData.itemAmount;
if(jumpIndex<1)
jumpIndex=1;
for(float i=0;i<allPoints.Count;i+=jumpIndex){
int index = Mathf.FloorToInt(i);
allPoints[index].GenItem(dungeonData.itemId,rand);
}
}
public void GenMinBoss(List<MinBossGenerator> allPoints,System.Random rand){
if(allPoints==null||allPoints.Count==0)
return;
MinBossGenerator.GenAllBoss(allPoints,dungeonData.minBossId,dungeonData.minBossWaterId,dungeonData.minBossMonsterBuff,rand,dungeonData.IsTaskDungeon);
}
public void GenBoss(List<BossMonsterGenerator> allPoints,System.Random rand){
if(allPoints==null||allPoints.Count==0)
return;
BossMonsterGenerator.GenAllBoss(allPoints,dungeonData.bossId,dungeonData.minBossWaterId,dungeonData.bossMonsterBuff,rand,dungeonData.IsTaskDungeon);
}
public void GenRareItem(List<DunRareItemGenerator> allPoints,List<IdWeight> rareItemTags,System.Random rand,List<ItemIdCount> specifiedItems=null){
if(allPoints==null||allPoints.Count==0)
return;
DunRareItemGenerator.GenAllItem(allPoints,dungeonData.rareItemId,dungeonData.rareItemChance,rareItemTags,rand,specifiedItems);
}
public void SetWaterType(Vector3 entrancePos){
if(dungeonData.IsTaskDungeon)
RandomDungenMgrData.waterType = DungeonWaterType.None;
else{
if (VFVoxelWater.self != null)
{
if(VFVoxelWater.self.IsInWater(entrancePos)){
// if(VFVoxelWater.self.IsInWater(entrancePos+new Vector3(0,2,0)))
RandomDungenMgrData.waterType = DungeonWaterType.Deep;
// else
// RandomDungenMgrData.waterType = DungeonWaterType.Shallow;
}else{
RandomDungenMgrData.waterType = DungeonWaterType.None;
}
}else{
RandomDungenMgrData.waterType = DungeonWaterType.None;
}
}
}
public void GenWater_SafeBottom(DungeonWaterType waterType){
Vector3 posMin = RandomDungenMgrData.genDunPos+new Vector3 (-1000,-50,-1000);
Vector3 posMax = posMin+new Vector3 (2000,5,2000);
if(waterType ==DungeonWaterType.Deep){
dungeonWater = GameObject.Instantiate(dungeonWaterPrefab);
dungeonWater.transform.position = RandomDungenMgrData.genDunPos-new Vector3 (0,4,0);
}else if(waterType ==DungeonWaterType.Shallow){
dungeonWater = GameObject.Instantiate(dungeonWaterPrefab);
dungeonWater.transform.position = RandomDungenMgrData.genDunPos-new Vector3 (0,10,0);
}else{
//
// dungeonWater = GameObject.Instantiate(dungeonWaterPrefab);
// dungeonWater.transform.position = RandomDungenMgrData.genDunPos-new Vector3 (0,4,0);
}
if(generator.CurrentDungeon.gameObject!=null){
Bounds bd = PETools.PEUtil.GetWordColliderBoundsInChildren(generator.CurrentDungeon.gameObject);
posMin = bd.min+new Vector3 (-80,0,-80);
posMax = new Vector3 (bd.max.x+80,posMin.y+5,bd.max.z+80);
if(dungeonWater!=null){
dungeonWater.transform.position = new Vector3 (bd.center.x,dungeonWater.transform.position.y,bd.center.z);
dungeonWater.transform.localScale = new Vector3 ((bd.size.x+100)/10,1,(bd.size.z+100)/10);
}
}
FBSafePlane.instance.ResetCol(posMin, posMax, RandomDungenMgrData.revivePos);
}
#endregion
#region entrance
//1.only 1 in 256X256 Area
//2.check nearhave 256X256
public const float PASSTIME_T = 360;
public const float PASSDIST_T = 1000;
public const float GEN_T = 1.5f;//2
public const int DISTANCE_MAX = 20;
public const int INDEX256MAX = 1;//18;
public const int GEN_RADIUS_MIN = 50;//50;
public const int GEN_RADIUS_MAX = 100;//100;[min,max)
public bool generateSwitch = false;
public float multiFactor = 4;
public PeTrans playerTrans;
public Vector3 born_pos;
public Vector3 start_pos;
public Vector3 last_pos;
public float timeCounter = 0;
public float last_time;
public float timePassed = 0;
public float distancePassed = 0;
public int counter = 0;
const int AREA_RADIUS = 8;//2^8=256
public static Dictionary<IntVector2,DunEntranceObj> entranceArea = new Dictionary<IntVector2,DunEntranceObj>();
public static Dictionary<Vector3,DunEntranceObj> allEntrance = new Dictionary<Vector3,DunEntranceObj> ();
// public void AddEntrance(Vector3 pos){
// isAdding=true;
// if(!entrancesToAdd.Contains(pos)){
//
// entrancesToAdd.Add(pos);
// }
// isAdding = false;
// }
void Update(){
if (PeGameMgr.IsAdventure)
{
counter++;
timeCounter += Time.deltaTime;
if (counter > 240)
{
if (playerTrans == null)
{
if (PeCreature.Instance.mainPlayer != null && PeCreature.Instance.mainPlayer.peTrans.position != Vector3.zero)
{
playerTrans = PeCreature.Instance.mainPlayer.peTrans;
born_pos = playerTrans.position;
if(Application.isEditor)
Debug.Log("<color=yellow>" + "born_pos" + born_pos + "</color>");
start_pos = born_pos;
last_pos = start_pos;
last_time = timeCounter;
}
counter = 0;
return;
}
if(RandomDungenMgrData.InDungeon)
{
last_pos = RandomDungenMgrData.enterPos;
last_time = timeCounter;
return;
}
if (!generateSwitch)
{
timePassed += timeCounter - last_time;
float moreDistance = Vector2.Distance(new Vector2(playerTrans.position.x, playerTrans.position.z), new Vector2(last_pos.x, last_pos.z));//--to do:
if (moreDistance > DISTANCE_MAX)
{
moreDistance = DISTANCE_MAX;
}
distancePassed += moreDistance;
last_pos = playerTrans.position;
last_time = timeCounter;
if (CheckGenerate(timePassed, distancePassed))
{
generateSwitch = true;
timePassed = 0;
distancePassed = 0;
}
else
{
counter = 0;
return;
}
}
if (generateSwitch)
{
System.Random randSeed = new System.Random();
int distance = GEN_RADIUS_MAX - GEN_RADIUS_MIN;
int xPlus = randSeed.Next(distance * 2) - distance;
int zPlus = randSeed.Next(distance * 2) - distance;
if (xPlus >= 0)
xPlus += GEN_RADIUS_MIN;
else
xPlus = xPlus - GEN_RADIUS_MIN + 1;
if (zPlus >= 0)
zPlus += GEN_RADIUS_MIN;
else
zPlus = zPlus - GEN_RADIUS_MIN + 1;
IntVector2 GenPos = new IntVector2((int)playerTrans.position.x + xPlus, (int)playerTrans.position.z + zPlus);
//--to do areaAvalable
Vector3 pos;
//int boxId;
if(IsTerrainAvailable(GenPos, out pos)){
if (IsAreaAvalable(new Vector2(pos.x,pos.z)))
{
InstantiateEntrance(pos-new Vector3(0,0.5f,0));
generateSwitch = false;
}
}
}
counter = 0;
}
}
//
// counter++;
// if(counter>24){
// if (PeGameMgr.IsAdventure&&PeGameMgr.yirdName!=AdventureScene.Dungen.ToString()){
// if(entrancesToAdd.Count>0&&!isAdding){
// List<Vector3> posList = entrancesToAdd;
// entrancesToAdd=new List<Vector3> ();
// foreach(Vector3 genPos in posList){
//
// }
// }
// counter=0;
// }
// }
}
bool CheckGenerate(float passedTime, float passedDistance)
{
bool flag = false;
if (passedTime < PASSTIME_T)
{
return flag;
}
if (passedDistance < PASSDIST_T)
{
return flag;
}
float factor = 1;
if(PeGameMgr.IsMulti)
factor = multiFactor;
if (passedTime * passedDistance / PASSTIME_T / PASSDIST_T>GEN_T*factor)
{
flag = true;
}
return flag;
}
bool IsAreaAvalable(Vector2 pos)
{
if(VArtifactTownManager.Instance.TileContainsTown(new IntVector2(Mathf.RoundToInt(pos.x) >> 5, Mathf.RoundToInt(pos.y)>>5)))
return false;
IntVector2 indexArea = new IntVector2(Mathf.RoundToInt(pos.x) >> AREA_RADIUS, Mathf.RoundToInt(pos.y)>>AREA_RADIUS);
for(int i=indexArea.x-1;i<indexArea.x+2;i++)
for(int j=indexArea.y-1;j<indexArea.y+2;j++)
if(entranceArea.ContainsKey(new IntVector2(i,j)))
return false;
return true;
}
public bool IsTerrainAvailable(IntVector2 GenPos,out Vector3 pos)
{
if(!VFDataRTGen.IsDungeonEntranceAvailable(GenPos)){
pos = Vector3.zero;
return false;
}
// int y = VFDataRTGen.GetPosHeight(GenPos,true);
//
// pos = new Vector3(GenPos.x,y+4,GenPos.y);
// RaycastHit hit;
// if (Physics.Raycast(pos, Vector3.down, out hit, 512, 1 << Pathea.Layer.VFVoxelTerrain))
// {
// pos.y = hit.point.y;
// }else{
// return false;
// }
bool result = RandomDunGenUtil.GetAreaLowestPos(GenPos,10,out pos);
return result;
}
void InstantiateEntrance(Vector3 genPos,int level = -1){
if(level==-1)
level = RandomDunGenUtil.GetEntranceLevel(genPos);
DungeonBaseData bd = RandomDungeonDataBase.GetDataFromLevel(level);
if(bd!=null){
if(PeGameMgr.IsSingle)
GenDunEntrance(genPos,bd);
else{
PlayerNetwork.mainPlayer.RequestGenDunEntrance(genPos,bd.id);
}
}
}
public UnityEngine.Object GetEntrancePrefabPath(DungeonType type){
if(type ==DungeonType.Iron)
return entrancePrefab0;
if(type == DungeonType.Cave)
return entrancePrefab1;
return entrancePrefab0;
}
public void GenDunEntrance(Vector3 genPos,DungeonBaseData basedata){
if(!allEntrance.ContainsKey(genPos)){
UnityEngine.Object entranceObj= GetEntrancePrefabPath(basedata.Type);
DunEntranceObj entrance = new DunEntranceObj(entranceObj,genPos);
entrance.Level=basedata.level;
entrance.DungeonId = basedata.id;
allEntrance[genPos] = entrance;
if(basedata.level>=100){
}
else{
IntVector2 indexArea = new IntVector2(Mathf.RoundToInt(genPos.x) >> AREA_RADIUS, Mathf.RoundToInt(genPos.z)>>AREA_RADIUS);
entranceArea[indexArea] = entrance;
}
SceneMan.AddSceneObj(entrance);
return;
}
}
public void DestroyEntrance(Vector3 entrancePos){
if(!allEntrance.ContainsKey(entrancePos))
return;
allEntrance[entrancePos].DestroySelf();
allEntrance.Remove(entrancePos);
IntVector2 indexArea = new IntVector2(Mathf.RoundToInt(entrancePos.x) >> AREA_RADIUS, Mathf.RoundToInt(entrancePos.z)>>AREA_RADIUS);
entranceArea.Remove(indexArea);
}
//method 2.
public void GenTestEntrance(int level = -1){
int x = Mathf.RoundToInt(PeCreature.Instance.mainPlayer.position.x);
int z = Mathf.RoundToInt(PeCreature.Instance.mainPlayer.position.z+15);
int y = VFDataRTGen.GetPosHeight(x,z);
Vector3 genPos = new Vector3 (x,y,z);
InstantiateEntrance(genPos,level);
}
//task
public void GenTaskEntrance(IntVector2 genXZ,int level = -1){
Vector3 genPos = RandomDunGenUtil.GetPosOnGround(genXZ);
InstantiateEntrance(genPos,level);
}
#endregion
}
| 0 | 0.90701 | 1 | 0.90701 | game-dev | MEDIA | 0.918929 | game-dev | 0.967266 | 1 | 0.967266 |
dphfox/Fusion | 4,164 | docs/tutorials/tables/forpairs.md | `ForPairs` is like `ForValues` and `ForKeys` in one object. It can process pairs
of keys and values at the same time.
It supports both constants and state objects.
```Lua
local itemColours = { shoes = "red", socks = "blue" }
local owner = scope:Value("Janet")
local manipulated = scope:ForPairs(itemColours, function(use, scope, thing, colour)
local newKey = colour
local newValue = use(owner) .. "'s " .. thing
return newKey, newValue
end)
print(peek(manipulated)) --> {red = "Janet's shoes", blue = "Janet's socks"}
owner:set("April")
print(peek(manipulated)) --> {red = "April's shoes", blue = "April's socks"}
```
-----
## Usage
To create a new `ForPairs` object, call the constructor with an input table and
a processor function. The first two arguments are `use` and `scope`, just like
[computed objects](../../fundamentals/computeds). The third and fourth arguments
are one of the key-value pairs read from the input table.
```Lua
local itemColours = { shoes = "red", socks = "blue" }
local swapped = scope:ForPairs(data, function(use, scope, item, colour)
return colour, item
end)
```
You can read the processed table using `peek()`:
```Lua hl_lines="6"
local itemColours = { shoes = "red", socks = "blue" }
local swapped = scope:ForPairs(data, function(use, scope, item, colour)
return colour, item
end)
print(peek(swapped)) --> { red = "shoes", blue = "socks" }
```
The input table can be a state object. When the input table changes, the output
will update.
```Lua
local itemColours = scope:Value({ shoes = "red", socks = "blue" })
local swapped = scope:ForPairs(data, function(use, scope, item, colour)
return colour, item
end)
print(peek(swapped)) --> { red = "shoes", blue = "socks" }
itemColours:set({ sandals = "red", socks = "green" })
print(peek(swapped)) --> { red = "sandals", green = "socks" }
```
You can also `use()` state objects in your calculations, just like a computed.
```Lua
local itemColours = { shoes = "red", socks = "blue" }
local shouldSwap = scope:Value(false)
local swapped = scope:ForPairs(data, function(use, scope, item, colour)
if use(shouldSwap) then
return colour, item
else
return item, colour
end
end)
print(peek(swapped)) --> { shoes = "red", socks = "blue" }
shouldSwap:set(true)
print(peek(swapped)) --> { red = "shoes", blue = "socks" }
```
Anything added to the `scope` is cleaned up for you when either the processed
key or the processed value is removed.
```Lua
local itemColours = scope:Value({ shoes = "red", socks = "blue" })
local swapped = scope:ForPairs(data, function(use, scope, item, colour)
table.insert(scope, function()
print("No longer wearing " .. colour .. " " .. item)
end)
return colour, item
end)
itemColours:set({ shoes = "red", socks = "green" }) --> No longer wearing blue socks
```
??? tip "How ForPairs optimises your code"
Rather than creating a new output table from scratch every time the input table
is changed, `ForPairs` will try and reuse as much as possible to improve
performance.
Since `ForPairs` has to depend on both keys and values, changing any value in
the input table will cause a recalculation for that key-value pair.


Inversely, `ForPairs` won't recalculate any key-value pairs that stay the same.
Instead, these will be preserved in the output table.


If you don't need the keys or the values, Fusion can offer better optimisations.
For example, if you're working with an array of values where position doesn't
matter, [ForValues can move values between keys.](./forvalues.md)
Alternatively, if you're working with a set of objects stored in keys, and don't
need the values in the table,
[ForKeys will ignore the values for optimal performance.](./forkeys.md) | 0 | 0.684718 | 1 | 0.684718 | game-dev | MEDIA | 0.81677 | game-dev | 0.806073 | 1 | 0.806073 |
magefree/mage | 1,600 | Mage.Sets/src/mage/cards/o/OminousSphinx.java |
package mage.cards.o;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.common.CycleOrDiscardControllerTriggeredAbility;
import mage.abilities.effects.common.continuous.BoostTargetEffect;
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.filter.StaticFilters;
import mage.target.TargetPermanent;
import mage.target.common.TargetCreaturePermanent;
import static mage.filter.StaticFilters.FILTER_OPPONENTS_PERMANENT_CREATURE;
/**
*
* @author spjspj
*/
public final class OminousSphinx extends CardImpl {
public OminousSphinx(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{U}{U}");
this.subtype.add(SubType.SPHINX);
this.power = new MageInt(4);
this.toughness = new MageInt(4);
// Flying
this.addAbility(FlyingAbility.getInstance());
// Whenever you cycle or discard a card,target creature an opponent controls gets -2/-0 until end of turn.
CycleOrDiscardControllerTriggeredAbility ability = new CycleOrDiscardControllerTriggeredAbility(new BoostTargetEffect(-2, -0, Duration.EndOfTurn));
ability.addTarget(new TargetPermanent(FILTER_OPPONENTS_PERMANENT_CREATURE));
this.addAbility(ability);
}
private OminousSphinx(final OminousSphinx card) {
super(card);
}
@Override
public OminousSphinx copy() {
return new OminousSphinx(this);
}
}
| 0 | 0.97477 | 1 | 0.97477 | game-dev | MEDIA | 0.95978 | game-dev | 0.992381 | 1 | 0.992381 |
SpagoBILabs/SpagoBI | 704,113 | SpagoBIMobileEngine/src/main/webapp/js/sencha_2.1.1/touch-charts-debug.js | /**
* @class Ext.fx.Queue
* Animation Queue mixin to handle chaining and queueing by target.
* @private
*/
Ext.ns('Ext.fx.target');
Ext.fx.Queue = {
constructor: function() {
this.targets = new Ext.util.HashMap();
this.fxQueue = {};
},
// @private
getFxDefaults: function(targetId) {
var target = this.targets.get(targetId);
if (target) {
return target.fxDefaults;
}
return {};
},
// @private
setFxDefaults: function(targetId, obj) {
var target = this.targets.get(targetId);
if (target) {
target.fxDefaults = Ext.apply(target.fxDefaults || {}, obj);
}
},
// @private
stopAnimation: function(targetId) {
var me = this,
queue = me.getFxQueue(targetId),
ln = queue.length;
while (ln) {
queue[ln - 1].end();
ln--;
}
},
/**
* @private
* Returns current animation object if the element has any effects actively running or queued, else returns false.
*/
getActiveAnimation: function(targetId) {
var queue = this.getFxQueue(targetId);
return (queue && !!queue.length) ? queue[0] : false;
},
// @private
hasFxBlock: function(targetId) {
var queue = this.getFxQueue(targetId);
return queue && queue[0] && queue[0].block;
},
// @private get fx queue for passed target, create if needed.
getFxQueue: function(targetId) {
if (!targetId) {
return false;
}
var me = this,
queue = me.fxQueue[targetId],
target = me.targets.get(targetId);
if (!target) {
return false;
}
if (!queue) {
me.fxQueue[targetId] = [];
// GarbageCollector will need to clean up Elements since they aren't currently observable
if (target.type != 'element') {
target.target.on('destroy', function() {
me.fxQueue[targetId] = [];
});
}
}
return me.fxQueue[targetId];
},
// @private
queueFx: function(anim) {
var me = this,
target = anim.target,
queue, ln;
if (!target) {
return;
}
queue = me.getFxQueue(target.getId());
ln = queue.length;
if (ln) {
if (anim.concurrent) {
anim.paused = false;
}
else {
queue[ln - 1].on('afteranimate', function() {
anim.paused = false;
});
}
}
else {
anim.paused = false;
}
anim.on('afteranimate', function() {
// COMPAT
queue.remove(anim);
if (anim.remove) {
if (target.type == 'element') {
var el = Ext.get(target.id);
if (el) {
el.remove();
}
}
}
}, this);
queue.push(anim);
}
};
/**
* @class Ext.fx.Manager
* Animation Manager which keeps track of all current animations and manages them on a frame by frame basis.
* @private
* @singleton
*/
Ext.fx.Manager = {
constructor: function() {
var me = this;
me.items = new Ext.util.MixedCollection();
me.addEvents(
/**
* @event framebegin
* Fires before the frame starts.
*/
'framebegin',
/**
* @event frameend
* Fires when the frame ends.
*/
'frameend'
);
Ext.util.Observable.constructor.call(me);
Ext.fx.Queue.constructor.call(me);
},
/**
* @cfg {Number} interval Default interval in miliseconds to calculate each frame. Defaults to 16ms (~60fps)
*/
interval: 32,
// @private Target factory
createTarget: function(target) {
var me = this,
targetObj;
if (Ext.isObject(target)) {
// Draw Sprite
if (target.isSprite) {
targetObj = new Ext.fx.target.Sprite(target);
}
// Draw Sprite Composite
else if (target.isCompositeSprite) {
targetObj = new Ext.fx.target.CompositeSprite(target);
}
else if (target.isAnimTarget) {
return target;
}
else {
return null;
}
me.targets.add(targetObj);
return targetObj;
}
else {
return null;
}
},
/**
* Add an Anim to the manager. This is done automatically when an Anim instance is created.
* @param {Ext.fx.Anim} anim
*/
addAnim: function(anim) {
var me = this,
items = me.items,
task = me.task;
items.add(anim);
// Start the timer if not already running
if (!task && items.length) {
me.task = setInterval(me.runner, me.interval);
}
},
/**
* Remove an Anim from the manager. This is done automatically when an Anim ends.
* @param {Ext.fx.Anim} anim
*/
removeAnim: function(anim) {
var me = this,
items = me.items,
task = me.task;
items.remove(anim);
// Stop the timer if there are no more managed Anims
if (task && !items.length) {
clearInterval(task);
delete me.task;
}
},
/**
* @private
* Filter function to determine which animations need to be started
*/
startingFilter: function(o) {
return o.paused === false && o.running === false && o.iterations > 0;
},
/**
* @private
* Filter function to determine which animations are still running
*/
runningFilter: function(o) {
return o.paused === false && o.running === true && o.isAnimator !== true;
},
/**
* @private
* Runner function being called each frame
*/
runner: function() {
var me = Ext.fx.Manager,
items = me.items;
if (!me.running) {
me.fireEvent('framebegin');
me.running = true;
me.targetData = {};
me.targetArr = {};
// Single timestamp for all animations this interval
me.timestamp = new Date();
// Start any items not current running
items.filterBy(me.startingFilter).each(me.startAnim, me);
// Build the new attributes to be applied for all targets in this frame
items.filterBy(me.runningFilter).each(me.runAnim, me);
// Apply all the pending changes to their targets
me.applyPendingAttrs();
me.fireEvent('frameend');
me.running = false;
}
},
/**
* @private
* Start the individual animation (initialization)
*/
startAnim: function(anim) {
anim.start(this.timestamp);
},
/**
* @private
* Run the individual animation for this frame
*/
runAnim: function(anim) {
if (!anim) {
return;
}
var me = this,
targetId = anim.target.getId(),
elapsedTime = me.timestamp - anim.startTime;
this.collectTargetData(anim, elapsedTime);
// For JS animation, trigger the lastFrame handler if this is the final frame
if (elapsedTime >= anim.duration) {
me.applyPendingAttrs(true);
delete me.targetData[targetId];
delete me.targetArr[targetId];
anim.lastFrame();
}
},
/**
* Collect target attributes for the given Anim object at the given timestamp
* @param {Ext.fx.Anim} anim The Anim instance
* @param {Number} elapsedTime Time after the anim's start time
*/
collectTargetData: function(anim, elapsedTime) {
var me = this,
targetId = anim.target.getId(),
targetData = me.targetData[targetId],
data;
if (!targetData) {
targetData = me.targetData[targetId] = [];
me.targetArr[targetId] = anim.target;
}
data = {
duration: anim.duration,
easing: anim.easing,
attrs: {}
};
Ext.apply(data.attrs, anim.runAnim(elapsedTime));
targetData.push(data);
},
/**
* @private
* Apply all pending attribute changes to their targets
*/
applyPendingAttrs: function(isLastFrame) {
var targetData = this.targetData,
targetArr = this.targetArr,
targetId;
for (targetId in targetData) {
if (targetData.hasOwnProperty(targetId)) {
targetArr[targetId].setAttr(targetData[targetId], false, isLastFrame);
}
}
}
};
Ext.applyIf(Ext.fx.Manager, Ext.fx.Queue);
Ext.applyIf(Ext.fx.Manager, Ext.util.Observable.prototype);
Ext.fx.Manager.constructor();
/**
* @class Ext.fx.CubicBezier
* @ignore
*/
Ext.fx.CubicBezier = {
cubicBezierAtTime: function(t, p1x, p1y, p2x, p2y, duration) {
var cx = 3 * p1x,
bx = 3 * (p2x - p1x) - cx,
ax = 1 - cx - bx,
cy = 3 * p1y,
by = 3 * (p2y - p1y) - cy,
ay = 1 - cy - by;
function sampleCurveX(t) {
return ((ax * t + bx) * t + cx) * t;
}
function solve(x, epsilon) {
var t = solveCurveX(x, epsilon);
return ((ay * t + by) * t + cy) * t;
}
function solveCurveX(x, epsilon) {
var t0, t1, t2, x2, d2, i;
for (t2 = x, i = 0; i < 8; i++) {
x2 = sampleCurveX(t2) - x;
if (Math.abs(x2) < epsilon) {
return t2;
}
d2 = (3 * ax * t2 + 2 * bx) * t2 + cx;
if (Math.abs(d2) < 1e-6) {
break;
}
t2 = t2 - x2 / d2;
}
t0 = 0;
t1 = 1;
t2 = x;
if (t2 < t0) {
return t0;
}
if (t2 > t1) {
return t1;
}
while (t0 < t1) {
x2 = sampleCurveX(t2);
if (Math.abs(x2 - x) < epsilon) {
return t2;
}
if (x > x2) {
t0 = t2;
} else {
t1 = t2;
}
t2 = (t1 - t0) / 2 + t0;
}
return t2;
}
return solve(t, 1 / (200 * duration));
},
cubicBezier: function(x1, y1, x2, y2) {
var fn = function(pos) {
return Ext.fx.CubicBezier.cubicBezierAtTime(pos, x1, y1, x2, y2, 1);
};
fn.toCSS3 = function() {
return 'cubic-bezier(' + [x1, y1, x2, y2].join(',') + ')';
};
fn.reverse = function() {
return Ext.fx.CubicBezier.cubicBezier(1 - x2, 1 - y2, 1 - x1, 1 - y1);
};
return fn;
}
};
/**
* @class Ext.fx.Easing
*
This class contains a series of function definitions used to modify values during an animation.
They describe how the intermediate values used during a transition will be calculated. It allows for a transition to change
speed over its duration. The following options are available:
- linear The default easing type
- backIn
- backOut
- bounceIn
- bounceOut
- ease
- easeIn
- easeOut
- easeInOut
- elasticIn
- elasticOut
- cubic-bezier(x1, y1, x2, y2)
Note that cubic-bezier will create a custom easing curve following the CSS3 transition-timing-function specification `{@link http://www.w3.org/TR/css3-transitions/#transition-timing-function_tag}`. The four values specify points P1 and P2 of the curve
as (x1, y1, x2, y2). All values must be in the range [0, 1] or the definition is invalid.
* @markdown
* @singleton
*/
(Ext.fx.Easing = function() {
var math = Math,
pi = math.PI,
pow = math.pow,
sin = math.sin,
sqrt = math.sqrt,
abs = math.abs,
backInSeed = 1.70158;
Ext.apply(Ext.fx.Easing, {
linear: function(n) {
return n;
},
ease: function(n) {
var q = 0.07813 - n / 2,
Q = sqrt(0.0066 + q * q),
x = Q - q,
X = pow(abs(x), 1/3) * (x < 0 ? -1 : 1),
y = -Q - q,
Y = pow(abs(y), 1/3) * (y < 0 ? -1 : 1),
t = X + Y + 0.25;
return pow(1 - t, 2) * 3 * t * 0.1 + (1 - t) * 3 * t * t + t * t * t;
},
easeIn: function (n) {
return pow(n, 1.7);
},
easeOut: function (n) {
return pow(n, 0.48);
},
easeInOut: function(n) {
var q = 0.48 - n / 1.04,
Q = sqrt(0.1734 + q * q),
x = Q - q,
X = pow(abs(x), 1/3) * (x < 0 ? -1 : 1),
y = -Q - q,
Y = pow(abs(y), 1/3) * (y < 0 ? -1 : 1),
t = X + Y + 0.5;
return (1 - t) * 3 * t * t + t * t * t;
},
backIn: function (n) {
return n * n * ((backInSeed + 1) * n - backInSeed);
},
backOut: function (n) {
n = n - 1;
return n * n * ((backInSeed + 1) * n + backInSeed) + 1;
},
elasticIn: function (n) {
if (n === 0 || n === 1) {
return n;
}
var p = 0.3,
s = p / 4;
return pow(2, -10 * n) * sin((n - s) * (2 * pi) / p) + 1;
},
elasticOut: function (n) {
return 1 - Ext.fx.Easing.elasticIn(1 - n);
},
bounceIn: function (n) {
return 1 - Ext.fx.Easing.bounceOut(1 - n);
},
bounceOut: function (n) {
var s = 7.5625,
p = 2.75,
l;
if (n < (1 / p)) {
l = s * n * n;
} else {
if (n < (2 / p)) {
n -= (1.5 / p);
l = s * n * n + 0.75;
} else {
if (n < (2.5 / p)) {
n -= (2.25 / p);
l = s * n * n + 0.9375;
} else {
n -= (2.625 / p);
l = s * n * n + 0.984375;
}
}
}
return l;
}
});
Ext.apply(Ext.fx.Easing, {
'back-in': Ext.fx.Easing.backIn.prototype,
'back-out': Ext.fx.Easing.backOut.prototype,
'ease-in': Ext.fx.Easing.easeIn.prototype,
'ease-out': Ext.fx.Easing.easeOut.prototype,
'elastic-in': Ext.fx.Easing.elasticIn.prototype,
'elastic-out': Ext.fx.Easing.elasticIn.prototype,
'bounce-in': Ext.fx.Easing.bounceIn.prototype,
'bounce-out': Ext.fx.Easing.bounceOut.prototype,
'ease-in-out': Ext.fx.Easing.easeInOut.prototype
});
})();
/**
* @class Ext.fx.PropertyHandler
* @ignore
*/
Ext.fx.PropertyHandler = {
defaultHandler: {
pixelDefaults: ['width', 'height', 'top', 'left'],
unitRE: /^(-?\d*\.?\d*){1}(em|ex|px|in|cm|mm|pt|pc|%)*$/,
computeDelta: function(from, end, damper, initial, attr) {
damper = (typeof damper == 'number') ? damper : 1;
var match = this.unitRE.exec(from),
start, units;
if (match) {
from = match[1];
units = match[2];
// COMPAT Ext.Array.contains
if (!units && this.pixelDefaults.indexOf(attr) !== -1) {
units = 'px';
}
}
from = +from || 0;
match = this.unitRE.exec(end);
if (match) {
end = match[1];
units = match[2] || units;
}
end = +end || 0;
start = (initial != null) ? initial : from;
return {
from: from,
delta: (end - start) * damper,
units: units
};
},
get: function(from, end, damper, initialFrom, attr) {
var ln = from.length,
out = [],
i, initial, res, j, len;
for (i = 0; i < ln; i++) {
if (initialFrom) {
initial = initialFrom[i][1].from;
}
if (Ext.isArray(from[i][1]) && Ext.isArray(end)) {
res = [];
j = 0;
len = from[i][1].length;
for (; j < len; j++) {
res.push(this.computeDelta(from[i][1][j], end[j], damper, initial, attr));
}
out.push([from[i][0], res]);
}
else {
out.push([from[i][0], this.computeDelta(from[i][1], end, damper, initial, attr)]);
}
}
return out;
},
set: function(values, easing) {
var ln = values.length,
out = [],
i, val, res, len, j;
for (i = 0; i < ln; i++) {
val = values[i][1];
if (Ext.isArray(val)) {
res = [];
j = 0;
len = val.length;
for (; j < len; j++) {
res.push(val[j].from + (val[j].delta * easing) + (val[j].units || 0));
}
out.push([values[i][0], res]);
} else {
out.push([values[i][0], val.from + (val.delta * easing) + (val.units || 0)]);
}
}
return out;
}
},
color: {
rgbRE: /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i,
hexRE: /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i,
hex3RE: /^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i,
parseColor : function(color, damper) {
damper = (typeof damper == 'number') ? damper : 1;
var base,
out = false,
match;
Ext.each([this.hexRE, this.rgbRE, this.hex3RE], function(re, idx) {
base = (idx % 2 == 0) ? 16 : 10;
match = re.exec(color);
if (match && match.length == 4) {
if (idx == 2) {
match[1] += match[1];
match[2] += match[2];
match[3] += match[3];
}
out = {
red: parseInt(match[1], base),
green: parseInt(match[2], base),
blue: parseInt(match[3], base)
};
return false;
}
});
return out || color;
},
computeDelta: function(from, end, damper, initial) {
from = this.parseColor(from);
end = this.parseColor(end, damper);
var start = initial ? initial : from,
tfrom = typeof start,
tend = typeof end;
//Extra check for when the color string is not recognized.
if (tfrom == 'string' || tfrom == 'undefined'
|| tend == 'string' || tend == 'undefined') {
return end || start;
}
return {
from: from,
delta: {
red: Math.round((end.red - start.red) * damper),
green: Math.round((end.green - start.green) * damper),
blue: Math.round((end.blue - start.blue) * damper)
}
};
},
get: function(start, end, damper, initialFrom) {
var ln = start.length,
out = [],
i, initial;
for (i = 0; i < ln; i++) {
if (initialFrom) {
initial = initialFrom[i][1].from;
}
out.push([start[i][0], this.computeDelta(start[i][1], end, damper, initial)]);
}
return out;
},
set: function(values, easing) {
var ln = values.length,
out = [],
i, val, parsedString, from, delta;
for (i = 0; i < ln; i++) {
val = values[i][1];
if (val) {
from = val.from;
delta = val.delta;
//multiple checks to reformat the color if it can't recognized by computeDelta.
val = (typeof val == 'object' && 'red' in val)?
'rgb(' + val.red + ', ' + val.green + ', ' + val.blue + ')' : val;
val = (typeof val == 'object' && val.length)? val[0] : val;
if (typeof val == 'undefined') {
return [];
}
parsedString = typeof val == 'string'? val :
'rgb(' + [
(from.red + Math.round(delta.red * easing)) % 256,
(from.green + Math.round(delta.green * easing)) % 256,
(from.blue + Math.round(delta.blue * easing)) % 256
].join(',') + ')';
out.push([
values[i][0],
parsedString
]);
}
}
return out;
}
},
object: {
interpolate: function(prop, damper) {
damper = (typeof damper == 'number') ? damper : 1;
var out = {},
p;
for(p in prop) {
out[p] = parseFloat(prop[p], 10) * damper;
}
return out;
},
computeDelta: function(from, end, damper, initial) {
from = this.interpolate(from);
end = this.interpolate(end, damper);
var start = initial ? initial : from,
delta = {},
p;
for(p in end) {
delta[p] = end[p] - start[p];
}
return {
from: from,
delta: delta
};
},
get: function(start, end, damper, initialFrom) {
var ln = start.length,
out = [],
i, initial;
for (i = 0; i < ln; i++) {
if (initialFrom) {
initial = initialFrom[i][1].from;
}
out.push([start[i][0], this.computeDelta(start[i][1], end, damper, initial)]);
}
return out;
},
set: function(values, easing) {
var ln = values.length,
out = [],
outObject = {},
i, from, delta, val, p;
for (i = 0; i < ln; i++) {
val = values[i][1];
from = val.from;
delta = val.delta;
for (p in from) {
outObject[p] = Math.round(from[p] + delta[p] * easing);
}
out.push([
values[i][0],
outObject
]);
}
return out;
}
},
path: {
computeDelta: function(from, end, damper, initial) {
damper = (typeof damper == 'number') ? damper : 1;
var start;
from = +from || 0;
end = +end || 0;
start = (initial != null) ? initial : from;
return {
from: from,
delta: (end - start) * damper
};
},
forcePath: function(path) {
if (!Ext.isArray(path) && !Ext.isArray(path[0])) {
path = Ext.draw.Draw.parsePathString(path);
}
return path;
},
get: function(start, end, damper, initialFrom) {
var endPath = this.forcePath(end),
out = [],
startLn = start.length,
startPathLn, pointsLn, i, deltaPath, initial, j, k, path, startPath;
for (i = 0; i < startLn; i++) {
startPath = this.forcePath(start[i][1]);
deltaPath = Ext.draw.Draw.interpolatePaths(startPath, endPath);
startPath = deltaPath[0];
endPath = deltaPath[1];
startPathLn = startPath.length;
path = [];
for (j = 0; j < startPathLn; j++) {
deltaPath = [startPath[j][0]];
pointsLn = startPath[j].length;
for (k = 1; k < pointsLn; k++) {
initial = initialFrom && initialFrom[0][1][j][k].from;
deltaPath.push(this.computeDelta(startPath[j][k], endPath[j][k], damper, initial));
}
path.push(deltaPath);
}
out.push([start[i][0], path]);
}
return out;
},
set: function(values, easing) {
var ln = values.length,
out = [],
i, j, k, newPath, calcPath, deltaPath, deltaPathLn, pointsLn;
for (i = 0; i < ln; i++) {
deltaPath = values[i][1];
newPath = [];
deltaPathLn = deltaPath.length;
for (j = 0; j < deltaPathLn; j++) {
calcPath = [deltaPath[j][0]];
pointsLn = deltaPath[j].length;
for (k = 1; k < pointsLn; k++) {
calcPath.push(deltaPath[j][k].from + deltaPath[j][k].delta * easing);
}
newPath.push(calcPath.join(','));
}
out.push([values[i][0], newPath.join(',')]);
}
return out;
}
}
};
Ext.each([
'outlineColor',
'backgroundColor',
'borderColor',
'borderTopColor',
'borderRightColor',
'borderBottomColor',
'borderLeftColor',
'fill',
'stroke'
], function(prop) {
Ext.fx.PropertyHandler[prop] = Ext.fx.PropertyHandler.color;
}, Ext.fx.PropertyHandler);
/**
* @class Ext.fx.Animator
* Animation instance
This class is used to run keyframe based animations, which follows the CSS3 based animation structure.
Keyframe animations differ from typical from/to animations in that they offer the ability to specify values
at various points throughout the animation.
__Using Keyframes__
The {@link #keyframes} option is the most important part of specifying an animation when using this
class. A key frame is a point in a particular animation. We represent this as a percentage of the
total animation duration. At each key frame, we can specify the target values at that time. Note that
you *must* specify the values at 0% and 100%, the start and ending values. There is also a {@link keyframe}
event that fires after each key frame is reached.
__Example Usage__
In the example below, we modify the values of the element at each fifth throughout the animation.
Ext.create('Ext.fx.Animator', {
target: Ext.getBody().createChild({
style: {
width: '100px',
height: '100px',
'background-color': 'red'
}
}),
duration: 10000, // 10 seconds
keyframes: {
0: {
opacity: 1,
backgroundColor: 'FF0000'
},
20: {
x: 30,
opacity: 0.5
},
40: {
x: 130,
backgroundColor: '0000FF'
},
60: {
y: 80,
opacity: 0.3
},
80: {
width: 200,
y: 200
},
100: {
opacity: 1,
backgroundColor: '00FF00'
}
}
});
* @markdown
*/
Ext.fx.Animator = Ext.extend(Ext.util.Observable, {
isAnimator: true,
/**
* @cfg {Number} duration
* Time in milliseconds for the animation to last. Defaults to 250.
*/
duration: 250,
/**
* @cfg {Number} delay
* Time to delay before starting the animation. Defaults to 0.
*/
delay: 0,
/* private used to track a delayed starting time */
delayStart: 0,
/**
* @cfg {Boolean} dynamic
* Currently only for Component Animation: Only set a component's outer element size bypassing layouts. Set to true to do full layouts for every frame of the animation. Defaults to false.
*/
dynamic: false,
/**
* @cfg {String} easing
This describes how the intermediate values used during a transition will be calculated. It allows for a transition to change
speed over its duration.
- backIn
- backOut
- bounceIn
- bounceOut
- ease
- easeIn
- easeOut
- easeInOut
- elasticIn
- elasticOut
- cubic-bezier(x1, y1, x2, y2)
Note that cubic-bezier will create a custom easing curve following the CSS3 transition-timing-function specification `{@link http://www.w3.org/TR/css3-transitions/#transition-timing-function_tag}`. The four values specify points P1 and P2 of the curve
as (x1, y1, x2, y2). All values must be in the range [0, 1] or the definition is invalid.
* @markdown
*/
easing: 'ease',
/**
* Flag to determine if the animation has started
* @property running
* @type boolean
*/
running: false,
/**
* Flag to determine if the animation is paused. Only set this to true if you need to
* keep the Anim instance around to be unpaused later; otherwise call {@link #end}.
* @property paused
* @type boolean
*/
paused: false,
/**
* @private
*/
damper: 1,
/**
* @cfg {Number} iterations
* Number of times to execute the animation. Defaults to 1.
*/
iterations: 1,
/**
* Current iteration the animation is running.
* @property currentIteration
* @type int
*/
currentIteration: 0,
/**
* Current keyframe step of the animation.
* @property keyframeStep
* @type Number
*/
keyframeStep: 0,
/**
* @private
*/
animKeyFramesRE: /^(from|to|\d+%?)$/,
/**
* @cfg {Ext.fx.target} target
* The Ext.fx.target to apply the animation to. If not specified during initialization, this can be passed to the applyAnimator
* method to apply the same animation to many targets.
*/
/**
* @cfg {Object} keyframes
* Animation keyframes follow the CSS3 Animation configuration pattern. 'from' is always considered '0%' and 'to'
* is considered '100%'.<b>Every keyframe declaration must have a keyframe rule for 0% and 100%, possibly defined using
* "from" or "to"</b>. A keyframe declaration without these keyframe selectors is invalid and will not be available for
* animation. The keyframe declaration for a keyframe rule consists of properties and values. Properties that are unable to
* be animated are ignored in these rules, with the exception of 'easing' which can be changed at each keyframe. For example:
<pre><code>
keyframes : {
'0%': {
left: 100
},
'40%': {
left: 150
},
'60%': {
left: 75
},
'100%': {
left: 100
}
}
</code></pre>
*/
constructor: function(config) {
var me = this;
config = Ext.apply(me, config || {});
me.config = config;
me.id = Ext.id(null, 'ext-animator-');
me.addEvents(
/**
* @event beforeanimate
* Fires before the animation starts. A handler can return false to cancel the animation.
* @param {Ext.fx.Animator} this
*/
'beforeanimate',
/**
* @event keyframe
* Fires at each keyframe.
* @param {Ext.fx.Animator} this
* @param {Number} keyframe step number
*/
'keyframe',
/**
* @event afteranimate
* Fires when the animation is complete.
* @param {Ext.fx.Animator} this
* @param {Date} startTime
*/
'afteranimate'
);
Ext.fx.Animator.superclass.constructor.call(me, config);
me.timeline = [];
me.createTimeline(me.keyframes);
if (me.target) {
me.applyAnimator(me.target);
Ext.fx.Manager.addAnim(me);
}
},
/**
* @private
*/
sorter: function (a, b) {
return a.pct - b.pct;
},
/**
* @private
* Takes the given keyframe configuration object and converts it into an ordered array with the passed attributes per keyframe
* or applying the 'to' configuration to all keyframes. Also calculates the proper animation duration per keyframe.
*/
createTimeline: function(keyframes) {
var me = this,
attrs = [],
to = me.to || {},
duration = me.duration,
prevMs, ms, i, ln, pct, attr;
for (pct in keyframes) {
if (keyframes.hasOwnProperty(pct) && me.animKeyFramesRE.test(pct)) {
attr = {attrs: Ext.apply(keyframes[pct], to)};
// CSS3 spec allow for from/to to be specified.
if (pct == "from") {
pct = 0;
}
else if (pct == "to") {
pct = 100;
}
// convert % values into integers
attr.pct = parseInt(pct, 10);
attrs.push(attr);
}
}
// Sort by pct property
// COMPAT Array
attrs.sort(me.sorter);
// Only an end
//if (attrs[0].pct) {
// attrs.unshift({pct: 0, attrs: element.attrs});
//}
ln = attrs.length;
for (i = 0; i < ln; i++) {
prevMs = (attrs[i - 1]) ? duration * (attrs[i - 1].pct / 100) : 0;
ms = duration * (attrs[i].pct / 100);
me.timeline.push({
duration: ms - prevMs,
attrs: attrs[i].attrs
});
}
},
/**
* Applies animation to the Ext.fx.target
* @private
* @param target
* @type string/object
*/
applyAnimator: function(target) {
var me = this,
anims = [],
timeline = me.timeline,
ln = timeline.length,
anim, easing, damper, attrs, i;
if (me.fireEvent('beforeanimate', me) !== false) {
for (i = 0; i < ln; i++) {
anim = timeline[i];
attrs = anim.attrs;
easing = attrs.easing || me.easing;
damper = attrs.damper || me.damper;
delete attrs.easing;
delete attrs.damper;
anim = new Ext.fx.Anim({
target: target,
easing: easing,
damper: damper,
duration: anim.duration,
paused: true,
to: attrs
});
anims.push(anim);
}
me.animations = anims;
me.target = anim.target;
for (i = 0; i < ln - 1; i++) {
anim = anims[i];
anim.nextAnim = anims[i + 1];
anim.on('afteranimate', function() {
this.nextAnim.paused = false;
});
anim.on('afteranimate', function() {
this.fireEvent('keyframe', this, ++this.keyframeStep);
}, me);
}
anims[ln - 1].on('afteranimate', function() {
this.lastFrame();
}, me);
}
},
/*
* @private
* Fires beforeanimate and sets the running flag.
*/
start: function(startTime) {
var me = this,
delay = me.delay,
delayStart = me.delayStart,
delayDelta;
if (delay) {
if (!delayStart) {
me.delayStart = startTime;
return;
}
else {
delayDelta = startTime - delayStart;
if (delayDelta < delay) {
return;
}
else {
// Compensate for frame delay;
startTime = new Date(delayStart.getTime() + delay);
}
}
}
if (me.fireEvent('beforeanimate', me) !== false) {
me.startTime = startTime;
me.running = true;
me.animations[me.keyframeStep].paused = false;
}
},
/*
* @private
* Perform lastFrame cleanup and handle iterations
* @returns a hash of the new attributes.
*/
lastFrame: function() {
var me = this,
iter = me.iterations,
iterCount = me.currentIteration;
iterCount++;
if (iterCount < iter) {
me.startTime = new Date();
me.currentIteration = iterCount;
me.keyframeStep = 0;
me.applyAnimator(me.target);
me.animations[me.keyframeStep].paused = false;
}
else {
me.currentIteration = 0;
me.end();
}
},
/*
* Fire afteranimate event and end the animation. Usually called automatically when the
* animation reaches its final frame, but can also be called manually to pre-emptively
* stop and destroy the running animation.
*/
end: function() {
var me = this;
me.fireEvent('afteranimate', me, me.startTime, new Date() - me.startTime);
}
});
/**
* @class Ext.fx.Anim
*
* This class manages animation for a specific {@link #target}. The animation allows
* animation of various properties on the target, such as size, position, color and others.
*
* ## Starting Conditions
* The starting conditions for the animation are provided by the {@link #from} configuration.
* Any/all of the properties in the {@link #from} configuration can be specified. If a particular
* property is not defined, the starting value for that property will be read directly from the target.
*
* ## End Conditions
* The ending conditions for the animation are provided by the {@link #to} configuration. These mark
* the final values once the animations has finished. The values in the {@link #from} can mirror
* those in the {@link #to} configuration to provide a starting point.
*
* ## Other Options
* - {@link #duration}: Specifies the time period of the animation.
* - {@link #easing}: Specifies the easing of the animation.
* - {@link #iterations}: Allows the animation to repeat a number of times.
* - {@link #alternate}: Used in conjunction with {@link #iterations}, reverses the direction every second iteration.
*
* ## Example Code
*
* var myComponent = Ext.create('Ext.Component', {
* renderTo: document.body,
* width: 200,
* height: 200,
* style: 'border: 1px solid red;'
* });
*
* new Ext.fx.Anim({
* target: myComponent,
* duration: 1000,
* from: {
* width: 400 //starting width 400
* },
* to: {
* width: 300, //end width 300
* height: 300 // end width 300
* }
* });
*/
Ext.fx.Anim = Ext.extend(Ext.util.Observable, {
isAnimation: true,
/**
* @cfg {Number} duration
* Time in milliseconds for a single animation to last. Defaults to 250. If the {@link #iterations} property is
* specified, then each animate will take the same duration for each iteration.
*/
duration: 250,
/**
* @cfg {Number} delay
* Time to delay before starting the animation. Defaults to 0.
*/
delay: 0,
/* private used to track a delayed starting time */
delayStart: 0,
/**
* @cfg {Boolean} dynamic
* Currently only for Component Animation: Only set a component's outer element size bypassing layouts. Set to true to do full layouts for every frame of the animation. Defaults to false.
*/
dynamic: false,
/**
* @cfg {String} easing
This describes how the intermediate values used during a transition will be calculated. It allows for a transition to change
speed over its duration.
-backIn
-backOut
-bounceIn
-bounceOut
-ease
-easeIn
-easeOut
-easeInOut
-elasticIn
-elasticOut
-cubic-bezier(x1, y1, x2, y2)
Note that cubic-bezier will create a custom easing curve following the CSS3 transition-timing-function specification `{@link http://www.w3.org/TR/css3-transitions/#transition-timing-function_tag}`. The four values specify points P1 and P2 of the curve
as (x1, y1, x2, y2). All values must be in the range [0, 1] or the definition is invalid.
* @markdown
*/
easing: 'ease',
/**
* @cfg {Object} keyframes
* Animation keyframes follow the CSS3 Animation configuration pattern. 'from' is always considered '0%' and 'to'
* is considered '100%'.<b>Every keyframe declaration must have a keyframe rule for 0% and 100%, possibly defined using
* "from" or "to"</b>. A keyframe declaration without these keyframe selectors is invalid and will not be available for
* animation. The keyframe declaration for a keyframe rule consists of properties and values. Properties that are unable to
* be animated are ignored in these rules, with the exception of 'easing' which can be changed at each keyframe. For example:
<pre><code>
keyframes : {
'0%': {
left: 100
},
'40%': {
left: 150
},
'60%': {
left: 75
},
'100%': {
left: 100
}
}
</code></pre>
*/
/**
* @private
*/
damper: 1,
/**
* @private
*/
bezierRE: /^(?:cubic-)?bezier\(([^,]+),([^,]+),([^,]+),([^\)]+)\)/,
/**
* Run the animation from the end to the beginning
* Defaults to false.
* @cfg {Boolean} reverse
*/
reverse: false,
/**
* Flag to determine if the animation has started
* @property running
* @type boolean
*/
running: false,
/**
* Flag to determine if the animation is paused. Only set this to true if you need to
* keep the Anim instance around to be unpaused later; otherwise call {@link #end}.
* @property paused
* @type boolean
*/
paused: false,
/**
* Number of times to execute the animation. Defaults to 1.
* @cfg {int} iterations
*/
iterations: 1,
/**
* Used in conjunction with iterations to reverse the animation each time an iteration completes.
* @cfg {Boolean} alternate
* Defaults to false.
*/
alternate: false,
/**
* Current iteration the animation is running.
* @property currentIteration
* @type int
*/
currentIteration: 0,
/**
* Starting time of the animation.
* @property startTime
* @type Date
*/
startTime: 0,
/**
* Contains a cache of the interpolators to be used.
* @private
* @property propHandlers
* @type Object
*/
/**
* @cfg {String/Object} target
* The {@link Ext.fx.target.Target} to apply the animation to. This should only be specified when creating an Ext.fx.Anim directly.
* The target does not need to be a {@link Ext.fx.target.Target} instance, it can be the underlying object. For example, you can
* pass a Component, Element or Sprite as the target and the Anim will create the appropriate {@link Ext.fx.target.Target} object
* automatically.
*/
/**
* @cfg {Object} from
* An object containing property/value pairs for the beginning of the animation. If not specified, the current state of the
* Ext.fx.target will be used. For example:
<pre><code>
from : {
opacity: 0, // Transparent
color: '#ffffff', // White
left: 0
}
</code></pre>
*/
/**
* @cfg {Object} to
* An object containing property/value pairs for the end of the animation. For example:
<pre><code>
to : {
opacity: 1, // Opaque
color: '#00ff00', // Green
left: 500
}
</code></pre>
*/
// @private
constructor: function(config) {
var me = this;
config = config || {};
// If keyframes are passed, they really want an Animator instead.
if (config.keyframes) {
return new Ext.fx.Animator(config);
}
config = Ext.apply(me, config);
if (me.from === undefined) {
me.from = {};
}
me.propHandlers = {};
me.config = config;
me.target = Ext.fx.Manager.createTarget(me.target);
me.easingFn = Ext.fx.Easing[me.easing];
me.target.dynamic = me.dynamic;
// If not a pre-defined curve, try a cubic-bezier
if (!me.easingFn) {
me.easingFn = String(me.easing).match(me.bezierRE);
if (me.easingFn && me.easingFn.length == 5) {
var curve = me.easingFn;
me.easingFn = Ext.fx.cubicBezier(+curve[1], +curve[2], +curve[3], +curve[4]);
}
}
me.id = Ext.id(null, 'ext-anim-');
Ext.fx.Manager.addAnim(me);
me.addEvents(
/**
* @event beforeanimate
* Fires before the animation starts. A handler can return false to cancel the animation.
* @param {Ext.fx.Anim} this
*/
'beforeanimate',
/**
* @event afteranimate
* Fires when the animation is complete.
* @param {Ext.fx.Anim} this
* @param {Date} startTime
*/
'afteranimate',
/**
* @event lastframe
* Fires when the animation's last frame has been set.
* @param {Ext.fx.Anim} this
* @param {Date} startTime
*/
'lastframe'
);
Ext.fx.Anim.superclass.constructor.call(me, config);
if (config.callback) {
me.on('afteranimate', config.callback, config.scope);
}
return me;
},
/**
* @private
* Helper to the target
*/
setAttr: function(attr, value) {
return Ext.fx.Manager.items.get(this.id).setAttr(this.target, attr, value);
},
/*
* @private
* Set up the initial currentAttrs hash.
*/
initAttrs: function() {
var me = this,
from = me.from,
to = me.to,
initialFrom = me.initialFrom || {},
out = {},
start, end, propHandler, attr;
for (attr in to) {
if (to.hasOwnProperty(attr)) {
start = me.target.getAttr(attr, from[attr]);
end = to[attr];
// Use default (numeric) property handler
if (!Ext.fx.PropertyHandler[attr]) {
if (Ext.isObject(end)) {
propHandler = me.propHandlers[attr] = Ext.fx.PropertyHandler.object;
} else {
propHandler = me.propHandlers[attr] = Ext.fx.PropertyHandler.defaultHandler;
}
}
// Use custom handler
else {
propHandler = me.propHandlers[attr] = Ext.fx.PropertyHandler[attr];
}
out[attr] = propHandler.get(start, end, me.damper, initialFrom[attr], attr);
}
}
me.currentAttrs = out;
},
/*
* @private
* Fires beforeanimate and sets the running flag.
*/
start: function(startTime) {
var me = this,
delay = me.delay,
delayStart = me.delayStart,
delayDelta;
if (delay) {
if (!delayStart) {
me.delayStart = startTime;
return;
}
else {
delayDelta = startTime - delayStart;
if (delayDelta < delay) {
return;
}
else {
// Compensate for frame delay;
startTime = new Date(delayStart.getTime() + delay);
}
}
}
if (me.fireEvent('beforeanimate', me) !== false) {
me.startTime = startTime;
if (!me.paused && !me.currentAttrs) {
me.initAttrs();
}
me.running = true;
}
},
/*
* @private
* Calculate attribute value at the passed timestamp.
* @returns a hash of the new attributes.
*/
runAnim: function(elapsedTime) {
var me = this,
attrs = me.currentAttrs,
duration = me.duration,
easingFn = me.easingFn,
propHandlers = me.propHandlers,
ret = {},
easing, values, attr, lastFrame;
if (elapsedTime >= duration) {
elapsedTime = duration;
lastFrame = true;
}
if (me.reverse) {
elapsedTime = duration - elapsedTime;
}
for (attr in attrs) {
if (attrs.hasOwnProperty(attr)) {
values = attrs[attr];
easing = lastFrame ? 1 : easingFn(elapsedTime / duration);
ret[attr] = propHandlers[attr].set(values, easing);
}
}
return ret;
},
/*
* @private
* Perform lastFrame cleanup and handle iterations
* @returns a hash of the new attributes.
*/
lastFrame: function() {
var me = this,
iter = me.iterations,
iterCount = me.currentIteration;
iterCount++;
if (iterCount < iter) {
if (me.alternate) {
me.reverse = !me.reverse;
}
me.startTime = new Date();
me.currentIteration = iterCount;
// Turn off paused for CSS3 Transitions
me.paused = false;
}
else {
me.currentIteration = 0;
me.end();
me.fireEvent('lastframe', me, me.startTime);
}
},
/*
* Fire afteranimate event and end the animation. Usually called automatically when the
* animation reaches its final frame, but can also be called manually to pre-emptively
* stop and destroy the running animation.
*/
end: function() {
var me = this;
me.startTime = 0;
me.paused = false;
me.running = false;
Ext.fx.Manager.removeAnim(me);
me.fireEvent('afteranimate', me, me.startTime);
}
});
// Set flag to indicate that Fx is available. Class might not be available immediately.
Ext.enableFx = true;
/**
* @class Ext.fx.target.Target
This class specifies a generic target for an animation. It provides a wrapper around a
series of different types of objects to allow for a generic animation API.
A target can be a single object or a Composite object containing other objects that are
to be animated. This class and it's subclasses are generally not created directly, the
underlying animation will create the appropriate Ext.fx.target.Target object by passing
the instance to be animated.
The following types of objects can be animated:
- {@link #Ext.fx.target.Component Components}
- {@link #Ext.fx.target.Element Elements}
- {@link #Ext.fx.target.Sprite Sprites}
* @markdown
* @abstract
* @constructor
* @param {Mixed} target The object to be animated
*/
Ext.fx.target.Target = Ext.extend(Object, {
isAnimTarget: true,
constructor: function(target) {
this.target = target;
this.id = this.getId();
},
getId: function() {
return this.target.id;
}
});
/**
* @class Ext.fx.target.Sprite
* @extends Ext.fx.target.Target
This class represents a animation target for a {@link Ext.draw.Sprite}. In general this class will not be
created directly, the {@link Ext.draw.Sprite} will be passed to the animation and
and the appropriate target will be created.
* @markdown
*/
Ext.fx.target.Sprite = Ext.extend(Ext.fx.target.Target, {
type: 'draw',
getFromPrim: function(sprite, attr) {
var o;
if (attr == 'translate') {
o = {
x: sprite.attr.translation.x || 0,
y: sprite.attr.translation.y || 0
};
}
else if (attr == 'rotate') {
o = {
degrees: sprite.attr.rotation.degrees || 0,
x: sprite.attr.rotation.x,
y: sprite.attr.rotation.y
};
}
else {
o = sprite.attr[attr];
}
return o;
},
getAttr: function(attr, val) {
return [[this.target, val != undefined ? val : this.getFromPrim(this.target, attr)]];
},
setAttr: function(targetData) {
var ln = targetData.length,
spriteArr = [],
attrs, attr, attrArr, attPtr, spritePtr, idx, value, i, j, x, y, ln2;
for (i = 0; i < ln; i++) {
attrs = targetData[i].attrs;
for (attr in attrs) {
attrArr = attrs[attr];
ln2 = attrArr.length;
for (j = 0; j < ln2; j++) {
spritePtr = attrArr[j][0];
attPtr = attrArr[j][1];
if (attr === 'translate') {
value = {
x: attPtr.x,
y: attPtr.y
};
}
else if (attr === 'rotate') {
x = attPtr.x;
if (isNaN(x)) {
x = null;
}
y = attPtr.y;
if (isNaN(y)) {
y = null;
}
value = {
degrees: attPtr.degrees,
x: x,
y: y
};
}
else if (attr === 'width' || attr === 'height' || attr === 'x' || attr === 'y') {
value = parseFloat(attPtr);
}
else {
value = attPtr;
}
// COMPAT indexOf
idx = spriteArr.indexOf(spritePtr);
if (idx == -1) {
spriteArr.push([spritePtr, {}]);
idx = spriteArr.length - 1;
}
spriteArr[idx][1][attr] = value;
}
}
}
ln = spriteArr.length;
for (i = 0; i < ln; i++) {
spritePtr = spriteArr[i];
spritePtr[0].setAttributes(spritePtr[1]);
}
this.target.tween();
}
});
/**
* @class Ext.fx.target.CompositeSprite
* @extends Ext.fx.target.Sprite
This class represents a animation target for a {@link Ext.draw.CompositeSprite}. It allows
each {@link Ext.draw.Sprite} in the group to be animated as a whole. In general this class will not be
created directly, the {@link Ext.draw.CompositeSprite} will be passed to the animation and
and the appropriate target will be created.
* @markdown
*/
Ext.fx.target.CompositeSprite = Ext.extend(Ext.fx.target.Sprite, {
getAttr: function(attr, val) {
var out = [],
target = this.target;
target.each(function(sprite) {
out.push([sprite, val != undefined ? val : this.getFromPrim(sprite, attr)]);
}, this);
return out;
}
});
/**
* @class Ext.util.Animate
* This animation class is a mixin.
*
* Ext.util.Animate provides an API for the creation of animated transitions of properties and styles.
* This class is used as a mixin and currently applied to {@link Ext.core.Element}, {@link Ext.CompositeElement},
* {@link Ext.draw.Sprite}, {@link Ext.draw.CompositeSprite}, and {@link Ext.Component}. Note that Components
* have a limited subset of what attributes can be animated such as top, left, x, y, height, width, and
* opacity (color, paddings, and margins can not be animated).
*
* ## Animation Basics
*
* All animations require three things - `easing`, `duration`, and `to` (the final end value for each property)
* you wish to animate. Easing and duration are defaulted values specified below.
* Easing describes how the intermediate values used during a transition will be calculated.
* {@link Ext.fx.Anim#easing Easing} allows for a transition to change speed over its duration.
* You may use the defaults for easing and duration, but you must always set a
* {@link Ext.fx.Anim#to to} property which is the end value for all animations.
*
* Popular element 'to' configurations are:
*
* - opacity
* - x
* - y
* - color
* - height
* - width
*
* Popular sprite 'to' configurations are:
*
* - translation
* - path
* - scale
* - stroke
* - rotation
*
* The default duration for animations is 250 (which is a 1/4 of a second). Duration is denoted in
* milliseconds. Therefore 1 second is 1000, 1 minute would be 60000, and so on. The default easing curve
* used for all animations is 'ease'. Popular easing functions are included and can be found in {@link Ext.fx.Anim#easing Easing}.
*
* For example, a simple animation to fade out an element with a default easing and duration:
*
* var p1 = Ext.get('myElementId');
*
* p1.animate({
* to: {
* opacity: 0
* }
* });
*
* To make this animation fade out in a tenth of a second:
*
* var p1 = Ext.get('myElementId');
*
* p1.animate({
* duration: 100,
* to: {
* opacity: 0
* }
* });
*
* ## Animation Queues
*
* By default all animations are added to a queue which allows for animation via a chain-style API.
* For example, the following code will queue 4 animations which occur sequentially (one right after the other):
*
* p1.animate({
* to: {
* x: 500
* }
* }).animate({
* to: {
* y: 150
* }
* }).animate({
* to: {
* backgroundColor: '#f00' //red
* }
* }).animate({
* to: {
* opacity: 0
* }
* });
*
* You can change this behavior by calling the {@link Ext.util.Animate#syncFx syncFx} method and all
* subsequent animations for the specified target will be run concurrently (at the same time).
*
* p1.syncFx(); //this will make all animations run at the same time
*
* p1.animate({
* to: {
* x: 500
* }
* }).animate({
* to: {
* y: 150
* }
* }).animate({
* to: {
* backgroundColor: '#f00' //red
* }
* }).animate({
* to: {
* opacity: 0
* }
* });
*
* This works the same as:
*
* p1.animate({
* to: {
* x: 500,
* y: 150,
* backgroundColor: '#f00' //red
* opacity: 0
* }
* });
*
* The {@link Ext.util.Animate#stopAnimation stopAnimation} method can be used to stop any
* currently running animations and clear any queued animations.
*
* ## Animation Keyframes
*
* You can also set up complex animations with {@link Ext.fx.Anim#keyframe keyframe} which follows the
* CSS3 Animation configuration pattern. Note rotation, translation, and scaling can only be done for sprites.
* The previous example can be written with the following syntax:
*
* p1.animate({
* duration: 1000, //one second total
* keyframes: {
* 25: { //from 0 to 250ms (25%)
* x: 0
* },
* 50: { //from 250ms to 500ms (50%)
* y: 0
* },
* 75: { //from 500ms to 750ms (75%)
* backgroundColor: '#f00' //red
* },
* 100: { //from 750ms to 1sec
* opacity: 0
* }
* }
* });
*
* ## Animation Events
*
* Each animation you create has events for {@link Ext.fx.Anim#beforeanimation beforeanimation},
* {@link Ext.fx.Anim#afteranimate afteranimate}, and {@link Ext.fx.Anim#lastframe lastframe}.
* Keyframed animations adds an additional {@link Ext.fx.Animator#keyframe keyframe} event which
* fires for each keyframe in your animation.
*
* All animations support the {@link Ext.util.Observable#listeners listeners} configuration to attact functions to these events.
*
* startAnimate: function() {
* var p1 = Ext.get('myElementId');
* p1.animate({
* duration: 100,
* to: {
* opacity: 0
* },
* listeners: {
* beforeanimate: function() {
* // Execute my custom method before the animation
* this.myBeforeAnimateFn();
* },
* afteranimate: function() {
* // Execute my custom method after the animation
* this.myAfterAnimateFn();
* },
* scope: this
* });
* },
* myBeforeAnimateFn: function() {
* // My custom logic
* },
* myAfterAnimateFn: function() {
* // My custom logic
* }
*
* Due to the fact that animations run asynchronously, you can determine if an animation is currently
* running on any target by using the {@link Ext.util.Animate#getActiveAnimation getActiveAnimation}
* method. This method will return false if there are no active animations or return the currently
* running {@link Ext.fx.Anim} instance.
*
* In this example, we're going to wait for the current animation to finish, then stop any other
* queued animations before we fade our element's opacity to 0:
*
* var curAnim = p1.getActiveAnimation();
* if (curAnim) {
* curAnim.on('afteranimate', function() {
* p1.stopAnimation();
* p1.animate({
* to: {
* opacity: 0
* }
* });
* });
* }
*
* @docauthor Jamie Avins <jamie@sencha.com>
*/
Ext.util.Animate = {
/**
* <p>Perform custom animation on this object.<p>
* <p>This method is applicable to both the the {@link Ext.Component Component} class and the {@link Ext.core.Element Element} class.
* It performs animated transitions of certain properties of this object over a specified timeline.</p>
* <p>The sole parameter is an object which specifies start property values, end property values, and properties which
* describe the timeline. Of the properties listed below, only <b><code>to</code></b> is mandatory.</p>
* <p>Properties include<ul>
* <li><code>from</code> <div class="sub-desc">An object which specifies start values for the properties being animated.
* If not supplied, properties are animated from current settings. The actual properties which may be animated depend upon
* ths object being animated. See the sections below on Element and Component animation.<div></li>
* <li><code>to</code> <div class="sub-desc">An object which specifies end values for the properties being animated.</div></li>
* <li><code>duration</code><div class="sub-desc">The duration <b>in milliseconds</b> for which the animation will run.</div></li>
* <li><code>easing</code> <div class="sub-desc">A string value describing an easing type to modify the rate of change from the default linear to non-linear. Values may be one of:<code><ul>
* <li>ease</li>
* <li>easeIn</li>
* <li>easeOut</li>
* <li>easeInOut</li>
* <li>backIn</li>
* <li>backOut</li>
* <li>elasticIn</li>
* <li>elasticOut</li>
* <li>bounceIn</li>
* <li>bounceOut</li>
* </ul></code></div></li>
* <li><code>keyframes</code> <div class="sub-desc">This is an object which describes the state of animated properties at certain points along the timeline.
* it is an object containing properties who's names are the percentage along the timeline being described and who's values specify the animation state at that point.</div></li>
* <li><code>listeners</code> <div class="sub-desc">This is a standard {@link Ext.util.Observable#listeners listeners} configuration object which may be used
* to inject behaviour at either the <code>beforeanimate</code> event or the <code>afteranimate</code> event.</div></li>
* </ul></p>
* <h3>Animating an {@link Ext.core.Element Element}</h3>
* When animating an Element, the following properties may be specified in <code>from</code>, <code>to</code>, and <code>keyframe</code> objects:<ul>
* <li><code>x</code> <div class="sub-desc">The page X position in pixels.</div></li>
* <li><code>y</code> <div class="sub-desc">The page Y position in pixels</div></li>
* <li><code>left</code> <div class="sub-desc">The element's CSS <code>left</code> value. Units must be supplied.</div></li>
* <li><code>top</code> <div class="sub-desc">The element's CSS <code>top</code> value. Units must be supplied.</div></li>
* <li><code>width</code> <div class="sub-desc">The element's CSS <code>width</code> value. Units must be supplied.</div></li>
* <li><code>height</code> <div class="sub-desc">The element's CSS <code>height</code> value. Units must be supplied.</div></li>
* <li><code>scrollLeft</code> <div class="sub-desc">The element's <code>scrollLeft</code> value.</div></li>
* <li><code>scrollTop</code> <div class="sub-desc">The element's <code>scrollLeft</code> value.</div></li>
* <li><code>opacity</code> <div class="sub-desc">The element's <code>opacity</code> value. This must be a value between <code>0</code> and <code>1</code>.</div></li>
* </ul>
* <p><b>Be aware than animating an Element which is being used by an Ext Component without in some way informing the Component about the changed element state
* will result in incorrect Component behaviour. This is because the Component will be using the old state of the element. To avoid this problem, it is now possible to
* directly animate certain properties of Components.</b></p>
* <h3>Animating a {@link Ext.Component Component}</h3>
* When animating an Element, the following properties may be specified in <code>from</code>, <code>to</code>, and <code>keyframe</code> objects:<ul>
* <li><code>x</code> <div class="sub-desc">The Component's page X position in pixels.</div></li>
* <li><code>y</code> <div class="sub-desc">The Component's page Y position in pixels</div></li>
* <li><code>left</code> <div class="sub-desc">The Component's <code>left</code> value in pixels.</div></li>
* <li><code>top</code> <div class="sub-desc">The Component's <code>top</code> value in pixels.</div></li>
* <li><code>width</code> <div class="sub-desc">The Component's <code>width</code> value in pixels.</div></li>
* <li><code>width</code> <div class="sub-desc">The Component's <code>width</code> value in pixels.</div></li>
* <li><code>dynamic</code> <div class="sub-desc">Specify as true to update the Component's layout (if it is a Container) at every frame
* of the animation. <i>Use sparingly as laying out on every intermediate size change is an expensive operation</i>.</div></li>
* </ul>
* <p>For example, to animate a Window to a new size, ensuring that its internal layout, and any shadow is correct:</p>
* <pre><code>
myWindow = Ext.create('Ext.window.Window', {
title: 'Test Component animation',
width: 500,
height: 300,
layout: {
type: 'hbox',
align: 'stretch'
},
items: [{
title: 'Left: 33%',
margins: '5 0 5 5',
flex: 1
}, {
title: 'Left: 66%',
margins: '5 5 5 5',
flex: 2
}]
});
myWindow.show();
myWindow.header.el.on('click', function() {
myWindow.animate({
to: {
width: (myWindow.getWidth() == 500) ? 700 : 500,
height: (myWindow.getHeight() == 300) ? 400 : 300,
}
});
});
</code></pre>
* <p>For performance reasons, by default, the internal layout is only updated when the Window reaches its final <code>"to"</code> size. If dynamic updating of the Window's child
* Components is required, then configure the animation with <code>dynamic: true</code> and the two child items will maintain their proportions during the animation.</p>
* @param {Object} config An object containing properties which describe the animation's start and end states, and the timeline of the animation.
* @return {Object} this
*/
animate: function(animObj) {
var me = this;
if (Ext.fx.Manager.hasFxBlock(me.id)) {
return me;
}
Ext.fx.Manager.queueFx(new Ext.fx.Anim(me.anim(animObj)));
return this;
},
// @private - process the passed fx configuration.
anim: function(config) {
if (!Ext.isObject(config)) {
return (config) ? {} : false;
}
var me = this;
if (config.stopAnimation) {
me.stopAnimation();
}
Ext.applyIf(config, Ext.fx.Manager.getFxDefaults(me.id));
return Ext.apply({
target: me,
paused: true
}, config);
},
/**
* Stops any running effects and clears this object's internal effects queue if it contains
* any additional effects that haven't started yet.
* @return {Ext.core.Element} The Element
*/
stopAnimation: function() {
Ext.fx.Manager.stopAnimation(this.id);
return this;
},
/**
* Ensures that all effects queued after syncFx is called on this object are
* run concurrently. This is the opposite of {@link #sequenceFx}.
* @return {Object} this
*/
syncFx: function() {
Ext.fx.Manager.setFxDefaults(this.id, {
concurrent: true
});
return this;
},
/**
* Ensures that all effects queued after sequenceFx is called on this object are
* run in sequence. This is the opposite of {@link #syncFx}.
* @return {Object} this
*/
sequenceFx: function() {
Ext.fx.Manager.setFxDefaults(this.id, {
concurrent: false
});
return this;
},
/**
* Returns thq current animation if this object has any effects actively running or queued, else returns false.
* @return {Mixed} anim if element has active effects, else false
*/
getActiveAnimation: function() {
return Ext.fx.Manager.getActiveAnimation(this.id);
}
};
/**
* @class Ext.layout.component.Draw
* @extends Ext.layout.component.Component
* @private
*
*/
Ext.layout.DrawLayout = Ext.extend(Ext.layout.AutoComponentLayout, {
type: 'draw',
onLayout : function(width, height) {
this.owner.surface.setSize(width, height);
Ext.layout.DrawLayout.superclass.onLayout.apply(this, arguments);
}
});
Ext.regLayout('draw', Ext.layout.DrawLayout);
/**
* @class Ext.draw.Color
* @extends Object
*
* Represents an RGB color and provides helper functions get
* color components in HSL color space.
*/
Ext.ns('Ext.draw.engine');
Ext.draw.Color = Ext.extend(Object, {
colorToHexRe: /(.*?)rgb\((\d+),\s*(\d+),\s*(\d+)\)/,
rgbRe: /\s*rgba?\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*(,\s*[0-9\.]+\s*)?\)\s*/,
hexRe: /\s*#([0-9a-fA-F][0-9a-fA-F]?)([0-9a-fA-F][0-9a-fA-F]?)([0-9a-fA-F][0-9a-fA-F]?)\s*/,
/**
* @cfg {Number} lightnessFactor
*
* The default factor to compute the lighter or darker color. Defaults to 0.2.
*/
lightnessFactor: 0.2,
/**
* @constructor
* @param {Number} red Red component (0..255)
* @param {Number} green Green component (0..255)
* @param {Number} blue Blue component (0..255)
*/
// COMPAT Ext.util.Numbers -> Ext.Number
constructor : function(red, green, blue) {
var me = this,
clamp = Ext.util.Numbers.constrain;
me.r = clamp(red, 0, 255);
me.g = clamp(green, 0, 255);
me.b = clamp(blue, 0, 255);
},
/**
* Get the red component of the color, in the range 0..255.
* @return {Number}
*/
getRed: function() {
return this.r;
},
/**
* Get the green component of the color, in the range 0..255.
* @return {Number}
*/
getGreen: function() {
return this.g;
},
/**
* Get the blue component of the color, in the range 0..255.
* @return {Number}
*/
getBlue: function() {
return this.b;
},
/**
* Get the RGB values.
* @return {Array}
*/
getRGB: function() {
var me = this;
return [me.r, me.g, me.b];
},
/**
* Get the equivalent HSL components of the color.
* @return {Array}
*/
getHSL: function() {
var me = this,
r = me.r / 255,
g = me.g / 255,
b = me.b / 255,
max = Math.max(r, g, b),
min = Math.min(r, g, b),
delta = max - min,
h,
s = 0,
l = 0.5 * (max + min);
// min==max means achromatic (hue is undefined)
if (min != max) {
s = (l < 0.5) ? delta / (max + min) : delta / (2 - max - min);
if (r == max) {
h = 60 * (g - b) / delta;
} else if (g == max) {
h = 120 + 60 * (b - r) / delta;
} else {
h = 240 + 60 * (r - g) / delta;
}
if (h < 0) {
h += 360;
}
if (h >= 360) {
h -= 360;
}
}
return [h, s, l];
},
/**
* Return a new color that is lighter than this color.
* @param {Number} factor Lighter factor (0..1), default to 0.2
* @return Ext.draw.Color
*/
getLighter: function(factor) {
var hsl = this.getHSL();
factor = factor || this.lightnessFactor;
// COMPAT Ext.util.Numbers -> Ext.Number
hsl[2] = Ext.util.Numbers.constrain(hsl[2] + factor, 0, 1);
return this.fromHSL(hsl[0], hsl[1], hsl[2]);
},
/**
* Return a new color that is darker than this color.
* @param {Number} factor Darker factor (0..1), default to 0.2
* @return Ext.draw.Color
*/
getDarker: function(factor) {
factor = factor || this.lightnessFactor;
return this.getLighter(-factor);
},
/**
* Return the color in the hex format, i.e. '#rrggbb'.
* @return {String}
*/
toString: function() {
var me = this,
round = Math.round,
r = round(me.r).toString(16),
g = round(me.g).toString(16),
b = round(me.b).toString(16);
r = (r.length == 1) ? '0' + r : r;
g = (g.length == 1) ? '0' + g : g;
b = (b.length == 1) ? '0' + b : b;
return ['#', r, g, b].join('');
},
/**
* Convert a color to hexadecimal format.
*
* @param {String|Array} color The color value (i.e 'rgb(255, 255, 255)', 'color: #ffffff').
* Can also be an Array, in this case the function handles the first member.
* @returns {String} The color in hexadecimal format.
*/
toHex: function(color) {
if (Ext.isArray(color)) {
color = color[0];
}
if (!Ext.isString(color)) {
return '';
}
if (color.substr(0, 1) === '#') {
return color;
}
var digits = this.colorToHexRe.exec(color);
if (Ext.isArray(digits)) {
var red = parseInt(digits[2], 10),
green = parseInt(digits[3], 10),
blue = parseInt(digits[4], 10),
rgb = blue | (green << 8) | (red << 16);
return digits[1] + '#' + ("000000" + rgb.toString(16)).slice(-6);
}
else {
return '';
}
},
/**
* Parse the string and create a new color.
*
* Supported formats: '#rrggbb', '#rgb', and 'rgb(r,g,b)'.
*
* If the string is not recognized, an undefined will be returned instead.
*
* @param {String} str Color in string.
* @returns Ext.draw.Color
*/
fromString: function(str) {
var values, r, g, b,
parse = parseInt;
if ((str.length == 4 || str.length == 7) && str.substr(0, 1) === '#') {
values = str.match(this.hexRe);
if (values) {
r = parse(values[1], 16) >> 0;
g = parse(values[2], 16) >> 0;
b = parse(values[3], 16) >> 0;
if (str.length == 4) {
r += (r * 16);
g += (g * 16);
b += (b * 16);
}
}
}
else {
values = str.match(this.rgbRe);
if (values) {
r = values[1];
g = values[2];
b = values[3];
}
}
return (typeof r == 'undefined') ? undefined : new Ext.draw.Color(r, g, b);
},
/**
* Returns the gray value (0 to 255) of the color.
*
* The gray value is calculated using the formula r*0.3 + g*0.59 + b*0.11.
*
* @returns {Number}
*/
getGrayscale: function() {
// http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
},
/**
* Create a new color based on the specified HSL values.
*
* @param {Number} h Hue component (0..359)
* @param {Number} s Saturation component (0..1)
* @param {Number} l Lightness component (0..1)
* @returns Ext.draw.Color
*/
fromHSL: function(h, s, l) {
var C, X, m, rgb = [],
abs = Math.abs,
floor = Math.floor;
if (s == 0 || h == null) {
// achromatic
rgb = [l, l, l];
}
else {
// http://en.wikipedia.org/wiki/HSL_and_HSV#From_HSL
// C is the chroma
// X is the second largest component
// m is the lightness adjustment
h /= 60;
C = s * (1 - abs(2 * l - 1));
X = C * (1 - abs(h - 2 * floor(h / 2) - 1));
m = l - C / 2;
switch (floor(h)) {
case 0:
rgb = [C, X, 0];
break;
case 1:
rgb = [X, C, 0];
break;
case 2:
rgb = [0, C, X];
break;
case 3:
rgb = [0, X, C];
break;
case 4:
rgb = [X, 0, C];
break;
case 5:
rgb = [C, 0, X];
break;
}
rgb = [rgb[0] + m, rgb[1] + m, rgb[2] + m];
}
return new Ext.draw.Color(rgb[0] * 255, rgb[1] * 255, rgb[2] * 255);
}
});
(function() {
var prototype = Ext.draw.Color.prototype;
Ext.draw.Color.fromHSL = function() {
return prototype.fromHSL.apply(prototype, arguments);
};
Ext.draw.Color.fromString = function() {
return prototype.fromString.apply(prototype, arguments);
};
Ext.draw.Color.toHex = function() {
return prototype.toHex.apply(prototype, arguments);
};
})();
/**
* @class Ext.draw.Draw
* Base Drawing class. Provides base drawing functions.
*/
Ext.draw.Draw = {
pathToStringRE: /,?([achlmqrstvxz]),?/gi,
pathCommandRE: /([achlmqstvz])[\s,]*((-?\d*\.?\d*(?:e[-+]?\d+)?\s*,?\s*)+)/ig,
pathValuesRE: /(-?\d*\.?\d*(?:e[-+]?\d+)?)\s*,?\s*/ig,
stopsRE: /^(\d+%?)$/,
radian: Math.PI / 180,
pi2: Math.PI * 2,
snapEndsIntervalWeights: [[0, 15], [20, 4], [30, 2], [40, 4], [50, 9], [60, 4], [70, 2], [80, 4], [100, 15]],
is: function(o, type) {
type = String(type).toLowerCase();
return (type == "object" && o === Object(o)) ||
(type == "undefined" && typeof o == type) ||
(type == "null" && o === null) ||
(type == "array" && Array.isArray && Array.isArray(o)) ||
(Object.prototype.toString.call(o).toLowerCase().slice(8, -1)) == type;
},
ellipsePath: function(sprite) {
var attr = sprite.attr;
return Ext.String.format("M{0},{1}A{2},{3},0,1,1,{0},{4}A{2},{3},0,1,1,{0},{1}z", attr.x, attr.y - attr.ry, attr.rx, attr.ry, attr.y + attr.ry);
},
rectPath: function(sprite) {
var attr = sprite.attr;
if (attr.radius) {
return Ext.String.format("M{0},{1}l{2},0a{3},{3},0,0,1,{3},{3}l0,{5}a{3},{3},0,0,1,{4},{3}l{6},0a{3},{3},0,0,1,{4},{4}l0,{7}a{3},{3},0,0,1,{3},{4}z", attr.x + attr.radius, attr.y, attr.width - attr.radius * 2, attr.radius, -attr.radius, attr.height - attr.radius * 2, attr.radius * 2 - attr.width, attr.radius * 2 - attr.height);
}
else {
return Ext.String.format("M{0},{1}l{2},0,0,{3},{4},0z", attr.x, attr.y, attr.width, attr.height, -attr.width);
}
},
// Convert the passed arrayPath to a proper SVG path string (d attribute)
pathToString: function(arrayPath) {
if (Ext.isArray(arrayPath)) {
arrayPath = arrayPath.join(',');
}
return arrayPath.replace(Ext.draw.Draw.pathToStringRE, "$1");
},
parsePathString: function (pathString) {
if (!pathString) {
return null;
}
var paramCounts = {a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0},
data = [],
me = this;
if (me.is(pathString, "array") && me.is(pathString[0], "array")) { // rough assumption
data = me.pathClone(pathString);
}
if (!data.length) {
Ext.draw.Draw.pathToString(pathString).replace(me.pathCommandRE, function (a, b, c) {
var params = [],
name = b.toLowerCase();
c.replace(me.pathValuesRE, function (a, b) {
b && params.push(+b);
});
if (name == "m" && params.length > 2) {
data.push([b].concat(params.splice(0, 2)));
name = "l";
b = (b == "m") ? "l" : "L";
}
while (params.length >= paramCounts[name]) {
data.push([b].concat(params.splice(0, paramCounts[name])));
if (!paramCounts[name]) {
break;
}
}
});
}
return data;
},
mapPath: function (path, matrix) {
if (!matrix) {
return path;
}
var x, y, i, ii, j, jj, pathi;
path = this.path2curve(path);
for (i = 0, ii = path.length; i < ii; i++) {
pathi = path[i];
for (j = 1, jj = pathi.length; j < jj-1; j += 2) {
x = matrix.x(pathi[j], pathi[j + 1]);
y = matrix.y(pathi[j], pathi[j + 1]);
pathi[j] = x;
pathi[j + 1] = y;
}
}
return path;
},
pathClone: function(pathArray) {
var res = [],
j, jj, i, ii;
if (!this.is(pathArray, "array") || !this.is(pathArray && pathArray[0], "array")) { // rough assumption
pathArray = this.parsePathString(pathArray);
}
for (i = 0, ii = pathArray.length; i < ii; i++) {
res[i] = [];
for (j = 0, jj = pathArray[i].length; j < jj; j++) {
res[i][j] = pathArray[i][j];
}
}
return res;
},
pathToAbsolute: function (pathArray) {
if (!this.is(pathArray, "array") || !this.is(pathArray && pathArray[0], "array")) { // rough assumption
pathArray = this.parsePathString(pathArray);
}
var res = [],
x = 0,
y = 0,
mx = 0,
my = 0,
i = 0,
ln = pathArray.length,
r, pathSegment, j, ln2;
// MoveTo initial x/y position
if (pathArray[0][0] == "M") {
x = +pathArray[0][1];
y = +pathArray[0][2];
mx = x;
my = y;
i++;
res[0] = ["M", x, y];
}
for (; i < ln; i++) {
r = res[i] = [];
pathSegment = pathArray[i];
if (pathSegment[0] != pathSegment[0].toUpperCase()) {
r[0] = pathSegment[0].toUpperCase();
switch (r[0]) {
// Elliptical Arc
case "A":
r[1] = pathSegment[1];
r[2] = pathSegment[2];
r[3] = pathSegment[3];
r[4] = pathSegment[4];
r[5] = pathSegment[5];
r[6] = +(pathSegment[6] + x);
r[7] = +(pathSegment[7] + y);
break;
// Vertical LineTo
case "V":
r[1] = +pathSegment[1] + y;
break;
// Horizontal LineTo
case "H":
r[1] = +pathSegment[1] + x;
break;
case "M":
// MoveTo
mx = +pathSegment[1] + x;
my = +pathSegment[2] + y;
default:
j = 1;
ln2 = pathSegment.length;
for (; j < ln2; j++) {
r[j] = +pathSegment[j] + ((j % 2) ? x : y);
}
}
}
else {
j = 0;
ln2 = pathSegment.length;
for (; j < ln2; j++) {
res[i][j] = pathSegment[j];
}
}
switch (r[0]) {
// ClosePath
case "Z":
x = mx;
y = my;
break;
// Horizontal LineTo
case "H":
x = r[1];
break;
// Vertical LineTo
case "V":
y = r[1];
break;
// MoveTo
case "M":
pathSegment = res[i];
ln2 = pathSegment.length;
mx = pathSegment[ln2 - 2];
my = pathSegment[ln2 - 1];
default:
pathSegment = res[i];
ln2 = pathSegment.length;
x = pathSegment[ln2 - 2];
y = pathSegment[ln2 - 1];
}
}
return res;
},
// Returns a path converted to a set of curveto commands
path2curve: function (path) {
var me = this,
points = me.pathToAbsolute(path),
ln = points.length,
attrs = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null},
i, seg, segLn, point;
for (i = 0; i < ln; i++) {
points[i] = me.command2curve(points[i], attrs);
if (points[i].length > 7) {
points[i].shift();
point = points[i];
while (point.length) {
points.splice(i++, 0, ["C"].concat(point.splice(0, 6)));
}
points.splice(i, 1);
ln = points.length;
}
seg = points[i];
segLn = seg.length;
attrs.x = seg[segLn - 2];
attrs.y = seg[segLn - 1];
attrs.bx = parseFloat(seg[segLn - 4]) || attrs.x;
attrs.by = parseFloat(seg[segLn - 3]) || attrs.y;
}
return points;
},
interpolatePaths: function (path, path2) {
var me = this,
p = me.pathToAbsolute(path),
p2 = me.pathToAbsolute(path2),
attrs = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null},
attrs2 = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null},
fixArc = function (pp, i) {
if (pp[i].length > 7) {
pp[i].shift();
var pi = pp[i];
while (pi.length) {
pp.splice(i++, 0, ["C"].concat(pi.splice(0, 6)));
}
pp.splice(i, 1);
ii = Math.max(p.length, p2.length || 0);
}
},
fixM = function (path1, path2, a1, a2, i) {
if (path1 && path2 && path1[i][0] == "M" && path2[i][0] != "M") {
path2.splice(i, 0, ["M", a2.x, a2.y]);
a1.bx = 0;
a1.by = 0;
a1.x = path1[i][1];
a1.y = path1[i][2];
ii = Math.max(p.length, p2.length || 0);
}
};
for (var i = 0, ii = Math.max(p.length, p2.length || 0); i < ii; i++) {
p[i] = me.command2curve(p[i], attrs);
fixArc(p, i);
(p2[i] = me.command2curve(p2[i], attrs2));
fixArc(p2, i);
fixM(p, p2, attrs, attrs2, i);
fixM(p2, p, attrs2, attrs, i);
var seg = p[i],
seg2 = p2[i],
seglen = seg.length,
seg2len = seg2.length;
attrs.x = seg[seglen - 2];
attrs.y = seg[seglen - 1];
attrs.bx = parseFloat(seg[seglen - 4]) || attrs.x;
attrs.by = parseFloat(seg[seglen - 3]) || attrs.y;
attrs2.bx = (parseFloat(seg2[seg2len - 4]) || attrs2.x);
attrs2.by = (parseFloat(seg2[seg2len - 3]) || attrs2.y);
attrs2.x = seg2[seg2len - 2];
attrs2.y = seg2[seg2len - 1];
}
return [p, p2];
},
//Returns any path command as a curveto command based on the attrs passed
command2curve: function (pathCommand, d) {
var me = this;
if (!pathCommand) {
return ["C", d.x, d.y, d.x, d.y, d.x, d.y];
}
if (pathCommand[0] != "T" && pathCommand[0] != "Q") {
d.qx = d.qy = null;
}
switch (pathCommand[0]) {
case "M":
d.X = pathCommand[1];
d.Y = pathCommand[2];
break;
case "A":
pathCommand = ["C"].concat(me.arc2curve.apply(me, [d.x, d.y].concat(pathCommand.slice(1))));
break;
case "S":
pathCommand = ["C", d.x + (d.x - (d.bx || d.x)), d.y + (d.y - (d.by || d.y))].concat(pathCommand.slice(1));
break;
case "T":
d.qx = d.x + (d.x - (d.qx || d.x));
d.qy = d.y + (d.y - (d.qy || d.y));
pathCommand = ["C"].concat(me.quadratic2curve(d.x, d.y, d.qx, d.qy, pathCommand[1], pathCommand[2]));
break;
case "Q":
d.qx = pathCommand[1];
d.qy = pathCommand[2];
pathCommand = ["C"].concat(me.quadratic2curve(d.x, d.y, pathCommand[1], pathCommand[2], pathCommand[3], pathCommand[4]));
break;
case "L":
pathCommand = ["C"].concat(d.x, d.y, pathCommand[1], pathCommand[2], pathCommand[1], pathCommand[2]);
break;
case "H":
pathCommand = ["C"].concat(d.x, d.y, pathCommand[1], d.y, pathCommand[1], d.y);
break;
case "V":
pathCommand = ["C"].concat(d.x, d.y, d.x, pathCommand[1], d.x, pathCommand[1]);
break;
case "Z":
pathCommand = ["C"].concat(d.x, d.y, d.X, d.Y, d.X, d.Y);
break;
}
return pathCommand;
},
quadratic2curve: function (x1, y1, ax, ay, x2, y2) {
var _13 = 1 / 3,
_23 = 2 / 3;
return [
_13 * x1 + _23 * ax,
_13 * y1 + _23 * ay,
_13 * x2 + _23 * ax,
_13 * y2 + _23 * ay,
x2,
y2
];
},
rotate: function (x, y, rad) {
var cos = Math.cos(rad),
sin = Math.sin(rad),
X = x * cos - y * sin,
Y = x * sin + y * cos;
return {x: X, y: Y};
},
arc2curve: function (x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) {
// for more information of where this Math came from visit:
// http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
var me = this,
PI = Math.PI,
radian = me.radian,
_120 = PI * 120 / 180,
rad = radian * (+angle || 0),
res = [],
math = Math,
mcos = math.cos,
msin = math.sin,
msqrt = math.sqrt,
mabs = math.abs,
masin = math.asin,
xy, cos, sin, x, y, h, rx2, ry2, k, cx, cy, f1, f2, df, c1, s1, c2, s2,
t, hx, hy, m1, m2, m3, m4, newres, i, ln, f2old, x2old, y2old;
if (!recursive) {
xy = me.rotate(x1, y1, -rad);
x1 = xy.x;
y1 = xy.y;
xy = me.rotate(x2, y2, -rad);
x2 = xy.x;
y2 = xy.y;
cos = mcos(radian * angle);
sin = msin(radian * angle);
x = (x1 - x2) / 2;
y = (y1 - y2) / 2;
h = (x * x) / (rx * rx) + (y * y) / (ry * ry);
if (h > 1) {
h = msqrt(h);
rx = h * rx;
ry = h * ry;
}
rx2 = rx * rx;
ry2 = ry * ry;
k = (large_arc_flag == sweep_flag ? -1 : 1) *
msqrt(mabs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x)));
cx = k * rx * y / ry + (x1 + x2) / 2;
cy = k * -ry * x / rx + (y1 + y2) / 2;
f1 = masin(((y1 - cy) / ry).toFixed(7));
f2 = masin(((y2 - cy) / ry).toFixed(7));
f1 = x1 < cx ? PI - f1 : f1;
f2 = x2 < cx ? PI - f2 : f2;
if (f1 < 0) {
f1 = PI * 2 + f1;
}
if (f2 < 0) {
f2 = PI * 2 + f2;
}
if (sweep_flag && f1 > f2) {
f1 = f1 - PI * 2;
}
if (!sweep_flag && f2 > f1) {
f2 = f2 - PI * 2;
}
}
else {
f1 = recursive[0];
f2 = recursive[1];
cx = recursive[2];
cy = recursive[3];
}
df = f2 - f1;
if (mabs(df) > _120) {
f2old = f2;
x2old = x2;
y2old = y2;
f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1);
x2 = cx + rx * mcos(f2);
y2 = cy + ry * msin(f2);
res = me.arc2curve(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]);
}
df = f2 - f1;
c1 = mcos(f1);
s1 = msin(f1);
c2 = mcos(f2);
s2 = msin(f2);
t = math.tan(df / 4);
hx = 4 / 3 * rx * t;
hy = 4 / 3 * ry * t;
m1 = [x1, y1];
m2 = [x1 + hx * s1, y1 - hy * c1];
m3 = [x2 + hx * s2, y2 - hy * c2];
m4 = [x2, y2];
m2[0] = 2 * m1[0] - m2[0];
m2[1] = 2 * m1[1] - m2[1];
if (recursive) {
return [m2, m3, m4].concat(res);
}
else {
res = [m2, m3, m4].concat(res).join().split(",");
newres = [];
ln = res.length;
for (i = 0; i < ln; i++) {
newres[i] = i % 2 ? me.rotate(res[i - 1], res[i], rad).y : me.rotate(res[i], res[i + 1], rad).x;
}
return newres;
}
},
pathDimensions: function (path) {
if (!path || !path.length) {
return {x: 0, y: 0, width: 0, height: 0};
}
path = this.path2curve(path);
var x = 0,
y = 0,
X = [],
Y = [],
i = 0,
ln = path.length,
p, xmin, ymin, dim;
for (; i < ln; i++) {
p = path[i];
if (p[0] == "M") {
x = p[1];
y = p[2];
X.push(x);
Y.push(y);
}
else {
dim = this.curveDim(x, y, p[1], p[2], p[3], p[4], p[5], p[6]);
X = X.concat(dim.min.x, dim.max.x);
Y = Y.concat(dim.min.y, dim.max.y);
x = p[5];
y = p[6];
}
}
xmin = Math.min.apply(0, X);
ymin = Math.min.apply(0, Y);
return {
x: xmin,
y: ymin,
path: path,
width: Math.max.apply(0, X) - xmin,
height: Math.max.apply(0, Y) - ymin
};
},
intersectInside: function(path, cp1, cp2) {
return (cp2[0] - cp1[0]) * (path[1] - cp1[1]) > (cp2[1] - cp1[1]) * (path[0] - cp1[0]);
},
intersectIntersection: function(s, e, cp1, cp2) {
var p = [],
dcx = cp1[0] - cp2[0],
dcy = cp1[1] - cp2[1],
dpx = s[0] - e[0],
dpy = s[1] - e[1],
n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0],
n2 = s[0] * e[1] - s[1] * e[0],
n3 = 1 / (dcx * dpy - dcy * dpx);
p[0] = (n1 * dpx - n2 * dcx) * n3;
p[1] = (n1 * dpy - n2 * dcy) * n3;
return p;
},
intersect: function(subjectPolygon, clipPolygon) {
var me = this,
i = 0,
ln = clipPolygon.length,
cp1 = clipPolygon[ln - 1],
outputList = subjectPolygon,
cp2, s, e, ln2, inputList, j;
for (; i < ln; ++i) {
cp2 = clipPolygon[i];
inputList = outputList;
outputList = [];
s = inputList[inputList.length - 1];
j = 0;
ln2 = inputList.length;
for (; j < ln2; j++) {
e = inputList[j];
if (me.intersectInside(e, cp1, cp2)) {
if (!me.intersectInside(s, cp1, cp2)) {
outputList.push(me.intersectIntersection(s, e, cp1, cp2));
}
outputList.push(e);
}
else if (me.intersectInside(s, cp1, cp2)) {
outputList.push(me.intersectIntersection(s, e, cp1, cp2));
}
s = e;
}
cp1 = cp2;
}
return outputList;
},
curveDim: function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) {
var a = (c2x - 2 * c1x + p1x) - (p2x - 2 * c2x + c1x),
b = 2 * (c1x - p1x) - 2 * (c2x - c1x),
c = p1x - c1x,
t1 = (-b + Math.sqrt(b * b - 4 * a * c)) / 2 / a,
t2 = (-b - Math.sqrt(b * b - 4 * a * c)) / 2 / a,
y = [p1y, p2y],
x = [p1x, p2x],
dot;
if (Math.abs(t1) > 1e12) {
t1 = 0.5;
}
if (Math.abs(t2) > 1e12) {
t2 = 0.5;
}
if (t1 > 0 && t1 < 1) {
dot = this.findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1);
x.push(dot.x);
y.push(dot.y);
}
if (t2 > 0 && t2 < 1) {
dot = this.findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2);
x.push(dot.x);
y.push(dot.y);
}
a = (c2y - 2 * c1y + p1y) - (p2y - 2 * c2y + c1y);
b = 2 * (c1y - p1y) - 2 * (c2y - c1y);
c = p1y - c1y;
t1 = (-b + Math.sqrt(b * b - 4 * a * c)) / 2 / a;
t2 = (-b - Math.sqrt(b * b - 4 * a * c)) / 2 / a;
if (Math.abs(t1) > 1e12) {
t1 = 0.5;
}
if (Math.abs(t2) > 1e12) {
t2 = 0.5;
}
if (t1 > 0 && t1 < 1) {
dot = this.findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1);
x.push(dot.x);
y.push(dot.y);
}
if (t2 > 0 && t2 < 1) {
dot = this.findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2);
x.push(dot.x);
y.push(dot.y);
}
return {
min: {x: Math.min.apply(0, x), y: Math.min.apply(0, y)},
max: {x: Math.max.apply(0, x), y: Math.max.apply(0, y)}
};
},
/**
* @private
*
* Calculates bezier curve control anchor points for a particular point in a path, with a
* smoothing curve applied. The smoothness of the curve is controlled by the 'value' parameter.
* Note that this algorithm assumes that the line being smoothed is normalized going from left
* to right; it makes special adjustments assuming this orientation.
*
* @param {Number} prevX X coordinate of the previous point in the path
* @param {Number} prevY Y coordinate of the previous point in the path
* @param {Number} curX X coordinate of the current point in the path
* @param {Number} curY Y coordinate of the current point in the path
* @param {Number} nextX X coordinate of the next point in the path
* @param {Number} nextY Y coordinate of the next point in the path
* @param {Number} value A value to control the smoothness of the curve; this is used to
* divide the distance between points, so a value of 2 corresponds to
* half the distance between points (a very smooth line) while higher values
* result in less smooth curves. Defaults to 4.
* @return {Object} Object containing x1, y1, x2, y2 bezier control anchor points; x1 and y1
* are the control point for the curve toward the previous path point, and
* x2 and y2 are the control point for the curve toward the next path point.
*/
getAnchors: function (prevX, prevY, curX, curY, nextX, nextY, value) {
value = value || 4;
var math = Math,
PI = math.PI,
halfPI = PI / 2,
abs = math.abs,
sin = math.sin,
cos = math.cos,
atan = math.atan,
control1Length, control2Length, control1Angle, control2Angle,
control1X, control1Y, control2X, control2Y, alpha;
// Find the length of each control anchor line, by dividing the horizontal distance
// between points by the value parameter.
control1Length = (curX - prevX) / value;
control2Length = (nextX - curX) / value;
// Determine the angle of each control anchor line. If the middle point is a vertical
// turnaround then we force it to a flat horizontal angle to prevent the curve from
// dipping above or below the middle point. Otherwise we use an angle that points
// toward the previous/next target point.
if ((curY >= prevY && curY >= nextY) || (curY <= prevY && curY <= nextY)) {
control1Angle = control2Angle = halfPI;
} else {
control1Angle = atan((curX - prevX) / abs(curY - prevY));
if (prevY < curY) {
control1Angle = PI - control1Angle;
}
control2Angle = atan((nextX - curX) / abs(curY - nextY));
if (nextY < curY) {
control2Angle = PI - control2Angle;
}
}
// Adjust the calculated angles so they point away from each other on the same line
alpha = halfPI - ((control1Angle + control2Angle) % (PI * 2)) / 2;
if (alpha > halfPI) {
alpha -= PI;
}
control1Angle += alpha;
control2Angle += alpha;
// Find the control anchor points from the angles and length
control1X = curX - control1Length * sin(control1Angle);
control1Y = curY + control1Length * cos(control1Angle);
control2X = curX + control2Length * sin(control2Angle);
control2Y = curY + control2Length * cos(control2Angle);
// One last adjustment, make sure that no control anchor point extends vertically past
// its target prev/next point, as that results in curves dipping above or below and
// bending back strangely. If we find this happening we keep the control angle but
// reduce the length of the control line so it stays within bounds.
if ((curY > prevY && control1Y < prevY) || (curY < prevY && control1Y > prevY)) {
control1X += abs(prevY - control1Y) * (control1X - curX) / (control1Y - curY);
control1Y = prevY;
}
if ((curY > nextY && control2Y < nextY) || (curY < nextY && control2Y > nextY)) {
control2X -= abs(nextY - control2Y) * (control2X - curX) / (control2Y - curY);
control2Y = nextY;
}
return {
x1: control1X,
y1: control1Y,
x2: control2X,
y2: control2Y
};
},
/* Smoothing function for a path. Converts a path into cubic beziers. Value defines the divider of the distance between points.
* Defaults to a value of 4.
*/
smooth: function (originalPath, value) {
var path = this.path2curve(originalPath),
newp = [path[0]],
x = path[0][1],
y = path[0][2],
j,
points,
i = 1,
ii = path.length,
beg = 1,
mx = x,
my = y,
cx = 0,
cy = 0;
for (; i < ii; i++) {
var pathi = path[i],
pathil = pathi.length,
pathim = path[i - 1],
pathiml = pathim.length,
pathip = path[i + 1],
pathipl = pathip && pathip.length;
if (pathi[0] == "M") {
mx = pathi[1];
my = pathi[2];
j = i + 1;
while (path[j][0] != "C") {
j++;
}
cx = path[j][5];
cy = path[j][6];
newp.push(["M", mx, my]);
beg = newp.length;
x = mx;
y = my;
continue;
}
if (pathi[pathil - 2] == mx && pathi[pathil - 1] == my && (!pathip || pathip[0] == "M")) {
var begl = newp[beg].length;
points = this.getAnchors(pathim[pathiml - 2], pathim[pathiml - 1], mx, my, newp[beg][begl - 2], newp[beg][begl - 1], value);
newp[beg][1] = points.x2;
newp[beg][2] = points.y2;
}
else if (!pathip || pathip[0] == "M") {
points = {
x1: pathi[pathil - 2],
y1: pathi[pathil - 1]
};
} else {
points = this.getAnchors(pathim[pathiml - 2], pathim[pathiml - 1], pathi[pathil - 2], pathi[pathil - 1], pathip[pathipl - 2], pathip[pathipl - 1], value);
}
newp.push(["C", x, y, points.x1, points.y1, pathi[pathil - 2], pathi[pathil - 1]]);
x = points.x2;
y = points.y2;
}
return newp;
},
findDotAtSegment: function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
var t1 = 1 - t;
return {
x: Math.pow(t1, 3) * p1x + Math.pow(t1, 2) * 3 * t * c1x + t1 * 3 * t * t * c2x + Math.pow(t, 3) * p2x,
y: Math.pow(t1, 3) * p1y + Math.pow(t1, 2) * 3 * t * c1y + t1 * 3 * t * t * c2y + Math.pow(t, 3) * p2y
};
},
/**
* snapEnds is a utility function that gives you axis ticks information based on start, end
* and preferred number of steps. It happens quite often that you have just a dataset and need to
* build an axis. If you simply take min and max and divide delta to number of steps you could get
* very ugly numbers. Lets say you have min = 0.532 and max = 0.823 and you want to draw axis
* across 20 steps. Simple calculation like (max - min) / steps will give us: 0.014549(9), so
* your axis will look like this:
*
* 0.532, 0.5465499, 0.5610998, 0.5756497, etc
*
* Not pretty at all. snapEnds will give different set of numbers for the same values:
*
* 0.5, 0.52, 0.54, 0.56, 0.58, 0.6, 0.62, ... 0.8, 0.82, 0.84
*
* It starts a bit earlier and ends a bit later and trying to find a step which will look nice.
*
* @param {Number} from The minimum value in the data
* @param {Number} to The maximum value in the data
* @param {Number} stepsMax The maximum number of ticks
* @param {Number} endsLocked If true, the 'from' and 'to' parameters will be used as fixed end values
* and will not be adjusted
* @return {Object} The calculated step and ends info; properties are:
* - from: The result start value, which may be lower than the original start value
* - to: The result end value, which may be higher than the original end value
* - power: The power of 10 used in the step calculation
* - step: The value size of each step
* - steps: The number of steps. NOTE: the steps may not divide the from/to range perfectly evenly;
* there may be a smaller distance between the last step and the end value than between prior
* steps, particularly when the `endsLocked` param is true. Therefore it is best to not use
* the `steps` result when finding the axis tick points, instead use the `step`, `to`, and
* `from` to find the correct point for each tick.
*/
snapEnds: function (from, to, stepsMax, endsLocked) {
var math = Math,
pow = math.pow,
floor = math.floor,
// start with a precise step size
step = (to - from) / stepsMax,
// power is a power of 10 of the step. For axis 1, 2, 3 or 10, 20, 30 or
// 0.1, 0.2, 0.3 power will be 0, 1 and -1 respectively.
power = floor(math.log(step) / math.LN10) + 1,
tenToPower = pow(10, power),
// modulo will translate rounded value of the step to the 0 - 100 range. We will need it later.
modulo = math.round((step % tenToPower) * pow(10, 2 - power)),
// interval is an array of value/weight pairs
interval = Ext.draw.Draw.snapEndsIntervalWeights,
ln = interval.length,
stepCount = 0,
topWeight = 1e9,
cur, value, weight, i, topValue;
// round the start value by the power, so e.g. 0.532 will become 0.5.
if (!endsLocked) {
from = floor(from / tenToPower) * tenToPower;
}
cur = from;
// find what is our step going to be to be closer to "pretty" numbers. This is done taking into
// account the interval weights. This way we figure out topValue.
for (i = 0; i < ln; i++) {
value = interval[i][0];
weight = (value - modulo) < 0 ? 1e6 : (value - modulo) / interval[i][1];
if (weight < topWeight) {
topValue = value;
topWeight = weight;
}
}
// with the new topValue, calculate the final step size
step = floor(step * pow(10, -power)) * pow(10, power) + topValue * pow(10, power - 2);
while (cur < to) {
cur += step;
stepCount++;
}
// Cut everything that is after tenth digit after floating point. This is to get rid of
// rounding errors, i.e. 12.00000000000121212.
if (!endsLocked) {
to = +cur.toFixed(10);
}
return {
from: from,
to: to,
power: power,
step: step,
steps: stepCount
};
},
sorter: function (a, b) {
return a.offset - b.offset;
},
rad: function(degrees) {
return degrees % 360 * Math.PI / 180;
},
degrees: function(radian) {
return radian * 180 / Math.PI % 360;
},
withinBox: function(x, y, bbox) {
bbox = bbox || {};
return (x >= bbox.x && x <= (bbox.x + bbox.width) && y >= bbox.y && y <= (bbox.y + bbox.height));
},
parseGradient: function(gradient) {
var me = this,
type = gradient.type || 'linear',
angle = gradient.angle || 0,
radian = me.radian,
stops = gradient.stops,
stopsArr = [],
stop,
vector,
max,
stopObj;
if (type == 'linear') {
vector = [0, 0, Math.cos(angle * radian), Math.sin(angle * radian)];
max = 1 / (Math.max(Math.abs(vector[2]), Math.abs(vector[3])) || 1);
vector[2] *= max;
vector[3] *= max;
if (vector[2] < 0) {
vector[0] = -vector[2];
vector[2] = 0;
}
if (vector[3] < 0) {
vector[1] = -vector[3];
vector[3] = 0;
}
}
for (stop in stops) {
if (stops.hasOwnProperty(stop) && me.stopsRE.test(stop)) {
stopObj = {
offset: parseInt(stop, 10),
color: Ext.draw.Color.toHex(stops[stop].color) || '#ffffff',
opacity: stops[stop].opacity || 1
};
stopsArr.push(stopObj);
}
}
// Sort by pct property
stopsArr.sort(me.sorter);
if (type == 'linear') {
return {
id: gradient.id,
type: type,
vector: vector,
stops: stopsArr
};
}
else {
return {
id: gradient.id,
type: type,
centerX: gradient.centerX,
centerY: gradient.centerY,
focalX: gradient.focalX,
focalY: gradient.focalY,
radius: gradient.radius,
vector: vector,
stops: stopsArr
};
}
}
};
/**
* @class Ext.draw.CompositeSprite
* @extends Ext.util.MixedCollection
*
* A composite Sprite handles a group of sprites with common methods to a sprite
* such as `hide`, `show`, `setAttributes`. These methods are applied to the set of sprites
* added to the group.
*
* CompositeSprite extends {@link Ext.util.MixedCollection} so you can use the same methods
* in `MixedCollection` to iterate through sprites, add and remove elements, etc.
*
* In order to create a CompositeSprite, one has to provide a handle to the surface where it is
* rendered:
*
* var group = Ext.create('Ext.draw.CompositeSprite', {
* surface: drawComponent.surface
* });
*
* Then just by using `MixedCollection` methods it's possible to add {@link Ext.draw.Sprite}s:
*
* group.add(sprite1);
* group.add(sprite2);
* group.add(sprite3);
*
* And then apply common Sprite methods to them:
*
* group.setAttributes({
* fill: '#f00'
* }, true);
*/
Ext.draw.CompositeSprite = Ext.extend(Ext.util.MixedCollection, {
/* End Definitions */
isCompositeSprite: true,
constructor: function(config) {
var me = this;
config = config || {};
Ext.apply(me, config);
me.addEvents(
'mousedown',
'mouseup',
'mouseover',
'mouseout',
'click'
);
me.id = Ext.id(null, 'ext-sprite-group-');
Ext.draw.CompositeSprite.superclass.constructor.apply(this, arguments);
},
// @private
onClick: function(e) {
this.fireEvent('click', e);
},
// @private
onMouseUp: function(e) {
this.fireEvent('mouseup', e);
},
// @private
onMouseDown: function(e) {
this.fireEvent('mousedown', e);
},
// @private
onMouseOver: function(e) {
this.fireEvent('mouseover', e);
},
// @private
onMouseOut: function(e) {
this.fireEvent('mouseout', e);
},
attachEvents: function(o) {
var me = this;
o.on({
scope: me,
mousedown: me.onMouseDown,
mouseup: me.onMouseUp,
mouseover: me.onMouseOver,
mouseout: me.onMouseOut,
click: me.onClick
});
},
/** Add a Sprite to the Group */
add: function(key, o) {
var result = Ext.draw.CompositeSprite.superclass.add.apply(this, arguments);
this.attachEvents(result);
return result;
},
insert: function(index, key, o) {
return Ext.draw.CompositeSprite.superclass.insert.apply(this, arguments);
},
/** Remove a Sprite from the Group */
remove: function(o) {
var me = this;
o.un({
scope: me,
mousedown: me.onMouseDown,
mouseup: me.onMouseUp,
mouseover: me.onMouseOver,
mouseout: me.onMouseOut,
click: me.onClick
});
Ext.draw.CompositeSprite.superclass.remove.apply(this, arguments);
},
/**
* Returns the group bounding box.
* Behaves like {@link Ext.draw.Sprite} getBBox method.
*/
getBBox: function() {
var i = 0,
sprite,
bb,
items = this.items,
len = this.length,
infinity = Infinity,
minX = infinity,
maxHeight = -infinity,
minY = infinity,
maxWidth = -infinity;
for (; i < len; i++) {
sprite = items[i];
bb = sprite.getBBox();
minX = Math.min(minX, bb.x);
minY = Math.min(minY, bb.y);
maxHeight = Math.max(maxHeight, bb.height + bb.y);
maxWidth = Math.max(maxWidth, bb.width + bb.x);
}
return {
x: minX,
y: minY,
height: maxHeight - minY,
width: maxWidth - minX
};
},
/**
* Iterates through all sprites calling
* `setAttributes` on each one. For more information
* {@link Ext.draw.Sprite} provides a description of the
* attributes that can be set with this method.
*/
setAttributes: function(attrs, redraw) {
var i = 0,
items = this.items,
len = this.length;
for (; i < len; i++) {
items[i].setAttributes(attrs, redraw);
}
return this;
},
/**
* Hides all sprites. If the first parameter of the method is true
* then a redraw will be forced for each sprite.
*/
hide: function(redraw) {
var i = 0,
items = this.items,
len = this.length;
for (; i < len; i++) {
items[i].hide(redraw);
}
return this;
},
/**
* Shows all sprites. If the first parameter of the method is true
* then a redraw will be forced for each sprite.
*/
show: function(redraw) {
var i = 0,
items = this.items,
len = this.length;
for (; i < len; i++) {
items[i].show(redraw);
}
return this;
},
redraw: function() {
var me = this,
i = 0,
items = me.items,
surface = me.getSurface(),
len = me.length;
if (surface) {
for (; i < len; i++) {
surface.renderItem(items[i]);
}
}
return me;
},
setStyle: function(obj) {
var i = 0,
items = this.items,
len = this.length,
item, el;
for (; i < len; i++) {
item = items[i];
el = item.el;
if (el) {
el.setStyle(obj);
}
}
},
addCls: function(obj) {
var i = 0,
items = this.items,
surface = this.getSurface(),
len = this.length;
if (surface) {
for (; i < len; i++) {
surface.addCls(items[i], obj);
}
}
},
removeCls: function(obj) {
var i = 0,
items = this.items,
surface = this.getSurface(),
len = this.length;
if (surface) {
for (; i < len; i++) {
surface.removeCls(items[i], obj);
}
}
},
/**
* Grab the surface from the items
* @private
* @return {Ext.draw.Surface} The surface, null if not found
*/
getSurface: function(){
var first = this.first();
if (first) {
return first.surface;
}
return null;
},
/**
* Destroys the SpriteGroup
*/
destroy: function(){
var me = this,
surface = me.getSurface(),
item;
if (surface) {
while (me.getCount() > 0) {
item = me.first();
me.remove(item);
surface.remove(item);
}
}
me.clearListeners();
}
});
Ext.applyIf(Ext.draw.CompositeSprite.prototype, Ext.util.Animate.prototype);
/**
* @class Ext.draw.Sprite
* @extends Object
*
* A Sprite is an object rendered in a Drawing surface. There are different options and types of sprites.
* The configuration of a Sprite is an object with the following properties:
*
* - **type** - (String) The type of the sprite. Possible options are 'circle', 'path', 'rect', 'text', 'square', 'image'.
* - **width** - (Number) Used in rectangle sprites, the width of the rectangle.
* - **height** - (Number) Used in rectangle sprites, the height of the rectangle.
* - **size** - (Number) Used in square sprites, the dimension of the square.
* - **radius** - (Number) Used in circle sprites, the radius of the circle.
* - **x** - (Number) The position along the x-axis.
* - **y** - (Number) The position along the y-axis.
* - **path** - (Array) Used in path sprites, the path of the sprite written in SVG-like path syntax.
* - **opacity** - (Number) The opacity of the sprite.
* - **fill** - (String) The fill color.
* - **stroke** - (String) The stroke color.
* - **stroke-width** - (Number) The width of the stroke.
* - **font** - (String) Used with text type sprites. The full font description. Uses the same syntax as the CSS `font` parameter.
* - **text** - (String) Used with text type sprites. The text itself.
*
* Additionally there are three transform objects that can be set with `setAttributes` which are `translate`, `rotate` and
* `scale`.
*
* For translate, the configuration object contains x and y attributes that indicate where to
* translate the object. For example:
*
* sprite.setAttributes({
* translate: {
* x: 10,
* y: 10
* }
* }, true);
*
* For rotation, the configuration object contains x and y attributes for the center of the rotation (which are optional),
* and a `degrees` attribute that specifies the rotation in degrees. For example:
*
* sprite.setAttributes({
* rotate: {
* degrees: 90
* }
* }, true);
*
* For scaling, the configuration object contains x and y attributes for the x-axis and y-axis scaling. For example:
*
* sprite.setAttributes({
* scale: {
* x: 10,
* y: 3
* }
* }, true);
*
* Sprites can be created with a reference to a {@link Ext.draw.Surface}
*
* var drawComponent = Ext.create('Ext.draw.Component', options here...);
*
* var sprite = Ext.create('Ext.draw.Sprite', {
* type: 'circle',
* fill: '#ff0',
* surface: drawComponent.surface,
* radius: 5
* });
*
* Sprites can also be added to the surface as a configuration object:
*
* var sprite = drawComponent.surface.add({
* type: 'circle',
* fill: '#ff0',
* radius: 5
* });
*
* In order to properly apply properties and render the sprite we have to
* `show` the sprite setting the option `redraw` to `true`:
*
* sprite.show(true);
*
* The constructor configuration object of the Sprite can also be used and passed into the {@link Ext.draw.Surface}
* add method to append a new sprite to the canvas. For example:
*
* drawComponent.surface.add({
* type: 'circle',
* fill: '#ffc',
* radius: 100,
* x: 100,
* y: 100
* });
*/
Ext.draw.Sprite = Ext.extend(Ext.util.Observable, {
dirty: false,
dirtyHidden: false,
dirtyTransform: false,
dirtyPath: true,
dirtyFont: true,
zIndexDirty: true,
isSprite: true,
zIndex: 0,
fontProperties: [
'font',
'font-size',
'font-weight',
'font-style',
'font-family',
'text-anchor',
'text'
],
pathProperties: [
'x',
'y',
'd',
'path',
'height',
'width',
'radius',
'r',
'rx',
'ry',
'cx',
'cy'
],
minDefaults: {
circle: {
cx: 0,
cy: 0,
r: 0,
fill: "none"
},
ellipse: {
cx: 0,
cy: 0,
rx: 0,
ry: 0,
fill: "none"
},
rect: {
x: 0,
y: 0,
width: 0,
height: 0,
rx: 0,
ry: 0,
fill: "none"
},
text: {
x: 0,
y: 0,
"text-anchor": "start",
fill: "#000"
},
path: {
d: "M0,0",
fill: "none"
},
image: {
x: 0,
y: 0,
width: 0,
height: 0,
preserveAspectRatio: "none"
}
},
constructor: function(config) {
var me = this;
config = config || {};
me.id = Ext.id(null, 'ext-sprite-');
me.transformations = [];
me.surface = config.surface;
me.group = config.group;
me.type = config.type;
//attribute bucket
me.bbox = {};
me.attr = {
zIndex: 0,
translation: {
x: null,
y: null
},
rotation: {
degrees: null,
x: null,
y: null
},
scaling: {
x: null,
y: null,
cx: null,
cy: null
}
};
//delete not bucket attributes
delete config.surface;
delete config.group;
delete config.type;
Ext.applyIf(config, me.minDefaults[me.type]);
me.setAttributes(config);
me.addEvents(
'beforedestroy',
'destroy',
'render',
'mousedown',
'mouseup',
'mouseover',
'mouseout',
'mousemove',
'click',
'rightclick',
'mouseenter',
'mouseleave',
'touchstart',
'touchmove',
'touchend'
);
Ext.draw.Sprite.superclass.constructor.apply(this, arguments);
},
/**
* Change the attributes of the sprite.
* @param {Object} attrs attributes to be changed on the sprite.
* @param {Boolean} redraw Flag to immediatly draw the change.
* @return {Ext.draw.Sprite} this
*/
setAttributes: function(attrs, redraw) {
var me = this,
fontProps = me.fontProperties,
fontPropsLength = fontProps.length,
pathProps = me.pathProperties,
pathPropsLength = pathProps.length,
hasSurface = !!me.surface,
custom = hasSurface && me.surface.customAttributes || {},
spriteAttrs = me.attr,
attr, i, translate, translation, rotate, rotation, scale, scaling;
attrs = Ext.apply({}, attrs);
for (attr in custom) {
if (attrs.hasOwnProperty(attr) && typeof custom[attr] == "function") {
Ext.apply(attrs, custom[attr].apply(me, [].concat(attrs[attr])));
}
}
// Flag a change in hidden
if (!!attrs.hidden !== !!spriteAttrs.hidden) {
me.dirtyHidden = true;
}
// Flag path change
for (i = 0; i < pathPropsLength; i++) {
attr = pathProps[i];
if (attr in attrs && attrs[attr] !== spriteAttrs[attr]) {
me.dirtyPath = true;
break;
}
}
// Flag zIndex change
if ('zIndex' in attrs) {
me.zIndexDirty = true;
}
// Flag font/text change
for (i = 0; i < fontPropsLength; i++) {
attr = fontProps[i];
if (attr in attrs && attrs[attr] !== spriteAttrs[attr]) {
me.dirtyFont = true;
break;
}
}
translate = attrs.translate;
translation = spriteAttrs.translation;
if (translate) {
if ((translate.x && translate.x !== translation.x) ||
(translate.y && translate.y !== translation.y)) {
Ext.apply(translation, translate);
me.dirtyTransform = true;
}
delete attrs.translate;
}
rotate = attrs.rotate;
rotation = spriteAttrs.rotation;
if (rotate) {
if ((!rotate.x || rotate.x !== rotation.x) ||
(!rotate.y || rotate.y !== rotation.y) ||
(rotate.degrees && rotate.degrees !== rotation.degrees)) {
Ext.apply(rotation, rotate);
me.dirtyTransform = true;
}
delete attrs.rotate;
}
scale = attrs.scale;
scaling = spriteAttrs.scaling;
if (scale) {
if ((scale.x && scale.x !== scaling.x) ||
(scale.y && scale.y !== scaling.y) ||
(scale.cx && scale.cx !== scaling.cx) ||
(scale.cy && scale.cy !== scaling.cy)) {
Ext.apply(scaling, scale);
me.dirtyTransform = true;
}
delete attrs.scale;
}
Ext.apply(spriteAttrs, attrs);
me.dirty = true;
if (redraw === true && hasSurface) {
me.redraw();
}
return this;
},
/**
* Retrieve the bounding box of the sprite. This will be returned as an object with x, y, width, and height properties.
* @return {Object} bbox
*/
getBBox: function(isWithoutTransform) {
return this.surface.getBBox(this, isWithoutTransform);
},
setText: function(text) {
return this.surface.setText(this, text);
},
/**
* Hide the sprite.
* @param {Boolean} redraw Flag to immediatly draw the change.
* @return {Ext.draw.Sprite} this
*/
hide: function(redraw) {
this.setAttributes({
hidden: true
}, redraw);
return this;
},
/**
* Show the sprite.
* @param {Boolean} redraw Flag to immediatly draw the change.
* @return {Ext.draw.Sprite} this
*/
show: function(redraw) {
this.setAttributes({
hidden: false
}, redraw);
return this;
},
/**
* Remove the sprite.
*/
remove: function() {
if (this.surface) {
this.surface.remove(this);
return true;
}
return false;
},
onRemove: function() {
this.surface.onRemove(this);
},
/**
* Removes the sprite and clears all listeners.
*/
destroy: function() {
var me = this;
if (me.fireEvent('beforedestroy', me) !== false) {
me.remove();
me.surface.onDestroy(me);
me.clearListeners();
me.fireEvent('destroy');
}
},
/**
* Redraw the sprite.
* @return {Ext.draw.Sprite} this
*/
redraw: function() {
this.surface.renderItem(this);
return this;
},
/**
* Draw a sprite Tween (animation interpolation).
* @return {Ext.draw.Sprite} this
*/
tween: function() {
this.surface.tween(this);
return this;
},
/**
* Wrapper for setting style properties, also takes single object parameter of multiple styles.
* @param {String/Object} property The style property to be set, or an object of multiple styles.
* @param {String} value (optional) The value to apply to the given property, or null if an object was passed.
* @return {Ext.draw.Sprite} this
*/
setStyle: function() {
this.el.setStyle.apply(this.el, arguments);
return this;
},
/**
* Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out. Note this method
* is severly limited in VML.
* @param {String/Array} className The CSS class to add, or an array of classes
* @return {Ext.draw.Sprite} this
*/
addCls: function(obj) {
this.surface.addCls(this, obj);
return this;
},
/**
* Removes one or more CSS classes from the element.
* @param {String/Array} className The CSS class to remove, or an array of classes. Note this method
* is severly limited in VML.
* @return {Ext.draw.Sprite} this
*/
removeCls: function(obj) {
this.surface.removeCls(this, obj);
return this;
}
});
Ext.applyIf(Ext.draw.Sprite.prototype, Ext.util.Animate);
/**
* @class Ext.draw.Matrix
* @private
*/
Ext.draw.Matrix = Ext.extend(Object, {
constructor: function(a, b, c, d, e, f) {
if (a != null) {
this.matrix = [[a, c, e], [b, d, f], [0, 0, 1]];
}
else {
this.matrix = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];
}
},
add: function(a, b, c, d, e, f) {
var me = this,
out = [[], [], []],
matrix = [[a, c, e], [b, d, f], [0, 0, 1]],
x, y, z, res;
for (x = 0; x < 3; x++) {
for (y = 0; y < 3; y++) {
res = 0;
for (z = 0; z < 3; z++) {
res += me.matrix[x][z] * matrix[z][y];
}
out[x][y] = res;
}
}
me.matrix = out;
return me;
},
prepend: function(a, b, c, d, e, f) {
var me = this,
out = [[], [], []],
matrix = [[a, c, e], [b, d, f], [0, 0, 1]],
x, y, z, res;
for (x = 0; x < 3; x++) {
for (y = 0; y < 3; y++) {
res = 0;
for (z = 0; z < 3; z++) {
res += matrix[x][z] * me.matrix[z][y];
}
out[x][y] = res;
}
}
me.matrix = out;
return me;
},
invert: function() {
var matrix = this.matrix,
a = matrix[0][0],
b = matrix[1][0],
c = matrix[0][1],
d = matrix[1][1],
e = matrix[0][2],
f = matrix[1][2],
x = a * d - b * c;
return new Ext.draw.Matrix(d / x, -b / x, -c / x, a / x, (c * f - d * e) / x, (b * e - a * f) / x);
},
clone: function() {
var matrix = this.matrix;
return new Ext.draw.Matrix(matrix[0][0], matrix[1][0], matrix[0][1], matrix[1][1], matrix[0][2], matrix[1][2]);
},
translate: function(x, y) {
this.prepend(1, 0, 0, 1, x, y);
return this;
},
scale: function(x, y, cx, cy) {
var me = this;
if (y == null) {
y = x;
}
me.add(1, 0, 0, 1, cx, cy);
me.add(x, 0, 0, y, 0, 0);
me.add(1, 0, 0, 1, -cx, -cy);
return me;
},
rotate: function(a, x, y) {
a = Ext.draw.Draw.rad(a);
var me = this,
cos = +Math.cos(a).toFixed(9),
sin = +Math.sin(a).toFixed(9);
me.add(cos, sin, -sin, cos, x, y);
me.add(1, 0, 0, 1, -x, -y);
return me;
},
x: function(x, y) {
var matrix = this.matrix;
return x * matrix[0][0] + y * matrix[0][1] + matrix[0][2];
},
y: function(x, y) {
var matrix = this.matrix;
return x * matrix[1][0] + y * matrix[1][1] + matrix[1][2];
},
get: function(i, j) {
return + this.matrix[i][j].toFixed(4);
},
/**
* Determines whether this matrix is an identity matrix (no transform)
* @return {Boolean}
*/
isIdentity: function() {
return this.equals(new Ext.draw.Matrix());
},
/**
* Determines if this matrix has the same values as another matrix
* @param {Ext.draw.Matrix} matrix
* @return {Boolean}
*/
equals: function(matrix) {
var thisMatrix = this.matrix,
otherMatrix = matrix.matrix;
return thisMatrix[0][0] === otherMatrix[0][0] &&
thisMatrix[0][1] === otherMatrix[0][1] &&
thisMatrix[0][2] === otherMatrix[0][2] &&
thisMatrix[1][0] === otherMatrix[1][0] &&
thisMatrix[1][1] === otherMatrix[1][1] &&
thisMatrix[1][2] === otherMatrix[1][2];
},
toString: function() {
var me = this;
return [me.get(0, 0), me.get(0, 1), me.get(1, 0), me.get(1, 1), 0, 0].join();
},
toCanvas: function(ctx) {
var matrix = this.matrix;
ctx.transform(matrix[0][0], matrix[1][0], matrix[0][1], matrix[1][1], matrix[0][2], matrix[1][2]);
},
toSvg: function() {
var matrix = this.matrix;
return "matrix(" + [matrix[0][0], matrix[1][0], matrix[0][1], matrix[1][1], matrix[0][2], matrix[1][2]].join() + ")";
},
toFilter: function() {
var me = this;
return "progid:DXImageTransform.Microsoft.Matrix(M11=" + me.get(0, 0) +
", M12=" + me.get(0, 1) + ", M21=" + me.get(1, 0) + ", M22=" + me.get(1, 1) +
", Dx=" + me.get(0, 2) + ", Dy=" + me.get(1, 2) + ")";
},
offset: function() {
var matrix = this.matrix;
return [matrix[0][2].toFixed(4), matrix[1][2].toFixed(4)];
},
// Split matrix into Translate Scale, Shear, and Rotate
split: function () {
function norm(a) {
return a[0] * a[0] + a[1] * a[1];
}
function normalize(a) {
var mag = Math.sqrt(norm(a));
a[0] /= mag;
a[1] /= mag;
}
var matrix = this.matrix,
out = {
translateX: matrix[0][2],
translateY: matrix[1][2]
},
row;
// scale and shear
row = [[matrix[0][0], matrix[0][1]], [matrix[1][1], matrix[1][1]]];
out.scaleX = Math.sqrt(norm(row[0]));
normalize(row[0]);
out.shear = row[0][0] * row[1][0] + row[0][1] * row[1][1];
row[1] = [row[1][0] - row[0][0] * out.shear, row[1][1] - row[0][1] * out.shear];
out.scaleY = Math.sqrt(norm(row[1]));
normalize(row[1]);
out.shear /= out.scaleY;
// rotation
out.rotate = Math.asin(-row[0][1]);
out.isSimple = !+out.shear.toFixed(9) && (out.scaleX.toFixed(9) == out.scaleY.toFixed(9) || !out.rotate);
return out;
}
});
/**
* @class Ext.draw.Surface
* @extends Object
*
* A Surface is an interface to render methods inside a draw {@link Ext.draw.Component}.
* A Surface contains methods to render sprites, get bounding boxes of sprites, add
* sprites to the canvas, initialize other graphic components, etc. One of the most used
* methods for this class is the `add` method, to add Sprites to the surface.
*
* Most of the Surface methods are abstract and they have a concrete implementation
* in VML or SVG engines.
*
* A Surface instance can be accessed as a property of a draw component. For example:
*
* drawComponent.surface.add({
* type: 'circle',
* fill: '#ffc',
* radius: 100,
* x: 100,
* y: 100
* });
*
* The configuration object passed in the `add` method is the same as described in the {@link Ext.draw.Sprite}
* class documentation.
*
* ### Listeners
*
* You can also add event listeners to the surface using the `Observable` listener syntax. Supported events are:
*
* - 'mouseup'
* - 'mousedown'
* - 'mouseover'
* - 'mouseout'
* - 'mousemove'
* - 'mouseenter'
* - 'mouseleave'
* - 'click'
* - 'dblclick'
* - 'tap'
* - 'tapstart'
* - 'tapend'
* - 'tapcancel'
* - 'taphold'
* - 'doubletap'
* - 'singletap'
* - 'touchstart'
* - 'touchmove'
* - 'touchend'
* - 'drag'
* - 'dragstart'
* - 'dragend'
* - 'pinch'
* - 'pinchstart'
* - 'pinchend'
* - 'swipe'
*
* For example:
*
* drawComponent.surface.on({
* 'mousemove': function() {
* console.log('moving the mouse over the surface');
* }
* });
*
* ## Example
*
* drawComponent.surface.add([
* {
* type: 'circle',
* radius: 10,
* fill: '#f00',
* x: 10,
* y: 10,
* group: 'circles'
* },
* {
* type: 'circle',
* radius: 10,
* fill: '#0f0',
* x: 50,
* y: 50,
* group: 'circles'
* },
* {
* type: 'circle',
* radius: 10,
* fill: '#00f',
* x: 100,
* y: 100,
* group: 'circles'
* },
* {
* type: 'rect',
* radius: 10,
* x: 10,
* y: 10,
* group: 'rectangles'
* },
* {
* type: 'rect',
* radius: 10,
* x: 50,
* y: 50,
* group: 'rectangles'
* },
* {
* type: 'rect',
* radius: 10,
* x: 100,
* y: 100,
* group: 'rectangles'
* }
* ]);
*
* // Get references to my groups
* my circles = surface.getGroup('circles');
* my rectangles = surface.getGroup('rectangles');
*
* // Animate the circles down
* circles.animate({
* duration: 1000,
* translate: {
* y: 200
* }
* });
*
* // Animate the rectangles across
* rectangles.animate({
* duration: 1000,
* translate: {
* x: 200
* }
* });
*/
// COMPAT set Ext.baseCSSPrefix
Ext.baseCSSPrefix = 'x-';
(function() {
function createProcessEventMethod(name) {
return function(e) {
this.processEvent(name, e);
}
}
Ext.draw.Surface = Ext.extend(Ext.util.Observable, {
// @private
zoomX: 1,
zoomY: 1,
panX: 0,
panY: 0,
// @private
availableAttrs: {
blur: 0,
"clip-rect": "0 0 1e9 1e9",
cursor: "default",
cx: 0,
cy: 0,
'dominant-baseline': 'auto',
fill: "none",
"fill-opacity": 1,
font: '10px "Arial"',
"font-family": '"Arial"',
"font-size": "10",
"font-style": "normal",
"font-weight": 400,
gradient: "",
height: 0,
hidden: false,
href: "http://sencha.com/",
opacity: 1,
path: "M0,0",
radius: 0,
rx: 0,
ry: 0,
scale: "1 1",
src: "",
stroke: "#000",
"stroke-dasharray": "",
"stroke-linecap": "butt",
"stroke-linejoin": "butt",
"stroke-miterlimit": 0,
"stroke-opacity": 1,
"stroke-width": 1,
target: "_blank",
text: "",
"text-anchor": "middle",
title: "Ext Draw",
width: 0,
x: 0,
y: 0,
zIndex: 0
},
/**
* @cfg {Number} height
* The height of this component in pixels (defaults to auto).
* <b>Note</b> to express this dimension as a percentage or offset see {@link Ext.Component#anchor}.
*/
/**
* @cfg {Number} width
* The width of this component in pixels (defaults to auto).
* <b>Note</b> to express this dimension as a percentage or offset see {@link Ext.Component#anchor}.
*/
container: undefined,
height: 352,
width: 512,
x: 0,
y: 0,
constructor: function(config) {
var me = this;
config = config || {};
Ext.apply(me, config);
me.domRef = Ext.getDoc().dom;
me.customAttributes = {};
me.addEvents.apply(me, Ext.draw.Surface.eventNames);
Ext.draw.Surface.superclass.constructor.apply(me, arguments);
me.getId();
me.initGradients();
me.initItems();
if (me.renderTo) {
me.render(me.renderTo);
delete me.renderTo;
}
me.initBackground(config.background);
},
/**
* @private initializes surface events. Should be called after render.
*/
initializeEvents: function() {
//NOTE: drag events have been moved to a deferred function.
var me = this;
me.mon(me.el, {
scope: me,
mouseover: me.onMouseOver,
mouseout: me.onMouseOut,
mouseenter: me.onMouseEnter,
mouseleave: me.onMouseLeave,
mousemove: me.onMouseMove,
mouseup: me.onMouseUp,
mousedown: me.onMouseDown,
click: me.onClick,
doubleclick: me.onDoubleClick,
tap: me.onTap,
tapstart: me.onTapStart,
tapend: me.onTapEnd,
tapcancel: me.onTapCancel,
taphold: me.onTapHold,
doubletap: me.onDoubleTap,
singletap: me.onSingleTap,
touchstart: me.onTouchStart,
touchmove: me.onTouchMove,
touchend: me.onTouchEnd,
pinchstart: me.onPinchStart,
pinch: me.onPinch,
pinchend: me.onPinchEnd,
swipe: me.onSwipe
});
},
initializeDragEvents: function() {
var me = this;
if (me.dragEventsInitialized) {
return;
}
me.dragEventsInitialized = true;
me.mon(me.el, {
scope: me,
dragstart: me.onDragStart,
drag: me.onDrag,
dragend: me.onDragEnd
});
},
// @private called to initialize components in the surface
// this is dependent on the underlying implementation.
initSurface: Ext.emptyFn,
// @private called to setup the surface to render an item
//this is dependent on the underlying implementation.
renderItem: Ext.emptyFn,
// @private
renderItems: Ext.emptyFn,
renderFrame: Ext.emptyFn,
// @private
setViewBox: Ext.emptyFn,
// @private
tween: Ext.emptyFn,
/**
* Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out.
*
* For example:
*
* drawComponent.surface.addCls(sprite, 'x-visible');
*
* @param {Object} sprite The sprite to add the class to.
* @param {String/Array} className The CSS class to add, or an array of classes
*/
addCls: Ext.emptyFn,
/**
* Removes one or more CSS classes from the element.
*
* For example:
*
* drawComponent.surface.removeCls(sprite, 'x-visible');
*
* @param {Object} sprite The sprite to remove the class from.
* @param {String/Array} className The CSS class to remove, or an array of classes
*/
removeCls: Ext.emptyFn,
/**
* Sets CSS style attributes to an element.
*
* For example:
*
* drawComponent.surface.setStyle(sprite, {
* 'cursor': 'pointer'
* });
*
* @param {Object} sprite The sprite to add, or an array of classes to
* @param {Object} styles An Object with CSS styles.
*/
setStyle: Ext.emptyFn,
// @private
createWrapEl: function(container) {
return Ext.fly(container).createChild({tag: 'div', cls: Ext.baseCSSPrefix + 'surface-wrap', style: 'overflow:hidden'});
},
// @private
initGradients: function() {
var gradients = this.gradients;
if (gradients) {
Ext.each(gradients, this.addGradient, this);
}
},
// @private
initItems: function() {
var me = this,
items = me.items;
me.items = new Ext.draw.CompositeSprite();
me.groups = new Ext.draw.CompositeSprite();
if (items) {
me.add(items);
}
},
// @private
initBackground: function(config) {
var me = this,
gradientId,
gradient,
width = me.width,
height = me.height;
if (config) {
if (config.gradient) {
gradient = config.gradient;
gradientId = gradient.id;
me.addGradient(gradient);
me.background = me.add({
type: 'rect',
x: 0,
y: 0,
width: width,
height: height,
fill: 'url(#' + gradientId + ')',
zIndex: -100
});
} else if (config.fill) {
me.background = me.add({
type: 'rect',
x: 0,
y: 0,
width: width,
height: height,
fill: config.fill,
zIndex: -100
});
} else if (config.image) {
me.background = me.add({
type: 'image',
x: 0,
y: 0,
width: width,
height: height,
src: config.image,
zIndex: -100
});
}
}
},
/**
* Sets the size of the surface. Accomodates the background (if any) to fit the new size too.
*
* For example:
*
* drawComponent.surface.setSize(500, 500);
*
* This method is generally called when also setting the size of the draw Component.
*
* @param {Number} w The new width of the canvas.
* @param {Number} h The new height of the canvas.
*/
setSize: function(w, h) {
if (this.background) {
this.background.setAttributes({
width: w,
height: h,
hidden: false
}, true);
}
this.width = w;
this.height = h;
this.updateSurfaceElBox();
},
// @private
scrubAttrs: function(sprite) {
var me = this,
attrs = {},
exclude = {},
sattr = sprite.attr,
i;
for (i in sattr) {
// Narrow down attributes to the main set
if (me.translateAttrs.hasOwnProperty(i)) {
// Translated attr
attrs[me.translateAttrs[i]] = sattr[i];
exclude[me.translateAttrs[i]] = true;
}
else if (me.availableAttrs.hasOwnProperty(i) && !exclude[i]) {
// Passtrhough attr
attrs[i] = sattr[i];
}
}
return attrs;
},
onMouseMove: createProcessEventMethod('mousemove'),
onMouseOver: createProcessEventMethod('mouseover'),
onMouseOut: createProcessEventMethod('mouseout'),
onMouseEnter: createProcessEventMethod('mouseenter'),
onMouseLeave: createProcessEventMethod('mouseleave'),
onMouseUp: createProcessEventMethod('mouseup'),
onMouseDown: createProcessEventMethod('mousedown'),
onClick: createProcessEventMethod('click'),
onDoubleClick: createProcessEventMethod('doubleclick'),
onTap: createProcessEventMethod('tap'),
onTapStart: createProcessEventMethod('tapstart'),
onTapEnd: createProcessEventMethod('tapend'),
onTapCancel: createProcessEventMethod('tapcancel'),
onTapHold: createProcessEventMethod('taphold'),
onDoubleTap: createProcessEventMethod('doubletap'),
onSingleTap: createProcessEventMethod('singletap'),
onTouchStart: createProcessEventMethod('touchstart'),
onTouchMove: createProcessEventMethod('touchmove'),
onTouchEnd: createProcessEventMethod('touchend'),
onDragStart: createProcessEventMethod('dragstart'),
onDrag: createProcessEventMethod('drag'),
onDragEnd: createProcessEventMethod('dragend'),
onPinchStart: createProcessEventMethod('pinchstart'),
onPinch: createProcessEventMethod('pinch'),
onPinchEnd: createProcessEventMethod('pinchend'),
onSwipe: createProcessEventMethod('swipe'),
// @private - Normalize a delegated single event from the main container to each sprite and sprite group
processEvent: function(name, e) {
var me = this,
sprite = me.getSpriteForEvent(e);
if (sprite) {
sprite.fireEvent(name, sprite, e);
}
me.fireEvent(name, e);
},
/**
* @protected - For a given event, find the Sprite corresponding to it if any.
* @return {Ext.draw.Sprite} The sprite instance, or null if none found.
*/
getSpriteForEvent: function(e) {
return null;
},
/**
* Add a gradient definition to the Surface. Note that in some surface engines, adding
* a gradient via this method will not take effect if the surface has already been rendered.
* Therefore, it is preferred to pass the gradients as an item to the surface config, rather
* than calling this method, especially if the surface is rendered immediately (e.g. due to
* 'renderTo' in its config). For more information on how to create gradients in the Chart
* configuration object please refer to {@link Ext.chart.Chart}.
*
* The gradient object to be passed into this method is composed by:
*
*
* - **id** - string - The unique name of the gradient.
* - **angle** - number, optional - The angle of the gradient in degrees.
* - **stops** - object - An object with numbers as keys (from 0 to 100) and style objects as values.
*
*
For example:
drawComponent.surface.addGradient({
id: 'gradientId',
angle: 45,
stops: {
0: {
color: '#555'
},
100: {
color: '#ddd'
}
}
});
*/
addGradient: Ext.emptyFn,
/**
* Add a Sprite to the surface. See {@link Ext.draw.Sprite} for the configuration object to be passed into this method.
*
* For example:
*
* drawComponent.surface.add({
* type: 'circle',
* fill: '#ffc',
* radius: 100,
* x: 100,
* y: 100
* });
*
*/
add: function() {
var me = this,
args = Array.prototype.slice.call(arguments),
hasMultipleArgs = args.length > 1,
sprite, items, i, ln, item, results;
if (hasMultipleArgs || Ext.isArray(args[0])) {
items = hasMultipleArgs ? args : args[0];
results = [];
for (i = 0, ln = items.length; i < ln; i++) {
item = items[i];
item = me.add(item);
results.push(item);
}
return results;
}
sprite = me.prepareItems(args[0], true)[0];
me.normalizeSpriteCollection(sprite);
me.onAdd(sprite);
return sprite;
},
/**
* @private
* Insert or move a given sprite into the correct position in the items
* MixedCollection, according to its zIndex. Will be inserted at the end of
* an existing series of sprites with the same or lower zIndex. If the sprite
* is already positioned within an appropriate zIndex group, it will not be moved.
* This ordering can be used by subclasses to assist in rendering the sprites in
* the correct order for proper z-index stacking.
* @param {Ext.draw.Sprite} sprite
* @return {Number} the sprite's new index in the list
*/
normalizeSpriteCollection: function(sprite) {
var items = this.items,
zIndex = sprite.attr.zIndex,
idx = items.indexOf(sprite);
if (idx < 0 || (idx > 0 && items.getAt(idx - 1).attr.zIndex > zIndex) ||
(idx < items.length - 1 && items.getAt(idx + 1).attr.zIndex < zIndex)) {
items.removeAt(idx);
idx = items.findIndexBy(function(otherSprite) {
return otherSprite.attr.zIndex > zIndex;
});
if (idx < 0) {
idx = items.length;
}
items.insert(idx, sprite);
}
return idx;
},
onAdd: function(sprite) {
var group = sprite.group,
draggable = sprite.draggable,
groups, ln, i;
if (group) {
groups = [].concat(group);
ln = groups.length;
for (i = 0; i < ln; i++) {
group = groups[i];
this.getGroup(group).add(sprite);
}
delete sprite.group;
}
if (draggable) {
sprite.initDraggable();
}
},
/**
* Remove a given sprite from the surface, optionally destroying the sprite in the process.
* You can also call the sprite own `remove` method.
*
* For example:
*
* drawComponent.surface.remove(sprite);
* //or...
* sprite.remove();
*
* @param {Ext.draw.Sprite} sprite
* @param {Boolean} destroySprite
* @return {Number} the sprite's new index in the list
*/
remove: function(sprite, destroySprite) {
if (sprite) {
this.items.remove(sprite);
this.groups.each(function(item) {
item.remove(sprite);
});
sprite.onRemove();
if (destroySprite === true) {
sprite.destroy();
}
}
},
/**
* Remove all sprites from the surface, optionally destroying the sprites in the process.
*
* For example:
*
* drawComponent.surface.removeAll();
*
* @param {Boolean} destroySprites Whether to destroy all sprites when removing them.
* @return {Number} The sprite's new index in the list.
*/
removeAll: function(destroySprites) {
var items = this.items.items,
ln = items.length,
i;
for (i = ln - 1; i > -1; i--) {
this.remove(items[i], destroySprites);
}
},
onRemove: Ext.emptyFn,
onDestroy: Ext.emptyFn,
// @private
applyTransformations: function(sprite) {
sprite.bbox.transform = 0;
sprite.dirtyTransform = false;
var me = this,
dirty = false,
attr = sprite.attr;
if (attr.translation.x != null || attr.translation.y != null) {
me.translate(sprite);
dirty = true;
}
if (attr.scaling.x != null || attr.scaling.y != null) {
me.scale(sprite);
dirty = true;
}
if (attr.rotation.degrees != null) {
me.rotate(sprite);
dirty = true;
}
if (dirty) {
sprite.bbox.transform = 0;
me.transform(sprite);
sprite.transformations = [];
}
},
// @private
rotate: function (sprite) {
var bbox,
deg = sprite.attr.rotation.degrees,
centerX = sprite.attr.rotation.x,
centerY = sprite.attr.rotation.y,
trans = sprite.attr.translation,
dx = trans && trans.x || 0,
dy = trans && trans.y || 0;
if (!Ext.isNumber(centerX) || !Ext.isNumber(centerY)) {
bbox = this.getBBox(sprite, true); //isWithoutTransform=true
centerX = !Ext.isNumber(centerX) ? (bbox.x + dx) + bbox.width / 2 : centerX;
centerY = !Ext.isNumber(centerY) ? (bbox.y + dy) + bbox.height / 2 : centerY;
}
sprite.transformations.push({
type: "rotate",
degrees: deg,
x: centerX,
y: centerY
});
},
// @private
translate: function(sprite) {
var x = sprite.attr.translation.x || 0,
y = sprite.attr.translation.y || 0;
sprite.transformations.push({
type: "translate",
x: x,
y: y
});
},
// @private
scale: function(sprite) {
var bbox,
x = sprite.attr.scaling.x || 1,
y = sprite.attr.scaling.y || 1,
centerX = sprite.attr.scaling.centerX,
centerY = sprite.attr.scaling.centerY;
if (!Ext.isNumber(centerX) || !Ext.isNumber(centerY)) {
bbox = this.getBBox(sprite);
centerX = !Ext.isNumber(centerX) ? bbox.x + bbox.width / 2 : centerX;
centerY = !Ext.isNumber(centerY) ? bbox.y + bbox.height / 2 : centerY;
}
sprite.transformations.push({
type: "scale",
x: x,
y: y,
centerX: centerX,
centerY: centerY
});
},
// @private
rectPath: function (x, y, w, h, r) {
if (r) {
return [["M", x + r, y], ["l", w - r * 2, 0], ["a", r, r, 0, 0, 1, r, r], ["l", 0, h - r * 2], ["a", r, r, 0, 0, 1, -r, r], ["l", r * 2 - w, 0], ["a", r, r, 0, 0, 1, -r, -r], ["l", 0, r * 2 - h], ["a", r, r, 0, 0, 1, r, -r], ["z"]];
}
return [["M", x, y], ["l", w, 0], ["l", 0, h], ["l", -w, 0], ["z"]];
},
// @private
ellipsePath: function (x, y, rx, ry) {
if (ry == null) {
ry = rx;
}
return [["M", x, y], ["m", 0, -ry], ["a", rx, ry, 0, 1, 1, 0, 2 * ry], ["a", rx, ry, 0, 1, 1, 0, -2 * ry], ["z"]];
},
// @private
getPathpath: function (el) {
return el.attr.path;
},
// @private
getPathcircle: function (el) {
var a = el.attr;
return this.ellipsePath(a.x, a.y, a.radius, a.radius);
},
// @private
getPathellipse: function (el) {
var a = el.attr;
return this.ellipsePath(a.x, a.y, a.radiusX, a.radiusY);
},
// @private
getPathrect: function (el) {
var a = el.attr;
return this.rectPath(a.x, a.y, a.width, a.height, a.r);
},
// @private
getPathimage: function (el) {
var a = el.attr;
return this.rectPath(a.x || 0, a.y || 0, a.width, a.height);
},
// @private
getPathtext: function (el) {
var bbox = this.getBBoxText(el);
return this.rectPath(bbox.x, bbox.y, bbox.width, bbox.height);
},
createGroup: function(id) {
var group = this.groups.get(id);
if (!group) {
group = new Ext.draw.CompositeSprite({
surface: this
});
group.id = id || Ext.id(null, 'ext-surface-group-');
this.groups.add(group);
}
return group;
},
/**
* Returns a new group or an existent group associated with the current surface.
* The group returned is a {@link Ext.draw.CompositeSprite} group.
*
* For example:
*
* var spriteGroup = drawComponent.surface.getGroup('someGroupId');
*
* @param {String} id The unique identifier of the group.
* @return {Object} The {@link Ext.draw.CompositeSprite}.
*/
getGroup: function(id) {
if (typeof id == "string") {
var group = this.groups.get(id);
if (!group) {
group = this.createGroup(id);
}
} else {
group = id;
}
return group;
},
// @private
prepareItems: function(items, applyDefaults) {
items = [].concat(items);
// Make sure defaults are applied and item is initialized
var item, i, ln;
for (i = 0, ln = items.length; i < ln; i++) {
item = items[i];
if (!(item instanceof Ext.draw.Sprite)) {
// Temporary, just take in configs...
item.surface = this;
items[i] = this.createItem(item);
} else {
item.surface = this;
}
}
return items;
},
/**
* Changes the text in the sprite element. The sprite must be a `text` sprite.
* This method can also be called from {@link Ext.draw.Sprite}.
*
* For example:
*
* var spriteGroup = drawComponent.surface.setText(sprite, 'my new text');
*
* @param {Object} sprite The Sprite to change the text.
* @param {String} text The new text to be set.
*/
setText: Ext.emptyFn,
//@private Creates an item and appends it to the surface. Called
//as an internal method when calling `add`.
createItem: Ext.emptyFn,
/**
* Retrieves the id of this component.
* Will autogenerate an id if one has not already been set.
*/
getId: function() {
return this.id || (this.id = Ext.id(null, 'ext-surface-'));
},
/**
* Destroys the surface. This is done by removing all components from it and
* also removing its reference to a DOM element.
*
* For example:
*
* drawComponent.surface.destroy();
*/
destroy: function() {
delete this.domRef;
this.removeAll();
},
//Empty the surface (without destroying it)
clear: Ext.emtpyFn,
/**
* @private update the position/size/clipping of the series surface to match the current
* chartBBox and the stored zoom/pan properties.
*/
updateSurfaceElBox: function() {
var me = this,
floor = Math.floor,
width = floor(me.width * me.zoomX),
height = floor(me.height * me.zoomY),
panX = me.panX,
panY = me.panY,
maxWidth = 2000,
maxHeight = 1500,
surfaceEl = me.surfaceEl,
surfaceDom = surfaceEl.dom,
surfaceWidth = me.width,
surfaceHeight = me.height,
ctx = me.surfaceEl.dom.getContext('2d'),
setTranslation = false,
newWidth, newHeight,
diffX, diffY;
if (width * height > maxWidth * maxHeight) {
setTranslation = true;
//maintain aspect ratio.
newHeight = height * maxWidth / width;
if (newHeight > height) {
newHeight = maxHeight;
}
newWidth = width * newHeight / height;
panX = (surfaceWidth - newWidth) / 2;
panY = (surfaceHeight - newHeight) / 2;
diffX = me.panX - panX;
diffY = me.panY - panY;
width = newWidth;
height = newHeight;
}
// adjust the surfaceEl to match current zoom/pan; only if the size is changing to prevent
// the canvas from getting cleared as happens when width/height are set.
if (surfaceDom.width != width || surfaceDom.height != height) {
surfaceEl.setSize(width, height);
surfaceDom.width = width;
surfaceDom.height = height;
//TODO(nico): this is canvas specific.
//this with the pixel check should be moved to
//Canvas.js.
if (setTranslation) {
ctx.translate(diffX, diffY);
}
}
surfaceEl.setTopLeft(panY, panX);
},
/**
* Sets the persistent transform and updates the surfaceEl's size and position to match.
* @param {Number} panX
* @param {Number} panY
* @param {Number} zoomX
* @param {Number} zoomY
*/
setSurfaceTransform: function(panX, panY, zoomX, zoomY) {
var me = this;
me.panX = panX;
me.panY = panY;
me.zoomX = zoomX;
me.zoomY = zoomY;
me.setSurfaceFastTransform(null);
me.updateSurfaceElBox();
},
/**
* Sets a fast CSS3 transform on the surfaceEl.
* @param {Ext.draw.Matrix} matrix
*/
setSurfaceFastTransform: function(matrix) {
this.transformMatrix = matrix;
this.surfaceEl.setStyle({
webkitTransformOrigin: '0 0',
webkitTransform: matrix ? matrix.toSvg() : ''
});
}
});
})();
/**
* Create and return a new concrete Surface instance appropriate for the current environment.
* @param {Object} config Initial configuration for the Surface instance
* @param {Array} enginePriority Optional order of implementations to use; the first one that is
* available in the current environment will be used. Defaults to
* <code>['Svg', 'Vml']</code>.
*/
Ext.draw.Surface.create = function(config, enginePriority) {
return new Ext.draw.engine.Canvas(config);
enginePriority = enginePriority || ['Canvas', 'Svg'];
var i = 0,
len = enginePriority.length;
for (; i < len; i++) {
//if (Ext.supports[enginePriority[i]]) {
//return new Ext.draw.engine[enginePriority[i]](config);
//return new Ext.draw.engine.Svg(config);
//}
}
return false;
};
/**
* A list of all event names that should be relayed by a Surface object from its inner surfaceEl.
*/
Ext.draw.Surface.eventNames = [
'mouseup',
'mousedown',
'mouseover',
'mouseout',
'mousemove',
'mouseenter',
'mouseleave',
'click',
'dblclick',
'tap',
'tapstart',
'tapend',
'tapcancel',
'taphold',
'doubletap',
'singletap',
'touchstart',
'touchmove',
'touchend',
'drag',
'dragstart',
'dragend',
'pinch',
'pinchstart',
'pinchend',
'swipe'
];
/**
* @class Ext.draw.Canvas
* @extends Ext.draw.Surface
*<p>Provides specific methods to draw with Canvas.</p>
*/
Ext.draw.engine.Canvas = Ext.extend(Ext.draw.Surface, {
//read only style attribute canvas property mapping.
attributeMap: {
rotate: "rotation",
stroke: "strokeStyle",
fill: "fillStyle",
lineWidth: "lineWidth",
"text-anchor": "textAlign",
"stroke-width": "lineWidth",
"stroke-linecap": "lineCap",
"stroke-linejoin": "lineJoin",
"stroke-miterlimit": "miterLimit",
opacity: "globalAlpha",
font: 'font',
shadowColor: "shadowColor",
shadowOffsetX: "shadowOffsetX",
shadowOffsetY: "shadowOffsetY",
shadowBlur: "shadowBlur"
},
//read only default canvas property value map.
attributeDefaults: {
strokeStyle: "rgba(0, 0, 0, 0)",
fillStyle: "rgba(0, 0, 0, 0)",
lineWidth: 1,
lineCap: "square",
lineJoin: "miter",
miterLimit: 1,
shadowColor: "none",
shadowOffsetX: 0,
shadowOffsetY: 0,
shadowBlur: 0,
font: "10px Helvetica, sans-serif",
textAlign: "start",
globalAlpha: 1
},
gradientRe: /\s*url\s*\(#([^\)]+)\)\s*/,
//read-only map of value convertions
//used to convert a gradient id string into a gradient object
//in a generic way
attributeParsers: {
fillStyle: function(value, sprite, me) {
if (!value) {
return value;
}
//is a gradient object
if (Ext.isObject(value)) {
me.addGradient(value);
value = 'url(#' + value.id + ')';
}
var id = value.match(me.gradientRe);
if (id) {
return me.createGradient(me._gradients[id[1]], sprite);
} else {
return value == 'none'? 'rgba(0, 0, 0, 0)' : value;
}
},
strokeStyle: function(value, sprite, me) {
if (!value) {
return value;
}
//is a gradient object
if (Ext.isObject(value)) {
me.addGradient(value);
value = 'url(#' + value.id + ')';
}
var id = value.match(me.gradientRe);
if (id) {
return me.createGradient(me._gradients[id[1]], sprite);
} else {
return value == 'none'? 'rgba(0, 0, 0, 0)' : value;
}
},
textAlign: function(value, sprite) {
if (value === 'middle') {
return 'center';
}
return value;
}
},
constructor: function(config) {
var me = this;
//whether to add an event system to the canvas or not
me.initEvents = 'initEvents' in config ? config.initEvents : true;
//store a hash of gradient configurations
me._gradients = {};
Ext.draw.engine.Canvas.superclass.constructor.apply(this, arguments);
me.initCanvas(config.renderTo);
// Redraw after each animation frame event
Ext.fx.Manager.addListener('frameend', function() {
// Only render a frame on frameend if we were changed via tween
if (me.animatedFrame) {
me.animatedFrame = false;
me.renderFrame();
}
});
//disable context menu
//TODO(nico): This should be configurable.
this.canvas.oncontextmenu = function() { return false; };
},
//initializes the only canvas instance to draw the shapes to.
initCanvas: function(container) {
if (this.ctx) {
return;
}
var me = this,
domContainer = Ext.get(container),
width = domContainer.getWidth(),
height = domContainer.getHeight(),
div = me.createWrapEl(container),
canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
div.setSize(width, height);
//add an id to the dom div element.
div.dom.id = me.id + '-wrap';
canvas.id = me.id + '-canvas';
canvas.width = width;
canvas.height = height;
div.appendChild(canvas);
me.el = div;
me.surfaceEl = Ext.get(canvas);
me.canvas = canvas;
me.ctx = ctx;
//Add event manager for canvas class
if (me.initEvents) {
me.initializeEvents();
}
},
getSpriteForEvent: function() {
return null; //TODO!!!
},
//stores the gradient configuration into a hashmap
addGradient: function(gradient) {
var me = this;
gradient = Ext.draw.Draw.parseGradient(gradient);
me._gradients[gradient.id] = gradient;
},
//applies the current transformations to the element's matrix
//TODO(nico): similar to what's found in Svg engine
transform: function(sprite) {
var matrix = new Ext.draw.Matrix,
transforms = sprite.transformations,
transformsLength = transforms.length,
i = 0,
transform, type;
for (; i < transformsLength; i++) {
transform = transforms[i];
type = transform.type;
if (type == "translate") {
matrix.translate(transform.x, transform.y);
}
else if (type == "rotate") {
matrix.rotate(transform.degrees, transform.x, transform.y);
}
else if (type == "scale") {
matrix.scale(transform.x, transform.y, transform.centerX, transform.centerY);
}
}
sprite.matrix = matrix;
},
setSize: function(w, h) {
var width, height,
me = this,
canvas = me.canvas;
if (typeof w == 'object') {
width = w.width;
height = w.height;
} else {
width = w;
height = h;
}
if (width !== canvas.width || height !== canvas.height) {
me.el.setSize(width, height);
me.surfaceEl.setSize(width, height);
canvas.width = width;
canvas.height = height;
me.width = width;
me.height = height;
}
Ext.draw.engine.Canvas.superclass.setSize.call(this, w, h);
},
tween: function() {
this.animatedFrame = true;
Ext.draw.engine.Canvas.superclass.tween.apply(this);
},
//Rendering
renderFrame: function() {
this.render();
},
render: function(container) {
var me = this;
if (!me.canvas) {
me.initCanvas(container);
}
me.renderAll();
},
createItem: function (config) {
var sprite = new Ext.draw.Sprite(config);
sprite.surface = this;
sprite.matrix = new Ext.draw.Matrix;
sprite.bbox = {
plain: 0,
transform: 0
};
return sprite;
},
// @private
//TODO(nico): should sort also by abstract concept: "priority"
zIndexSort: function(a, b) {
var aAttr = a.attr,
bAttr = b.attr,
aIndex = aAttr && aAttr.zIndex || -1,
bIndex = bAttr && bAttr.zIndex || -1,
val = aIndex - bIndex;
if (!val) {
return (a.id > b.id) ? 1 : -1;
}
else {
return val;
}
},
renderAll: function() {
var me = this;
me.clear();
//sort by zIndex
me.items.items.sort(me.zIndexSort);
me.items.each(me.renderSprite, me);
},
renderSprite: function (sprite) {
// Clear dirty flags that aren't used by the Canvas renderer
sprite.dirtyHidden = sprite.dirtyPath = sprite.zIndexDirty = sprite.dirtyFont = sprite.dirty = false;
if (sprite.attr.hidden) {
return;
}
if (!sprite.matrix) {
sprite.matrix = new Ext.draw.Matrix();
}
var me = this,
ctx = me.ctx,
attr = sprite.attr,
attributeMap = me.attributeMap,
attributeDefaults = me.attributeDefaults,
attributeParsers = me.attributeParsers,
prop, val, propertyValue;
if (sprite.dirtyTransform) {
me.applyTransformations(sprite);
}
ctx.save();
//set matrix state
sprite.matrix.toCanvas(ctx);
//set styles
for (prop in attributeMap) {
val = attributeMap[prop];
if (val in attributeParsers) {
propertyValue = attributeParsers[val](attr[prop], sprite, me);
if (propertyValue !== undefined) {
ctx[val] = propertyValue;
} else {
ctx[val] = attributeDefaults[val];
}
}
else {
propertyValue = attr[prop];
if (propertyValue !== undefined) {
ctx[val] = propertyValue;
} else {
ctx[val] = attributeDefaults[val];
}
}
}
//render shape
me[sprite.type + 'Render'](sprite);
ctx.restore();
},
circleRender: function(sprite) {
var me = this,
ctx = me.ctx,
attr = sprite.attr,
x = +(attr.x || 0),
y = +(attr.y || 0),
radius = attr.radius,
pi2 = Ext.draw.Draw.pi2;
//draw fill circle
ctx.beginPath();
ctx.arc(x, y, radius, 0, pi2, true);
ctx.closePath();
ctx.fill();
//draw stroke circle
ctx.beginPath();
ctx.arc(x, y, radius, 0, pi2, true);
ctx.closePath();
ctx.stroke();
},
ellipseRender: function(sprite) {
var me = this,
ctx = me.ctx,
attr = sprite.attr,
width = attr.width,
height = attr.height,
x = +(attr.x || 0),
y = +(attr.y || 0),
scaleX = 1,
scaleY = 1,
scalePosX = 1,
scalePosY = 1,
radius = 0,
pi2 = Ext.draw.Draw.pi2;
if (width > height) {
radius = width / 2;
scaleY = height / width;
scalePosY = width / height;
}
else {
radius = height / 2;
scaleX = width / height;
scalePosX = height / width;
}
ctx.scale(scaleX, scaleY);
//make fill ellipse
ctx.beginPath();
ctx.arc(x * scalePosX, y * scalePosY, radius, 0, pi2, true);
ctx.closePath();
ctx.fill();
//make stroke ellipse
ctx.beginPath();
ctx.arc(x * scalePosX, y * scalePosY, radius, 0, pi2, true);
ctx.closePath();
ctx.stroke();
},
imageRender: function(sprite) {
var me = this,
ctx = me.ctx,
attr = sprite.attr,
width = attr.width,
height = attr.height,
x = +(attr.x || 0),
y = +(attr.y || 0),
src = attr.src,
img;
if (sprite._img) {
img = sprite._img;
}
else {
sprite._img = img = new Image();
img.height = height;
img.width = width;
img._loading = true;
img.onload = function() {
img._loading = false;
me.renderFrame();
};
img.src = src.slice(1, src.length -1);
}
if (!img._loading) {
ctx.drawImage(img, x - width / 2, y - height / 2, width, height);
}
},
rectRender: function(sprite) {
var me = this,
ctx = me.ctx,
attr = sprite.attr,
width = attr.width,
height = attr.height,
x = +(attr.x || 0),
y = +(attr.y || 0);
if (isFinite(x) && isFinite(y) && isFinite(width) && isFinite(height)) {
ctx.fillRect(x, y, width, height);
ctx.strokeRect(x, y, width, height);
}
},
textRender: function(sprite) {
var me = this,
ctx = me.ctx,
attr = sprite.attr,
x = +(attr.x || 0),
y = +(attr.y || 0),
text = attr.text;
if (isFinite(x) && isFinite(y)) {
ctx.textBaseline = 'middle';
ctx.fillText(text, x, y);
}
},
pathRender: function(sprite) {
if (!sprite.attr.path) {
return;
}
var me = this,
ctx = me.ctx,
attr = sprite.attr,
path = Ext.draw.Draw.path2curve(attr.path),
ln = path.length,
x, y, i;
ctx.beginPath();
for (i = 0; i < ln; i++) {
switch (path[i][0]) {
case "M":
ctx.moveTo(path[i][1], path[i][2]);
if (x == null) {
x = path[i][1];
}
if (y == null) {
y = path[i][2];
}
break;
case "C":
ctx.bezierCurveTo(path[i][1],
path[i][2],
path[i][3],
path[i][4],
path[i][5],
path[i][6]);
break;
case "Z":
ctx.lineTo(x, y);
break;
}
}
//if stroke is not transparent then draw it
if (attr.stroke && attr.stroke != 'none' && attr.stroke != 'rgba(0, 0, 0, 0)') {
ctx.stroke();
}
//if fill is not transparent then draw it
if (attr.fill && attr.fill != 'none' && attr.fill != 'rgba(0, 0, 0, 0)') {
ctx.fill();
}
ctx.closePath();
},
//Contains method used for event handling.
//Returns the target pointed by the mouse or
//false otherwise.
contains: function(x, y) {
var me = this,
items = me.items.items,
l = items.length,
sprite;
while (l--) {
sprite = items[l];
if (me.bboxContains(x, y, sprite)) {
if (me[sprite.type + 'Contains'](x, y, sprite)) {
//TODO(nico): not returning just the sprite because a
//more complex object with more informaiton on the event
//may be returned.
return {
target: sprite
};
}
}
}
return false;
},
//Whether the point is in the BBox of the shape
bboxContains: function(x, y, sprite) {
var bbox = sprite.getBBox();
return (x >= bbox.x && x <= (bbox.x + bbox.width)
&& (y >= bbox.y && y <= (bbox.y + bbox.height)));
},
//Whether the point is in the shape
circleContains: function(x, y, sprite) {
var attr = sprite.attr,
trans = attr.translation,
cx = (attr.x || 0) + (trans && trans.x || 0),
cy = (attr.y || 0) + (trans && trans.y || 0),
dx = x - cx,
dy = y - cy,
radius = attr.radius;
return (dx * dx + dy * dy) <= (radius * radius);
},
//Whether the point is in the shape
ellipseContains: function(x, y, sprite) {
var attr = sprite.attr,
trans = attr.translation,
cx = (attr.x || 0) + (trans && trans.x || 0),
cy = (attr.y || 0) + (trans && trans.y || 0),
radiusX = attr.radiusX || (attr.width / 2) || 0,
radiusY = attr.radiusY || (attr.height / 2) || 0,
radius = 0,
scaleX = 1,
scaleY = 1,
dx, dy;
if (radiusX > radiusY) {
radius = radiusX;
scaleY = radiusY / radiusX;
} else {
radius = radiusY;
scaleY = radiusX / radiusY;
}
dx = (x - cx) / scaleX;
dy = (y - cy) / scaleY;
return (dx * dx + dy * dy) <= (radius * radius);
},
//Same behavior as the BBox check, so return true.
imageContains: function(x, y, sprite) {
return true;
},
//Same behavior as the BBox check, so return true.
rectContains: function(x, y, sprite) {
return true;
},
//Same behavior as the BBox check, so return true.
textContains: function(x, y, sprite) {
return true;
},
//TODO(nico): to be implemented later.
pathContains: function(x, y, sprite) {
return false;
},
createGradient: function(gradient, sprite) {
var ctx = this.ctx,
bbox = sprite.getBBox(),
x1 = bbox.x,
y1 = bbox.y,
width = bbox.width,
height = bbox.height,
x2 = x1 + width,
y2 = y1 + height,
a = Math.round(Math.abs(gradient.degrees || gradient.angle || 0) % 360),
stops = gradient.stops,
stop, canvasGradient;
if (a <= 0) {
canvasGradient = ctx.createLinearGradient(x1, y1, x1, y2);
} else if (a <= 45) {
canvasGradient = ctx.createLinearGradient(x1, y1, x2, y2);
} else if (a <= 90) {
canvasGradient = ctx.createLinearGradient(x1, y1, x2, y1);
} else if (a <= 135) {
canvasGradient = ctx.createLinearGradient(x2, y1, x1, y2);
} else if (a <= 180) {
canvasGradient = ctx.createLinearGradient(x1, y2, x1, y1);
} else if (a <= 225) {
canvasGradient = ctx.createLinearGradient(x2, y2, x1, y1);
} else if (a <= 270) {
canvasGradient = ctx.createLinearGradient(x2, y1, x1, y1);
} else if (a <= 315) {
canvasGradient = ctx.createLinearGradient(x1, y2, x2, y1);
} else {
canvasGradient = ctx.createLinearGradient(x1, y1, x2, y2);
}
for (stop in stops) {
if (stops.hasOwnProperty(stop)) {
canvasGradient.addColorStop(stop, stops[stop].color || '#000');
}
}
return canvasGradient;
},
//getBBox
getBBox: function (sprite, isWithoutTransform) {
if (sprite.type == 'text') {
return this.getBBoxText(sprite, isWithoutTransform);
}
var realPath = this["getPath" + sprite.type](sprite);
if (isWithoutTransform) {
sprite.bbox.plain = sprite.bbox.plain || Ext.draw.Draw.pathDimensions(realPath);
return sprite.bbox.plain;
}
//sprite.bbox.transform = sprite.bbox.transform || Ext.draw.Draw.pathDimensions(Ext.draw.Draw.mapPath(realPath, sprite.matrix));
//caching the bounding box causes problems :(
sprite.bbox.transform = Ext.draw.Draw.pathDimensions(Ext.draw.Draw.mapPath(realPath, sprite.matrix));
return sprite.bbox.transform;
},
getBBoxText: function(sprite, isWithoutTransform) {
var me = this,
ctx = me.ctx,
attr = sprite.attr,
matrix,
x = attr.x || 0,
y = attr.y || 0,
x1, x2, y1, y2,
x1t, x2t, x3t, x4t,
y1t, y2t, y3t, y4t,
width, height,
trans = sprite.attr.translation,
dx = trans && trans.x || 0,
dy = trans && trans.y || 0,
font = attr.font,
fontSize = +(font && font.match(/[0-9]+/)[0]) || 10,
text = attr.text,
measure;
ctx.save();
if (font) {
ctx.font = font;
}
measure = ctx.measureText(text);
ctx.restore();
if (sprite.dirtyTransform) {
me.applyTransformations(sprite);
}
matrix = sprite.matrix;
x1 = x + dx;
y1 = y + dy;
x2 = x1 + (measure.width || fontSize);
y2 = y1 + (measure.height || fontSize);
if (isWithoutTransform) {
return {
x: x,
y: y,
width: (measure.width || fontSize),
height: (measure.height || fontSize)
};
}
x1t = matrix.x(x1, y1);
y1t = matrix.y(x1, y1);
x2t = matrix.x(x1, y2);
y2t = matrix.y(x1, y2);
x3t = matrix.x(x2, y1);
y3t = matrix.y(x2, y1);
x4t = matrix.x(x2, y2);
y4t = matrix.y(x2, y2);
x = Math.min(x1t, x2t, x3t, x4t);
y = Math.min(y1t, y2t, y3t, y4t);
width = Math.abs(x - Math.max(x1t, x2t, x3t, x4t));
height = Math.abs(y - Math.max(y1t, y2t, y3t, y4t));
return {
x: x,
y: y,
width: width,
height: height
};
},
getRegion: function() {
var canvas = this.canvas,
xy = Ext.get(canvas).getXY();
return {
left: xy[0],
top: xy[1],
right: xy[0] + canvas.width,
bottom: xy[1] + canvas.height
};
},
//force will force the method to return a value.
getShadowAttributesArray: function(force) {
if (force) {
return [{
"stroke-width": 6,
"stroke-opacity": 1,
stroke: 'rgba(200, 200, 200, 0.5)',
translate: {
x: 1.2,
y: 2
}
},
{
"stroke-width": 4,
"stroke-opacity": 1,
stroke: 'rgba(150, 150, 150, 0.5)',
translate: {
x: 0.9,
y: 1.5
}
},
{
"stroke-width": 2,
"stroke-opacity": 1,
stroke: 'rgba(100, 100, 100, 0.5)',
translate: {
x: 0.6,
y: 1
}
}];
} else {
return [];
}
},
//force will force the method to return a value.
getShadowOptions: function(force) {
return {
shadowOffsetX: 2,
//http://code.google.com/p/android/issues/detail?id=16025
shadowOffsetY: Ext.is.Android ? -2 : 2,
shadowBlur: 3,
shadowColor: '#444'
};
},
clear: function() {
var me = this,
canvas = me.canvas,
ctx = me.ctx,
width = canvas.width,
height = canvas.height;
ctx.clearRect(0, 0, width, height);
}
});
/**
* @class Ext.draw.Component
* @extends Ext.Component
*
* The Draw Component is a surface in which sprites can be rendered. The Draw Component
* manages and holds a `Surface` instance: an interface that has
* an SVG or VML implementation depending on the browser capabilities and where
* Sprites can be appended.
* {@img Ext.draw.Component/Ext.draw.Component.png Ext.draw.Component component}
* One way to create a draw component is:
*
* var drawComponent = Ext.create('Ext.draw.Component', {
* viewBox: false,
* items: [{
* type: 'circle',
* fill: '#79BB3F',
* radius: 100,
* x: 100,
* y: 100
* }]
* });
*
* Ext.create('Ext.Window', {
* width: 215,
* height: 235,
* layout: 'fit',
* items: [drawComponent]
* }).show();
*
* In this case we created a draw component and added a sprite to it.
* The *type* of the sprite is *circle* so if you run this code you'll see a yellow-ish
* circle in a Window. When setting `viewBox` to `false` we are responsible for setting the object's position and
* dimensions accordingly.
*
* You can also add sprites by using the surface's add method:
*
* drawComponent.surface.add({
* type: 'circle',
* fill: '#79BB3F',
* radius: 100,
* x: 100,
* y: 100
* });
*
* For more information on Sprites, the core elements added to a draw component's surface,
* refer to the Ext.draw.Sprite documentation.
*/
Ext.draw.Component = Ext.extend(Ext.Component, {
/**
* @cfg {Array} enginePriority
* Defines the priority order for which Surface implementation to use. The first
* one supported by the current environment will be used.
*/
enginePriority: ['Canvas'],
baseCls: 'ext-surface',
componentLayout: 'draw',
/**
* @cfg {Boolean} viewBox
* Turn on view box support which will scale and position items in the draw component to fit to the component while
* maintaining aspect ratio. Note that this scaling can override other sizing settings on yor items. Defaults to true.
*/
viewBox: true,
/**
* @cfg {Boolean} autoSize
* Turn on autoSize support which will set the bounding div's size to the natural size of the contents. Defaults to false.
*/
autoSize: false,
/**
* @cfg {Array} gradients (optional) Define a set of gradients that can be used as `fill` property in sprites.
* The gradients array is an array of objects with the following properties:
*
* <ul>
* <li><strong>id</strong> - string - The unique name of the gradient.</li>
* <li><strong>angle</strong> - number, optional - The angle of the gradient in degrees.</li>
* <li><strong>stops</strong> - object - An object with numbers as keys (from 0 to 100) and style objects
* as values</li>
* </ul>
*
For example:
<pre><code>
gradients: [{
id: 'gradientId',
angle: 45,
stops: {
0: {
color: '#555'
},
100: {
color: '#ddd'
}
}
}, {
id: 'gradientId2',
angle: 0,
stops: {
0: {
color: '#590'
},
20: {
color: '#599'
},
100: {
color: '#ddd'
}
}
}]
</code></pre>
Then the sprites can use `gradientId` and `gradientId2` by setting the fill attributes to those ids, for example:
<pre><code>
sprite.setAttributes({
fill: 'url(#gradientId)'
}, true);
</code></pre>
*/
cls: 'x-draw-component',
initComponent: function() {
var me = this;
Ext.draw.Component.superclass.initComponent.call(me);
// Expose all mouse/touch events fired by the Surface
me.addEvents.apply(me, Ext.draw.Surface.eventNames);
},
/**
* @private
*
* Create the Surface on initial render
*/
onRender: function() {
var me = this,
viewBox = me.viewBox,
autoSize = me.autoSize,
bbox, items, width, height, x, y;
Ext.draw.Component.superclass.onRender.apply(this, arguments);
me.surface = me.createSurface();
items = me.surface.items;
if (viewBox || autoSize) {
bbox = items.getBBox();
width = bbox.width;
height = bbox.height;
x = bbox.x;
y = bbox.y;
if (me.viewBox) {
me.surface.setViewBox(x, y, width, height);
}
else {
// AutoSized
me.autoSizeSurface();
}
}
},
/**
* @private Return a reference to the {@link Ext.draw.Surface} instance from which events
* should be relayed.
*/
getEventsSurface: function() {
return this.surface;
},
initEvents: function() {
var me = this;
Ext.draw.Component.superclass.initEvents.call(me);
// Relay all mouse/touch events from the surface
me.relayEvents(me.getEventsSurface(), Ext.draw.Surface.eventNames);
},
//@private
autoSizeSurface: function() {
var me = this,
items = me.surface.items,
bbox = items.getBBox(),
width = bbox.width,
height = bbox.height;
items.setAttributes({
translate: {
x: -bbox.x,
//Opera has a slight offset in the y axis.
y: -bbox.y + (+Ext.isOpera)
}
}, true);
if (me.rendered) {
me.setSize(width, height);
}
else {
me.surface.setSize(width, height);
}
me.el.setSize(width, height);
},
/**
* Create the Surface instance. Resolves the correct Surface implementation to
* instantiate based on the 'enginePriority' config. Once the Surface instance is
* created you can use the handle to that instance to add sprites. For example:
*
<pre><code>
drawComponent.surface.add(sprite);
</code></pre>
*/
createSurface: function(config) {
var me = this,
apply = Ext.apply;
return Ext.draw.Surface.create(apply({}, apply({
width: me.width,
height: me.height,
renderTo: me.el,
id: Ext.id()
}, config), me.initialConfig));
},
/**
* @private
*
* Clean up the Surface instance on component destruction
*/
onDestroy: function() {
var surface = this.surface;
if (surface) {
surface.destroy();
}
Ext.draw.Component.superclass.onDestroy.call(this);
}
});
Ext.reg('draw', Ext.draw.Component);
/**
* @class Ext.chart.Shape
* @ignore
*/
Ext.ns('Ext.chart');
Ext.chart.Shape = {
image: function (surface, opts) {
opts.height = opts.height || 16;
opts.width = opts.width || 16;
return surface.add(Ext.applyIf({
type: 'image',
x: opts.x,
y: opts.y,
height: opts.height,
width: opts.width,
src: opts.src
}, opts));
},
circle: function (surface, opts) {
return surface.add(Ext.apply({
type: 'circle',
x: opts.x,
y: opts.y,
stroke: null,
radius: opts.radius
}, opts));
},
line: function (surface, opts) {
return surface.add(Ext.apply({
type: 'rect',
x: opts.x - opts.radius,
y: opts.y - opts.radius,
height: 2 * opts.radius,
width: 2 * opts.radius / 5
}, opts));
},
square: function (surface, opts) {
return surface.add(Ext.applyIf({
type: 'rect',
x: opts.x - opts.radius,
y: opts.y - opts.radius,
height: 2 * opts.radius,
width: 2 * opts.radius,
radius: null
}, opts));
},
triangle: function (surface, opts) {
opts.radius *= 1.75;
return surface.add(Ext.apply({
type: 'path',
stroke: null,
path: "M".concat(opts.x, ",", opts.y, "m0-", opts.radius * 0.58, "l", opts.radius * 0.5, ",", opts.radius * 0.87, "-", opts.radius, ",0z")
}, opts));
},
diamond: function (surface, opts) {
var r = opts.radius;
r *= 1.5;
return surface.add(Ext.apply({
type: 'path',
stroke: null,
path: ["M", opts.x, opts.y - r, "l", r, r, -r, r, -r, -r, r, -r, "z"]
}, opts));
},
cross: function (surface, opts) {
var r = opts.radius;
r = r / 1.7;
return surface.add(Ext.apply({
type: 'path',
stroke: null,
path: "M".concat(opts.x - r, ",", opts.y, "l", [-r, -r, r, -r, r, r, r, -r, r, r, -r, r, r, r, -r, r, -r, -r, -r, r, -r, -r, "z"])
}, opts));
},
plus: function (surface, opts) {
var r = opts.radius / 1.3;
return surface.add(Ext.apply({
type: 'path',
stroke: null,
path: "M".concat(opts.x - r / 2, ",", opts.y - r / 2, "l", [0, -r, r, 0, 0, r, r, 0, 0, r, -r, 0, 0, r, -r, 0, 0, -r, -r, 0, 0, -r, "z"])
}, opts));
},
arrow: function (surface, opts) {
var r = opts.radius;
return surface.add(Ext.apply({
type: 'path',
path: "M".concat(opts.x - r * 0.7, ",", opts.y - r * 0.4, "l", [r * 0.6, 0, 0, -r * 0.4, r, r * 0.8, -r, r * 0.8, 0, -r * 0.4, -r * 0.6, 0], "z")
}, opts));
},
drop: function (surface, x, y, text, size, angle) {
size = size || 30;
angle = angle || 0;
surface.add({
type: 'path',
path: ['M', x, y, 'l', size, 0, 'A', size * 0.4, size * 0.4, 0, 1, 0, x + size * 0.7, y - size * 0.7, 'z'],
fill: '#000',
stroke: 'none',
rotate: {
degrees: 22.5 - angle,
x: x,
y: y
}
});
angle = (angle + 90) * Math.PI / 180;
surface.add({
type: 'text',
x: x + size * Math.sin(angle) - 10, // Shift here, Not sure why.
y: y + size * Math.cos(angle) + 5,
text: text,
'font-size': size * 12 / 40,
stroke: 'none',
fill: '#fff'
});
}
};
/**
* @class Ext.chart.Toolbar
* @extends Ext.Container
*
* The chart toolbar is a container that is docked to one side of the chart, that is intended
* to hold buttons for performing user actions without taking up valuable screen real estate
* from the chart. This is used internally for things like the button for showing the legend
* when the legend is {@link Ext.chart.Legend#dock docked}, or the
* {@link Ext.chart.interactions.PanZoom pan/zoom interaction}'s button for switching between
* pan and zoom mode in non-multi-touch environments.
*
* An instance of this class is created automatically by the chart when it is needed; authors
* should not need to instantiate it directly. To customize the configuration of the toolbar,
* specify the chart's {@link Ext.chart.Chart#toolbar toolbar} config.
*
* @author Jason Johnston <jason@sencha.com>
* @docauthor Jason Johnston <jason@sencha.com>
*/
Ext.chart.Toolbar = Ext.extend(Ext.Container, {
isChartToolbar: true,
defaultType: 'button',
baseCls: Ext.baseCSSPrefix + 'chart-toolbar',
/**
* @cfg {String} position
* The position at which the toolbar should be docked in relation to the chart. Can be one of:
*
* - "top" - positions the legend centered at the top of the chart
* - "bottom" - positions the legend centered at the bottom of the chart
* - "left" - positions the legend centered on the left side of the chart
* - "right" - positions the legend centered on the right side of the chart
*
* toolbar: {
* position: 'right'
* }
*
* In addition, you can specify different positionss based on the orientation of the browser viewport,
* for instance you might want to put the toolbar on the right in landscape orientation but on the bottom in
* portrait orientation. To achieve this, you can set the `position` config to an Object with `portrait` and
* `landscape` properties, and set the value of those properties to one of the recognized value types described
* above. For example, the following config will put the toolbar on the right in landscape and on the bottom
* in portrait:
*
* toolbar:
* position: {
* landscape: 'right',
* portrait: 'bottom'
* }
* }
*
* If not specified, the position will default to the configured position of the chart legend (if
* a legend is configured), or 'bottom' otherwise.
*/
/**
* Returns whether the toolbar is configured with orientation-specific positions.
* @return {Boolean}
*/
isOrientationSpecific: function() {
var position = this.position;
return (position && Ext.isObject(position) && 'portrait' in position);
},
/**
* Get the target position of the toolbar, after resolving any orientation-specific configs.
* In most cases this method should be used rather than reading the `position` property directly.
* @return {String} The position config value
*/
getPosition: function() {
var me = this,
position = me.position,
legend = me.chart.legend;
if (!position && legend) {
// Fall back to legend position if legend is present
position = legend.getPosition();
}
else if (me.isOrientationSpecific()) {
// Grab orientation-specific config if specified
position = position[Ext.getOrientation()];
}
if (!position || !Ext.isString(position)) {
// Catchall fallback
position = 'bottom';
}
return position;
},
/**
* @protected
* Updates the toolbar to match the current viewport orientation.
*/
orient: function() {
var me = this,
orientation = Ext.getOrientation();
if (!me.rendered) {
me.render(me.chart.el);
}
if (orientation !== me.lastOrientation) {
me.el.dom.setAttribute('data-side', me.getPosition());
me.lastOrientation = orientation;
}
}
});
/**
* @class Ext.chart.Legend
*
* Defines a legend for a chart's series.
* The 'chart' member must be set prior to rendering.
* The legend class displays a list of legend items each of them related with a
* series being rendered. In order to render the legend item of the proper series
* the series configuration object must have {@link Ext.chart.Series#showInLegend showInLegend}
* set to true.
*
* The legend configuration object accepts a {@link #position} as parameter, which allows
* control over where the legend appears in relation to the chart. The position can be
* confiured with different values for portrait vs. landscape orientations. Also, the {@link #dock}
* config can be used to hide the legend in a sheet docked to one of the sides.
*
* Full example:
<pre><code>
var store = new Ext.data.JsonStore({
fields: ['name', 'data1', 'data2', 'data3', 'data4', 'data5'],
data: [
{'name':'metric one', 'data1':10, 'data2':12, 'data3':14, 'data4':8, 'data5':13},
{'name':'metric two', 'data1':7, 'data2':8, 'data3':16, 'data4':10, 'data5':3},
{'name':'metric three', 'data1':5, 'data2':2, 'data3':14, 'data4':12, 'data5':7},
{'name':'metric four', 'data1':2, 'data2':14, 'data3':6, 'data4':1, 'data5':23},
{'name':'metric five', 'data1':27, 'data2':38, 'data3':36, 'data4':13, 'data5':33}
]
});
new Ext.chart.Chart({
renderTo: Ext.getBody(),
width: 500,
height: 300,
animate: true,
store: store,
shadow: true,
theme: 'Category1',
legend: {
position: 'top'
},
axes: [{
type: 'Numeric',
grid: true,
position: 'left',
fields: ['data1', 'data2', 'data3', 'data4', 'data5'],
title: 'Sample Values',
grid: {
odd: {
opacity: 1,
fill: '#ddd',
stroke: '#bbb',
'stroke-width': 1
}
},
minimum: 0,
adjustMinimumByMajorUnit: 0
}, {
type: 'Category',
position: 'bottom',
fields: ['name'],
title: 'Sample Metrics',
grid: true,
label: {
rotate: {
degrees: 315
}
}
}],
series: [{
type: 'area',
highlight: false,
axis: 'left',
xField: 'name',
yField: ['data1', 'data2', 'data3', 'data4', 'data5'],
style: {
opacity: 0.93
}
}]
});
</code></pre>
*
* @constructor
*/
Ext.chart.Legend = Ext.extend(Ext.util.Observable, {
/**
* @cfg {Boolean} visible
* Whether or not the legend should be displayed.
*/
visible: true,
/**
* @cfg {String} position
* The position of the legend in relation to the chart. Can be one of:
*
* - "top" - positions the legend centered at the top of the chart
* - "bottom" - positions the legend centered at the bottom of the chart
* - "left" - positions the legend centered on the left side of the chart
* - "right" - positions the legend centered on the right side of the chart
* - an Object with numeric properties `x` and `y`, and boolean property `vertical` - displays the legend
* floating on top of the chart at the given x/y coordinates. If `vertical:true` the legend items will
* be arranged stacked vertically, otherwise they will be arranged side-by-side. If {@link #dock} is
* set to `true` then this position config will be ignored and will dock to the bottom.
*
* In addition, you can specify different legend alignments based on the orientation of the browser viewport,
* for instance you might want to put the legend on the right in landscape orientation but on the bottom in
* portrait orientation. To achieve this, you can set the `position` config to an Object with `portrait` and
* `landscape` properties, and set the value of those properties to one of the recognized value types described
* above. For example, the following config will put the legend on the right in landscape but float it on top
* of the chart at position 10,10 in portrait:
*
* legend: {
* position: {
* landscape: 'right',
* portrait: {
* x: 10,
* y: 10,
* vertical: true
* }
* }
* }
*/
position: 'bottom',
/**
* @cfg {Boolean} dock
* If set to `true`, then rather than rendering within the chart area the legend will be docked to the
* {@link #position configured edge position} within a {@link Ext.Sheet}. The sheet will be initially
* hidden and can be opened by tapping on a tab along the configured edge. This prevents screen real
* estate from being taken up by the legend, which is especially important on small screen devices.
*
* Defaults to `true` for phone-sized screens, `false` for larger screens.
*/
dock: Ext.is.Phone,
/**
* @cfg {Number} doubleTapThreshold
* The duration in milliseconds in which two consecutive taps will be considered a doubletap.
* Defaults to `250`.
*/
doubleTapThreshold: 250,
/**
* @constructor
* @param {Object} config
*/
constructor: function(config) {
var me = this,
chart = config.chart,
chartEl = chart.el,
button, sheet, view, transitions, sheetAnim;
me.addEvents(
/**
* @event combine
* Fired when two legend items are combined together via drag-drop.
* @param {Ext.chart.Legend} legend
* @param {Ext.chart.series.Series} series The series owning the items being combined
* @param {Number} index1 The index of the first legend item
* @param {Number} index2 The index of the second legend item
*/
'combine',
/**
* @event split
* Fired when a previously-combined legend item is split into its original constituent items.
* @param {Ext.chart.Legend} legend
* @param {Ext.chart.series.Series} series The series owning the item being split
* @param {Number} index The index of the legend item being split
*/
'split'
);
Ext.chart.Legend.superclass.constructor.call(me, config);
view = me.getView();
if (me.dock) {
// Legend is docked; create the sheet and trigger button
button = me.button = chart.getToolbar().add({
showAnimation: 'fade',
cls: Ext.baseCSSPrefix + 'legend-button',
iconCls: Ext.baseCSSPrefix + 'legend-button-icon',
iconMask: true,
handler: function() {
me.sheet.show();
}
});
button.show();
transitions = {
bottom : 'up',
top : 'down',
right : 'left',
left : 'right'
};
sheetAnim = {
type: 'slide',
duration: 150,
direction: transitions[me.getPosition()]
};
sheet = me.sheet = new Ext.Sheet({
enter: me.getPosition(),
stretchY: true,
stretchX: true,
ui: 'legend',
hideOnMaskTap: true,
enterAnimation: sheetAnim,
exitAnimation: sheetAnim,
width: 200,
height: 260,
renderTo: chartEl,
layout: 'fit',
items: view,
listeners: {
// If user swipes in direction sheet came from, close it
// Only works for side-positioned labels (otherwise could just be scrolling legend list)
swipe: {
element: 'el',
fn: function(gesture){
if (gesture.direction == me.getPosition()) {
me.sheet.hide();
}
}
}
}
});
} else {
// Not docked; render view directly into chart container
view.render(chartEl);
}
if (me.isDisplayed()) {
me.show();
}
},
/**
* Retrieves the view component for this legend, creating it first if needed.
* @return {@link Ext.chart.Legend.View}
*/
getView: function() {
var me = this;
return me.view || (me.view = new Ext.chart.Legend.View({
legend: me,
floating: !me.dock
}));
},
/**
* @private Determine whether the legend should be displayed. Looks at the legend's 'visible' config,
* and also the 'showInLegend' config for each of the series.
* @return {Boolean}
*/
isDisplayed: function() {
return this.visible && this.chart.series.findIndex('showInLegend', true) !== -1;
},
/**
* Returns whether the legend is configured with orientation-specific positions.
* @return {Boolean}
*/
isOrientationSpecific: function() {
var position = this.position;
return (Ext.isObject(position) && 'portrait' in position);
},
/**
* Get the target position of the legend, after resolving any orientation-specific configs.
* In most cases this method should be used rather than reading the `position` property directly.
* @return {String/Object} The position config value
*/
getPosition: function() {
var me = this,
position = me.position;
// Grab orientation-specific config if specified
if (me.isOrientationSpecific()) {
position = position[Ext.getOrientation()];
}
// If legend is docked, default non-String values to 'bottom'
if (me.dock && !Ext.isString(position)) {
position = 'bottom';
}
return position;
},
/**
* Returns whether the orientation of the legend items is vertical.
* @return {Boolean} `true` if the legend items are to be arranged stacked vertically, `false` if they
* are to be arranged side-by-side.
*/
isVertical: function() {
var position = this.getPosition();
return this.dock || (Ext.isObject(position) ? position.vertical : "left|right|float".indexOf('' + position) !== -1);
},
/**
* Update the legend component to match the current viewport orientation.
*/
orient: function() {
var me = this,
sheet = me.sheet,
position = me.getPosition(),
orientation = Ext.getOrientation(),
auto = 'auto';
me.getView().orient();
if (me.lastOrientation !== orientation) {
if (sheet) {
sheet.hide();
sheet.enter = sheet.exit = position;
sheet.setSize(null, null);
sheet.orient();
}
me.lastOrientation = orientation;
}
},
/**
* @private Update the position of the legend if it is displayed and not docked.
*/
updatePosition: function() {
if (!this.dock) {
var me = this,
chart = me.chart,
chartBBox = chart.chartBBox,
insets = chart.insetPadding,
isObject = Ext.isObject(insets),
insetLeft = (isObject ? insets.left : insets) || 0,
insetRight = (isObject ? insets.right : insets) || 0,
insetBottom = (isObject ? insets.bottom : insets) || 0,
insetTop = (isObject ? insets.top : insets) || 0,
chartWidth = chart.curWidth,
chartHeight = chart.curHeight,
seriesWidth = chartBBox.width - (insetLeft + insetRight),
seriesHeight = chartBBox.height - (insetTop + insetBottom),
chartX = chartBBox.x + insetLeft,
chartY = chartBBox.y + insetTop,
isVertical = me.isVertical(),
view = me.getView(),
math = Math,
mfloor = math.floor,
mmin = math.min,
mmax = math.max,
x, y, legendWidth, legendHeight, maxWidth, maxHeight, position, undef;
if (me.sheet) {
return; //only set position if view is directly floated
}
if (me.isDisplayed()) {
// Calculate the natural size
view.show();
view.setCalculatedSize(isVertical ? undef : null, isVertical ? null : undef); //clear fixed scroller length
legendWidth = view.getWidth();
legendHeight = view.getHeight();
position = me.getPosition();
if (Ext.isObject(position)) {
// Object with x/y properties: use them directly
x = position.x;
y = position.y;
} else {
// Named positions - calculate x/y based on chart dimensions
switch(position) {
case "left":
x = insetLeft;
y = mfloor(chartY + seriesHeight / 2 - legendHeight / 2);
break;
case "right":
x = mfloor(chartWidth - legendWidth) - insetRight;
y = mfloor(chartY + seriesHeight / 2 - legendHeight / 2);
break;
case "top":
x = mfloor(chartX + seriesWidth / 2 - legendWidth / 2);
y = insetTop;
break;
default:
x = mfloor(chartX + seriesWidth / 2 - legendWidth / 2);
y = mfloor(chartHeight - legendHeight) - insetBottom;
}
x = mmax(x, insetLeft);
y = mmax(y, insetTop);
}
maxWidth = chartWidth - x - insetRight;
maxHeight = chartHeight - y - insetBottom;
view.setPosition(x, y);
if (legendWidth > maxWidth || legendHeight > maxHeight) {
view.setCalculatedSize(mmin(legendWidth, maxWidth), mmin(legendHeight, maxHeight));
}
} else {
view.hide();
}
}
},
/**
* Calculate and return the number of pixels that should be reserved for the legend along
* its edge. Only returns a non-zero value if the legend is positioned to one of the four
* named edges, and if it is not {@link #dock docked}.
*/
getInsetSize: function() {
var me = this,
pos = me.getPosition(),
chartPadding = me.chart.insets,
left = chartPadding.left,
bottom = chartPadding.bottom,
top = chartPadding.top,
right = chartPadding.right,
size = 0,
view;
if (!me.dock && me.isDisplayed()) {
view = me.getView();
view.show();
if (pos === 'left' || pos === 'right') {
size = view.getWidth() + left;
}
else if (pos === 'top' || pos === 'bottom') {
size = view.getHeight() + top;
}
}
return size;
},
/**
* Shows the legend if it is currently hidden.
*/
show: function() {
(this.sheet || this.getView()).show();
},
/**
* Hides the legend if it is currently shown.
*/
hide: function() {
(this.sheet || this.getView()).hide();
},
/**
* @protected Fired when two legend items are combined via drag-drop in the legend view.
* @param {Ext.chart.series.Series} series The series for the combined items
* @param {Ext.chart.series.Series} index1 The series for the combined items
* @param {Ext.chart.series.Series} index2 The series for the combined items
*/
onCombine: function(series, index1, index2) {
var me = this;
series.combine(index1, index2);
me.getView().updateStore();
me.fireEvent('combine', me, series, index1, index2);
},
onSplit: function(series, index) {
var me = this;
series.split(index);
me.getView().updateStore();
me.fireEvent('split', me, series, index);
},
/**
* Reset the legend back to its initial state before any user interactions.
*/
reset: function() {
this.getView().reset();
}
});
/**
* @class Ext.chart.Legend.View
* @extends Ext.DataView
*
* A DataView specialized for displaying the legend items for a chart. This class is only
* used internally by {@link Ext.chart.Legend} and should not need to be instantiated directly.
*/
Ext.chart.Legend.View = Ext.extend(Ext.DataView, {
tpl: [
'<ul class="' + Ext.baseCSSPrefix + 'legend-items">',
'<tpl for=".">',
'<li class="' + Ext.baseCSSPrefix + 'legend-item <tpl if="disabled">' + Ext.baseCSSPrefix + 'legend-inactive' + '</tpl>">',
'<span class="' + Ext.baseCSSPrefix + 'legend-item-marker" style="background-color:{markerColor};"></span>{label}',
'</li>',
'</tpl>',
'</ul>'
],
disableSelection: true,
componentCls: Ext.baseCSSPrefix + 'legend',
horizontalCls: Ext.baseCSSPrefix + 'legend-horizontal',
inactiveItemCls: Ext.baseCSSPrefix + 'legend-inactive',
itemSelector: '.' + Ext.baseCSSPrefix + 'legend-item',
hideOnMaskTap: false,
triggerEvent: 'tap',
initComponent: function() {
var me = this;
me.createStore();
Ext.chart.Legend.View.superclass.initComponent.call(me);
me.on('refresh', me.updateDroppables, me);
},
initEvents: function() {
var me = this;
Ext.chart.Legend.View.superclass.initEvents.call(me);
me.el.on('taphold', me.onTapHold, me, {delegate: me.itemSelector});
},
/**
* @private Fired when a legend item is tap-held. Initializes a draggable for the
* held item.
*/
onTapHold: function(e, target) {
var me = this,
draggable, record, seriesId, combinable;
if (!Ext.fly(target).hasCls(me.inactiveItemCls)) {
record = me.getRecord(target);
seriesId = record.get('seriesId');
combinable = me.store.findBy(function(record2) {
return record2 !== record && record2.get('seriesId') === seriesId;
});
if (combinable > -1) {
draggable = new Ext.util.Draggable(target, {
threshold: 0,
revert: true,
direction: me.legend.isVertical() ? 'vertical' : 'horizontal',
group: seriesId
});
draggable.on('dragend', me.onDragEnd, me);
if (!draggable.dragging) {
draggable.onStart(e);
}
}
}
},
/**
* @private Updates the droppable objects for each list item. Should be called whenever
* the list view is re-rendered.
*/
updateDroppables: function() {
var me = this,
droppables = me.droppables,
droppable;
Ext.destroy(droppables);
droppables = me.droppables = [];
me.store.each(function(record) {
droppable = new Ext.chart.Legend.Droppable(me.getNode(record), {
group: record.get('seriesId'),
disabled: record.get('disabled')
});
droppable.on('drop', me.onDrop, me);
droppables.push(droppable);
});
},
/**
* @private Handles dropping one legend item on another.
*/
onDrop: function(droppable, draggable) {
var me = this,
dragRecord = me.getRecord(draggable.el.dom),
dropRecord = me.getRecord(droppable.el.dom);
me.legend.onCombine(dragRecord.get('series'), dragRecord.get('index'), dropRecord.get('index'));
},
onDragEnd : function(draggable, e) {
draggable.destroy();
},
/**
* @private Create the internal data store for the view
*/
createStore: function() {
var me = this;
me.store = new Ext.data.Store({
fields: ['markerColor', 'label', 'series', 'seriesId', 'index', 'disabled'],
data: me.getStoreData()
});
me.legend.chart.series.each(function(series) {
series.on('titlechange', me.updateStore, me);
});
},
/**
* @private Create and return the JSON data for the legend's internal data store
*/
getStoreData: function() {
var data = [];
this.legend.chart.series.each(function(series) {
if (series.showInLegend) {
Ext.each(series.getLegendLabels(), function(label, i) {
data.push({
label: label,
markerColor: series.getLegendColor(i),
series: series,
seriesId: Ext.id(series, 'legend-series-'),
index: i,
disabled: !series.visibleInLegend(i)
});
});
}
});
return data;
},
/**
* Updates the internal store to match the current legend info supplied by all the series.
*/
updateStore: function() {
var store = this.store;
store.suspendEvents(true);
store.removeAll();
store.add(this.getStoreData());
store.resumeEvents();
},
/**
* Update the legend component to match its current vertical/horizontal orientation
*/
orient: function() {
var me = this,
legend = me.legend,
horizontalCls = me.horizontalCls,
isVertical = legend.isVertical(),
orientation = Ext.getOrientation();
if (isVertical) {
me.removeCls(horizontalCls);
} else {
me.addCls(horizontalCls);
}
if (me.lastOrientation !== orientation) {
me.setCalculatedSize(null, null);
// Clean up things set by previous scroller -- Component#setScrollable should be fixed to do this
me.scrollEl.setStyle({
width: '',
height: '',
minWidth: '',
minHeight: ''
});
Ext.iterate(me.scroller.scrollView.indicators, function(axis, indicator) {
clearTimeout(indicator.hideTimer);
Ext.destroy(indicator.el);
delete indicator.el;
}, this);
me.scroller.destroy();
// Re-init scrolling in the correct direction
me.setScrollable(isVertical ? 'vertical' : 'horizontal');
if (isVertical) {
// Fix to the initial natural width so it doesn't expand when items are combined
me.setCalculatedSize(me.getWidth());
}
if (me.scroller) {
me.scroller.scrollTo({x: 0, y: 0});
}
me.lastOrientation = orientation;
}
},
afterComponentLayout: function() {
var me = this,
scroller = me.scroller,
innerSize, outerSize;
Ext.chart.Legend.View.superclass.afterComponentLayout.apply(me, arguments);
// Enable or disable scrolling depending on if the legend needs to be scrollable
if (scroller) {
innerSize = scroller.size;
outerSize = scroller.containerBox;
if (innerSize.width > outerSize.width || innerSize.height > outerSize.height) {
scroller.enable();
} else {
scroller.disable();
}
}
},
refresh: function() {
Ext.chart.Legend.View.superclass.refresh.apply(this, arguments);
// Refresh may decrease the size of the scrollable content; we need to clear minWidth/Height
// on the scrollEl so it doesn't force the floated view el to keep its old size.
this.scrollEl.setStyle({
minWidth: '',
minHeight: ''
});
},
onItemTap: function(item, i, e) {
Ext.chart.Legend.View.superclass.onItemTap.apply(this, arguments);
var me = this,
record = me.store.getAt(i),
series = record.get('series'),
index = record.get('index'),
threshold = me.legend.doubleTapThreshold,
tapTask = me.tapTask || (me.tapTask = new Ext.util.DelayedTask()),
now = +new Date();
tapTask.cancel();
// If the tapped item is a combined item, we need to distinguish between single and
// double taps by waiting a bit; otherwise trigger the single tap handler immediately.
if (series.isCombinedItem(index)) {
if (now - (me.lastTapTime || 0) < threshold) {
me.doItemDoubleTap(item, i);
}
else {
tapTask.delay(threshold, me.doItemTap, me, [item, i]);
}
me.lastTapTime = now;
} else {
me.doItemTap(item, i);
}
},
/**
* @private
* Handle single taps on legend items; toggles the corresponding series items on and off.
*/
doItemTap: function(item, i) {
var me = this,
record = me.store.getAt(i),
series = record.get('series'),
index = record.get('index'),
active = series.visibleInLegend(index),
droppable = me.droppables[i],
inactiveCls = me.inactiveItemCls;
// Set the _index property on the series, this is used by the hideAll and
// showAll methods for some series to know which legend item to hide/show.
// This would be cleaner if it were just a passed argument.
series._index = index;
if (active) {
series.hideAll();
Ext.fly(item).addCls(inactiveCls);
droppable.disable();
} else {
series.showAll();
Ext.fly(item).removeCls(inactiveCls);
droppable.enable();
}
// Flush rendering of affected surfaces
series.getSurface().renderFrame();
series.getOverlaySurface().renderFrame();
me.legend.chart.axes.each(function(axis) {
axis.renderFrame();
});
},
/**
* @private
* Handle double-taps on legend items; splits items that are a result of item combination
*/
doItemDoubleTap: function(item, i) {
var me = this,
record = me.getRecord(item);
if (record) {
me.legend.onSplit(record.get('series'), record.get('index'));
}
},
/**
* Reset the legend view back to its initial state before any user interactions.
*/
reset: function() {
var me = this;
me.store.each(function(record) {
var series = record.get('series');
series._index = record.get('index');
series.showAll();
Ext.fly(me.getNode(record)).removeCls(me.inactiveItemCls);
series.clearCombinations();
});
me.updateStore();
}
});
/**
* @private
* @class Ext.chart.Legend.Droppable
* @extends Ext.util.Droppable
* Custom Droppable implementation for legend items. Only lets one legend item be active as a
* drop target at once, using the center point of the draggable.
*/
Ext.chart.Legend.Droppable = Ext.extend(Ext.util.Droppable, {
isDragOver : function(draggable) {
var draggableRegion = draggable.region,
round = Math.round,
draggableCenter = {
x: round((draggableRegion.right - draggableRegion.left) / 2 + draggableRegion.left) + 0.5,
y: round((draggableRegion.bottom - draggableRegion.top) / 2 + draggableRegion.top) + 0.5
};
return draggable.el !== this.el && !this.region.isOutOfBound(draggableCenter);
}
});
/**
* @class Ext.chart.theme.Theme
* @ignore
*/
Ext.ns('Ext.chart.theme');
//TODO(nico): I'm pretty sure this shouldn't be here.
Ext.ComponentQuery.pseudos['nth-child'] = function(items, value) {
var index = +value -1;
if (items[index]) {
return [items[index]];
}
return [];
};
Ext.ComponentQuery.pseudos.highlight = function(items, value) {
var i = 0,
j = 0,
l = items.length,
ans = [],
item, refItems, refItem, lRefItems;
for (; i < l; ++i) {
item = items[i];
if (item.isXType && item.isXType('highlight')) {
ans.push(item);
}
if (item.getRefItems) {
refItems = item.getRefItems(true);
for (j = 0, lRefItems = refItems.length; j < lRefItems; ++j) {
refItem = refItems[j];
if (refItem.isXType && refItem.isXType('highlight')) {
ans.push(refItem);
}
}
}
}
return ans;
};
Ext.chart.theme.Theme = Ext.extend(Object, {
theme: 'Base',
themeInitialized: false,
applyStyles: function(themeName) {
if (this.themeInitialized) {
return;
}
//http://www.w3.org/TR/css3-selectors/#specificity.
var me = this,
root = {
getRefItems: function() {
return [me];
},
isXType: function() {
return false;
},
initCls: function() {
return [];
},
getItemId: function() {
return '';
}
},
themes = [Ext.chart.theme.Base.slice()],
i = 0,
n = 0,
results = [],
res, selector, style, rule, j, matches, lmatches, ln, l, configs;
if (themeName || me.theme != 'Base') {
themes.push(Ext.chart.theme[themeName || me.theme].slice());
}
for (ln = themes.length; n < ln; ++n) {
configs = themes[n];
l = configs.length;
//sort by specificity
configs.sort(function(a, b) {
var sa = a.specificity,
sb = b.specificity;
return sb[0] < sa[0] || (sb[0] == sa[0] && sb[1] < sa[1])
|| (sb[0] == sa[0] && sb[1] == sa[1] && sb[2] < sa[2]);
});
for (i = 0; i < l; ++i) {
rule = configs[i];
selector = rule.selector;
style = rule.style;
matches = Ext.ComponentQuery.query(selector, root);
results.push.apply(results, matches);
for (j = 0, lmatches = matches.length; j < lmatches; ++j) {
matches[j].themeStyle = Ext.apply(matches[j].themeStyle || {}, style);
}
}
}
//Now get all themable elements and apply the themed styles to their style objects.
//This way we can get the resulting cascaded style `themeStyle` (calculated above) and apply it to the
//`style` property without overriding the options made by the user.
for (j = 0, lmatches = results.length; j < lmatches; ++j) {
res = results[j];
res.style = Ext.applyIf(res.style || {}, res.themeStyle || {});
}
me.themeInitialized = true;
}
});
;Ext.chart.theme.Base = [
{
"selector": "chart",
"style": {
"padding": 10,
"colors": [
"#115fa6",
"#94ae0a",
"#a61120",
"#ff8809",
"#ffd13e",
"#a61187",
"#24ad9a",
"#7c7474",
"#a66111"
]
},
"specificity": [
0,
0,
1
]
},
{
"selector": "chart axis",
"style": {
"color": "#354f6e",
"fill": "#354f6e",
"stroke": "#cccccc",
"stroke-width": 1
},
"specificity": [
0,
0,
2
]
},
{
"selector": "chart axis label",
"style": {
"color": "#354f6e",
"fill": "#354f6e",
"font": "12px Helvetica, Arial, sans-serif",
"font-weight": "bold",
"spacing": 2,
"padding": 5
},
"specificity": [
0,
0,
3
]
},
{
"selector": "chart axis title",
"style": {
"font": "18px Helvetica, Arial, sans-serif",
"color": "#354f6e",
"fill": "#354f6e",
"padding": 5
},
"specificity": [
0,
0,
3
]
},
{
"selector": "chart axis[position=\"left\"] title",
"style": {
"rotate": {
"x": 0,
"y": 0,
"degrees": 270
}
},
"specificity": [
0,
1,
3
]
},
{
"selector": "chart axis[position=\"right\"] title",
"style": {
"rotate": {
"x": 0,
"y": 0,
"degrees": 270
}
},
"specificity": [
0,
1,
3
]
},
{
"selector": "chart axis[position=\"radial\"]",
"style": {
"fill": "none"
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart axis[position=\"radial\"] label",
"style": {
"font": "10px Helvetica, Arial, sans-serif",
"text-anchor": "middle"
},
"specificity": [
0,
1,
3
]
},
{
"selector": "chart axis[position=\"gauge\"]",
"style": {
"fill": "none"
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart axis[position=\"gauge\"] label",
"style": {
"font": "10px Helvetica, Arial, sans-serif",
"text-anchor": "middle"
},
"specificity": [
0,
1,
3
]
},
{
"selector": "chart series",
"style": {
"stroke-width": 1
},
"specificity": [
0,
0,
2
]
},
{
"selector": "chart series label",
"style": {
"font": "12px Helvetica, Arial, sans-serif",
"fill": "#333333",
"display": "none",
"field": "name",
"minMargin": "50",
"orientation": "horizontal"
},
"specificity": [
0,
0,
3
]
},
{
"selector": "chart series:nth-child(1)",
"style": {
"fill": "#115fa6"
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart series:nth-child(2)",
"style": {
"fill": "#94ae0a"
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart series:nth-child(3)",
"style": {
"fill": "#a61120"
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart series:nth-child(4)",
"style": {
"fill": "#ff8809"
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart series:nth-child(5)",
"style": {
"fill": "#ffd13e"
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart series:nth-child(6)",
"style": {
"fill": "#a61187"
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart series:nth-child(7)",
"style": {
"fill": "#24ad9a"
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart series:nth-child(8)",
"style": {
"fill": "#7c7474"
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart series:nth-child(9)",
"style": {
"fill": "#a66111"
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart series:highlight",
"style": {
"radius": 20,
"stroke-width": 5,
"stroke": "#ff5555"
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart series[type=\"line\"]:highlight",
"style": {
"stroke-width": 3
},
"specificity": [
0,
2,
2
]
},
{
"selector": "chart series[type=\"bar\"]:highlight",
"style": {
"stroke-width": 3,
"stroke": "#5555cc",
"opacity": 0.8
},
"specificity": [
0,
2,
2
]
},
{
"selector": "chart series[type=\"area\"]:highlight",
"style": {
"stroke-width": 3,
"stroke": "#111111"
},
"specificity": [
0,
2,
2
]
},
{
"selector": "chart series[type=\"pie\"]:highlight",
"style": {
"stroke": "none",
"stroke-width": 0
},
"specificity": [
0,
2,
2
]
},
{
"selector": "chart series[type=\"scatter\"]:highlight",
"style": {
"stroke": "none",
"stroke-width": 0
},
"specificity": [
0,
2,
2
]
},
{
"selector": "chart marker",
"style": {
"stroke": "#ffffff",
"stroke-width": 1,
"type": "circle",
"fill": "#000000",
"radius": 5,
"size": 5
},
"specificity": [
0,
0,
2
]
},
{
"selector": "chart marker:nth-child(1)",
"style": {
"fill": "#115fa6",
"type": "circle"
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart marker:nth-child(2)",
"style": {
"fill": "#94ae0a"
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart marker:nth-child(3)",
"style": {
"fill": "#a61120"
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart marker:nth-child(3)",
"style": {
"fill": "#a61120"
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart marker:nth-child(4)",
"style": {
"fill": "#ff8809"
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart marker:nth-child(5)",
"style": {
"fill": "#ffd13e"
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart marker:nth-child(6)",
"style": {
"fill": "#a61187"
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart marker:nth-child(7)",
"style": {
"fill": "#24ad9a"
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart marker:nth-child(8)",
"style": {
"fill": "#7c7474"
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart marker:nth-child(9)",
"style": {
"fill": "#a66111"
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart interaction[type=\"itemcompare\"] circle",
"style": {
"fill": "rgba(0, 0, 0, 0)",
"stroke": "#0d75f2",
"radius": 5
},
"specificity": [
0,
1,
3
]
},
{
"selector": "chart interaction[type=\"itemcompare\"] line",
"style": {
"stroke": "#0d75f2",
"stroke-width": 3
},
"specificity": [
0,
1,
3
]
},
{
"selector": "chart interaction[type=\"itemcompare\"] arrow",
"style": {
"fill": "#0d75f2",
"radius": 8
},
"specificity": [
0,
1,
3
]
},
{
"selector": "chart interaction[type=\"piegrouping\"] slice",
"style": {
"stroke": "#0d75f2",
"stroke-width": 2,
"fill": "#0d75f2",
"opacity": 0.5
},
"specificity": [
0,
1,
3
]
},
{
"selector": "chart interaction[type=\"piegrouping\"] handle",
"style": {
"stroke": "#0d75f2",
"stroke-width": 2,
"fill": "#0d75f2"
},
"specificity": [
0,
1,
3
]
}
];;Ext.chart.theme.Demo = [
{
"selector": "chart[cls=\"area1\"] axis[position=\"left\"] grid even",
"style": {
"opacity": 1,
"fill": "#dddddd",
"stroke": "#bbbbbb",
"stroke-width": 1
},
"specificity": [
0,
2,
4
]
},
{
"selector": "chart[cls=\"area1\"] axis[position=\"bottom\"] label",
"style": {
"rotate": {
"degrees": 45
}
},
"specificity": [
0,
2,
3
]
},
{
"selector": "chart[cls=\"area1\"] series",
"style": {
"opaciy": "0.93"
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart[cls=\"bar1\"] axis[position=\"bottom\"] grid",
"style": {
"stroke": "#cccccc"
},
"specificity": [
0,
2,
3
]
},
{
"selector": "chart[cls=\"column1\"]",
"style": {
"background": "#111111"
},
"specificity": [
0,
1,
1
]
},
{
"selector": "chart[cls=\"column1\"] axis",
"style": {
"stroke": "#eeeeee",
"fill": "#eeeeee"
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart[cls=\"column1\"] axis label",
"style": {
"fill": "#ffffff"
},
"specificity": [
0,
1,
3
]
},
{
"selector": "chart[cls=\"column1\"] axis title",
"style": {
"fill": "#ffffff"
},
"specificity": [
0,
1,
3
]
},
{
"selector": "chart[cls=\"column1\"] axis[position=\"left\"] grid odd",
"style": {
"stroke": "#555555"
},
"specificity": [
0,
2,
4
]
},
{
"selector": "chart[cls=\"column1\"] axis[position=\"left\"] grid even",
"style": {
"stroke": "#555555"
},
"specificity": [
0,
2,
4
]
},
{
"selector": "chart[cls=\"column1\"] series label",
"style": {
"fill": "#ffffff",
"font": "17px Arial",
"display": "insideEnd",
"text-anchor": "middle",
"orientation": "horizontal"
},
"specificity": [
0,
1,
3
]
},
{
"selector": "chart[cls=\"barcombo1\"] axis[position=\"bottom\"] grid",
"style": {
"stroke": "#cccccc"
},
"specificity": [
0,
2,
3
]
},
{
"selector": "chart[cls=\"piecombo1\"]",
"style": {
"padding": 20
},
"specificity": [
0,
1,
1
]
},
{
"selector": "chart[cls=\"piecombo1\"] series label",
"style": {
"display": "rotate",
"contrast": true,
"font": "14px Arial"
},
"specificity": [
0,
1,
3
]
},
{
"selector": "chart[cls=\"gaugecombo1\"]",
"style": {
"padding": 30
},
"specificity": [
0,
1,
1
]
},
{
"selector": "chart[cls=\"gaugecombo1\"] axis",
"style": {
"stroke": "#cccccc"
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart[cls=\"gaugecombo1\"] axis label",
"style": {
"font": "15px Arial"
},
"specificity": [
0,
1,
3
]
},
{
"selector": "chart[cls=\"radarcombo1\"]",
"style": {
"padding": 20
},
"specificity": [
0,
1,
1
]
},
{
"selector": "chart[cls=\"radarcombo1\"] axis",
"style": {
"stroke": "#cccccc",
"fill": "none"
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart[cls=\"radarcombo1\"] axis label",
"style": {
"font": "11px Arial",
"text-anchor": "middle"
},
"specificity": [
0,
1,
3
]
},
{
"selector": "chart[cls=\"radarcombo1\"] series",
"style": {
"opacity": 0.4
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart[cls=\"line1\"] axis[position=\"left\"] grid odd",
"style": {
"opacity": 1,
"fill": "#dddddd",
"stroke": "#bbbbbb",
"stroke-width": 0.5
},
"specificity": [
0,
2,
4
]
},
{
"selector": "chart[cls=\"line1\"] marker",
"style": {
"size": 4,
"radius": 4,
"stroke-width": 0
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart[cls=\"line1\"] series:nth-child(1) marker",
"style": {
"type": "image",
"height": "46",
"width": "46",
"src": "\"../resources/shared/img/iphone.png\""
},
"specificity": [
0,
2,
3
]
},
{
"selector": "chart[cls=\"line1\"] series:nth-child(2) marker",
"style": {
"type": "image",
"height": "46",
"width": "46",
"src": "\"../resources/shared/img/android.png\""
},
"specificity": [
0,
2,
3
]
},
{
"selector": "chart[cls=\"line1\"] series:nth-child(3) marker",
"style": {
"type": "image",
"height": "46",
"width": "46",
"src": "\"../resources/shared/img/ipad.png\""
},
"specificity": [
0,
2,
3
]
},
{
"selector": "chart[cls=\"pie1\"]",
"style": {
"padding": 10
},
"specificity": [
0,
1,
1
]
},
{
"selector": "chart[cls=\"pie1\"] series label",
"style": {
"display": "rotate",
"contrast": true,
"font": "18px Helvetica, Arial, sans-serif"
},
"specificity": [
0,
1,
3
]
},
{
"selector": "chart[cls=\"radar1\"]",
"style": {
"padding": 20
},
"specificity": [
0,
1,
1
]
},
{
"selector": "chart[cls=\"radar1\"] axis",
"style": {
"stroke": "#cccccc",
"fill": "none"
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart[cls=\"radar1\"] axis label",
"style": {
"font": "11px Arial",
"text-anchor": "middle"
},
"specificity": [
0,
1,
3
]
},
{
"selector": "chart[cls=\"radar1\"] series",
"style": {
"opacity": 0.4
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart[cls=\"scatter1\"]",
"style": {
"padding": 40
},
"specificity": [
0,
1,
1
]
},
{
"selector": "chart[cls=\"scatter1\"] axis[position=\"left\"] grid odd",
"style": {
"opacity": 1,
"fill": "#dddddd",
"stroke": "#bbbbbb",
"stroke-width": 0.5
},
"specificity": [
0,
2,
4
]
},
{
"selector": "chart[cls=\"scatter1\"] marker",
"style": {
"size": 8,
"radius": 8
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart[cls=\"stock1\"] axis label",
"style": {
"font": "12px Arial"
},
"specificity": [
0,
1,
3
]
},
{
"selector": "chart[cls=\"stock1\"] axis[position=\"left\"] grid",
"style": {
"stroke": "#cccccc"
},
"specificity": [
0,
2,
3
]
}
];;Ext.chart.theme.Energy = [
{
"selector": "chart",
"style": {
"colors": [
"rgba(17, 95, 166, 0.85)",
"rgba(148, 174, 10, 0.85)",
"rgba(166, 17, 32, 0.85)",
"rgba(255, 136, 9, 0.85)",
"rgba(255, 209, 62, 0.85)",
"rgba(166, 17, 135, 0.85)",
"rgba(36, 173, 154, 0.85)",
"rgba(124, 116, 116, 0.85)",
"rgba(166, 97, 17, 0.85)"
]
},
"specificity": [
0,
0,
1
]
},
{
"selector": "chart series",
"style": {
"stroke-width": 2
},
"specificity": [
0,
0,
2
]
},
{
"selector": "chart series grid odd",
"style": {
"stroke": "#333333"
},
"specificity": [
0,
0,
4
]
},
{
"selector": "chart series grid even",
"style": {
"stroke": "#222222"
},
"specificity": [
0,
0,
4
]
},
{
"selector": "chart axis",
"style": {
"stroke": "#555555",
"fill": "#555555"
},
"specificity": [
0,
0,
2
]
},
{
"selector": "chart axis label",
"style": {
"fill": "#666666"
},
"specificity": [
0,
0,
3
]
},
{
"selector": "chart axis title",
"style": {
"fill": "#cccccc"
},
"specificity": [
0,
0,
3
]
},
{
"selector": "chart axis[position=\"radial\"]",
"style": {
"fill": "none"
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart axis[position=\"radial\"] label",
"style": {
"fill": "#ffffff",
"text-anchor": "center",
"translate": {
"x": 0,
"y": -10
}
},
"specificity": [
0,
1,
3
]
},
{
"selector": "chart[cls=\"radar\"]",
"style": {
"padding": 40
},
"specificity": [
0,
1,
1
]
}
];;Ext.chart.theme.WorldData = [
{
"selector": "chart",
"style": {
"colors": [
"#49080e",
"#49080e",
"#d7a400"
],
"background": "#dbddd8"
},
"specificity": [
0,
0,
1
]
},
{
"selector": "chart series:highlight",
"style": {
"radius": 5,
"stroke-width": 3,
"stroke": "#ffffff"
},
"specificity": [
0,
1,
2
]
},
{
"selector": "chart axis",
"style": {
"stroke": "#c2c4be",
"fill": "#c2c4be"
},
"specificity": [
0,
0,
2
]
},
{
"selector": "chart axis label",
"style": {
"fill": "#909488"
},
"specificity": [
0,
0,
3
]
},
{
"selector": "chart axis title",
"style": {
"fill": "#43453e"
},
"specificity": [
0,
0,
3
]
}
];
/**
* @class Ext.chart.theme.Style
* @ignore
*/
Ext.ns('Ext.chart.theme');
Ext.chart.theme.Style = Ext.extend(Object, {
constructor: function(config) {
this.style = {};
this.themeStyle = {};
Ext.apply(this.style, config);
},
/* ---------------------------------
Methods needed for ComponentQuery
----------------------------------*/
//filled by the constructor.
ownerCt: null,
getItemId: function() {
return this.el && this.el.id || this.id || null;
},
initCls: function() {
return (this.cls || '').split(' ');
},
isXType: function(xtype) {
return xtype === '';
},
getRefItems: function(deep) {
return [];
}
});
/**
* @class Ext.chart.theme.LabelStyle
* @ignore
*
* @xtype label
*/
Ext.ns('Ext.chart.theme');
Ext.chart.theme.LabelStyle = Ext.extend(Ext.chart.theme.Style, {
constructor: function(config) {
Ext.chart.theme.LabelStyle.superclass.constructor.call(this, config);
},
/* ---------------------------------
Methods needed for ComponentQuery
----------------------------------*/
isXType: function(xtype) {
return xtype === 'label';
}
});
/**
* @class Ext.chart.theme.HighlightStyle
* @ignore
*
* @xtype marker
*/
Ext.ns('Ext.chart.theme');
Ext.chart.theme.HighlightStyle = Ext.extend(Ext.chart.theme.Style, {
constructor: function(config) {
Ext.chart.theme.HighlightStyle.superclass.constructor.call(this, config);
this.style = false;
},
/* ---------------------------------
Methods needed for ComponentQuery
----------------------------------*/
isXType: function(xtype) {
return xtype === 'highlight';
},
getRefItems: function(deep) {
return [];
}
});
/**
* @class Ext.chart.theme.MarkerStyle
* @ignore
*
* @xtype marker
*/
Ext.ns('Ext.chart.theme');
Ext.chart.theme.MarkerStyle = Ext.extend(Ext.chart.theme.Style, {
constructor: function(config) {
Ext.chart.theme.MarkerStyle.superclass.constructor.call(this, config);
},
/* ---------------------------------
Methods needed for ComponentQuery
----------------------------------*/
isXType: function(xtype) {
return xtype === 'marker';
}
});
/**
* @class Ext.chart.theme.TitleStyle
* @ignore
*
* @xtype title
*/
Ext.ns('Ext.chart.theme');
Ext.chart.theme.TitleStyle = Ext.extend(Ext.chart.theme.Style, {
constructor: function(config) {
Ext.chart.theme.TitleStyle.superclass.constructor.call(this, config);
},
/* ---------------------------------
Methods needed for ComponentQuery
----------------------------------*/
isXType: function(xtype) {
return xtype === 'title';
}
});
/**
* @class Ext.chart.theme.CalloutStyle
* @ignore
*
* @xtype marker
*/
Ext.ns('Ext.chart.theme');
Ext.chart.theme.CalloutStyle = Ext.extend(Ext.chart.theme.Style, {
constructor: function(config) {
Ext.chart.theme.CalloutStyle.superclass.constructor.call(this, config);
this.style = false;
this.oddStyle = new Ext.chart.theme.OddStyle();
this.evenStyle = new Ext.chart.theme.EvenStyle();
},
/* ---------------------------------
Methods needed for ComponentQuery
----------------------------------*/
isXType: function(xtype) {
return xtype === 'callout';
},
getRefItems: function(deep) {
return [];
}
});
/**
* @class Ext.chart.theme.GridStyle
* @ignore
*
* @xtype marker
*/
Ext.ns('Ext.chart.theme');
Ext.chart.theme.GridStyle = Ext.extend(Ext.chart.theme.Style, {
constructor: function(config) {
Ext.chart.theme.GridStyle.superclass.constructor.call(this, config);
this.style = false;
this.oddStyle = new Ext.chart.theme.OddStyle();
this.evenStyle = new Ext.chart.theme.EvenStyle();
},
/* ---------------------------------
Methods needed for ComponentQuery
----------------------------------*/
isXType: function(xtype) {
return xtype === 'grid';
},
getRefItems: function(deep) {
return [ this.oddStyle, this.evenStyle ];
}
});
/**
* @class Ext.chart.theme.EvenStyle
* @ignore
*
* @xtype even
*/
Ext.ns('Ext.chart.theme');
Ext.chart.theme.EvenStyle = Ext.extend(Ext.chart.theme.Style, {
constructor: function(config) {
Ext.chart.theme.EvenStyle.superclass.constructor.call(this, config);
this.style = false;
},
/* ---------------------------------
Methods needed for ComponentQuery
----------------------------------*/
isXType: function(xtype) {
return xtype === 'even';
}
});
/**
* @class Ext.chart.theme.OddStyle
* @ignore
*
* @xtype odd
*/
Ext.ns('Ext.chart.theme');
Ext.chart.theme.OddStyle = Ext.extend(Ext.chart.theme.Style, {
constructor: function(config) {
Ext.chart.theme.OddStyle.superclass.constructor.call(this, config);
this.style = false;
},
/* ---------------------------------
Methods needed for ComponentQuery
----------------------------------*/
isXType: function(xtype) {
return xtype === 'odd';
}
});
/**
* @class Ext.chart.Chart
* @extends Ext.draw.Component
*
* The Ext.chart package provides the capability to visualize data.
* Each chart binds directly to an Ext.data.Store enabling automatic updates of the chart.
* A chart configuration object has some overall styling options as well as an array of axes
* and series. A chart instance example could look like:
*
<pre><code>
new Ext.chart.Chart({
renderTo: Ext.getBody(),
width: 800,
height: 600,
animate: true,
store: store1,
shadow: true,
theme: 'Category1',
legend: {
position: 'right'
},
axes: [ ...some axes options... ],
series: [ ...some series options... ]
});
</code></pre>
*
* In this example we set the `width` and `height` of the chart, we decide whether our series are
* animated or not and we select a store to be bound to the chart. We also turn on shadows for all series,
* select a color theme `Category1` for coloring the series, set the legend to the right part of the chart and
* then tell the chart to render itself in the body element of the document. For more information about the axes and
* series configurations please check the documentation of each series (Line, Bar, Pie, etc).
*
* @xtype chart
*/
Ext.chart.Chart = Ext.extend(Ext.draw.Component, {
/**
* @property version Current Version of Touch Charts
* @type {String}
*/
version : '1.0.0',
// @private
viewBox: false,
/**
* @cfg {String} theme (optional) The name of the theme to be used. A theme defines the colors and
* other visual displays of tick marks on axis, text, title text, line colors, marker colors and styles, etc.
* Possible theme values are 'Base', 'Green', 'Sky', 'Red', 'Purple', 'Blue', 'Yellow' and also six category themes
* 'Category1' to 'Category6'. Default value is 'Base'.
*/
/**
* @cfg {Boolean/Object} shadow (optional) true for the default shadow configuration (shadowOffsetX: 2, shadowOffsetY: 2, shadowBlur: 3, shadowColor: '#444')
* or a standard shadow config object to be used for default chart shadows. Defaults to false.
*/
/**
* @cfg {Boolean/Object} animate (optional) true for the default animation (easing: 'ease' and duration: 500)
* or a standard animation config object to be used for default chart animations. Defaults to false.
*/
animate: false,
/**
* @cfg {Boolean/Object} legend (optional) true for the default legend display or a legend config object. Defaults to false.
*/
legend: false,
/**
* @cfg {integer} insetPadding (optional) Set the amount of inset padding in pixels for the chart. Defaults to 10.
*/
/**
* @cfg {Object|Boolean} background (optional) Set the chart background. This can be a gradient object, image, or color.
* Defaults to false for no background.
*
* For example, if `background` were to be a color we could set the object as
*
<pre><code>
background: {
//color string
fill: '#ccc'
}
</code></pre>
You can specify an image by using:
<pre><code>
background: {
image: 'http://path.to.image/'
}
</code></pre>
Also you can specify a gradient by using the gradient object syntax:
<pre><code>
background: {
gradient: {
id: 'gradientId',
angle: 45,
stops: {
0: {
color: '#555'
}
100: {
color: '#ddd'
}
}
}
}
</code></pre>
*/
background: false,
/**
* @cfg {Array} interactions
* Interactions are optional modules that can be plugged in to a chart to allow the user to interact
* with the chart and its data in special ways. The `interactions` config takes an Array of Object
* configurations, each one corresponding to a particular interaction class identified by a `type` property:
*
* new Ext.chart.Chart({
* renderTo: Ext.getBody(),
* width: 800,
* height: 600,
* store: store1,
* axes: [ ...some axes options... ],
* series: [ ...some series options... ],
* interactions: [{
* type: 'interactiontype'
* // ...additional configs for the interaction...
* }]
* });
*
* When adding an interaction which uses only its default configuration (no extra properties other than `type`),
* you can alternately specify only the type as a String rather than the full Object:
*
* interactions: ['reset', 'rotate']
*
* The current supported interaction types include:
*
* - {@link Ext.chart.interactions.PanZoom panzoom} - allows pan and zoom of axes
* - {@link Ext.chart.interactions.ItemCompare itemcompare} - allows selection and comparison of two data points
* - {@link Ext.chart.interactions.ItemHighlight itemhighlight} - allows highlighting of series data points
* - {@link Ext.chart.interactions.ItemInfo iteminfo} - allows displaying details of a data point in a popup panel
* - {@link Ext.chart.interactions.PieGrouping piegrouping} - allows selection of multiple consecutive pie slices
* - {@link Ext.chart.interactions.Rotate rotate} - allows rotation of pie and radar series
* - {@link Ext.chart.interactions.Reset reset} - allows resetting of all user interactions to the default state
* - {@link Ext.chart.interactions.ToggleStacked togglestacked} - allows toggling a multi-yField bar/column chart between stacked and grouped
*
* See the documentation for each of those interaction classes to see how they can be configured.
*
* Additional custom interactions can be registered with the {@link Ext.chart.interactions.Manager interaction manager}.
*/
/**
* @cfg {Object} toolbar
* Optional configuration for this chart's toolbar. The toolbar docks itself to one side of the chart
* and can contain buttons for handling certain actions. For example, if the chart legend is configured
* with {@link Ext.chart.Legend#dock dock:true} then a button for bringing up the legend will be placed
* in this toolbar. Custom may also be added to the toolbar if desired.
*
* See the {@link Ext.chart.Toolbar} docs for the recognized config properties.
*/
/**
* @private The z-indexes to use for the various surfaces
*/
surfaceZIndexes: {
main: 0,
axis: 10,
series: 20,
overlay: 30,
events: 40
},
/**
* @cfg {Ext.data.Store} store
* The store that supplies data to this chart.
*/
/**
* @cfg {[Ext.chart.series.Series]} series
* Array of {@link Ext.chart.series.Series Series} instances or config objects. For example:
*
* series: [{
* type: 'column',
* axis: 'left',
* listeners: {
* 'afterrender': function() {
* console('afterrender');
* }
* },
* xField: 'category',
* yField: 'data1'
* }]
*/
/**
* @cfg {[Ext.chart.axis.Axis]} axes
* Array of {@link Ext.chart.axis.Axis Axis} instances or config objects. For example:
*
* axes: [{
* type: 'Numeric',
* position: 'left',
* fields: ['data1'],
* title: 'Number of Hits',
* minimum: 0,
* //one minor tick between two major ticks
* minorTickSteps: 1
* }, {
* type: 'Category',
* position: 'bottom',
* fields: ['name'],
* title: 'Month of the Year'
* }]
*/
constructor: function(config) {
var me = this,
defaultAnim;
config = Ext.apply({}, config);
if (me.gradients) {
Ext.apply(config, { gradients: me.gradients });
}
if (me.background) {
Ext.apply(config, { background: me.background });
}
if (config.animate) {
defaultAnim = {
easing: 'ease',
duration: 500
};
if (Ext.isObject(config.animate)) {
config.animate = Ext.applyIf(config.animate, defaultAnim);
}
else {
config.animate = defaultAnim;
}
}
Ext.chart.Chart.superclass.constructor.apply(this, [config]);
},
initComponent: function() {
var me = this,
axes, series, interactions;
delete me.legend; //remove legend config from chart
Ext.chart.Chart.superclass.initComponent.call(this);
me.addEvents(
/**
* @event beforerefresh
* Fires before a refresh to the chart data is called. If the beforerefresh handler returns
* <tt>false</tt> the {@link #refresh} action will be cancelled.
* @param {Ext.chart.Chart} this
*/
'beforerefresh',
/**
* @event refresh
* Fires after the chart data has been refreshed.
* @param {Ext.chart.Chart} this
*/
'refresh',
/**
* @event redraw
* Fires after the chart is redrawn
* @param {Ext.chart.Chart} this
*/
'redraw'
/**
* @event itemmousemove
* Fires when the mouse is moved on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
/**
* @event itemmouseup
* Fires when a mouseup event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
/**
* @event itemmousedown
* Fires when a mousedown event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
/**
* @event itemmouseover
* Fires when the mouse enters a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
/**
* @event itemmouseout
* Fires when the mouse exits a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
/**
* @event itemclick
* Fires when a click event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
/**
* @event itemdoubleclick
* Fires when a doubleclick event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
/**
* @event itemtap
* Fires when a tap event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
/**
* @event itemtapstart
* Fires when a tapstart event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
/**
* @event itemtapend
* Fires when a tapend event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
/**
* @event itemtapcancel
* Fires when a tapcancel event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
/**
* @event itemtaphold
* Fires when a taphold event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
/**
* @event itemdoubletap
* Fires when a doubletap event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
/**
* @event itemsingletap
* Fires when a singletap event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
/**
* @event itemtouchstart
* Fires when a touchstart event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
/**
* @event itemtouchmove
* Fires when a touchmove event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
/**
* @event itemtouchend
* Fires when a touchend event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
/**
* @event itemdragstart
* Fires when a dragstart event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
/**
* @event itemdrag
* Fires when a drag event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
/**
* @event itemdragend
* Fires when a dragend event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
/**
* @event itempinchstart
* Fires when a pinchstart event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
/**
* @event itempinch
* Fires when a pinch event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
/**
* @event itempinchend
* Fires when a pinchend event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
/**
* @event itemswipe
* Fires when a swipe event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
);
// Borrow events from Series/ItemEvents so they can bubble up to the chart (doc'd above):
me.addEvents.apply(me, Ext.chart.series.ItemEvents.itemEventNames);
Ext.applyIf(me, {
zoom: {
width: 1,
height: 1,
x: 0,
y: 0
}
});
me.maxGutter = [0, 0];
axes = me.axes;
me.on('activate', me.onActivate, me);
me.axes = new Ext.util.MixedCollection(false, function(a) { return a.position; });
if (axes) {
me.axes.addAll(axes);
}
series = me.series;
me.series = new Ext.util.MixedCollection(false, function(a) { return a.seriesId || (a.seriesId = Ext.id(null, 'ext-chart-series-')); });
if (series) {
me.series.addAll(series);
}
interactions = me.interactions;
me.interactions = new Ext.util.MixedCollection(false, function(a) { return a.type; });
if (interactions) {
Ext.each(interactions, me.addInteraction, me);
}
},
onActivate: function() {
if (this.dirtyStore) {
this.redraw();
}
},
getEventsSurface: function() {
return this.getSurface('events');
},
initEvents: function() {
Ext.chart.Chart.superclass.initEvents.call(this);
this.interactions.each(function(interaction) {
interaction.initEvents();
});
},
getSurface: function(name) {
var me = this,
surfaces = me.surfaces || (me.surfaces = {main: me.surface}),
surface = surfaces[name],
zIndexes = me.surfaceZIndexes,
el;
if (!surface) {
surface = surfaces[name] = me.createSurface({
background: null,
initEvents: (name == 'events')
});
el = surface.el;
el.setStyle('position', 'absolute');
el.setStyle('zIndex', 10);
// Apply z-index if surface name is in the surfaceZIndexes mapping
if (name in zIndexes) {
el.setStyle('zIndex', zIndexes[name]);
}
}
return surface;
},
/**
* Retrieves a reference to the {@link Ext.chart.Toolbar} for this chart, creating it first
* if necessary.
* @return {Ext.chart.Toolbar}
*/
getToolbar: function() {
var me = this,
toolbar = me.toolbar;
if (!toolbar || !toolbar.isChartToolbar) {
toolbar = me.toolbar = new Ext.chart.Toolbar(Ext.applyIf({chart: me}, toolbar));
}
return toolbar;
},
// @private overrides the component method to set the correct dimensions to the chart.
doComponentLayout: function(width, height) {
var me = this,
eventSurface;
if (Ext.isNumber(width) && Ext.isNumber(height) && (me.dirtyStore ||
(width !== me.curWidth || height !== me.curHeight))) {
// Layouts in Touch 1.x aren't optimal, cache the previous size so we don't redraw so much.
me.curWidth = width;
me.curHeight = height;
// Update surfaces to match size
me.getSurface('main').setSize(width, height);
eventSurface = me.getEventsSurface();
eventSurface.setSize(width, height);
eventSurface.el.setTopLeft(0, 0);
if (me.store) {
me.redraw(true);
}
}
Ext.chart.Chart.superclass.doComponentLayout.apply(this, arguments);
},
/**
* Redraw the chart. If animations are set this will animate the chart too.
* @param {Boolean} resize (optional) flag which changes the default origin points of the chart for animations.
*/
redraw: function(resize) {
var me = this,
p, legend, toolbar, i, l, colors, color, colorArrayStyle, callback;
me.dirtyStore = false;
me.chartBBox = {
x: 0,
y: 0,
height: me.curHeight,
width: me.curWidth
};
me.colorArrayStyle = me.colorArrayStyle || [];
me.series.each(me.initializeSeries, me);
me.axes.each(me.initializeAxis, me);
if (!me.themeInitialized) {
// Apply styles from stylesheet.
me.applyStyles();
if (me.style && me.style.colors) {
colors = me.style.colors;
colorArrayStyle = me.colorArrayStyle;
for (i = 0, l = colors.length; i < l; ++i) {
color = colors[i];
if (Ext.isObject(color)) {
for (p in me.surfaces) {
me.surfaces[p].addGradient(color);
}
colorArrayStyle.push('url(#' + color.id + ')');
} else {
colorArrayStyle.push(color);
}
}
} else {
me.series.each(function(series, idx) {
me.colorArrayStyle[idx] = (series.style.fill || series.style.stroke || '#000');
});
}
me.series.each(function(series) {
series.colorArrayStyle = me.colorArrayStyle;
});
if (me.style && me.style.background) {
colors = me.style.background;
//a gradient object
if (Ext.isObject(colors)) {
me.background = { gradient: colors };
me.surfaces.main.addGradient(colors);
} else {
//an image
if (colors.indexOf('url') > -1) {
me.background = { image: colors };
//just a color
} else {
me.background = { fill: colors };
}
}
me.surfaces.main.initBackground(me.background);
}
}
me.initializeLegend();
legend = me.legend;
if (legend) {
legend.orient();
}
toolbar = me.toolbar;
if (toolbar && toolbar.isChartToolbar) {
toolbar.orient();
}
//process all views (aggregated data etc) on stores before rendering.
me.axes.each(function(axis) {
axis.processView();
});
me.axes.each(function(axis) {
axis.drawAxis(true);
});
// Place axes properly, including influence from each other
me.alignAxes();
// Reposition legend based on new axis alignment
if (legend) {
legend.updatePosition();
}
// Find the max gutter
me.getMaxGutter();
// Draw axes and series
me.resizing = !!resize;
me.axes.each(me.drawAxis, me);
me.series.each(me.drawCharts, me);
Ext.iterate(me.surfaces, function(name, surface) {
surface.renderFrame();
});
me.resizing = false;
if (Ext.is.iPad) {
Ext.repaint();
}
if (!me.interactionsInitialized) {
me.interactionsInitialized = true;
if (me.animate) {
me.interactions.each(function(interaction) {
interaction.initializeDefaults({
type: 'beforerender'
});
});
//on after render callback should remove itself since it's
//only called once.
callback = function() {
me.interactions.each(function(interaction) {
interaction.initializeDefaults({
type: 'afterrender'
});
});
me.series.get(0).removeListener('afterrender', callback);
};
me.series.get(0).addListener('afterrender', callback);
} else {
me.interactions.each(function(interaction) {
interaction.initializeDefaults();
});
}
}
me.fireEvent('redraw', me);
},
// @private set the store after rendering the chart.
afterRender: function() {
var ref,
me = this;
Ext.chart.Chart.superclass.afterRender.call(this);
if (me.categoryNames) {
me.setCategoryNames(me.categoryNames);
}
if (me.tipRenderer) {
ref = me.getFunctionRef(me.tipRenderer);
me.setTipRenderer(ref.fn, ref.scope);
}
me.bindStore(me.store);
me.refresh();
},
/**
* @private
* Return the x and y position of the given event relative to the chart's series area.
*/
getEventXY: function(e) {
e = (e.changedTouches && e.changedTouches[0]) || e.event || e.browserEvent || e;
var me = this,
chartXY = me.el.getXY(),
chartBBox = me.chartBBox,
x = e.pageX - chartXY[0] - chartBBox.x,
y = e.pageY - chartXY[1] - chartBBox.y;
return [x, y];
},
/**
* Given an x/y point relative to the chart, find and return the first series item that
* matches that point.
* @param {Number} x
* @param {Number} y
* @return {Object} an object with `series` and `item` properties, or `false` if no item found
*/
getItemForPoint: function(x, y) {
var me = this,
i = 0,
items = me.series.items,
l = items.length,
series, item;
for (; i < l; i++) {
series = items[i];
item = series.getItemForPoint(x, y);
if (item) {
return item;
}
}
return false;
},
/**
* Given an x/y point relative to the chart, find and return all series items that match that point.
* @param {Number} x
* @param {Number} y
* @return {Array} an array of objects with `series` and `item` properties
*/
getItemsForPoint: function(x, y) {
var me = this,
items = [];
me.series.each(function(series) {
var item = series.getItemForPoint(x, y);
if (item) {
items.push(item);
}
});
return items;
},
capitalize: function(string) {
return string.charAt(0).toUpperCase() + string.substr(1);
},
// @private buffered refresh for when we update the store
delayRefresh: function() {
var me = this;
if (!me.refreshTask) {
me.refreshTask = new Ext.util.DelayedTask(me.refresh, me);
}
me.refreshTask.delay(10);
},
// @private
refresh: function() {
var me = this,
undef;
me.dirtyStore = true;
if (me.rendered && me.curWidth != undef && me.curHeight != undef && me.fireEvent('beforerefresh', me) !== false) {
me.redraw();
me.fireEvent('refresh', me);
}
},
/**
* Changes the data store bound to this chart and refreshes it.
* @param {Ext.data.Store} store The store to bind to this chart
*/
bindStore: function(store) {
var me = this,
currentStore = me.store,
initial = !me.storeIsBound;
store = Ext.StoreMgr.lookup(store);
if (!initial && currentStore && store !== currentStore) {
if (currentStore.autoDestroy) {
currentStore.destroy();
}
else {
currentStore.un({
scope: me,
datachanged: me.refresh,
add: me.delayRefresh,
remove: me.delayRefresh,
update: me.delayRefresh
//clear: me.refresh
});
}
}
if (store && (initial || store !== currentStore)) {
store.on({
scope: me,
datachanged: me.refresh,
add: me.delayRefresh,
remove: me.delayRefresh,
update: me.delayRefresh
//clear: me.refresh
});
}
me.store = store;
me.storeIsBound = true;
if (store && !initial) {
me.refresh();
}
},
/**
* Adds an interaction to the chart.
* @param {Object/String} interaction Either an instantiated {@link Ext.chart.interactions.Abstract}
* instance, a configuration object for an interaction, or the interaction type as a String.
*/
addInteraction: function(interaction) {
if (Ext.isString(interaction)) {
interaction = {type: interaction};
}
if (!interaction.chart) {
interaction.chart = this;
interaction = Ext.chart.interactions.Manager.create(interaction);
}
this.interactions.add(interaction);
},
// @private initialize the series.
initializeLegend: function() {
var me = this,
legend = me.legend,
legendConfig = me.initialConfig.legend;
if (!legend && legendConfig) {
legend = me.legend = new Ext.chart.Legend(Ext.apply({chart: me}, legendConfig));
legend.on('combine', me.redraw, me);
legend.on('split', me.redraw, me);
}
},
// @private Create Axis
initializeAxis: function(axis) {
var me = this,
chartBBox = me.chartBBox,
w = chartBBox.width,
h = chartBBox.height,
x = chartBBox.x,
y = chartBBox.y,
config = {
chart: me,
ownerCt: me,
x: 0,
y: 0
};
switch (axis.position) {
case 'top':
Ext.apply(config, {
length: w,
width: h,
startX: x,
startY: y
});
break;
case 'bottom':
Ext.apply(config, {
length: w,
width: h,
startX: x,
startY: h
});
break;
case 'left':
Ext.apply(config, {
length: h,
width: w,
startX: x,
startY: h
});
break;
case 'right':
Ext.apply(config, {
length: h,
width: w,
startX: w,
startY: h
});
break;
}
if (!axis.chart) {
Ext.apply(config, axis);
axis = me.axes.replace(new Ext.chart.axis[this.capitalize(axis.type)](config));
}
else {
Ext.apply(axis, config);
}
},
/**
* @private Adjust the dimensions and positions of each axis and the chart body area after accounting
* for the space taken up on each side by the axes and legend.
*/
alignAxes: function() {
var me = this,
axes = me.axes,
legend = me.legend,
edges = ['top', 'right', 'bottom', 'left'],
chartBBox,
//get padding from sass styling or property setting.
insetPadding = me.insetPadding || +me.style.padding || 10,
insets;
//store the original configuration for insetPadding.
if (Ext.isObject(insetPadding)) {
me.insetPadding = Ext.apply({} ,insetPadding);
insets = {
top: insetPadding.top || 0,
right: insetPadding.right || 0,
bottom: insetPadding.bottom || 0,
left: insetPadding.left || 0
};
} else {
me.insetPadding = insetPadding;
insets = {
top: insetPadding,
right: insetPadding,
bottom: insetPadding,
left: insetPadding
};
}
me.insets = insets;
function getAxis(edge) {
var i = axes.findIndex('position', edge);
return (i < 0) ? null : axes.getAt(i);
}
// Find the space needed by axes and legend as a positive inset from each edge
Ext.each(edges, function(edge) {
var isVertical = (edge === 'left' || edge === 'right'),
axis = getAxis(edge),
bbox;
// Add legend size if it's on this edge
if (legend !== false) {
if (legend.getPosition() === edge) {
insets[edge] += legend.getInsetSize();
}
}
// Add axis size if there's one on this edge only if it has been
//drawn before.
if (axis && axis.bbox) {
bbox = axis.bbox;
insets[edge] += (isVertical ? bbox.width : bbox.height);
}
});
// Build the chart bbox based on the collected inset values
chartBBox = {
x: insets.left,
y: insets.top,
width: me.curWidth - insets.left - insets.right,
height: me.curHeight - insets.top - insets.bottom
};
me.chartBBox = chartBBox;
// Go back through each axis and set its size, position, and relative start point based on the
// corresponding edge of the chartBBox
axes.each(function(axis) {
var pos = axis.position,
axisBBox = axis.bbox || {width: 0, height: 0},
isVertical = (pos === 'left' || pos === 'right');
axis.x = (pos === 'left' ? chartBBox.x - axisBBox.width : chartBBox.x);
axis.y = (pos === 'top' ? chartBBox.y - axisBBox.height : chartBBox.y);
axis.width = (isVertical ? axisBBox.width + chartBBox.width: axisBBox.height + chartBBox.height);
axis.length = (isVertical ? chartBBox.height : chartBBox.width);
axis.startX = (isVertical ? (pos === 'left' ? axisBBox.width : chartBBox.width) : 0);
axis.startY = (pos === 'top' ? axisBBox.height : chartBBox.height);
});
},
// @private initialize the series.
initializeSeries: function(series, idx) {
var me = this,
config = {
chart: me,
ownerCt: me,
seriesId: series.seriesId,
index: idx
};
if (series instanceof Ext.chart.series.Series) {
Ext.apply(series, config);
} else {
Ext.applyIf(config, series);
series = me.series.replace(new Ext.chart.series[me.capitalize(series.type)](config));
}
if (series.initialize) {
series.initialize();
}
},
// @private
getMaxGutter: function() {
var me = this,
maxGutter = [0, 0];
me.series.each(function(s) {
var gutter = s.getGutters && s.getGutters() || [0, 0];
maxGutter[0] = Math.max(maxGutter[0], gutter[0]);
maxGutter[1] = Math.max(maxGutter[1], gutter[1]);
});
me.maxGutter = maxGutter;
},
// @private draw axis.
drawAxis: function(axis) {
axis.drawAxis();
},
// @private draw series.
drawCharts: function(series) {
series.drawSeries();
if (!this.animate) {
series.fireEvent('afterrender');
}
},
/**
* Reset the chart back to its initial state, before any user interaction.
* @param {Boolean} skipRedraw if `true`, redrawing of the chart will be skipped.
*/
reset: function(skipRedraw) {
var me = this,
legend = me.legend;
me.axes.each(function(axis) {
if (axis.reset) {
axis.reset();
}
});
me.series.each(function(series) {
if (series.reset) {
series.reset();
}
});
if (legend && legend.reset) {
legend.reset();
}
if (!skipRedraw) {
me.redraw();
}
},
// @private remove gently.
destroy: function() {
Ext.iterate(this.surfaces, function(name, surface) {
surface.destroy();
});
this.bindStore(null);
Ext.chart.Chart.superclass.destroy.apply(this, arguments);
},
/* ---------------------------------
Methods needed for ComponentQuery
----------------------------------*/
ownerCt: null,
getItemId: function() {
return this.el && this.el.id || this.id || null;
},
initCls: function() {
return (this.cls || '').split(' ');
},
isXType: function(xtype) {
return xtype === 'chart';
},
getRefItems: function(deep) {
var me = this,
ans = [];
me.series.each(function(series) {
ans.push(series);
if (deep) {
if (series.markerStyle) {
ans.push(series.markerStyle);
}
if (series.labelStyle) {
ans.push(series.labelStyle);
}
if (series.calloutStyle) {
ans.push(series.calloutStyle);
}
}
});
me.axes.each(function(axis) {
ans.push(axis);
if (deep && axis.labelStyle) {
ans.push(axis.labelStyle);
}
if (deep && axis.gridStyle) {
ans.push(axis.gridStyle);
ans.push(axis.gridStyle.oddStyle);
ans.push(axis.gridStyle.evenStyle);
}
});
me.interactions.each(function(interaction) {
ans.push(interaction);
if (deep) {
ans = ans.concat(interaction.getRefItems(deep));
}
});
return ans;
}
});
Ext.applyIf(Ext.chart.Chart.prototype, Ext.chart.theme.Theme.prototype);
Ext.reg('chart', Ext.chart.Chart);
Ext.chart.Panel = Ext.extend(Ext.Panel, {
defaultType: 'chart',
layout: 'fit',
constructor: function(config) {
config.dockedItems = {
xtype: 'panel',
height: '2.6em',
dock: 'top',
layout: {
type: 'card',
align: 'stretch'
},
activeItem: 0,
dockedItems: {
dock: 'right',
xtype: 'toolbar',
ui: 'light',
items: config.dockedItems
},
items: [{
dock: 'top',
xtype: 'toolbar',
ui: 'light',
title: config.title || ''
}, {
dock: 'top',
xtype: 'toolbar',
ui: 'light',
title: ''
}]
};
Ext.chart.Panel.superclass.constructor.call(this, config);
},
onRender: function() {
var me = this,
headerPanel;
Ext.chart.Panel.superclass.onRender.apply(me, arguments);
headerPanel = me.headerPanel = me.dockedItems.get(0);
me.descriptionPanel = headerPanel.items.get(1);
}
});
/**
* @class Ext.chart.Callout
* @ignore
*/
Ext.chart.Callout = Ext.extend(Object, {
constructor: function(config) {
var me = this;
if (config.callouts) {
config.callouts.styles = Ext.apply({}, config.callouts.styles || {});
me.callouts = Ext.apply(me.callouts || {}, config.callouts);
me.calloutsArray = [];
}
me.calloutStyle = new Ext.chart.theme.CalloutStyle();
},
renderCallouts: function() {
if (!this.callouts) {
return;
}
var me = this,
items = me.items,
animate = me.chart.animate,
config = me.callouts,
styles = config.styles,
group = me.calloutsArray,
store = me.chart.store,
len = store.getCount(),
ratio = items.length / len,
previouslyPlacedCallouts = [],
i, count, j, p;
for (i = 0, count = 0; i < len; i++) {
for (j = 0; j < ratio; j++) {
var item = items[count],
label = group[count],
storeItem = store.getAt(i),
display;
display = ((item && item.useCallout) || config.filter(storeItem, item, i, display, j, count)) && (Math.abs(item.endAngle - item.startAngle) > 0.8);
if (!display && !label) {
count++;
continue;
}
if (!label) {
group[count] = label = me.onCreateCallout(storeItem, item, i, display, j, count);
}
for (p in label) {
if (label[p] && label[p].setAttributes) {
label[p].setAttributes(styles, true);
}
}
if (!display) {
for (p in label) {
if (label[p]) {
if (label[p].setAttributes) {
label[p].setAttributes({
hidden: true
}, true);
} else if(label[p].setVisible) {
label[p].setVisible(false);
}
}
}
}
config.renderer(label, storeItem);
if (display) {
me.onPlaceCallout(label, storeItem, item, i, display, animate,
j, count, previouslyPlacedCallouts);
}
previouslyPlacedCallouts.push(label);
count++;
}
}
this.hideCallouts(count);
},
onCreateCallout: function(storeItem, item, i, display) {
var me = this,
config = me.callouts,
styles = config.styles,
width = styles.width || 100,
height = styles.height || 100,
surface = me.getSurface(),
calloutObj = {
label: false,
box: false,
lines: false
};
calloutObj.lines = surface.add(Ext.apply({}, {
type: 'path',
path: 'M0,0',
stroke: me.getLegendColor(i) || '#555'
}, config.lines || {}));
calloutObj.box = surface.add(Ext.apply({
type: 'rect',
width: width,
height: height
}, config.box || {}));
calloutObj.label = surface.add(Ext.apply({
type: 'text',
text: 'some text'
}, config.label || {}));
return calloutObj;
},
hideCallouts: function(index) {
var calloutsArray = this.calloutsArray,
len = calloutsArray.length,
co, p;
while (len-->index) {
co = calloutsArray[len];
for (p in co) {
if (co[p]) {
co[p].hide(true);
}
}
}
},
/* ---------------------------------
Methods needed for ComponentQuery
----------------------------------*/
//filled by the constructor.
ownerCt: null,
getItemId: function() {
return this.el && this.el.id || this.id || null;
},
initCls: function() {
return (this.cls || '').split(' ');
},
isXType: function(xtype) {
return xtype === 'callout';
},
getRefItems: function(deep) {
return [];
}
});
/**
* @class Ext.chart.Highlight
* @ignore
*/
Ext.chart.Highlight = Ext.extend(Object, {
/**
* Specifies whether this series should respond to highlighting, and optionally specifies custom
* attributes for the highlighting effect. Only used if the
* {@link Ext.chart.interactions.ItemHighlight itemhighlight} interaction is configured.
* Defaults to `true` which uses a default highlighting effect for the series items; set it to
* `false` to disable highlighting entirely on this series, or to an object with style properties
* (i.e fill, stroke, radius) to customize the highlighting effect.
*/
highlight: true,
/**
* @cfg {Number} highlightDuration
* The duration for the highlight effect in milliseconds. Default's 150
*/
highlightDuration: 150,
highlightCfg : null,
constructor: function(config) {
if (config.highlight !== false) {
if (config.highlight !== true) { //is an object
this.highlightCfg = Ext.apply({}, config.highlight);
}
else {
this.highlightCfg = {};
}
this.addEvents('highlight', 'unhighlight');
this.highlightStyle = new Ext.chart.theme.HighlightStyle();
}
},
/**
* Highlight the given series item.
* @param {Object} item Info about the item; same format as returned by #getItemForPoint.
*/
highlightItem: function(item) {
if (!item) {
return;
}
var me = this,
sprite = item.sprite,
opts = me.highlightCfg,
surface = me.chart.surface,
animate = me.chart.animate,
p, from, to, pi;
if (me.highlight === false || !sprite || sprite._highlighted) {
return;
}
//make sure we apply the stylesheet styles.
Ext.applyIf(me.highlightCfg, me.highlightStyle.style || {});
if (sprite._anim) {
sprite._anim.paused = true;
}
sprite._highlighted = true;
if (!sprite._defaults) {
sprite._defaults = Ext.apply({}, sprite.attr);
from = {};
to = {};
for (p in opts) {
if (! (p in sprite._defaults)) {
sprite._defaults[p] = surface.attributeDefaults[surface.attributeMap[p]];
}
from[p] = sprite._defaults[p];
to[p] = opts[p];
if (Ext.isObject(opts[p])) {
from[p] = {};
to[p] = {};
Ext.apply(sprite._defaults[p], sprite.attr[p]);
Ext.apply(from[p], sprite._defaults[p]);
for (pi in sprite._defaults[p]) {
if (! (pi in opts[p])) {
to[p][pi] = from[p][pi];
} else {
to[p][pi] = opts[p][pi];
}
}
for (pi in opts[p]) {
if (! (pi in to[p])) {
to[p][pi] = opts[p][pi];
}
}
}
}
sprite._from = from;
sprite._to = to;
sprite._endStyle = to;
}
if (animate) {
sprite._anim = new Ext.fx.Anim({
target: sprite,
from: sprite._from,
to: sprite._to,
duration: me.highlightDuration || 150
});
} else {
sprite.setAttributes(sprite._to, true);
}
me.fireEvent('highlight', item);
},
/**
* Un-highlight any existing highlights
*/
unHighlightItem: function() {
if (this.highlight === false || !this.items) {
return;
}
var me = this,
items = me.items,
len = items.length,
opts = me.highlightCfg,
animate = me.chart.animate,
i = 0,
obj, p, sprite;
for (; i < len; i++) {
if (!items[i]) {
continue;
}
sprite = items[i].sprite;
if (sprite && sprite._highlighted) {
if (sprite._anim) {
sprite._anim.paused = true;
}
obj = {};
for (p in opts) {
if (Ext.isObject(sprite._defaults[p])) {
obj[p] = {};
Ext.apply(obj[p], sprite._defaults[p]);
}
else {
obj[p] = sprite._defaults[p];
}
}
if (animate) {
//sprite._to = obj;
sprite._endStyle = obj;
sprite._anim = new Ext.fx.Anim({
target: sprite,
to: obj,
duration: me.highlightDuration || 150
});
}
else {
sprite.setAttributes(obj, true);
}
delete sprite._highlighted;
//delete sprite._defaults;
}
}
me.fireEvent('unhighlight');
},
cleanHighlights: function() {
if (this.highlight === false) {
return;
}
var group = this.group,
markerGroup = this.markerGroup,
i = 0,
l;
for (l = group.getCount(); i < l; i++) {
delete group.getAt(i)._defaults;
}
if (markerGroup) {
for (l = markerGroup.getCount(); i < l; i++) {
delete markerGroup.getAt(i)._defaults;
}
}
}
});
/**
* @class Ext.chart.Label
*
* Labels is a mixin whose methods are appended onto the Series class. Labels is an interface with methods implemented
* in each of the Series (Pie, Bar, etc) for label creation and label placement.
*
* The methods implemented by the Series are:
*
* - **`onCreateLabel(storeItem, item, i, display)`** Called each time a new label is created.
* The arguments of the method are:
* - *`storeItem`* The element of the store that is related to the label sprite.
* - *`item`* The item related to the label sprite. An item is an object containing the position of the shape
* used to describe the visualization and also pointing to the actual shape (circle, rectangle, path, etc).
* - *`i`* The index of the element created (i.e the first created label, second created label, etc)
* - *`display`* The display type. May be <b>false</b> if the label is hidden
*
* - **`onPlaceLabel(label, storeItem, item, i, display, animate)`** Called for updating the position of the label.
* The arguments of the method are:
* - *`label`* The sprite label.</li>
* - *`storeItem`* The element of the store that is related to the label sprite</li>
* - *`item`* The item related to the label sprite. An item is an object containing the position of the shape
* used to describe the visualization and also pointing to the actual shape (circle, rectangle, path, etc).
* - *`i`* The index of the element to be updated (i.e. whether it is the first, second, third from the labelGroup)
* - *`display`* The display type. May be <b>false</b> if the label is hidden.
* - *`animate`* A boolean value to set or unset animations for the labels.
*/
Ext.chart.Label = Ext.extend(Object, {
/**
* @cfg {Object} label
* Object with the following properties:
*
* - **display** : String
*
* Specifies the presence and position of labels for each pie slice. Either "rotate", "middle", "insideStart",
* "insideEnd", "outside", "over", "under", or "none" to prevent label rendering.
* Default value: 'none'.
*
* - **color** : String
*
* The color of the label text.
* Default value: '#000' (black).
*
* - **contrast** : Boolean
*
* True to render the label in contrasting color with the backround.
* Default value: false.
*
* - **field** : String
*
* The name of the field to be displayed in the label.
* Default value: 'name'.
*
* - **minMargin** : Number
*
* Specifies the minimum distance from a label to the origin of the visualization.
* This parameter is useful when using PieSeries width variable pie slice lengths.
* Default value: 50.
*
* - **font** : String
*
* The font used for the labels.
* Default value: "11px Helvetica, sans-serif".
*
* - **orientation** : String
*
* Either "horizontal" or "vertical".
* Default value: "horizontal".
*
* - **renderer** : Function
*
* Optional function for formatting the label into a displayable value.
* Default value: function(v) { return v; }
*/
//@private a regex to parse url type colors.
colorStringRe: /url\s*\(\s*#([^\/)]+)\s*\)/,
//@private the mixin constructor. Used internally by Series.
constructor: function(config) {
var me = this;
me.label = Ext.applyIf(config.label || {}, {
renderer: function(v) {
return v;
}
});
if (me.label.display !== 'none') {
me.labelsGroup = me.chart.surface.getGroup(me.seriesId + '-labels');
}
},
//@private a method to render all labels in the labelGroup
renderLabels: function() {
var me = this,
chart = me.chart,
gradients = chart.gradients,
items = me.items,
animate = chart.animate,
config = Ext.apply(me.labelStyle.style || {}, me.label || {}),
display = config.display,
field = [].concat(config.field),
group = me.labelsGroup,
len = me.getRecordCount(),
itemLength = (items || 0) && items.length,
ratio = itemLength / len,
gradientsCount = (gradients || 0) && gradients.length,
Color = Ext.draw.Color,
gradient, count = 0, index, j, k, colorStopTotal, colorStopIndex, colorStop, item, label,
sprite, spriteColor, spriteBrightness, labelColor, colorString;
if (display == 'none') {
return;
}
me.eachRecord(function(storeItem, i) {
index = 0;
for (j = 0; j < ratio; j++) {
item = items[count];
label = group.getAt(count);
//check the excludes
while (this.__excludes && this.__excludes[index]) {
index++;
}
if (!item && label) {
label.hide(true);
}
if (item && field[j]) {
if (!label) {
label = me.onCreateLabel(storeItem, item, i, display, j, index);
}
label.show(true);
me.onPlaceLabel(label, storeItem, item, i, display, animate, j, index);
//set contrast
if (config.contrast && item.sprite) {
sprite = item.sprite;
//set the color string to the color to be set.
if (sprite._endStyle) {
colorString = sprite._endStyle.fill;
}
else if (sprite._to) {
colorString = sprite._to.fill;
}
else {
colorString = sprite.attr.fill;
}
colorString = colorString || sprite.attr.fill;
spriteColor = Color.fromString(colorString);
//color wasn't parsed property maybe because it's a gradient id
if (colorString && !spriteColor) {
colorString = colorString.match(me.colorStringRe)[1];
for (k = 0; k < gradientsCount; k++) {
gradient = gradients[k];
if (gradient.id == colorString) {
//avg color stops
colorStop = 0;
colorStopTotal = 0;
for (colorStopIndex in gradient.stops) {
colorStop++;
colorStopTotal += Color.fromString(gradient.stops[colorStopIndex].color).getGrayscale();
}
spriteBrightness = (colorStopTotal / colorStop) / 255;
break;
}
}
} else {
spriteBrightness = spriteColor.getGrayscale() / 255;
}
if (label.isOutside) {
spriteBrightness = 1;
}
labelColor = Color.fromString(label.attr.color || label.attr.fill).getHSL();
labelColor[2] = spriteBrightness > 0.5 ? 0.2 : 0.8;
label.setAttributes({
fill: String(Color.fromHSL.apply({},
labelColor))
},
true);
}
}
count++;
index++;
}
});
me.hideLabels(count);
},
//@private a method to hide labels.
hideLabels: function(index) {
var labelsGroup = this.labelsGroup,
len;
if (labelsGroup) {
len = labelsGroup.getCount();
while (len-->index) {
labelsGroup.getAt(len).hide(true);
}
}
}
});
/**
* @class Ext.chart.Transformable
*
* Transformable is a mixin for chart items (axes, series, etc.) which makes them capable
* of having their surfaces panned and zoomed via transformations.
*
* There are two modes of transformation that this mixin supports:
*
* - **Persistent transform** - This is a logical transformation, saved to the item as properties
* {@link #panX}, {@link #panY}, {@link #zoomX}, and {@link #zoomY}. The item's drawing logic must
* honor these properties and should be explicitly re-run after updating the persistent transform.
* - **Fast transform** - This is a pixel-wise transform applied (via CSS3) to the {@link Ext.draw.Surface}
* element itself. As this does not perform a redraw of the surface, vector shapes currently
* rendered to the surface will be deformed by this transform. This is meant to only be transient,
* and to have {@link #syncToFastTransform} called once the speed is no longer required to apply
* the fast transform parameters into the persistent transform properties.
*/
Ext.chart.Transformable = Ext.extend(Object, {
/**
* @property zoomX
* @type {Number}
* The horizontal zoom transformation factor for this chart item. Defaults to 1.
*/
zoomX: 1,
/**
* @property zoomY
* @type {Number}
* The vertical zoom transformation factor for this chart item. Defaults to 1.
*/
zoomY: 1,
/**
* @property panX
* @type {Number}
* The horizontal pan transformation offset for this chart item. Defaults to 0.
*/
panX: 0,
/**
* @property panY
* @type {Number}
* The vertical pan transformation offset for this chart item. Defaults to 0.
*/
panY: 0,
constructor: function() {
this.addEvents(
/**
* @event transform
* Fired after a transformation has been applied to this chart item.
* @param {Object} this
* @param {Boolean} fast True if it is a CSS3 fast transform, false if a persistent transform
*/
'transform'
);
},
/**
* Directly sets the persistent pan/zoom transform properties for this chart item. Removes any
* active fast transform and updates the {@link #panX}, {@link #panY}, {@link #zoomX}, and
* {@link #zoomY} properties to match the supplied arguments.
* @param {Number} panX
* @param {Number} panY
* @param {Number} zoomX
* @param {Number} zoomY
*/
setTransform: function(panX, panY, zoomX, zoomY) {
var me = this;
me.panX = panX;
me.panY = panY;
me.zoomX = zoomX;
me.zoomY = zoomY;
me.clearFastTransform();
Ext.each(me.getTransformableSurfaces(), function(surface) {
surface.setSurfaceTransform(panX, panY, zoomX, zoomY);
});
me.fireEvent('transform', me, false);
},
/**
* Adjusts the persistent pan/zoom transform properties for this chart item. Removes any
* active fast transform and adjusts the existing {@link #panX}, {@link #panY}, {@link #zoomX}, and
* {@link #zoomY} properties by the supplied arguments.
* @param {Number} panX
* @param {Number} panY
* @param {Number} zoomX
* @param {Number} zoomY
*/
transformBy: function(panX, panY, zoomX, zoomY) {
var me = this;
me.setTransform(me.panX + panX, me.panY + panY, me.zoomX * zoomX, me.zoomY * zoomY);
},
/**
* Sets the pan/zoom transformation for this chart item, using CSS3 for fast hardware-accelerated
* transformation. The existing persistent {@link #panX}, {@link #panY}, {@link #zoomX}, and
* {@link #zoomY} properties will be left alone and the remaining transform required to reach
* the supplied arguments will be applied using a CSS3 transform.
* @param {Number} panX
* @param {Number} panY
* @param {Number} zoomX
* @param {Number} zoomY
*/
setTransformFast: function(panX, panY, zoomX, zoomY) {
var me = this;
panX -= me.panX;
panY -= me.panY;
zoomX /= me.zoomX;
zoomY /= me.zoomY;
me.clearFastTransform();
me.transformByFast(panX, panY, zoomX, zoomY);
},
/**
* Adjusts the pan/zoom transformation for this chart item, using CSS3 for fast hardware-accelerated
* transformation. The existing persistent {@link #panX}/{@link #panY}/{@link #zoomX}/{@link #zoomY}
* properties will be left alone and the supplied arguments will be added to the existing transform
* using CSS3.
* @param {Number} panX
* @param {Number} panY
* @param {Number} zoomX
* @param {Number} zoomY
*/
transformByFast: function(panX, panY, zoomX, zoomY) {
this.setFastTransformMatrix(this.getFastTransformMatrix().translate(panX, panY).scale(zoomX, zoomY, 0, 0));
},
/**
* Returns a {@link Ext.draw.Matrix} representing the total current transformation for this chart
* item, including both the persistent {@link #panX}/{@link #panY}/{@link #zoomX}/{@link #zoomY}
* and any additional CSS3 fast transform that is currently applied.
* @return {Ext.draw.Matrix}
*/
getTransformMatrix: function() {
var me = this;
return me.getFastTransformMatrix().clone().translate(me.panX, me.panY).scale(me.zoomX, me.zoomY, 0, 0);
},
/**
* Returns a {@link Ext.draw.Matrix} representing the CSS3 fast transform currently applied to this
* chart item. If no fast transform is applied a Matrix in its default state will be returned. This
* matrix does *not* include the persistent {@link #panX}/{@link #panY}/{@link #zoomX}/{@link #zoomY}
* transformation properties.
* @return {Ext.draw.Matrix}
*/
getFastTransformMatrix: function() {
return this.fastTransformMatrix || new Ext.draw.Matrix();
},
/**
* Sets the pan/zoom transformation for this chart item, using CSS3 for fast hardware-accelerated
* transformation. The existing persistent {@link #panX}, {@link #panY}, {@link #zoomX}, and
* {@link #zoomY} properties will be left alone and the remaining transform required to reach
* the supplied matrix argument will be applied using a CSS3 transform.
* @param {Ext.draw.Matrix} matrix
*/
setTransformMatrixFast: function(matrix) {
var parts = matrix.split();
this.setTransformFast(parts.translateX, parts.translateY, parts.scaleX, parts.scaleY);
},
/**
* @private
* Sets only the CSS3 fast transform to match the given {@link Ext.draw.Matrix}, overwriting
* any existing fast transform.
* @param {Ext.draw.Matrix} matrix
*/
setFastTransformMatrix: function(matrix) {
var me = this;
me.fastTransformMatrix = matrix;
Ext.each(me.getTransformableSurfaces(), function(surface) {
surface.setSurfaceFastTransform(matrix);
});
if (matrix) {
me.fireEvent('transform', me, true);
}
},
/**
* @private
* Removes any CSS3 fast transform currently applied to this chart item.
*/
clearFastTransform: function() {
this.setFastTransformMatrix(null);
},
/**
* Returns `true` if this chart item currently has a CSS3 fast transform applied, `false` if not.
* @return {Boolean}
*/
hasFastTransform: function() {
var matrix = this.fastTransformMatrix;
return matrix && !matrix.isIdentity();
},
/**
* Clears all transforms from this chart item.
*/
clearTransform: function() {
this.setTransform(0, 0, 1, 1);
},
/**
* If this chart item has a CSS3 fast transform applied, this method will apply that transform
* to the persistent {@link #panX}/{@link #panY}/{@link #zoomX}/{@link #zoomY} transform properties
* and remove the fast transform.
*/
syncToFastTransform: function() {
// decompose the fast transform matrix and adjust the persistent pan/zoom by its values
var me = this,
fastMatrix = me.getFastTransformMatrix(),
parts = fastMatrix.split();
delete me.fastTransformMatrix;
me.transformBy(parts.translateX, parts.translateY, parts.scaleX, parts.scaleY);
},
/**
* Return a list of the {@link Ext.draw.Surface surfaces} that should be kept in sync
* with this chart item's transformations.
*/
getTransformableSurfaces: function() {
return [];
}
});
/**
* @class Ext.chart.axis.Abstract
*/
Ext.ns('Ext.chart.axis');
Ext.chart.axis.Abstract = Ext.extend(Ext.util.Observable, {
constructor: function(config) {
config = config || {};
var me = this,
pos = config.position || 'left';
pos = pos.charAt(0).toUpperCase() + pos.substring(1);
Ext.apply(me, config);
me.fields = [].concat(me.fields);
me.labels = [];
me.getId();
me.labelGroup = me.getSurface().getGroup(me.axisId + "-labels");
me.titleStyle = new Ext.chart.theme.TitleStyle();
Ext.apply(me.titleStyle.style, config.labelTitle || {});
me.labelStyle = new Ext.chart.theme.LabelStyle();
Ext.apply(me.labelStyle.style, config.label || {});
me.gridStyle = new Ext.chart.theme.GridStyle();
Ext.apply(me.gridStyle.style, config.grid || {});
if (config.grid && config.grid.odd) {
me.gridStyle.oddStyle.style = Ext.apply(me.gridStyle.oddStyle.style || {},
config.grid.odd);
}
if (config.grid && config.grid.even) {
me.gridStyle.evenStyle.style = Ext.apply(me.gridStyle.evenStyle.style || {},
config.grid.even);
}
Ext.chart.Transformable.prototype.constructor.call(me);
},
grid: false,
steps: 10,
x: 0,
y: 0,
minValue: 0,
maxValue: 0,
getId: function() {
return this.axisId || (this.axisId = Ext.id(null, 'ext-axis-'));
},
/*
Called to process a view i.e to make aggregation and filtering over
a store creating a substore to be used to render the axis. Since many axes
may do different things on the data and we want the final result of all these
operations to be rendered we need to call processView on all axes before drawing
them.
*/
processView: Ext.emptyFn,
drawAxis: Ext.emptyFn,
/**
* Get the {@link Ext.draw.Surface} instance for this axis.
* @return {Ext.draw.Surface}
*/
getSurface: function() {
var me = this,
surface = me.surface,
chart = me.chart;
if (!surface) {
surface = me.surface = chart.getSurface(me.position + 'Axis');
surface.el.setStyle('zIndex', chart.surfaceZIndexes.axis);
}
return surface;
},
/**
* Hides all axis labels.
*/
hideLabels: function() {
this.labelGroup.hide();
},
/**
* @private update the position/size of the axis surface. By default we set it to the
* full chart size; subclasses can change this for custom clipping size.
*/
updateSurfaceBox: function() {
var me = this,
surface = me.getSurface(),
chart = me.chart;
surface.el.setTopLeft(0, 0);
surface.setSize(chart.curWidth, chart.curHeight);
},
getTransformableSurfaces: function() {
return [this.getSurface()];
},
/**
* Reset the axis to its original state, before any user interaction.
*/
reset: function() {
this.clearTransform();
},
/**
* Invokes renderFrame on this axis's surface(s)
*/
renderFrame: function() {
this.getSurface().renderFrame();
},
/* ---------------------------------
Methods needed for ComponentQuery
----------------------------------*/
//filled by the constructor.
ownerCt: null,
getItemId: function() {
return this.el && this.el.id || this.id || null;
},
initCls: function() {
return (this.cls || '').split(' ');
},
isXType: function(xtype) {
return xtype === 'axis';
},
getRefItems: function(deep) {
var me = this,
ans = [];
if (me.labelStyle) {
ans.push(me.labelStyle);
}
if (me.titleStyle) {
ans.push(me.titleStyle);
}
if (me.gridStyle) {
ans.push(me.gridStyle);
ans.push(me.gridStyle.oddStyle);
ans.push(me.gridStyle.evenStyle);
}
return ans;
}
});
Ext.applyIf(Ext.chart.axis.Abstract.prototype, Ext.chart.Transformable.prototype);
/**
* @class Ext.chart.axis.Axis
* @extends Ext.chart.axis.Abstract
*
* Defines axis for charts. The axis position, type, style can be configured.
* The axes are defined in an axes array of configuration objects where the type,
* field, grid and other configuration options can be set. To know more about how
* to create a Chart please check the Chart class documentation. Here's an example for the axes part:
* An example of axis for a series (in this case for an area chart that has multiple layers of yFields) could be:
*
* axes: [{
* type: 'Numeric',
* grid: true,
* position: 'left',
* fields: ['data1', 'data2', 'data3'],
* title: 'Number of Hits',
* grid: {
* odd: {
* opacity: 1,
* fill: '#ddd',
* stroke: '#bbb',
* 'stroke-width': 1
* }
* },
* minimum: 0
* }, {
* type: 'Category',
* position: 'bottom',
* fields: ['name'],
* title: 'Month of the Year',
* grid: true,
* label: {
* rotate: {
* degrees: 315
* }
* }
* }]
*
* In this case we use a `Numeric` axis for displaying the values of the Area series and a `Category` axis for displaying the names of
* the store elements. The numeric axis is placed on the left of the screen, while the category axis is placed at the bottom of the chart.
* Both the category and numeric axes have `grid` set, which means that horizontal and vertical lines will cover the chart background. In the
* category axis the labels will be rotated so they can fit the space better.
*/
Ext.chart.axis.Axis = Ext.extend(Ext.chart.axis.Abstract, {
/**
* @cfg {Number} majorTickSteps
* If `minimum` and `maximum` are specified it forces the number of major ticks to the specified value.
*/
/**
* @cfg {Number} minorTickSteps
* The number of small ticks between two major ticks. Default is zero.
*/
/**
* @cfg {Array} fields
* An array containing the names of record fields which should be mapped along the axis
*/
/**
* @cfg {String} title
* The title for the Axis
*/
/**
* @cfg {Object} label
* The label configuration object for the Axis
*/
/**
* @cfg {Number} dashSize
* The size of the dash marker. Default's 3.
*/
dashSize: 3,
/**
* @cfg {String} position
* Where to set the axis. Available options are `left`, `bottom`, `right`, `top`. Default's `bottom`.
*/
position: 'bottom',
/**
* Offset axis position. Default's 0.
* @property length
* @type {Number}
*/
length: 0,
/**
* Offset axis width. Default's 0.
* @property width
* @type {Number}
*/
width: 0,
majorTickSteps: false,
// @private
applyData: Ext.emptyFn,
/**
* @private If true, label values will be calculated during each axis draw; useful for numeric axes.
*/
calcLabels: false,
/**
* @private Size of the buffer area on either side of the viewport to provide seamless zoom/pan
* transforms. Expressed as a multiple of the viewport length, e.g. 1 will make the buffer on
* each side equal to the length of the visible axis viewport.
*/
overflowBuffer: 1.25,
renderFrame: function() {
var me = this,
surface = me.getSurface(),
labelSurface = me.getLabelSurface();
surface.renderFrame();
if (labelSurface !== surface) {
labelSurface.renderFrame();
}
},
// @private returns whether this axis is on the left or right side
isSide: function() {
var pos = this.position;
return pos === 'left' || pos === 'right';
},
/**
* @private update the position, size, and clipping of the axis surface to match the
* current bbox and zoom/pan properties.
*/
updateSurfaceBox: function() {
var me = this,
isSide = me.isSide(),
length = me.length,
viewLength = length + 1, //add 1px to viewable area so the last tick lines up with main line of adjacent axis
width = me.width,
surface = me.getSurface();
surface.el.setTopLeft(me.y, me.x);
surface.setSize(isSide ? width : viewLength, isSide ? viewLength : width);
},
// @private creates a structure with start, end and step points.
calcEnds: function() {
var me = this,
boundSeries = me.getBoundSeries(),
min = isNaN(me.minimum) ? Infinity : me.minimum,
max = isNaN(me.maximum) ? -Infinity : me.maximum,
zoom = me['zoom' + (me.isSide() ? 'Y' : 'X')],
endsLocked = me.chart.endsLocked,
outfrom, outto, out;
if (endsLocked) {
min = me.prevFrom;
max = me.prevTo;
} else {
// For each series bound to this axis, ask the series for its min/max values
// and use them to find the overall min/max.
boundSeries.each(function(series) {
var minMax = me.isBoundToField(series.xField) ? series.getMinMaxXValues() : series.getMinMaxYValues();
if (minMax[0] < min) {
min = minMax[0];
}
if (minMax[1] > max) {
max = minMax[1];
}
});
if (!isFinite(max)) {
max = me.prevMax || 0;
}
if (!isFinite(min)) {
min = me.prevMin || 0;
}
// If the max isn't on the floor, we want to ceil the max for a better endpoint.
if (min != max && (max != (Math.floor(max)))) {
max = Math.ceil(max);
}
}
// if minimum and maximum are the same in a numeric axis then change the minimum bound.
if (me.type == 'Numeric' && min === max) {
if (max !== 0) {
min = max / 2;
} else {
min = -1;
}
}
out = Ext.draw.Draw.snapEnds(min, max, (me.majorTickSteps !== false ? (me.majorTickSteps +1) : me.steps) * zoom, endsLocked);
outfrom = out.from;
outto = out.to;
if (!endsLocked) {
if (!isNaN(me.maximum)) {
//TODO(nico) users are responsible for their own minimum/maximum values set.
//Clipping should be added to remove lines in the chart which are below the axis.
out.to = me.maximum;
}
if (!isNaN(me.minimum)) {
//TODO(nico) users are responsible for their own minimum/maximum values set.
//Clipping should be added to remove lines in the chart which are below the axis.
out.from = me.minimum;
}
}
//Adjust after adjusting minimum and maximum
out.step = (out.to - out.from) / (outto - outfrom) * out.step;
if (me.adjustMaximumByMajorUnit) {
out.to += out.step;
}
if (me.adjustMinimumByMajorUnit) {
out.from -= out.step;
}
me.prevTo = out.to;
me.prevFrom = out.from;
me.prevMin = min == max? 0 : min;
me.prevMax = max;
return out;
},
/**
* Renders the axis into the screen and updates it's position.
*/
drawAxis: function (init) {
var me = this,
zoomX = me.zoomX,
zoomY = me.zoomY,
x = me.startX * zoomX,
y = me.startY * zoomY,
gutterX = me.chart.maxGutter[0] * zoomX,
gutterY = me.chart.maxGutter[1] * zoomY,
dashSize = me.dashSize,
subDashesX = me.minorTickSteps || 0,
subDashesY = me.minorTickSteps || 0,
isSide = me.isSide(),
viewLength = me.length,
bufferLength = viewLength * me.overflowBuffer,
totalLength = viewLength * (isSide ? zoomY : zoomX),
position = me.position,
inflections = [],
calcLabels = me.calcLabels,
stepCalcs = me.applyData(),
step = stepCalcs.step,
from = stepCalcs.from,
to = stepCalcs.to,
math = Math,
mfloor = math.floor,
mmax = math.max,
mmin = math.min,
mround = math.round,
trueLength, currentX, currentY, startX, startY, path, dashesX, dashesY, delta, skipTicks, i;
me.updateSurfaceBox();
//If no steps are specified
//then don't draw the axis. This generally happens
//when an empty store.
if (me.hidden || me.chart.store.getCount() < 1 || stepCalcs.steps <= 0) {
me.getSurface().items.hide(true);
if (me.displaySprite) {
me.displaySprite.hide(true);
}
return;
}
me.from = stepCalcs.from;
me.to = stepCalcs.to;
if (isSide) {
currentX = mfloor(x) + 0.5;
path = ["M", currentX, y, "l", 0, -totalLength];
trueLength = totalLength - (gutterY * 2);
}
else {
currentY = mfloor(y) + 0.5;
path = ["M", x, currentY, "l", totalLength, 0];
trueLength = totalLength - (gutterX * 2);
}
delta = trueLength * step / (to - from);
skipTicks = me.skipTicks = mfloor(mmax(0, (isSide ? totalLength + me.panY - viewLength - bufferLength : -me.panX - bufferLength)) / delta);
dashesX = mmax(subDashesX +1, 0);
dashesY = mmax(subDashesY +1, 0);
if (calcLabels) {
me.labels = [stepCalcs.from + skipTicks * step];
}
if (isSide) {
currentY = startY = y - gutterY - delta * skipTicks;
currentX = x - ((position == 'left') * dashSize * 2);
while (currentY >= startY - mmin(trueLength, viewLength + bufferLength * 2)) {
path.push("M", currentX, mfloor(currentY) + 0.5, "l", dashSize * 2 + 1, 0);
if (currentY != startY) {
for (i = 1; i < dashesY; i++) {
path.push("M", currentX + dashSize, mfloor(currentY + delta * i / dashesY) + 0.5, "l", dashSize + 1, 0);
}
}
inflections.push([ mfloor(x), mfloor(currentY) ]);
currentY -= delta;
if (calcLabels) {
// Cut everything that is after tenth digit after floating point. This is to get rid of
// rounding errors, i.e. 12.00000000000121212.
me.labels.push(+(me.labels[me.labels.length - 1] + step).toFixed(10));
}
if (delta === 0) {
break;
}
}
if (mround(currentY + delta - (y - gutterY - trueLength))) {
path.push("M", currentX, mfloor(y - totalLength + gutterY) + 0.5, "l", dashSize * 2 + 1, 0);
for (i = 1; i < dashesY; i++) {
path.push("M", currentX + dashSize, mfloor(y - totalLength + gutterY + delta * i / dashesY) + 0.5, "l", dashSize + 1, 0);
}
inflections.push([ mfloor(x), mfloor(currentY) ]);
if (calcLabels) {
// Cut everything that is after tenth digit after floating point. This is to get rid of
// rounding errors, i.e. 12.00000000000121212.
me.labels.push(+(me.labels[me.labels.length - 1] + step).toFixed(10));
}
}
} else {
currentX = startX = x + gutterX + delta * skipTicks;
currentY = y - ((position == 'top') * dashSize * 2);
while (currentX <= startX + mmin(trueLength, viewLength + bufferLength * 2)) {
path.push("M", mfloor(currentX) + 0.5, currentY, "l", 0, dashSize * 2 + 1);
if (currentX != startX) {
for (i = 1; i < dashesX; i++) {
path.push("M", mfloor(currentX - delta * i / dashesX) + 0.5, currentY, "l", 0, dashSize + 1);
}
}
inflections.push([ mfloor(currentX), mfloor(y) ]);
currentX += delta;
if (calcLabels) {
// Cut everything that is after tenth digit after floating point. This is to get rid of
// rounding errors, i.e. 12.00000000000121212.
me.labels.push(+(me.labels[me.labels.length - 1] + step).toFixed(10));
}
if (delta === 0) {
break;
}
}
if (mround(currentX - delta - (x + gutterX + trueLength))) {
path.push("M", mfloor(x + totalLength - gutterX) + 0.5, currentY, "l", 0, dashSize * 2 + 1);
for (i = 1; i < dashesX; i++) {
path.push("M", mfloor(x + totalLength - gutterX - delta * i / dashesX) + 0.5, currentY, "l", 0, dashSize + 1);
}
inflections.push([mfloor(currentX), mfloor(y) ]);
if (calcLabels) {
// Cut everything that is after tenth digit after floating point. This is to get rid of
// rounding errors, i.e. 12.00000000000121212.
me.labels.push(+(me.labels[me.labels.length - 1] + step).toFixed(10));
}
}
}
if (!me.axis) {
me.axis = me.getSurface().add(Ext.apply({
type: 'path',
path: path
}, me.style));
}
me.axis.setAttributes({
path: path,
hidden: false
}, true);
me.inflections = inflections;
if (!init) {
//if grids have been styled in some way
if ( me.grid ||
me.gridStyle.style ||
me.gridStyle.oddStyle.style ||
me.gridStyle.evenStyle.style ) {
me.drawGrid();
}
}
me.axisBBox = me.axis.getBBox();
me.drawLabel();
},
/**
* Renders an horizontal and/or vertical grid into the Surface.
*/
drawGrid: function() {
var me = this,
surface = me.getSurface(),
grid = me.gridStyle.style || me.grid,
odd = me.gridStyle.oddStyle.style || grid.odd,
even = me.gridStyle.evenStyle.style || grid.even,
inflections = me.inflections,
ln = inflections.length - ((odd || even)? 0 : 1),
position = me.position,
gutter = me.chart.maxGutter,
width = me.width - 2,
point, prevPoint,
i = 1,
isSide = me.isSide(),
path = [], styles, lineWidth, dlineWidth,
oddPath = [], evenPath = [];
if ((gutter[1] !== 0 && isSide) ||
(gutter[0] !== 0 && !isSide)) {
i = 0;
ln++;
}
for (; i < ln; i++) {
point = inflections[i];
prevPoint = inflections[i - 1];
if (odd || even) {
path = (i % 2)? oddPath : evenPath;
styles = ((i % 2)? odd : even) || {};
lineWidth = (styles.lineWidth || styles['stroke-width'] || 0) / 2;
dlineWidth = 2 * lineWidth;
if (position == 'left') {
path.push("M", prevPoint[0] + 1 + lineWidth, prevPoint[1] + 0.5 - lineWidth,
"L", prevPoint[0] + 1 + width - lineWidth, prevPoint[1] + 0.5 - lineWidth,
"L", point[0] + 1 + width - lineWidth, point[1] + 0.5 + lineWidth,
"L", point[0] + 1 + lineWidth, point[1] + 0.5 + lineWidth, "Z");
}
else if (position == 'right') {
path.push("M", prevPoint[0] - lineWidth, prevPoint[1] + 0.5 - lineWidth,
"L", prevPoint[0] - width + lineWidth, prevPoint[1] + 0.5 - lineWidth,
"L", point[0] - width + lineWidth, point[1] + 0.5 + lineWidth,
"L", point[0] - lineWidth, point[1] + 0.5 + lineWidth, "Z");
}
else if (position == 'top') {
path.push("M", prevPoint[0] + 0.5 + lineWidth, prevPoint[1] + 1 + lineWidth,
"L", prevPoint[0] + 0.5 + lineWidth, prevPoint[1] + 1 + width - lineWidth,
"L", point[0] + 0.5 - lineWidth, point[1] + 1 + width - lineWidth,
"L", point[0] + 0.5 - lineWidth, point[1] + 1 + lineWidth, "Z");
}
else {
path.push("M", prevPoint[0] + 0.5 + lineWidth, prevPoint[1] - lineWidth,
"L", prevPoint[0] + 0.5 + lineWidth, prevPoint[1] - width + lineWidth,
"L", point[0] + 0.5 - lineWidth, point[1] - width + lineWidth,
"L", point[0] + 0.5 - lineWidth, point[1] - lineWidth, "Z");
}
} else {
if (position == 'left') {
path = path.concat(["M", point[0] + 0.5, point[1] + 0.5, "l", width, 0]);
}
else if (position == 'right') {
path = path.concat(["M", point[0] - 0.5, point[1] + 0.5, "l", -width, 0]);
}
else if (position == 'top') {
path = path.concat(["M", point[0] + 0.5, point[1] + 0.5, "l", 0, width]);
}
else {
path = path.concat(["M", point[0] + 0.5, point[1] - 0.5, "l", 0, -width]);
}
}
}
if (odd || even) {
if (oddPath.length) {
if (!me.gridOdd && oddPath.length) {
me.gridOdd = surface.add({
type: 'path',
path: oddPath
});
}
me.gridOdd.setAttributes(Ext.apply({
path: oddPath,
hidden: false
}, odd || {}), true);
}
if (evenPath.length) {
if (!me.gridEven) {
me.gridEven = surface.add({
type: 'path',
path: evenPath
});
}
me.gridEven.setAttributes(Ext.apply({
path: evenPath,
hidden: false
}, even || {}), true);
}
}
else {
if (path.length) {
if (!me.gridLines) {
me.gridLines = me.getSurface().add({
type: 'path',
path: path,
"stroke-width": me.lineWidth || 1,
stroke: me.gridColor || '#ccc'
});
}
me.gridLines.setAttributes({
hidden: false,
path: path
}, true);
}
else if (me.gridLines) {
me.gridLines.hide(true);
}
}
},
isPannable: function() {
var me = this,
length = me.length,
isSide = me.isSide(),
math = Math,
ceil = math.ceil,
floor = math.floor,
matrix = me.getTransformMatrix();
return matrix && (
(isSide ? ceil(matrix.y(0, 0)) < 0 : floor(matrix.x(length, 0)) > length) ||
(isSide ? floor(matrix.y(0, length)) > length : ceil(matrix.x(0, 0)) < 0)
);
},
// @private
getOrCreateLabel: function (i, text) {
if(this.image){
return this.getOrCreateImageLabel(i, text);
}else{
return this.getOrCreateTextLabel(i, text);
}
},
//@private
getOrCreateTextLabel: function(i, text) {
var me = this,
labelGroup = me.labelGroup,
textLabel = labelGroup.getAt(i),
surface,
labelStyle = me.labelStyle.style;
if (textLabel) {
if (text != textLabel.attr.text) {
textLabel.setAttributes(Ext.apply({
text: text
}, labelStyle), true);
textLabel._bbox = textLabel.getBBox();
}
}
else {
surface = me.getLabelSurface();
textLabel = surface.add(Ext.apply({
group: labelGroup,
type: 'text',
x: 0,
y: 0,
text: text
}, labelStyle));
surface.renderItem(textLabel);
textLabel._bbox = textLabel.getBBox();
}
//get untransformed bounding box
if (labelStyle.rotation) {
textLabel.setAttributes({
rotation: {
degrees: 0
}
}, true);
textLabel._ubbox = textLabel.getBBox();
textLabel.setAttributes(labelStyle, true);
} else {
textLabel._ubbox = textLabel._bbox;
}
return textLabel;
},
// @private
getOrCreateImageLabel: function (i, text) {
var me = this,
labelGroup = me.labelGroup,
textLabel = labelGroup.getAt(i),
surface,
labelStyle = me.labelStyle.style;
if (textLabel) {
if (text != textLabel.attr.text) {
textLabel.setAttributes(Ext.apply({
src: text
}, labelStyle), true);
textLabel._bbox = textLabel.getBBox();
}
}
else {
surface = me.getLabelSurface();
textLabel = surface.add(Ext.apply({
group: labelGroup,
type: 'image',
x: 0,
y: 0,
width: 20,
height: 20,
src: text
}, labelStyle));
surface.renderItem(textLabel);
textLabel._bbox = textLabel.getBBox();
}
//get untransformed bounding box
if (labelStyle.rotation) {
textLabel.setAttributes({
rotation: {
degrees: 0
}
}, true);
textLabel._ubbox = textLabel.getBBox();
textLabel.setAttributes(labelStyle, true);
} else {
textLabel._ubbox = textLabel._bbox;
}
return textLabel;
},
rect2pointArray: function(sprite) {
var surface = this.getSurface(),
rect = surface.getBBox(sprite, true),
p1 = [rect.x, rect.y],
p1p = p1.slice(),
p2 = [rect.x + rect.width, rect.y],
p2p = p2.slice(),
p3 = [rect.x + rect.width, rect.y + rect.height],
p3p = p3.slice(),
p4 = [rect.x, rect.y + rect.height],
p4p = p4.slice(),
matrix = sprite.matrix;
//transform the points
p1[0] = matrix.x.apply(matrix, p1p);
p1[1] = matrix.y.apply(matrix, p1p);
p2[0] = matrix.x.apply(matrix, p2p);
p2[1] = matrix.y.apply(matrix, p2p);
p3[0] = matrix.x.apply(matrix, p3p);
p3[1] = matrix.y.apply(matrix, p3p);
p4[0] = matrix.x.apply(matrix, p4p);
p4[1] = matrix.y.apply(matrix, p4p);
return [p1, p2, p3, p4];
},
intersect: function(l1, l2) {
var r1 = this.rect2pointArray(l1),
r2 = this.rect2pointArray(l2);
return !!Ext.draw.Draw.intersect(r1, r2).length;
},
drawHorizontalLabels: function() {
var me = this,
labelConf = me.labelStyle.style,
renderer = labelConf.renderer || function(v) {
return v;
},
math = Math,
floor = math.floor,
max = math.max,
axes = me.chart.axes,
position = me.position,
inflections = me.inflections,
ln = inflections.length,
labels = me.labels,
skipTicks = me.skipTicks,
maxHeight = 0,
ratio,
bbox, point, prevLabel,
textLabel, text,
last, x, y, i, firstLabel;
if (!me.calcLabels && skipTicks) {
labels = labels.slice(skipTicks);
ln -= skipTicks;
}
last = ln - 1;
//get a reference to the first text label dimensions
point = inflections[0];
firstLabel = me.getOrCreateLabel(0, renderer(labels[0]));
ratio = math.abs(math.sin(labelConf.rotate && (labelConf.rotate.degrees * math.PI / 180) || 0)) >> 0;
for (i = 0; i < ln; i++) {
point = inflections[i];
text = renderer(labels[i]);
textLabel = me.getOrCreateLabel(i, text);
bbox = textLabel._bbox;
maxHeight = max(maxHeight, bbox.height + me.dashSize + (labelConf.padding || 0));
x = floor(point[0] - (ratio? bbox.height : bbox.width) / 2);
if (me.chart.maxGutter[0] == 0) {
if (i == 0 && axes.findIndex('position', 'left') == -1) {
x = point[0];
}
else if (i == last && axes.findIndex('position', 'right') == -1) {
x = point[0] - bbox.width;
}
}
if (position == 'top') {
y = point[1] - (me.dashSize * 2) - labelConf.padding - (bbox.height / 2);
}
else {
y = point[1] + (me.dashSize * 2) + labelConf.padding + (bbox.height / 2);
}
if (!me.isPannable()) {
x += me.x;
y += me.y;
}
textLabel.setAttributes({
hidden: false,
x: x,
y: y
}, true);
if (labelConf.rotate) {
textLabel.setAttributes(labelConf, true);
}
// Skip label if there isn't available minimum space
if (i != 0 && (me.intersect(textLabel, prevLabel)
|| me.intersect(textLabel, firstLabel))) {
textLabel.hide(true);
continue;
}
prevLabel = textLabel;
}
return maxHeight;
},
drawVerticalLabels: function() {
var me = this,
labelConf = me.labelStyle.style,
renderer = labelConf.renderer || function(v) {
return v;
},
inflections = me.inflections,
position = me.position,
ln = inflections.length,
labels = me.labels,
skipTicks = me.skipTicks,
maxWidth = 0,
math = Math,
max = math.max,
floor = math.floor,
ceil = math.ceil,
axes = me.chart.axes,
gutterY = me.chart.maxGutter[1],
bbox, point, prevLabel,
textLabel, text,
last, x, y, i;
if (!me.calcLabels && skipTicks) {
labels = labels.slice(skipTicks);
ln -= skipTicks;
}
last = ln;
for (i = 0; i < last; i++) {
point = inflections[i];
text = renderer(labels[i]);
textLabel = me.getOrCreateLabel(i, text);
bbox = textLabel._bbox;
maxWidth = max(maxWidth, bbox.width + me.dashSize + (labelConf.padding || 0));
y = point[1];
if (gutterY < bbox.height / 2) {
if (i == last - 1 && axes.findIndex('position', 'top') == -1) {
y += ceil(bbox.height / 2);
}
else if (i == 0 && axes.findIndex('position', 'bottom') == -1) {
y -= floor(bbox.height / 2);
}
}
if (position == 'left') {
x = point[0] - bbox.width - me.dashSize - (labelConf.padding || 0) - 2;
}
else {
x = point[0] + me.dashSize + (labelConf.padding || 0) + 2;
}
if (!me.isPannable()) {
x += me.x;
y += me.y + me.panY;
}
textLabel.setAttributes(Ext.apply({
hidden: false,
x: x,
y: y
}, labelConf), true);
// Skip label if there isn't available minimum space
if (i != 0 && me.intersect(textLabel, prevLabel)) {
textLabel.hide(true);
continue;
}
prevLabel = textLabel;
}
return maxWidth;
},
/**
* Renders the labels in the axes.
*/
drawLabel: function() {
if (!this.inflections) {
return 0;
}
var me = this,
labelGroup = me.labelGroup,
inflections = me.inflections,
surface = me.getLabelSurface(),
maxWidth = 0,
maxHeight = 0,
ln, i;
// If we are switching between rendering labels to the axis surface and the main
// chart surface, then we need to blow away all existing labels and let them get
// re-created on the new surface
if (me.lastLabelSurface !== surface) {
labelGroup.each(function(sprite) {
sprite.destroy();
});
labelGroup.clear();
me.lastLabelSurface = surface;
}
if (me.isSide()) {
maxWidth = me.drawVerticalLabels();
} else {
maxHeight = me.drawHorizontalLabels();
}
// Hide unused label sprites
ln = labelGroup.getCount();
i = inflections.length;
for (; i < ln; i++) {
labelGroup.getAt(i).hide(true);
}
me.bbox = {};
Ext.apply(me.bbox, me.axisBBox);
me.bbox.height = maxHeight;
me.bbox.width = maxWidth;
if (Ext.isString(me.title)) {
me.drawTitle(maxWidth, maxHeight);
}
},
/**
* @private
* Returns the surface onto which axis tick labels should be rendered. Differs between
* when the axis is in its initial non-zoomed state (uses the main chart surface so the
* labels can display outside the axis clipping area) and when it is zoomed so it overflows
* (uses the axis surface so the labels are clipped and panned along with the axis grid).
* @return {Ext.draw.Surface}
*/
getLabelSurface: function() {
var me = this;
return me.isPannable() ? me.getSurface() : me.chart.getSurface('main');
},
/**
* Updates the {@link #title} of this axis.
* @param {String} title
*/
setTitle: function(title) {
this.title = title;
this.drawLabel();
},
// @private draws the title for the axis.
drawTitle: function(maxWidth, maxHeight) {
var me = this,
position = me.position,
surface = me.chart.getSurface('main'), //title is drawn on main surface so it doesn't get transformed
displaySprite = me.displaySprite,
title = me.title,
rotate = me.isSide(),
x = me.startX + me.x,
y = me.startY + me.y,
base, bbox, pad;
if (displaySprite) {
displaySprite.setAttributes({text: title}, true);
} else {
base = {
type: 'text',
x: 0,
y: 0,
text: title
};
displaySprite = me.displaySprite = surface.add(Ext.apply(base, me.titleStyle.style, me.labelTitle));
surface.renderItem(displaySprite);
}
bbox = displaySprite.getBBox();
pad = me.dashSize + (me.titleStyle.style.padding || 0);
if (rotate) {
y -= ((me.length / 2) - (bbox.height / 2));
if (position == 'left') {
x -= (maxWidth + pad + (bbox.width / 2));
}
else {
x += (maxWidth + pad + bbox.width - (bbox.width / 2));
}
me.bbox.width += bbox.width + 10;
}
else {
x += (me.length / 2) - (bbox.width * 0.5);
if (position == 'top') {
y -= (maxHeight + pad + (bbox.height * 0.3));
}
else {
y += (maxHeight + pad + (bbox.height * 0.8));
}
me.bbox.height += bbox.height + 10;
}
displaySprite.setAttributes({
hidden: false,
translate: {
x: x,
y: y
}
}, true);
},
/**
* Return the Series object(s) that are bound to this axis.
* @return Ext.util.MixedCollection
*/
getBoundSeries: function() {
var me = this,
series = me.chart.series;
return series.filterBy(function(s) {
var seriesFields = [].concat(s.xField, s.yField),
i = seriesFields.length;
while (i--) {
if (me.isBoundToField(seriesFields[i])) {
return true;
}
}
return false;
});
},
/**
* Determine whether this axis is bound to the given field name.
* @param {String} field
* @return {Boolean}
*/
isBoundToField: function(field) {
var fields = this.fields,
i = fields.length;
while(i--) {
if (fields[i] === field) {
return true;
}
}
return false;
}
});
/**
* @class Ext.chart.axis.Category
* @extends Ext.chart.axis.Axis
*
* A type of axis that displays items in categories. This axis is generally used to
* display categorical information like names of items, month names, quarters, etc.
* but no quantitative values. For that other type of information <em>Number</em>
* axis are more suitable.
*
* As with other axis you can set the position of the axis and its title. For example:
*
* {@img Ext.chart.axis.Category/Ext.chart.axis.Category.png Ext.chart.axis.Category chart axis}
*
* var store = new Ext.data.JsonStore({
* fields: ['name', 'data1', 'data2', 'data3', 'data4', 'data5'],
* data: [
* {'name':'metric one', 'data1':10, 'data2':12, 'data3':14, 'data4':8, 'data5':13},
* {'name':'metric two', 'data1':7, 'data2':8, 'data3':16, 'data4':10, 'data5':3},
* {'name':'metric three', 'data1':5, 'data2':2, 'data3':14, 'data4':12, 'data5':7},
* {'name':'metric four', 'data1':2, 'data2':14, 'data3':6, 'data4':1, 'data5':23},
* {'name':'metric five', 'data1':27, 'data2':38, 'data3':36, 'data4':13, 'data5':33}
* ]
* });
*
* new Ext.chart.Chart({
* renderTo: Ext.getBody(),
* width: 500,
* height: 300,
* store: store,
* axes: [{
* type: 'Numeric',
* grid: true,
* position: 'left',
* fields: ['data1', 'data2', 'data3', 'data4', 'data5'],
* title: 'Sample Values',
* grid: {
* odd: {
* opacity: 1,
* fill: '#ddd',
* stroke: '#bbb',
* 'stroke-width': 1
* }
* },
* minimum: 0,
* adjustMinimumByMajorUnit: false
* }, {
* type: 'Category',
* position: 'bottom',
* fields: ['name'],
* title: 'Sample Metrics',
* grid: true,
* label: {
* rotate: {
* degrees: 315
* }
* }
* }],
* series: [{
* type: 'area',
* highlight: false,
* axis: 'left',
* xField: 'name',
* yField: ['data1', 'data2', 'data3', 'data4', 'data5'],
* style: {
* opacity: 0.93
* }
* }]
* });
*
* In this example with set the category axis to the bottom of the surface, bound the axis to
* the <em>name</em> property and set as title <em>Month of the Year</em>.
*/
Ext.chart.axis.Category = Ext.extend(Ext.chart.axis.Axis, {
/**
* @cfg {Array} categoryNames
* A list of category names to display along this axis.
*/
categoryNames: null,
/**
* @cfg {Boolean} calculateCategoryCount
* Indicates whether or not to calculate the number of categories (ticks and
* labels) when there is not enough room to display all labels on the axis.
* If set to true, the axis will determine the number of categories to plot.
* If not, all categories will be plotted.
*/
calculateCategoryCount: false,
// @private creates an array of labels to be used when rendering.
setLabels: function() {
var store = this.chart.store,
fields = this.fields,
ln = fields.length,
i;
this.labels = [];
store.each(function(record) {
for (i = 0; i < ln; i++) {
this.labels.push(record.get(fields[i]));
}
}, this);
},
// @private calculates labels positions and marker positions for rendering.
applyData: function() {
Ext.chart.axis.Category.superclass.applyData.call(this);
this.setLabels();
var count = this.chart.store.getCount();
return {
from: 0,
to: count - 1,
power: 1,
step: 1,
steps: count - 1
};
}
});
/**
* @class Ext.chart.axis.Gauge
* @extends Ext.chart.axis.Abstract
*
* Gauge Axis is the axis to be used with a Gauge series. The Gauge axis
* displays numeric data from an interval defined by the `minimum`, `maximum` and
* `step` configuration properties. The placement of the numeric data can be changed
* by altering the `margin` option that is set to `10` by default.
*
* A possible configuration for this axis would look like:
*
* axes: [{
* type: 'gauge',
* position: 'gauge',
* minimum: 0,
* maximum: 100,
* steps: 10,
* margin: 7
* }],
*/
Ext.chart.axis.Gauge = Ext.extend(Ext.chart.axis.Abstract, {
/**
* @cfg {Number} minimum (required) the minimum value of the interval to be displayed in the axis.
*/
/**
* @cfg {Number} maximum (required) the maximum value of the interval to be displayed in the axis.
*/
/**
* @cfg {Number} steps (optional) the number of steps and tick marks to add to the interval. Default's 10.
*/
/**
* @cfg {Number} margin (optional) the offset positioning of the tick marks and labels in pixels. Default's 10.
*/
position: 'gauge',
drawAxis: function(init) {
var me = this,
chart = me.chart,
surface = me.getSurface(),
bbox = chart.chartBBox,
centerX = bbox.x + (bbox.width / 2),
centerY = bbox.y + bbox.height,
margin = me.margin || 10,
rho = Math.min(bbox.width, 2 * bbox.height) /2 + margin,
sprites = [], sprite,
steps = me.steps,
i, pi = Math.PI,
cos = Math.cos,
sin = Math.sin;
if (me.sprites && !chart.resizing) {
me.drawLabel();
return;
}
me.updateSurfaceBox();
if (me.margin >= 0) {
if (!me.sprites) {
//draw circles
for (i = 0; i <= steps; i++) {
sprite = surface.add({
type: 'path',
path: ['M', centerX + (rho - margin) * cos(i / steps * pi - pi),
centerY + (rho - margin) * sin(i / steps * pi - pi),
'L', centerX + rho * cos(i / steps * pi - pi),
centerY + rho * sin(i / steps * pi - pi), 'Z'],
stroke: '#ccc'
});
sprite.setAttributes(Ext.apply(me.style || {}, {
hidden: false
}), true);
sprites.push(sprite);
}
} else {
sprites = me.sprites;
//draw circles
for (i = 0; i <= steps; i++) {
sprites[i].setAttributes({
path: ['M', centerX + (rho - margin) * cos(i / steps * pi - pi),
centerY + (rho - margin) * sin(i / steps * pi - pi),
'L', centerX + rho * cos(i / steps * pi - pi),
centerY + rho * sin(i / steps * pi - pi), 'Z']
}, true);
}
}
}
me.sprites = sprites;
me.drawLabel();
if (me.title) {
me.drawTitle();
}
},
drawTitle: function() {
var me = this,
chart = me.chart,
surface = me.getSurface(),
bbox = chart.chartBBox,
labelSprite = me.titleSprite,
labelBBox;
if (!labelSprite) {
me.titleSprite = labelSprite = surface.add({
type: 'text',
zIndex: 2
});
}
labelSprite.setAttributes(Ext.apply({
text: me.title
}, Ext.apply(me.titleStyle.style || {}, me.label || {})), true);
labelBBox = labelSprite.getBBox();
labelSprite.setAttributes({
x: bbox.x + (bbox.width / 2) - (labelBBox.width / 2),
y: bbox.y + bbox.height - (labelBBox.height / 2) - 4
}, true);
},
/**
* Updates the {@link #title} of this axis.
* @param {String} title
*/
setTitle: function(title) {
this.title = title;
this.drawTitle();
},
drawLabel: function() {
var me = this,
chart = me.chart,
surface = me.getSurface(),
bbox = chart.chartBBox,
centerX = bbox.x + (bbox.width / 2),
centerY = bbox.y + bbox.height,
margin = me.margin || 10,
rho = Math.min(bbox.width, 2 * bbox.height) /2 + 2 * margin,
round = Math.round,
labelArray = [], label,
maxValue = me.maximum || 0,
steps = me.steps, i = 0,
adjY,
pi = Math.PI,
cos = Math.cos,
sin = Math.sin,
labelConf = me.labelStyle.style,
renderer = labelConf.renderer || function(v) { return v; };
if (!me.labelArray) {
//draw scale
for (i = 0; i <= steps; i++) {
// TODO Adjust for height of text / 2 instead
adjY = (i === 0 || i === steps) ? 7 : 0;
label = surface.add({
type: 'text',
text: renderer(round(i / steps * maxValue)),
x: centerX + rho * cos(i / steps * pi - pi),
y: centerY + rho * sin(i / steps * pi - pi) - adjY,
'text-anchor': 'middle',
'stroke-width': 0.2,
zIndex: 10,
stroke: '#333'
});
label.setAttributes(Ext.apply(me.labelStyle.style || {}, {
hidden: false
}), true);
labelArray.push(label);
}
}
else {
labelArray = me.labelArray;
//draw values
for (i = 0; i <= steps; i++) {
// TODO Adjust for height of text / 2 instead
adjY = (i === 0 || i === steps) ? 7 : 0;
labelArray[i].setAttributes({
text: renderer(round(i / steps * maxValue)),
x: centerX + rho * cos(i / steps * pi - pi),
y: centerY + rho * sin(i / steps * pi - pi) - adjY
}, true);
}
}
me.labelArray = labelArray;
}
});
/**
* @class Ext.chart.axis.Numeric
* @extends Ext.chart.axis.Axis
*
* An axis to handle numeric values. This axis is used for quantitative data as
* opposed to the category axis. You can set mininum and maximum values to the
* axis so that the values are bound to that. If no values are set, then the
* scale will auto-adjust to the values.
*
* {@img Ext.chart.axis.Numeric/Ext.chart.axis.Numeric.png Ext.chart.axis.Numeric chart axis}
*
* For example:
*
* var store = new Ext.data.JsonStore({
* fields: ['name', 'data1', 'data2', 'data3', 'data4', 'data5'],
* data: [
* {'name':'metric one', 'data1':10, 'data2':12, 'data3':14, 'data4':8, 'data5':13},
* {'name':'metric two', 'data1':7, 'data2':8, 'data3':16, 'data4':10, 'data5':3},
* {'name':'metric three', 'data1':5, 'data2':2, 'data3':14, 'data4':12, 'data5':7},
* {'name':'metric four', 'data1':2, 'data2':14, 'data3':6, 'data4':1, 'data5':23},
* {'name':'metric five', 'data1':27, 'data2':38, 'data3':36, 'data4':13, 'data5':33}
* ]
* });
*
* new Ext.chart.Chart({
* renderTo: Ext.getBody(),
* width: 500,
* height: 300,
* store: store,
* axes: [{
* type: 'Numeric',
* grid: true,
* position: 'left',
* fields: ['data1', 'data2', 'data3', 'data4', 'data5'],
* title: 'Sample Values',
* grid: {
* odd: {
* opacity: 1,
* fill: '#ddd',
* stroke: '#bbb',
* 'stroke-width': 1
* }
* },
* minimum: 0,
* adjustMinimumByMajorUnit: 0
* }, {
* type: 'Category',
* position: 'bottom',
* fields: ['name'],
* title: 'Sample Metrics',
* grid: true,
* label: {
* rotate: {
* degrees: 315
* }
* }
* }],
* series: [{
* type: 'area',
* highlight: false,
* axis: 'left',
* xField: 'name',
* yField: ['data1', 'data2', 'data3', 'data4', 'data5'],
* style: {
* opacity: 0.93
* }
* }]
* });
*
* In this example we create an axis of Numeric type. We set a minimum value so that
* even if all series have values greater than zero, the grid starts at zero. We bind
* the axis onto the left part of the surface by setting <em>position</em> to <em>left</em>.
* We bind three different store fields to this axis by setting <em>fields</em> to an array.
* We set the title of the axis to <em>Number of Hits</em> by using the <em>title</em> property.
* We use a <em>grid</em> configuration to set odd background rows to a certain style and even rows
* to be transparent/ignored.
*
* @constructor
*/
Ext.chart.axis.Numeric = Ext.extend(Ext.chart.axis.Axis, {
type: 'numeric',
calcLabels: true,
constructor: function(config) {
var me = this,
label, f;
Ext.chart.axis.Numeric.superclass.constructor.apply(me, [config]);
label = me.label || {};
if (me.roundToDecimal === false) {
return;
}
if (label.renderer) {
f = label.renderer;
label.renderer = function(v) {
return me.roundToDecimal( f(v), me.decimals );
};
} else {
label.renderer = function(v) {
return me.roundToDecimal(v, me.decimals);
};
}
},
roundToDecimal: function(v, dec) {
var val = Math.pow(10, dec || 0);
return ((v * val) >> 0) / val;
},
/**
* @cfg {Number} minimum
* The minimum value drawn by the axis. If not set explicitly, the axis
* minimum will be calculated automatically.
*/
minimum: NaN,
/**
* @cfg {Number} maximum
* The maximum value drawn by the axis. If not set explicitly, the axis
* maximum will be calculated automatically.
*/
maximum: NaN,
/**
* @cfg {Number} decimals
* The number of decimals to round the value to.
* Default's 2.
*/
decimals: 2,
/**
* @cfg {String} scale
* The scaling algorithm to use on this axis. May be "linear" or
* "logarithmic".
*/
scale: "linear",
/**
* @cfg {String} position
* Indicates the position of the axis relative to the chart
*/
position: 'left',
/**
* @cfg {Boolean} adjustMaximumByMajorUnit
* Indicates whether to extend maximum beyond data's maximum to the nearest
* majorUnit.
*/
adjustMaximumByMajorUnit: false,
/**
* @cfg {Boolean} adjustMinimumByMajorUnit
* Indicates whether to extend the minimum beyond data's minimum to the
* nearest majorUnit.
*/
adjustMinimumByMajorUnit: false,
// @private apply data.
applyData: function() {
Ext.chart.axis.Numeric.superclass.applyData.apply(this, arguments);
return this.calcEnds();
}
});
/**
* @class Ext.chart.axis.Radial
* @extends Ext.chart.axis.Abstract
*
* Radial Axis is the axis to be used with a Radar Series. The Radial axis
* is a circular display of numerical data by steps, with the number of circles
* equivalent to the defined number of `steps`. Given the maximum data value,
* the axis will compute step values depending on the number of defined `steps`.
*
* A possible configuration for this axis would look like:
*
* axes: [{
* steps: 5,
* type: 'Radial',
* position: 'radial',
* label: {
* display: 'none'
* }
* }]
*/
Ext.chart.axis.Radial = Ext.extend(Ext.chart.axis.Abstract, {
/**
* @cfg {Number} maximum (optional) the maximum value to be displayed in the axis.
*/
/**
* @cfg {Number} steps (required) the number of steps to add to the radial axis.
*/
position: 'radial',
rotation: 0,
drawAxis: function(init) {
var me = this,
chart = me.chart,
surface = me.getSurface(),
bbox = chart.chartBBox,
store = chart.store,
l = store.getCount(),
centerX = bbox.x + (bbox.width / 2),
centerY = bbox.y + (bbox.height / 2),
math = Math,
mmax = math.max,
rho = math.min(bbox.width, bbox.height) /2,
sprites = [], sprite,
steps = me.steps,
rotation = -me.rotation,
rad = Ext.draw.Draw.rad,
cos = math.cos,
sin = math.sin,
i, angle;
if (!l) {
surface.items.hide(true);
return;
}
me.updateSurfaceBox();
me.centerX = centerX;
me.centerY = centerY;
if (!me.sprites) {
//draw circles
for (i = 1; i <= steps; i++) {
sprite = surface.add(Ext.apply(me.style || {}, {
type: 'circle',
x: centerX,
y: centerY,
'stroke-width': 1.5,
radius: mmax(rho * i / steps, 0),
stroke: '#ccc'
}));
sprite.setAttributes({
hidden: false
}, true);
sprites.push(sprite);
}
//draw lines
store.each(function(rec, i) {
angle = rad(rotation + i / l * 360);
sprite = surface.add(Ext.apply(me.style || {}, {
type: 'path',
path: ['M', centerX, centerY, 'L', centerX + rho * cos(angle), centerY + rho * sin(angle), 'Z']
}));
sprite.setAttributes({
hidden: false
}, true);
sprites.push(sprite);
});
} else {
sprites = me.sprites;
//draw circles
for (i = 0; i < steps; i++) {
sprites[i].setAttributes({
hidden: false,
x: centerX,
y: centerY,
radius: mmax(rho * (i + 1) / steps, 0)
}, true);
}
//draw lines
store.each(function(rec, j) {
angle = rad(rotation + j / l * 360);
sprites[i + j].setAttributes(Ext.apply(me.style || {}, {
hidden: false,
path: ['M', centerX, centerY, 'L', centerX + rho * cos(angle), centerY + rho * sin(angle), 'Z']
}), true);
});
}
me.sprites = sprites;
me.drawLabel();
},
drawLabel: function() {
var me = this,
chart = me.chart,
surface = me.getSurface(),
bbox = chart.chartBBox,
store = chart.store,
centerX = me.centerX,
centerY = me.centerY,
rho = Math.min(bbox.width, bbox.height) /2,
max = Math.max, round = Math.round,
labelArray = [], label,
fields = [], nfields,
categories = [], xField,
aggregate = !me.maximum,
maxValue = me.maximum || 0,
steps = me.steps, i = 0, j, dx, dy,
rotation = -me.rotation,
rad = Ext.draw.Draw.rad,
cos = Math.cos, sin = Math.sin,
display = me.label.display,
draw = display !== 'none',
labelGroup = me.labelGroup,
labelStyle = me.labelStyle.style,
categoriesStyle = Ext.apply({}, labelStyle),
margin = 10,
angle;
if (!draw) {
return;
}
//get all rendered fields
chart.series.each(function(series) {
fields.push(series.yField);
xField = series.xField;
});
//get maxValue to interpolate
store.each(function(record, i) {
if (aggregate) {
for (i = 0, nfields = fields.length; i < nfields; i++) {
maxValue = max(+record.get(fields[i]), maxValue);
}
}
categories.push(record.get(xField));
});
if (!me.labelArray) {
if (display != 'categories') {
//draw scale
for (i = 1; i <= steps; i++) {
label = surface.add({
group: labelGroup,
type: 'text',
text: round(i / steps * maxValue),
x: centerX,
y: centerY - rho * i / steps
});
if (labelStyle) {
label.setAttributes(labelStyle, true);
}
labelArray.push(label);
}
}
if (display != 'scale') {
//TODO(nico): ignore translate property since positioning is radial.
delete categoriesStyle.translate;
//draw text
for (j = 0, steps = categories.length; j < steps; j++) {
angle = rad(rotation + j / steps * 360);
dx = cos(angle) * (rho + margin);
dy = sin(angle) * (rho + margin);
label = surface.add({
group: labelGroup,
type: 'text',
text: categories[j],
x: centerX + dx,
y: centerY + dy,
'text-anchor': dx * dx <= 0.001? 'middle' : (dx < 0? 'end' : 'start')
});
if (labelStyle) {
label.setAttributes(categoriesStyle, true);
}
labelArray.push(label);
}
}
}
else {
labelArray = me.labelArray;
if (display != 'categories') {
//draw values
for (i = 0; i < steps; i++) {
labelArray[i].setAttributes({
text: round((i + 1) / steps * maxValue),
x: centerX,
y: centerY - rho * (i + 1) / steps,
hidden: false
}, true);
}
}
if (display != 'scale') {
//draw text
for (j = 0, steps = categories.length; j < steps; j++) {
angle = rad(rotation + j / steps * 360);
dx = cos(angle) * (rho + margin);
dy = sin(angle) * (rho + margin);
if (labelArray[i + j]) {
labelArray[i + j].setAttributes({
type: 'text',
text: categories[j],
x: centerX + dx,
y: centerY + dy,
'text-anchor': dx * dx <= 0.001? 'middle' : (dx < 0? 'end' : 'start'),
hidden: false
}, true);
}
}
}
}
me.labelArray = labelArray;
},
getSurface: function() {
return this.chart.getSurface('main');
},
reset: function() {
this.rotation = 0;
Ext.chart.axis.Radial.superclass.reset.call(this);
}
});
/**
* @class Ext.chart.axis.Time
* @extends Ext.chart.axis.Axis
*
* A type of axis whose units are measured in time values. Use this axis
* for listing dates that you will want to group or dynamically change.
* If you just want to display dates as categories then use the
* Category class for axis instead.
*
* For example:
*
* axes: [{
* type: 'Time',
* position: 'bottom',
* fields: 'date',
* title: 'Day',
* dateFormat: 'M d',
* groupBy: 'year,month,day',
* aggregateOp: 'sum',
*
* constrain: true,
* fromDate: new Date('1/1/11'),
* toDate: new Date('1/7/11')
* }]
*
* In this example we're creating a time axis that has as title *Day*.
* The field the axis is bound to is `date`.
* The date format to use to display the text for the axis labels is `M d`
* which is a three letter month abbreviation followed by the day number.
* The time axis will show values for dates between `fromDate` and `toDate`.
* Since `constrain` is set to true all other values for other dates not between
* the fromDate and toDate will not be displayed.
*
* @constructor
*/
Ext.chart.axis.Time = Ext.extend(Ext.chart.axis.Category, {
/**
* @cfg {Boolean} calculateByLabelSize
* The minimum value drawn by the axis. If not set explicitly, the axis
* minimum will be calculated automatically.
*/
calculateByLabelSize: true,
/**
* @cfg {String/Boolean} dateFormat
* Indicates the format the date will be rendered on.
* For example: 'M d' will render the dates as 'Jan 30', etc.
*/
dateFormat: false,
/**
* Indicates the time unit to use for each step. Can be 'day', 'month', 'year' or a comma-separated combination of all of them.
* Default's 'year,month,day'.
*
* @cfg groupBy
* @type {String}
*/
groupBy: 'year,month,day',
/**
* Aggregation operation when grouping. Possible options are 'sum', 'avg', 'max', 'min'. Default's 'sum'.
*
* @cfg aggregateOp
* @type {String}
*/
aggregateOp: 'sum',
/**
* The starting date for the time axis.
* @cfg fromDate
* @type Date
*/
fromDate: false,
/**
* The ending date for the time axis.
* @cfg toDate
* @type Date
*/
toDate: false,
/**
* An array with two components: The first is the unit of the step (day, month, year, etc). The second one is the number of units for the step (1, 2, etc.).
* Default's [Ext.Date.DAY, 1].
*
* @cfg step
* @type Array
*/
step: [Date.DAY, 1],
/**
* If true, the values of the chart will be rendered only if they belong between the fromDate and toDate.
* If false, the time axis will adapt to the new values by adding/removing steps.
* Default's [Ext.Date.DAY, 1].
*
* @cfg constrain
* @type Boolean
*/
constrain: false,
// @private a wrapper for date methods.
dateMethods: {
'year': function(date) {
return date.getFullYear();
},
'month': function(date) {
return date.getMonth() + 1;
},
'day': function(date) {
return date.getDate();
},
'hour': function(date) {
return date.getHours();
},
'minute': function(date) {
return date.getMinutes();
},
'second': function(date) {
return date.getSeconds();
},
'millisecond': function(date) {
return date.getMilliseconds();
}
},
// @private holds aggregate functions.
aggregateFn: (function() {
var etype = (function() {
var rgxp = /^\[object\s(.*)\]$/,
toString = Object.prototype.toString;
return function(e) {
return toString.call(e).match(rgxp)[1];
};
})();
return {
'sum': function(list) {
var i = 0,
l = list.length,
acum = 0;
if (!list.length || etype(list[0]) != 'Number') {
return list[0];
}
for (; i < l; i++) {
acum += list[i];
}
return acum;
},
'max': function(list) {
if (!list.length || etype(list[0]) != 'Number') {
return list[0];
}
return Math.max.apply(Math, list);
},
'min': function(list) {
if (!list.length || etype(list[0]) != 'Number') {
return list[0];
}
return Math.min.apply(Math, list);
},
'avg': function(list) {
var i = 0,
l = list.length,
acum = 0;
if (!list.length || etype(list[0]) != 'Number') {
return list[0];
}
for (; i < l; i++) {
acum += list[i];
}
return acum / l;
}
};
})(),
// @private normalized the store to fill date gaps in the time interval.
constrainDates: function() {
var fromDate = Ext.Date.clone(this.fromDate),
toDate = Ext.Date.clone(this.toDate),
step = this.step,
fields = this.fields,
field = fields.length ? fields[0] : fields,
store = this.chart.store,
newStore = new Ext.data.Store({
model: store.model
}),
record, recObj;
var getRecordByDate = (function() {
var index = 0,
l = store.getCount();
return function(date) {
var rec, recDate;
for (; index < l; index++) {
rec = store.getAt(index);
recDate = rec.get(field);
if (+recDate > +date) {
return false;
} else if (+recDate == +date) {
return rec;
}
}
return false;
};
})();
if (!this.constrain) {
this.chart.filteredStore = this.chart.store;
return;
}
while (+fromDate <= +toDate) {
record = getRecordByDate(fromDate);
recObj = {};
if (record) {
newStore.add(record.data);
} else {
newStore.model.prototype.fields.each(function(f) {
recObj[f.name] = false;
});
recObj.date = fromDate;
newStore.add(recObj);
}
fromDate = Ext.Date.add(fromDate, step[0], step[1]);
}
this.chart.filteredStore = newStore;
},
// @private aggregates values if multiple store elements belong to the same time step.
aggregate: function() {
var aggStore = {},
aggKeys = [],
key, value, op = this.aggregateOp,
field = this.fields,
i, fields = this.groupBy.split(','),
curField, recFields = [],
recFieldsLen = 0,
obj, dates = [],
json = [],
l = fields.length,
dateMethods = this.dateMethods,
aggregateFn = this.aggregateFn,
store = this.chart.filteredStore || this.chart.store;
//make sure we have a single field.
field = field.length ? field[0] : field;
store.each(function(rec) {
//get all record field names in a simple array
if (!recFields.length) {
rec.fields.each(function(f) {
recFields.push(f.name);
});
recFieldsLen = recFields.length;
}
//get record date value
value = rec.get(field);
//generate key for grouping records
for (i = 0; i < l; i++) {
if (i == 0) {
key = String(dateMethods[fields[i]](value));
} else {
key += '||' + dateMethods[fields[i]](value);
}
}
//get aggregation record from hash
if (key in aggStore) {
obj = aggStore[key];
} else {
obj = aggStore[key] = {};
aggKeys.push(key);
dates.push(value);
}
//append record values to an aggregation record
for (i = 0; i < recFieldsLen; i++) {
curField = recFields[i];
if (!obj[curField]) {
obj[curField] = [];
}
if (rec.get(curField) !== undefined) {
obj[curField].push(rec.get(curField));
}
}
});
//perform aggregation operations on fields
for (key in aggStore) {
obj = aggStore[key];
for (i = 0; i < recFieldsLen; i++) {
curField = recFields[i];
obj[curField] = aggregateFn[op](obj[curField]);
}
json.push(obj);
}
this.chart.substore = new Ext.data.JsonStore({
fields: recFields,
data: json
});
this.dates = dates;
},
// JCA Compatibility with Date
// @private creates a label array to be used as the axis labels.
setLabels: function() {
var me = this,
store = me.chart.substore,
fields = me.fields,
format = me.dateFormat,
dates = me.dates,
labels;
me.labels = labels = [];
store.each(function(record, i) {
if (!format) {
labels.push(record.get(fields));
} else {
labels.push(dates[i].format(format));
}
},
me);
},
processView: function() {
//TODO(nico): fix this eventually...
if (this.constrain) {
this.constrainDates();
this.aggregate();
this.chart.substore = this.chart.filteredStore;
} else {
this.aggregate();
}
},
// @private modifies the store and creates the labels for the axes.
applyData: function() {
this.setLabels();
var count = this.chart.substore.getCount();
return {
from: 0,
to: Math.max(count - 1, 0),
steps: count - 1,
step: 1
};
}
});
Ext.ns('Ext.chart.series');
/**
* @class Ext.chart.series.ItemEvents
*
* This series mixin defines events that occur on a particular series item, and adds default
* event handlers for detecting and firing those item interaction events.
*
* @author Jason Johnston <jason@sencha.com>
* @docauthor Jason Johnston <jason@sencha.com>
*/
(function() {
function createEventRelayMethod(name) {
return function(e) {
var me = this,
item = me.itemForEvent(e);
if (item) {
me.fireEvent(name, me, item, e);
}
}
}
Ext.chart.series.ItemEvents = Ext.extend(Object, {
constructor: function() {
var me = this,
itemEventNames = Ext.chart.series.ItemEvents.itemEventNames;
me.addEvents.apply(me, itemEventNames);
me.enableBubble(itemEventNames);
},
initEvents: function() {
var me = this;
me.chart.on({
scope: me,
mousemove: me.onMouseMove,
mouseup: me.onMouseUp,
mousedown: me.onMouseDown,
click: me.onClick,
doubleclick: me.onDoubleClick,
tap: me.onTap,
tapstart: me.onTapStart,
tapend: me.onTapEnd,
tapcancel: me.onTapCancel,
taphold: me.onTapHold,
doubletap: me.onDoubleTap,
singletap: me.onSingleTap,
touchstart: me.onTouchStart,
touchmove: me.onTouchMove,
touchend: me.onTouchEnd,
dragstart: me.onDragStart,
drag: me.onDrag,
dragend: me.onDragEnd,
pinchstart: me.onPinchStart,
pinch: me.onPinch,
pinchend: me.onPinchEnd,
swipe: me.onSwipe
});
},
itemForEvent: function(e) {
var me = this,
chartXY = me.chart.getEventXY(e);
return me.getItemForPoint(chartXY[0], chartXY[1]);
},
getBubbleTarget: function() {
return this.chart;
},
onMouseMove: function(e) {
var me = this,
lastItem = me.lastOverItem,
item = me.itemForEvent(e);
if (lastItem && item !== lastItem) {
me.fireEvent('itemmouseout', me, lastItem, e);
delete me.lastOverItem;
}
if (item) {
me.fireEvent('itemmousemove', me, item, e);
}
if (item && item !== lastItem) {
me.fireEvent('itemmouseover', me, item, e);
me.lastOverItem = item;
}
},
// Events directly relayed when on an item:
onMouseUp: createEventRelayMethod('itemmouseup'),
onMouseDown: createEventRelayMethod('itemmousedown'),
onClick: createEventRelayMethod('itemclick'),
onDoubleClick: createEventRelayMethod('itemdoubleclick'),
onTap: createEventRelayMethod('itemtap'),
onTapStart: createEventRelayMethod('itemtapstart'),
onTapEnd: createEventRelayMethod('itemtapend'),
onTapCancel: createEventRelayMethod('itemtapcancel'),
onTapHold: createEventRelayMethod('itemtaphold'),
onDoubleTap: createEventRelayMethod('itemdoubletap'),
onSingleTap: createEventRelayMethod('itemsingletap'),
onTouchStart: createEventRelayMethod('itemtouchstart'),
onTouchMove: createEventRelayMethod('itemtouchmove'),
onTouchEnd: createEventRelayMethod('itemtouchend'),
onDragStart: createEventRelayMethod('itemdragstart'),
onDrag: createEventRelayMethod('itemdrag'),
onDragEnd: createEventRelayMethod('itemdragend'),
onPinchStart: createEventRelayMethod('itempinchstart'),
onPinch: createEventRelayMethod('itempinch'),
onPinchEnd: createEventRelayMethod('itempinchend'),
onSwipe: createEventRelayMethod('itemswipe')
});
Ext.chart.series.ItemEvents.itemEventNames = [
/**
* @event itemmousemove
* Fires when the mouse is moved on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
'itemmousemove',
/**
* @event itemmouseup
* Fires when a mouseup event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
'itemmouseup',
/**
* @event itemmousedown
* Fires when a mousedown event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
'itemmousedown',
/**
* @event itemmouseover
* Fires when the mouse enters a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
'itemmouseover',
/**
* @event itemmouseout
* Fires when the mouse exits a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
'itemmouseout',
/**
* @event itemclick
* Fires when a click event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
'itemclick',
/**
* @event itemdoubleclick
* Fires when a doubleclick event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
'itemdoubleclick',
/**
* @event itemtap
* Fires when a tap event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
'itemtap',
/**
* @event itemtapstart
* Fires when a tapstart event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
'itemtapstart',
/**
* @event itemtapend
* Fires when a tapend event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
'itemtapend',
/**
* @event itemtapcancel
* Fires when a tapcancel event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
'itemtapcancel',
/**
* @event itemtaphold
* Fires when a taphold event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
'itemtaphold',
/**
* @event itemdoubletap
* Fires when a doubletap event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
'itemdoubletap',
/**
* @event itemsingletap
* Fires when a singletap event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
'itemsingletap',
/**
* @event itemtouchstart
* Fires when a touchstart event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
'itemtouchstart',
/**
* @event itemtouchmove
* Fires when a touchmove event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
'itemtouchmove',
/**
* @event itemtouchend
* Fires when a touchend event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
'itemtouchend',
/**
* @event itemdragstart
* Fires when a dragstart event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
'itemdragstart',
/**
* @event itemdrag
* Fires when a drag event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
'itemdrag',
/**
* @event itemdragend
* Fires when a dragend event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
'itemdragend',
/**
* @event itempinchstart
* Fires when a pinchstart event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
'itempinchstart',
/**
* @event itempinch
* Fires when a pinch event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
'itempinch',
/**
* @event itempinchend
* Fires when a pinchend event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
'itempinchend',
/**
* @event itemswipe
* Fires when a swipe event occurs on a series item.
* @param {Ext.chart.series.Series} series
* @param {Object} item
* @param {Event} event
*/
'itemswipe'
// TODO itemtouchenter, itemtouchleave?
];
})();
/**
* @class Ext.chart.series.Series
*
* Series is the abstract class containing the common logic to all chart series. Series includes
* methods from Labels, Highlights, Tips and Callouts mixins. This class implements the logic of
* animating, hiding, showing all elements and returning the color of the series to be used as a legend item.
*
* ## Listeners
*
* The series class supports listeners via the Observable syntax. Some of these listeners are:
*
* - `itemmouseup` When the user interacts with a marker.
* - `itemmousedown` When the user interacts with a marker.
* - `itemmousemove` When the user iteracts with a marker.
* - (similar `item*` events occur for many raw mouse and touch events)
* - `afterrender` Will be triggered when the animation ends or when the series has been rendered completely.
*
* For example:
*
* series: [{
* type: 'column',
* axis: 'left',
* listeners: {
* 'afterrender': function() {
* console('afterrender');
* }
* },
* xField: 'category',
* yField: 'data1'
* }]
*
*/
Ext.ns('Ext.chart.series');
Ext.chart.series.Series = Ext.extend(Ext.util.Observable, {
// TODO make into interaction:
/**
* @cfg {Object} tips
* Add tooltips to the visualization's markers. The options for the tips are the
* same configuration used with {@link Ext.tip.ToolTip}. For example:
*
* tips: {
* trackMouse: true,
* width: 140,
* height: 28,
* renderer: function(storeItem, item) {
* this.setTitle(storeItem.get('name') + ': ' + storeItem.get('data1') + ' views');
* }
* },
*/
/**
* @protected {String} type
* The type of series. Set in subclasses.
*/
type: null,
/**
* @cfg {String} title
* The human-readable name of the series.
*/
title: null,
/**
* @cfg {Boolean} showInLegend
* Whether to show this series in the legend.
*/
showInLegend: true,
/**
* @cfg {Function} renderer
* A function that can be overridden to set custom styling properties to each rendered element.
* Passes in (sprite, record, attributes, index, store) to the function.
*/
renderer: function(sprite, record, attributes, index, store) {
return attributes;
},
/**
* @cfg {Array} shadowAttributes
* An array with shadow attributes
*/
shadowAttributes: null,
//@private triggerdrawlistener flag
triggerAfterDraw: false,
constructor: function(config) {
var me = this;
//new fresh object as own property.
me.style = {};
me.themeStyle = {};
if (config) {
Ext.apply(me, config);
}
me.shadowGroups = [];
me.markerStyle = new Ext.chart.theme.MarkerStyle();
me.labelStyle = new Ext.chart.theme.LabelStyle();
Ext.chart.Label.prototype.constructor.call(me, config);
Ext.chart.Highlight.prototype.constructor.call(me, config);
Ext.chart.Callout.prototype.constructor.call(me, config);
Ext.chart.Transformable.prototype.constructor.call(me);
Ext.chart.series.ItemEvents.prototype.constructor.call(me);
me.addEvents({
beforedraw: true,
draw: true,
afterdraw: true,
/**
* @event titlechange
* Fires when the series title is changed via {@link #setTitle}.
* @param {String} title The new title value
* @param {Number} index The index in the collection of titles
*/
titlechange: true
});
me.initEvents();
Ext.chart.series.Series.superclass.constructor.call(me, config);
},
/**
* @private get the surface for drawing the series sprites
*/
getSurface: function() {
var me = this,
surface = me.surface;
if (!surface) {
surface = me.surface = me.chart.getSurface('series' + me.index);
surface.el.setStyle('zIndex', me.chart.surfaceZIndexes.series);
}
return surface;
},
/**
* @private get the surface for drawing the series overlay sprites
*/
getOverlaySurface: function() {
var me = this,
surface = me.overlaySurface;
if (!surface) {
surface = me.overlaySurface = me.chart.getSurface('seriesOverlay' + me.index);
surface.el.setStyle('zIndex', me.chart.surfaceZIndexes.overlay);
}
return surface;
},
// @private set the bbox and clipBox for the series
setBBox: function(noGutter) {
var me = this,
chart = me.chart,
chartBBox = chart.chartBBox,
gutterX = noGutter ? 0 : chart.maxGutter[0],
gutterY = noGutter ? 0 : chart.maxGutter[1],
clipBox, bbox;
clipBox = {
x: 0,
y: 0,
width: chartBBox.width,
height: chartBBox.height
};
me.clipBox = clipBox;
bbox = {
x: ((clipBox.x + gutterX) - (chart.zoom.x * chart.zoom.width)) * me.zoomX,
y: ((clipBox.y + gutterY) - (chart.zoom.y * chart.zoom.height)) * me.zoomY,
width: (clipBox.width - (gutterX * 2)) * chart.zoom.width * me.zoomX,
height: (clipBox.height - (gutterY * 2)) * chart.zoom.height * me.zoomY
};
me.bbox = bbox;
},
// @private set the animation for the sprite
onAnimate: function(sprite, attr) {
var me = this;
sprite.stopAnimation();
if (me.triggerAfterDraw) {
return sprite.animate(Ext.applyIf(attr, me.chart.animate));
} else {
me.triggerAfterDraw = true;
return sprite.animate(Ext.apply(Ext.applyIf(attr, me.chart.animate), {
listeners: {
'afteranimate': function() {
me.triggerAfterDraw = false;
me.fireEvent('afterrender');
}
}
}));
}
},
// @private return the gutter.
getGutters: function() {
return [0, 0];
},
/**
* For a given x/y point relative to the Surface, find a corresponding item from this
* series, if any.
* @param {Number} x
* @param {Number} y
* @return {Object} An object describing the item, or null if there is no matching item. The exact contents of
* this object will vary by series type, but should always contain at least the following:
* <ul>
* <li>{Ext.chart.series.Series} series - the Series object to which the item belongs</li>
* <li>{Object} value - the value(s) of the item's data point</li>
* <li>{Array} point - the x/y coordinates relative to the chart box of a single point
* for this data item, which can be used as e.g. a tooltip anchor point.</li>
* <li>{Ext.draw.Sprite} sprite - the item's rendering Sprite.
* </ul>
*/
getItemForPoint: function(x, y) {
var me = this,
items = me.items,
bbox = me.bbox,
i, ln;
if (items && items.length && !me.seriesIsHidden && Ext.draw.Draw.withinBox(x, y, bbox)) {
// Adjust for series pan
x -= me.panX;
y -= me.panY;
// Check bounds
for (i = 0, ln = items.length; i < ln; i++) {
if (items[i] && me.isItemInPoint(x, y, items[i], i)) {
return items[i];
}
}
}
return null;
},
isItemInPoint: function() {
return false;
},
/**
* Hides all the elements in the series.
*/
hideAll: function() {
var me = this,
items = me.items,
item, len, i, j, l, sprite, shadows;
me.seriesIsHidden = true;
me._prevShowMarkers = me.showMarkers;
me.showMarkers = false;
//hide all labels
me.hideLabels(0);
//hide all sprites
for (i = 0, len = items.length; i < len; i++) {
item = items[i];
sprite = item.sprite;
if (sprite) {
sprite.setAttributes({
hidden: true
}, true);
if (sprite.shadows) {
shadows = sprite.shadows;
for (j = 0, l = shadows.length; j < l; ++j) {
shadows[j].hide(true);
}
}
}
}
},
/**
* Shows all the elements in the series.
*/
showAll: function() {
var me = this,
prevAnimate = me.chart.animate;
me.chart.animate = false;
me.seriesIsHidden = false;
me.showMarkers = me._prevShowMarkers;
me.drawSeries();
me.chart.animate = prevAnimate;
},
/**
* Performs drawing of this series.
*/
drawSeries: function() {
this.updateSurfaceBox();
},
/**
* Returns an array of labels to be displayed as items in the legend. Only relevant if
* {@link #showInLegend} is true.
*/
getLegendLabels: function() {
var title = this.title;
return title ? [title] : [];
},
getColorFromStyle: function(style) {
if (Ext.isObject(style)) {
return style.stops[0].color;
}
//if it's a gradient just return the first color stop.
return style.indexOf('url') == -1 ? style : me.getSurface('main')._gradients[style.match(/url\(#([^\)]+)\)/)[1]].stops[0].color;
},
/**
* Returns a string with the color to be used for the series legend item.
*/
getLegendColor: function(index) {
var me = this, fill, stroke;
if (me.style) {
fill = me.style.fill;
stroke = me.style.stroke;
if (fill && fill != 'none') {
return me.getColorFromStyle(fill);
}
return me.getColorFromStyle(stroke);
}
return '#000';
},
/**
* Checks whether the data field should be visible in the legend
* @private
* @param {Number} index The index of the current item
*/
visibleInLegend: function(index){
return !this.seriesIsHidden && !this.isExcluded(index);
},
/**
* Changes the value of the {@link #title} for the series.
* Arguments can take two forms:
* <ul>
* <li>A single String value: this will be used as the new single title for the series (applies
* to series with only one yField)</li>
* <li>A numeric index and a String value: this will set the title for a single indexed yField.</li>
* </ul>
* @param {Number} index
* @param {String} title
*/
setTitle: function(index, title) {
var me = this,
oldTitle = me.title;
if (Ext.isString(index)) {
title = index;
index = 0;
}
if (Ext.isArray(oldTitle)) {
oldTitle[index] = title;
} else {
me.title = title;
}
me.fireEvent('titlechange', title, index);
},
/**
* @private update the position/size of the series surface
*/
updateSurfaceBox: function() {
var me = this,
surface = me.getSurface(),
overlaySurface = me.getOverlaySurface(),
chartBBox = me.chart.chartBBox;
surface.el.setTopLeft(chartBBox.y, chartBBox.x);
surface.setSize(chartBBox.width, chartBBox.height);
overlaySurface.el.setTopLeft(chartBBox.y, chartBBox.x);
overlaySurface.setSize(chartBBox.width, chartBBox.height);
},
getTransformableSurfaces: function() {
// Need to transform the overlay surface along with the normal surface
// TODO might be good to skip transforming the overlay surface if there is nothing in it
return [this.getSurface(), this.getOverlaySurface()];
},
/**
* Iterate over each of the records for this series. The default implementation simply iterates
* through the entire data store, but individual series implementations can override this to
* provide custom handling, e.g. adding/removing records.
* @param {Function} fn The function to execute for each record.
* @param {Object} scope Scope for the fn.
*/
eachRecord: function(fn, scope) {
var chart = this.chart;
(chart.substore || chart.store).each(fn, scope);
},
/**
* Return the number of records being displayed in this series. Defaults to the number of
* records in the store; individual series implementations can override to provide custom handling.
*/
getRecordCount: function() {
var chart = this.chart,
store = chart.substore || chart.store;
return store ? store.getCount() : 0;
},
/**
* Determines whether the series item at the given index has been excluded, i.e. toggled off in the legend.
* @param index
*/
isExcluded: function(index) {
var excludes = this.__excludes;
return !!(excludes && excludes[index]);
},
/**
* Combine two of this series's indexed items into one. This is done via drag-drop on the
* legend for series that render more than one legend item. The data store is not modified,
* but the series uses the cumulative list of combinations in its rendering.
* @param {Number} index1 Index of the first item
* @param {Number} index2 Index of the second item
*/
combine: function(index1, index2) {
var me = this,
combinations = me.combinations || (me.combinations = []),
excludes = me.__excludes;
combinations.push([index1, index2]);
if (excludes && index1 < excludes.length) {
excludes.splice(index1, 1);
}
},
/**
* Determines whether the item at the given index is the result of item combination.
* @param {Number} index
* @return {Boolean}
*/
isCombinedItem: function(index) {
return this.getCombinationIndexesForItem(index).length > 0;
},
getCombinationIndexesForItem: function(index) {
var me = this,
combinations = me.combinations,
provenances = [],
i, len, combo, comboIndexA, comboIndexB;
if (combinations) {
// Step through the combinations to determine which combination step(s) contribute
// to the item at the given index, if any
for (i = 0, len = combinations.length; i < len; i++) {
combo = combinations[i];
comboIndexA = combo[0];
comboIndexB = combo[1];
if (!provenances[comboIndexB]) {
provenances[comboIndexB] = [];
}
if (provenances[comboIndexA]) {
provenances[comboIndexB] = provenances[comboIndexB].concat(provenances[comboIndexA]);
}
provenances[comboIndexB].push(i);
provenances.splice(comboIndexA, 1);
}
}
return provenances[index] || [];
},
split: function(index) {
var me = this,
combinations = me.combinations,
excludes = me.__excludes,
i, j, len, comboIndexes, combo, movedItemIndex;
if (combinations) {
comboIndexes = me.getCombinationIndexesForItem(index);
// For each contributing combination, remove it from the list and adjust the indexes
// of all subsequent combinations and excludes to account for it
if (comboIndexes) {
for (i = comboIndexes.length; i--;) {
movedItemIndex = combinations[comboIndexes[i]][0];
for (j = comboIndexes[i] + 1, len = combinations.length; j < len; j++) {
if (movedItemIndex <= combinations[j][0]) {
combinations[j][0]++;
}
if (movedItemIndex <= combinations[j][1]) {
combinations[j][1]++;
}
}
combinations.splice(comboIndexes[i], 1);
if (excludes) {
excludes.splice(movedItemIndex, 0, false);
}
}
}
// Now that the combinations list is updated, reset and replay them all
me.clearCombinations();
for (i = 0, len = combinations.length; i < len; i++) {
combo = combinations[i];
me.combine(combo[0], combo[1]);
}
}
},
/**
* Split any series items that were combined via {@link #combine} into their original items.
*/
clearCombinations: function() {
delete this.combinations;
},
/**
* Reset the series to its original state, before any user interaction.
*/
reset: function() {
var me = this;
me.unHighlightItem();
me.cleanHighlights();
me.clearTransform();
},
/* ---------------------------------
Methods needed for ComponentQuery
----------------------------------*/
//filled by the constructor.
ownerCt: null,
getItemId: function() {
return this.el && this.el.id || this.id || null;
},
initCls: function() {
return (this.cls || '').split(' ');
},
isXType: function(xtype) {
return xtype === 'series';
},
getRefItems: function(deep) {
var me = this,
ans = [];
if (me.markerStyle) {
ans.push(me.markerStyle);
}
if (me.labelStyle) {
ans.push(me.labelStyle);
}
if (me.calloutStyle) {
ans.push(me.calloutStyle);
}
if (me.highlightStyle) {
ans.push(me.highlightStyle);
}
return ans;
}
});
Ext.applyIf(Ext.chart.series.Series.prototype, Ext.chart.Label.prototype);
Ext.applyIf(Ext.chart.series.Series.prototype, Ext.chart.Highlight.prototype);
Ext.applyIf(Ext.chart.series.Series.prototype, Ext.chart.Callout.prototype);
Ext.applyIf(Ext.chart.series.Series.prototype, Ext.chart.Transformable.prototype);
Ext.applyIf(Ext.chart.series.Series.prototype, Ext.chart.series.ItemEvents.prototype);
/**
* @class Ext.chart.series.Cartesian
* @extends Ext.chart.series.Series
*
* Common base class for series implementations which plot values using x/y coordinates.
*
* @constructor
*/
Ext.chart.series.Cartesian = Ext.extend(Ext.chart.series.Series, {
/**
* The field used to access the x axis value from the items from the data
* source.
*
* @cfg xField
* @type String
*/
xField: null,
/**
* The field used to access the y-axis value from the items from the data
* source.
*
* @cfg yField
* @type String
*/
yField: null,
/**
* @cfg {String} axis
* The position of the axis to bind the values to. Possible values are 'left', 'bottom', 'top' and 'right'.
* You must explicitly set this value to bind the values of the line series to the ones in the axis, otherwise a
* relative scale will be used.
*/
axis: 'left',
getLegendLabels: function() {
var me = this,
labels = [],
combinations = me.combinations;
Ext.each([].concat(me.yField), function(yField, i) {
var title = me.title;
// Use the 'title' config if present, otherwise use the raw yField name
labels.push((Ext.isArray(title) ? title[i] : title) || yField);
});
// Handle yFields combined via legend drag-drop
if (combinations) {
Ext.each(combinations, function(combo) {
var label0 = labels[combo[0]],
label1 = labels[combo[1]];
labels[combo[1]] = label0 + ' & ' + label1;
labels.splice(combo[0], 1);
});
}
return labels;
},
/**
* @protected Iterates over a given record's values for each of this series's yFields,
* executing a given function for each value. Any yFields that have been combined
* via legend drag-drop will be treated as a single value.
* @param {Ext.data.Model} record
* @param {Function} fn
* @param {Object} scope
*/
eachYValue: function(record, fn, scope) {
Ext.each(this.getYValueAccessors(), function(accessor, i) {
fn.call(scope, accessor(record), i);
});
},
/**
* @protected Returns the number of yField values, taking into account fields combined
* via legend drag-drop.
* @return {Number}
*/
getYValueCount: function() {
return this.getYValueAccessors().length;
},
combine: function(index1, index2) {
var me = this,
accessors = me.getYValueAccessors(),
accessor1 = accessors[index1],
accessor2 = accessors[index2];
// Combine the yValue accessors for the two indexes into a single accessor that returns their sum
accessors[index2] = function(record) {
return accessor1(record) + accessor2(record);
};
accessors.splice(index1, 1);
Ext.chart.series.Cartesian.superclass.combine.call(me, index1, index2);
},
clearCombinations: function() {
// Clear combined accessors, they'll get regenerated on next call to getYValueAccessors
delete this.yValueAccessors;
Ext.chart.series.Cartesian.superclass.clearCombinations.call(this);
},
/**
* @protected Returns an array of functions, each of which returns the value of the yField
* corresponding to function's index in the array, for a given record (each function takes the
* record as its only argument.) If yFields have been combined by the user via legend drag-drop,
* this list of accessors will be kept in sync with those combinations.
* @return {Array} array of accessor functions
*/
getYValueAccessors: function() {
var me = this,
accessors = me.yValueAccessors;
if (!accessors) {
accessors = me.yValueAccessors = [];
Ext.each([].concat(me.yField), function(yField) {
accessors.push(function(record) {
return record.get(yField);
});
});
}
return accessors;
},
/**
* Calculate the min and max values for this series's xField.
* @return {Array} [min, max]
*/
getMinMaxXValues: function() {
var me = this,
min, max,
xField = me.xField;
if (me.getRecordCount() > 0) {
min = Infinity;
max = -min;
me.eachRecord(function(record) {
var xValue = record.get(xField);
if (xValue > max) {
max = xValue;
}
if (xValue < min) {
min = xValue;
}
});
} else {
min = max = 0;
}
return [min, max];
},
/**
* Calculate the min and max values for this series's yField(s). Takes into account yField
* combinations, exclusions, and stacking.
* @return {Array} [min, max]
*/
getMinMaxYValues: function() {
var me = this,
stacked = me.stacked,
min, max,
positiveTotal, negativeTotal;
function eachYValueStacked(yValue, i) {
if (!me.isExcluded(i)) {
if (yValue < 0) {
negativeTotal += yValue;
} else {
positiveTotal += yValue;
}
}
}
function eachYValue(yValue, i) {
if (!me.isExcluded(i)) {
if (yValue > max) {
max = yValue;
}
if (yValue < min) {
min = yValue;
}
}
}
if (me.getRecordCount() > 0) {
min = Infinity;
max = -min;
me.eachRecord(function(record) {
if (stacked) {
positiveTotal = 0;
negativeTotal = 0;
me.eachYValue(record, eachYValueStacked);
if (positiveTotal > max) {
max = positiveTotal;
}
if (negativeTotal < min) {
min = negativeTotal;
}
} else {
me.eachYValue(record, eachYValue);
}
});
} else {
min = max = 0;
}
return [min, max];
}
});
/**
* Creates a Bar Chart. A Bar Chart is a useful visualization technique to display quantitative information for
* different categories that can show some progression (or regression) in the dataset. As with all other series, the Bar
* Series must be appended in the *series* Chart array configuration. See the Chart documentation for more information.
* A typical configuration object for the bar series could be:
*
* {@img Ext.chart.series.Bar/Ext.chart.series.Bar.png Ext.chart.series.Bar chart series}
*
* var store = new Ext.data.JsonStore({
* fields: ['name', 'data1', 'data2', 'data3', 'data4', 'data5'],
* data: [
* {'name':'metric one', 'data1':10, 'data2':12, 'data3':14, 'data4':8, 'data5':13},
* {'name':'metric two', 'data1':7, 'data2':8, 'data3':16, 'data4':10, 'data5':3},
* {'name':'metric three', 'data1':5, 'data2':2, 'data3':14, 'data4':12, 'data5':7},
* {'name':'metric four', 'data1':2, 'data2':14, 'data3':6, 'data4':1, 'data5':23},
* {'name':'metric five', 'data1':27, 'data2':38, 'data3':36, 'data4':13, 'data5':33}
* ]
* });
*
* new Ext.chart.Chart({
* renderTo: Ext.getBody(),
* width: 500,
* height: 300,
* animate: true,
* store: store,
* axes: [{
* type: 'Numeric',
* position: 'bottom',
* fields: ['data1'],
* label: {
* renderer: Ext.util.Format.numberRenderer('0,0')
* },
* title: 'Sample Values',
* grid: true,
* minimum: 0
* }, {
* type: 'Category',
* position: 'left',
* fields: ['name'],
* title: 'Sample Metrics'
* }],
* series: [{
* type: 'bar',
* axis: 'bottom',
* highlight: true,
* tips: {
* trackMouse: true,
* width: 140,
* height: 28,
* renderer: function(storeItem, item) {
* this.setTitle(storeItem.get('name') + ': ' + storeItem.get('data1') + ' views');
* }
* },
* label: {
* display: 'insideEnd',
* field: 'data1',
* renderer: Ext.util.Format.numberRenderer('0'),
* orientation: 'horizontal',
* color: '#333',
* 'text-anchor': 'middle'
* },
* xField: 'name',
* yField: ['data1']
* }]
* });
*
* In this configuration we set `bar` as the series type, bind the values of the bar to the bottom axis and set the
* xField or category field to the `name` parameter of the store. We also set `highlight` to true which enables smooth
* animations when bars are hovered. We also set some configuration for the bar labels to be displayed inside the bar,
* to display the information found in the `data1` property of each element store, to render a formated text with the
* `Ext.util.Format` we pass in, to have an `horizontal` orientation (as opposed to a vertical one) and we also set
* other styles like `color`, `text-anchor`, etc.
*/
Ext.chart.series.Bar = Ext.extend(Ext.chart.series.Cartesian, {
type: 'bar',
/**
* @private {Boolean} column Whether to set the visualization as column chart or horizontal bar chart.
*/
column: false,
axis: 'bottom',
/**
* @cfg style Style properties that will override the theming series styles.
*/
/**
* @cfg {Number} gutter The gutter space between single bars, as a percentage of the bar width
*/
gutter: 38.2,
/**
* @cfg {Number} groupGutter The gutter space between groups of bars, as a percentage of the bar width
*/
groupGutter: 38.2,
/**
* @cfg {Number} xPadding Padding between the left/right axes and the bars
*/
xPadding: 0,
/**
* @cfg {Number} yPadding Padding between the top/bottom axes and the bars
*/
yPadding: 10,
xJustify: false,
/**
* @private
* @property disjointStacked
* @type Boolean
* If set to `true`, then if `stacked:true` the bars will be drawn stacked in terms of their
* y-values but remain side-by-side in the x-direction, basically a hybrid between stacked and
* grouped. This is only used internally to support an intermediate animation state when
* toggling between stacked and grouped (see the ToggleStacked interaction).
*/
constructor: function(config) {
Ext.chart.series.Bar.superclass.constructor.apply(this, arguments);
var me = this,
surface = me.getSurface(),
shadow = me.chart.shadow,
i, l;
Ext.apply(me, config, {
shadowAttributes: surface.getShadowAttributesArray(),
shadowOptions: Ext.apply(surface.getShadowOptions(), shadow === true ? {} : (shadow || {}))
});
me.group = surface.getGroup(me.seriesId + '-bars');
if (shadow) {
for (i = 0, l = me.shadowAttributes.length; i < l; i++) {
me.shadowGroups.push(surface.getGroup(me.seriesId + '-shadows' + i));
}
}
me.initialStacked = me.stacked;
},
// @private sets the bar girth.
getBarGirth: function() {
var me = this,
column = me.column,
ln = me.getRecordCount(),
gutter = me.gutter / 100;
return (me.chart.chartBBox[column ? 'width' : 'height'] - me[column ? 'xPadding' : 'yPadding'] * 2) / (ln * (gutter + 1) - gutter);
},
// @private returns the gutters.
getGutters: function() {
var me = this,
column = me.column,
gutter = Math.ceil((column ? me.xPadding : me.yPadding) + me.getBarGirth() / 2);
return column ? [gutter, 0] : [0, gutter];
},
// @private Get chart and data boundaries
getBounds: function() {
var me = this,
chart = me.chart,
barsLen = me.getYValueCount(),
visibleBarsLen = barsLen,
groupGutter = me.groupGutter / 100,
column = me.column,
zoomX = me.zoomX,
zoomY = me.zoomY,
xPadding = me.xPadding * zoomX,
yPadding = me.yPadding * zoomY,
stacked = me.stacked,
disjointStacked = me.disjointStacked,
barWidth = me.getBarGirth() * (column ? zoomX : zoomY),
math = Math,
mmax = math.max,
mabs = math.abs,
groupBarWidth, bbox, minY, maxY, axis, out,
scale, zero, total, j, plus, minus, recordIndex;
me.setBBox(true);
bbox = me.bbox;
//Skip excluded yFields
for (j = 0, total = barsLen; j < total; j++) {
if (me.isExcluded(j)) {
visibleBarsLen--;
}
}
if (me.axis) {
axis = chart.axes.get(me.axis);
if (axis) {
out = axis.calcEnds();
minY = out.from;
maxY = out.to;
}
}
if (me.yField && !Ext.isNumber(minY)) {
axis = new Ext.chart.axis.Axis({
chart: chart,
fields: [].concat(me.yField)
});
out = axis.calcEnds();
minY = out.from;
maxY = out.to;
}
if (!Ext.isNumber(minY)) {
minY = 0;
}
if (!Ext.isNumber(maxY)) {
maxY = 0;
}
scale = (column ? bbox.height - yPadding * 2 : bbox.width - xPadding * 2) / (maxY - minY);
groupBarWidth = barWidth / ((stacked && !disjointStacked ? 1 : visibleBarsLen) * (groupGutter + 1) - groupGutter);
zero = (column) ? bbox.y + bbox.height - yPadding : bbox.x + xPadding;
function eachYValue(yValue, i) {
if (!me.isExcluded(i)) {
total[yValue > 0 ? 1 : 0][recordIndex] += mabs(yValue);
}
}
if (stacked) {
total = [[], []];
me.eachRecord(function(record, i) {
total[0][i] = total[0][i] || 0;
total[1][i] = total[1][i] || 0;
recordIndex = i;
me.eachYValue(record, eachYValue);
});
total[+(maxY > 0)].push(mabs(maxY));
total[+(minY > 0)].push(mabs(minY));
minus = mmax.apply(math, total[0]);
plus = mmax.apply(math, total[1]);
scale = (column ? bbox.height - yPadding * 2 : bbox.width - xPadding * 2) / (plus + minus);
zero = zero + minus * scale * (column ? -1 : 1);
}
else if (minY / maxY < 0) {
zero = zero - minY * scale * (column ? -1 : 1);
}
if(me.xJustify){
bbox.x = bbox.x-barWidth/2;
}
return {
bbox: bbox,
barsLen: barsLen,
visibleBarsLen: visibleBarsLen,
barWidth: barWidth,
groupBarWidth: groupBarWidth,
scale: scale,
zero: zero,
xPadding: xPadding,
yPadding: yPadding,
signed: minY / maxY < 0,
minY: minY,
maxY: maxY
};
},
// @private Build an array of paths for the chart
getPaths: function() {
var me = this,
chart = me.chart,
bounds = me.bounds = me.getBounds(),
items = me.items = [],
gutter = me.gutter / 100,
groupGutter = me.groupGutter / 100,
animate = chart.animate,
column = me.column,
group = me.group,
enableShadows = chart.shadow,
shadowGroups = me.shadowGroups,
shadowGroupsLn = shadowGroups.length,
bbox = bounds.bbox,
xPadding = me.xPadding * me.zoomX,
yPadding = me.yPadding * me.zoomY,
stacked = me.stacked,
disjointStacked = me.disjointStacked,
barsLen = bounds.barsLen,
colors = me.colorArrayStyle,
colorLength = colors && colors.length || 0,
math = Math,
mmax = math.max,
mabs = math.abs,
total = me.getRecordCount(),
height, totalDim, totalNegDim, bottom, top, hasShadow, barAttr, attrs, counter,
shadowIndex, shadow, sprite, offset, floorY, recordIndex, currentRecord;
function eachYValue(yValue, i) {
// Excluded series
if (me.isExcluded(i)) {
return;
}
height = Math.round(yValue * bounds.scale);
barAttr = {
fill: colors[(barsLen > 1 ? i : 0) % colorLength]
};
if (column) {
Ext.apply(barAttr, {
height: height,
width: mmax(bounds.groupBarWidth, 0),
x: (bbox.x + xPadding + recordIndex * bounds.barWidth * (1 + gutter) + counter * bounds.groupBarWidth * (1 + groupGutter) * (!stacked || disjointStacked ? 1 : 0)),
y: bottom - height
});
}
else {
// draw in reverse order
offset = (total - 1) - recordIndex;
Ext.apply(barAttr, {
height: mmax(bounds.groupBarWidth, 0),
width: height + (bottom == bounds.zero),
x: bottom + (bottom != bounds.zero),
y: (bbox.y + yPadding + offset * bounds.barWidth * (1 + gutter) + counter * bounds.groupBarWidth * (1 + groupGutter) * (!stacked || disjointStacked ? 1 : 0) + 1)
});
}
if (height < 0) {
if (column) {
barAttr.y = top;
barAttr.height = mabs(height);
} else {
barAttr.x = top + height;
barAttr.width = mabs(height);
}
}
if (stacked) {
if (height < 0) {
top += height * (column ? -1 : 1);
} else {
bottom += height * (column ? -1 : 1);
}
totalDim += mabs(height);
if (height < 0) {
totalNegDim += mabs(height);
}
}
barAttr.x = Math.floor(barAttr.x) + 1;
floorY = Math.floor(barAttr.y);
if (!Ext.isIE9 && barAttr.y > floorY) {
floorY--;
}
barAttr.y = floorY;
var br = Ext.apply({},barAttr);
if(me.xJustify && i==0){
br.width =Math.floor(barAttr.width/2);
br.x = br.x+br.width;
}else{
br.width =Math.floor(barAttr.width);
}
br.height = Math.floor(barAttr.height);
items.push({
series: me,
storeItem: currentRecord,
value: [currentRecord.get(me.xField), yValue],
attr: br,
point: column ? [br.x + br.width / 2, yValue >= 0 ? br.y : br.y + br.height] :
[yValue >= 0 ? br.x + br.width : br.x, br.y + br.height / 2]
});
// When resizing, reset before animating
if (animate && chart.resizing) {
attrs = column ? {
x: br.x,
y: bounds.zero,
width: br.width,
height: 0
} : {
x: bounds.zero,
y: br.y,
width: 0,
height: br.height
};
if (enableShadows && (stacked && !hasShadow || !stacked)) {
hasShadow = true;
//update shadows
for (shadowIndex = 0; shadowIndex < shadowGroupsLn; shadowIndex++) {
shadow = shadowGroups[shadowIndex].getAt(stacked ? recordIndex : (recordIndex * barsLen + i));
if (shadow) {
shadow.setAttributes(attrs, true);
}
}
}
//update sprite position and width/height
sprite = group.getAt(recordIndex * barsLen + i);
if (sprite) {
sprite.setAttributes(attrs, true);
}
}
counter++;
}
me.eachRecord(function(record, i) {
bottom = top = bounds.zero;
totalDim = 0;
totalNegDim = 0;
hasShadow = false;
counter = 0;
currentRecord = record;
recordIndex = i;
me.eachYValue(record, eachYValue);
if (stacked && items.length) {
items[i * counter].totalDim = totalDim;
items[i * counter].totalNegDim = totalNegDim;
}
}, me);
},
// @private render/setAttributes on the shadows
renderShadows: function(i, barAttr, baseAttrs, bounds) {
var me = this,
chart = me.chart,
surface = me.getSurface(),
animate = chart.animate,
stacked = me.stacked,
shadowGroups = me.shadowGroups,
shadowAttributes = me.shadowAttributes,
shadowGroupsLn = shadowGroups.length,
store = chart.substore || chart.store,
column = me.column,
items = me.items,
shadows = [],
zero = bounds.zero,
shadowIndex, shadowBarAttr, shadow, totalDim, totalNegDim, j, rendererAttributes;
if ((stacked && (i % bounds.visibleBarsLen === 0)) || !stacked) {
j = i / bounds.visibleBarsLen;
//create shadows
for (shadowIndex = 0; shadowIndex < shadowGroupsLn; shadowIndex++) {
shadowBarAttr = Ext.apply({}, shadowAttributes[shadowIndex]);
shadow = shadowGroups[shadowIndex].getAt(stacked ? j : i);
shadowBarAttr.x = barAttr.x;
shadowBarAttr.y = barAttr.y;
shadowBarAttr.width = barAttr.width;
shadowBarAttr.height = barAttr.height;
if (!shadow) {
shadow = surface.add(Ext.apply({
type: 'rect',
group: shadowGroups[shadowIndex]
}, Ext.apply({}, baseAttrs, shadowBarAttr)));
}
if (stacked) {
totalDim = items[i].totalDim;
totalNegDim = items[i].totalNegDim;
if (column) {
shadowBarAttr.y = zero - totalNegDim;
shadowBarAttr.height = totalDim;
}
else {
shadowBarAttr.x = zero - totalNegDim;
shadowBarAttr.width = totalDim;
}
}
if (animate) {
if (!stacked) {
rendererAttributes = me.renderer(shadow, store.getAt(j), shadowBarAttr, i, store);
me.onAnimate(shadow, { to: rendererAttributes });
}
else {
rendererAttributes = me.renderer(shadow, store.getAt(j), Ext.apply(shadowBarAttr, { hidden: true }), i, store);
shadow.setAttributes(rendererAttributes, true);
}
}
else {
rendererAttributes = me.renderer(shadow, store.getAt(j), Ext.apply(shadowBarAttr, { hidden: false }), i, store);
shadow.setAttributes(rendererAttributes, true);
}
shadows.push(shadow);
}
}
return shadows;
},
/**
* Draws the series for the current chart.
*/
drawSeries: function() {
var me = this,
chart = me.chart,
store = chart.substore || chart.store,
surface = me.getSurface(),
animate = chart.animate,
stacked = me.stacked,
column = me.column,
enableShadows = chart.shadow,
shadowGroups = me.shadowGroups,
shadowGroupsLn = shadowGroups.length,
group = me.group,
seriesStyle = me.style,
items, ln, i, j, baseAttrs, sprite, rendererAttributes, shadowIndex, shadowGroup,
bounds, endSeriesStyle, barAttr, attrs, anim, item;
if (me.fireEvent('beforedraw', me) === false) {
return;
}
Ext.chart.series.Bar.superclass.drawSeries.call(this);
if (!me.getRecordCount()) {
surface.items.hide(true);
return;
}
//fill colors are taken from the colors array.
delete seriesStyle.fill;
me.unHighlightItem();
me.cleanHighlights();
me.getPaths();
bounds = me.bounds;
items = me.items;
baseAttrs = column ? {
y: bounds.zero,
height: 0
} : {
x: bounds.zero,
width: 0
};
ln = items.length;
// Create new or reuse sprites and animate/display
for (i = 0; i < ln; i++) {
item = items[i];
sprite = group.getAt(i);
barAttr = item.attr;
if (enableShadows) {
item.shadows = me.renderShadows(i, barAttr, baseAttrs, bounds);
}
// Create a new sprite if needed (no height)
if (!sprite) {
attrs = Ext.apply({}, baseAttrs, barAttr);
attrs = Ext.apply(attrs, endSeriesStyle || {});
if (enableShadows) {
Ext.apply(attrs, me.shadowOptions);
}
sprite = surface.add(Ext.apply({}, {
type: 'rect',
group: group
}, attrs));
}
if (animate) {
rendererAttributes = me.renderer(sprite, store.getAt(i), barAttr, i, store);
sprite._to = rendererAttributes;
anim = me.onAnimate(sprite, { to: Ext.apply(rendererAttributes, endSeriesStyle) });
if (enableShadows && stacked && (i % bounds.barsLen === 0)) {
j = i / bounds.barsLen;
for (shadowIndex = 0; shadowIndex < shadowGroupsLn; shadowIndex++) {
anim.on('afteranimate', function() {
this.show(true);
}, shadowGroups[shadowIndex].getAt(j));
}
}
}
else {
rendererAttributes = me.renderer(sprite, store.getAt(i), Ext.apply(barAttr, { hidden: false }), i, store);
sprite.setAttributes(Ext.apply(rendererAttributes, endSeriesStyle), true);
}
item.sprite = sprite;
}
// Hide unused sprites
ln = group.getCount();
for (j = i; j < ln; j++) {
group.getAt(j).hide(true);
}
// Hide unused shadows
if (enableShadows) {
for (shadowIndex = 0; shadowIndex < shadowGroupsLn; shadowIndex++) {
shadowGroup = shadowGroups[shadowIndex];
ln = shadowGroup.getCount();
for (j = i; j < ln; j++) {
shadowGroup.getAt(j).hide(true);
}
}
}
me.renderLabels();
me.fireEvent('draw', me);
},
// @private handled when creating a label.
onCreateLabel: function(storeItem, item, i, display) {
var me = this,
surface = me.getSurface(),
group = me.labelsGroup,
config = me.label,
endLabelStyle = Ext.apply({}, config, me.labelStyle.style || {}),
sprite;
return surface.add(Ext.apply({
type: 'text',
group: group
}, endLabelStyle || {}));
},
// @private callback used when placing a label.
onPlaceLabel: function(label, storeItem, item, i, display, animate, j, index) {
// Determine the label's final position. Starts with the configured preferred value but
// may get flipped from inside to outside or vice-versa depending on space.
var me = this,
opt = me.bounds,
groupBarWidth = opt.groupBarWidth,
column = me.column,
chart = me.chart,
chartBBox = chart.chartBBox,
resizing = chart.resizing,
xValue = item.value[0],
yValue = item.value[1],
attr = item.attr,
config = Ext.apply(me.labelStyle.style || {}, me.label || {}),
rotate = config.orientation == 'vertical',
field = [].concat(config.field),
format = config.renderer,
text = format(storeItem.get(field[index])),
size = me.getLabelSize(text),
width = size.width,
height = size.height,
zero = opt.zero,
outside = 'outside',
insideStart = 'insideStart',
insideEnd = 'insideEnd',
offsetX = 10,
offsetY = 6,
signed = opt.signed,
x, y, finalAttr;
label.setAttributes({
text: text
});
label.isOutside = false;
if (column) {
if (display == outside) {
if (height + offsetY + attr.height > (yValue >= 0 ? zero: chartBBox.height - zero)) {
display = insideEnd;
}
} else {
if (height + offsetY > attr.height) {
display = outside;
label.isOutside = true;
}
}
x = attr.x + groupBarWidth / 2;
y = display == insideStart ?
(zero + ((height / 2 + 3) * (yValue >= 0 ? -1 : 1))) :
(yValue >= 0 ? (attr.y + ((height / 2 + 3) * (display == outside ? -1 : 1))) :
(attr.y + attr.height + ((height / 2 + 3) * (display === outside ? 1 : -1))));
}
else {
if (display == outside) {
if (width + offsetX + attr.width > (yValue >= 0 ? chartBBox.width - zero : zero)) {
display = insideEnd;
}
}
else {
if (width + offsetX > attr.width) {
display = outside;
label.isOutside = true;
}
}
x = display == insideStart ?
(zero + ((width / 2 + 5) * (yValue >= 0 ? 1 : -1))) :
(yValue >= 0 ? (attr.x + attr.width + ((width / 2 + 5) * (display === outside ? 1 : -1))) :
(attr.x + ((width / 2 + 5) * (display === outside ? -1 : 1))));
y = attr.y + groupBarWidth / 2;
}
//set position
finalAttr = {
x: x,
y: y
};
//rotate
if (rotate) {
finalAttr.rotate = {
x: x,
y: y,
degrees: 270
};
}
//check for resizing
if (animate && resizing) {
if (column) {
x = attr.x + attr.width / 2;
y = zero;
} else {
x = zero;
y = attr.y + attr.height / 2;
}
label.setAttributes({
x: x,
y: y
}, true);
if (rotate) {
label.setAttributes({
rotate: {
x: x,
y: y,
degrees: 270
}
}, true);
}
}
//handle animation
if (animate) {
me.onAnimate(label, { to: finalAttr });
}
else {
label.setAttributes(Ext.apply(finalAttr, {
hidden: false
}), true);
}
},
/* @private
* Gets the dimensions of a given bar label. Uses a single hidden sprite to avoid
* changing visible sprites.
* @param value
*/
getLabelSize: function(value) {
var tester = this.testerLabel,
config = this.label,
endLabelStyle = Ext.apply({}, config, this.labelStyle.style || {}),
rotated = config.orientation === 'vertical',
bbox, w, h,
undef;
if (!tester) {
tester = this.testerLabel = this.getSurface().add(Ext.apply({
type: 'text',
opacity: 0
}, endLabelStyle));
}
tester.setAttributes({
text: value
}, true);
// Flip the width/height if rotated, as getBBox returns the pre-rotated dimensions
bbox = tester.getBBox();
w = bbox.width;
h = bbox.height;
return {
width: rotated ? h : w,
height: rotated ? w : h
};
},
// @private used to animate label, markers and other sprites.
onAnimate: function(sprite, attr) {
sprite.show();
Ext.chart.series.Bar.superclass.onAnimate.apply(this, arguments);
},
isItemInPoint: function(x, y, item) {
var bbox = item.sprite.getBBox();
return bbox.x <= x && bbox.y <= y
&& (bbox.x + bbox.width) >= x
&& (bbox.y + bbox.height) >= y;
},
// @private hide all markers
hideAll: function() {
var axes = this.chart.axes;
if (!isNaN(this._index)) {
if (!this.__excludes) {
this.__excludes = [];
}
this.__excludes[this._index] = true;
this.drawSeries();
axes.each(function(axis) {
axis.drawAxis();
});
}
},
// @private show all markers
showAll: function() {
var axes = this.chart.axes;
if (!isNaN(this._index)) {
if (!this.__excludes) {
this.__excludes = [];
}
this.__excludes[this._index] = false;
this.drawSeries();
axes.each(function(axis) {
axis.drawAxis();
});
}
},
/**
* Returns a string with the color to be used for the series legend item.
* @param index
*/
getLegendColor: function(index) {
var me = this,
colorArrayStyle = me.colorArrayStyle;
return me.getColorFromStyle(colorArrayStyle[index % colorArrayStyle.length]);
},
highlightItem: function(item) {
Ext.chart.series.Bar.superclass.highlightItem.apply(this, arguments);
this.renderLabels();
},
unHighlightItem: function() {
Ext.chart.series.Bar.superclass.unHighlightItem.apply(this, arguments);
this.renderLabels();
},
cleanHighlights: function() {
Ext.chart.series.Bar.superclass.cleanHighlights.apply(this, arguments);
this.renderLabels();
},
reset: function() {
var me = this;
me.stacked = me.initialStacked;
Ext.chart.series.Bar.superclass.reset.call(me);
}
});
/**
* @class Ext.chart.series.Column
* @extends Ext.chart.series.Bar
*
* Creates a Column Chart. Much of the methods are inherited from Bar. A Column Chart is a useful visualization technique to display quantitative information for different
* categories that can show some progression (or regression) in the data set.
* As with all other series, the Column Series must be appended in the *series* Chart array configuration. See the Chart
* documentation for more information. A typical configuration object for the column series could be:
*
* {@img Ext.chart.series.Column/Ext.chart.series.Column.png Ext.chart.series.Column chart series
*
* ## Example
*
* var store = new Ext.data.JsonStore({
* fields: ['name', 'data1', 'data2', 'data3', 'data4', 'data5'],
* data: [
* {'name':'metric one', 'data1':10, 'data2':12, 'data3':14, 'data4':8, 'data5':13},
* {'name':'metric two', 'data1':7, 'data2':8, 'data3':16, 'data4':10, 'data5':3},
* {'name':'metric three', 'data1':5, 'data2':2, 'data3':14, 'data4':12, 'data5':7},
* {'name':'metric four', 'data1':2, 'data2':14, 'data3':6, 'data4':1, 'data5':23},
* {'name':'metric five', 'data1':27, 'data2':38, 'data3':36, 'data4':13, 'data5':33}
* ]
* });
*
* new Ext.chart.Chart({
* renderTo: Ext.getBody(),
* width: 500,
* height: 300,
* animate: true,
* store: store,
* axes: [{
* type: 'Numeric',
* position: 'bottom',
* fields: ['data1'],
* label: {
* renderer: Ext.util.Format.numberRenderer('0,0')
* },
* title: 'Sample Values',
* grid: true,
* minimum: 0
* }, {
* type: 'Category',
* position: 'left',
* fields: ['name'],
* title: 'Sample Metrics'
* }],
* axes: [{
* type: 'Numeric',
* position: 'left',
* fields: ['data1'],
* label: {
* renderer: Ext.util.Format.numberRenderer('0,0')
* },
* title: 'Sample Values',
* grid: true,
* minimum: 0
* }, {
* type: 'Category',
* position: 'bottom',
* fields: ['name'],
* title: 'Sample Metrics'
* }],
* series: [{
* type: 'column',
* axis: 'left',
* highlight: true,
* tips: {
* trackMouse: true,
* width: 140,
* height: 28,
* renderer: function(storeItem, item) {
* this.setTitle(storeItem.get('name') + ': ' + storeItem.get('data1') + ' $');
* }
* },
* label: {
* display: 'insideEnd',
* 'text-anchor': 'middle',
* field: 'data1',
* renderer: Ext.util.Format.numberRenderer('0'),
* orientation: 'vertical',
* color: '#333'
* },
* xField: 'name',
* yField: 'data1'
* }]
* });
*
* In this configuration we set `column` as the series type, bind the values of the bars to the bottom axis, set `highlight` to true so that bars are smoothly highlighted
* when hovered and bind the `xField` or category field to the data store `name` property and the `yField` as the data1 property of a store element.
*/
Ext.chart.series.Column = Ext.extend(Ext.chart.series.Bar, {
type: 'column',
column: true,
axis: 'left',
/**
* @cfg {Number} xPadding
* Padding between the left/right axes and the bars
*/
xPadding: 10,
/**
* @cfg {Number} yPadding
* Padding between the top/bottom axes and the bars
*/
yPadding: 0
});
/**
* @class Ext.chart.series.Gauge
* @extends Ext.chart.series.Series
*
* Creates a Gauge Chart. Gauge Charts are used to show progress in a certain variable. There are two ways of using the Gauge chart.
* One is setting a store element into the Gauge and selecting the field to be used from that store. Another one is instanciating the
* visualization and using the `setValue` method to adjust the value you want.
*
* A chart/series configuration for the Gauge visualization could look like this:
*
* {
* xtype: 'chart',
* store: store,
* axes: [{
* type: 'gauge',
* position: 'gauge',
* minimum: 0,
* maximum: 100,
* steps: 10,
* margin: -10
* }],
* series: [{
* type: 'gauge',
* angleField: 'data1',
* donut: false,
* colorSet: ['#F49D10', '#ddd']
* }]
* }
*
* In this configuration we create a special Gauge axis to be used with the gauge visualization (describing half-circle markers), and also we're
* setting a maximum, minimum and steps configuration options into the axis. The Gauge series configuration contains the store field to be bound to
* the visual display and the color set to be used with the visualization.
*
* @xtype gauge
*/
Ext.chart.series.Gauge = Ext.extend(Ext.chart.series.Series, {
type: "gauge",
rad: Math.PI / 180,
/**
* @cfg {String} angleField
* The store record field name to be used for the gauge angles.
* The values bound to this field name must be positive real numbers.
* This parameter is required.
*/
angleField: false,
/**
* @cfg {Boolean} needle
* Use the Gauge Series as an area series or add a needle to it. Default's false.
*/
needle: false,
/**
* @cfg {Boolean|Number} donut
* Use the entire disk or just a fraction of it for the gauge. Default's false.
*/
donut: false,
/**
* @cfg {Boolean} showInLegend
* Whether to add the gauge chart elements as legend items. Default's false.
*/
showInLegend: false,
/**
* @cfg {Object} style
* An object containing styles for overriding series styles from Theming.
*/
constructor: function(config) {
Ext.chart.series.Gauge.superclass.constructor.apply(this, arguments);
var me = this,
chart = me.chart,
surface = me.getSurface(),
shadow = chart.shadow, i, l;
Ext.apply(me, config, {
shadowAttributes: surface.getShadowAttributesArray(),
shadowOptions: surface.getShadowOptions()
});
me.group = surface.getGroup(me.seriesId);
if (shadow) {
for (i = 0, l = me.shadowAttributes.length; i < l; i++) {
me.shadowGroups.push(surface.getGroup(me.seriesId + '-shadows' + i));
}
}
surface.customAttributes.segment = function(opt) {
return me.getSegment(opt);
};
},
//@private updates some onbefore render parameters.
initialize: function() {
var me = this;
//Add yFields to be used in Legend.js
me.yField = [];
if (me.label.field) {
me.eachRecord(function(rec) {
me.yField.push(rec.get(me.label.field));
});
}
},
// @private returns an object with properties for a PieSlice.
getSegment: function(opt) {
var me = this,
rad = me.rad,
cos = Math.cos,
sin = Math.sin,
abs = Math.abs,
x = me.centerX,
y = me.centerY,
x1 = 0, x2 = 0, x3 = 0, x4 = 0,
y1 = 0, y2 = 0, y3 = 0, y4 = 0,
delta = 1e-2,
startAngle = opt.startAngle,
endAngle = opt.endAngle,
midAngle = (startAngle + endAngle) / 2 * rad,
margin = opt.margin || 0,
flag = abs(endAngle - startAngle) > 180,
auxValue = abs(endAngle % 360),
flag2 = auxValue > 90 && auxValue < 270,
a1 = Math.min(startAngle, endAngle) * rad,
a2 = Math.max(startAngle, endAngle) * rad,
singleSlice = false,
fullCircle = false;
x += margin * cos(midAngle);
y += margin * sin(midAngle);
x1 = x + opt.startRho * cos(a1);
y1 = y + opt.startRho * sin(a1);
x2 = x + opt.endRho * cos(a1);
y2 = y + opt.endRho * sin(a1);
x3 = x + opt.startRho * cos(a2);
y3 = y + opt.startRho * sin(a2);
x4 = x + opt.endRho * cos(a2);
y4 = y + opt.endRho * sin(a2);
if (abs(x1 - x3) <= delta && abs(y1 - y3) <= delta) {
singleSlice = true;
}
fullCircle = singleSlice && (abs(x2 - x4) <= delta && abs(y2 - y4) <= delta);
//Solves mysterious clipping bug with IE
if (fullCircle) {
return {
path: [
["M", x4, y4 - 1e-4],
["A", opt.endRho, opt.endRho, 0, +flag, +flag2, x4, y4],
["Z"]]
};
} else if (singleSlice) {
return {
path: [
["M", x1, y1],
["L", x2, y2],
["A", opt.endRho, opt.endRho, 0, +flag, 1, x4, y4],
["Z"]]
};
} else {
return {
path: [
["M", x1, y1],
["L", x2, y2],
["A", opt.endRho, opt.endRho, 0, +flag, 1, x4, y4],
["M", x4, y4],
["L", x3, y3],
["A", opt.startRho, opt.startRho, 0, +flag, 0, x1, y1],
["Z"]]
};
}
},
// @private utility function to calculate the middle point of a pie slice.
calcMiddle: function(item) {
var me = this,
rad = me.rad,
slice = item.slice,
x = me.centerX,
y = me.centerY,
startAngle = slice.startAngle,
endAngle = slice.endAngle,
a1 = Math.min(startAngle, endAngle) * rad,
a2 = Math.max(startAngle, endAngle) * rad,
midAngle = -(a1 + (a2 - a1) / 2),
xm = x + (item.endRho + item.startRho) / 2 * Math.cos(midAngle),
ym = y - (item.endRho + item.startRho) / 2 * Math.sin(midAngle);
item.middle = {
x: xm,
y: ym
};
},
/**
* Draws the series for the current chart.
*/
drawSeries: function() {
var me = this,
chart = me.chart,
store = chart.substore || chart.store,
group = me.group,
animate = me.chart.animate,
axis = me.chart.axes.get(0),
minimum = axis && axis.minimum || me.minimum || 0,
maximum = axis && axis.maximum || me.maximum || 0,
field = me.angleField || me.field || me.xField,
surface = me.getSurface(),
chartBBox = chart.chartBBox,
donut = +me.donut,
items = [],
seriesStyle = me.style,
colorArrayStyle = me.colorArrayStyle,
colorArrayLength = colorArrayStyle && colorArrayStyle.length || 0,
cos = Math.cos,
sin = Math.sin,
enableShadows = !!chart.shadow,
rendererAttributes, centerX, centerY, slice, slices, sprite, value,
item, ln, record, i, path,
p, spriteOptions, bbox, splitAngle, sliceA, sliceB;
if (me.fireEvent('beforedraw', me) === false) {
return;
}
Ext.chart.series.Gauge.superclass.drawSeries.call(this);
me.setBBox();
bbox = me.bbox;
//override theme colors
if (me.colorSet) {
colorArrayStyle = me.colorSet;
colorArrayLength = colorArrayStyle.length;
}
//if not store or store is empty then there's nothing to draw
if (!me.getRecordCount()) {
surface.items.hide(true);
return;
}
centerX = me.centerX = (chartBBox.width / 2);
centerY = me.centerY = chartBBox.height;
me.radius = Math.min(centerX, centerY);
me.slices = slices = [];
me.items = items = [];
if (!me.value) {
record = store.getAt(0);
me.value = record.get(field);
}
value = me.value;
if (me.needle) {
sliceA = {
series: me,
value: value,
startAngle: -180,
endAngle: 0,
rho: me.radius
};
splitAngle = -180 * (1 - (value - minimum) / (maximum - minimum));
slices.push(sliceA);
} else {
splitAngle = -180 * (1 - (value - minimum) / (maximum - minimum));
sliceA = {
series: me,
value: value,
startAngle: -180,
endAngle: splitAngle,
rho: me.radius
};
sliceB = {
series: me,
value: me.maximum - value,
startAngle: splitAngle,
endAngle: 0,
rho: me.radius
};
slices.push(sliceA, sliceB);
}
//do pie slices after.
for (i = 0, ln = slices.length; i < ln; i++) {
slice = slices[i];
sprite = group.getAt(i);
//set pie slice properties
rendererAttributes = Ext.apply({
segment: {
startAngle: slice.startAngle,
endAngle: slice.endAngle,
margin: 0,
rho: slice.rho,
startRho: slice.rho * +donut / 100,
endRho: slice.rho
}
}, Ext.apply(seriesStyle, colorArrayStyle && { fill: colorArrayStyle[i % colorArrayLength] } || {}));
item = Ext.apply({},
rendererAttributes.segment, {
slice: slice,
series: me,
storeItem: record,
index: i
});
items[i] = item;
// Create a new sprite if needed (no height)
if (!sprite) {
spriteOptions = Ext.apply({
type: "path",
group: group
}, Ext.apply(seriesStyle, colorArrayStyle && { fill: colorArrayStyle[i % colorArrayLength] } || {}));
if (enableShadows) {
Ext.apply(spriteOptions, me.shadowOptions);
}
sprite = surface.add(Ext.apply(spriteOptions, rendererAttributes));
}
slice.sprite = slice.sprite || [];
item.sprite = sprite;
slice.sprite.push(sprite);
if (animate) {
rendererAttributes = me.renderer(sprite, record, rendererAttributes, i, store);
sprite._to = rendererAttributes;
me.onAnimate(sprite, {
to: rendererAttributes
});
} else {
rendererAttributes = me.renderer(sprite, record, Ext.apply(rendererAttributes, {
hidden: false
}), i, store);
sprite.setAttributes(rendererAttributes, true);
}
}
if (me.needle) {
splitAngle = splitAngle * Math.PI / 180;
if (!me.needleSprite) {
me.needleSprite = me.getSurface().add({
type: 'path',
path: ['M', centerX + (me.radius * +donut / 100) * cos(splitAngle),
centerY + -Math.abs((me.radius * +donut / 100) * sin(splitAngle)),
'L', centerX + me.radius * cos(splitAngle),
centerY + -Math.abs(me.radius * sin(splitAngle))],
'stroke-width': 4,
'stroke': '#222'
});
} else {
if (animate) {
me.onAnimate(me.needleSprite, {
to: {
path: ['M', centerX + (me.radius * +donut / 100) * cos(splitAngle),
centerY + -Math.abs((me.radius * +donut / 100) * sin(splitAngle)),
'L', centerX + me.radius * cos(splitAngle),
centerY + -Math.abs(me.radius * sin(splitAngle))]
}
});
} else {
me.needleSprite.setAttributes({
type: 'path',
path: ['M', centerX + (me.radius * +donut / 100) * cos(splitAngle),
centerY + -Math.abs((me.radius * +donut / 100) * sin(splitAngle)),
'L', centerX + me.radius * cos(splitAngle),
centerY + -Math.abs(me.radius * sin(splitAngle))]
});
}
}
me.needleSprite.setAttributes({
hidden: false
}, true);
}
delete me.value;
me.fireEvent('draw', me);
},
/**
* Sets the Gauge chart to the current specified value.
*/
setValue: function (value) {
this.value = value;
this.drawSeries();
},
// @private callback for when creating a label sprite.
onCreateLabel: Ext.emptyFn,
// @private callback for when placing a label sprite.
onPlaceLabel: Ext.emptyFn,
// @private callback for when placing a callout.
onPlaceCallout: Ext.emptyFn,
// @private handles sprite animation for the series.
onAnimate: function(sprite, attr) {
sprite.show();
Ext.chart.series.Gauge.superclass.onAnimate.apply(this, arguments);
},
isItemInPoint: function() {
return false;
},
// @private shows all elements in the series.
showAll: function() {
if (!isNaN(this._index)) {
this.__excludes[this._index] = false;
this.drawSeries();
}
},
/**
* Returns the color of the series (to be displayed as color for the series legend item).
* @param index {Number} Info about the item; same format as returned by #getItemForPoint
*/
getLegendColor: function(index) {
var me = this,
colorArrayStyle = me.colorArrayStyle;
return me.getColorFromStyle(colorArrayStyle[index % colorArrayStyle.length]);
}
});
/**
* @class Ext.chart.series.Line
* @extends Ext.chart.series.Cartesian
*
* Creates a Line Chart. A Line Chart is a useful visualization technique to display quantitative information for different
* categories or other real values (as opposed to the bar chart), that can show some progression (or regression) in the dataset.
* As with all other series, the Line Series must be appended in the *series* Chart array configuration. See the Chart
* documentation for more information. A typical configuration object for the line series could be:
*
* {@img Ext.chart.series.Line/Ext.chart.series.Line.png Ext.chart.series.Line chart series}
*
* var store = new Ext.data.JsonStore({
* fields: ['name', 'data1', 'data2', 'data3', 'data4', 'data5'],
* data: [
* {'name':'metric one', 'data1':10, 'data2':12, 'data3':14, 'data4':8, 'data5':13},
* {'name':'metric two', 'data1':7, 'data2':8, 'data3':16, 'data4':10, 'data5':3},
* {'name':'metric three', 'data1':5, 'data2':2, 'data3':14, 'data4':12, 'data5':7},
* {'name':'metric four', 'data1':2, 'data2':14, 'data3':6, 'data4':1, 'data5':23},
* {'name':'metric five', 'data1':27, 'data2':38, 'data3':36, 'data4':13, 'data5':33}
* ]
* });
*
* new Ext.chart.Chart({
* renderTo: Ext.getBody(),
* width: 500,
* height: 300,
* animate: true,
* store: store,
* axes: [{
* type: 'Numeric',
* position: 'bottom',
* fields: ['data1'],
* label: {
* renderer: Ext.util.Format.numberRenderer('0,0')
* },
* title: 'Sample Values',
* grid: true,
* minimum: 0
* }, {
* type: 'Category',
* position: 'left',
* fields: ['name'],
* title: 'Sample Metrics'
* }],
* series: [{
* type: 'line',
* highlight: {
* size: 7,
* radius: 7
* },
* axis: 'left',
* xField: 'name',
* yField: 'data1',
* markerCfg: {
* type: 'cross',
* size: 4,
* radius: 4,
* 'stroke-width': 0
* }
* }, {
* type: 'line',
* highlight: {
* size: 7,
* radius: 7
* },
* axis: 'left',
* fill: true,
* xField: 'name',
* yField: 'data3',
* markerCfg: {
* type: 'circle',
* size: 4,
* radius: 4,
* 'stroke-width': 0
* }
* }]
* });
*
* In this configuration we're adding two series (or lines), one bound to the `data1`
* property of the store and the other to `data3`. The type for both configurations is
* `line`. The `xField` for both series is the same, the name propert of the store.
* Both line series share the same axis, the left axis. You can set particular marker
* configuration by adding properties onto the markerConfig object. Both series have
* an object as highlight so that markers animate smoothly to the properties in highlight
* when hovered. The second series has `fill=true` which means that the line will also
* have an area below it of the same color.
*
* **Note:** In the series definition remember to explicitly set the axis to bind the
* values of the line series to. This can be done by using the `axis` configuration property.
*/
Ext.chart.series.Line = Ext.extend(Ext.chart.series.Cartesian, {
type: 'line',
/**
* @cfg {String} axis
* The position of the axis to bind the values to. Possible values are 'left', 'bottom', 'top' and 'right'.
* You must explicitly set this value to bind the values of the line series to the ones in the axis, otherwise a
* relative scale will be used.
*/
/**
* @cfg {Number} selectionTolerance
* The offset distance from the cursor position to the line series to trigger events (then used for highlighting series, etc).
*/
selectionTolerance: 20,
/**
* @cfg {Boolean} showMarkers
* Whether markers should be displayed at the data points along the line. If true,
* then the {@link #markerConfig} config item will determine the markers' styling.
*/
showMarkers: true,
/**
* @cfg {Object} markerConfig
* The display style for the markers. Only used if {@link #showMarkers} is true.
* The markerConfig is a configuration object containing the same set of properties defined in
* the Sprite class. For example, if we were to set red circles as markers to the line series we could
* pass the object:
*
<pre><code>
markerConfig: {
type: 'circle',
radius: 4,
'fill': '#f00'
}
</code></pre>
*/
markerConfig: {},
/**
* @cfg {Object} style
* An object containing styles for the visualization lines. These styles will override the theme styles.
* Some options contained within the style object will are described next.
*/
/**
* @cfg {Boolean/Number} smooth
* If set to `true` or a non-zero number, the line will be smoothed/rounded around its points; otherwise
* straight line segments will be drawn.
*
* A numeric value is interpreted as a divisor of the horizontal distance between consecutive points in
* the line; larger numbers result in sharper curves while smaller numbers result in smoother curves.
*
* If set to `true` then a default numeric value of 3 will be used. Defaults to `false`.
*/
smooth: false,
/**
* @private Default numeric smoothing value to be used when {@link #smooth} = true.
*/
defaultSmoothness: 3,
/**
* @cfg {Boolean} fill
* If true, the area below the line will be filled using either the styles defined with sass or
* {@link #style.eefill} and {@link #style.opacity} config properties from {@link style}. Defaults to false.
*/
fill: false,
/**
* @private Size of the buffer area on either side of the viewport to provide seamless zoom/pan
* transforms. Expressed as a multiple of the viewport length, e.g. 1 will make the buffer on
* each side equal to the length of the visible axis viewport.
*/
overflowBuffer: 1,
constructor: function(config) {
Ext.chart.series.Line.superclass.constructor.apply(this, arguments);
var me = this,
surface = me.getSurface(),
shadow = me.chart.shadow,
//get android version (if any)
force = true,
i, l;
Ext.apply(me, config, {
//get shadow as sprites (if force is true --for android > 2)
shadowAttributes: surface.getShadowAttributesArray(force),
//get canvas shadow options.
shadowOptions: force && {} || Ext.apply(surface.getShadowOptions(), shadow === true ? {} : (shadow || {}))
});
me.group = surface.getGroup(me.seriesId);
if (me.showMarkers) {
me.markerGroup = surface.getGroup(me.seriesId + '-markers');
}
if (shadow) {
for (i = 0, l = this.shadowAttributes.length; i < l; i++) {
me.shadowGroups.push(surface.getGroup(me.seriesId + '-shadows' + i));
}
}
},
// @private makes an average of points when there are more data points than pixels to be rendered.
shrink: function(xValues, yValues, size) {
// Start at the 2nd point...
var len = xValues.length,
ratio = Math.floor(len / size),
i = 1,
xSum = 0,
ySum = 0,
xRes = [xValues[0]],
yRes = [yValues[0]];
for (; i < len; ++i) {
xSum += xValues[i] || 0;
ySum += yValues[i] || 0;
if (i % ratio == 0) {
xRes.push(xSum/ratio);
yRes.push(ySum/ratio);
xSum = 0;
ySum = 0;
}
}
return {
x: xRes,
y: yRes
};
},
/**
* Draws the series for the current chart.
*/
drawSeries: function() {
var me = this,
chart = me.chart,
store = chart.substore || chart.store,
storeCount = me.getRecordCount(),
bufferWidth = chart.chartBBox.width * me.overflowBuffer,
surface = me.getSurface(),
bbox = {},
group = me.group,
showMarkers = me.showMarkers,
markerGroup = me.markerGroup,
enableShadows = chart.shadow,
shadowGroups = me.shadowGroups,
shadowAttributes = me.shadowAttributes,
smooth = me.smooth,
lnsh = shadowGroups.length,
dummyPath = ["M"],
path = ["M"],
markerIndex = chart.markerIndex,
axes = [].concat(me.axis),
shadowBarAttr,
xValues = [],
yValues = [],
onbreak = false,
markerStyle = me.markerStyle.style,
seriesStyle = me.style,
colorArrayStyle = me.colorArrayStyle,
colorArrayLength = colorArrayStyle && colorArrayStyle.length || 0,
isNumber = Ext.isNumber,
seriesIdx = me.seriesIdx, shadows, shadow, shindex, fromPath, fill, fillPath, rendererAttributes,
x, y, prevX, prevY, firstX, firstY, markerCount, i, j, ln, axis, ends, marker, markerAux, item, xValue,
yValue, coords, xScale, yScale, minX, maxX, minY, maxY, line, animation, endMarkerStyle,
endLineStyle, type, count, bufferMinX, bufferMaxX;
if (me.fireEvent('beforedraw', me) === false) {
return;
}
Ext.chart.series.Line.superclass.drawSeries.call(this);
//if store is empty or the series is excluded in the legend then there's nothing to draw.
if (!storeCount || me.seriesIsHidden) {
surface.items.hide(true);
return;
}
//prepare style objects for line and markers
endMarkerStyle = Ext.apply({}, markerStyle, me.markerConfig);
type = endMarkerStyle.type;
delete endMarkerStyle.type;
endLineStyle = seriesStyle;
//if no stroke with is specified force it to 0.5 because this is
//about making *lines*
if (!endLineStyle['stroke-width']) {
endLineStyle['stroke-width'] = 0.5;
}
//If we're using a time axis and we need to translate the points,
//then reuse the first markers as the last markers.
if (markerIndex && markerGroup && markerGroup.getCount()) {
for (i = 0; i < markerIndex; i++) {
marker = markerGroup.getAt(i);
markerGroup.remove(marker);
markerGroup.add(marker);
markerAux = markerGroup.getAt(markerGroup.getCount() - 2);
marker.setAttributes({
x: 0,
y: 0,
translate: {
x: markerAux.attr.translation.x,
y: markerAux.attr.translation.y
}
}, true);
}
}
me.unHighlightItem();
me.cleanHighlights();
me.setBBox();
bbox = me.bbox;
me.clipRect = [bbox.x, bbox.y, bbox.width, bbox.height];
for (i = 0, ln = axes.length; i < ln; i++) {
axis = chart.axes.get(axes[i]);
if (axis) {
ends = axis.calcEnds();
if (axis.position == 'top' || axis.position == 'bottom') {
minX = ends.from;
maxX = ends.to;
}
else {
minY = ends.from;
maxY = ends.to;
}
}
}
// If a field was specified without a corresponding axis, create one to get bounds
//only do this for the axis where real values are bound (that's why we check for
//me.axis)
if (me.xField && !isNumber(minX)
&& (me.axis == 'bottom' || me.axis == 'top')) {
axis = new Ext.chart.axis.Axis({
chart: chart,
fields: [].concat(me.xField)
}).calcEnds();
minX = axis.from;
maxX = axis.to;
}
if (me.yField && !isNumber(minY)
&& (me.axis == 'right' || me.axis == 'left')) {
axis = new Ext.chart.axis.Axis({
chart: chart,
fields: [].concat(me.yField)
}).calcEnds();
minY = axis.from;
maxY = axis.to;
}
if (isNaN(minX)) {
minX = 0;
xScale = bbox.width / ((storeCount - 1) || 1);
}
else {
xScale = bbox.width / ((maxX - minX) || (storeCount -1) || 1);
}
if (isNaN(minY)) {
minY = 0;
yScale = bbox.height / ((storeCount - 1) || 1);
}
else {
yScale = bbox.height / ((maxY - minY) || 1);
}
// Find the min and max x values that fit within the zoom/pan buffer area
bufferMinX = minX - (bufferWidth + me.panX) / xScale;
bufferMaxX = bufferMinX + (bufferWidth * 2 + chart.chartBBox.width) / xScale;
// Extract all x and y values from the store
me.eachRecord(function(record, i) {
xValue = record.get(me.xField);
// Ensure a value
if (typeof xValue == 'string' || typeof xValue == 'object'
//set as uniform distribution if the axis is a category axis.
|| (me.axis != 'top' && me.axis != 'bottom')) {
xValue = i;
}
// Filter out values that don't fit within the pan/zoom buffer area
if (xValue >= bufferMinX && xValue <= bufferMaxX) {
yValue = record.get(me.yField);
//skip undefined values
if (typeof yValue == 'undefined' || (typeof yValue == 'string' && !yValue)) {
return;
}
// Ensure a value
if (typeof yValue == 'string' || typeof yValue == 'object'
//set as uniform distribution if the axis is a category axis.
|| (me.axis != 'left' && me.axis != 'right')) {
yValue = i;
}
xValues.push(xValue);
yValues.push(yValue);
}
});
ln = xValues.length;
if (ln > bbox.width) {
coords = me.shrink(xValues, yValues, bbox.width);
xValues = coords.x;
yValues = coords.y;
}
me.items = [];
count = 0;
ln = xValues.length;
for (i = 0; i < ln; i++) {
xValue = xValues[i];
yValue = yValues[i];
if (yValue === false) {
if (path.length == 1) {
path = [];
}
onbreak = true;
me.items.push(false);
continue;
} else {
x = (bbox.x + (xValue - minX) * xScale).toFixed(2);
y = ((bbox.y + bbox.height) - (yValue - minY) * yScale).toFixed(2);
if (onbreak) {
onbreak = false;
path.push('M');
}
path = path.concat([x, y]);
}
if ((typeof firstY == 'undefined') && (typeof y != 'undefined')) {
firstY = y;
firstX = x;
}
// If this is the first line, create a dummypath to animate in from.
if (!me.line || chart.resizing) {
dummyPath = dummyPath.concat([x, bbox.y + bbox.height / 2]);
}
// When resizing, reset before animating
if (chart.animate && chart.resizing && me.line) {
me.line.setAttributes({
path: dummyPath
}, true);
if (me.fillPath) {
me.fillPath.setAttributes({
path: dummyPath,
opacity: 0.2
}, true);
}
if (me.line.shadows) {
shadows = me.line.shadows;
for (j = 0, lnsh = shadows.length; j < lnsh; j++) {
shadow = shadows[j];
shadow.setAttributes({
path: dummyPath
}, true);
}
}
}
if (showMarkers) {
marker = markerGroup.getAt(count++);
if (!marker) {
marker = Ext.chart.Shape[type](surface, Ext.apply({
group: [group, markerGroup],
x: 0, y: 0,
translate: {
x: prevX || x,
y: prevY || (bbox.y + bbox.height / 2)
},
value: '"' + xValue + ', ' + yValue + '"',
zIndex: 4000
}, endMarkerStyle));
marker._to = {
translate: {
x: x,
y: y
}
};
} else {
marker.setAttributes({
value: '"' + xValue + ', ' + yValue + '"',
x: 0, y: 0,
hidden: false
}, true);
marker._to = {
translate: {
x: x, y: y
}
};
}
}
me.items.push({
series: me,
value: [xValue, yValue],
point: [x, y],
sprite: marker,
storeItem: store.getAt(i)
});
prevX = x;
prevY = y;
}
if (path.length <= 1) {
//nothing to be rendered
return;
}
if (me.smooth) {
path = Ext.draw.Draw.smooth(path, isNumber(smooth) ? smooth : me.defaultSmoothness);
}
//Correct path if we're animating timeAxis intervals
if (chart.markerIndex && me.previousPath) {
fromPath = me.previousPath;
fromPath.splice(1, 2);
} else {
fromPath = path;
}
// Only create a line if one doesn't exist.
if (!me.line) {
me.line = surface.add(Ext.apply({
type: 'path',
group: group,
path: dummyPath,
stroke: endLineStyle.stroke || endLineStyle.fill
}, endLineStyle || {}));
if (enableShadows) {
me.line.setAttributes(Ext.apply({}, me.shadowOptions), true);
}
//unset fill here (there's always a default fill withing the themes).
me.line.setAttributes({
fill: 'none',
zIndex: 3000
});
if (!endLineStyle.stroke && colorArrayLength) {
me.line.setAttributes({
stroke: colorArrayStyle[seriesIdx % colorArrayLength]
}, true);
}
if (enableShadows) {
//create shadows
shadows = me.line.shadows = [];
for (shindex = 0; shindex < lnsh; shindex++) {
shadowBarAttr = shadowAttributes[shindex];
shadowBarAttr = Ext.apply({}, shadowBarAttr, { path: dummyPath });
shadow = surface.add(Ext.apply({}, {
type: 'path',
group: shadowGroups[shindex]
}, shadowBarAttr));
shadows.push(shadow);
}
}
}
if (me.fill) {
fillPath = path.concat([
["L", x, bbox.y + bbox.height],
["L", firstX, bbox.y + bbox.height],
["L", firstX, firstY]
]);
if (!me.fillPath) {
me.fillPath = surface.add({
group: group,
type: 'path',
opacity: endLineStyle.opacity || 0.3,
fill: endLineStyle.fill || colorArrayStyle[seriesIdx % colorArrayLength],
path: dummyPath
});
}
}
markerCount = showMarkers && markerGroup.getCount();
if (chart.animate) {
fill = me.fill;
line = me.line;
//Add renderer to line. There is not unique record associated with this.
rendererAttributes = me.renderer(line, false, { path: path }, i, store);
Ext.apply(rendererAttributes, endLineStyle || {}, {
stroke: endLineStyle.stroke || endLineStyle.fill
});
//fill should not be used here but when drawing the special fill path object
delete rendererAttributes.fill;
line.show(true);
if (chart.markerIndex && me.previousPath) {
me.animation = animation = me.onAnimate(line, {
to: rendererAttributes,
from: {
path: fromPath
}
});
} else {
me.animation = animation = me.onAnimate(line, {
to: rendererAttributes
});
}
//animate shadows
if (enableShadows) {
shadows = line.shadows;
for(j = 0; j < lnsh; j++) {
shadows[j].show(true);
if (chart.markerIndex && me.previousPath) {
me.onAnimate(shadows[j], {
to: { path: path },
from: { path: fromPath }
});
} else {
me.onAnimate(shadows[j], {
to: { path: path }
});
}
}
}
//animate fill path
if (fill) {
me.fillPath.show(true);
me.onAnimate(me.fillPath, {
to: Ext.apply({}, {
path: fillPath,
fill: endLineStyle.fill || colorArrayStyle[seriesIdx % colorArrayLength],
'stroke-width': 0
}, endLineStyle || {})
});
}
//animate markers
if (showMarkers) {
count = 0;
for(i = 0; i < ln; i++) {
if (me.items[i]) {
item = markerGroup.getAt(count++);
if (item) {
rendererAttributes = me.renderer(item, store.getAt(i), item._to, i, store);
me.onAnimate(item, {
to: Ext.apply(rendererAttributes, endMarkerStyle || {})
});
item.show(true);
}
}
}
for(; count < markerCount; count++) {
item = markerGroup.getAt(count);
item.hide(true);
}
// for(i = 0; i < (chart.markerIndex || 0)-1; i++) {
// item = markerGroup.getAt(i);
// item.hide(true);
// }
}
} else {
rendererAttributes = me.renderer(me.line, false, { path: path, hidden: false }, i, store);
Ext.apply(rendererAttributes, endLineStyle || {}, {
stroke: endLineStyle.stroke || endLineStyle.fill
});
//fill should not be used here but when drawing the special fill path object
delete rendererAttributes.fill;
me.line.setAttributes(rendererAttributes, true);
//set path for shadows
if (enableShadows) {
shadows = me.line.shadows;
for(j = 0; j < lnsh; j++) {
shadows[j].setAttributes({
path: path,
hidden: false
}, true);
}
}
if (me.fill) {
me.fillPath.setAttributes({
path: fillPath,
hidden: false
}, true);
}
if (showMarkers) {
count = 0;
for(i = 0; i < ln; i++) {
if (me.items[i]) {
item = markerGroup.getAt(count++);
if (item) {
rendererAttributes = me.renderer(item, store.getAt(i), item._to, i, store);
item.setAttributes(Ext.apply(endMarkerStyle || {}, rendererAttributes || {}), true);
item.show(true);
}
}
}
for(; count < markerCount; count++) {
item = markerGroup.getAt(count);
item.hide(true);
}
}
}
if (chart.markerIndex) {
path.splice(1, 0, path[1], path[2]);
me.previousPath = path;
}
me.renderLabels();
me.renderCallouts();
me.fireEvent('draw', me);
},
// @private called when a label is to be created.
onCreateLabel: function(storeItem, item, i, display) {
var me = this,
group = me.labelsGroup,
config = me.label,
bbox = me.bbox,
endLabelStyle = Ext.apply(config, me.labelStyle.style);
return me.getSurface().add(Ext.apply({
'type': 'text',
'text-anchor': 'middle',
'group': group,
'x': item.point[0],
'y': bbox.y + bbox.height / 2,
zIndex: 200
}, endLabelStyle || {}));
},
// @private called when a label is to be created.
onPlaceLabel: function(label, storeItem, item, i, display, animate) {
var me = this,
chart = me.chart,
resizing = chart.resizing,
config = me.label,
format = config.renderer,
field = config.field,
bbox = me.bbox,
x = item.point[0],
y = item.point[1],
radius = item.sprite.attr.radius,
bb, width, height;
label.setAttributes({
text: format(storeItem.get(field)),
hidden: true
}, true);
if (display == 'rotate') {
label.setAttributes({
'text-anchor': 'start',
'rotation': {
x: x,
y: y,
degrees: -45
}
}, true);
//correct label position to fit into the box
bb = label.getBBox();
width = bb.width;
height = bb.height;
x = x < bbox.x? bbox.x : x;
x = (x + width > bbox.x + bbox.width)? (x - (x + width - bbox.x - bbox.width)) : x;
y = (y - height < bbox.y)? bbox.y + height : y;
} else if (display == 'under' || display == 'over') {
//TODO(nicolas): find out why width/height values in circle bounding boxes are undefined.
bb = item.sprite.getBBox();
bb.width = bb.width || (radius * 2);
bb.height = bb.height || (radius * 2);
y = y + (display == 'over'? -bb.height : bb.height);
//correct label position to fit into the box
bb = label.getBBox();
width = bb.width/2;
height = bb.height/2;
x = x - width < bbox.x? bbox.x + width : x;
x = (x + width > bbox.x + bbox.width) ? (x - (x + width - bbox.x - bbox.width)) : x;
y = y - height < bbox.y? bbox.y + height : y;
y = (y + height > bbox.y + bbox.height) ? (y - (y + height - bbox.y - bbox.height)) : y;
}
if (me.chart.animate && !me.chart.resizing) {
label.show(true);
me.onAnimate(label, {
to: {
x: x,
y: y
}
});
} else {
label.setAttributes({
x: x,
y: y
}, true);
if (resizing) {
me.animation.on('afteranimate', function() {
label.show(true);
});
} else {
label.show(true);
}
}
},
//@private Overriding highlights.js highlightItem method.
highlightItem: function(item) {
var me = this,
line = me.line,
marker, markerStyle, markerType;
Ext.chart.series.Line.superclass.highlightItem.call(me, item);
if (line && !me.highlighted) {
if (!('__strokeWidth' in line)) {
line.__strokeWidth = line.attr['stroke-width'] || 0;
}
if (line.__anim) {
line.__anim.paused = true;
}
line.__anim = new Ext.fx.Anim({
target: line,
to: {
'stroke-width': line.__strokeWidth + 3
}
});
me.highlighted = true;
}
// If no markers are configured, we still want to display one at the highlighted point
// so the user can see what was highlighted.
if (!me.showMarkers) {
marker = me.highlightMarker;
if (!marker) {
markerStyle = Ext.apply({}, me.markerStyle.style, me.markerConfig);
markerType = markerStyle.type;
delete markerStyle.type;
marker = me.highlightMarker = Ext.chart.Shape[markerType](me.getSurface(), Ext.apply({x: 0, y: 0}, markerStyle));
}
marker.setAttributes({
translate: {
x: item.point[0],
y: item.point[1]
},
hidden: false
}, true);
}
},
//@private Overriding highlights.js unHighlightItem method.
unHighlightItem: function() {
var me = this,
line = me.line,
marker = me.highlightMarker;
Ext.chart.series.Line.superclass.unHighlightItem.call(me);
if (line && me.highlighted) {
line.__anim = new Ext.fx.Anim({
target: line,
to: {
'stroke-width': line.__strokeWidth
}
});
me.highlighted = false;
}
if (marker) {
marker.hide(true);
}
},
//@private called when a callout needs to be placed.
onPlaceCallout : function(callout, storeItem, item, i, display, animate, index) {
if (!display) {
return;
}
var me = this,
chart = me.chart,
config = me.callouts,
items = me.items,
prev = i == 0? false : items[i -1].point,
next = (i == items.length -1)? false : items[i +1].point,
cur = [+item.point[0], +item.point[1]],
dir, norm, normal, a, aprev, anext,
offsetFromViz = config.offsetFromViz || 30,
offsetBox = config.offsetBox || 3,
boxx, boxy, boxw, boxh,
p, clipRect = me.clipRect,
bbox = {
width: config.styles.width || 10,
height: config.styles.height || 10
},
x, y;
//get the right two points
if (!prev) {
prev = cur;
}
if (!next) {
next = cur;
}
a = (next[1] - prev[1]) / (next[0] - prev[0]);
aprev = (cur[1] - prev[1]) / (cur[0] - prev[0]);
anext = (next[1] - cur[1]) / (next[0] - cur[0]);
norm = Math.sqrt(1 + a * a);
dir = [1 / norm, a / norm];
normal = [-dir[1], dir[0]];
//keep the label always on the outer part of the "elbow"
if (aprev > 0 && anext < 0 && normal[1] < 0
|| aprev < 0 && anext > 0 && normal[1] > 0) {
normal[0] *= -1;
normal[1] *= -1;
} else if (Math.abs(aprev) < Math.abs(anext) && normal[0] < 0
|| Math.abs(aprev) > Math.abs(anext) && normal[0] > 0) {
normal[0] *= -1;
normal[1] *= -1;
}
//position
x = cur[0] + normal[0] * offsetFromViz;
y = cur[1] + normal[1] * offsetFromViz;
//box position and dimensions
boxx = x + (normal[0] > 0? 0 : -(bbox.width + 2 * offsetBox));
boxy = y - bbox.height /2 - offsetBox;
boxw = bbox.width + 2 * offsetBox;
boxh = bbox.height + 2 * offsetBox;
//now check if we're out of bounds and invert the normal vector correspondingly
//this may add new overlaps between labels (but labels won't be out of bounds).
if (boxx < clipRect[0] || (boxx + boxw) > (clipRect[0] + clipRect[2])) {
normal[0] *= -1;
}
if (boxy < clipRect[1] || (boxy + boxh) > (clipRect[1] + clipRect[3])) {
normal[1] *= -1;
}
//update positions
x = cur[0] + normal[0] * offsetFromViz;
y = cur[1] + normal[1] * offsetFromViz;
//update box position and dimensions
boxx = x + (normal[0] > 0? 0 : -(bbox.width + 2 * offsetBox));
boxy = y - bbox.height /2 - offsetBox;
boxw = bbox.width + 2 * offsetBox;
boxh = bbox.height + 2 * offsetBox;
if (chart.animate) {
//set the line from the middle of the pie to the box.
me.onAnimate(callout.lines, {
to: {
path: ["M", cur[0], cur[1], "L", x, y, "Z"]
}
});
//set component position
if (callout.panel) {
callout.panel.setPosition(boxx, boxy, true);
}
}
else {
//set the line from the middle of the pie to the box.
callout.lines.setAttributes({
path: ["M", cur[0], cur[1], "L", x, y, "Z"]
}, true);
//set component position
if (callout.panel) {
callout.panel.setPosition(boxx, boxy);
}
}
for (p in callout) {
callout[p].show(true);
}
},
isItemInPoint: function(x, y, item, i) {
var me = this,
items = me.items,
tolerance = me.selectionTolerance,
point, diffX, diffY, dist,
sqrt = Math.sqrt;
// See if the target item is within the selectionTolerance distance from the x/y point
point = item.point;
diffX = x - point[0];
diffY = y - point[1];
dist = sqrt(diffX * diffX + diffY * diffY);
if (dist <= tolerance) {
// We have a match, but it's possible the previous or next item are even closer, so check them
if (i > 0 && items[i - 1]) {
point = items[i - 1].point;
diffX = x - point[0];
diffY = y - point[1];
if (sqrt(diffX * diffX + diffY * diffY) < dist) {
return false;
}
}
if (items[i + 1]) {
point = items[i + 1].point;
diffX = x - point[0];
diffY = y - point[1];
if (sqrt(diffX * diffX + diffY * diffY) < dist) {
return false;
}
}
return true;
}
return false;
},
// @private toggle visibility of all series elements (markers, sprites).
toggleAll: function(show) {
var me = this,
i, ln, shadow, shadows;
if (!show) {
Ext.chart.series.Line.superclass.hideAll.call(me);
}
else {
Ext.chart.series.Line.superclass.showAll.call(me);
}
if (me.line) {
me.line.setAttributes({
hidden: !show
}, true);
//hide shadows too
if (me.line.shadows) {
for (i = 0, shadows = me.line.shadows, ln = shadows.length; i < ln; i++) {
shadow = shadows[i];
shadow.setAttributes({
hidden: !show
}, true);
}
}
}
if (me.fillPath) {
me.fillPath.setAttributes({
hidden: !show
}, true);
}
},
// @private hide all series elements (markers, sprites).
hideAll: function() {
this.toggleAll(false);
},
// @private hide all series elements (markers, sprites).
showAll: function() {
this.toggleAll(true);
}
});
/**
* @class Ext.chart.series.Pie
* @extends Ext.chart.series.Series
*
* Creates a Pie Chart. A Pie Chart is a useful visualization technique to display quantitative information for different
* categories that also have a meaning as a whole.
* As with all other series, the Pie Series must be appended in the *series* Chart array configuration. See the Chart
* documentation for more information. A typical configuration object for the pie series could be:
*
* {@img Ext.chart.series.Pie/Ext.chart.series.Pie.png Ext.chart.series.Pie chart series}
*
* var store = new Ext.data.JsonStore({
* fields: ['name', 'data1', 'data2', 'data3', 'data4', 'data5'],
* data: [
* {'name':'metric one', 'data1':10, 'data2':12, 'data3':14, 'data4':8, 'data5':13},
* {'name':'metric two', 'data1':7, 'data2':8, 'data3':16, 'data4':10, 'data5':3},
* {'name':'metric three', 'data1':5, 'data2':2, 'data3':14, 'data4':12, 'data5':7},
* {'name':'metric four', 'data1':2, 'data2':14, 'data3':6, 'data4':1, 'data5':23},
* {'name':'metric five', 'data1':27, 'data2':38, 'data3':36, 'data4':13, 'data5':33}
* ]
* });
*
* new Ext.chart.Chart({
* renderTo: Ext.getBody(),
* width: 500,
* height: 300,
* animate: true,
* store: store,
* theme: 'Base:gradients',
* series: [{
* type: 'pie',
* angleField: 'data1',
* showInLegend: true,
* tips: {
* trackMouse: true,
* width: 140,
* height: 28,
* renderer: function(storeItem, item) {
* //calculate and display percentage on hover
* var total = 0;
* store.each(function(rec) {
* total += rec.get('data1');
* });
* this.setTitle(storeItem.get('name') + ': ' + Math.round(storeItem.get('data1') / total * 100) + '%');
* }
* },
* highlight: {
* segment: {
* margin: 20
* }
* },
* label: {
* field: 'name',
* display: 'rotate',
* contrast: true,
* font: '18px Arial'
* }
* }]
* });
*
* In this configuration we set `pie` as the type for the series, set an object with specific style properties for highlighting options
* (triggered when hovering elements). We also set true to `showInLegend` so all the pie slices can be represented by a legend item.
* We set `data1` as the value of the field to determine the angle span for each pie slice. We also set a label configuration object
* where we set the field name of the store field to be renderer as text for the label. The labels will also be displayed rotated.
* We set `contrast` to `true` to flip the color of the label if it is to similar to the background color. Finally, we set the font family
* and size through the `font` parameter.
*
* @xtype pie
*/
Ext.chart.series.Pie = Ext.extend(Ext.chart.series.Series, {
type: 'pie',
rad: Math.PI / 180,
/**
* @cfg {Number} rotation
* The angle in degrees at which the first pie slice should start. Defaults to `0`.
*/
rotation: 0,
/**
* @cfg {String} angleField
* The store record field name to be used for the pie angles.
* The values bound to this field name must be positive real numbers.
* This parameter is required.
*/
angleField: false,
/**
* @cfg {String} lengthField
* The store record field name to be used for the pie slice lengths.
* The values bound to this field name must be positive real numbers.
* This parameter is optional.
*/
lengthField: false,
/**
* @cfg {Boolean|Number} donut
* Whether to set the pie chart as donut chart.
* Default's false. Can be set to a particular percentage to set the radius
* of the donut chart.
*/
donut: false,
/**
* @cfg {Boolean} showInLegend
* Whether to add the pie chart elements as legend items. Default's false.
*/
showInLegend: false,
/**
* @cfg {Boolean} labelOverflowPadding
* Extra distance value for which the labelOverflow listener is triggered. Default to 20.
*/
labelOverflowPadding: 20,
/**
* @cfg {Array} colorSet
* An array of color values which will be used, in order, as the pie slice fill colors.
*/
/**
* @cfg {Object} style
* An object containing styles for overriding series styles from Theming.
*/
constructor: function(config) {
Ext.applyIf(config, {
highlightCfg: {
segment: {
margin: 20
}
}
});
Ext.chart.series.Pie.superclass.constructor.apply(this, arguments);
var me = this,
chart = me.chart,
surface = me.getSurface(),
shadow = chart.shadow, i, l;
Ext.apply(me, config, {
shadowAttributes: surface.getShadowAttributesArray(),
shadowOptions: Ext.apply(surface.getShadowOptions(), shadow === true ? {} : (shadow || {}))
});
me.group = surface.getGroup(me.seriesId);
if (shadow) {
for (i = 0, l = me.shadowAttributes.length; i < l; i++) {
me.shadowGroups.push(surface.getGroup(me.seriesId + '-shadows' + i));
}
}
surface.customAttributes.segment = function(opt) {
return me.getSegment(opt);
};
me.__excludes = me.__excludes || [];
//add labelOverflows as managed events.
me.addEvents('labelOverflow');
//add default label overflow listener which hides the label.
me.addListener('labelOverflow', me.onLabelOverflow);
},
//default configuration for label overflowing the pie slice shape.
onLabelOverflow: function(label) {
label.hide(true);
},
// @private returns an object with properties for a PieSlice.
getSegment: function(opt) {
var me = this,
rad = me.rad,
cos = Math.cos,
sin = Math.sin,
abs = Math.abs,
x = me.centerX,
y = me.centerY,
x1 = 0, x2 = 0, x3 = 0, x4 = 0,
y1 = 0, y2 = 0, y3 = 0, y4 = 0,
delta = 1e-2,
startAngle = opt.startAngle,
endAngle = opt.endAngle,
midAngle = (startAngle + endAngle) / 2 * rad,
margin = opt.margin || 0,
flag = abs(endAngle - startAngle) > 180,
a1 = Math.min(startAngle, endAngle) * rad,
a2 = Math.max(startAngle, endAngle) * rad,
singleSlice = false,
fullCircle = false;
x += margin * cos(midAngle);
y += margin * sin(midAngle);
x1 = x + opt.startRho * cos(a1);
y1 = y + opt.startRho * sin(a1);
x2 = x + opt.endRho * cos(a1);
y2 = y + opt.endRho * sin(a1);
x3 = x + opt.startRho * cos(a2);
y3 = y + opt.startRho * sin(a2);
x4 = x + opt.endRho * cos(a2);
y4 = y + opt.endRho * sin(a2);
if (abs(x1 - x3) <= delta && abs(y1 - y3) <= delta) {
singleSlice = true;
}
fullCircle = singleSlice && (abs(x2 - x4) <= delta && abs(y2 - y4) <= delta);
if (startAngle === endAngle) {
return {path: ''}
}
//Solves mysterious clipping bug with IE
else if (fullCircle) {
return {
path: [
["M", x + opt.endRho, y - 1e-4],
["A", opt.endRho, opt.endRho, 0, 1, 0, x + opt.endRho, y],
["Z"]]
};
} else if (singleSlice) {
return {
path: [
["M", x1, y1],
["L", x2, y2],
["A", opt.endRho, opt.endRho, 0, +flag, 1, x4, y4],
["Z"]]
};
} else {
return {
path: [
["M", x1, y1],
["L", x2, y2],
["A", opt.endRho, opt.endRho, 0, +flag, 1, x4, y4],
["L", x4, y4],
["L", x3, y3],
["A", opt.startRho, opt.startRho, 0, +flag, 0, x1, y1],
["Z"]]
};
}
},
// @private utility function to calculate the middle point of a pie slice.
calcMiddle: function(item) {
var me = this,
rad = me.rad,
slice = item.slice,
x = me.centerX,
y = me.centerY,
startAngle = slice.startAngle,
endAngle = slice.endAngle,
a1 = Math.min(startAngle, endAngle) * rad,
a2 = Math.max(startAngle, endAngle) * rad,
midAngle = -(a1 + (a2 - a1) / 2),
xm = x + (item.endRho + item.startRho) / 2 * Math.cos(midAngle),
ym = y - (item.endRho + item.startRho) / 2 * Math.sin(midAngle);
item.middle = {
x: xm,
y: ym
};
},
/**
* Draws the series for the current chart.
*/
drawSeries: function() {
var me = this,
store = me.chart.substore || me.chart.store,
group = me.group,
animate = me.chart.animate,
field = me.angleField || me.field || me.xField,
lenField = [].concat(me.lengthField),
totalLenField = 0,
chart = me.chart,
surface = me.getSurface(),
chartBBox = chart.chartBBox,
enableShadows = chart.shadow,
shadowGroups = me.shadowGroups,
shadowAttributes = me.shadowAttributes,
lnsh = shadowGroups.length,
layers = lenField.length,
rhoAcum = 0,
donut = +me.donut,
layerTotals = [],
items = [],
totalField = 0,
maxLenField = 0,
angle = me.rotation,
seriesStyle = me.style,
colorArrayStyle = me.colorArrayStyle,
colorArrayLength = colorArrayStyle && colorArrayStyle.length || 0,
rendererAttributes,
shadowAttr,
shadows,
shadow,
shindex,
centerX,
centerY,
deltaRho,
first = 0,
slice,
slices,
sprite,
value,
item,
lenValue,
ln,
i,
j,
endAngle,
middleAngle,
path,
p,
spriteOptions, bbox;
if (me.fireEvent('beforedraw', me) === false) {
return;
}
Ext.chart.series.Pie.superclass.drawSeries.call(this);
me.setBBox();
bbox = me.bbox;
//override theme colors
if (me.colorSet) {
colorArrayStyle = me.colorSet;
colorArrayLength = colorArrayStyle.length;
}
me.unHighlightItem();
me.cleanHighlights();
centerX = me.centerX = chartBBox.x + (chartBBox.width / 2);
centerY = me.centerY = chartBBox.y + (chartBBox.height / 2);
me.radius = Math.min(centerX - chartBBox.x, centerY - chartBBox.y);
me.slices = slices = [];
me.items = items = [];
me.eachRecord(function(record, i) {
if (me.isExcluded(i)) {
//hidden series
return;
}
totalField += +record.get(field);
if (lenField[0]) {
for (j = 0, totalLenField = 0; j < layers; j++) {
totalLenField += +record.get(lenField[j]);
}
layerTotals[i] = totalLenField;
maxLenField = Math.max(maxLenField, totalLenField);
}
}, this);
totalField = totalField || 1;
me.eachRecord(function(record, i) {
if (me.isExcluded(i)) {
//hidden series
return;
}
value = record.get(field);
middleAngle = angle - 360 * value / totalField / 2;
// TODO - Put up an empty circle
if (isNaN(middleAngle)) {
middleAngle = 360;
value = 1;
totalField = 1;
}
// First slice
if (!i || first === 0) {
angle = 360 - middleAngle;
me.firstAngle = angle;
middleAngle = angle - 360 * value / totalField / 2;
}
endAngle = angle - 360 * value / totalField;
slice = {
series: me,
value: value,
startAngle: angle,
endAngle: endAngle,
storeItem: record
};
if (lenField[0]) {
lenValue = layerTotals[i];
slice.rho = me.radius * (lenValue / maxLenField);
} else {
slice.rho = me.radius;
}
slices[i] = slice;
angle = endAngle;
first++;
}, me);
//do all shadows first.
if (enableShadows) {
for (i = 0, ln = slices.length; i < ln; i++) {
if (me.isExcluded(i)) {
//hidden series
continue;
}
slice = slices[i];
slice.shadowAttrs = [];
for (j = 0, rhoAcum = 0, shadows = []; j < layers; j++) {
sprite = group.getAt(i * layers + j);
deltaRho = lenField[j] ? store.getAt(i).get(lenField[j]) / layerTotals[i] * slice.rho: slice.rho;
//set pie slice properties
rendererAttributes = {
segment: {
startAngle: slice.startAngle,
endAngle: slice.endAngle,
margin: 0,
rho: slice.rho,
startRho: rhoAcum + (deltaRho * donut / 100),
endRho: rhoAcum + deltaRho
},
hidden: !slice.value && (slice.startAngle % 360) == (slice.endAngle % 360)
};
//create shadows
for (shindex = 0, shadows = []; shindex < lnsh; shindex++) {
shadowAttr = shadowAttributes[shindex];
shadow = shadowGroups[shindex].getAt(i);
if (!shadow) {
shadow = me.getSurface().add(Ext.apply({}, {
type: 'path',
group: shadowGroups[shindex],
strokeLinejoin: "round"
}, rendererAttributes, shadowAttr));
}
if (animate) {
shadowAttr = me.renderer(shadow, store.getAt(i), Ext.apply({}, rendererAttributes, shadowAttr), i, store);
me.onAnimate(shadow, {
to: shadowAttr
});
} else {
shadowAttr = me.renderer(shadow, store.getAt(i), Ext.apply(shadowAttr, {
hidden: false
}), i, store);
shadow.setAttributes(shadowAttr, true);
}
shadows.push(shadow);
}
slice.shadowAttrs[j] = shadows;
}
}
}
//do pie slices after.
for (i = 0, ln = slices.length; i < ln; i++) {
if (me.isExcluded(i)) {
//hidden series
continue;
}
slice = slices[i];
for (j = 0, rhoAcum = 0; j < layers; j++) {
sprite = group.getAt(i * layers + j);
deltaRho = lenField[j] ? store.getAt(i).get(lenField[j]) / layerTotals[i] * slice.rho: slice.rho;
//set pie slice properties
rendererAttributes = Ext.apply({
segment: {
startAngle: slice.startAngle,
endAngle: slice.endAngle,
margin: 0,
rho: slice.rho,
startRho: rhoAcum + (deltaRho * donut / 100),
endRho: rhoAcum + deltaRho
},
hidden: !slice.value && (slice.startAngle % 360) == (slice.endAngle % 360)
}, Ext.apply(seriesStyle, colorArrayStyle && { fill: colorArrayStyle[(layers > 1? j : i) % colorArrayLength] } || {}));
item = Ext.apply({},
rendererAttributes.segment, {
slice: slice,
series: me,
storeItem: slice.storeItem,
index: i
});
me.calcMiddle(item);
if (enableShadows) {
item.shadows = slice.shadowAttrs[j];
}
items[i] = item;
// Create a new sprite if needed (no height)
if (!sprite) {
spriteOptions = Ext.apply({
type: "path",
group: group,
middle: item.middle
}, Ext.apply(seriesStyle, colorArrayStyle && { fill: colorArrayStyle[(layers > 1? j : i) % colorArrayLength] } || {}));
if (enableShadows) {
Ext.apply(spriteOptions, me.shadowOptions);
}
sprite = surface.add(Ext.apply(spriteOptions, rendererAttributes));
}
slice.sprite = slice.sprite || [];
item.sprite = sprite;
slice.sprite.push(sprite);
slice.point = [item.middle.x, item.middle.y];
rendererAttributes = me.renderer(sprite, store.getAt(i), rendererAttributes, i, store);
if (animate) {
sprite._to = rendererAttributes;
me.onAnimate(sprite, {
to: rendererAttributes
});
} else {
sprite.setAttributes(rendererAttributes, true);
}
rhoAcum += deltaRho;
}
}
// Hide unused bars
ln = group.getCount();
for (i = 0; i < ln; i++) {
if (!slices[(i / layers) >> 0] && group.getAt(i)) {
group.getAt(i).hide(true);
}
}
if (enableShadows) {
lnsh = shadowGroups.length;
for (shindex = 0; shindex < ln; shindex++) {
if (!slices[(shindex / layers) >> 0]) {
for (j = 0; j < lnsh; j++) {
if (shadowGroups[j].getAt(shindex)) {
shadowGroups[j].getAt(shindex).hide(true);
}
}
}
}
}
me.renderLabels();
me.renderCallouts();
me.fireEvent('draw', me);
},
// @private callback for when creating a label sprite.
onCreateLabel: function(storeItem, item) {
var me = this,
group = me.labelsGroup,
config = me.label,
middle = item.middle,
endLabelStyle = Ext.apply(me.labelStyle.style || {}, config || {});
return me.getSurface().add(Ext.apply({
'type': 'text',
'text-anchor': 'middle',
'group': group,
'x': middle.x,
'y': middle.y
}, endLabelStyle));
},
// @private callback for when placing a label sprite.
onPlaceLabel: function(label, storeItem, item, i, display, animate, index) {
var me = this,
chart = me.chart,
resizing = chart.resizing,
config = me.label,
format = config.renderer,
field = [].concat(config.field),
centerX = me.centerX,
centerY = me.centerY,
middle = item.middle,
opt = {
x: middle.x,
y: middle.y
},
x = middle.x - centerX,
y = middle.y - centerY,
from = {},
rho = 1,
theta = Math.atan2(y, x || 1),
dg = theta * 180 / Math.PI,
prevDg,
sliceContainsLabel;
function fixAngle(a) {
if (a < 0) a += 360;
return a % 360;
}
label.setAttributes({
text: format(storeItem.get(field[index]))
}, true);
switch (display) {
case 'outside':
rho = Math.sqrt(x * x + y * y) * 2;
//update positions
opt.x = rho * Math.cos(theta) + centerX;
opt.y = rho * Math.sin(theta) + centerY;
break;
case 'rotate':
dg = fixAngle(dg);
dg = (dg > 90 && dg < 270) ? dg + 180: dg;
prevDg = label.attr.rotation.degrees;
if (prevDg != null && Math.abs(prevDg - dg) > 180) {
if (dg > prevDg) {
dg -= 360;
} else {
dg += 360;
}
dg = dg % 360;
} else {
dg = fixAngle(dg);
}
//update rotation angle
opt.rotate = {
degrees: dg,
x: opt.x,
y: opt.y
};
break;
default:
break;
}
//ensure the object has zero translation
opt.translate = {
x: 0, y: 0
};
if (animate && !resizing && (display != 'rotate' || prevDg !== null)) {
me.onAnimate(label, {
to: opt
});
} else {
label.setAttributes(opt, true);
}
label._from = from;
sliceContainsLabel = me.sliceContainsLabel(item.slice, label);
if (!sliceContainsLabel) {
me.fireEvent('labelOverflow', label, item);
}
},
onCreateCallout: function() {
var me = this, ans;
ans = Ext.chart.series.Pie.superclass.onCreateCallout.apply(this, arguments);
ans.lines.setAttributes({
path: ['M', me.centerX, me.centerY]
});
ans.box.setAttributes({
x: me.centerX,
y: me.centerY
});
ans.label.setAttributes({
x: me.centerX,
y: me.centerY
});
return ans;
},
// @private callback for when placing a callout sprite.
onPlaceCallout: function(callout, storeItem, item) {
var me = this,
chart = me.chart,
centerX = me.centerX,
centerY = me.centerY,
middle = item.middle,
opt = {
x: middle.x,
y: middle.y
},
x = middle.x - centerX,
y = middle.y - centerY,
rho = 1,
rhoCenter,
theta = Math.atan2(y, x || 1),
label = callout.label,
box = callout.box,
lines = callout.lines,
lattr = lines.attr,
bbox = label.getBBox(),
offsetFromViz = lattr.offsetFromViz || 20,
offsetToSide = lattr.offsetToSide || 10,
offsetBox = box.attr.offsetBox || 10,
p;
//should be able to config this.
rho = item.endRho + offsetFromViz;
rhoCenter = (item.endRho + item.startRho) / 2 + (item.endRho - item.startRho) / 3;
//update positions
opt.x = rho * Math.cos(theta) + centerX;
opt.y = rho * Math.sin(theta) + centerY;
x = rhoCenter * Math.cos(theta);
y = rhoCenter * Math.sin(theta);
if (chart.animate) {
//set the line from the middle of the pie to the box.
me.onAnimate(callout.lines, {
to: {
path: ["M", x + centerX, y + centerY, "L", opt.x, opt.y, "Z", "M", opt.x, opt.y, "l", x > 0 ? offsetToSide: -offsetToSide, 0, "z"]
}
});
//set box position
me.onAnimate(callout.box, {
to: {
x: opt.x + (x > 0 ? offsetToSide: -(offsetToSide + bbox.width + 2 * offsetBox)),
y: opt.y + (y > 0 ? ( - bbox.height - offsetBox / 2) : ( - bbox.height - offsetBox / 2)),
width: bbox.width + 2 * offsetBox,
height: bbox.height + 2 * offsetBox
}
});
//set text position
me.onAnimate(callout.label, {
to: {
x: opt.x + (x > 0 ? (offsetToSide + offsetBox) : -(offsetToSide + bbox.width + offsetBox)),
y: opt.y + (y > 0 ? -bbox.height / 4: -bbox.height / 4)
}
});
} else {
//set the line from the middle of the pie to the box.
callout.lines.setAttributes({
path: ["M", x + centerX, y + centerY, "L", opt.x, opt.y, "Z", "M", opt.x, opt.y, "l", x > 0 ? offsetToSide: -offsetToSide, 0, "z"]
},
true);
//set box position
callout.box.setAttributes({
x: opt.x + (x > 0 ? offsetToSide: -(offsetToSide + bbox.width + 2 * offsetBox)),
y: opt.y + (y > 0 ? ( - bbox.height - offsetBox / 2) : ( - bbox.height - offsetBox / 2)),
width: bbox.width + 2 * offsetBox,
height: bbox.height + 2 * offsetBox
},
true);
//set text position
callout.label.setAttributes({
x: opt.x + (x > 0 ? (offsetToSide + offsetBox) : -(offsetToSide + bbox.width + offsetBox)),
y: opt.y + (y > 0 ? -bbox.height / 4: -bbox.height / 4)
},
true);
}
for (p in callout) {
callout[p].show(true);
}
},
// @private handles sprite animation for the series.
onAnimate: function(sprite, attr) {
sprite.show();
return Ext.chart.series.Pie.superclass.onAnimate.apply(this, arguments);
},
isItemInPoint: function(x, y, item) {
var me = this,
chartBBox = me.chart.chartBBox,
cx = me.centerX - chartBBox.x,
cy = me.centerY - chartBBox.y,
abs = Math.abs,
dx = abs(x - cx),
dy = abs(y - cy),
startAngle = item.startAngle,
endAngle = item.endAngle,
rho = Math.sqrt(dx * dx + dy * dy),
angle = Math.atan2(y - cy, x - cx) / me.rad;
while (angle < endAngle) {
angle += 360;
}
while (angle > startAngle) {
angle -= 360;
}
return (angle <= startAngle && angle > endAngle
&& rho >= item.startRho && rho <= item.endRho);
},
getItemForAngle: function(angle) {
var me = this,
items = me.items,
i = items.length;
while (i--) {
if (items[i] && me.isAngleInItem(angle, items[i])) {
return items[i];
}
}
},
isAngleInItem: function(angle, item) {
var startAngle = item.startAngle,
endAngle = item.endAngle;
while (angle < endAngle) {
angle += 360;
}
while (angle > startAngle) {
angle -= 360;
}
return (angle <= startAngle && angle > endAngle);
},
sliceContainsLabel: function(slice, label) {
var me = this,
PI = Math.PI,
startAngle = slice.startAngle,
endAngle = slice.endAngle,
diffAngle = Math.abs(endAngle - startAngle) * PI / 180,
bbox = label.getBBox(true), //isWithoutTransform == true
dist = me.radius,
height = bbox.height + (me.labelOverflowPadding || 0),
angleHeight;
if (diffAngle >= PI) {
return true;
}
angleHeight = Math.abs(Math.tan(diffAngle / 2)) * dist * 2;
return angleHeight >= height;
},
// @private hides all elements in the series.
hideAll: function() {
var i, l, shadow, shadows, sh, lsh, sprite;
if (!isNaN(this._index)) {
this.__excludes = this.__excludes || [];
this.__excludes[this._index] = true;
sprite = this.slices[this._index].sprite;
for (sh = 0, lsh = sprite.length; sh < lsh; sh++) {
sprite[sh].setAttributes({
hidden: true
}, true);
}
if (this.slices[this._index].shadowAttrs) {
for (i = 0, shadows = this.slices[this._index].shadowAttrs, l = shadows.length; i < l; i++) {
shadow = shadows[i];
for (sh = 0, lsh = shadow.length; sh < lsh; sh++) {
shadow[sh].setAttributes({
hidden: true
}, true);
}
}
}
this.drawSeries();
}
},
// @private shows all elements in the series.
showAll: function() {
var me = this,
excludes = me.__excludes,
index = me._index;
if (!isNaN(index) && excludes && excludes[index]) {
excludes[index] = false;
me.drawSeries();
}
},
/**
* Highlight the specified item. If no item is provided the whole series will be highlighted.
* @param item {Object} Info about the item; same format as returned by #getItemForPoint
*/
highlightItem: function(item) {
var me = this,
rad = me.rad;
item = item || this.items[this._index];
if (!item || item.sprite && item.sprite._animating) {
return;
}
Ext.chart.series.Pie.superclass.highlightItem.apply(this, [item]);
if (me.highlight === false) {
return;
}
if ('segment' in me.highlightCfg) {
var highlightSegment = me.highlightCfg.segment,
animate = me.chart.animate,
attrs, i, shadows, shadow, ln, to, itemHighlightSegment, prop;
//animate labels
if (me.labelsGroup) {
var group = me.labelsGroup,
label = group.getAt(item.index),
middle = (item.startAngle + item.endAngle) / 2 * rad,
r = highlightSegment.margin || 0,
x = r * Math.cos(middle),
y = r * Math.sin(middle);
//TODO(nico): rounding to 1e-10
//gives the right translation. Translation
//was buggy for very small numbers. In this
//case we're not looking to translate to very small
//numbers but not to translate at all.
if (Math.abs(x) < 1e-10) {
x = 0;
}
if (Math.abs(y) < 1e-10) {
y = 0;
}
if (animate) {
label.stopAnimation();
label.animate({
to: {
translate: {
x: x,
y: y
}
},
duration: me.highlightDuration
});
}
else {
label.setAttributes({
translate: {
x: x,
y: y
}
}, true);
}
}
//animate shadows
if (me.chart.shadow && item.shadows) {
i = 0;
shadows = item.shadows;
ln = shadows.length;
for (; i < ln; i++) {
shadow = shadows[i];
to = {};
itemHighlightSegment = item.sprite._from.segment;
for (prop in itemHighlightSegment) {
if (! (prop in highlightSegment)) {
to[prop] = itemHighlightSegment[prop];
}
}
attrs = {
segment: Ext.applyIf(to, me.highlightCfg.segment)
};
if (animate) {
shadow.stopAnimation();
shadow.animate({
to: attrs,
duration: me.highlightDuration
});
}
else {
shadow.setAttributes(attrs, true);
}
}
}
}
},
/**
* un-highlights the specified item. If no item is provided it will un-highlight the entire series.
* @param item {Object} Info about the item; same format as returned by #getItemForPoint
*/
unHighlightItem: function() {
var me = this;
if (me.highlight === false) {
return;
}
if (('segment' in me.highlightCfg) && me.items) {
var items = me.items,
animate = me.chart.animate,
shadowsEnabled = !!me.chart.shadow,
group = me.labelsGroup,
len = items.length,
i = 0,
j = 0,
display = me.label.display,
shadowLen, p, to, ihs, hs, sprite, shadows, shadow, item, label, attrs;
for (; i < len; i++) {
item = items[i];
if (!item) {
continue;
}
sprite = item.sprite;
if (sprite && sprite._highlighted) {
//animate labels
if (group) {
label = group.getAt(item.index);
attrs = Ext.apply({
translate: {
x: 0,
y: 0
}
},
display == 'rotate' ? {
rotate: {
x: label.attr.x,
y: label.attr.y,
degrees: label.attr.rotation.degrees
}
}: {});
if (animate) {
label.stopAnimation();
label.animate({
to: attrs,
duration: me.highlightDuration
});
}
else {
label.setAttributes(attrs, true);
}
}
if (shadowsEnabled) {
shadows = item.shadows;
shadowLen = shadows.length;
for (; j < shadowLen; j++) {
to = {};
ihs = item.sprite._to.segment;
hs = item.sprite._from.segment;
Ext.apply(to, hs);
for (p in ihs) {
if (! (p in hs)) {
to[p] = ihs[p];
}
}
shadow = shadows[j];
if (animate) {
shadow.stopAnimation();
shadow.animate({
to: {
segment: to
},
duration: me.highlightDuration
});
}
else {
shadow.setAttributes({ segment: to }, true);
}
}
}
}
}
}
Ext.chart.series.Pie.superclass.unHighlightItem.apply(me, arguments);
},
getLegendLabels: function() {
var me = this,
labelField = me.label.field,
labels = [];
if (labelField) {
me.eachRecord(function(rec) {
labels.push(rec.get(labelField));
});
}
return labels;
},
/**
* Returns the color of the series (to be displayed as color for the series legend item).
* @param item {Object} Info about the item; same format as returned by #getItemForPoint
*/
getLegendColor: function(index) {
var me = this,
colorSet = me.colorSet,
colorArrayStyle = me.colorArrayStyle;
return me.getColorFromStyle(
(colorSet && colorSet[index % colorSet.length]) || colorArrayStyle[index % colorArrayStyle.length]
);
},
/**
* Iterate over each of the displayed records for this pie series, taking into account
* records that have been combined into one by the user.
* @param {Function} fn The function to execute for each record.
* @param {Object} scope Scope for the fn.
*/
eachRecord: function(fn, scope) {
var me = this,
store = me.chart.substore || me.chart.store,
combinations = me.combinations,
labelField = me.label.field,
angleField = me.angleField || me.field || me.xField,
lengthFields = [].concat(me.lengthField),
records;
// If we have combined records, take a snapshot of the store data and apply the combinations
if (combinations) {
records = store.data.clone();
Ext.each(combinations, function(combo) {
var record1 = records.getAt(combo[0]),
record2 = records.getAt(combo[1]),
comboData = {};
// Build a combination data model object from the two target records
comboData[labelField] = record1.get(labelField) + ' & ' + record2.get(labelField);
comboData[angleField] = +record1.get(angleField) + record2.get(angleField);
if (lengthFields[0]) {
Ext.each(lengthFields, function(lengthField) {
comboData[lengthField] = +record1.get(lengthField) + record2.get(lengthField);
});
}
// Insert the new combination record in place of the second original record, and remove both originals
records.insert(combo[1], Ext.ModelMgr.create(comboData, store.model));
records.remove(record1);
records.remove(record2);
});
records.each(fn, scope);
} else {
// No combinations - just iterate the store directly
store.each(fn, scope);
}
},
getRecordCount: function() {
var me = this,
combinations = me.combinations;
return Ext.chart.series.Pie.superclass.getRecordCount.call(me) - (combinations ? combinations.length : 0);
},
/**
* @private update the position/size of the series surface. For pie series we set it to the
* full chart size so it doesn't get clipped when slices slide out.
*/
updateSurfaceBox: function() {
var me = this,
surface = me.getSurface(),
overlaySurface = me.getOverlaySurface(),
chart = me.chart,
width = chart.curWidth,
height = chart.curHeight;
surface.el.setTopLeft(0, 0);
surface.setSize(width, height);
overlaySurface.el.setTopLeft(0, 0);
overlaySurface.setSize(width, height);
},
reset: function() {
this.rotation = 0;
Ext.chart.series.Pie.superclass.reset.call(this);
}
});
/**
* @class Ext.chart.series.Radar
* @extends Ext.chart.series.Series
*
* Creates a Radar Chart. A Radar Chart is a useful visualization technique for comparing different quantitative values for
* a constrained number of categories.
* As with all other series, the Radar series must be appended in the *series* Chart array configuration. See the Chart
* documentation for more information. A typical configuration object for the radar series could be:
*
* {@img Ext.chart.series.Radar/Ext.chart.series.Radar.png Ext.chart.series.Radar chart series}
*
* var store = new Ext.data.JsonStore({
* fields: ['name', 'data1', 'data2', 'data3', 'data4', 'data5'],
* data: [
* {'name':'metric one', 'data1':10, 'data2':12, 'data3':14, 'data4':8, 'data5':13},
* {'name':'metric two', 'data1':7, 'data2':8, 'data3':16, 'data4':10, 'data5':3},
* {'name':'metric three', 'data1':5, 'data2':2, 'data3':14, 'data4':12, 'data5':7},
* {'name':'metric four', 'data1':2, 'data2':14, 'data3':6, 'data4':1, 'data5':23},
* {'name':'metric five', 'data1':27, 'data2':38, 'data3':36, 'data4':13, 'data5':33}
* ]
* });
*
* new Ext.chart.Chart({
* renderTo: Ext.getBody(),
* width: 500,
* height: 300,
* animate: true,
* theme:'Category2',
* store: store,
* axes: [{
* type: 'Radial',
* position: 'radial',
* label: {
* display: true
* }
* }],
* series: [{
* type: 'radar',
* xField: 'name',
* yField: 'data3',
* showInLegend: true,
* showMarkers: true,
* markerConfig: {
* radius: 5,
* size: 5
* },
* style: {
* 'stroke-width': 2,
* fill: 'none'
* }
* },{
* type: 'radar',
* xField: 'name',
* yField: 'data2',
* showMarkers: true,
* showInLegend: true,
* markerConfig: {
* radius: 5,
* size: 5
* },
* style: {
* 'stroke-width': 2,
* fill: 'none'
* }
* },{
* type: 'radar',
* xField: 'name',
* yField: 'data5',
* showMarkers: true,
* showInLegend: true,
* markerConfig: {
* radius: 5,
* size: 5
* },
* style: {
* 'stroke-width': 2,
* fill: 'none'
* }
* }]
* });
*
* In this configuration we add three series to the chart. Each of these series is bound to the same categories field, `name` but bound to different properties for each category,
* `data1`, `data2` and `data3` respectively. All series display markers by having `showMarkers` enabled. The configuration for the markers of each series can be set by adding properties onto
* the markerConfig object. Finally we override some theme styling properties by adding properties to the `style` object.
*
* @xtype radar
*/
Ext.chart.series.Radar = Ext.extend(Ext.chart.series.Series, {
type: "radar",
rad: Math.PI / 180,
rotation: 0,
showInLegend: false,
/**
* @cfg {Object} style
* An object containing styles for overriding series styles from Theming.
*/
/**
* @cfg {Boolean} showMarkers
* Whether markers should be displayed at the data points along the line. If true,
* then the {@link #markerConfig} config item will determine the markers' styling.
*/
/**
* @cfg {Object} markerConfig
* The display style for the markers. Only used if {@link #showMarkers} is true.
* The markerConfig is a configuration object containing the same set of properties defined in
* the Sprite class. For example, if we were to set red circles as markers to the line series we could
* pass the object:
*
<pre><code>
markerConfig: {
type: 'circle',
radius: 4,
'fill': '#f00'
}
</code></pre>
*/
/**
* @cfg {String} xField
* The store record field name for the labels used in the radar series.
*/
/**
* @cfg {Object} yField
* The store record field name for the deflection of the graph in the radar series.
*/
constructor: function(config) {
Ext.chart.series.Radar.superclass.constructor.apply(this, arguments);
var me = this,
surface = me.getSurface();
me.group = surface.getGroup(me.seriesId);
if (me.showMarkers) {
me.markerGroup = surface.getGroup(me.seriesId + '-markers');
}
},
/**
* Draws the series for the current chart.
*/
drawSeries: function() {
var me = this,
group = me.group,
chart = me.chart,
field = me.field || me.yField,
surface = me.getSurface(),
chartBBox = chart.chartBBox,
centerX, centerY,
items,
radius,
maxValue = 0,
fields = [],
max = Math.max,
cos = Math.cos,
sin = Math.sin,
rotation = -me.rotation,
rad = Ext.draw.Draw.rad,
angle,
l = me.getRecordCount(),
startPath, path, x, y, rho,
nfields,
seriesStyle = me.style,
axis = chart.axes && chart.axes.get(0),
aggregate = !(axis && axis.maximum);
if (me.fireEvent('beforedraw', me) === false) {
return;
}
Ext.chart.series.Radar.superclass.drawSeries.call(this);
me.setBBox();
maxValue = aggregate? 0 : (axis.maximum || 0);
//if the store is empty then there's nothing to draw
if (!l || me.seriesIsHidden) {
surface.items.hide(true);
return;
}
me.unHighlightItem();
me.cleanHighlights();
centerX = me.centerX = (chartBBox.width / 2);
centerY = me.centerY = (chartBBox.height / 2);
me.radius = radius = Math.min(chartBBox.width, chartBBox.height) /2;
me.items = items = [];
if (aggregate) {
//get all renderer fields
chart.series.each(function(series) {
fields.push(series.yField);
});
//get maxValue to interpolate
me.eachRecord(function(record, i) {
for (i = 0, nfields = fields.length; i < nfields; i++) {
maxValue = max(+record.get(fields[i]), maxValue);
}
});
}
//ensure non-zero value.
maxValue = maxValue || 1;
//create path and items
startPath = []; path = [];
me.eachRecord(function(record, i) {
rho = radius * record.get(field) / maxValue;
angle = rad(rotation + i / l * 360);
x = rho * cos(angle);
y = rho * sin(angle);
if (i == 0) {
path.push('M', x + centerX, y + centerY);
startPath.push('M', 0.01 * x + centerX, 0.01 * y + centerY);
} else {
path.push('L', x + centerX, y + centerY);
startPath.push('L', 0.01 * x + centerX, 0.01 * y + centerY);
}
items.push({
sprite: false, //TODO(nico): add markers
point: [centerX + x, centerY + y],
series: me
});
});
path.push('Z');
//create path sprite
if (!me.radar) {
me.radar = surface.add(Ext.apply({
type: 'path',
group: group,
path: startPath
}, seriesStyle || {}));
}
//reset on resizing
if (chart.resizing) {
me.radar.setAttributes({
path: startPath
}, true);
}
//render/animate
me.radar.show(true);
if (chart.animate) {
me.onAnimate(me.radar, {
to: Ext.apply({
path: path
}, seriesStyle || {})
});
} else {
me.radar.setAttributes(Ext.apply({
path: path
}, seriesStyle || {}), true);
}
//render markers, labels and callouts
if (me.showMarkers) {
me.drawMarkers();
}
me.renderLabels();
me.renderCallouts();
me.fireEvent('draw', me);
},
// @private draws the markers for the lines (if any).
drawMarkers: function() {
var me = this,
chart = me.chart,
surface = me.getSurface(),
markerStyle = Ext.apply({}, me.markerStyle.style || {}),
endMarkerStyle = Ext.apply(markerStyle, me.markerConfig),
items = me.items,
type = endMarkerStyle.type,
markerGroup = me.markerGroup,
centerX = me.centerX,
centerY = me.centerY,
item, i, l, marker;
delete endMarkerStyle.type;
for (i = 0, l = items.length; i < l; i++) {
item = items[i];
marker = markerGroup.getAt(i);
if (!marker) {
marker = Ext.chart.Shape[type](surface, Ext.apply({
group: markerGroup,
x: 0,
y: 0,
translate: {
x: centerX,
y: centerY
}
}, endMarkerStyle));
}
else {
marker.show();
}
if (chart.resizing) {
marker.setAttributes({
x: 0,
y: 0,
translate: {
x: centerX,
y: centerY
}
}, true);
}
marker._to = {
translate: {
x: item.point[0],
y: item.point[1]
}
};
//render/animate
if (chart.animate) {
me.onAnimate(marker, {
to: marker._to
});
}
else {
marker.setAttributes(Ext.apply(marker._to, endMarkerStyle || {}), true);
}
}
},
isItemInPoint: function(x, y, item) {
var point,
tolerance = 10,
abs = Math.abs;
point = item.point;
return (abs(point[0] - x) <= tolerance &&
abs(point[1] - y) <= tolerance);
},
// @private callback for when creating a label sprite.
onCreateLabel: function(storeItem, item) {
var me = this,
group = me.labelsGroup,
config = me.label,
centerX = me.centerX,
centerY = me.centerY;
return me.getSurface().add(Ext.apply({
'type': 'text',
'text-anchor': 'middle',
'group': group,
'x': centerX,
'y': centerY
}, config || {}));
},
// @private callback for when placing a label sprite.
onPlaceLabel: function(label, storeItem, item, i, display, animate) {
var me = this,
chart = me.chart,
resizing = chart.resizing,
config = me.label,
format = config.renderer,
field = config.field,
centerX = me.centerX,
centerY = me.centerY,
opt = {
x: item.point[0],
y: item.point[1]
};
label.setAttributes({
text: format(storeItem.get(field)),
hidden: true
},
true);
if (resizing) {
label.setAttributes({
x: centerX,
y: centerY
}, true);
}
if (animate) {
label.show(true);
me.onAnimate(label, {
to: opt
});
} else {
label.setAttributes(opt, true);
label.show(true);
}
},
// @private for toggling (show/hide) series.
toggleAll: function(show) {
var me = this,
i, ln, shadow, shadows;
if (!show) {
Ext.chart.series.Radar.superclass.hideAll.call(me);
}
else {
Ext.chart.series.Radar.superclass.showAll.call(me);
}
if (me.radar) {
me.radar.setAttributes({
hidden: !show
}, true);
//hide shadows too
if (me.radar.shadows) {
for (i = 0, shadows = me.radar.shadows, ln = shadows.length; i < ln; i++) {
shadow = shadows[i];
shadow.setAttributes({
hidden: !show
}, true);
}
}
}
},
// @private hide all elements in the series.
hideAll: function() {
this.toggleAll(false);
this.hideMarkers(0);
},
// @private show all elements in the series.
showAll: function() {
this.toggleAll(true);
},
// @private hide all markers that belong to `markerGroup`
hideMarkers: function(index) {
var me = this,
count = me.markerGroup && me.markerGroup.getCount() || 0,
i = index || 0;
for (; i < count; i++) {
me.markerGroup.getAt(i).hide(true);
}
},
getLegendLabels: function() {
var label = this.title || this.yField;
return label ? [label] : [];
},
reset: function() {
this.rotation = 0;
Ext.chart.series.Radar.superclass.reset.call(this);
}
});
/**
* @class Ext.chart.series.Scatter
* @extends Ext.chart.series.Cartesian
*
* Creates a Scatter Chart. The scatter plot is useful when trying to display more than two variables in the same visualization.
* These variables can be mapped into x, y coordinates and also to an element's radius/size, color, etc.
* As with all other series, the Scatter Series must be appended in the *series* Chart array configuration. See the Chart
* documentation for more information on creating charts. A typical configuration object for the scatter could be:
*
* {@img Ext.chart.series.Scatter/Ext.chart.series.Scatter.png Ext.chart.series.Scatter chart series}
*
* var store = new Ext.data.JsonStore({
* fields: ['name', 'data1', 'data2', 'data3', 'data4', 'data5'],
* data: [
* {'name':'metric one', 'data1':10, 'data2':12, 'data3':14, 'data4':8, 'data5':13},
* {'name':'metric two', 'data1':7, 'data2':8, 'data3':16, 'data4':10, 'data5':3},
* {'name':'metric three', 'data1':5, 'data2':2, 'data3':14, 'data4':12, 'data5':7},
* {'name':'metric four', 'data1':2, 'data2':14, 'data3':6, 'data4':1, 'data5':23},
* {'name':'metric five', 'data1':27, 'data2':38, 'data3':36, 'data4':13, 'data5':33}
* ]
* });
*
* new Ext.chart.Chart({
* renderTo: Ext.getBody(),
* width: 500,
* height: 300,
* animate: true,
* theme:'Category2',
* store: store,
* axes: [{
* type: 'Numeric',
* position: 'bottom',
* fields: ['data1', 'data2', 'data3'],
* title: 'Sample Values',
* grid: true,
* minimum: 0
* }, {
* type: 'Category',
* position: 'left',
* fields: ['name'],
* title: 'Sample Metrics'
* }],
* series: [{
* type: 'scatter',
* markerConfig: {
* radius: 5,
* size: 5
* },
* axis: 'left',
* xField: 'name',
* yField: 'data2'
* }, {
* type: 'scatter',
* markerConfig: {
* radius: 5,
* size: 5
* },
* axis: 'left',
* xField: 'name',
* yField: 'data3'
* }]
* });
*
* In this configuration we add three different categories of scatter series. Each of them is bound to a different field of the same data store,
* `data1`, `data2` and `data3` respectively. All x-fields for the series must be the same field, in this case `name`.
* Each scatter series has a different styling configuration for markers, specified by the `markerConfig` object. Finally we set the left axis as
* axis to show the current values of the elements.
*
* @xtype scatter
*/
Ext.chart.series.Scatter = Ext.extend(Ext.chart.series.Cartesian, {
type: 'scatter',
/**
* @cfg {Object} markerConfig
* The display style for the scatter series markers.
*/
/**
* @cfg {Object} style
* Append styling properties to this object for it to override theme properties.
*/
/**
* @cfg {String/Array} axis
* The position of the axis to bind the values to. Possible values are 'left', 'bottom', 'top' and 'right'.
* You must explicitly set this value to bind the values of the line series to the ones in the axis, otherwise a
* relative scale will be used. If multiple axes are being used, they should both be specified in in the configuration.
*/
constructor: function(config) {
Ext.chart.series.Scatter.superclass.constructor.apply(this, arguments);
var me = this,
shadow = me.chart.shadow,
surface = me.getSurface(), i, l;
Ext.apply(me, config, {
style: {},
markerConfig: {},
shadowAttributes: surface.getShadowAttributesArray(),
shadowOptions: Ext.apply(surface.getShadowOptions(), shadow === true ? {} : (shadow || {}))
});
me.group = surface.getGroup(me.seriesId);
if (shadow) {
for (i = 0, l = me.shadowAttributes.length; i < l; i++) {
me.shadowGroups.push(surface.getGroup(me.seriesId + '-shadows' + i));
}
}
},
// @private Get chart and data boundaries
getBounds: function() {
var me = this,
chart = me.chart,
count = me.getRecordCount(),
axes = [].concat(me.axis),
bbox, xScale, yScale, ln, minX, minY, maxX, maxY, i, axis, ends;
me.setBBox();
bbox = me.bbox;
for (i = 0, ln = axes.length; i < ln; i++) {
axis = chart.axes.get(axes[i]);
if (axis) {
ends = axis.calcEnds();
if (axis.position == 'top' || axis.position == 'bottom') {
minX = ends.from;
maxX = ends.to;
}
else {
minY = ends.from;
maxY = ends.to;
}
}
}
// If a field was specified without a corresponding axis, create one to get bounds
if (me.xField && !Ext.isNumber(minX)) {
axis = new Ext.chart.axis.Axis({
chart: chart,
fields: [].concat(me.xField)
}).calcEnds();
minX = axis.from;
maxX = axis.to;
}
if (me.yField && !Ext.isNumber(minY)) {
axis = new Ext.chart.axis.Axis({
chart: chart,
fields: [].concat(me.yField)
}).calcEnds();
minY = axis.from;
maxY = axis.to;
}
if (isNaN(minX)) {
minX = 0;
maxX = count - 1;
xScale = bbox.width / (count - 1);
}
else {
xScale = bbox.width / (maxX - minX);
}
if (isNaN(minY)) {
minY = 0;
maxY = count - 1;
yScale = bbox.height / (count - 1);
}
else {
yScale = bbox.height / (maxY - minY);
}
return {
bbox: bbox,
minX: minX,
minY: minY,
xScale: xScale,
yScale: yScale
};
},
// @private Build an array of paths for the chart
getPaths: function() {
var me = this,
chart = me.chart,
enableShadows = chart.shadow,
group = me.group,
bounds = me.bounds = me.getBounds(),
bbox = me.bbox,
xScale = bounds.xScale,
yScale = bounds.yScale,
minX = bounds.minX,
minY = bounds.minY,
boxX = bbox.x,
boxY = bbox.y,
boxHeight = bbox.height,
attrs = [],
x, y, xValue, yValue, sprite;
me.items = me.items || [];
me.eachRecord(function(record, i) {
xValue = record.get(me.xField);
yValue = record.get(me.yField);
//skip undefined values
if (typeof yValue == 'undefined' || (typeof yValue == 'string' && !yValue)) {
return;
}
// Ensure a value
if (typeof xValue == 'string' || typeof xValue == 'object') {
xValue = i;
}
if (typeof yValue == 'string' || typeof yValue == 'object') {
yValue = i;
}
x = boxX + (xValue - minX) * xScale;
y = boxY + boxHeight - (yValue - minY) * yScale;
attrs.push({
x: x,
y: y
});
me.items.push({
series: me,
value: [xValue, yValue],
point: [x, y],
storeItem: record
});
// When resizing, reset before animating
if (chart.animate && chart.resizing) {
sprite = group.getAt(i);
if (sprite) {
me.resetPoint(sprite);
if (enableShadows) {
me.resetShadow(sprite);
}
}
}
});
return attrs;
},
// @private translate point to the center
resetPoint: function(sprite) {
var bbox = this.bbox;
sprite.setAttributes({
translate: {
x: (bbox.x + bbox.width) / 2,
y: (bbox.y + bbox.height) / 2
}
}, true);
},
// @private translate shadows of a sprite to the center
resetShadow: function(sprite) {
var me = this,
shadows = sprite.shadows,
shadowAttributes = me.shadowAttributes,
ln = me.shadowGroups.length,
bbox = me.bbox,
i, attr;
for (i = 0; i < ln; i++) {
attr = Ext.apply({}, shadowAttributes[i]);
if (attr.translate) {
attr.translate.x += (bbox.x + bbox.width) / 2;
attr.translate.y += (bbox.y + bbox.height) / 2;
}
else {
attr.translate = {
x: (bbox.x + bbox.width) / 2,
y: (bbox.y + bbox.height) / 2
};
}
shadows[i].setAttributes(attr, true);
}
},
// @private create a new point
createPoint: function(attr, type) {
var me = this,
group = me.group,
bbox = me.bbox;
return Ext.chart.Shape[type](me.getSurface(), Ext.apply({}, {
x: 0,
y: 0,
group: group,
translate: {
x: (bbox.x + bbox.width) / 2,
y: (bbox.y + bbox.height) / 2
}
}, attr));
},
// @private create a new set of shadows for a sprite
createShadow: function(sprite, endMarkerStyle, type) {
var me = this,
shadowGroups = me.shadowGroups,
shadowAttributes = me.shadowAttributes,
lnsh = shadowGroups.length,
bbox = me.bbox,
i, shadow, shadows, attr;
sprite.shadows = shadows = [];
for (i = 0; i < lnsh; i++) {
attr = Ext.apply({}, shadowAttributes[i]);
if (attr.translate) {
attr.translate.x += (bbox.x + bbox.width) / 2;
attr.translate.y += (bbox.y + bbox.height) / 2;
}
else {
Ext.apply(attr, {
translate: {
x: (bbox.x + bbox.width) / 2,
y: (bbox.y + bbox.height) / 2
}
});
}
Ext.apply(attr, endMarkerStyle);
shadow = Ext.chart.Shape[type](me.getSurface(), Ext.apply({}, {
x: 0,
y: 0,
group: shadowGroups[i]
}, attr));
shadows.push(shadow);
}
},
/**
* Draws the series for the current chart.
*/
drawSeries: function() {
var me = this,
chart = me.chart,
store = chart.substore || chart.store,
group = me.group,
enableShadows = chart.shadow,
shadowGroups = me.shadowGroups,
shadowAttributes = me.shadowAttributes,
lnsh = shadowGroups.length,
sprite, attrs, attr, ln, i, endMarkerStyle, shindex, type, shadows,
rendererAttributes, shadowAttribute;
if (me.fireEvent('beforedraw', me) === false) {
return;
}
Ext.chart.series.Scatter.superclass.drawSeries.call(this);
endMarkerStyle = Ext.apply(me.markerStyle.style || {}, me.markerConfig);
type = endMarkerStyle.type;
delete endMarkerStyle.type;
//if the store is empty then there's nothing to be rendered
if (!me.getRecordCount() || me.seriesIsHidden) {
me.getSurface().items.hide(true);
return;
}
me.unHighlightItem();
me.cleanHighlights();
attrs = me.getPaths();
ln = attrs.length;
for (i = 0; i < ln; i++) {
attr = attrs[i];
sprite = group.getAt(i);
Ext.apply(attr, endMarkerStyle);
// Create a new sprite if needed (no height)
if (!sprite) {
sprite = me.createPoint(attr, type);
if (enableShadows) {
me.createShadow(sprite, endMarkerStyle, type);
sprite.setAttributes(me.shadowOptions, true);
}
}
shadows = sprite.shadows;
if (chart.animate) {
rendererAttributes = me.renderer(sprite, store.getAt(i), { translate: attr }, i, store);
sprite._to = rendererAttributes;
me.onAnimate(sprite, {
to: rendererAttributes
});
//animate shadows
for (shindex = 0; shindex < lnsh; shindex++) {
shadowAttribute = Ext.apply({}, shadowAttributes[shindex]);
rendererAttributes = me.renderer(shadows[shindex], store.getAt(i), Ext.apply({}, {
translate: {
x: attr.x + (shadowAttribute.translate? shadowAttribute.translate.x : 0),
y: attr.y + (shadowAttribute.translate? shadowAttribute.translate.y : 0)
}
}, shadowAttribute), i, store);
me.onAnimate(shadows[shindex], { to: rendererAttributes });
}
}
else {
rendererAttributes = me.renderer(sprite, store.getAt(i), { translate: attr }, i, store);
sprite._to = rendererAttributes;
sprite.setAttributes(rendererAttributes, true);
//update shadows
for (shindex = 0; shindex < lnsh; shindex++) {
shadowAttribute = Ext.apply({}, shadowAttributes[shindex]);
rendererAttributes = me.renderer(shadows[shindex], store.getAt(i), Ext.apply({}, {
translate: {
x: attr.x + (shadowAttribute.translate? shadowAttribute.translate.x : 0),
y: attr.y + (shadowAttribute.translate? shadowAttribute.translate.y : 0)
}
}, shadowAttribute), i, store);
shadows[shindex].setAttributes(rendererAttributes, true);
}
}
me.items[i].sprite = sprite;
}
// Hide unused sprites
ln = group.getCount();
for (i = attrs.length; i < ln; i++) {
group.getAt(i).hide(true);
}
me.renderLabels();
me.renderCallouts();
me.fireEvent('draw', me);
},
// @private callback for when creating a label sprite.
onCreateLabel: function(storeItem, item, i, display) {
var me = this,
group = me.labelsGroup,
config = me.label,
endLabelStyle = Ext.apply({}, config, me.labelStyle.style || {}),
bbox = me.bbox;
return me.getSurface().add(Ext.apply({
type: 'text',
group: group,
x: item.point[0],
y: bbox.y + bbox.height / 2
}, endLabelStyle));
},
// @private callback for when placing a label sprite.
onPlaceLabel: function(label, storeItem, item, i, display, animate) {
var me = this,
chart = me.chart,
resizing = chart.resizing,
config = me.label,
format = config.renderer,
field = config.field,
bbox = me.bbox,
x = item.point[0],
y = item.point[1],
radius = item.sprite.attr.radius,
bb, width, height, anim;
label.setAttributes({
text: format(storeItem.get(field)),
hidden: true
}, true);
if (display == 'rotate') {
label.setAttributes({
'text-anchor': 'start',
'rotation': {
x: x,
y: y,
degrees: -45
}
}, true);
//correct label position to fit into the box
bb = label.getBBox();
width = bb.width;
height = bb.height;
x = x < bbox.x? bbox.x : x;
x = (x + width > bbox.x + bbox.width)? (x - (x + width - bbox.x - bbox.width)) : x;
y = (y - height < bbox.y)? bbox.y + height : y;
} else if (display == 'under' || display == 'over') {
//TODO(nicolas): find out why width/height values in circle bounding boxes are undefined.
bb = item.sprite.getBBox();
bb.width = bb.width || (radius * 2);
bb.height = bb.height || (radius * 2);
y = y + (display == 'over'? -bb.height : bb.height);
//correct label position to fit into the box
bb = label.getBBox();
width = bb.width/2;
height = bb.height/2;
x = x - width < bbox.x ? bbox.x + width : x;
x = (x + width > bbox.x + bbox.width) ? (x - (x + width - bbox.x - bbox.width)) : x;
y = y - height < bbox.y? bbox.y + height : y;
y = (y + height > bbox.y + bbox.height) ? (y - (y + height - bbox.y - bbox.height)) : y;
}
if (!chart.animate) {
label.setAttributes({
x: x,
y: y
}, true);
label.show(true);
}
else {
if (resizing) {
anim = item.sprite.getActiveAnimation();
if (anim) {
anim.on('afteranimate', function() {
label.setAttributes({
x: x,
y: y
}, true);
label.show(true);
});
}
else {
label.show(true);
}
}
else {
me.onAnimate(label, {
to: {
x: x,
y: y
}
});
}
}
},
// @private callback for when placing a callout sprite.
onPlaceCallout: function(callout, storeItem, item, i, display, animate, index) {
var me = this,
chart = me.chart,
cur = item.point,
normal,
bbox = callout.label.getBBox(),
offsetFromViz = 30,
offsetBox = 3,
boxx, boxy, boxw, boxh,
p, clipRect = me.bbox,
x, y;
//position
normal = [Math.cos(Math.PI /4), -Math.sin(Math.PI /4)];
x = cur[0] + normal[0] * offsetFromViz;
y = cur[1] + normal[1] * offsetFromViz;
//box position and dimensions
boxx = x + (normal[0] > 0? 0 : -(bbox.width + 2 * offsetBox));
boxy = y - bbox.height /2 - offsetBox;
boxw = bbox.width + 2 * offsetBox;
boxh = bbox.height + 2 * offsetBox;
//now check if we're out of bounds and invert the normal vector correspondingly
//this may add new overlaps between labels (but labels won't be out of bounds).
if (boxx < clipRect[0] || (boxx + boxw) > (clipRect[0] + clipRect[2])) {
normal[0] *= -1;
}
if (boxy < clipRect[1] || (boxy + boxh) > (clipRect[1] + clipRect[3])) {
normal[1] *= -1;
}
//update positions
x = cur[0] + normal[0] * offsetFromViz;
y = cur[1] + normal[1] * offsetFromViz;
//update box position and dimensions
boxx = x + (normal[0] > 0? 0 : -(bbox.width + 2 * offsetBox));
boxy = y - bbox.height /2 - offsetBox;
boxw = bbox.width + 2 * offsetBox;
boxh = bbox.height + 2 * offsetBox;
if (chart.animate) {
//set the line from the middle of the pie to the box.
me.onAnimate(callout.lines, {
to: {
path: ["M", cur[0], cur[1], "L", x, y, "Z"]
}
}, true);
//set box position
me.onAnimate(callout.box, {
to: {
x: boxx,
y: boxy,
width: boxw,
height: boxh
}
}, true);
//set text position
me.onAnimate(callout.label, {
to: {
x: x + (normal[0] > 0? offsetBox : -(bbox.width + offsetBox)),
y: y
}
}, true);
} else {
//set the line from the middle of the pie to the box.
callout.lines.setAttributes({
path: ["M", cur[0], cur[1], "L", x, y, "Z"]
}, true);
//set box position
callout.box.setAttributes({
x: boxx,
y: boxy,
width: boxw,
height: boxh
}, true);
//set text position
callout.label.setAttributes({
x: x + (normal[0] > 0? offsetBox : -(bbox.width + offsetBox)),
y: y
}, true);
}
for (p in callout) {
callout[p].show(true);
}
},
// @private handles sprite animation for the series.
onAnimate: function(sprite, attr) {
sprite.show();
Ext.chart.series.Scatter.superclass.onAnimate.apply(this, arguments);
},
isItemInPoint: function(x, y, item) {
var point,
tolerance = 10;
point = item.point;
return (point[0] - tolerance <= x && point[0] + tolerance >= x &&
point[1] - tolerance <= y && point[1] + tolerance >= y);
}
});
/**
* @class Ext.chart.series.Area
* @extends Ext.chart.series.Cartesian
*
<p>
Creates a Stacked Area Chart. The stacked area chart is useful when displaying multiple aggregated layers of information.
As with all other series, the Area Series must be appended in the *series* Chart array configuration. See the Chart
documentation for more information. A typical configuration object for the area series could be:
</p>
{@img Ext.chart.series.Area/Ext.chart.series.Area.png Ext.chart.series.Area chart series}
<pre><code>
var store = new Ext.data.JsonStore({
fields: ['name', 'data1', 'data2', 'data3', 'data4', 'data5'],
data: [
{'name':'metric one', 'data1':10, 'data2':12, 'data3':14, 'data4':8, 'data5':13},
{'name':'metric two', 'data1':7, 'data2':8, 'data3':16, 'data4':10, 'data5':3},
{'name':'metric three', 'data1':5, 'data2':2, 'data3':14, 'data4':12, 'data5':7},
{'name':'metric four', 'data1':2, 'data2':14, 'data3':6, 'data4':1, 'data5':23},
{'name':'metric five', 'data1':27, 'data2':38, 'data3':36, 'data4':13, 'data5':33}
]
});
new Ext.chart.Chart({
renderTo: Ext.getBody(),
width: 500,
height: 300,
store: store,
axes: [{
type: 'Numeric',
grid: true,
position: 'left',
fields: ['data1', 'data2', 'data3', 'data4', 'data5'],
title: 'Sample Values',
grid: {
odd: {
opacity: 1,
fill: '#ddd',
stroke: '#bbb',
'stroke-width': 1
}
},
minimum: 0,
adjustMinimumByMajorUnit: 0
}, {
type: 'Category',
position: 'bottom',
fields: ['name'],
title: 'Sample Metrics',
grid: true,
label: {
rotate: {
degrees: 315
}
}
}],
series: [{
type: 'area',
highlight: false,
axis: 'left',
xField: 'name',
yField: ['data1', 'data2', 'data3', 'data4', 'data5'],
style: {
opacity: 0.93
}
}]
});
</code></pre>
<p>
In this configuration we set `area` as the type for the series, set highlighting options to true for highlighting elements on hover,
take the left axis to measure the data in the area series, set as xField (x values) the name field of each element in the store,
and as yFields (aggregated layers) seven data fields from the same store. Then we override some theming styles by adding some opacity
to the style object.
</p>
* @xtype area
*
*/
Ext.chart.series.Area = Ext.extend(Ext.chart.series.Cartesian, {
type: 'area',
// @private Area charts are alyways stacked
stacked: true,
/**
* @cfg {Object} style
* Append styling properties to this object for it to override theme properties.
*/
constructor: function(config) {
Ext.chart.series.Area.superclass.constructor.apply(this, arguments);
var me = this,
surface = me.getSurface(),
i, l;
Ext.apply(me, config, {
__excludes: [],
highlightCfg: {
lineWidth: 3,
stroke: '#55c',
opacity: 0.8,
color: '#f00'
}
});
if (me.highlight !== false) {
me.highlightSprite = surface.add({
type: 'path',
path: ['M', 0, 0],
zIndex: 1000,
opacity: 0.3,
lineWidth: 5,
hidden: true,
stroke: '#444'
});
}
me.group = surface.getGroup(me.seriesId);
},
// @private Shrinks dataSets down to a smaller size
shrink: function(xValues, yValues, size) {
var len = xValues.length,
ratio = Math.floor(len / size),
i, j,
xSum = 0,
yCompLen = this.areas.length,
ySum = [],
xRes = [],
yRes = [];
//initialize array
for (j = 0; j < yCompLen; ++j) {
ySum[j] = 0;
}
for (i = 0; i < len; ++i) {
xSum += xValues[i];
for (j = 0; j < yCompLen; ++j) {
ySum[j] += yValues[i][j];
}
if (i % ratio == 0) {
//push averages
xRes.push(xSum/ratio);
for (j = 0; j < yCompLen; ++j) {
ySum[j] /= ratio;
}
yRes.push(ySum);
//reset sum accumulators
xSum = 0;
for (j = 0, ySum = []; j < yCompLen; ++j) {
ySum[j] = 0;
}
}
}
return {
x: xRes,
y: yRes
};
},
// @private Get chart and data boundaries
getBounds: function() {
var me = this,
chart = me.chart,
xValues = [],
allYValues = [],
infinity = Infinity,
minX = infinity,
maxX = -infinity,
minY, maxY,
math = Math,
mmin = math.min,
mmax = math.max,
bbox, xScale, yScale, ln, sumValues, axis, out, recordYValues;
me.setBBox();
bbox = me.bbox;
// Run through the axis
if (me.axis) {
axis = chart.axes.get(me.axis);
if (axis) {
out = axis.calcEnds();
minY = out.from;
maxY = out.to;
}
}
if (me.yField && !Ext.isNumber(minY)) {
axis = new Ext.chart.axis.Axis({
chart: chart,
fields: [].concat(me.yField)
});
out = axis.calcEnds();
minY = out.from;
maxY = out.to;
}
if (!Ext.isNumber(minY)) {
minY = 0;
}
if (!Ext.isNumber(maxY)) {
maxY = 0;
}
function eachYValue(yValue) {
if (typeof yValue == 'number') {
recordYValues.push(yValue);
}
}
me.eachRecord(function(record, i) {
var xValue = record.get(me.xField);
if (typeof xValue != 'number') {
xValue = i;
}
xValues.push(xValue);
recordYValues = [];
me.eachYValue(record, eachYValue);
minX = math.min(minX, xValue);
maxX = math.max(maxX, xValue);
allYValues.push(recordYValues);
});
xScale = bbox.width / ((maxX - minX) || 1);
yScale = bbox.height / ((maxY - minY) || 1);
ln = xValues.length;
if ((ln > bbox.width) && me.areas) {
sumValues = me.shrink(xValues, allYValues, bbox.width);
xValues = sumValues.x;
allYValues = sumValues.y;
}
return {
bbox: bbox,
minX: minX,
minY: minY,
xValues: xValues,
yValues: allYValues,
xScale: xScale,
yScale: yScale,
areasLen: me.getYValueCount()
};
},
// @private Build an array of paths for the chart
getPaths: function() {
var me = this,
first = true,
bounds = me.getBounds(),
bbox = bounds.bbox,
items = me.items = [],
componentPaths = [],
componentPath,
paths = [],
i, ln, x, y, xValue, yValue, acumY, areaIndex, prevAreaIndex, areaElem, path;
ln = bounds.xValues.length;
// Start the path
for (i = 0; i < ln; i++) {
xValue = bounds.xValues[i];
yValue = bounds.yValues[i];
x = bbox.x + (xValue - bounds.minX) * bounds.xScale;
acumY = 0;
for (areaIndex = 0; areaIndex < bounds.areasLen; areaIndex++) {
// Excluded series
if (me.isExcluded(areaIndex)) {
continue;
}
if (!componentPaths[areaIndex]) {
componentPaths[areaIndex] = [];
}
areaElem = yValue[areaIndex];
acumY += areaElem;
y = bbox.y + bbox.height - (acumY - bounds.minY) * bounds.yScale;
if (!paths[areaIndex]) {
paths[areaIndex] = ['M', x, y];
componentPaths[areaIndex].push(['L', x, y]);
} else {
paths[areaIndex].push('L', x, y);
componentPaths[areaIndex].push(['L', x, y]);
}
if (!items[areaIndex]) {
items[areaIndex] = {
pointsUp: [],
pointsDown: [],
series: me
};
}
items[areaIndex].pointsUp.push([x, y]);
}
}
// Close the paths
for (areaIndex = 0; areaIndex < bounds.areasLen; areaIndex++) {
// Excluded series
if (me.isExcluded(areaIndex)) {
continue;
}
path = paths[areaIndex];
// Close bottom path to the axis
if (areaIndex == 0 || first) {
first = false;
path.push('L', x, bbox.y + bbox.height,
'L', bbox.x, bbox.y + bbox.height,
'Z');
}
// Close other paths to the one before them
else {
componentPath = componentPaths[prevAreaIndex];
componentPath.reverse();
path.push('L', x, componentPath[0][2]);
for (i = 0; i < ln; i++) {
path.push(componentPath[i][0],
componentPath[i][1],
componentPath[i][2]);
items[areaIndex].pointsDown[ln -i -1] = [componentPath[i][1], componentPath[i][2]];
}
path.push('L', bbox.x, path[2], 'Z');
}
prevAreaIndex = areaIndex;
}
return {
paths: paths,
areasLen: bounds.areasLen
};
},
/**
* Draws the series for the current chart.
*/
drawSeries: function() {
var me = this,
chart = me.chart,
store = chart.substore || chart.store,
surface = me.getSurface(),
animate = chart.animate,
group = me.group,
areas = me.areas,
endLineStyle = me.style,
colorArrayStyle = me.colorArrayStyle,
colorArrayLength = colorArrayStyle && colorArrayStyle.length || 0,
areaIndex, areaElem, paths, path, rendererAttributes;
if (me.fireEvent('beforedraw', me) === false) {
return;
}
Ext.chart.series.Area.superclass.drawSeries.call(this);
me.unHighlightItem();
me.cleanHighlights();
if (!me.getRecordCount()) {
surface.items.hide(true);
return;
}
paths = me.getPaths();
if (!areas) {
areas = me.areas = [];
}
for (areaIndex = 0; areaIndex < paths.areasLen; areaIndex++) {
// Excluded series
if (me.isExcluded(areaIndex)) {
continue;
}
if (!areas[areaIndex]) {
me.items[areaIndex].sprite = areas[areaIndex] = surface.add(Ext.apply({}, {
type: 'path',
group: group,
// 'clip-rect': me.clipBox,
path: paths.paths[areaIndex],
stroke: endLineStyle.stroke || colorArrayStyle[areaIndex % colorArrayLength],
fill: colorArrayStyle[areaIndex % colorArrayLength]
}, endLineStyle || {}));
}
areaElem = areas[areaIndex];
path = paths.paths[areaIndex];
if (animate) {
//Add renderer to line. There is not a unique record associated with this.
rendererAttributes = me.renderer(areaElem, false, {
path: path,
// 'clip-rect': me.clipBox,
fill: colorArrayStyle[areaIndex % colorArrayLength],
stroke: endLineStyle.stroke || colorArrayStyle[areaIndex % colorArrayLength]
}, areaIndex, store);
//fill should not be used here but when drawing the special fill path object
me.animation = me.onAnimate(areaElem, {
to: rendererAttributes
});
} else {
rendererAttributes = me.renderer(areaElem, false, {
path: path,
// 'clip-rect': me.clipBox,
hidden: false,
fill: colorArrayStyle[areaIndex % colorArrayLength],
stroke: endLineStyle.stroke || colorArrayStyle[areaIndex % colorArrayLength]
}, areaIndex, store);
areas[areaIndex].setAttributes(rendererAttributes, true);
}
}
// Hide leftover area sprites
for (; areaIndex < areas.length; areaIndex++) {
areas[areaIndex].hide();
}
me.renderLabels();
me.renderCallouts();
me.fireEvent('draw', me);
},
// @private
onAnimate: function(sprite, attr) {
sprite.show();
Ext.chart.series.Area.superclass.onAnimate.apply(this, arguments);
},
// @private
onCreateLabel: function(storeItem, item, i, display) {
var me = this,
group = me.labelsGroup,
config = me.label,
bbox = me.bbox,
endLabelStyle = Ext.apply({}, config, me.labelStyle.style);
return me.getSurface().add(Ext.apply({
'type': 'text',
'text-anchor': 'middle',
'group': group,
'x': item.point[0],
'y': bbox.y + bbox.height / 2
}, endLabelStyle || {}));
},
// @private
onPlaceLabel: function(label, storeItem, item, i, display, animate, index) {
var me = this,
chart = me.chart,
resizing = chart.resizing,
config = me.label,
format = config.renderer,
field = config.field,
bbox = me.bbox,
x = item.point[0],
y = item.point[1],
bb, width, height;
label.setAttributes({
text: format(storeItem.get(field[index])),
hidden: true
}, true);
bb = label.getBBox();
width = bb.width / 2;
height = bb.height / 2;
x = x - width < bbox.x? bbox.x + width : x;
x = (x + width > bbox.x + bbox.width) ? (x - (x + width - bbox.x - bbox.width)) : x;
y = y - height < bbox.y? bbox.y + height : y;
y = (y + height > bbox.y + bbox.height) ? (y - (y + height - bbox.y - bbox.height)) : y;
if (me.chart.animate && !me.chart.resizing) {
label.show(true);
me.onAnimate(label, {
to: {
x: x,
y: y
}
});
} else {
label.setAttributes({
x: x,
y: y
}, true);
if (resizing) {
me.animation.on('afteranimate', function() {
label.show(true);
});
} else {
label.show(true);
}
}
},
// @private
onPlaceCallout : function(callout, storeItem, item, i, display, animate, index) {
var me = this,
chart = me.chart,
surface = me.getSurface(),
resizing = chart.resizing,
config = me.callouts,
items = me.items,
prev = (i == 0) ? false : items[i -1].point,
next = (i == items.length -1) ? false : items[i +1].point,
cur = item.point,
dir, norm, normal, a, aprev, anext,
bbox = callout.label.getBBox(),
offsetFromViz = 30,
offsetToSide = 10,
offsetBox = 3,
boxx, boxy, boxw, boxh,
p, clipRect = me.clipRect,
x, y;
//get the right two points
if (!prev) {
prev = cur;
}
if (!next) {
next = cur;
}
a = (next[1] - prev[1]) / (next[0] - prev[0]);
aprev = (cur[1] - prev[1]) / (cur[0] - prev[0]);
anext = (next[1] - cur[1]) / (next[0] - cur[0]);
norm = Math.sqrt(1 + a * a);
dir = [1 / norm, a / norm];
normal = [-dir[1], dir[0]];
//keep the label always on the outer part of the "elbow"
if (aprev > 0 && anext < 0 && normal[1] < 0 || aprev < 0 && anext > 0 && normal[1] > 0) {
normal[0] *= -1;
normal[1] *= -1;
} else if (Math.abs(aprev) < Math.abs(anext) && normal[0] < 0 || Math.abs(aprev) > Math.abs(anext) && normal[0] > 0) {
normal[0] *= -1;
normal[1] *= -1;
}
//position
x = cur[0] + normal[0] * offsetFromViz;
y = cur[1] + normal[1] * offsetFromViz;
//box position and dimensions
boxx = x + (normal[0] > 0? 0 : -(bbox.width + 2 * offsetBox));
boxy = y - bbox.height /2 - offsetBox;
boxw = bbox.width + 2 * offsetBox;
boxh = bbox.height + 2 * offsetBox;
//now check if we're out of bounds and invert the normal vector correspondingly
//this may add new overlaps between labels (but labels won't be out of bounds).
if (boxx < clipRect[0] || (boxx + boxw) > (clipRect[0] + clipRect[2])) {
normal[0] *= -1;
}
if (boxy < clipRect[1] || (boxy + boxh) > (clipRect[1] + clipRect[3])) {
normal[1] *= -1;
}
//update positions
x = cur[0] + normal[0] * offsetFromViz;
y = cur[1] + normal[1] * offsetFromViz;
//update box position and dimensions
boxx = x + (normal[0] > 0? 0 : -(bbox.width + 2 * offsetBox));
boxy = y - bbox.height /2 - offsetBox;
boxw = bbox.width + 2 * offsetBox;
boxh = bbox.height + 2 * offsetBox;
//set the line from the middle of the pie to the box.
callout.lines.setAttributes({
path: ["M", cur[0], cur[1], "L", x, y, "Z"]
}, true);
//set box position
callout.box.setAttributes({
x: boxx,
y: boxy,
width: boxw,
height: boxh
}, true);
//set text position
callout.label.setAttributes({
x: x + (normal[0] > 0? offsetBox : -(bbox.width + offsetBox)),
y: y
}, true);
for (p in callout) {
callout[p].show(true);
}
},
isItemInPoint: function(x, y, item, i) {
var me = this,
pointsUp = item.pointsUp,
pointsDown = item.pointsDown,
abs = Math.abs,
dist = Infinity, p, pln, point;
for (p = 0, pln = pointsUp.length; p < pln; p++) {
point = [pointsUp[p][0], pointsUp[p][1]];
if (dist > abs(x - point[0])) {
dist = abs(x - point[0]);
} else {
point = pointsUp[p -1];
if (y >= point[1] && (!pointsDown.length || y <= (pointsDown[p -1][1]))) {
item.storeIndex = p -1;
item.storeField = me.yField[i];
item.storeItem = me.chart.store.getAt(p -1);
item._points = pointsDown.length? [point, pointsDown[p -1]] : [point];
return true;
} else {
break;
}
}
}
return false;
},
/**
* Highlight this entire series.
* @param {Object} item Info about the item; same format as returned by #getItemForPoint.
*/
highlightSeries: function() {
var area, to, fillColor;
if (this._index !== undefined) {
area = this.areas[this._index];
if (area.__highlightAnim) {
area.__highlightAnim.paused = true;
}
area.__highlighted = true;
area.__prevOpacity = area.__prevOpacity || area.attr.opacity || 1;
area.__prevFill = area.__prevFill || area.attr.fill;
area.__prevLineWidth = area.__prevLineWidth || area.attr.lineWidth;
fillColor = Ext.draw.Color.fromString(area.__prevFill);
to = {
lineWidth: (area.__prevLineWidth || 0) + 2
};
if (fillColor) {
to.fill = fillColor.getLighter(0.2).toString();
}
else {
to.opacity = Math.max(area.__prevOpacity - 0.3, 0);
}
if (this.chart.animate) {
area.__highlightAnim = new Ext.fx.Anim(Ext.apply({
target: area,
to: to
}, this.chart.animate));
}
else {
area.setAttributes(to, true);
}
}
},
/**
* UnHighlight this entire series.
* @param {Object} item Info about the item; same format as returned by #getItemForPoint.
*/
unHighlightSeries: function() {
var area;
if (this._index !== undefined) {
area = this.areas[this._index];
if (area.__highlightAnim) {
area.__highlightAnim.paused = true;
}
if (area.__highlighted) {
area.__highlighted = false;
area.__highlightAnim = new Ext.fx.Anim({
target: area,
to: {
fill: area.__prevFill,
opacity: area.__prevOpacity,
lineWidth: area.__prevLineWidth
}
});
}
}
},
/**
* Highlight the specified item. If no item is provided the whole series will be highlighted.
* @param item {Object} Info about the item; same format as returned by #getItemForPoint
*/
highlightItem: function(item) {
var me = this,
highlightSprite = me.highlightSprite,
points, path;
if (!item) {
this.highlightSeries();
return;
}
points = item._points;
path = points.length == 2? ['M', points[0][0], points[0][1], 'L', points[1][0], points[1][1]]
: ['M', points[0][0], points[0][1], 'L', points[0][0], me.bbox.y + me.bbox.height];
if (highlightSprite) {
//make sure we apply the stylesheet styles.
Ext.applyIf(this.highlightCfg, this.highlightStyle.style || {});
highlightSprite.setAttributes(Ext.apply({
path: path,
hidden: false
}, this.highlightCfg), true);
}
//added for canvas rendering.
me.getSurface().renderFrame();
},
/**
* un-highlights the specified item. If no item is provided it will un-highlight the entire series.
* @param item {Object} Info about the item; same format as returned by #getItemForPoint
*/
unHighlightItem: function(item) {
if (!item) {
this.unHighlightSeries();
}
if (this.highlightSprite) {
this.highlightSprite.hide(true);
}
},
// @private
hideAll: function() {
var me = this,
index = me._index;
if (!isNaN(index)) {
me.__excludes[index] = true;
me.areas[index].hide(true);
me.chart.axes.each(function(axis) {
axis.drawAxis();
});
me.drawSeries();
}
},
// @private
showAll: function() {
var me = this,
index = me._index;
if (!isNaN(index)) {
me.__excludes[index] = false;
me.areas[index].show(true);
me.chart.axes.each(function(axis) {
axis.drawAxis();
});
me.drawSeries();
}
},
/**
* Returns the color of the series (to be displayed as color for the series legend item).
* @param item {Object} Info about the item; same format as returned by #getItemForPoint
*/
getLegendColor: function(index) {
var me = this,
colorArrayStyle = me.colorArrayStyle;
return me.getColorFromStyle(colorArrayStyle[index % colorArrayStyle.length]);
}
});
Ext.ns('Ext.chart.interactions');
/**
* @class Ext.chart.interactions.Manager
* @singleton
*
* A singleton manager instance for chart interactions. Interaction classes register
* themselves by name with this manager.
*/
Ext.chart.interactions.Manager = new Ext.AbstractManager();
/**
* @class Ext.chart.interactions.Abstract
* @extends Ext.util.Observable
*
* Defines a common abstract parent class for all interactions.
*
* @author Jason Johnston <jason@sencha.com>
* @docauthor Jason Johnston <jason@sencha.com>
*/
Ext.chart.interactions.Abstract = Ext.extend(Ext.util.Observable, {
/**
* @cfg {String} gesture
* Specifies which gesture type should be used for starting the interaction.
* Defaults to `tap`.
*/
gesture: 'tap',
constructor: function(config) {
var me = this;
Ext.chart.interactions.Abstract.superclass.constructor.call(me, config);
me.ownerCt = me.chart;
},
/**
* @protected
* A method to be implemented by subclasses where all event attachment should occur.
*/
initEvents: function() {
var me = this;
//check whether we're using drag events then initialize them in the surface.
if (me.gesture && me.gesture == 'drag' || me.panGesture && me.panGesture == 'drag') {
me.chart.getSurface('events').initializeDragEvents();
}
me.addChartListener(me.gesture, me.onGesture, me);
},
/**
* @protected
* Placeholder method.
*/
onGesture: Ext.emptyFn,
/**
* @protected Find and return a single series item corresponding to the given event,
* or null if no matching item is found.
* @param {Event} e
* @return {Object} the item object or null if none found.
*/
getItemForEvent: function(e) {
var me = this,
chart = me.chart,
chartXY = chart.getEventXY(e);
return chart.getItemForPoint(chartXY[0], chartXY[1]);
},
/**
* @protected Find and return all series items corresponding to the given event.
* @param {Event} e
* @return {Array} array of matching item objects
*/
getItemsForEvent: function(e) {
var me = this,
chart = me.chart,
chartXY = chart.getEventXY(e);
return chart.getItemsForPoint(chartXY[0], chartXY[1]);
},
/**
* @protected Add an event listener to this interaction's chart. All ineteraction event listeners
* should be attached using this method, since it adds logic for honoring event locks.
* @param name
* @param fn
* @param scope
* @param opts
*/
addChartListener: function(name, fn, scope, opts) {
var me = this,
locks = me.getLocks();
me.chart.on(
name,
// wrap the handler so it does not fire if the event is locked by another interaction
function() {
if (!(name in locks) || locks[name] === me) {
fn.apply(this, arguments);
}
},
scope,
opts
);
},
lockEvents: function() {
var me = this,
locks = me.getLocks(),
args = arguments,
i = args.length;
while (i--) {
locks[args[i]] = me;
}
},
unlockEvents: function() {
var locks = this.getLocks(),
args = arguments,
i = args.length;
while (i--) {
delete locks[args[i]];
}
},
getLocks: function() {
var chart = this.chart;
return chart.lockedEvents || (chart.lockedEvents = {});
},
isMultiTouch: function() {
return !(Ext.is.MultiTouch === false || (Ext.is.Android && !Ext.is.hasOwnProperty('MultiTouch')) || Ext.is.Desktop);
},
initializeDefaults: Ext.emptyFn,
/* ---------------------------------
Methods needed for ComponentQuery
----------------------------------*/
//filled by the constructor.
ownerCt: null,
getItemId: function() {
return this.id || (this.id = Ext.id());
},
initCls: function() {
return (this.cls || '').split(' ');
},
isXType: function(xtype) {
return xtype === 'interaction';
},
getRefItems: function(deep) {
return [];
}
});
/**
* @class Ext.chart.interactions.DelayedSync
*
* This is a mixin for chart interactions which gives them basic support for synchronizing
* the chart to the user's interaction after a configurable {@link #syncDelay delay}. This
* is useful for example in interactions which perform fast CSS3 transformation during the
* interaction's gesture, but needs to perform a full synchronization to that transformation
* for full quality after a delay.
*
* @author Jason Johnston <jason@sencha.com>
* @docauthor Jason Johnston <jason@sencha.com>
*/
Ext.chart.interactions.DelayedSync = Ext.extend(Object, {
/**
* @cfg {Number} syncDelay
* Specifies a timeout in milliseconds between when the user finishes an interaction
* gesture and when the chart are synced and redrawn to match.
* Defaults to 500.
*/
syncDelay: 500,
/**
* @cfg {String} syncWaitText
* The text to be displayed while the chart is redrawing itself after the interaction sync.
* Defaults to 'Rendering...'.
*/
syncWaitText: 'Rendering...',
constructor: function() {
var me = this,
DelayedTask = Ext.util.DelayedTask;
me.startSyncTask = new DelayedTask(me.startSync, me);
me.doSyncTask = new DelayedTask(me.doSync, me);
me.unlockInteractionTask = new DelayedTask(me.unlockInteraction, me);
},
sync: Ext.emptyFn,
needsSync: function() {
return true;
},
startSync: function() {
var me = this;
if (me.needsSync()) {
me.lockInteraction();
// Must delay the actual rerender to allow the lock/mask to take effect
me.doSyncTask.delay(1);
}
},
doSync: function() {
var me = this;
// Invoke the class's sync logic
if (me.needsSync()) {
me.sync();
}
// Must delay the unlock otherwise the browser will queue the events during
// render and apply them immediately afterward
me.unlockInteractionTask.delay(1);
},
cancelSync: function() {
var me = this;
me.startSyncTask.cancel();
me.doSyncTask.cancel();
me.unlockInteractionTask.cancel();
},
delaySync: function() {
var me = this;
me.cancelSync();
me.startSyncTask.delay(me.syncDelay);
},
lockInteraction: function() {
var me = this,
chart = me.chart,
chartEl = chart.el,
stopEvent = me.stopEvent;
me.unlockInteraction();
chartEl.on({
touchstart: stopEvent,
touchmove: stopEvent,
touchend: stopEvent,
capture: true
});
// chartEl.mask(me.syncWaitText, Ext.baseCSSPrefix + 'chart-wait', false);
// Ext.repaint(); //mask doesn't get sized properly otherwise
},
unlockInteraction: function() {
var me = this,
chart = me.chart,
chartEl = chart.el,
stopEvent = me.stopEvent;
chartEl.un({
touchstart: stopEvent,
touchmove: stopEvent,
touchend: stopEvent,
capture: true
});
// chartEl.unmask();
},
stopEvent: function(e) {
e.stopEvent();
}
});
/**
* @class Ext.chart.interactions.PanZoom
* @extends Ext.chart.interactions.Abstract
*
* The PanZoom interaction allows the user to navigate the data for one or more chart
* axes by panning and/or zooming. Navigation can be limited to particular axes. Zooming is
* performed by pinching on the chart or axis area; panning is performed by single-touch dragging.
*
* For devices which do not support multiple-touch events, zooming can not be done via pinch
* gestures; in this case the interaction will allow the user to perform both zooming and
* panning using the same single-touch drag gesture. Tapping the chart will switch between
* the two modes, {@link #modeIndicatorDuration briefly displaying a graphical indicator}
* showing whether it is in zoom or pan mode.
*
* You can attach this interaction to a chart by including an entry in the chart's
* {@link Ext.chart.Chart#interactions interactions} config with the `panzoom` type:
*
* new Ext.chart.Chart({
* renderTo: Ext.getBody(),
* width: 800,
* height: 600,
* store: store1,
* axes: [ ...some axes options... ],
* series: [ ...some series options... ],
* interactions: [{
* type: 'panzoom',
* axes: {
* left: {
* maxZoom: 5,
* startZoom: 2
* },
* bottom: {
* maxZoom: 2
* }
* }
* }]
* });
*
* The configuration object for the `panzoom` interaction type should specify which axes
* will be made navigable via the `axes` config. See the {@link #axes} config documentation
* for details on the allowed formats. If the `axes` config is not specified, it will default
* to making all axes navigable with the default axis options.
*
* @author Jason Johnston <jason@sencha.com>
* @docauthor Jason Johnston <jason@sencha.com>
*/
Ext.chart.interactions.PanZoom = Ext.extend(Ext.chart.interactions.Abstract, {
/**
* @cfg {Object/Array} axes
* Specifies which axes should be made navigable. The config value can take the following formats:
*
* - An Object whose keys correspond to the {@link Ext.chart.axis.Axis#position position} of each
* axis that should be made navigable. Each key's value can either be an Object with further
* configuration options for each axis or simply `true` for a default set of options.
* {
* type: 'panzoom',
* axes: {
* left: {
* maxZoom: 5,
* allowPan: false
* },
* bottom: true
* }
* }
*
* If using the full Object form, the following options can be specified for each axis:
*
* - minZoom (Number) A minimum zoom level for the axis. Defaults to `1` which is its natural size.
* - maxZoom (Number) A maximum zoom level for the axis. Defaults to `10`.
* - startZoom (Number) A starting zoom level for the axis. Defaults to `1`.
* - allowZoom (Boolean) Whether zooming is allowed for the axis. Defaults to `true`.
* - allowPan (Boolean) Whether panning is allowed for the axis. Defaults to `true`.
* - startPan (Boolean) A starting panning offset for the axis. Defaults to `0`.
*
* - An Array of strings, each one corresponding to the {@link Ext.chart.axis.Axis#position position}
* of an axis that should be made navigable. The default options will be used for each named axis.
*
* {
* type: 'panzoom',
* axes: ['left', 'bottom']
* }
*
* If the `axes` config is not specified, it will default to making all axes navigable with the
* default axis options.
*/
axes: {
top: {},
right: {},
bottom: {},
left: {}
},
/**
* @cfg {Boolean} showOverflowArrows
* If `true`, arrows will be conditionally shown at either end of each axis to indicate that the
* axis is overflowing and can therefore be panned in that direction. Set this to `false` to
* prevent the arrows from being displayed. Defaults to `true`.
*/
showOverflowArrows: true,
/**
* @cfg {Object} overflowArrowOptions
* A set of optional overrides for the overflow arrow sprites' options. Only relevant when
* {@link #showOverflowArrows} is `true`.
*/
gesture: 'pinch',
panGesture: 'drag',
constructor: function(config) {
var me = this,
interactionsNS = Ext.chart.interactions,
zoomModeCls = Ext.baseCSSPrefix + 'zooming',
axesConfig;
interactionsNS.PanZoom.superclass.constructor.call(me, config);
interactionsNS.DelayedSync.prototype.constructor.call(me, config);
if (me.showOverflowArrows) {
me.chart.on('redraw', me.updateAllOverflowArrows, me);
}
// Normalize the `axes` config
axesConfig = me.axes;
if (Ext.isArray(axesConfig)) {
// array of axis names - translate to full object form
me.axes = {};
Ext.each(axesConfig, function(axis) {
me.axes[axis] = {};
});
} else if (Ext.isObject(axesConfig)) {
Ext.iterate(axesConfig, function(key, val) {
// axis name with `true` value -> translate to object
if (val === true) {
axesConfig[key] = {};
}
});
}
else {
Ext.Error.raise("Invalid value for panzoom interaction 'axes' config: '" + axesConfig + "'");
}
// Add pan/zoom toggle button to toolbar if needed
if (!me.isMultiTouch()) {
me.zoomOnPanGesture = true; //default to zooming
me.modeToggleButton = me.chart.getToolbar().add({
cls: Ext.baseCSSPrefix + 'panzoom-toggle ' + zoomModeCls,
iconCls: Ext.baseCSSPrefix + 'panzoom-toggle-icon',
iconMask: true,
handler: function() {
var button = this,
zoom = me.zoomOnPanGesture = !me.zoomOnPanGesture;
if (zoom) {
button.addCls(zoomModeCls);
} else {
button.removeCls(zoomModeCls);
}
}
});
}
},
initEvents: function() {
var me = this;
Ext.chart.interactions.PanZoom.superclass.initEvents.call(me, arguments);
me.addChartListener(me.gesture + 'start', me.onGestureStart, me);
me.addChartListener(me.gesture + 'end', me.onGestureEnd, me);
me.addChartListener(me.panGesture + 'start', me.onPanGestureStart, me);
me.addChartListener(me.panGesture, me.onPanGesture, me);
me.addChartListener(me.panGesture + 'end', me.onPanGestureEnd, me);
},
initializeDefaults: function(opt) {
var me = this;
if (!opt || opt.type == 'beforerender') {
me.onGestureStart();
me.onPanGestureStart();
me.chart.axes.each(function(axis) {
if (!me.axes[axis.position]) {
return;
}
var config = me.axes[axis.position],
startPan = config.startPan || 0,
startZoom = config.startZoom || 1;
if (startPan != 0 || startZoom != 1) {
me.transformAxisBy(axis, startPan, startPan, startZoom, startZoom);
}
});
}
if (!opt || opt.type == 'afterrender') {
me.onGestureEnd();
me.onPanGestureEnd();
}
},
getInteractiveAxes: function() {
var me = this,
axisConfigs = me.axes;
return me.chart.axes.filterBy(function(axis) {
return !!axisConfigs[axis.position];
});
},
isEventOnAxis: function(e, axis) {
// TODO right now this uses the current event position but really we want to only
// use the gesture's start event. Pinch does not give that to us though.
var util = Ext.util;
return !util.Region.getRegion(axis.getSurface().el).isOutOfBound(util.Point.fromEvent(e));
},
sync: function() {
var me = this,
chart = me.chart,
anim = chart.animate,
axes = me.getInteractiveAxes();
chart.animate = false;
chart.endsLocked = true;
axes.each(function(axis) {
if (axis.hasFastTransform()) {
axis.syncToFastTransform();
// redraw the axis
axis.drawAxis();
axis.renderFrame();
}
});
// sync all series bound to this axis
me.getSeriesForAxes(axes).each(function(series) {
if (series.hasFastTransform()) {
series.syncToFastTransform();
// redraw the series
series.drawSeries();
series.getSurface().renderFrame();
}
});
chart.endsLocked = false;
chart.animate = anim;
},
needsSync: function() {
return !!this.getInteractiveAxes().findBy(function(axis) {
return axis.hasFastTransform();
});
},
transformAxisBy: function(axis, panX, panY, zoomX, zoomY) {
var me = this,
config = me.axes[axis.position],
minZoom = config.minZoom || 1,
maxZoom = config.maxZoom || 4,
isNumber = Ext.isNumber,
length = axis.length,
isSide = axis.isSide(),
pan = isSide ? panY : panX,
zoom = isSide ? zoomY : zoomX;
function doTransform(target) {
var matrix = target.getTransformMatrix().clone(),
currentZoom, inverse, inset;
if (pan !== 0) {
matrix.translate(isSide ? 0 : pan, isSide ? pan : 0);
}
if (zoom !== 1) {
// constrain to minZoom/maxZoom zoom
currentZoom = matrix.get(+isSide, +isSide);
if (isNumber(minZoom)) {
zoom = Math.max(zoom, minZoom / currentZoom);
}
if (isNumber(maxZoom)) {
zoom = Math.min(zoom, maxZoom / currentZoom);
}
// use the matrix's inverse to find the scale origin that lines up with the middle of the axis
inverse = matrix.invert();
matrix.scale(
isSide ? 1 : zoom, isSide ? zoom : 1, inverse.x(length / 2, 0), inverse.y(0, length / 2));
}
// constrain pan
inset = matrix[isSide ? 'y' : 'x'](0, 0);
if (inset > 0) {
matrix.translate(isSide ? 0 : -inset, isSide ? -inset : 0);
}
inset = length - matrix[isSide ? 'y' : 'x'](length, length);
if (inset > 0) {
matrix.translate(isSide ? 0 : inset, isSide ? inset : 0);
}
target.setTransformMatrixFast(matrix);
}
doTransform(axis);
axis.getBoundSeries().each(doTransform);
if (me.showOverflowArrows) {
me.updateAxisOverflowArrows(axis);
}
},
getPannableAxes: function(e) {
var me = this,
axisConfigs = me.axes,
config;
return me.chart.axes.filterBy(function(axis) {
config = axisConfigs[axis.position];
return config && config.allowPan !== false && me.isEventOnAxis(e, axis);
});
},
panBy: function(axes, x, y) {
axes.each(function(axis) {
this.transformAxisBy(axis, x, y, 1, 1);
},
this);
},
onPanGestureStart: function(e) {
if (!e || !e.touches || e.touches.length < 2) { //Limit drags to single touch
var me = this;
me.cancelSync();
if (me.zoomOnPanGesture) {
me.onGestureStart(e);
}
}
},
onPanGesture: function(e) {
if (!e.touches || e.touches.length < 2) { //Limit drags to single touch
var me = this;
if (me.zoomOnPanGesture) {
me.zoomBy(
me.getZoomableAxes(e), (e.previousX + e.previousDeltaX) / e.previousX, e.previousY / (e.previousY + e.previousDeltaY));
} else {
me.panBy(me.getPannableAxes(e), e.previousDeltaX, e.previousDeltaY);
}
}
},
onPanGestureEnd: function(e) {
var me = this;
if (me.zoomOnPanGesture) {
me.onGestureEnd(e);
} else {
me.delaySync();
}
},
getSeriesForAxes: function(axes) {
var series = new Ext.util.MixedCollection(false, function(s) {
return s.seriesId;
});
axes.each(function(axis) {
series.addAll(axis.getBoundSeries().items);
});
return series;
},
getZoomableAxes: function(e) {
var me = this,
axisConfigs = me.axes,
config;
return me.chart.axes.filterBy(function(axis) {
config = axisConfigs[axis.position];
return config && config.allowZoom !== false && (!e || me.isEventOnAxis(e, axis));
});
},
zoomBy: function(axes, zoomX, zoomY) {
axes.each(function(axis) {
this.transformAxisBy(axis, 0, 0, zoomX, zoomY);
},
this);
},
onGestureStart: function(e) {
var me = this;
me.cancelSync();
// Hide axis labels while zooming
me.getZoomableAxes(e).each(function(axis) {
axis.hideLabels();
axis.getLabelSurface().renderFrame();
});
},
onGesture: function(e) {
var me = this,
abs = Math.abs,
xDistance = abs(e.secondPageX - e.firstPageX),
yDistance = abs(e.secondPageY - e.firstPageY),
lastDistances = me.lastZoomDistances || [xDistance, yDistance],
zoomX = xDistance < 30 ? 1 : xDistance / (lastDistances[0] || xDistance),
zoomY = yDistance < 30 ? 1 : yDistance / (lastDistances[1] || yDistance);
me.zoomBy(me.getZoomableAxes(e), zoomX, zoomY);
me.lastZoomDistances = [xDistance, yDistance];
},
onGestureEnd: function(e) {
var me = this;
// If there is no transform, unhide the axis tick labels
me.getZoomableAxes(e).each(function(axis) {
if (!axis.hasFastTransform()) {
axis.drawLabel();
axis.getLabelSurface().renderFrame();
}
});
me.delaySync();
delete me.lastZoomDistances;
},
getOverflowArrow: function(axis, direction, opts) {
var me = this,
axisPos = axis.position,
allIndicators = me.overflowIndicators || (me.overflowIndicators = {}),
axisIndicators = allIndicators[axisPos] || (allIndicators[axisPos] = {});
return axisIndicators[direction] || (
axisIndicators[direction] = Ext.chart.Shape.arrow(me.chart.getEventsSurface(), opts));
},
updateAxisOverflowArrows: function(axis) {
var me = this,
isSide = axis.isSide(),
axisPos = axis.position,
allowPan = me.axes[axisPos].allowPan !== false,
length = axis.length,
chart = me.chart,
bbox = chart.chartBBox,
matrix = axis.getTransformMatrix(),
spriteOpts = Ext.apply({
hidden: true,
radius: 5,
opacity: 0.3,
fill: axis.style.stroke
}, me.overflowArrowOptions),
math = Math,
ceil = math.ceil,
floor = math.floor,
upSprite = me.getOverflowArrow(axis, 'up', spriteOpts),
downSprite = me.getOverflowArrow(axis, 'down', spriteOpts),
path;
if (allowPan && (isSide ? ceil(matrix.y(0, 0)) < 0 : floor(matrix.x(length, 0)) > length)) {
// Top
if (isSide) {
path = ['M', bbox.x, bbox.y, 'l', bbox.width / 2, 0, 0, 5, -10, 10, 20, 0, -10, -10, 0, -5, bbox.width / 2, 0, 0, 20, -bbox.width, 0, 'z'].join(',');
}
// Right
else {
path = ['M', bbox.x + bbox.width, bbox.y, 'l', 0, bbox.height / 2, -5, 0, -10, -10, 0, 20, 10, -10, 5, 0, 0, bbox.height / 2, -20, 0, 0, -bbox.height, 'z'].join(',');
}
upSprite.setAttributes({
hidden: false,
path: path
});
} else {
upSprite.hide();
}
if (allowPan && (isSide ? floor(matrix.y(0, length)) > length : ceil(matrix.x(0, 0)) < 0)) {
// Bottom
if (isSide) {
path = ['M', bbox.x, bbox.y + bbox.height, 'l', bbox.width / 2, 0, 0, -5, -10, -10, 20, 0, -10, 10, 0, 5, bbox.width / 2, 0, 0, -20, -bbox.width, 0, 'z'].join(',');
}
// Left
else {
path = ['M', bbox.x, bbox.y, 'l', 0, bbox.height/ 2, 5, 0, 10, -10, 0, 20, -10, -10, -5, 0, 0, bbox.height / 2, 20, 0, 0, -bbox.height, 'z'].join(',');
}
downSprite.setAttributes({
hidden: false,
path: path
});
} else {
downSprite.hide();
}
if (upSprite.dirtyTransform || upSprite.dirtyHidden || downSprite.dirtyTransform || downSprite.dirtyHidden) {
me.chart.getEventsSurface().renderFrame();
}
},
updateAllOverflowArrows: function() {
var me = this;
me.getInteractiveAxes().each(me.updateAxisOverflowArrows, me);
}
});
Ext.applyIf(Ext.chart.interactions.PanZoom.prototype, Ext.chart.interactions.DelayedSync.prototype);
Ext.chart.interactions.Manager.registerType('panzoom', Ext.chart.interactions.PanZoom);
/**
* @class Ext.chart.interactions.PieGrouping
* @extends Ext.chart.interactions.Abstract
*
* The PieGrouping interaction allows the user to select a group of consecutive slices
* in a {@link Ext.chart.series.Pie pie series} to get additional information about the
* group. It provides an interactive user interface with handles that can be dragged
* around the pie to add/remove slices in the selection group.
*
* You can attach this interaction to a chart by including an entry in the chart's
* {@link Ext.chart.Chart#interactions interactions} config with the `piegrouping` type:
*
* new Ext.chart.Chart({
* renderTo: Ext.getBody(),
* width: 800,
* height: 600,
* store: store1,
* series: [ ...pie series options... ],
* interactions: [{
* type: 'piegrouping'
* }]
* });
*
* @author Jason Johnston <jason@sencha.com>
* @docauthor Jason Johnston <jason@sencha.com>
*/
Ext.chart.interactions.PieGrouping = Ext.extend(Ext.chart.interactions.Abstract, {
type: 'piegrouping',
/**
* @cfg {String} gesture
* Specifies the gesture that, when performed on a slice in the pie series, initializes the
* selection UI on that slice. Defaults to `tap`.
*/
gesture: 'tap',
// TODO does it make sense to make this configurable? Are any other gestures relevant for this?
resizeGesture: 'drag',
/**
* @cfg {Number} outset
* Specifies how far beyond the pie circle radius the selection overlay extends.
* Defaults to `6`.
*/
outset: 6,
/**
* @cfg {Boolean} snapWhileDragging
* If set to `true`, the selection overlay will snap to the nearest pie slice continuously
* while the user is dragging the handles, firing the {@link #selectionchange} event each
* time it snaps. Otherwise, the selection will only snap to the nearest slice when the user
* releases the handle drag, firing the event once. Defaults to `false`.
*/
/**
* @cfg {Function} onSelectionChange
* A handler function that can be implemented to handle selection changes, as an alternative
* to adding a listener for the {@link #selectionchange} event. The function will be passed
* the same parameters as are passed to selectionchange listeners.
*/
onSelectionChange: Ext.emptyFn,
constructor: function(config) {
this.addEvents(
/**
* @event selectionchange
* Fired when the set of selected pie slice items changes.
* @param {Ext.chart.interactions.PieGrouping} interaction
* @param {Array} selectedItems
*/
'selectionchange'
);
Ext.chart.interactions.PieGrouping.superclass.constructor.call(this, config);
this.handleStyle = new Ext.chart.interactions.PieGrouping.HandleStyle();
this.sliceStyle = new Ext.chart.interactions.PieGrouping.SliceStyle();
},
initEvents: function() {
Ext.chart.interactions.PieGrouping.superclass.initEvents.call(this, arguments);
var me = this,
resizeGesture = me.resizeGesture;
me.addChartListener(resizeGesture + 'start', me.onResizeStart, me);
me.addChartListener(resizeGesture, me.onResize, me);
me.addChartListener(resizeGesture + 'end', me.onResizeEnd, me);
},
onGesture: function(e) {
var me = this,
outset = me.outset,
item = me.getItemForEvent(e),
handleStyle = me.handleStyle.style,
sliceStyle = me.sliceStyle.style,
surface, startAngle, endAngle, handleLine;
// If already active, allow tap outside the pie to cancel selection, or tapping an item
// not within the selection to start a new selection.
if (me.active && (!item || me.getSelectedItems().indexOf(item) < 0)) {
me.cancel();
}
// Start selection at the tapped item's boundaries
if (!me.active && item) {
surface = me.getSeries().getOverlaySurface();
startAngle = item.startAngle;
endAngle = item.endAngle;
me.slice = {
startAngle: startAngle,
endAngle: endAngle,
sprite: surface.add(Ext.applyIf({
type: 'path'
}, sliceStyle))
};
handleLine = 'M' + Math.max(item.startRho - outset, 0) + ',0L' + (item.endRho + outset) + ',0';
me.startHandle = {
angle: startAngle,
sprite: surface.add(Ext.applyIf({
type: 'path',
path: handleLine + 'l5,-8l-10,0l5,8',
fill: handleStyle.stroke
}, handleStyle))
};
me.endHandle = {
angle: endAngle,
sprite: surface.add(Ext.applyIf({
type: 'path',
path: handleLine + 'l5,8l-10,0l5,-8',
fill: handleStyle.stroke
}, handleStyle))
};
me.mon(me.getSeries(), 'draw', me.onSeriesDraw, me);
me.active = true;
me.updateSprites();
me.fireSelectionChange();
}
},
onResizeStart: function(e) {
var me = this,
abs = Math.abs,
normalizeAngle = me.normalizeAngle,
startHandle = me.startHandle,
endHandle = me.endHandle,
resizeGesture = me.resizeGesture,
activeHandle, angle;
if (me.active) {
angle = normalizeAngle(me.getAngleForEvent(e));
if (abs(angle - normalizeAngle(startHandle.angle)) < 10) {
activeHandle = startHandle;
}
else if (abs(angle - normalizeAngle(endHandle.angle)) < 10) {
activeHandle = endHandle;
}
if (activeHandle) {
me.lockEvents(resizeGesture + 'start', resizeGesture, resizeGesture + 'end');
}
me.activeHandle = activeHandle;
}
},
onResize: function(e) {
var me = this,
handle = me.activeHandle,
snapWhileDragging = me.snapWhileDragging,
slice = me.slice,
sliceStartAngle, sliceEndAngle,
sliceChanged = false,
handleAngle;
if (handle) {
sliceStartAngle = slice.startAngle;
sliceEndAngle = slice.endAngle;
handleAngle = me.getAngleForEvent(e);
handle.angle = handleAngle;
if (handle === me.startHandle) {
sliceStartAngle = snapWhileDragging ? me.snapToItemAngles(handleAngle, 0)[0] : handleAngle;
while (sliceStartAngle > sliceEndAngle) {
sliceStartAngle -= 360;
}
while (sliceStartAngle <= sliceEndAngle) {
sliceStartAngle += 360;
}
if (slice.startAngle !== sliceStartAngle || !snapWhileDragging) {
sliceChanged = true;
}
slice.startAngle = sliceStartAngle;
} else {
sliceEndAngle = snapWhileDragging ? me.snapToItemAngles(0, handleAngle)[1] : handleAngle;
while (sliceStartAngle > sliceEndAngle) {
sliceEndAngle += 360;
}
while (sliceStartAngle <= sliceEndAngle) {
sliceEndAngle -= 360;
}
if (slice.endAngle !== sliceEndAngle || !snapWhileDragging) {
sliceChanged = true;
}
slice.endAngle = sliceEndAngle;
}
me.updateSprites();
if (sliceChanged && snapWhileDragging) {
me.fireSelectionChange();
}
}
},
onResizeEnd: function(e) {
var me = this,
handle = me.activeHandle,
startHandle = me.startHandle,
endHandle = me.endHandle,
slice = me.slice,
closestAngle = me.closestAngle,
resizeGesture = me.resizeGesture,
snappedAngles, sliceStartAngle, sliceEndAngle;
if (handle) {
snappedAngles = me.snapToItemAngles(startHandle.angle, endHandle.angle);
sliceStartAngle = slice.startAngle;
sliceEndAngle = slice.endAngle;
if (handle === startHandle) {
startHandle.angle = closestAngle(snappedAngles[0], startHandle.angle, 1);
sliceStartAngle = snappedAngles[0];
while (sliceStartAngle > sliceEndAngle) {
sliceStartAngle -= 360;
}
while (sliceStartAngle <= sliceEndAngle) {
sliceStartAngle += 360;
}
slice.startAngle = sliceStartAngle;
} else {
endHandle.angle = closestAngle(snappedAngles[1], endHandle.angle, 0);
sliceEndAngle = snappedAngles[1];
while (sliceStartAngle > sliceEndAngle) {
sliceEndAngle += 360;
}
while (sliceStartAngle <= sliceEndAngle) {
sliceEndAngle -= 360;
}
slice.endAngle = sliceEndAngle;
}
me.updateSprites(true);
if (!me.snapWhileDragging) {
me.fireSelectionChange();
}
delete me.activeHandle;
me.unlockEvents(resizeGesture + 'start', resizeGesture, resizeGesture + 'end');
}
},
/**
* @private tries to sync the selection overlay to the series when it is redrawn
*/
onSeriesDraw: function() {
var me = this,
startHandle = me.startHandle,
endHandle = me.endHandle,
slice = me.slice,
lastSelection = me.lastSelection,
oldStartItem, oldEndItem,
newStartItem, newEndItem;
if (me.active && lastSelection) {
oldStartItem = lastSelection[0];
oldEndItem = lastSelection[lastSelection.length - 1];
newStartItem = me.findItemByRecord(oldStartItem.storeItem);
newEndItem = me.findItemByRecord(oldEndItem.storeItem);
if (!newStartItem || !newEndItem) {
me.cancel();
} else {
startHandle.angle = slice.startAngle = newStartItem.startAngle;
endHandle.angle = slice.endAngle = newEndItem.endAngle;
while (slice.startAngle > slice.endAngle) {
slice.startAngle -= 360;
}
while (slice.startAngle <= slice.endAngle) {
slice.startAngle += 360;
}
me.updateSprites();
me.fireSelectionChange();
}
}
},
findItemByRecord: function(record) {
var items = this.getSeries().items,
i = items.length;
while (i--) {
if (items[i] && items[i].storeItem === record) {
return items[i];
}
}
},
normalizeAngle: function(angle) {
while (angle < 0) {
angle += 360;
}
return angle % 360;
},
fireSelectionChange: function() {
var me = this,
items = me.getSelectedItems();
me.onSelectionChange(me, items);
me.fireEvent('selectionchange', me, items);
me.lastSelection = items;
},
renderFrame: function() {
this.getSeries().getOverlaySurface().renderFrame();
},
updateSprites: function(animate) {
var me = this,
series = me.getSeries(),
startHandle = me.startHandle,
endHandle = me.endHandle,
angle1 = startHandle.angle,
angle2 = endHandle.angle,
centerX = series.centerX,
centerY = series.centerY,
slice = me.slice,
outset = me.outset,
item1, item2, attrs;
if (me.active) {
// Start handle
attrs = {
rotate: {
degrees: angle1,
x: 0,
y: 0
},
translate: {
x: centerX,
y: centerY
}
};
if (animate) {
startHandle.sprite.stopAnimation();
startHandle.sprite.animate({to: attrs});
} else {
startHandle.sprite.setAttributes(attrs, true);
}
// End handle
attrs = {
rotate: {
degrees: angle2,
x: 0,
y: 0
},
translate: {
x: centerX,
y: centerY
}
};
if (animate) {
endHandle.sprite.stopAnimation();
endHandle.sprite.animate({to: attrs});
} else {
endHandle.sprite.setAttributes(attrs, true);
}
// Slice
item1 = series.getItemForAngle(angle1 - 1e-9);
item2 = series.getItemForAngle(angle2 + 1e-9);
attrs = {
segment: {
startAngle: slice.startAngle,
endAngle: slice.endAngle,
startRho: Math.max(Math.min(item1.startRho, item2.startRho) - outset, 0),
endRho: Math.min(item1.endRho, item2.endRho) + outset
}
};
if (animate) {
slice.sprite.stopAnimation();
slice.sprite.animate({to: attrs});
} else {
slice.sprite.setAttributes(attrs, true);
}
if (!animate) {
me.renderFrame();
}
}
},
snapToItemAngles: function(startAngle, endAngle) {
var me = this,
series = me.getSeries(),
item1 = series.getItemForAngle(startAngle - 1e-9),
item2 = series.getItemForAngle(endAngle + 1e-9);
return [item1.startAngle, item2.endAngle];
},
closestAngle: function(target, current, dir) {
if (dir) {
while (target > current) {
target -= 360;
}
while (target < current) {
target += 360;
}
} else {
while (target < current) {
target += 360;
}
while (target > current) {
target -= 360;
}
}
return target;
},
cancel: function() {
var me = this,
series;
if (me.active) {
series = me.getSeries();
Ext.destroy(me.startHandle.sprite, me.endHandle.sprite, me.slice.sprite);
me.active = false;
me.startHandle = me.endHandle = me.slice = null;
me.fireSelectionChange();
me.renderFrame();
me.mun(series, 'draw', me.onSeriesDraw, me);
}
},
getSelectedItems: function() {
var me = this,
slice = me.slice,
selectedItems,
series = me.getSeries(),
allItems, item1Index, item2Index;
if (me.active) {
allItems = me.getSeries().items;
item1Index = allItems.indexOf(series.getItemForAngle(slice.startAngle - 1e-9));
item2Index = allItems.indexOf(series.getItemForAngle(slice.endAngle + 1e-9));
if (item1Index <= item2Index) {
selectedItems = allItems.slice(item1Index, item2Index + 1);
} else {
selectedItems = allItems.slice(item1Index).concat(allItems.slice(0, item2Index + 1));
}
// prune undefined items
selectedItems = selectedItems.filter(function(item, i, arr) {
return i in arr;
});
}
return selectedItems || [];
},
getAngleForEvent: function(e) {
var me = this,
series = me.getSeries(),
seriesXY = series.getSurface().el.getXY();
return Ext.draw.Draw.degrees(
Math.atan2(e.pageY - series.centerY - seriesXY[1], e.pageX - series.centerX - seriesXY[0])
);
},
getSeries: function() {
var me = this,
series = me._series;
if (!series) {
series = me._series = me.chart.series.findBy(function(series) {
return series.type === 'pie';
});
series.getOverlaySurface().customAttributes.segment = function(opts) {
return series.getSegment(opts);
};
}
return series;
},
/* ---------------------------------
Methods needed for ComponentQuery
----------------------------------*/
getRefItems: function(deep) {
return [this.handleStyle, this.sliceStyle];
}
});
Ext.chart.interactions.Manager.registerType('piegrouping', Ext.chart.interactions.PieGrouping);
Ext.chart.interactions.PieGrouping.HandleStyle = Ext.extend(Ext.chart.theme.Style, {
isXType: function(xtype) {
return xtype === 'handle';
}
});
Ext.chart.interactions.PieGrouping.SliceStyle = Ext.extend(Ext.chart.theme.Style, {
isXType: function(xtype) {
return xtype === 'slice';
}
});
/**
* @class Ext.chart.interactions.Rotate
* @extends Ext.chart.interactions.Abstract
*
* The Rotate interaction allows rotation of a Pie or Radar chart series. By default rotation
* is performed via a single-finger drag around the center of the series, but can be configured
* to use a two-finger pinch-rotate gesture by setting `gesture: 'pinch'`.
*
* To attach this interaction to a chart, include an entry in the chart's
* {@link Ext.chart.Chart#interactions interactions} config with the `rotate` type:
*
* new Ext.chart.Chart({
* renderTo: Ext.getBody(),
* width: 800,
* height: 600,
* store: store1,
* series: [ ...pie/radar series options... ],
* interactions: [{
* type: 'rotate'
* }]
* });
*
* @author Jason Johnston <jason@sencha.com>
* @docauthor Jason Johnston <jason@sencha.com>
*/
Ext.chart.interactions.Rotate = Ext.extend(Ext.chart.interactions.Abstract, {
/**
* @cfg {String} gesture
* Defines the gesture type that will be used to rotate the chart. Currently only
* supports `pinch` for two-finger rotation and `drag` for single-finger rotation.
* Defaults to `drag`.
*/
gesture: 'drag',
constructor: function(config) {
var me = this,
interactionsNS = Ext.chart.interactions;
interactionsNS.Rotate.superclass.constructor.call(me, config);
interactionsNS.DelayedSync.prototype.constructor.call(me, config);
},
initEvents: function() {
Ext.chart.interactions.Rotate.superclass.initEvents.call(this, arguments);
var me = this,
gesture = me.gesture;
me.addChartListener(gesture + 'start', me.onGestureStart, me);
me.addChartListener(gesture + 'end', me.onGestureEnd, me);
},
onGestureStart: function() {
var me = this,
axis = me.getAxis();
me.cancelSync();
me.getSeries().each(function(series) {
series.unHighlightItem();
series.origHighlight = series.highlight;
series.highlight = false;
if (series.callouts) {
series.hideCallouts(0);
series.getSurface().renderFrame();
}
});
if (axis && axis.position === 'radial') {
axis.hideLabels();
axis.renderFrame();
}
},
onGesture: function(e) {
var me = this,
oldAngle = me.lastAngle,
firstPageX, secondPageX, firstPageY, secondPageY,
series, seriesXY, newAngle, undef;
if (me.gesture === 'pinch') {
// Multi-touch pinch event - use angle between two touches
firstPageX = e.firstPageX;
firstPageY = e.firstPageY;
secondPageX = e.secondPageX;
secondPageY = e.secondPageY;
} else {
// Single-touch event - use angle between touch point and series center
series = me.getSeries().get(0);
seriesXY = series.getSurface().el.getXY();
firstPageX = series.centerX + seriesXY[0];
firstPageY = series.centerY + seriesXY[1];
secondPageX = e.pageX;
secondPageY = e.pageY;
}
newAngle = Ext.draw.Draw.degrees(Math.atan2(secondPageY - firstPageY, secondPageX - firstPageX));
if (oldAngle === undef) {
oldAngle = newAngle;
}
if (oldAngle !== newAngle) {
me.rotateBy(newAngle - oldAngle);
}
me.lastAngle = newAngle;
},
onGestureEnd: function() {
var me = this;
me.delaySync();
me.getSeries().each(function(series) {
series.highlight = series.origHighlight;
});
delete me.lastAngle;
},
rotateBy: function(angle) {
var me = this,
series = me.getSeries(),
axis = me.getAxis(),
matrix;
me.rotation = (me.rotation || 0) + angle;
series.each(function(series) {
matrix = series.getFastTransformMatrix();
matrix.rotate(angle, series.centerX, series.centerY);
series.setFastTransformMatrix(matrix);
});
if (axis) {
matrix = axis.getFastTransformMatrix();
matrix.rotate(angle, axis.centerX, axis.centerY);
axis.setFastTransformMatrix(matrix);
}
},
seriesFilter: function(series) {
return series.type === 'pie' || series.type === 'radar';
},
getSeries: function() {
return this.chart.series.filter(this.seriesFilter);
},
axisFilter: function(axis) {
return axis.position === 'radial';
},
getAxis: function() {
return this.chart.axes.findBy(this.axisFilter);
},
sync: function() {
var me = this,
chart = me.chart,
axis = me.getAxis(),
anim = chart.animate;
chart.animate = false;
me.getSeries().each(function(series) {
series.rotation -= me.rotation;
series.drawSeries();
series.getSurface().renderFrame();
series.clearTransform();
});
if (axis) {
axis.rotation -= me.rotation;
axis.drawAxis();
axis.renderFrame();
axis.clearTransform();
}
chart.animate = anim;
me.rotation = 0;
},
needsSync: function() {
return !!this.rotation;
}
});
Ext.applyIf(Ext.chart.interactions.Rotate.prototype, Ext.chart.interactions.DelayedSync.prototype);
Ext.chart.interactions.Manager.registerType('rotate', Ext.chart.interactions.Rotate);
/**
* @class Ext.chart.interactions.ItemCompare
* @extends Ext.chart.interactions.Abstract
*
* The ItemCompare interaction allows the user to select two data points in a series and
* see a trend comparison between the two. An arrowed line will be drawn between the two points.
*
* You can attach this interaction to a chart by including an entry in the chart's
* {@link Ext.chart.Chart#interactions interactions} config with the `itemcompare` type:
*
* new Ext.chart.Chart({
* renderTo: Ext.getBody(),
* width: 800,
* height: 600,
* store: store1,
* axes: [ ...some axes options... ],
* series: [ ...some series options... ],
* interactions: [{
* type: 'itemcompare'
* }]
* });
*
* The display of the arrowed line {@link Ext.draw.Sprite sprites} can be customized via the
* {@link #circle}, {@link #line}, and {@link #arrow} configs. It can also be given a global
* {@link #offset position offset}.
*
* Use the {@link #show} and {@link #hide} events to perform additional actions when the trend
* is displayed or hidden, such as displaying the trend change percentage to the user. Handlers
* for these events are passed a reference to the ItemCompare interaction instance, so you
* can access data from the {@link #item1} and {@link #item2} properties.
*
* @author Nicolas Garcia Belmonte <nicolas@sencha.com>
* @docauthor Jason Johnston <jason@sencha.com>
*/
Ext.chart.interactions.ItemCompare = Ext.extend(Ext.chart.interactions.Abstract, {
/**
* @cfg {Object} circle
* Custom {@link Ext.draw.Sprite} configuration to be applied to the sprite for the trend
* line's starting circle.
*/
/**
* @cfg {Object} line
* Custom {@link Ext.draw.Sprite} configuration to be applied to the sprite for the trend
* line's connecting line.
*/
/**
* @cfg {Object} arrow
* Custom {@link Ext.draw.Sprite} configuration to be applied to the sprite for the trend
* line's ending arrow.
*/
/**
* @cfg {Object} offset
* An optional x and y offset for the trend line's sprites in relation to the series items'
* target points. Defaults to `{x:0, y:0}`.
*/
/**
* @property item1
* @type {Object}
* An object containing information about the first selected data point item if any.
*/
/**
* @property item2
* @type {Object}
* An object containing information about the second selected data point item if any.
*/
/**
* @cfg {String} gesture
* Specifies which gesture type should be used for selecting the items to be compared.
* Defaults to `tap`.
*/
gesture: 'tap',
type: 'itemcompare',
constructor: function(config) {
var me = this;
me.addEvents(
/**
* @event hide
* Fired when the point-to-point comparison is displayed
* @param {Ext.chart.interactions.ItemCompare} this interaction instance
*/
'show',
/**
* @event hide
* Fired when the point-to-point comparison is hidden
* @param {Ext.chart.interactions.ItemCompare} this interaction instance
*/
'hide');
me.circleStyle = new (Ext.extend(Ext.chart.theme.Style, {isXType: function(xtype) {return xtype === 'circle';}}))(config.circle);
me.lineStyle = new (Ext.extend(Ext.chart.theme.Style, {isXType: function(xtype) {return xtype === 'line';}}))(config.line);
me.arrowStyle = new (Ext.extend(Ext.chart.theme.Style, {isXType: function(xtype) {return xtype === 'arrow';}}))(config.arrow);
delete config.line;
delete config.circle;
delete config.arrow;
config.chart.on('refresh', me.reset, me);
Ext.chart.interactions.ItemCompare.superclass.constructor.call(this, config);
},
onGesture: function(e) {
var me = this,
item = me.getItemForEvent(e);
if (item) {
//if we were already showing the overlay for previous items, then reset
if (me.item1 && me.item2) {
me.reset();
}
if (me.item1) {
if (me.item1.series != item.series) {
me.reset();
}
else if (item !== me.item1) {
me.item2 = item;
item.series.highlightItem(item);
me.showOverlay();
}
} else {
me.item1 = item;
item.series.highlightItem(item);
}
} else {
me.reset();
}
},
/**
* Resets any selected comparison items, removes the overlay arrow if present, and fires
* the 'hide' event.
*/
reset: function() {
var me = this,
series = me.activeSeries;
if (series) {
me.line.remove();
me.circle.remove();
me.arrow.remove();
series.unHighlightItem();
series.un('transform', me.onSeriesTransform, me);
series.getOverlaySurface().renderFrame();
delete me.activeSeries;
}
me.item1 = me.item2 = null;
me.fireEvent('hide', me);
},
onSeriesTransform: function(obj, fast) {
if (!fast) {
this.renderSprites();
}
},
showOverlay: function() {
var me = this,
series = me.item1.series; //both items are always from the same series
me.activeSeries = series;
series.on('transform', me.onSeriesTransform, me);
me.renderSprites();
me.fireEvent('show', me);
},
initSprites: function() {
var me = this,
Sprite = Ext.draw.Sprite,
arrowStyle = me.arrowStyle.style,
arrowRadius;
if (!me.line) {
me.line = new Sprite(
Ext.apply({
type: 'path',
path: ['M', 0, 0]
},
me.lineStyle.style)
);
me.circle = new Sprite(
Ext.apply({
type: 'circle',
radius: 3
},
me.circleStyle.style)
);
arrowRadius = arrowStyle.radius || 3;
me.arrow = new Sprite(
Ext.apply({
type: 'path',
path: "M".concat("0,0m0-", arrowRadius * 0.58, "l", arrowRadius * 0.5, ",", arrowRadius * 0.87, "-", arrowRadius, ",0z")
},
arrowStyle)
);
}
},
renderSprites: function() {
var me = this,
item1 = me.item1,
item2 = me.item2,
series = item1.series, //both items are always from the same series
overlaySurface, p1, p2, offset, offsetX, offsetY, x1, y1, x2, y2, line, circle, arrow;
if (series) {
me.initSprites();
overlaySurface = series.getOverlaySurface();
p1 = item1.point;
p2 = item2.point;
offset = me.offset || {};
offsetX = offset.x || 0;
offsetY = offset.y || 0;
x1 = (p1[0] + offsetX);
y1 = (p1[1] + offsetY);
x2 = (p2[0] + offsetX);
y2 = (p2[1] + offsetY);
line = me.line;
circle = me.circle;
arrow = me.arrow;
line.setAttributes({
path: ['M', x1, y1, 'L', x2, y2]
});
circle.setAttributes({
translate: {
x: x1,
y: y1
}
});
arrow.setAttributes({
translate: {
x: x2,
y: y2
},
rotate: {
x: 0,
y: 0,
degrees: (Math.atan2(p2[1] - p1[1], p2[0] - p1[0]) * 180 / Math.PI - 90) + 180
}
});
overlaySurface.add(line, circle, arrow);
overlaySurface.renderFrame();
}
},
/* ---------------------------------
Methods needed for ComponentQuery
----------------------------------*/
getRefItems: function(deep) {
var me = this;
return [me.arrowStyle, me.lineStyle, me.circleStyle];
}
});
Ext.chart.interactions.Manager.registerType('itemcompare', Ext.chart.interactions.ItemCompare);
/**
* @class Ext.chart.interactions.ItemHighlight
* @extends Ext.chart.interactions.Abstract
*
* The ItemHighlight interaction allows highlighting of series data items on the chart.
* This interaction enables triggering and clearing the highlight on certain events, but
* does not control how the highlighting is implemented or styled; that is handled by
* each individual Series type and the {@link Ext.chart.Highlight} mixin. See the documentation
* for that mixin for how to customize the highlighting effect.
*
* To attach this interaction to a chart, include an entry in the chart's
* {@link Ext.chart.Chart#interactions interactions} config with the `itemhighlight` type:
*
* new Ext.chart.Chart({
* renderTo: Ext.getBody(),
* width: 800,
* height: 600,
* store: store1,
* axes: [ ...some axes options... ],
* series: [ ...some series options... ],
* interactions: [{
* type: 'itemhighlight'
* }]
* });
*
* @author Jason Johnston <jason@sencha.com>
* @docauthor Jason Johnston <jason@sencha.com>
*/
Ext.chart.interactions.ItemHighlight = Ext.extend(Ext.chart.interactions.Abstract, {
gesture: 'tap',
unHighlightEvent: 'touchstart',
initEvents: function() {
var me = this;
Ext.chart.interactions.ItemHighlight.superclass.initEvents.call(me, arguments);
me.addChartListener(me.unHighlightEvent, me.onUnHighlightEvent, me);
},
onGesture: function(e) {
var me = this,
items = me.getItemsForEvent(e),
item, highlightedItem, series,
i, len;
for(i = 0, len = items.length; i < len; i++) {
item = items[i];
series = item.series;
highlightedItem = series.highlightedItem;
if (highlightedItem !== item) {
if (highlightedItem) {
highlightedItem.series.unHighlightItem();
}
series.highlightItem(item);
series.highlightedItem = item;
}
}
},
onUnHighlightEvent: function(e) {
var me = this,
chart = me.chart,
xy = chart.getEventXY(e),
highlightedItem;
chart.series.each(function(series) {
highlightedItem = series.highlightedItem;
if (highlightedItem && highlightedItem !== series.getItemForPoint(xy[0], xy[1])) {
series.unHighlightItem();
delete series.highlightedItem;
}
});
}
});
Ext.chart.interactions.Manager.registerType('itemhighlight', Ext.chart.interactions.ItemHighlight);
/**
* @class Ext.chart.interactions.ItemInfo
* @extends Ext.util.Observable
*
* The ItemInfo interaction allows displaying detailed information about a series data
* point in a popup panel.
*
* To attach this interaction to a chart, include an entry in the chart's
* {@link Ext.chart.Chart#interactions interactions} config with the `iteminfo` type:
*
* new Ext.chart.Chart({
* renderTo: Ext.getBody(),
* width: 800,
* height: 600,
* store: store1,
* axes: [ ...some axes options... ],
* series: [ ...some series options... ],
* interactions: [{
* type: 'iteminfo',
* listeners: {
* show: function(me, item, panel) {
* panel.update('Stock Price: $' + item.storeItem.get('price'));
* }
* }
* }]
* });
* @author Nicolas Garcia Belmonte <nicolas@sencha.com>
* @docauthor Jason Johnston <jason@sencha.com>
*/
Ext.chart.interactions.ItemInfo = Ext.extend(Ext.chart.interactions.Abstract, {
/**
* @cfg {String} gesture
* Defines the gesture type that should trigger the item info panel to be displayed.
* Defaults to `tap`.
*/
gesture: 'tap',
/**
* @cfg {Object} panel
* An optional set of configuration overrides for the {@link Ext.Panel} that gets
* displayed. This object will be merged with the default panel configuration.
*/
constructor: function(config) {
var me = this;
me.addEvents(
/**
* @event show
* Fires when the info panel is shown.
* @param {Ext.chart.interactions.ItemInfo} this The interaction instance
* @param {Object} item The item whose info is being displayed
* @param {Ext.Panel} panel The panel for displaying the info
*/
'show'
);
Ext.chart.interactions.ItemInfo.superclass.constructor.call(me, config);
},
getPanel: function() {
var me = this,
panel = me.infoPanel;
if (!panel) {
panel = me.infoPanel = new Ext.Panel(Ext.apply({
floating: true,
modal: true,
centered: true,
width: 250,
styleHtmlContent: true,
scroll: 'vertical',
dockedItems: [{
dock: 'top',
xtype: 'toolbar',
title: 'Item Detail'
}],
stopMaskTapEvent: false,
fullscreen: false,
listeners: {
hide: me.reset,
scope: me
}
},
me.panel));
}
return panel;
},
onGesture: function(e) {
var me = this,
item = me.getItemForEvent(e),
panel;
if (item) {
me.item = item;
item.series.highlightItem(item);
panel = me.getPanel();
me.fireEvent('show', me, item, panel);
panel.show('pop');
}
},
reset: function() {
var me = this,
item = me.item;
if (item) {
item.series.unHighlightItem(item);
delete me.item;
}
}
});
Ext.chart.interactions.Manager.registerType('iteminfo', Ext.chart.interactions.ItemInfo);
/**
* @class Ext.chart.interactions.Reset
* @extends Ext.chart.interactions.Abstract
*
* The Reset interaction allows resetting of all previous user interactions with
* the chart. By default the reset is triggered by a double-tap on the empty chart
* area; to customize the event use the {@link #event} config.
*
* To attach this interaction to a chart, include an entry in the chart's
* {@link Ext.chart.Chart#interactions interactions} config with the `reset` type:
*
* new Ext.chart.Chart({
* renderTo: Ext.getBody(),
* width: 800,
* height: 600,
* store: store1,
* axes: [ ...some axes options... ],
* series: [ ...some series options... ],
* interactions: [{
* type: 'reset'
* }]
* });
* @author Nicolas Garcia Belmonte <nicolas@sencha.com>
* @docauthor Jason Johnston <jason@sencha.com>
*/
Ext.chart.interactions.Reset = Ext.extend(Ext.chart.interactions.Abstract, {
/**
* @cfg {String} gesture
* Defines the gesture type that should trigger the chart reset. Gestures that occur on a series
* item will be ignored. Defaults to `doubletap`.
*/
gesture: 'doubletap',
/**
* @cfg {Boolean} confirm
* If set to `true`, a dialog will be presented to the user to confirm that they want to reset
* the chart. Defaults to `false`.
*/
/**
* @cfg {String} confirmTitle
* Specifies the title displayed in the confirmation dialog, if {@link #confirm} is `true`.
* Defaults to `'Reset'`
*/
confirmTitle: 'Reset',
/**
* @cfg {String} confirmText
* Specifies the text displayed in the confirmation dialog, if {@link #confirm} is `true`.
* Defaults to `'Reset the chart?'`
*/
confirmText: 'Reset the chart?',
onGesture: function(e) {
var me = this,
chart = me.chart;
if (!me.getItemForEvent(e)) {
if (me.confirm) {
Ext.Msg.confirm(me.confirmTitle, me.confirmText, function(button) {
if (button === 'yes') {
chart.reset();
}
});
} else {
chart.reset();
}
}
}
});
Ext.chart.interactions.Manager.registerType('reset', Ext.chart.interactions.Reset);
/**
* @class Ext.chart.interactions.ToggleStacked
* @extends Ext.chart.interactions.Abstract
*
* The ToggleStacked interaction allows toggling a {@link Ext.chart.series.Bar bar} or
* {@link Ext.chart.series.Column column} series between stacked and grouped orientations
* for multiple yField values. By default this is triggered via a `swipe` event; to customize
* the trigger event modify the {@link #event} config.
*
* To attach this interaction to a chart, include an entry in the chart's
* {@link Ext.chart.Chart#interactions interactions} config with the `togglestacked` type:
*
* new Ext.chart.Chart({
* renderTo: Ext.getBody(),
* width: 800,
* height: 600,
* store: store1,
* axes: [ ...some axes options... ],
* series: [ ...bar or column series options... ],
* interactions: [{
* type: 'togglestacked',
* event: 'doubletap'
* }]
* });
*
* @author Jason Johnston <jason@sencha.com>
* @docauthor Jason Johnston <jason@sencha.com>
*/
Ext.chart.interactions.ToggleStacked = Ext.extend(Ext.chart.interactions.Abstract, {
/**
* @cfg {String} gesture
* Defines the gesture type that should trigger the toggle. Defaults to `swipe`.
*/
gesture: 'swipe',
/**
* @cfg {Boolean} animateDirect
* If set to `true`, then animation will skip the intermediate disjoint state and simply
* animate directly from the stacked to grouped orientation. Only relevant if the chart
* is configured to allow animation. Defaults to `false`.
*/
onGesture: function(e) {
var me = this,
chart = me.chart,
series = me.getSeries();
if (series) {
if (chart.animate && !me.animateDirect) {
if (!me.locked) {
me.lock();
if (series.stacked) {
series.disjointStacked = true;
me.afterAnim(series, function() {
series.stacked = series.disjointStacked = false;
me.afterAnim(series, me.unlock);
chart.redraw();
});
series.drawSeries();
}
else {
series.stacked = series.disjointStacked = true;
me.afterAnim(series, function() {
series.disjointStacked = false;
me.afterAnim(series, me.unlock);
series.drawSeries();
});
chart.redraw();
}
}
} else {
series.stacked = !series.stacked;
chart.redraw();
}
}
},
lock: function() {
this.locked = true;
},
unlock: function() {
this.locked = false;
},
afterAnim: function(series, fn) {
// TODO this fires too soon if the series is configured with bar labels
series.on('afterrender', fn, this, {
single: true,
// must delay slightly so the handler can set another afterrender
// listener without it getting called immediately:
delay: 1
});
},
getSeries: function() {
return this.chart.series.findBy(function(series) {
return series.type === 'bar' || series.type === 'column';
});
}
});
Ext.chart.interactions.Manager.registerType('togglestacked', Ext.chart.interactions.ToggleStacked);
| 0 | 0.887933 | 1 | 0.887933 | game-dev | MEDIA | 0.639411 | game-dev,web-frontend | 0.976929 | 1 | 0.976929 |
STEdyd666/dash-blueprint-components | 2,145 | usage.py | import dash_blueprint_components as dbpc
import dash
from dash import html, callback, Input, Output, State
app = dash.Dash(__name__)
options = [
{
"label": "List",
"value": "list",
},
{
"label": "Grid",
"value": "grid",
},
{
"label": "Gallery",
"value": "gallery",
},
]
app.layout = html.Div(
style={"background": "lightgrey"},
children=[
dbpc.SegmentedControl(
id="segmented-control",
options=options,
value="list",
),
dbpc.SegmentedControl(
id="segmented-control_2",
options=options,
disabled=True,
),
dbpc.Button(
id="read_control_2_value",
text="Read value",
),
dbpc.InputGroup(
id="input-group",
value="",
),
dbpc.InputGroup(
id="input-group_2",
value="",
),
],
)
@callback(
Output("segmented-control_2", "value"),
Input("segmented-control", "value"),
State("segmented-control", "defaultValue"),
)
def update_segmented_control_2(value, default):
print(f"Updating the responsive segmented control, received value: {value}")
print(f"Default value: {default}")
return value
@callback(
Output("input-group", "value"),
Input("segmented-control_2", "value"),
Input("read_control_2_value", "n_clicks"),
)
def show_value(value, read_value):
if value is None:
raise dash.exceptions.PreventUpdate
print(f"Received value: {value}")
return value
@callback(
Output("input-group_2", "value"),
Input("read_control_2_value", "n_clicks"),
State("segmented-control", "value"),
State("segmented-control", "value"),
)
def show_control_1_value(read_value, value1, value2):
if not read_value:
raise dash.exceptions.PreventUpdate
if value1 is None:
value1 = "No value detected for control 1"
if value2 is None:
value2 = "No value detected for control 2"
return f"Control 1 value: {value1}, Control 2 value: {value2}"
app.run(debug=True) | 0 | 0.746701 | 1 | 0.746701 | game-dev | MEDIA | 0.571164 | game-dev | 0.871773 | 1 | 0.871773 |
mangosthree/server | 32,317 | src/game/Object/ArenaTeam.cpp | /**
* MaNGOS is a full featured server for World of Warcraft, supporting
* the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8
*
* Copyright (C) 2005-2025 MaNGOS <https://www.getmangos.eu>
*
* 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* World of Warcraft, and all World of Warcraft or Warcraft art, images,
* and lore are copyrighted by Blizzard Entertainment, Inc.
*/
#include "WorldPacket.h"
#include "ObjectMgr.h"
#include "ObjectGuid.h"
#include "ArenaTeam.h"
#include "World.h"
#include "Player.h"
void ArenaTeamMember::ModifyPersonalRating(Player* plr, int32 mod, uint32 slot)
{
if (int32(personal_rating) + mod < 0)
{
personal_rating = 0;
}
else
{
personal_rating += mod;
}
if (plr)
{
plr->SetArenaTeamInfoField(slot, ARENA_TEAM_PERSONAL_RATING, personal_rating);
}
}
ArenaTeam::ArenaTeam()
{
m_TeamId = 0;
m_Type = ARENA_TYPE_NONE;
m_BackgroundColor = 0; // background
m_EmblemStyle = 0; // icon
m_EmblemColor = 0; // icon color
m_BorderStyle = 0; // border
m_BorderColor = 0; // border color
m_stats.games_week = 0;
m_stats.games_season = 0;
m_stats.rank = 0;
int32 conf_value = sWorld.getConfig(CONFIG_INT32_ARENA_STARTRATING);
if (conf_value < 0) // -1 = select by season id
{
if (sWorld.getConfig(CONFIG_UINT32_ARENA_SEASON_ID) >= 6)
{
m_stats.rating = 0;
}
else
{
m_stats.rating = 1500;
}
}
else
{
m_stats.rating = uint32(conf_value);
}
m_stats.wins_week = 0;
m_stats.wins_season = 0;
}
ArenaTeam::~ArenaTeam()
{
}
bool ArenaTeam::Create(ObjectGuid captainGuid, ArenaType type, std::string arenaTeamName)
{
if (!IsArenaTypeValid(type))
{
return false;
}
if (!sObjectMgr.GetPlayer(captainGuid)) // player not exist
{
return false;
}
if (sObjectMgr.GetArenaTeamByName(arenaTeamName)) // arena team with this name already exist
{
return false;
}
DEBUG_LOG("GUILD: creating arena team %s to leader: %s", arenaTeamName.c_str(), captainGuid.GetString().c_str());
m_CaptainGuid = captainGuid;
m_Name = arenaTeamName;
m_Type = type;
m_TeamId = sObjectMgr.GenerateArenaTeamId();
// ArenaTeamName already assigned to ArenaTeam::name, use it to encode string for DB
CharacterDatabase.escape_string(arenaTeamName);
CharacterDatabase.BeginTransaction();
// CharacterDatabase.PExecute("DELETE FROM `arena_team` WHERE `arenateamid`='%u'", m_TeamId); - MAX(arenateam)+1 not exist
CharacterDatabase.PExecute("DELETE FROM `arena_team_member` WHERE `arenateamid`='%u'", m_TeamId);
CharacterDatabase.PExecute("INSERT INTO `arena_team` (`arenateamid`,`name`,`captainguid`,`type`,`BackgroundColor`,`EmblemStyle`,`EmblemColor`,`BorderStyle`,`BorderColor`) "
"VALUES('%u','%s','%u','%u','%u','%u','%u','%u','%u')",
m_TeamId, arenaTeamName.c_str(), m_CaptainGuid.GetCounter(), m_Type, m_BackgroundColor, m_EmblemStyle, m_EmblemColor, m_BorderStyle, m_BorderColor);
CharacterDatabase.PExecute("INSERT INTO `arena_team_stats` (`arenateamid`, `rating`, `games_week`, `wins_week`, `games_season`, `wins_season`, `rank`) VALUES "
"('%u', '%u', '%u', '%u', '%u', '%u', '%u')", m_TeamId, m_stats.rating, m_stats.games_week, m_stats.wins_week, m_stats.games_season, m_stats.wins_season, m_stats.rank);
CharacterDatabase.CommitTransaction();
AddMember(m_CaptainGuid);
return true;
}
bool ArenaTeam::AddMember(ObjectGuid playerGuid)
{
std::string plName;
uint8 plClass;
// arena team is full (can't have more than type * 2 players!)
if (GetMembersSize() >= GetMaxMembersSize())
{
return false;
}
Player* pl = sObjectMgr.GetPlayer(playerGuid);
if (pl)
{
if (pl->GetArenaTeamId(GetSlot()))
{
sLog.outError("Arena::AddMember() : player already in this sized team");
return false;
}
plClass = pl->getClass();
plName = pl->GetName();
}
else
{
// 0 1
QueryResult* result = CharacterDatabase.PQuery("SELECT `name`, `class` FROM `characters` WHERE `guid`='%u'", playerGuid.GetCounter());
if (!result)
{
return false;
}
plName = (*result)[0].GetCppString();
plClass = (*result)[1].GetUInt8();
delete result;
// check if player already in arenateam of that size
if (Player::GetArenaTeamIdFromDB(playerGuid, GetType()) != 0)
{
sLog.outError("Arena::AddMember() : player %s already in this sized team", playerGuid.GetString().c_str());
return false;
}
}
ArenaTeamMember newmember;
newmember.name = plName;
newmember.guid = playerGuid;
newmember.Class = plClass;
newmember.games_season = 0;
newmember.games_week = 0;
newmember.wins_season = 0;
newmember.wins_week = 0;
int32 conf_value = sWorld.getConfig(CONFIG_INT32_ARENA_STARTPERSONALRATING);
if (conf_value < 0) // -1 = select by season id
{
if (sWorld.getConfig(CONFIG_UINT32_ARENA_SEASON_ID) >= 6)
{
if (m_stats.rating < 1000)
{
newmember.personal_rating = 0;
}
else
{
newmember.personal_rating = 1000;
}
}
else
{
newmember.personal_rating = 1500;
}
}
else
{
newmember.personal_rating = uint32(conf_value);
}
m_members.push_back(newmember);
CharacterDatabase.PExecute("INSERT INTO `arena_team_member` (`arenateamid`, `guid`, `personal_rating`) VALUES ('%u', '%u', '%u')", m_TeamId, newmember.guid.GetCounter(), newmember.personal_rating);
if (pl)
{
pl->SetInArenaTeam(m_TeamId, GetSlot(), GetType());
pl->SetArenaTeamIdInvited(0);
pl->SetArenaTeamInfoField(GetSlot(), ARENA_TEAM_PERSONAL_RATING, newmember.personal_rating);
// hide promote/remove buttons
if (m_CaptainGuid != playerGuid)
{
pl->SetArenaTeamInfoField(GetSlot(), ARENA_TEAM_MEMBER, 1);
}
}
return true;
}
bool ArenaTeam::LoadArenaTeamFromDB(QueryResult* arenaTeamDataResult)
{
if (!arenaTeamDataResult)
{
return false;
}
Field* fields = arenaTeamDataResult->Fetch();
m_TeamId = fields[0].GetUInt32();
m_Name = fields[1].GetCppString();
m_CaptainGuid = ObjectGuid(HIGHGUID_PLAYER, fields[2].GetUInt32());
m_Type = ArenaType(fields[3].GetUInt32());
if (!IsArenaTypeValid(m_Type))
{
return false;
}
m_BackgroundColor = fields[4].GetUInt32();
m_EmblemStyle = fields[5].GetUInt32();
m_EmblemColor = fields[6].GetUInt32();
m_BorderStyle = fields[7].GetUInt32();
m_BorderColor = fields[8].GetUInt32();
// load team stats
m_stats.rating = fields[9].GetUInt32();
m_stats.games_week = fields[10].GetUInt32();
m_stats.wins_week = fields[11].GetUInt32();
m_stats.games_season = fields[12].GetUInt32();
m_stats.wins_season = fields[13].GetUInt32();
m_stats.rank = fields[14].GetUInt32();
return true;
}
bool ArenaTeam::LoadMembersFromDB(QueryResult* arenaTeamMembersResult)
{
if (!arenaTeamMembersResult)
{
return false;
}
bool captainPresentInTeam = false;
do
{
Field* fields = arenaTeamMembersResult->Fetch();
// prevent crash if db records are broken, when all members in result are already processed and current team hasn't got any members
if (!fields)
{
break;
}
uint32 arenaTeamId = fields[0].GetUInt32();
if (arenaTeamId < m_TeamId)
{
// there is in table arena_team_member record which doesn't have arenateamid in arena_team table, report error
sLog.outErrorDb("ArenaTeam %u does not exist but it has record in arena_team_member table, deleting it!", arenaTeamId);
CharacterDatabase.PExecute("DELETE FROM `arena_team_member` WHERE `arenateamid` = '%u'", arenaTeamId);
continue;
}
if (arenaTeamId > m_TeamId)
// we loaded all members for this arena_team already, break cycle
break;
ArenaTeamMember newmember;
newmember.guid = ObjectGuid(HIGHGUID_PLAYER, fields[1].GetUInt32());
newmember.games_week = fields[2].GetUInt32();
newmember.wins_week = fields[3].GetUInt32();
newmember.games_season = fields[4].GetUInt32();
newmember.wins_season = fields[5].GetUInt32();
newmember.personal_rating = fields[6].GetUInt32();
newmember.name = fields[7].GetCppString();
newmember.Class = fields[8].GetUInt8();
// check if member exists in characters table
if (newmember.name.empty())
{
sLog.outErrorDb("ArenaTeam %u has member with empty name - probably player %s doesn't exist, deleting him from memberlist!", arenaTeamId, newmember.guid.GetString().c_str());
DelMember(newmember.guid);
continue;
}
// arena team can't be > 2 * arenatype (2 for 2x2, 3 for 3x3, 5 for 5x5)
if (GetMembersSize() >= GetMaxMembersSize())
{
return false;
}
if (newmember.guid == GetCaptainGuid())
{
captainPresentInTeam = true;
}
m_members.push_back(newmember);
}
while (arenaTeamMembersResult->NextRow());
if (Empty() || !captainPresentInTeam)
{
// arena team is empty or captain is not in team, delete from db
sLog.outErrorDb("ArenaTeam %u does not have any members or its captain is not in team, disbanding it...", m_TeamId);
return false;
}
return true;
}
void ArenaTeam::SetCaptain(ObjectGuid guid)
{
// disable remove/promote buttons
Player* oldcaptain = sObjectMgr.GetPlayer(GetCaptainGuid());
if (oldcaptain)
{
oldcaptain->SetArenaTeamInfoField(GetSlot(), ARENA_TEAM_MEMBER, 1);
}
// set new captain
m_CaptainGuid = guid;
// update database
CharacterDatabase.PExecute("UPDATE `arena_team` SET `captainguid` = '%u' WHERE `arenateamid` = '%u'", guid.GetCounter(), m_TeamId);
// enable remove/promote buttons
if (Player* newcaptain = sObjectMgr.GetPlayer(guid))
{
newcaptain->SetArenaTeamInfoField(GetSlot(), ARENA_TEAM_MEMBER, 0);
}
}
void ArenaTeam::DelMember(ObjectGuid guid)
{
for (MemberList::iterator itr = m_members.begin(); itr != m_members.end(); ++itr)
{
if (itr->guid == guid)
{
m_members.erase(itr);
break;
}
}
if (Player* player = sObjectMgr.GetPlayer(guid))
{
player->GetSession()->SendArenaTeamCommandResult(ERR_ARENA_TEAM_QUIT_S, GetName(), "", 0);
// delete all info regarding this team
for (int i = 0; i < ARENA_TEAM_END; ++i)
{
player->SetArenaTeamInfoField(GetSlot(), ArenaTeamInfoType(i), 0);
}
}
CharacterDatabase.PExecute("DELETE FROM `arena_team_member` WHERE `arenateamid` = '%u' AND `guid` = '%u'", GetId(), guid.GetCounter());
}
void ArenaTeam::Disband(WorldSession* session)
{
// event
if (session)
{
// probably only 1 string required...
BroadcastEvent(ERR_ARENA_TEAM_DISBANDED_S, session->GetPlayerName(), GetName().c_str());
}
while (!m_members.empty())
{
// Removing from members is done in DelMember.
DelMember(m_members.front().guid);
}
CharacterDatabase.BeginTransaction();
CharacterDatabase.PExecute("DELETE FROM `arena_team` WHERE `arenateamid` = '%u'", m_TeamId);
CharacterDatabase.PExecute("DELETE FROM `arena_team_member` WHERE `arenateamid` = '%u'", m_TeamId); //< this should be already done by calling DelMember(memberGuids[j]); for each member
CharacterDatabase.PExecute("DELETE FROM `arena_team_stats` WHERE `arenateamid` = '%u'", m_TeamId);
CharacterDatabase.CommitTransaction();
sObjectMgr.RemoveArenaTeam(m_TeamId);
}
void ArenaTeam::Roster(WorldSession* session)
{
uint8 unk308 = 0;
WorldPacket data(SMSG_ARENA_TEAM_ROSTER, 100);
data << uint32(GetId()); // team id
data << uint8(unk308); // 308 unknown value but affect packet structure
data << uint32(GetMembersSize()); // members count
data << uint32(GetType()); // arena team type?
for (MemberList::const_iterator itr = m_members.begin(); itr != m_members.end(); ++itr)
{
Player* pl = sObjectMgr.GetPlayer(itr->guid);
data << itr->guid; // guid
data << uint8((pl ? 1 : 0)); // online flag
data << itr->name; // member name
data << uint32((itr->guid == GetCaptainGuid() ? 0 : 1));// captain flag 0 captain 1 member
data << uint8((pl ? pl->getLevel() : 0)); // unknown, level?
data << uint8(itr->Class); // class
data << uint32(itr->games_week); // played this week
data << uint32(itr->wins_week); // wins this week
data << uint32(itr->games_season); // played this season
data << uint32(itr->wins_season); // wins this season
data << uint32(itr->personal_rating); // personal rating
if (unk308)
{
data << float(0.0); // 308 unk
data << float(0.0); // 308 unk
}
}
session->SendPacket(&data);
DEBUG_LOG("WORLD: Sent SMSG_ARENA_TEAM_ROSTER");
}
void ArenaTeam::Query(WorldSession* session)
{
WorldPacket data(SMSG_ARENA_TEAM_QUERY_RESPONSE, 4 * 7 + GetName().size() + 1);
data << uint32(GetId()); // team id
data << GetName(); // team name
data << uint32(GetType()); // arena team type (2=2x2, 3=3x3 or 5=5x5)
data << uint32(m_BackgroundColor); // background color
data << uint32(m_EmblemStyle); // emblem style
data << uint32(m_EmblemColor); // emblem color
data << uint32(m_BorderStyle); // border style
data << uint32(m_BorderColor); // border color
session->SendPacket(&data);
DEBUG_LOG("WORLD: Sent SMSG_ARENA_TEAM_QUERY_RESPONSE");
}
void ArenaTeam::Stats(WorldSession* session)
{
WorldPacket data(SMSG_ARENA_TEAM_STATS, 4 * 7);
data << uint32(GetId()); // team id
data << uint32(m_stats.rating); // rating
data << uint32(m_stats.games_week); // games this week
data << uint32(m_stats.wins_week); // wins this week
data << uint32(m_stats.games_season); // played this season
data << uint32(m_stats.wins_season); // wins this season
data << uint32(m_stats.rank); // rank
session->SendPacket(&data);
}
void ArenaTeam::NotifyStatsChanged()
{
// this is called after a rated match ended
// updates arena team stats for every member of the team (not only the ones who participated!)
for (MemberList::const_iterator itr = m_members.begin(); itr != m_members.end(); ++itr)
{
Player* plr = sObjectMgr.GetPlayer(itr->guid);
if (plr)
{
Stats(plr->GetSession());
}
}
}
void ArenaTeam::InspectStats(WorldSession* session, ObjectGuid guid)
{
ArenaTeamMember* member = GetMember(guid);
if (!member)
{
return;
}
WorldPacket data(MSG_INSPECT_ARENA_TEAMS, 8 + 1 + 4 * 6);
data << guid; // player guid
data << uint8(GetSlot()); // slot (0...2)
data << uint32(GetId()); // arena team id
data << uint32(m_stats.rating); // rating
data << uint32(m_stats.games_season); // season played
data << uint32(m_stats.wins_season); // season wins
data << uint32(member->games_season); // played (count of all games, that the inspected member participated...)
data << uint32(member->personal_rating); // personal rating
session->SendPacket(&data);
}
void ArenaTeam::SetEmblem(uint32 backgroundColor, uint32 emblemStyle, uint32 emblemColor, uint32 borderStyle, uint32 borderColor)
{
m_BackgroundColor = backgroundColor;
m_EmblemStyle = emblemStyle;
m_EmblemColor = emblemColor;
m_BorderStyle = borderStyle;
m_BorderColor = borderColor;
CharacterDatabase.PExecute("UPDATE `arena_team` SET `BackgroundColor`='%u', `EmblemStyle`='%u', `EmblemColor`='%u', `BorderStyle`='%u', `BorderColor`='%u' WHERE `arenateamid`='%u'", m_BackgroundColor, m_EmblemStyle, m_EmblemColor, m_BorderStyle, m_BorderColor, m_TeamId);
}
void ArenaTeam::SetStats(uint32 stat_type, uint32 value)
{
switch (stat_type)
{
case STAT_TYPE_RATING:
m_stats.rating = value;
CharacterDatabase.PExecute("UPDATE `arena_team_stats` SET `rating` = '%u' WHERE `arenateamid` = '%u'", value, GetId());
break;
case STAT_TYPE_GAMES_WEEK:
m_stats.games_week = value;
CharacterDatabase.PExecute("UPDATE `arena_team_stats` SET `games_week` = '%u' WHERE `arenateamid` = '%u'", value, GetId());
break;
case STAT_TYPE_WINS_WEEK:
m_stats.wins_week = value;
CharacterDatabase.PExecute("UPDATE `arena_team_stats` SET `wins_week` = '%u' WHERE `arenateamid` = '%u'", value, GetId());
break;
case STAT_TYPE_GAMES_SEASON:
m_stats.games_season = value;
CharacterDatabase.PExecute("UPDATE `arena_team_stats` SET `games_season` = '%u' WHERE `arenateamid` = '%u'", value, GetId());
break;
case STAT_TYPE_WINS_SEASON:
m_stats.wins_season = value;
CharacterDatabase.PExecute("UPDATE `arena_team_stats` SET `wins_season` = '%u' WHERE `arenateamid` = '%u'", value, GetId());
break;
case STAT_TYPE_RANK:
m_stats.rank = value;
CharacterDatabase.PExecute("UPDATE `arena_team_stats` SET `rank` = '%u' WHERE `arenateamid` = '%u'", value, GetId());
break;
default:
DEBUG_LOG("unknown stat type in ArenaTeam::SetStats() %u", stat_type);
break;
}
}
void ArenaTeam::BroadcastPacket(WorldPacket* packet)
{
for (MemberList::const_iterator itr = m_members.begin(); itr != m_members.end(); ++itr)
{
Player* player = sObjectMgr.GetPlayer(itr->guid);
if (player)
{
player->GetSession()->SendPacket(packet);
}
}
}
void ArenaTeam::BroadcastEvent(ArenaTeamEvents event, ObjectGuid guid, char const* str1 /*=NULL*/, char const* str2 /*=NULL*/, char const* str3 /*=NULL*/)
{
uint8 strCount = !str1 ? 0 : (!str2 ? 1 : (!str3 ? 2 : 3));
WorldPacket data(SMSG_ARENA_TEAM_EVENT, 1 + 1 + 1 * strCount + (!guid ? 0 : 8));
data << uint8(event);
data << uint8(strCount);
if (str3)
{
data << str1;
data << str2;
data << str3;
}
else if (str2)
{
data << str1;
data << str2;
}
else if (str1)
{
data << str1;
}
if (guid)
{
data << ObjectGuid(guid);
}
BroadcastPacket(&data);
DEBUG_LOG("WORLD: Sent SMSG_ARENA_TEAM_EVENT");
}
uint8 ArenaTeam::GetSlotByType(ArenaType type)
{
switch (type)
{
case ARENA_TYPE_2v2: return 0;
case ARENA_TYPE_3v3: return 1;
case ARENA_TYPE_5v5: return 2;
default:
break;
}
sLog.outError("FATAL: Unknown arena team type %u for some arena team", type);
return 0xFF;
}
ArenaType ArenaTeam::GetTypeBySlot(uint8 slot)
{
switch (slot)
{
case 0: return ARENA_TYPE_2v2;
case 1: return ARENA_TYPE_3v3;
case 2: return ARENA_TYPE_5v5;
default:
break;
}
sLog.outError("FATAL: Unknown arena team slot %u for some arena team", slot);
return ArenaType(0xFF);
}
uint32 ArenaTeam::GetPoints(uint32 MemberRating)
{
// returns how many points would be awarded with this team type with this rating
float points;
uint32 rating = MemberRating + 150 < m_stats.rating ? MemberRating : m_stats.rating;
if (rating <= 1500)
{
// As of Season 6 and later, all teams below 1500 rating will earn points as if they were a 1500 rated team
if (sWorld.getConfig(CONFIG_UINT32_ARENA_SEASON_ID) >= 6)
{
rating = 1500;
}
points = (float)rating * 0.22f + 14.0f;
}
else
{
points = 1511.26f / (1.0f + 1639.28f * exp(-0.00412f * (float)rating));
}
// type penalties for <5v5 teams
if (m_Type == ARENA_TYPE_2v2)
{
points *= 0.76f;
}
else if (m_Type == ARENA_TYPE_3v3)
{
points *= 0.88f;
}
return (uint32) points;
}
bool ArenaTeam::HaveMember(ObjectGuid guid) const
{
for (MemberList::const_iterator itr = m_members.begin(); itr != m_members.end(); ++itr)
if (itr->guid == guid)
{
return true;
}
return false;
}
float ArenaTeam::GetChanceAgainst(uint32 own_rating, uint32 enemy_rating)
{
// returns the chance to win against a team with the given rating, used in the rating adjustment calculation
// ELO system
if (sWorld.getConfig(CONFIG_UINT32_ARENA_SEASON_ID) >= 6)
if (enemy_rating < 1000)
{
enemy_rating = 1000;
}
return 1.0f / (1.0f + exp(log(10.0f) * (float)((float)enemy_rating - (float)own_rating) / 400.0f));
}
void ArenaTeam::FinishGame(int32 mod)
{
if (int32(m_stats.rating) + mod < 0)
{
m_stats.rating = 0;
}
else
{
m_stats.rating += mod;
}
m_stats.games_week += 1;
m_stats.games_season += 1;
// update team's rank
m_stats.rank = 1;
ObjectMgr::ArenaTeamMap::const_iterator i = sObjectMgr.GetArenaTeamMapBegin();
for (; i != sObjectMgr.GetArenaTeamMapEnd(); ++i)
{
if (i->second->GetType() == this->m_Type && i->second->GetStats().rating > m_stats.rating)
{
++m_stats.rank;
}
}
}
int32 ArenaTeam::WonAgainst(uint32 againstRating)
{
// called when the team has won
// 'chance' calculation - to beat the opponent
float chance = GetChanceAgainst(m_stats.rating, againstRating);
float K = (m_stats.rating < 1000) ? 48.0f : 32.0f;
// calculate the rating modification (ELO system with k=32 or k=48 if rating<1000)
int32 mod = (int32)floor(K * (1.0f - chance));
// modify the team stats accordingly
FinishGame(mod);
m_stats.wins_week += 1;
m_stats.wins_season += 1;
// return the rating change, used to display it on the results screen
return mod;
}
int32 ArenaTeam::LostAgainst(uint32 againstRating)
{
// called when the team has lost
//'chance' calculation - to loose to the opponent
float chance = GetChanceAgainst(m_stats.rating, againstRating);
float K = (m_stats.rating < 1000) ? 48.0f : 32.0f;
// calculate the rating modification (ELO system with k=32 or k=48 if rating<1000)
int32 mod = (int32)ceil(K * (0.0f - chance));
// modify the team stats accordingly
FinishGame(mod);
// return the rating change, used to display it on the results screen
return mod;
}
void ArenaTeam::MemberLost(Player* plr, uint32 againstRating)
{
// called for each participant of a match after losing
for (MemberList::iterator itr = m_members.begin(); itr != m_members.end(); ++itr)
{
if (itr->guid == plr->GetObjectGuid())
{
// update personal rating
float chance = GetChanceAgainst(itr->personal_rating, againstRating);
float K = (itr->personal_rating < 1000) ? 48.0f : 32.0f;
// calculate the rating modification (ELO system with k=32 or k=48 if rating<1000)
int32 mod = (int32)ceil(K * (0.0f - chance));
itr->ModifyPersonalRating(plr, mod, GetSlot());
// update personal played stats
itr->games_week += 1;
itr->games_season += 1;
// update the unit fields
plr->SetArenaTeamInfoField(GetSlot(), ARENA_TEAM_GAMES_WEEK, itr->games_week);
plr->SetArenaTeamInfoField(GetSlot(), ARENA_TEAM_GAMES_SEASON, itr->games_season);
return;
}
}
}
void ArenaTeam::OfflineMemberLost(ObjectGuid guid, uint32 againstRating)
{
// called for offline player after ending rated arena match!
for (MemberList::iterator itr = m_members.begin(); itr != m_members.end(); ++itr)
{
if (itr->guid == guid)
{
// update personal rating
float chance = GetChanceAgainst(itr->personal_rating, againstRating);
float K = (itr->personal_rating < 1000) ? 48.0f : 32.0f;
// calculate the rating modification (ELO system with k=32 or k=48 if rating<1000)
int32 mod = (int32)ceil(K * (0.0f - chance));
if (int32(itr->personal_rating) + mod < 0)
{
itr->personal_rating = 0;
}
else
{
itr->personal_rating += mod;
}
// update personal played stats
itr->games_week += 1;
itr->games_season += 1;
return;
}
}
}
void ArenaTeam::MemberWon(Player* plr, uint32 againstRating)
{
// called for each participant after winning a match
for (MemberList::iterator itr = m_members.begin(); itr != m_members.end(); ++itr)
{
if (itr->guid == plr->GetObjectGuid())
{
// update personal rating
float chance = GetChanceAgainst(itr->personal_rating, againstRating);
float K = (itr->personal_rating < 1000) ? 48.0f : 32.0f;
// calculate the rating modification (ELO system with k=32 or k=48 if rating<1000)
int32 mod = (int32)floor(K * (1.0f - chance));
itr->ModifyPersonalRating(plr, mod, GetSlot());
// update personal stats
itr->games_week += 1;
itr->games_season += 1;
itr->wins_season += 1;
itr->wins_week += 1;
// update unit fields
plr->SetArenaTeamInfoField(GetSlot(), ARENA_TEAM_GAMES_WEEK, itr->games_week);
plr->SetArenaTeamInfoField(GetSlot(), ARENA_TEAM_GAMES_SEASON, itr->games_season);
return;
}
}
}
void ArenaTeam::UpdateArenaPointsHelper(std::map<uint32, uint32>& PlayerPoints)
{
// called after a match has ended and the stats are already modified
// helper function for arena point distribution (this way, when distributing, no actual calculation is required, just a few comparisons)
// 10 played games per week is a minimum
if (m_stats.games_week < 10)
{
return;
}
// to get points, a player has to participate in at least 30% of the matches
uint32 min_plays = (uint32) ceil(m_stats.games_week * 0.3);
for (MemberList::const_iterator itr = m_members.begin(); itr != m_members.end(); ++itr)
{
// the player participated in enough games, update his points
uint32 points_to_add = 0;
if (itr->games_week >= min_plays)
{
points_to_add = GetPoints(itr->personal_rating);
}
// OBSOLETE : CharacterDatabase.PExecute("UPDATE arena_team_member SET points_to_add = '%u' WHERE arenateamid = '%u' AND guid = '%u'", points_to_add, m_TeamId, itr->guid);
std::map<uint32, uint32>::iterator plr_itr = PlayerPoints.find(itr->guid.GetCounter());
if (plr_itr != PlayerPoints.end())
{
// check if there is already more points
if (plr_itr->second < points_to_add)
{
PlayerPoints[itr->guid.GetCounter()] = points_to_add;
}
}
else
{
PlayerPoints[itr->guid.GetCounter()] = points_to_add;
}
}
}
void ArenaTeam::SaveToDB()
{
// save team and member stats to db
// called after a match has ended, or when calculating arena_points
CharacterDatabase.BeginTransaction();
CharacterDatabase.PExecute("UPDATE `arena_team_stats` SET `rating` = '%u',`games_week` = '%u',`games_season` = '%u',`rank` = '%u',`wins_week` = '%u',`wins_season` = '%u' WHERE `arenateamid` = '%u'", m_stats.rating, m_stats.games_week, m_stats.games_season, m_stats.rank, m_stats.wins_week, m_stats.wins_season, GetId());
for (MemberList::const_iterator itr = m_members.begin(); itr != m_members.end(); ++itr)
{
CharacterDatabase.PExecute("UPDATE `arena_team_member` SET `played_week` = '%u', `wons_week` = '%u', `played_season` = '%u', `wons_season` = '%u', `personal_rating` = '%u' WHERE `arenateamid` = '%u' AND `guid` = '%u'", itr->games_week, itr->wins_week, itr->games_season, itr->wins_season, itr->personal_rating, m_TeamId, itr->guid.GetCounter());
}
CharacterDatabase.CommitTransaction();
}
void ArenaTeam::FinishWeek()
{
m_stats.games_week = 0; // played this week
m_stats.wins_week = 0; // wins this week
for (MemberList::iterator itr = m_members.begin(); itr != m_members.end(); ++itr)
{
itr->games_week = 0;
itr->wins_week = 0;
}
}
bool ArenaTeam::IsFighting() const
{
for (MemberList::const_iterator itr = m_members.begin(); itr != m_members.end(); ++itr)
{
if (Player* p = sObjectMgr.GetPlayer(itr->guid))
{
if (p->GetMap()->IsBattleArena())
{
return true;
}
}
}
return false;
}
// add new arena event to all already connected team members
void ArenaTeam::MassInviteToEvent(WorldSession* session)
{
WorldPacket data(SMSG_CALENDAR_ARENA_TEAM);
data << uint32(m_members.size());
for (MemberList::const_iterator itr = m_members.begin(); itr != m_members.end(); ++itr)
{
uint32 level = Player::GetLevelFromDB(itr->guid);
if (itr->guid != session->GetPlayer()->GetObjectGuid())
{
data << itr->guid.WriteAsPacked();
data << uint8(level);
}
}
session->SendPacket(&data);
}
| 0 | 0.964992 | 1 | 0.964992 | game-dev | MEDIA | 0.80698 | game-dev | 0.987047 | 1 | 0.987047 |
CalamityTeam/CalamityModPublic | 2,174 | Projectiles/Ranged/PrismExplosionSmall.cs | using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
using Terraria.ModLoader;
namespace CalamityMod.Projectiles.Ranged
{
public class PrismExplosionSmall : ModProjectile, ILocalizedModType
{
public new string LocalizationCategory => "Projectiles.Ranged";
public override void SetStaticDefaults()
{
Main.projFrames[Projectile.type] = 7;
}
public override void SetDefaults()
{
Projectile.width = Projectile.height = 130;
Projectile.friendly = true;
Projectile.ignoreWater = false;
Projectile.tileCollide = false;
Projectile.DamageType = DamageClass.Ranged;
Projectile.penetrate = -1;
Projectile.timeLeft = 150;
Projectile.extraUpdates = 2;
Projectile.usesLocalNPCImmunity = true;
Projectile.localNPCHitCooldown = 11;
Projectile.scale = 0.5f;
}
public override void AI()
{
Lighting.AddLight(Projectile.Center, Color.White.ToVector3() * 1.15f);
Projectile.frameCounter++;
if (Projectile.frameCounter % 8 == 7)
Projectile.frame++;
if (Projectile.frame >= Main.projFrames[Projectile.type])
Projectile.Kill();
Projectile.scale *= 1.0115f;
Projectile.Opacity = Utils.GetLerpValue(5f, 36f, Projectile.timeLeft, true);
}
public override bool PreDraw(ref Color lightColor)
{
Texture2D texture = Terraria.GameContent.TextureAssets.Projectile[Projectile.type].Value;
Texture2D lightTexture = ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/SmallGreyscaleCircle").Value;
Rectangle frame = texture.Frame(1, Main.projFrames[Projectile.type], 0, Projectile.frame);
Vector2 drawPosition = Projectile.Center - Main.screenPosition;
Vector2 origin = frame.Size() * 0.5f;
Main.EntitySpriteDraw(texture, drawPosition, frame, Color.White, 0f, origin, 1f, SpriteEffects.None, 0);
return false;
}
}
}
| 0 | 0.664594 | 1 | 0.664594 | game-dev | MEDIA | 0.965897 | game-dev | 0.907573 | 1 | 0.907573 |
openc2e/openc2e | 1,539 | externals/SDL2/src/main/psp/SDL_psp_main.c | /*
SDL_psp_main.c, placed in the public domain by Sam Lantinga 3/13/14
*/
#include "SDL_config.h"
#ifdef __PSP__
#include "SDL_main.h"
#include <pspkernel.h>
#include <pspthreadman.h>
#ifdef main
#undef main
#endif
/* If application's main() is redefined as SDL_main, and libSDLmain is
linked, then this file will create the standard exit callback,
define the PSP_MODULE_INFO macro, and exit back to the browser when
the program is finished.
You can still override other parameters in your own code if you
desire, such as PSP_HEAP_SIZE_KB, PSP_MAIN_THREAD_ATTR,
PSP_MAIN_THREAD_STACK_SIZE, etc.
*/
PSP_MODULE_INFO("SDL App", 0, 1, 0);
PSP_MAIN_THREAD_ATTR(THREAD_ATTR_VFPU | THREAD_ATTR_USER);
int sdl_psp_exit_callback(int arg1, int arg2, void *common)
{
sceKernelExitGame();
return 0;
}
int sdl_psp_callback_thread(SceSize args, void *argp)
{
int cbid;
cbid = sceKernelCreateCallback("Exit Callback",
sdl_psp_exit_callback, NULL);
sceKernelRegisterExitCallback(cbid);
sceKernelSleepThreadCB();
return 0;
}
int sdl_psp_setup_callbacks(void)
{
int thid;
thid = sceKernelCreateThread("update_thread",
sdl_psp_callback_thread, 0x11, 0xFA0, 0, 0);
if(thid >= 0)
sceKernelStartThread(thid, 0, 0);
return thid;
}
int main(int argc, char *argv[])
{
sdl_psp_setup_callbacks();
SDL_SetMainReady();
(void)SDL_main(argc, argv);
return 0;
}
#endif /* __PSP__ */
/* vi: set ts=4 sw=4 expandtab: */
| 0 | 0.888836 | 1 | 0.888836 | game-dev | MEDIA | 0.631454 | game-dev | 0.671832 | 1 | 0.671832 |
Waterdish/Shipwright-Android | 5,210 | soh/soh/Enhancements/randomizer/3drando/text.hpp | #pragma once
#include <string>
#include <stdint.h>
#define PLURAL 0
#define SINGULAR 1
class Text {
public:
Text() = default;
Text(std::string english_, std::string french_, std::string spanish_)
: english(std::move(english_)), french(std::move(french_)), spanish(std::move(spanish_)),
german(std::move("")) {
// german defaults to english text until a translation is provided.
german = english;
}
Text(std::string english_, std::string french_, std::string spanish_, std::string german_)
: english(std::move(english_)), french(std::move(french_)), spanish(std::move(spanish_)),
german(std::move(german_)) {
}
Text(std::string english_)
: english(std::move(english_)), french(std::move("")), spanish(std::move("")), german(std::move("")) {
// default unprovided languages to english text
french = spanish = german = english;
}
const std::string& GetEnglish() const {
return english;
}
const std::string& GetFrench() const {
if (french.length() > 0) {
return french;
}
return english;
}
const std::string& GetSpanish() const {
if (spanish.length() > 0) {
return spanish;
}
return english;
}
const std::string& GetGerman() const {
if (german.length() > 0) {
return german;
}
return english;
}
const std::string& GetForLanguage(uint8_t language) const {
switch (language) {
case 0: // LANGUAGE_ENG: changed to resolve #include loops
return GetEnglish();
case 2: // LANGUAGE_FRA:
return GetFrench();
case 1: // LANGUAGE_GER:
return GetGerman();
default:
return GetEnglish();
}
}
Text operator+(const Text& right) const {
return Text{ english + right.GetEnglish(), french + right.GetFrench(), spanish + right.GetSpanish(),
german + right.GetGerman() };
}
Text operator+(const std::string& right) const {
return Text{ english + right, french + right, spanish + right, german + right };
}
bool operator==(const Text& right) const {
return english == right.english;
}
bool operator==(const std::string& right) const {
return english == right || french == right || spanish == right || german == right;
}
bool operator!=(const Text& right) const {
return !operator==(right);
}
void Replace(std::string oldStr, std::string newStr) {
for (std::string* str : { &english, &french, &spanish, &german }) {
size_t position = str->find(oldStr);
while (position != std::string::npos) {
str->replace(position, oldStr.length(), newStr);
position = str->find(oldStr);
}
}
}
void Replace(std::string oldStr, Text newText) {
size_t position = english.find(oldStr);
while (position != std::string::npos) {
english.replace(position, oldStr.length(), newText.GetEnglish());
position = english.find(oldStr);
}
position = french.find(oldStr);
while (position != std::string::npos) {
french.replace(position, oldStr.length(), newText.GetFrench());
position = french.find(oldStr);
}
position = spanish.find(oldStr);
while (position != std::string::npos) {
spanish.replace(position, oldStr.length(), newText.GetSpanish());
position = spanish.find(oldStr);
}
position = german.find(oldStr);
while (position != std::string::npos) {
german.replace(position, oldStr.length(), newText.GetGerman());
position = german.find(oldStr);
}
}
// Convert first char to upper case
Text Capitalize(void) const {
Text cap = *this + "";
for (std::string* str : { &cap.english, &cap.french, &cap.spanish, &cap.german }) {
(*str)[0] = std::toupper((*str)[0]);
}
return cap;
}
// find the appropriate bars that separate singular from plural
void SetForm(int form) {
for (std::string* str : { &english, &french, &spanish, &german }) {
size_t firstBar = str->find('|');
if (firstBar != std::string::npos) {
size_t secondBar = str->find('|', firstBar + 1);
if (secondBar != std::string::npos) {
size_t thirdBar = str->find('|', secondBar + 1);
if (thirdBar != std::string::npos) {
if (form == SINGULAR) {
str->erase(secondBar, thirdBar - secondBar);
} else {
str->erase(firstBar, secondBar - firstBar);
}
}
}
}
}
// remove the remaining bar
this->Replace("|", "");
}
std::string english = "";
std::string french = "";
std::string spanish = "";
std::string german = "";
};
| 0 | 0.70535 | 1 | 0.70535 | game-dev | MEDIA | 0.513362 | game-dev | 0.828246 | 1 | 0.828246 |
Jire/tarnish | 4,345 | game-server/src/main/java/com/osroyale/game/world/entity/combat/strategy/player/custom/TridentOfTheSwampStrategy.java | package com.osroyale.game.world.entity.combat.strategy.player.custom;
import com.osroyale.Config;
import com.osroyale.game.Animation;
import com.osroyale.game.Graphic;
import com.osroyale.game.UpdatePriority;
import com.osroyale.game.world.entity.combat.CombatType;
import com.osroyale.game.world.entity.combat.attack.FightType;
import com.osroyale.game.world.entity.combat.hit.CombatHit;
import com.osroyale.game.world.entity.combat.hit.Hit;
import com.osroyale.game.world.entity.combat.projectile.CombatProjectile;
import com.osroyale.game.world.entity.combat.strategy.basic.MagicStrategy;
import com.osroyale.game.world.entity.mob.Mob;
import com.osroyale.game.world.entity.mob.player.Player;
import com.osroyale.game.world.entity.mob.player.PlayerRight;
import com.osroyale.game.world.entity.skill.Skill;
import com.osroyale.game.world.items.Item;
import com.osroyale.game.world.items.containers.equipment.Equipment;
import com.osroyale.net.packet.out.SendMessage;
import com.osroyale.util.RandomUtils;
public class TridentOfTheSwampStrategy extends MagicStrategy<Player> {
private static final TridentOfTheSwampStrategy INSTANCE = new TridentOfTheSwampStrategy();
private static CombatProjectile PROJECTILE;
static {
try {
PROJECTILE = CombatProjectile.getDefinition("Trident of the Swamp");
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean canAttack(Player attacker, Mob defender) {
if (defender.isPlayer() && !PlayerRight.isOwner(defender.getPlayer())) {
attacker.send(new SendMessage("You can't attack players with this weapon."));
return false;
}
Item weapon = attacker.equipment.get(Equipment.WEAPON_SLOT);
if (weapon == null) {
attacker.getCombat().reset();
return false;
}
if (weapon.getId() == 12899 && attacker.tridentSwampCharges < 1) {
attacker.send(new SendMessage("Your trident is out of charges!"));
attacker.getCombat().reset();
return false;
}
return true;
}
@Override
public void start(Player attacker, Mob defender, Hit[] hits) {
PROJECTILE.getAnimation().ifPresent(animation -> attacker.animate(animation, true));
PROJECTILE.getStart().ifPresent(attacker::graphic);
int projectileDuration = PROJECTILE.sendProjectile(attacker, defender);
final Graphic endGraphic = getEndGraphic(PROJECTILE.getEnd(), missed(hits), SPLASH, projectileDuration);
if (endGraphic != null) {
defender.graphic(endGraphic);
}
if (!defender.isPlayer() || !PlayerRight.isIronman(attacker)) {
for (Hit hit : hits) {
int exp = 2 * hit.getDamage();
attacker.skills.addExperience(Skill.MAGIC, exp * Config.COMBAT_MODIFICATION);
attacker.skills.addExperience(Skill.HITPOINTS, exp / 3 * Config.COMBAT_MODIFICATION);
}
}
}
@Override
public void attack(Player attacker, Mob defender, Hit hit) {
attacker.tridentSwampCharges--;
}
@Override
public void hit(Player attacker, Mob defender, Hit hit) {
if (RandomUtils.success(0.25)) {
defender.venom();
}
}
@Override
public Animation getAttackAnimation(Player attacker, Mob defender) {
int animation = attacker.getCombat().getFightType().getAnimation();
return new Animation(animation, UpdatePriority.HIGH);
}
@Override
public int getAttackDelay(Player attacker, Mob defender, FightType fightType) {
return attacker.getCombat().getFightType().getDelay();
}
@Override
public int getAttackDistance(Player attacker, FightType fightType) {
return 10;
}
@Override
public CombatHit[] getHits(Player attacker, Mob defender) {
int max = 23;
int level = attacker.skills.getLevel(Skill.MAGIC);
if (level - 75 > 0) {
max += (level - 75) / 3;
}
return new CombatHit[] { nextMagicHit(attacker, defender, max, PROJECTILE) };
}
@Override
public CombatType getCombatType() {
return CombatType.MAGIC;
}
public static TridentOfTheSwampStrategy get() {
return INSTANCE;
}
}
| 0 | 0.871842 | 1 | 0.871842 | game-dev | MEDIA | 0.992959 | game-dev | 0.977845 | 1 | 0.977845 |
MrXiaoM/HideMyArmors | 1,186 | src/main/java/top/mrxiaom/hidemyarmors/ModifierVeryOldPacket.java | package top.mrxiaom.hidemyarmors;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.reflect.StructureModifier;
import com.comphenix.protocol.wrappers.EnumWrappers;
import org.bukkit.inventory.ItemStack;
import org.bukkit.permissions.Permissible;
public class ModifierVeryOldPacket {
public static final int SLOT_HAND = 0;
public static final int SLOT_HEAD = 1;
public static final int SLOT_CHEST = 2;
public static final int SLOT_LEGS = 3;
public static final int SLOT_FEET = 4;
public static final int SLOT_OFF_HAND = 5;
/**
* 1.8.X
*/
public static void modify(PacketContainer packet, Permissible perm, EntityPacketAdapter.TriFunction<Permissible, Integer, ItemStack, ItemStack> modifyItem) {
StructureModifier<Short> itemSlots = packet.getShorts();
StructureModifier<ItemStack> itemModifier = packet.getItemModifier();
short slot = itemSlots.readSafely(0);
ItemStack item = itemModifier.readSafely(0);
ItemStack newItem = modifyItem.apply(perm, (int) slot, item);
if (newItem != null) {
itemModifier.writeSafely(0, newItem);
}
}
}
| 0 | 0.948698 | 1 | 0.948698 | game-dev | MEDIA | 0.985952 | game-dev | 0.861564 | 1 | 0.861564 |
woshihuo12/UnityHello | 3,040 | UnityHello/Assets/BundleResources/BuildByDir/Lua/LuaScripts/core/lua_object.lua.bytes | --lua_object类 类似unity3d的GameObject类。它的核心功能是添加组件和向组件发送消息。
local components = {}
local lua_object = class("lua_object")
local function load_component(name)
if components[name] == nil then
components[name] = require("components/" .. name)
end
return components[name]
end
local function get_component_name(path)
local _, b, name = string.find(path, "[%.,%/]*(%a+_*%a+)$")
return name
end
function lua_object:initialize(name)
self.name = name or "lua_object"
self.components = {}
self.updatecomponents = {}
self.active = true
self.parent = nil
self.is_disposed = false
end
function lua_object:add_component(arg)
local name = get_component_name(arg)
if self.components[name] then
return self.components[name]
end
local cmp = load_component(arg)
assert(cmp, "component " .. name .. " does not exist!")
local loadedcmp = cmp(self)
self.components[name] = loadedcmp
loadedcmp.name = name
if loadedcmp.start then
loadedcmp:start()
end
if loadedcmp.on_update then
if not self.updatecomponents then
self.updatecomponents = {}
end
self.updatecomponents[name] = loadedcmp
end
return loadedcmp
end
function lua_object:remove_component(name)
local cmp = self.components[name]
if cmp and cmp.remove then
cmp:remove()
end
self.components[name] = nil
self.updatecomponents[name] = nil
end
function lua_object:dispose()
table.clear(self.components)
table.clear(self.updatecomponents)
self.active = false
self.is_disposed = true
end
function lua_object:register_event(event, method, ...)
if self.event_fun == nil then
self.event_fun = {}
end
local event_call = self.event_fun[event]
if event_call == nil then
event_call = {}
self.event_fun[event] = event_call
end
event_call[method] = {...}
end
function lua_object:call_event(event)
if self.event_fun == nil then
return
end
local event_call = self.event_fun[event]
if event_call and not self.is_disposed then
local t
for k, v in pairs(event_call) do
t = type(k)
if t == "string" then
local fn = self[k]
if fn then
fn(self, unpack(v))
elseif t == "function" then
k(self, unpack(v))
end
end
end
end
self.event_fun[event] = nil
end
function lua_object:send_message(method, ...)
local cmps = self.components
local fn
fn = self[method]
if type(fn) == "function" then
fn(self, ...)
end
if cmps then
for k, v in pairs(cmps) do
fn = v[method]
if type(fn) == "function" then
fn(v, ...)
end
end
end
end
function lua_object:__tostring()
return string.format("lua_object.name = %s", self.name)
end
return lua_object | 0 | 0.869892 | 1 | 0.869892 | game-dev | MEDIA | 0.889851 | game-dev | 0.925743 | 1 | 0.925743 |
sharkattack51/GarageKit_for_Unity | 41,915 | UnityProject/Assets/Demigiant/DOTween/Modules/DOTweenModuleUI.cs | // Author: Daniele Giardini - http://www.demigiant.com
// Created: 2018/07/13
#if true // MODULE_MARKER
using System;
using System.Globalization;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening.Core;
using DG.Tweening.Core.Enums;
using DG.Tweening.Plugins;
using DG.Tweening.Plugins.Options;
using Outline = UnityEngine.UI.Outline;
using Text = UnityEngine.UI.Text;
#pragma warning disable 1591
namespace DG.Tweening
{
public static class DOTweenModuleUI
{
#region Shortcuts
#region CanvasGroup
/// <summary>Tweens a CanvasGroup's alpha color to the given value.
/// Also stores the canvasGroup as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
public static TweenerCore<float, float, FloatOptions> DOFade(this CanvasGroup target, float endValue, float duration)
{
TweenerCore<float, float, FloatOptions> t = DOTween.To(() => target.alpha, x => target.alpha = x, endValue, duration);
t.SetTarget(target);
return t;
}
#endregion
#region Graphic
/// <summary>Tweens an Graphic's color to the given value.
/// Also stores the image as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
public static TweenerCore<Color, Color, ColorOptions> DOColor(this Graphic target, Color endValue, float duration)
{
TweenerCore<Color, Color, ColorOptions> t = DOTween.To(() => target.color, x => target.color = x, endValue, duration);
t.SetTarget(target);
return t;
}
/// <summary>Tweens an Graphic's alpha color to the given value.
/// Also stores the image as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
public static TweenerCore<Color, Color, ColorOptions> DOFade(this Graphic target, float endValue, float duration)
{
TweenerCore<Color, Color, ColorOptions> t = DOTween.ToAlpha(() => target.color, x => target.color = x, endValue, duration);
t.SetTarget(target);
return t;
}
#endregion
#region Image
/// <summary>Tweens an Image's color to the given value.
/// Also stores the image as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
public static TweenerCore<Color, Color, ColorOptions> DOColor(this Image target, Color endValue, float duration)
{
TweenerCore<Color, Color, ColorOptions> t = DOTween.To(() => target.color, x => target.color = x, endValue, duration);
t.SetTarget(target);
return t;
}
/// <summary>Tweens an Image's alpha color to the given value.
/// Also stores the image as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
public static TweenerCore<Color, Color, ColorOptions> DOFade(this Image target, float endValue, float duration)
{
TweenerCore<Color, Color, ColorOptions> t = DOTween.ToAlpha(() => target.color, x => target.color = x, endValue, duration);
t.SetTarget(target);
return t;
}
/// <summary>Tweens an Image's fillAmount to the given value.
/// Also stores the image as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach (0 to 1)</param><param name="duration">The duration of the tween</param>
public static TweenerCore<float, float, FloatOptions> DOFillAmount(this Image target, float endValue, float duration)
{
if (endValue > 1) endValue = 1;
else if (endValue < 0) endValue = 0;
TweenerCore<float, float, FloatOptions> t = DOTween.To(() => target.fillAmount, x => target.fillAmount = x, endValue, duration);
t.SetTarget(target);
return t;
}
/// <summary>Tweens an Image's colors using the given gradient
/// (NOTE 1: only uses the colors of the gradient, not the alphas - NOTE 2: creates a Sequence, not a Tweener).
/// Also stores the image as the tween's target so it can be used for filtered operations</summary>
/// <param name="gradient">The gradient to use</param><param name="duration">The duration of the tween</param>
public static Sequence DOGradientColor(this Image target, Gradient gradient, float duration)
{
Sequence s = DOTween.Sequence();
GradientColorKey[] colors = gradient.colorKeys;
int len = colors.Length;
for (int i = 0; i < len; ++i) {
GradientColorKey c = colors[i];
if (i == 0 && c.time <= 0) {
target.color = c.color;
continue;
}
float colorDuration = i == len - 1
? duration - s.Duration(false) // Verifies that total duration is correct
: duration * (i == 0 ? c.time : c.time - colors[i - 1].time);
s.Append(target.DOColor(c.color, colorDuration).SetEase(Ease.Linear));
}
s.SetTarget(target);
return s;
}
#endregion
#region LayoutElement
/// <summary>Tweens an LayoutElement's flexibleWidth/Height to the given value.
/// Also stores the LayoutElement as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static TweenerCore<Vector2, Vector2, VectorOptions> DOFlexibleSize(this LayoutElement target, Vector2 endValue, float duration, bool snapping = false)
{
TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => new Vector2(target.flexibleWidth, target.flexibleHeight), x => {
target.flexibleWidth = x.x;
target.flexibleHeight = x.y;
}, endValue, duration);
t.SetOptions(snapping).SetTarget(target);
return t;
}
/// <summary>Tweens an LayoutElement's minWidth/Height to the given value.
/// Also stores the LayoutElement as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static TweenerCore<Vector2, Vector2, VectorOptions> DOMinSize(this LayoutElement target, Vector2 endValue, float duration, bool snapping = false)
{
TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => new Vector2(target.minWidth, target.minHeight), x => {
target.minWidth = x.x;
target.minHeight = x.y;
}, endValue, duration);
t.SetOptions(snapping).SetTarget(target);
return t;
}
/// <summary>Tweens an LayoutElement's preferredWidth/Height to the given value.
/// Also stores the LayoutElement as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static TweenerCore<Vector2, Vector2, VectorOptions> DOPreferredSize(this LayoutElement target, Vector2 endValue, float duration, bool snapping = false)
{
TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => new Vector2(target.preferredWidth, target.preferredHeight), x => {
target.preferredWidth = x.x;
target.preferredHeight = x.y;
}, endValue, duration);
t.SetOptions(snapping).SetTarget(target);
return t;
}
#endregion
#region Outline
/// <summary>Tweens a Outline's effectColor to the given value.
/// Also stores the Outline as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
public static TweenerCore<Color, Color, ColorOptions> DOColor(this Outline target, Color endValue, float duration)
{
TweenerCore<Color, Color, ColorOptions> t = DOTween.To(() => target.effectColor, x => target.effectColor = x, endValue, duration);
t.SetTarget(target);
return t;
}
/// <summary>Tweens a Outline's effectColor alpha to the given value.
/// Also stores the Outline as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
public static TweenerCore<Color, Color, ColorOptions> DOFade(this Outline target, float endValue, float duration)
{
TweenerCore<Color, Color, ColorOptions> t = DOTween.ToAlpha(() => target.effectColor, x => target.effectColor = x, endValue, duration);
t.SetTarget(target);
return t;
}
/// <summary>Tweens a Outline's effectDistance to the given value.
/// Also stores the Outline as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
public static TweenerCore<Vector2, Vector2, VectorOptions> DOScale(this Outline target, Vector2 endValue, float duration)
{
TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.effectDistance, x => target.effectDistance = x, endValue, duration);
t.SetTarget(target);
return t;
}
#endregion
#region RectTransform
/// <summary>Tweens a RectTransform's anchoredPosition to the given value.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static TweenerCore<Vector2, Vector2, VectorOptions> DOAnchorPos(this RectTransform target, Vector2 endValue, float duration, bool snapping = false)
{
TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.anchoredPosition, x => target.anchoredPosition = x, endValue, duration);
t.SetOptions(snapping).SetTarget(target);
return t;
}
/// <summary>Tweens a RectTransform's anchoredPosition X to the given value.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static TweenerCore<Vector2, Vector2, VectorOptions> DOAnchorPosX(this RectTransform target, float endValue, float duration, bool snapping = false)
{
TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.anchoredPosition, x => target.anchoredPosition = x, new Vector2(endValue, 0), duration);
t.SetOptions(AxisConstraint.X, snapping).SetTarget(target);
return t;
}
/// <summary>Tweens a RectTransform's anchoredPosition Y to the given value.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static TweenerCore<Vector2, Vector2, VectorOptions> DOAnchorPosY(this RectTransform target, float endValue, float duration, bool snapping = false)
{
TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.anchoredPosition, x => target.anchoredPosition = x, new Vector2(0, endValue), duration);
t.SetOptions(AxisConstraint.Y, snapping).SetTarget(target);
return t;
}
/// <summary>Tweens a RectTransform's anchoredPosition3D to the given value.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static TweenerCore<Vector3, Vector3, VectorOptions> DOAnchorPos3D(this RectTransform target, Vector3 endValue, float duration, bool snapping = false)
{
TweenerCore<Vector3, Vector3, VectorOptions> t = DOTween.To(() => target.anchoredPosition3D, x => target.anchoredPosition3D = x, endValue, duration);
t.SetOptions(snapping).SetTarget(target);
return t;
}
/// <summary>Tweens a RectTransform's anchoredPosition3D X to the given value.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static TweenerCore<Vector3, Vector3, VectorOptions> DOAnchorPos3DX(this RectTransform target, float endValue, float duration, bool snapping = false)
{
TweenerCore<Vector3, Vector3, VectorOptions> t = DOTween.To(() => target.anchoredPosition3D, x => target.anchoredPosition3D = x, new Vector3(endValue, 0, 0), duration);
t.SetOptions(AxisConstraint.X, snapping).SetTarget(target);
return t;
}
/// <summary>Tweens a RectTransform's anchoredPosition3D Y to the given value.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static TweenerCore<Vector3, Vector3, VectorOptions> DOAnchorPos3DY(this RectTransform target, float endValue, float duration, bool snapping = false)
{
TweenerCore<Vector3, Vector3, VectorOptions> t = DOTween.To(() => target.anchoredPosition3D, x => target.anchoredPosition3D = x, new Vector3(0, endValue, 0), duration);
t.SetOptions(AxisConstraint.Y, snapping).SetTarget(target);
return t;
}
/// <summary>Tweens a RectTransform's anchoredPosition3D Z to the given value.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static TweenerCore<Vector3, Vector3, VectorOptions> DOAnchorPos3DZ(this RectTransform target, float endValue, float duration, bool snapping = false)
{
TweenerCore<Vector3, Vector3, VectorOptions> t = DOTween.To(() => target.anchoredPosition3D, x => target.anchoredPosition3D = x, new Vector3(0, 0, endValue), duration);
t.SetOptions(AxisConstraint.Z, snapping).SetTarget(target);
return t;
}
/// <summary>Tweens a RectTransform's anchorMax to the given value.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static TweenerCore<Vector2, Vector2, VectorOptions> DOAnchorMax(this RectTransform target, Vector2 endValue, float duration, bool snapping = false)
{
TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.anchorMax, x => target.anchorMax = x, endValue, duration);
t.SetOptions(snapping).SetTarget(target);
return t;
}
/// <summary>Tweens a RectTransform's anchorMin to the given value.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static TweenerCore<Vector2, Vector2, VectorOptions> DOAnchorMin(this RectTransform target, Vector2 endValue, float duration, bool snapping = false)
{
TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.anchorMin, x => target.anchorMin = x, endValue, duration);
t.SetOptions(snapping).SetTarget(target);
return t;
}
/// <summary>Tweens a RectTransform's pivot to the given value.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
public static TweenerCore<Vector2, Vector2, VectorOptions> DOPivot(this RectTransform target, Vector2 endValue, float duration)
{
TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.pivot, x => target.pivot = x, endValue, duration);
t.SetTarget(target);
return t;
}
/// <summary>Tweens a RectTransform's pivot X to the given value.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
public static TweenerCore<Vector2, Vector2, VectorOptions> DOPivotX(this RectTransform target, float endValue, float duration)
{
TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.pivot, x => target.pivot = x, new Vector2(endValue, 0), duration);
t.SetOptions(AxisConstraint.X).SetTarget(target);
return t;
}
/// <summary>Tweens a RectTransform's pivot Y to the given value.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
public static TweenerCore<Vector2, Vector2, VectorOptions> DOPivotY(this RectTransform target, float endValue, float duration)
{
TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.pivot, x => target.pivot = x, new Vector2(0, endValue), duration);
t.SetOptions(AxisConstraint.Y).SetTarget(target);
return t;
}
/// <summary>Tweens a RectTransform's sizeDelta to the given value.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static TweenerCore<Vector2, Vector2, VectorOptions> DOSizeDelta(this RectTransform target, Vector2 endValue, float duration, bool snapping = false)
{
TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.sizeDelta, x => target.sizeDelta = x, endValue, duration);
t.SetOptions(snapping).SetTarget(target);
return t;
}
/// <summary>Punches a RectTransform's anchoredPosition towards the given direction and then back to the starting one
/// as if it was connected to the starting position via an elastic.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="punch">The direction and strength of the punch (added to the RectTransform's current position)</param>
/// <param name="duration">The duration of the tween</param>
/// <param name="vibrato">Indicates how much will the punch vibrate</param>
/// <param name="elasticity">Represents how much (0 to 1) the vector will go beyond the starting position when bouncing backwards.
/// 1 creates a full oscillation between the punch direction and the opposite direction,
/// while 0 oscillates only between the punch and the start position</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static Tweener DOPunchAnchorPos(this RectTransform target, Vector2 punch, float duration, int vibrato = 10, float elasticity = 1, bool snapping = false)
{
return DOTween.Punch(() => target.anchoredPosition, x => target.anchoredPosition = x, punch, duration, vibrato, elasticity)
.SetTarget(target).SetOptions(snapping);
}
/// <summary>Shakes a RectTransform's anchoredPosition with the given values.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="duration">The duration of the tween</param>
/// <param name="strength">The shake strength</param>
/// <param name="vibrato">Indicates how much will the shake vibrate</param>
/// <param name="randomness">Indicates how much the shake will be random (0 to 180 - values higher than 90 kind of suck, so beware).
/// Setting it to 0 will shake along a single direction.</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
/// <param name="fadeOut">If TRUE the shake will automatically fadeOut smoothly within the tween's duration, otherwise it will not</param>
/// <param name="randomnessMode">Randomness mode</param>
public static Tweener DOShakeAnchorPos(this RectTransform target, float duration, float strength = 100, int vibrato = 10, float randomness = 90, bool snapping = false, bool fadeOut = true, ShakeRandomnessMode randomnessMode = ShakeRandomnessMode.Full)
{
return DOTween.Shake(() => target.anchoredPosition, x => target.anchoredPosition = x, duration, strength, vibrato, randomness, true, fadeOut, randomnessMode)
.SetTarget(target).SetSpecialStartupMode(SpecialStartupMode.SetShake).SetOptions(snapping);
}
/// <summary>Shakes a RectTransform's anchoredPosition with the given values.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="duration">The duration of the tween</param>
/// <param name="strength">The shake strength on each axis</param>
/// <param name="vibrato">Indicates how much will the shake vibrate</param>
/// <param name="randomness">Indicates how much the shake will be random (0 to 180 - values higher than 90 kind of suck, so beware).
/// Setting it to 0 will shake along a single direction.</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
/// <param name="fadeOut">If TRUE the shake will automatically fadeOut smoothly within the tween's duration, otherwise it will not</param>
/// <param name="randomnessMode">Randomness mode</param>
public static Tweener DOShakeAnchorPos(this RectTransform target, float duration, Vector2 strength, int vibrato = 10, float randomness = 90, bool snapping = false, bool fadeOut = true, ShakeRandomnessMode randomnessMode = ShakeRandomnessMode.Full)
{
return DOTween.Shake(() => target.anchoredPosition, x => target.anchoredPosition = x, duration, strength, vibrato, randomness, fadeOut, randomnessMode)
.SetTarget(target).SetSpecialStartupMode(SpecialStartupMode.SetShake).SetOptions(snapping);
}
#region Special
/// <summary>Tweens a RectTransform's anchoredPosition to the given value, while also applying a jump effect along the Y axis.
/// Returns a Sequence instead of a Tweener.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param>
/// <param name="jumpPower">Power of the jump (the max height of the jump is represented by this plus the final Y offset)</param>
/// <param name="numJumps">Total number of jumps</param>
/// <param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static Sequence DOJumpAnchorPos(this RectTransform target, Vector2 endValue, float jumpPower, int numJumps, float duration, bool snapping = false)
{
if (numJumps < 1) numJumps = 1;
float startPosY = 0;
float offsetY = -1;
bool offsetYSet = false;
// Separate Y Tween so we can elaborate elapsedPercentage on that insted of on the Sequence
// (in case users add a delay or other elements to the Sequence)
Sequence s = DOTween.Sequence();
Tween yTween = DOTween.To(() => target.anchoredPosition, x => target.anchoredPosition = x, new Vector2(0, jumpPower), duration / (numJumps * 2))
.SetOptions(AxisConstraint.Y, snapping).SetEase(Ease.OutQuad).SetRelative()
.SetLoops(numJumps * 2, LoopType.Yoyo)
.OnStart(()=> startPosY = target.anchoredPosition.y);
s.Append(DOTween.To(() => target.anchoredPosition, x => target.anchoredPosition = x, new Vector2(endValue.x, 0), duration)
.SetOptions(AxisConstraint.X, snapping).SetEase(Ease.Linear)
).Join(yTween)
.SetTarget(target).SetEase(DOTween.defaultEaseType);
s.OnUpdate(() => {
if (!offsetYSet) {
offsetYSet = true;
offsetY = s.isRelative ? endValue.y : endValue.y - startPosY;
}
Vector2 pos = target.anchoredPosition;
pos.y += DOVirtual.EasedValue(0, offsetY, s.ElapsedDirectionalPercentage(), Ease.OutQuad);
target.anchoredPosition = pos;
});
return s;
}
#endregion
#endregion
#region ScrollRect
/// <summary>Tweens a ScrollRect's horizontal/verticalNormalizedPosition to the given value.
/// Also stores the ScrollRect as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static Tweener DONormalizedPos(this ScrollRect target, Vector2 endValue, float duration, bool snapping = false)
{
return DOTween.To(() => new Vector2(target.horizontalNormalizedPosition, target.verticalNormalizedPosition),
x => {
target.horizontalNormalizedPosition = x.x;
target.verticalNormalizedPosition = x.y;
}, endValue, duration)
.SetOptions(snapping).SetTarget(target);
}
/// <summary>Tweens a ScrollRect's horizontalNormalizedPosition to the given value.
/// Also stores the ScrollRect as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static Tweener DOHorizontalNormalizedPos(this ScrollRect target, float endValue, float duration, bool snapping = false)
{
return DOTween.To(() => target.horizontalNormalizedPosition, x => target.horizontalNormalizedPosition = x, endValue, duration)
.SetOptions(snapping).SetTarget(target);
}
/// <summary>Tweens a ScrollRect's verticalNormalizedPosition to the given value.
/// Also stores the ScrollRect as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static Tweener DOVerticalNormalizedPos(this ScrollRect target, float endValue, float duration, bool snapping = false)
{
return DOTween.To(() => target.verticalNormalizedPosition, x => target.verticalNormalizedPosition = x, endValue, duration)
.SetOptions(snapping).SetTarget(target);
}
#endregion
#region Slider
/// <summary>Tweens a Slider's value to the given value.
/// Also stores the Slider as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static TweenerCore<float, float, FloatOptions> DOValue(this Slider target, float endValue, float duration, bool snapping = false)
{
TweenerCore<float, float, FloatOptions> t = DOTween.To(() => target.value, x => target.value = x, endValue, duration);
t.SetOptions(snapping).SetTarget(target);
return t;
}
#endregion
#region Text
/// <summary>Tweens a Text's color to the given value.
/// Also stores the Text as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
public static TweenerCore<Color, Color, ColorOptions> DOColor(this Text target, Color endValue, float duration)
{
TweenerCore<Color, Color, ColorOptions> t = DOTween.To(() => target.color, x => target.color = x, endValue, duration);
t.SetTarget(target);
return t;
}
/// <summary>
/// Tweens a Text's text from one integer to another, with options for thousands separators
/// </summary>
/// <param name="fromValue">The value to start from</param>
/// <param name="endValue">The end value to reach</param>
/// <param name="duration">The duration of the tween</param>
/// <param name="addThousandsSeparator">If TRUE (default) also adds thousands separators</param>
/// <param name="culture">The <see cref="CultureInfo"/> to use (InvariantCulture if NULL)</param>
public static TweenerCore<int, int, NoOptions> DOCounter(
this Text target, int fromValue, int endValue, float duration, bool addThousandsSeparator = true, CultureInfo culture = null
){
int v = fromValue;
CultureInfo cInfo = !addThousandsSeparator ? null : culture ?? CultureInfo.InvariantCulture;
TweenerCore<int, int, NoOptions> t = DOTween.To(() => v, x => {
v = x;
target.text = addThousandsSeparator
? v.ToString("N0", cInfo)
: v.ToString();
}, endValue, duration);
t.SetTarget(target);
return t;
}
/// <summary>Tweens a Text's alpha color to the given value.
/// Also stores the Text as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
public static TweenerCore<Color, Color, ColorOptions> DOFade(this Text target, float endValue, float duration)
{
TweenerCore<Color, Color, ColorOptions> t = DOTween.ToAlpha(() => target.color, x => target.color = x, endValue, duration);
t.SetTarget(target);
return t;
}
/// <summary>Tweens a Text's text to the given value.
/// Also stores the Text as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end string to tween to</param><param name="duration">The duration of the tween</param>
/// <param name="richTextEnabled">If TRUE (default), rich text will be interpreted correctly while animated,
/// otherwise all tags will be considered as normal text</param>
/// <param name="scrambleMode">The type of scramble mode to use, if any</param>
/// <param name="scrambleChars">A string containing the characters to use for scrambling.
/// Use as many characters as possible (minimum 10) because DOTween uses a fast scramble mode which gives better results with more characters.
/// Leave it to NULL (default) to use default ones</param>
public static TweenerCore<string, string, StringOptions> DOText(this Text target, string endValue, float duration, bool richTextEnabled = true, ScrambleMode scrambleMode = ScrambleMode.None, string scrambleChars = null)
{
if (endValue == null) {
if (Debugger.logPriority > 0) Debugger.LogWarning("You can't pass a NULL string to DOText: an empty string will be used instead to avoid errors");
endValue = "";
}
TweenerCore<string, string, StringOptions> t = DOTween.To(() => target.text, x => target.text = x, endValue, duration);
t.SetOptions(richTextEnabled, scrambleMode, scrambleChars)
.SetTarget(target);
return t;
}
#endregion
#region Blendables
#region Graphic
/// <summary>Tweens a Graphic's color to the given value,
/// in a way that allows other DOBlendableColor tweens to work together on the same target,
/// instead than fight each other as multiple DOColor would do.
/// Also stores the Graphic as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The value to tween to</param><param name="duration">The duration of the tween</param>
public static Tweener DOBlendableColor(this Graphic target, Color endValue, float duration)
{
endValue = endValue - target.color;
Color to = new Color(0, 0, 0, 0);
return DOTween.To(() => to, x => {
Color diff = x - to;
to = x;
target.color += diff;
}, endValue, duration)
.Blendable().SetTarget(target);
}
#endregion
#region Image
/// <summary>Tweens a Image's color to the given value,
/// in a way that allows other DOBlendableColor tweens to work together on the same target,
/// instead than fight each other as multiple DOColor would do.
/// Also stores the Image as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The value to tween to</param><param name="duration">The duration of the tween</param>
public static Tweener DOBlendableColor(this Image target, Color endValue, float duration)
{
endValue = endValue - target.color;
Color to = new Color(0, 0, 0, 0);
return DOTween.To(() => to, x => {
Color diff = x - to;
to = x;
target.color += diff;
}, endValue, duration)
.Blendable().SetTarget(target);
}
#endregion
#region Text
/// <summary>Tweens a Text's color BY the given value,
/// in a way that allows other DOBlendableColor tweens to work together on the same target,
/// instead than fight each other as multiple DOColor would do.
/// Also stores the Text as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The value to tween to</param><param name="duration">The duration of the tween</param>
public static Tweener DOBlendableColor(this Text target, Color endValue, float duration)
{
endValue = endValue - target.color;
Color to = new Color(0, 0, 0, 0);
return DOTween.To(() => to, x => {
Color diff = x - to;
to = x;
target.color += diff;
}, endValue, duration)
.Blendable().SetTarget(target);
}
#endregion
#endregion
#region Shapes
/// <summary>Tweens a RectTransform's anchoredPosition so that it draws a circle around the given center.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations.<para/>
/// IMPORTANT: SetFrom(value) requires a <see cref="Vector2"/> instead of a float, where the X property represents the "from degrees value"</summary>
/// <param name="center">Circle-center/pivot around which to rotate (in UI anchoredPosition coordinates)</param>
/// <param name="endValueDegrees">The end value degrees to reach (to rotate counter-clockwise pass a negative value)</param>
/// <param name="duration">The duration of the tween</param>
/// <param name="relativeCenter">If TRUE the <see cref="center"/> coordinates will be considered as relative to the target's current anchoredPosition</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static TweenerCore<Vector2, Vector2, CircleOptions> DOShapeCircle(
this RectTransform target, Vector2 center, float endValueDegrees, float duration, bool relativeCenter = false, bool snapping = false
)
{
TweenerCore<Vector2, Vector2, CircleOptions> t = DOTween.To(
CirclePlugin.Get(), () => target.anchoredPosition, x => target.anchoredPosition = x, center, duration
);
t.SetOptions(endValueDegrees, relativeCenter, snapping).SetTarget(target);
return t;
}
#endregion
#endregion
// █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████
// ███ INTERNAL CLASSES ████████████████████████████████████████████████████████████████████████████████████████████████
// █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████
public static class Utils
{
/// <summary>
/// Converts the anchoredPosition of the first RectTransform to the second RectTransform,
/// taking into consideration offset, anchors and pivot, and returns the new anchoredPosition
/// </summary>
public static Vector2 SwitchToRectTransform(RectTransform from, RectTransform to)
{
Vector2 localPoint;
Vector2 fromPivotDerivedOffset = new Vector2(from.rect.width * 0.5f + from.rect.xMin, from.rect.height * 0.5f + from.rect.yMin);
Vector2 screenP = RectTransformUtility.WorldToScreenPoint(null, from.position);
screenP += fromPivotDerivedOffset;
RectTransformUtility.ScreenPointToLocalPointInRectangle(to, screenP, null, out localPoint);
Vector2 pivotDerivedOffset = new Vector2(to.rect.width * 0.5f + to.rect.xMin, to.rect.height * 0.5f + to.rect.yMin);
return to.anchoredPosition + localPoint - pivotDerivedOffset;
}
}
}
}
#endif
| 0 | 0.929233 | 1 | 0.929233 | game-dev | MEDIA | 0.406734 | game-dev | 0.96637 | 1 | 0.96637 |
ProjectIgnis/CardScripts | 1,183 | official/c6343408.lua | --奇跡の発掘
--Miracle Dig
local s,id=GetID()
function s.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_TOGRAVE)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCondition(s.condition)
e1:SetTarget(s.target)
e1:SetOperation(s.activate)
c:RegisterEffect(e1)
end
function s.filter(c)
return c:IsFaceup() and c:IsMonster()
end
function s.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsExistingMatchingCard(s.filter,tp,LOCATION_REMOVED,0,5,nil)
end
function s.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_REMOVED) and chkc:IsControler(tp) and s.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(s.filter,tp,LOCATION_REMOVED,0,3,nil) end
Duel.Hint(HINT_SELECTMSG,tp,aux.Stringid(id,0))
local g=Duel.SelectTarget(tp,s.filter,tp,LOCATION_REMOVED,0,3,3,nil)
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,g,3,0,0)
end
function s.activate(e,tp,eg,ep,ev,re,r,rp)
local tg=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS)
local sg=tg:Filter(Card.IsRelateToEffect,nil,e)
if #sg>0 then
Duel.SendtoGrave(sg,REASON_EFFECT|REASON_RETURN)
end
end | 0 | 0.920926 | 1 | 0.920926 | game-dev | MEDIA | 0.974281 | game-dev | 0.962483 | 1 | 0.962483 |
luanti-org/luanti | 1,055 | src/script/cpp_api/s_modchannels.cpp | // Luanti
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (C) 2017 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
#include "s_modchannels.h"
#include "s_internal.h"
#include "modchannels.h"
void ScriptApiModChannels::on_modchannel_message(const std::string &channel,
const std::string &sender, const std::string &message)
{
SCRIPTAPI_PRECHECKHEADER
// Get core.registered_on_generateds
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_modchannel_message");
// Call callbacks
lua_pushstring(L, channel.c_str());
lua_pushstring(L, sender.c_str());
lua_pushstring(L, message.c_str());
runCallbacks(3, RUN_CALLBACKS_MODE_AND);
}
void ScriptApiModChannels::on_modchannel_signal(
const std::string &channel, ModChannelSignal signal)
{
SCRIPTAPI_PRECHECKHEADER
// Get core.registered_on_generateds
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_modchannel_signal");
// Call callbacks
lua_pushstring(L, channel.c_str());
lua_pushinteger(L, (int)signal);
runCallbacks(2, RUN_CALLBACKS_MODE_AND);
}
| 0 | 0.705385 | 1 | 0.705385 | game-dev | MEDIA | 0.243324 | game-dev | 0.661098 | 1 | 0.661098 |
GregTechCEu/GregTech | 1,828 | src/main/java/gregtech/api/recipes/properties/impl/ResearchProperty.java | package gregtech.api.recipes.properties.impl;
import gregtech.api.GregTechAPI;
import gregtech.api.recipes.properties.RecipeProperty;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.I18n;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagList;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.jetbrains.annotations.NotNull;
public final class ResearchProperty extends RecipeProperty<ResearchPropertyData> {
public static final String KEY = "research";
private static ResearchProperty INSTANCE;
private ResearchProperty() {
super(KEY, ResearchPropertyData.class);
}
@NotNull
public static ResearchProperty getInstance() {
if (INSTANCE == null) {
INSTANCE = new ResearchProperty();
GregTechAPI.RECIPE_PROPERTIES.register(KEY, INSTANCE);
}
return INSTANCE;
}
@Override
public @NotNull NBTBase serialize(@NotNull Object value) {
NBTTagList list = new NBTTagList();
for (var entry : castValue(value)) {
list.appendTag(entry.serializeNBT());
}
return list;
}
@Override
public @NotNull Object deserialize(@NotNull NBTBase nbt) {
NBTTagList list = (NBTTagList) nbt;
ResearchPropertyData data = new ResearchPropertyData();
for (int i = 0; i < list.tagCount(); i++) {
data.add(ResearchPropertyData.ResearchEntry.deserializeFromNBT(list.getCompoundTagAt(i)));
}
return data;
}
@Override
@SideOnly(Side.CLIENT)
public void drawInfo(@NotNull Minecraft minecraft, int x, int y, int color, Object value) {
minecraft.fontRenderer.drawString(I18n.format("gregtech.recipe.research"), x, y, color);
}
}
| 0 | 0.565692 | 1 | 0.565692 | game-dev | MEDIA | 0.98757 | game-dev | 0.615403 | 1 | 0.615403 |
endlesstravel/Love2dCS | 3,969 | csharp_test/T09_Tumbler.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Love;
using static Love.Misc.MeshUtils;
namespace LovePhysicsTestBed
{
class T09_Tumbler: Test
{
const float scale = 1;
int m_count = 0;
float genDT = 0 ;
public override void ResetTranslation()
{
VScale = 20f / scale;
}
List<KeyValuePair<Body, Mesh>> listToDraw = new List<KeyValuePair<Body, Mesh>>();
public override void Update(float dt)
{
{
base.Update(dt);
if (m_count < 200)
{
genDT += dt;
if (genDT >= 0.02)
{
genDT = 0;
var b = Physics.NewBody(m_world, 0.0f * scale, 10.0f * scale, BodyType.Dynamic);
var r = NewRectShape(b, 0, 0, 0.125f * 2 * scale, 0.125f * 2 * scale);
Physics.NewFixture(b, r, 1.0f * scale);
}
m_count++;
}
}
}
public override void DrawWorld()
{
listToDraw.ForEach((Action<KeyValuePair<Body, Mesh>>)((KeyValuePair<Body, Mesh> item) =>
{
var b = item.Key;
var m = item.Value;
var p = b.GetPosition();
Graphics.SetColor(T01_Tiles.ColorByBody(b));
Graphics.Draw(m, (float)p.X, p.Y, b.GetAngle());
}));
}
PolygonShape NewRectShape(Body body, float x, float y, float w, float h)
{
var rr= Physics.NewRectangleShape(x, y, w, h, 0);
var pp = rr.GetPoints();
var rawData = new Vertex[]{
new Vertex(pp[0].X, pp[0].Y),
new Vertex(pp[1].X, pp[1].Y),
new Vertex(pp[2].X, pp[2].Y),
new Vertex(pp[3].X, pp[3].Y),
};
var sinfo = Love.Misc.MeshUtils.StandardVertexDescribe;
listToDraw.Add(new KeyValuePair<Body, Mesh>(body, Graphics.NewMesh(
sinfo,
sinfo.TransToByte(rawData),
MeshDrawMode.Fan, SpriteBatchUsage.Static)));
return rr;
}
public override void Load()
{
genDT = 0;
Body ground = Physics.NewBody(m_world);
{
Body body = Physics.NewBody(m_world, 0.0f * scale, 10.0f * scale, BodyType.Dynamic);
body.SetSleepingAllowed(false);
Physics.NewFixture(body,
NewRectShape(body, 10.0f * scale, 0.0f * scale, 0.5f * 2 * scale, 10.0f * 2 * scale),
5.0f * scale);
Physics.NewFixture(body,
NewRectShape(body , - 10.0f * scale, 0.0f * scale, 0.5f * 2 * scale, 10.0f * 2 * scale),
5.0f * scale);
Physics.NewFixture(body,
NewRectShape(body, 0.0f * scale, 10.0f * scale, 10.0f * 2 * scale, 0.5f * 2 * scale),
5.0f * scale);
Physics.NewFixture(body,
NewRectShape(body, 0.0f * scale, -10.0f * scale, 10.0f * 2 * scale, 0.5f * 2 * scale),
5.0f * scale);
//RevoluteJoint jd = Physics.NewRevoluteJoint(ground, body,
// new Vector2(0.0f, 10.0f) * scale,
// new Vector2(0.0f, 0.0f) * scale
// );
RevoluteJoint jd = Physics.NewRevoluteJoint(ground, body,
new Vector2(0.0f, 10.0f) * scale,
new Vector2(0.0f, 10.0f) * scale
);
jd.SetMotorSpeed(-0.05f * Mathf.PI);
jd.SetMaxMotorTorque(1e8f * scale);
jd.SetMotorEnabled(true);
}
m_count = 0;
}
}
}
| 0 | 0.817935 | 1 | 0.817935 | game-dev | MEDIA | 0.89134 | game-dev | 0.857618 | 1 | 0.857618 |
ddiakopoulos/sandbox | 11,883 | vr-environment/third_party/bullet3/src/BulletCollision/CollisionDispatch/btConvexConcaveCollisionAlgorithm.cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
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 "btConvexConcaveCollisionAlgorithm.h"
#include "LinearMath/btQuickprof.h"
#include "BulletCollision/CollisionDispatch/btCollisionObject.h"
#include "BulletCollision/CollisionShapes/btMultiSphereShape.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h"
#include "BulletCollision/CollisionShapes/btConcaveShape.h"
#include "BulletCollision/CollisionDispatch/btManifoldResult.h"
#include "BulletCollision/NarrowPhaseCollision/btRaycastCallback.h"
#include "BulletCollision/CollisionShapes/btTriangleShape.h"
#include "BulletCollision/CollisionShapes/btSphereShape.h"
#include "LinearMath/btIDebugDraw.h"
#include "BulletCollision/NarrowPhaseCollision/btSubSimplexConvexCast.h"
#include "BulletCollision/CollisionDispatch/btCollisionObjectWrapper.h"
btConvexConcaveCollisionAlgorithm::btConvexConcaveCollisionAlgorithm( const btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,bool isSwapped)
: btActivatingCollisionAlgorithm(ci,body0Wrap,body1Wrap),
m_isSwapped(isSwapped),
m_btConvexTriangleCallback(ci.m_dispatcher1,body0Wrap,body1Wrap,isSwapped)
{
}
btConvexConcaveCollisionAlgorithm::~btConvexConcaveCollisionAlgorithm()
{
}
void btConvexConcaveCollisionAlgorithm::getAllContactManifolds(btManifoldArray& manifoldArray)
{
if (m_btConvexTriangleCallback.m_manifoldPtr)
{
manifoldArray.push_back(m_btConvexTriangleCallback.m_manifoldPtr);
}
}
btConvexTriangleCallback::btConvexTriangleCallback(btDispatcher* dispatcher,const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,bool isSwapped):
m_dispatcher(dispatcher),
m_dispatchInfoPtr(0)
{
m_convexBodyWrap = isSwapped? body1Wrap:body0Wrap;
m_triBodyWrap = isSwapped? body0Wrap:body1Wrap;
//
// create the manifold from the dispatcher 'manifold pool'
//
m_manifoldPtr = m_dispatcher->getNewManifold(m_convexBodyWrap->getCollisionObject(),m_triBodyWrap->getCollisionObject());
clearCache();
}
btConvexTriangleCallback::~btConvexTriangleCallback()
{
clearCache();
m_dispatcher->releaseManifold( m_manifoldPtr );
}
void btConvexTriangleCallback::clearCache()
{
m_dispatcher->clearManifold(m_manifoldPtr);
}
void btConvexTriangleCallback::processTriangle(btVector3* triangle,int
partId, int triangleIndex)
{
BT_PROFILE("btConvexTriangleCallback::processTriangle");
if (!TestTriangleAgainstAabb2(triangle, m_aabbMin, m_aabbMax))
{
return;
}
//just for debugging purposes
//printf("triangle %d",m_triangleCount++);
btCollisionAlgorithmConstructionInfo ci;
ci.m_dispatcher1 = m_dispatcher;
#if 0
///debug drawing of the overlapping triangles
if (m_dispatchInfoPtr && m_dispatchInfoPtr->m_debugDraw && (m_dispatchInfoPtr->m_debugDraw->getDebugMode() &btIDebugDraw::DBG_DrawWireframe ))
{
const btCollisionObject* ob = const_cast<btCollisionObject*>(m_triBodyWrap->getCollisionObject());
btVector3 color(1,1,0);
btTransform& tr = ob->getWorldTransform();
m_dispatchInfoPtr->m_debugDraw->drawLine(tr(triangle[0]),tr(triangle[1]),color);
m_dispatchInfoPtr->m_debugDraw->drawLine(tr(triangle[1]),tr(triangle[2]),color);
m_dispatchInfoPtr->m_debugDraw->drawLine(tr(triangle[2]),tr(triangle[0]),color);
}
#endif
if (m_convexBodyWrap->getCollisionShape()->isConvex())
{
btTriangleShape tm(triangle[0],triangle[1],triangle[2]);
tm.setMargin(m_collisionMarginTriangle);
btCollisionObjectWrapper triObWrap(m_triBodyWrap,&tm,m_triBodyWrap->getCollisionObject(),m_triBodyWrap->getWorldTransform(),partId,triangleIndex);//correct transform?
btCollisionAlgorithm* colAlgo = ci.m_dispatcher1->findAlgorithm(m_convexBodyWrap,&triObWrap,m_manifoldPtr);
const btCollisionObjectWrapper* tmpWrap = 0;
if (m_resultOut->getBody0Internal() == m_triBodyWrap->getCollisionObject())
{
tmpWrap = m_resultOut->getBody0Wrap();
m_resultOut->setBody0Wrap(&triObWrap);
m_resultOut->setShapeIdentifiersA(partId,triangleIndex);
}
else
{
tmpWrap = m_resultOut->getBody1Wrap();
m_resultOut->setBody1Wrap(&triObWrap);
m_resultOut->setShapeIdentifiersB(partId,triangleIndex);
}
colAlgo->processCollision(m_convexBodyWrap,&triObWrap,*m_dispatchInfoPtr,m_resultOut);
if (m_resultOut->getBody0Internal() == m_triBodyWrap->getCollisionObject())
{
m_resultOut->setBody0Wrap(tmpWrap);
} else
{
m_resultOut->setBody1Wrap(tmpWrap);
}
colAlgo->~btCollisionAlgorithm();
ci.m_dispatcher1->freeCollisionAlgorithm(colAlgo);
}
}
void btConvexTriangleCallback::setTimeStepAndCounters(btScalar collisionMarginTriangle,const btDispatcherInfo& dispatchInfo,const btCollisionObjectWrapper* convexBodyWrap, const btCollisionObjectWrapper* triBodyWrap, btManifoldResult* resultOut)
{
m_convexBodyWrap = convexBodyWrap;
m_triBodyWrap = triBodyWrap;
m_dispatchInfoPtr = &dispatchInfo;
m_collisionMarginTriangle = collisionMarginTriangle;
m_resultOut = resultOut;
//recalc aabbs
btTransform convexInTriangleSpace;
convexInTriangleSpace = m_triBodyWrap->getWorldTransform().inverse() * m_convexBodyWrap->getWorldTransform();
const btCollisionShape* convexShape = static_cast<const btCollisionShape*>(m_convexBodyWrap->getCollisionShape());
//CollisionShape* triangleShape = static_cast<btCollisionShape*>(triBody->m_collisionShape);
convexShape->getAabb(convexInTriangleSpace,m_aabbMin,m_aabbMax);
btScalar extraMargin = collisionMarginTriangle;
btVector3 extra(extraMargin,extraMargin,extraMargin);
m_aabbMax += extra;
m_aabbMin -= extra;
}
void btConvexConcaveCollisionAlgorithm::clearCache()
{
m_btConvexTriangleCallback.clearCache();
}
void btConvexConcaveCollisionAlgorithm::processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut)
{
BT_PROFILE("btConvexConcaveCollisionAlgorithm::processCollision");
const btCollisionObjectWrapper* convexBodyWrap = m_isSwapped ? body1Wrap : body0Wrap;
const btCollisionObjectWrapper* triBodyWrap = m_isSwapped ? body0Wrap : body1Wrap;
if (triBodyWrap->getCollisionShape()->isConcave())
{
const btConcaveShape* concaveShape = static_cast<const btConcaveShape*>( triBodyWrap->getCollisionShape());
if (convexBodyWrap->getCollisionShape()->isConvex())
{
btScalar collisionMarginTriangle = concaveShape->getMargin();
resultOut->setPersistentManifold(m_btConvexTriangleCallback.m_manifoldPtr);
m_btConvexTriangleCallback.setTimeStepAndCounters(collisionMarginTriangle,dispatchInfo,convexBodyWrap,triBodyWrap,resultOut);
m_btConvexTriangleCallback.m_manifoldPtr->setBodies(convexBodyWrap->getCollisionObject(),triBodyWrap->getCollisionObject());
concaveShape->processAllTriangles( &m_btConvexTriangleCallback,m_btConvexTriangleCallback.getAabbMin(),m_btConvexTriangleCallback.getAabbMax());
resultOut->refreshContactPoints();
m_btConvexTriangleCallback.clearWrapperData();
}
}
}
btScalar btConvexConcaveCollisionAlgorithm::calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut)
{
(void)resultOut;
(void)dispatchInfo;
btCollisionObject* convexbody = m_isSwapped ? body1 : body0;
btCollisionObject* triBody = m_isSwapped ? body0 : body1;
//quick approximation using raycast, todo: hook up to the continuous collision detection (one of the btConvexCast)
//only perform CCD above a certain threshold, this prevents blocking on the long run
//because object in a blocked ccd state (hitfraction<1) get their linear velocity halved each frame...
btScalar squareMot0 = (convexbody->getInterpolationWorldTransform().getOrigin() - convexbody->getWorldTransform().getOrigin()).length2();
if (squareMot0 < convexbody->getCcdSquareMotionThreshold())
{
return btScalar(1.);
}
//const btVector3& from = convexbody->m_worldTransform.getOrigin();
//btVector3 to = convexbody->m_interpolationWorldTransform.getOrigin();
//todo: only do if the motion exceeds the 'radius'
btTransform triInv = triBody->getWorldTransform().inverse();
btTransform convexFromLocal = triInv * convexbody->getWorldTransform();
btTransform convexToLocal = triInv * convexbody->getInterpolationWorldTransform();
struct LocalTriangleSphereCastCallback : public btTriangleCallback
{
btTransform m_ccdSphereFromTrans;
btTransform m_ccdSphereToTrans;
btTransform m_meshTransform;
btScalar m_ccdSphereRadius;
btScalar m_hitFraction;
LocalTriangleSphereCastCallback(const btTransform& from,const btTransform& to,btScalar ccdSphereRadius,btScalar hitFraction)
:m_ccdSphereFromTrans(from),
m_ccdSphereToTrans(to),
m_ccdSphereRadius(ccdSphereRadius),
m_hitFraction(hitFraction)
{
}
virtual void processTriangle(btVector3* triangle, int partId, int triangleIndex)
{
BT_PROFILE("processTriangle");
(void)partId;
(void)triangleIndex;
//do a swept sphere for now
btTransform ident;
ident.setIdentity();
btConvexCast::CastResult castResult;
castResult.m_fraction = m_hitFraction;
btSphereShape pointShape(m_ccdSphereRadius);
btTriangleShape triShape(triangle[0],triangle[1],triangle[2]);
btVoronoiSimplexSolver simplexSolver;
btSubsimplexConvexCast convexCaster(&pointShape,&triShape,&simplexSolver);
//GjkConvexCast convexCaster(&pointShape,convexShape,&simplexSolver);
//ContinuousConvexCollision convexCaster(&pointShape,convexShape,&simplexSolver,0);
//local space?
if (convexCaster.calcTimeOfImpact(m_ccdSphereFromTrans,m_ccdSphereToTrans,
ident,ident,castResult))
{
if (m_hitFraction > castResult.m_fraction)
m_hitFraction = castResult.m_fraction;
}
}
};
if (triBody->getCollisionShape()->isConcave())
{
btVector3 rayAabbMin = convexFromLocal.getOrigin();
rayAabbMin.setMin(convexToLocal.getOrigin());
btVector3 rayAabbMax = convexFromLocal.getOrigin();
rayAabbMax.setMax(convexToLocal.getOrigin());
btScalar ccdRadius0 = convexbody->getCcdSweptSphereRadius();
rayAabbMin -= btVector3(ccdRadius0,ccdRadius0,ccdRadius0);
rayAabbMax += btVector3(ccdRadius0,ccdRadius0,ccdRadius0);
btScalar curHitFraction = btScalar(1.); //is this available?
LocalTriangleSphereCastCallback raycastCallback(convexFromLocal,convexToLocal,
convexbody->getCcdSweptSphereRadius(),curHitFraction);
raycastCallback.m_hitFraction = convexbody->getHitFraction();
btCollisionObject* concavebody = triBody;
btConcaveShape* triangleMesh = (btConcaveShape*) concavebody->getCollisionShape();
if (triangleMesh)
{
triangleMesh->processAllTriangles(&raycastCallback,rayAabbMin,rayAabbMax);
}
if (raycastCallback.m_hitFraction < convexbody->getHitFraction())
{
convexbody->setHitFraction( raycastCallback.m_hitFraction);
return raycastCallback.m_hitFraction;
}
}
return btScalar(1.);
}
| 0 | 0.945981 | 1 | 0.945981 | game-dev | MEDIA | 0.983471 | game-dev | 0.885476 | 1 | 0.885476 |
TheEpicBlock/PolyMc | 2,727 | src/main/java/io/github/theepicblock/polymc/api/block/BlockStateMerger.java | package io.github.theepicblock.polymc.api.block;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.DoorBlock;
import net.minecraft.block.TrapdoorBlock;
import net.minecraft.block.enums.SlabType;
import net.minecraft.state.property.Properties;
import net.minecraft.state.property.Property;
import java.util.function.BiFunction;
/**
* It's recommended to read the comments inside the code of {@link io.github.theepicblock.polymc.impl.poly.block.FunctionBlockStatePoly#FunctionBlockStatePoly(Block, BiFunction, BlockStateMerger)}, which is where the merger will be used.
*/
@FunctionalInterface
public interface BlockStateMerger {
BlockStateMerger DEFAULT = new PropertyMerger<>(Properties.STAGE)
.combine(new PropertyMerger<>(Properties.DISTANCE_1_7))
.combine(new PropertyMerger<>(Properties.DISTANCE_0_7))
.combine(new PropertyMerger<>(Properties.AGE_15))
.combine(new PropertyMerger<>(Properties.POWERED, state -> state.getBlock() instanceof DoorBlock || state.getBlock() instanceof TrapdoorBlock))
.combine(new PropertyMerger<>(Properties.TRIGGERED))
.combine(new PropertyMerger<>(Properties.PERSISTENT))
.combine(new PropertyMerger<>(Properties.NOTE))
.combine(new PropertyMerger<>(Properties.INSTRUMENT))
.combine((state) -> {
if (state.contains(Properties.MOISTURE)) {
// Moisture lower than 7 are the same
if (state.get(Properties.MOISTURE) < 7) {
return state.with(Properties.MOISTURE, 0);
}
}
return state;
}).combine((state) -> {
if (state.contains(Properties.SLAB_TYPE) && state.contains(Properties.WATERLOGGED)) {
// Waterlogged double slabs do not need to exist
if (state.get(Properties.SLAB_TYPE) == SlabType.DOUBLE && state.get(Properties.WATERLOGGED)) {
return state.with(Properties.WATERLOGGED, false);
}
}
return state;
});
BlockStateMerger ALL = (a) -> {
for (var property : a.getProperties()) {
a = normalizeProperty(a, property);
}
return a;
};
BlockState normalize(BlockState b);
default BlockStateMerger combine(BlockStateMerger other) {
return (a) -> this.normalize(other.normalize(a));
}
static <T extends Comparable<T>> BlockState normalizeProperty(BlockState state, Property<T> property) {
return state.with(property, property.getValues().iterator().next());
}
}
| 0 | 0.859138 | 1 | 0.859138 | game-dev | MEDIA | 0.993643 | game-dev | 0.936731 | 1 | 0.936731 |
kunitoki/yup | 8,384 | thirdparty/rive/source/animation/animation_reset_factory.cpp | #include "rive/animation/animation_reset_factory.hpp"
#include "rive/animation/linear_animation.hpp"
#include "rive/animation/animation_state.hpp"
#include "rive/animation/keyed_object.hpp"
#include "rive/animation/keyed_property.hpp"
#include "rive/generated/core_registry.hpp"
#include <map>
#include <set>
using namespace rive;
class KeyedPropertyData
{
public:
const KeyedProperty* keyedProperty;
bool isBaseline;
KeyedPropertyData(const KeyedProperty* value, bool baselineValue) :
keyedProperty(value), isBaseline(baselineValue)
{}
};
class KeyedObjectData
{
public:
std::vector<KeyedPropertyData> keyedPropertiesData;
std::set<int> keyedPropertiesSet;
uint32_t objectId;
KeyedObjectData(const uint32_t value) { objectId = value; }
void addProperties(const KeyedObject* keyedObject, bool isBaseline)
{
size_t index = 0;
while (index < keyedObject->numKeyedProperties())
{
auto keyedProperty = keyedObject->getProperty(index);
auto pos = keyedPropertiesSet.find(keyedProperty->propertyKey());
if (pos == keyedPropertiesSet.end())
{
switch (
CoreRegistry::propertyFieldId(keyedProperty->propertyKey()))
{
case CoreDoubleType::id:
case CoreColorType::id:
keyedPropertiesSet.insert(keyedProperty->propertyKey());
keyedPropertiesData.push_back(
KeyedPropertyData(keyedProperty, isBaseline));
break;
}
}
index++;
}
}
};
class AnimationsData
{
private:
std::vector<std::unique_ptr<KeyedObjectData>> keyedObjectsData;
KeyedObjectData* getKeyedObjectData(const KeyedObject* keyedObject)
{
for (auto& keyedObjectData : keyedObjectsData)
{
if (keyedObjectData->objectId == keyedObject->objectId())
{
return keyedObjectData.get();
}
}
auto keyedObjectData =
rivestd::make_unique<KeyedObjectData>(keyedObject->objectId());
auto ref = keyedObjectData.get();
keyedObjectsData.push_back(std::move(keyedObjectData));
return ref;
}
void findKeyedObjects(const LinearAnimation* animation,
bool isFirstAnimation)
{
size_t index = 0;
while (index < animation->numKeyedObjects())
{
auto keyedObject = animation->getObject(index);
auto keyedObjectData = getKeyedObjectData(keyedObject);
keyedObjectData->addProperties(keyedObject, isFirstAnimation);
index++;
}
}
public:
AnimationsData(std::vector<const LinearAnimation*>& animations,
bool useFirstAsBaseline)
{
bool isFirstAnimation = useFirstAsBaseline;
for (auto animation : animations)
{
findKeyedObjects(animation, isFirstAnimation);
isFirstAnimation = false;
}
}
void writeObjects(AnimationReset* animationReset,
ArtboardInstance* artboard)
{
for (auto& keyedObjectData : keyedObjectsData)
{
auto object = artboard->resolve(keyedObjectData->objectId);
if (object == nullptr)
{
continue;
}
auto component = object->as<Component>();
auto propertiesData = keyedObjectData->keyedPropertiesData;
if (propertiesData.size() > 0)
{
animationReset->writeObjectId(keyedObjectData->objectId);
animationReset->writeTotalProperties(
(uint32_t)propertiesData.size());
for (auto keyedPropertyData : propertiesData)
{
auto keyedProperty = keyedPropertyData.keyedProperty;
auto propertyKey = keyedProperty->propertyKey();
switch (CoreRegistry::propertyFieldId(propertyKey))
{
case CoreDoubleType::id:
animationReset->writePropertyKey(propertyKey);
if (keyedPropertyData.isBaseline)
{
auto firstKeyframe = keyedProperty->first();
if (firstKeyframe != nullptr)
{
auto value = keyedProperty->first()
->as<KeyFrameDouble>()
->value();
animationReset->writePropertyValue(value);
}
}
else
{
animationReset->writePropertyValue(
CoreRegistry::getDouble(component,
propertyKey));
}
break;
case CoreColorType::id:
animationReset->writePropertyKey(propertyKey);
if (keyedPropertyData.isBaseline)
{
auto firstKeyframe = keyedProperty->first();
if (firstKeyframe != nullptr)
{
auto value = keyedProperty->first()
->as<KeyFrameColor>()
->value();
animationReset->writePropertyValue(
(float)value);
}
}
else
{
animationReset->writePropertyValue(
(float)CoreRegistry::getColor(component,
propertyKey));
}
break;
}
}
}
}
animationReset->complete();
}
};
std::unique_ptr<AnimationReset> AnimationResetFactory::getInstance()
{
std::unique_lock<std::mutex> lock(m_mutex);
if (m_resources.size() > 0)
{
auto instance = std::move(m_resources.back());
m_resources.pop_back();
return instance;
}
auto instance = rivestd::make_unique<AnimationReset>();
return instance;
}
void AnimationResetFactory::fromState(
StateInstance* stateInstance,
std::vector<const LinearAnimation*>& animations)
{
if (stateInstance != nullptr)
{
auto state = stateInstance->state();
if (state->is<AnimationState>() &&
state->as<AnimationState>()->animation() != nullptr)
{
animations.push_back(state->as<AnimationState>()->animation());
}
}
}
std::unique_ptr<AnimationReset> AnimationResetFactory::fromStates(
StateInstance* stateFrom,
StateInstance* currentState,
ArtboardInstance* artboard)
{
std::vector<const LinearAnimation*> animations;
fromState(stateFrom, animations);
fromState(currentState, animations);
return fromAnimations(animations, artboard, false);
}
std::unique_ptr<AnimationReset> AnimationResetFactory::fromAnimations(
std::vector<const LinearAnimation*>& animations,
ArtboardInstance* artboard,
bool useFirstAsBaseline)
{
auto animationsData = new AnimationsData(animations, useFirstAsBaseline);
auto animationReset = AnimationResetFactory::getInstance();
animationsData->writeObjects(animationReset.get(), artboard);
delete animationsData;
return animationReset;
}
std::vector<std::unique_ptr<AnimationReset>> AnimationResetFactory::m_resources;
std::mutex AnimationResetFactory::m_mutex;
void AnimationResetFactory::release(std::unique_ptr<AnimationReset> value)
{
std::unique_lock<std::mutex> lock(m_mutex);
value->clear();
m_resources.push_back(std::move(value));
}
| 0 | 0.878554 | 1 | 0.878554 | game-dev | MEDIA | 0.49866 | game-dev,desktop-app | 0.882542 | 1 | 0.882542 |
PacktPublishing/Mastering-Cpp-Game-Development | 3,996 | Chapter11/Include/bullet/Bullet3OpenCL/RigidBody/b3GpuGenericConstraint.cpp | /*
Copyright (c) 2012 Advanced Micro Devices, Inc.
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.
*/
//Originally written by Erwin Coumans
#include "b3GpuGenericConstraint.h"
#include "Bullet3Collision/NarrowPhaseCollision/shared/b3RigidBodyData.h"
#include <new>
#include "Bullet3Common/b3Transform.h"
void b3GpuGenericConstraint::getInfo1 (unsigned int* info,const b3RigidBodyData* bodies)
{
switch (m_constraintType)
{
case B3_GPU_POINT2POINT_CONSTRAINT_TYPE:
{
*info = 3;
break;
};
default:
{
b3Assert(0);
}
};
}
void getInfo2Point2Point(b3GpuGenericConstraint* constraint, b3GpuConstraintInfo2* info, const b3RigidBodyData* bodies)
{
b3Transform trA;
trA.setIdentity();
trA.setOrigin(bodies[constraint->m_rbA].m_pos);
trA.setRotation(bodies[constraint->m_rbA].m_quat);
b3Transform trB;
trB.setIdentity();
trB.setOrigin(bodies[constraint->m_rbB].m_pos);
trB.setRotation(bodies[constraint->m_rbB].m_quat);
// anchor points in global coordinates with respect to body PORs.
// set jacobian
info->m_J1linearAxis[0] = 1;
info->m_J1linearAxis[info->rowskip+1] = 1;
info->m_J1linearAxis[2*info->rowskip+2] = 1;
b3Vector3 a1 = trA.getBasis()*constraint->getPivotInA();
b3Vector3 a1a = b3QuatRotate(trA.getRotation(),constraint->getPivotInA());
{
b3Vector3* angular0 = (b3Vector3*)(info->m_J1angularAxis);
b3Vector3* angular1 = (b3Vector3*)(info->m_J1angularAxis+info->rowskip);
b3Vector3* angular2 = (b3Vector3*)(info->m_J1angularAxis+2*info->rowskip);
b3Vector3 a1neg = -a1;
a1neg.getSkewSymmetricMatrix(angular0,angular1,angular2);
}
if (info->m_J2linearAxis)
{
info->m_J2linearAxis[0] = -1;
info->m_J2linearAxis[info->rowskip+1] = -1;
info->m_J2linearAxis[2*info->rowskip+2] = -1;
}
b3Vector3 a2 = trB.getBasis()*constraint->getPivotInB();
{
// b3Vector3 a2n = -a2;
b3Vector3* angular0 = (b3Vector3*)(info->m_J2angularAxis);
b3Vector3* angular1 = (b3Vector3*)(info->m_J2angularAxis+info->rowskip);
b3Vector3* angular2 = (b3Vector3*)(info->m_J2angularAxis+2*info->rowskip);
a2.getSkewSymmetricMatrix(angular0,angular1,angular2);
}
// set right hand side
// b3Scalar currERP = (m_flags & B3_P2P_FLAGS_ERP) ? m_erp : info->erp;
b3Scalar currERP = info->erp;
b3Scalar k = info->fps * currERP;
int j;
for (j=0; j<3; j++)
{
info->m_constraintError[j*info->rowskip] = k * (a2[j] + trB.getOrigin()[j] - a1[j] - trA.getOrigin()[j]);
//printf("info->m_constraintError[%d]=%f\n",j,info->m_constraintError[j]);
}
#if 0
if(m_flags & B3_P2P_FLAGS_CFM)
{
for (j=0; j<3; j++)
{
info->cfm[j*info->rowskip] = m_cfm;
}
}
#endif
#if 0
b3Scalar impulseClamp = m_setting.m_impulseClamp;//
for (j=0; j<3; j++)
{
if (m_setting.m_impulseClamp > 0)
{
info->m_lowerLimit[j*info->rowskip] = -impulseClamp;
info->m_upperLimit[j*info->rowskip] = impulseClamp;
}
}
info->m_damping = m_setting.m_damping;
#endif
}
void b3GpuGenericConstraint::getInfo2 (b3GpuConstraintInfo2* info, const b3RigidBodyData* bodies)
{
switch (m_constraintType)
{
case B3_GPU_POINT2POINT_CONSTRAINT_TYPE:
{
getInfo2Point2Point(this,info,bodies);
break;
};
default:
{
b3Assert(0);
}
};
}
| 0 | 0.864737 | 1 | 0.864737 | game-dev | MEDIA | 0.866788 | game-dev | 0.984682 | 1 | 0.984682 |
HaroohiePals/MarioKartToolbox | 1,032 | src/HaroohiePals.Nitro.NitroSystem/G3d/Binary/Animation/G3dAnimationHeader.cs | using HaroohiePals.IO;
using System;
using System.Text;
namespace HaroohiePals.Nitro.NitroSystem.G3d.Binary;
public sealed class G3dAnimationHeader
{
public G3dAnimationHeader(EndianBinaryReaderEx er, char expectedCategory0, string expectedCategory1)
{
Category0 = (char)er.Read<byte>();
if (Category0 != expectedCategory0)
{
throw new SignatureNotCorrectException("" + Category0, "" + expectedCategory0, er.BaseStream.Position - 1);
}
Revision = er.Read<byte>();
Category1 = er.ReadString(Encoding.ASCII, 2);
if (Category1 != expectedCategory1)
{
throw new SignatureNotCorrectException(Category1, expectedCategory1, er.BaseStream.Position - 2);
}
}
public void Write(EndianBinaryWriterEx er)
{
er.Write(Category0, Encoding.ASCII);
er.Write(Revision);
er.Write(Category1, Encoding.ASCII, false);
}
public char Category0;
public byte Revision;
public string Category1;
}
| 0 | 0.868183 | 1 | 0.868183 | game-dev | MEDIA | 0.355731 | game-dev | 0.806873 | 1 | 0.806873 |
Person8880/Shine | 32,709 | lua/shine/extensions/mapvote/voting.lua | --[[
Voting logic.
]]
local Shine = Shine
local Ceil = math.ceil
local Floor = math.floor
local GetMaxPlayers = Server.GetMaxPlayers
local GetNumPlayers = Shine.GetHumanPlayerCount
local Max = math.max
local Min = math.min
local next = next
local pairs = pairs
local Random = math.random
local SharedTime = Shared.GetTime
local StringFormat = string.format
local StringStartsWith = string.StartsWith
local StringUpper = string.upper
local TableAsSet = table.AsSet
local TableConcat = table.concat
local TableQuickCopy = table.QuickCopy
local TableRemove = table.remove
local tonumber = tonumber
local Plugin = ...
local IsType = Shine.IsType
Shine.LoadPluginModule( "vote.lua", Plugin )
function Plugin:SendVoteOptions( Client, Options, Duration, NextMap, TimeLeft, ShowTime, CurrentMap )
local MessageTable = {
Options = Options,
CurrentMap = CurrentMap,
Duration = Duration,
NextMap = NextMap,
TimeLeft = TimeLeft,
ShowTime = ShowTime,
ForceMenuOpen = self.Config.ForceMenuOpenOnMapVote
}
if Client then
self:SendNetworkMessage( Client, "VoteOptions", MessageTable, true )
else
self:SendNetworkMessage( nil, "VoteOptions", MessageTable, true )
end
end
do
local StringHexToNumber = string.HexToNumber
local function ModIDToHex( ModID )
return IsType( ModID, "number" ) and StringFormat( "%x", ModID ) or ModID
end
local function FindBestMatchingModID( self, ModList )
local MapMods = Shine.Stream.Of( ModList ):Map( ModIDToHex ):Filter( function( ModID )
return self.KnownMapMods[ ModID ]
end ):AsTable()
-- If we know which mod is the map, use it.
local ModID = MapMods[ 1 ]
if not ModID then
-- Otherwise assume it's the first mod with an unknown type.
MapMods = Shine.Stream.Of( ModList ):Map( ModIDToHex ):Filter( function( ModID )
return self.KnownMapMods[ ModID ] ~= false
end ):AsTable()
ModID = MapMods[ 1 ]
end
return ModID
end
local function HasMod( ModList, ModID )
local ModIDBase10 = StringHexToNumber( ModID )
if not ModIDBase10 then return false end
for i = 1, #ModList do
local MapMod = ModList[ i ]
if
MapMod == ModIDBase10 or
( IsType( MapMod, "string" ) and StringHexToNumber( MapMod ) == ModIDBase10 )
then
return true
end
end
return false
end
local function IsModMap( MapName, Index, self )
local Options = self.MapOptions[ MapName ]
return Options and IsType( Options.mods, "table" ) and not self.KnownVanillaMaps[ MapName ]
end
local function GetModInfo( MapName, Index, self )
local Options = self.MapOptions[ MapName ]
local ModID = self.MapNameToModID[ MapName ]
if not ModID or not HasMod( Options.mods, ModID ) then
ModID = FindBestMatchingModID( self, Options.mods ) or ModID
end
if not IsType( ModID, "string" ) or not StringHexToNumber( ModID ) then
ModID = nil
end
return {
MapName = MapName,
ModID = ModID
}
end
local function HasModID( Value ) return Value.ModID ~= nil end
function Plugin:GetMapModsForMapList( MapList )
return Shine.Stream( MapList )
:Filter( IsModMap, self )
:Map( GetModInfo, self )
:Filter( HasModID )
end
function Plugin:SendMapMods( Client, MapList )
MapList = MapList or self.Vote.MapList
if not MapList then return end
self:GetMapModsForMapList( MapList ):ForEach( function( MapInfo )
local MapName = MapInfo.MapName
local ModID = MapInfo.ModID
self.Logger:Debug( "Map %s has mod ID: %s", MapName, ModID )
self:SendNetworkMessage( Client, "MapMod", {
MapName = MapName,
ModID = ModID
}, true )
end )
end
end
function Plugin:SendMapPrefixes( Client )
local Prefixes = self:GetMapModPrefixes()
for Prefix in pairs( Prefixes ) do
self:SendNetworkMessage( Client, "MapModPrefix", {
Prefix = Prefix
}, true )
end
end
function Plugin:ClientConnect( Client )
self:UpdateVoteCounters( self.StartingVote )
end
function Plugin:NetworkVoteData( Client, Duration )
-- Send any mods for maps in the current vote (so the map vote menu shows the right preview image).
self:SendMapMods( Client )
-- Send all known map prefixes (so the map vote menu can derive the actual map names to load a preview for).
self:SendMapPrefixes( Client )
-- Send them the current vote progress and options (after the above so the menu has everything it needs).
self:SendVoteOptions(
Client,
self.Vote.OptionsText,
Duration,
self.NextMap.Voting,
self:GetTimeRemaining(),
not self.VoteOnEnd,
self:GetCurrentMap()
)
-- Send the current vote counters so they're reflected in the UI.
for Map, Votes in pairs( self.Vote.VoteList ) do
self:SendMapVoteCount( Client, Map, Votes )
end
self.Vote.NotifiedClients[ Client ] = true
end
--[[
Send the map vote text and map options when a new player connects and a map vote is in progress.
]]
function Plugin:ClientConfirmConnect( Client )
if not self:VoteStarted() or ( self.Vote.NotifiedClients and self.Vote.NotifiedClients[ Client ] ) then
if self.Logger:IsDebugEnabled() then
self.Logger:Debug(
"%s does not need to be notified of an ongoing map vote.",
Shine.GetClientInfo( Client )
)
end
return
end
local Time = SharedTime()
local Duration = Floor( self.Vote.EndTime - Time )
if Duration < 5 then
if self.Logger:IsDebugEnabled() then
self.Logger:Debug(
"Skipping sending map vote to %s as the vote will end soon.",
Shine.GetClientInfo( Client )
)
end
return
end
if self.Logger:IsDebugEnabled() then
self.Logger:Debug( "Sending map vote to %s who has just connected.", Shine.GetClientInfo( Client ) )
end
self:NetworkVoteData( Client, Duration )
end
function Plugin:ClientDisconnect( Client )
self.StartingVote:ClientDisconnect( Client )
self:UpdateVoteCounters( self.StartingVote )
if self.Vote.NotifiedClients then
self.Vote.NotifiedClients[ Client ] = nil
end
end
function Plugin:SetGameState( Gamerules, State, OldState )
if State == kGameState.Started and self.Config.BlockAfterRoundTimeInMinutes > 0 then
self.VoteDisableTime = SharedTime() + self.Config.BlockAfterRoundTimeInMinutes * 60
else
self.VoteDisableTime = math.huge
end
end
function Plugin:CheckGameStartOutsideVote()
-- Do nothing normally to avoid constant overhead.
end
Plugin.CheckGameStart = Plugin.CheckGameStartOutsideVote
Plugin.UpdatePregame = Plugin.CheckGameStartOutsideVote
function Plugin:ShouldBlockGameStart()
-- Stop the game from starting during a player-initiated vote or after a vote has triggered a map change.
return self.CyclingMap or ( self:VoteStarted() and not self:IsNextMapVote() )
end
function Plugin:UpdatePregameDuringVote( Gamerules )
if self:ShouldBlockGameStart() then
if Gamerules:GetGameState() == kGameState.PreGame then
return false
end
else
self.UpdatePregame = self.CheckGameStartOutsideVote
end
end
function Plugin:CheckGameStartDuringVote( Gamerules )
if self:ShouldBlockGameStart() then
return false
else
self.CheckGameStart = self.CheckGameStartOutsideVote
end
end
--[[
Client's requesting the vote data.
]]
function Plugin:SendVoteData( Client )
if not self:VoteStarted() then return end
local Time = SharedTime()
local Duration = Floor( self.Vote.EndTime - Time )
self:NetworkVoteData( Client, Duration )
end
function Plugin:ReceiveRequestVoteOptions( Client, Message )
self:SendVoteData( Client )
end
function Plugin:OnVoteStart( ID, SourcePlugin )
if ID == "random" then
local VoteRandom = Shine.IsPlugin( SourcePlugin ) and SourcePlugin or Shine.Plugins.voterandom
if
VoteRandom and VoteRandom.GetStartFailureMessage and VoteRandom.Enabled and
( self:IsEndVote() or self.CyclingMap )
then
return false, "You cannot start a vote at the end of the map.", VoteRandom:GetStartFailureMessage()
end
return
end
if self.CyclingMap then
return false, "The map is now changing, unable to start a vote.",
"VOTE_FAIL_MAP_CHANGE", {}
end
end
-- Block these votes when the end of map vote is running.
Plugin.BlockedEndOfMapVotes = {
VoteResetGame = true,
VoteRandomizeRR = true,
VotingForceEvenTeams = true,
VoteChangeMap = true,
VoteAddCommanderBots = true
}
function Plugin:NS2StartVote( VoteName, Client, Data )
if not self:IsEndVote() and not self.CyclingMap then return end
if self.BlockedEndOfMapVotes[ VoteName ] then
return false, kVoteCannotStartReason.Waiting
end
end
function Plugin:GetVoteDelay()
return self.Config.VoteDelayInMinutes * 60
end
function Plugin:GetVoteConstraint( Category, Type, NumTotal )
local Constraint = self.Config.Constraints[ Category ][ Type ]
if StringUpper( Constraint.Type ) == self.ConstraintType.FRACTION_OF_PLAYERS then
return Ceil( Constraint.Value * NumTotal )
end
return Constraint.Value
end
function Plugin:IsEndVote()
return self.VoteOnEnd and self:VoteStarted() and self:IsNextMapVote()
end
function Plugin:IsNextMapVote()
return self.NextMap.Voting or false
end
--[[
Returns the number of votes needed to begin a map vote.
]]
function Plugin:GetVotesNeededToStart()
return self:GetVoteConstraint( "StartVote", "MinVotesRequired", self:GetPlayerCountForVote() )
end
--[[
Returns whether a map vote is in progress.
]]
function Plugin:VoteStarted()
return self:TimerExists( self.VoteTimer )
end
--[[
Returns whether a map vote can start.
]]
function Plugin:CanStartVote()
local Time = SharedTime()
if self.Vote.NextVote > Time then
local TimeTillNextVote = Ceil( self.Vote.NextVote - Time )
return false,
StringFormat( "You must wait for %s before starting a map vote.", string.TimeToString( TimeTillNextVote ) ),
"VOTE_FAIL_MUST_WAIT",
{
SecondsToWait = TimeTillNextVote
}
end
if Time > self.VoteDisableTime then
return false, "It is too far into the current round to begin a map vote.", "VOTE_FAIL_TOO_LATE", {}
end
local PlayerCount = self:GetPlayerCountForVote()
if PlayerCount < self:GetVoteConstraint( "StartVote", "MinPlayers", GetMaxPlayers() ) then
return false, "There are not enough players to start a vote.", "VOTE_FAIL_INSUFFICIENT_PLAYERS", {}
end
return true
end
function Plugin:GetVoteEnd( Category )
local PlayerCount = self:GetPlayerCountForVote()
return self:GetVoteConstraint( Category, "MinVotesToFinish", PlayerCount )
end
--[[
Adds a vote to begin a map vote.
]]
function Plugin:AddStartVote( Client )
if not Client then return false, "Console cannot vote." end
local Success, Err, Args = self:CanClientVote( Client )
if not Success then
return false, "Client is not eligible to vote.", Err, Args
end
local Allow, Error, Key, Data = Shine.Hook.Call( "OnVoteStart", "rtv", self )
if Allow == false then
return false, Error, Key, Data
end
if self:VoteStarted() then
return false, "A vote is already in progress.", "VOTE_FAIL_IN_PROGRESS", {}
end
local Success = self.StartingVote:AddVote( Client )
if not Success then
return false, "You have already voted to begin a map vote.", "VOTE_FAIL_ALREADY_VOTED", {}
end
return true
end
function Plugin:GetVoteChoices()
return Shine.Set( self.Vote.VoteList ):AsList()
end
--[[
Gets the corresponding map in the current vote matching a string.
Allows players to do !vote summit or !vote docking etc.
]]
function Plugin:GetVoteChoice( Map )
local Choices = self.Vote.VoteList
if Choices[ Map ] then return Map end
Map = Map:lower()
if #Map < 4 then return nil end --Not specific enough.
for Name, Votes in pairs( Choices ) do
if Name:lower():find( Map, 1, true ) then
return Name
end
end
return nil
end
--[[
Sends the number of votes the given map has to the given player or everyone.
]]
function Plugin:SendMapVoteCount( Client, Map, Count )
self:SendNetworkMessage( Client, "VoteProgress", { Map = Map, Votes = Count }, true )
end
--[[
Sends a client's vote choice so their menu knows which map they have selected.
]]
function Plugin:SendVoteChoice( Client, Map, IsSelected )
self:SendNetworkMessage( Client, "ChosenMap", { MapName = Map, IsSelected = IsSelected }, true )
end
local function SetVoteCount( self, MapName, Count )
self.Vote.VoteList[ MapName ] = Count
-- Update all client's vote counters.
self:SendMapVoteCount( nil, MapName, Count )
end
function Plugin:RemoveVote( Client, Map )
if not Client then return false, "Console cannot vote." end
local Choice = self:GetVoteChoice( Map )
if not Choice then
return false, StringFormat( "%s is not a valid map choice.", Map ), "VOTE_FAIL_INVALID_MAP", { MapName = Map }
end
if self.Vote.Voted:HasKeyValue( Client, Choice ) then
self.Vote.Voted:RemoveKeyValue( Client, Choice )
self.Vote.TotalVotes = self.Vote.TotalVotes - 1
SetVoteCount( self, Choice, self.Vote.VoteList[ Choice ] - 1 )
self:SendVoteChoice( Client, Choice, false )
if self.Logger:IsDebugEnabled() then
self.Logger:Debug(
"Client %s revoked their vote for %s (now at %s/%s votes).",
Shine.GetClientInfo( Client ),
Choice,
self.Vote.VoteList[ Choice ],
self.Vote.TotalVotes
)
end
return true, Choice
end
return false
end
--[[
Adds a vote for a given map in the map vote.
]]
function Plugin:AddVote( Client, Map )
if not Client then return false, "Console cannot vote." end
local Success, Err, Args = self:CanClientVote( Client )
if not Success then
return false, "Client is not eligible to vote.", Err, Args
end
if not self:VoteStarted() then return false, "no vote in progress" end
local Choice = self:GetVoteChoice( Map )
if not Choice then
return false, StringFormat( "%s is not a valid map choice.", Map ), "VOTE_FAIL_INVALID_MAP", { MapName = Map }
end
local OldVote
local IsSingleChoice = self.Config.VotingMode == Plugin.VotingMode.SINGLE_CHOICE
if IsSingleChoice then
local OldVotes = self.Vote.Voted:Get( Client )
OldVote = OldVotes and OldVotes[ 1 ]
if OldVote == Choice then
return false, StringFormat( "You have already voted for %s.", Choice ),
"VOTE_FAIL_VOTED_MAP", { MapName = Choice }
end
if OldVote then
self.Vote.Voted:RemoveKeyValue( Client, OldVote )
SetVoteCount( self, OldVote, self.Vote.VoteList[ OldVote ] - 1 )
if self.Logger:IsDebugEnabled() then
self.Logger:Debug(
"Client %s revoked their vote for %s (now at %s/%s votes).",
Shine.GetClientInfo( Client ),
OldVote,
self.Vote.VoteList[ OldVote ],
self.Vote.TotalVotes
)
end
end
else
if self.Vote.Voted:HasKeyValue( Client, Choice ) then
return false, StringFormat( "You have already voted for %s.", Choice ),
"VOTE_FAIL_VOTED_MAP", { MapName = Choice }
end
local Choices = self.Vote.Voted:Get( Client )
local MaxMapChoices = self.Config.MaxVoteChoicesPerPlayer
if Choices and #Choices >= MaxMapChoices then
return false, StringFormat( "You cannot vote for more than %d maps.", MaxMapChoices ),
"VOTE_FAIL_CHOICE_LIMIT_REACHED", { MaxMapChoices = MaxMapChoices }
end
end
SetVoteCount( self, Choice, self.Vote.VoteList[ Choice ] + 1 )
if Client ~= "Console" then
self:SendVoteChoice( Client, Choice, true )
end
if not OldVote then
self.Vote.TotalVotes = self.Vote.TotalVotes + 1
end
self.Vote.Voted:Add( Client, Choice )
if self.Logger:IsDebugEnabled() then
self.Logger:Debug(
"Client %s voted for %s (now at %s/%s votes).",
Shine.GetClientInfo( Client ),
Choice,
self.Vote.VoteList[ Choice ],
self.Vote.TotalVotes
)
end
local TotalVotes
if IsSingleChoice then
TotalVotes = self.Vote.TotalVotes
else
-- It doesn't make sense to use the total number of votes when multiple choices are allowed as it will be
-- a multiple of the player count. Instead, end early if any map receives the fraction to finish amount.
TotalVotes = self.Vote.VoteList[ Choice ]
end
local VotesToEnd = self:GetVoteEnd( self:GetVoteCategory( self:IsNextMapVote() ) )
if TotalVotes >= VotesToEnd then
self.Logger:Debug( "Ending vote early due to %s/%s votes being cast.", TotalVotes, VotesToEnd )
self:SimpleTimer( 0, function()
self:ProcessResults()
end )
self:DestroyTimer( self.VoteTimer )
end
return true, Choice, OldVote
end
function Plugin:GetVoteCategory( NextMap )
return NextMap and "NextMapVote" or "MapVote"
end
--[[
Tells the given player or everyone that the vote is over.
]]
function Plugin:EndVote( Player )
self:SendNetworkMessage( Player, "EndVote", {}, true )
end
function Plugin:ExtendMap( Time, NextMap )
local Cycle = self.MapCycle
local ExtendTime = self.Config.ExtendTimeInMinutes * 60
local CycleTime = Cycle and ( Cycle.time * 60 ) or 0
local BaseTime = CycleTime > Time and CycleTime or Time
if self.RoundLimit > 0 then
self.Round = self.Round - 1
self:NotifyTranslated( nil, "EXTENDING_ROUND" )
else
self:SendTranslatedNotify( nil, "EXTENDING_TIME", {
Duration = ExtendTime
} )
end
self.NextMap.ExtendTime = BaseTime + ExtendTime
self.NextMap.Extends = self.NextMap.Extends + 1
if self.VoteOnEnd then return end
if NextMap then
self.NextMapVoteTime = Time + ExtendTime * self.Config.NextMapVoteMapTimeFraction
else
if not self.Config.EnableNextMapVote then return end
-- Start the next timer taking the extended time as the new cycle time.
local NextVoteTime = ( BaseTime + ExtendTime ) * self.Config.NextMapVoteMapTimeFraction - Time
-- Timer would start immediately for the next map vote...
if NextVoteTime <= Time then
NextVoteTime = ExtendTime * self.Config.NextMapVoteMapTimeFraction
end
self.NextMapVoteTime = Time + NextVoteTime
end
end
function Plugin:ApplyRTVWinner( Time, Choice )
if Choice == self:GetCurrentMap() then
self.NextMap.Winner = Choice
self:ExtendMap( Time, false )
self.Vote.NextVote = Time + self:GetVoteDelay()
return
end
self:SendTranslatedNotify( nil, "MAP_CHANGING", {
Duration = self.Config.ChangeDelayInSeconds
} )
self.Vote.CanVeto = true --Allow admins to cancel the change.
self.CyclingMap = true
--Queue the change.
self:SimpleTimer( self.Config.ChangeDelayInSeconds, function()
if not self.Vote.Veto then --No one cancelled it, change map.
MapCycle_ChangeMap( Choice )
else --Someone cancelled it, set the next vote time.
self.Vote.NextVote = Time + self:GetVoteDelay()
self.Vote.Veto = false
self.Vote.CanVeto = false --Veto has no meaning anymore.
self.CyclingMap = false
end
end )
end
function Plugin:ApplyNextMapWinner( Time, Choice, MentionMap )
self.NextMap.Winner = Choice
if Choice == self:GetCurrentMap() then
self:ExtendMap( Time, true )
else
local Key
if not self.VoteOnEnd then
Key = MentionMap and "WINNER_NEXT_MAP" or "WINNER_NEXT_MAP2"
else
Key = MentionMap and "WINNER_CYCLING" or "WINNER_CYCLING2"
self.CyclingMap = true
self:SimpleTimer( 5, function()
MapCycle_ChangeMap( Choice )
end )
end
if MentionMap then
self:SendTranslatedNotify( nil, Key, {
MapName = Choice
} )
else
self:NotifyTranslated( nil, Key )
end
end
self.NextMap.Voting = false
end
function Plugin:OnNextMapVoteFail( Time )
self.NextMap.Voting = false
if self.VoteOnEnd then
local Map = self:GetNextMap()
if not Map then
self.Logger:Warn( "Unable to find valid next map to advance to! Current map will be extended." )
self:ExtendMap( Time, true )
return
end
self:SendTranslatedNotify( nil, "MAP_CYCLING", {
MapName = Map
} )
self.CyclingMap = true
self:SimpleTimer( 5, function()
MapCycle_ChangeMap( Map )
end )
end
end
local TableRandom = table.ChooseRandom
function Plugin:ProcessResults( NextMap )
self:EndVote()
self.Vote.NotifiedClients = nil
local Cycle = self.MapCycle
local TotalVotes = self.Vote.TotalVotes
local MaxVotes = 0
local Voted = self.Vote.VoteList
local Time = SharedTime()
local Category = self:GetVoteCategory( NextMap )
local EligblePlayerCount = self:GetPlayerCountForVote()
-- Not enough players voted :|
if TotalVotes < Max( self:GetVoteConstraint( Category, "MinVotesRequired", EligblePlayerCount ), 1 ) then
self:NotifyTranslated( nil, "NOT_ENOUGH_VOTES" )
if self.VoteOnEnd and NextMap then
self:OnNextMapVoteFail( Time )
return
end
self.Vote.NextVote = Time + self:GetVoteDelay()
if NextMap then
self.NextMap.Voting = false
end
return
end
local Results = {}
--Compile the list of maps with the most votes, if two have the same amount they'll both be in the list.
for Map, Votes in pairs( Voted ) do
if Votes >= MaxVotes then
MaxVotes = Votes
end
end
for Map, Votes in pairs( Voted ) do
if Votes == MaxVotes then
Results[ #Results + 1 ] = Map
end
end
local Count = #Results
--Only one map won.
if Count == 1 then
if not NextMap then
self:SendTranslatedNotify( nil, "WINNER_VOTES", {
MapName = Results[ 1 ],
Votes = MaxVotes,
TotalVotes = TotalVotes
} )
self:ApplyRTVWinner( Time, Results[ 1 ] )
return
end
self:ApplyNextMapWinner( Time, Results[ 1 ], true )
return
end
--Now we're in the case where there's more than one map that won.
--If we're set to fail on a tie, then fail.
if self.Config.TieFails then
self:NotifyTranslated( nil, "VOTES_TIED_FAILURE" )
self.Vote.NextVote = Time + self:GetVoteDelay()
if NextMap then
self:OnNextMapVoteFail( Time )
end
return
end
--We're set to choose randomly between them on tie.
if self.Config.ChooseRandomOnTie then
local Choice = TableRandom( Results )
local Tied = TableConcat( Results, ", " )
self.Vote.CanVeto = true --Allow vetos.
self:SendTranslatedNotify( nil, "VOTES_TIED", {
MapNames = Tied
} )
self:SendTranslatedNotify( nil, "CHOOSING_RANDOM_MAP", {
MapName = Choice
} )
if not NextMap then
self:ApplyRTVWinner( Time, Choice )
return
end
self:ApplyNextMapWinner( Time, Choice )
return
end
--Now we're dealing with the case where we want to revote on fail, so we need to get rid of the timer.
self:DestroyTimer( self.VoteTimer )
if self.Vote.Votes < self.Config.MaxRevotes then --We can revote, so do so.
self:NotifyTranslated( nil, "VOTES_TIED_REVOTE" )
self.Vote.Votes = self.Vote.Votes + 1
self:SimpleTimer( 0, function()
self:StartVote( NextMap )
end )
else
self:NotifyTranslated( nil, "VOTES_TIED_LIMIT" )
if NextMap then
self:OnNextMapVoteFail( Time )
else
self.Vote.NextVote = Time + self:GetVoteDelay()
end
end
end
local Stream = Shine.Stream
do
local BaseEntryCount = 10
--[[
Chooses random maps from the remaining maps pool, weighting each map according
to their chance setting.
]]
function Plugin:ChooseRandomMaps( PotentialMaps, FinalChoices, MaxOptions )
local MapBucket = {}
local MapBucketStream = Stream( MapBucket )
local Count = 0
for Map in PotentialMaps:Iterate() do
local Chance = self.MapProbabilities[ Map ] or 1
local NumEntries = Ceil( Chance * BaseEntryCount )
-- The higher the chance, the more times the map appears in the bucket.
for i = 1, NumEntries do
Count = Count + 1
MapBucket[ Count ] = Map
end
end
while FinalChoices:GetCount() < MaxOptions and #MapBucket > 0 do
local Choice = TableRandom( MapBucket )
FinalChoices:Add( Choice )
MapBucketStream:Filter( function( Value )
return Value ~= Choice
end )
end
end
end
function Plugin:GetBlacklistedLastMaps( NumAvailable, NumSelected )
local LastMaps = self:GetLastMaps()
if not LastMaps then return {} end
local ExclusionOptions = self.Config.ExcludeLastMaps
-- Start with the amount of extra options remaining vs the max.
local AmountToRemove = NumAvailable - ( self.Config.MaxOptions - NumSelected )
-- Must remove at least the minimum, regardless of whether it drops the option count.
AmountToRemove = Max( AmountToRemove, ExclusionOptions.Min )
-- If there's a maximum set, then do not remove more than that.
local MaxRemovable = tonumber( ExclusionOptions.Max ) or 0
if ExclusionOptions.Max and MaxRemovable >= 0 then
AmountToRemove = Min( AmountToRemove, MaxRemovable )
end
local Maps = {}
for i = #LastMaps, Max( #LastMaps - AmountToRemove + 1, 1 ), -1 do
Maps[ #Maps + 1 ] = LastMaps[ i ]
end
return Maps
end
local function AreMapsSimilar( MapA, MapB )
return StringStartsWith( MapA, MapB ) or StringStartsWith( MapB, MapA )
end
function Plugin:RemoveLastMaps( PotentialMaps, FinalChoices )
local MapsToRemove = self:GetBlacklistedLastMaps( PotentialMaps:GetCount(), FinalChoices:GetCount() )
local MaxOptions = self.Config.MaxOptions
if self.Config.ExcludeLastMaps.UseStrictMatching then
-- Remove precisely the previous maps, ignoring any that are similar.
for i = 1, #MapsToRemove do
PotentialMaps:Remove( MapsToRemove[ i ] )
if FinalChoices:GetCount() > MaxOptions then
FinalChoices:Remove( MapsToRemove[ i ] )
end
end
else
PotentialMaps:Filter( function( Map )
for i = 1, #MapsToRemove do
-- If the map is similarly named to a previous map, exclude it.
-- For example: ns2_veil vs. ns2_veil_five.
if AreMapsSimilar( Map, MapsToRemove[ i ] ) then
if FinalChoices:GetCount() > MaxOptions then
FinalChoices:Remove( Map )
end
return false
end
end
return true
end )
end
end
local function LogMapGroupChoices( Logger, GroupName, Maps )
Logger:Debug( "Selected %d map(s) from group '%s': %s", #Maps, GroupName, TableConcat( Maps, ", " ) )
end
function Plugin:BuildPotentialMapChoices()
local PotentialMaps = Shine.Set( self.Config.Maps )
local PlayerCount = GetNumPlayers()
if self.Config.GroupCycleMode == self.GroupCycleMode.WEIGHTED_CHOICE and self.MapGroups then
local GroupChoices = Shine.Set()
for i = 1, #self.MapGroups do
local Group = self.MapGroups[ i ]
-- If no weighting is specified, assume the group should be fully represented in every vote.
local Weighting = tonumber( Group.select ) or #Group.maps
-- Remove maps randomly from the group until the weighting is satisfied.
local Maps = TableQuickCopy( Group.maps )
while #Maps > Weighting do
local Index = Random( 1, #Maps )
TableRemove( Maps, Index )
end
self.Logger:IfDebugEnabled( LogMapGroupChoices, Group.name, Maps )
GroupChoices:AddAll( Maps )
end
if GroupChoices:GetCount() > 0 then
-- Cut down the maps to those selected from the groups.
PotentialMaps:Intersection( GroupChoices )
end
else
local MapGroup = self:GetMapGroup()
-- If we have a map group, then get rid of any maps that aren't in the group.
if MapGroup then
local GroupMaps = TableAsSet( MapGroup.maps )
PotentialMaps:Intersection( GroupMaps )
self.LastMapGroup = MapGroup
end
end
-- We then look in the nominations, and enter those into the list.
local Nominations = self.Vote.Nominated
local MaxPermittedNominations = self:GetMaxNominations()
local NumNominationsAdded = 0
for i = 1, #Nominations do
local Nominee = Nominations[ i ]
if self:IsValidMapChoice( self.MapOptions[ Nominee ] or Nominee, PlayerCount ) then
PotentialMaps:Add( Nominee )
NumNominationsAdded = NumNominationsAdded + 1
if NumNominationsAdded >= MaxPermittedNominations then
-- Stop if we hit the limit of nominations allowed.
break
end
end
end
-- Now filter out any maps that are invalid.
PotentialMaps:Filter( function( Map ) return self:IsValidMapChoice( self.MapOptions[ Map ] or Map, PlayerCount ) end )
return PotentialMaps
end
function Plugin:AddForcedMaps( PotentialMaps, FinalChoices )
if self.ForcedMapCount <= 0 then return end
for Map in pairs( self.Config.ForcedMaps ) do
if Map ~= CurMap or AllowCurMap then
FinalChoices:Add( Map )
PotentialMaps:Remove( Map )
end
end
end
function Plugin:AddNomination( Nominee, FinalChoices, MaxOptionsExceededAction, NominationsSet )
if FinalChoices:GetCount() < self.Config.MaxOptions then
-- Always add when there's still options remaining.
FinalChoices:Add( Nominee )
return true
end
if MaxOptionsExceededAction == self.MaxOptionsExceededAction.ADD_MAP then
-- Allow the number of options to exceed the maximum.
FinalChoices:Add( Nominee )
return true
end
if MaxOptionsExceededAction == self.MaxOptionsExceededAction.REPLACE_MAP then
-- Try to replace a map in the choices that was not nominated.
FinalChoices:ReplaceMatchingValue( Nominee, function( Map )
return not NominationsSet:Contains( Map )
end )
return FinalChoices:Contains( Nominee )
end
-- Skip nominations when full.
return false
end
function Plugin:AddNominations( PotentialMaps, FinalChoices, Nominations )
local MaxPermittedNominations = self:GetMaxNominations()
local MaxOptionsExceededAction = self.Config.Nominations.MaxOptionsExceededAction
local NominationsSet = Shine.Set()
for i = 1, #Nominations do
local Nominee = Nominations[ i ]
if PotentialMaps:Contains( Nominee ) and not FinalChoices:Contains( Nominee )
and self:AddNomination( Nominee, FinalChoices, MaxOptionsExceededAction, NominationsSet ) then
NominationsSet:Add( Nominee )
PotentialMaps:Remove( Nominee )
if NominationsSet:GetCount() >= MaxPermittedNominations then
break
end
end
end
end
function Plugin:AddCurrentMap( PotentialMaps, FinalChoices )
local AllowCurMap = self:CanExtend()
local CurMap = self:GetCurrentMap()
if AllowCurMap then
if PotentialMaps:Contains( CurMap ) and self.Config.AlwaysExtend then
FinalChoices:Add( CurMap )
PotentialMaps:Remove( CurMap )
end
else
-- Otherwise remove it!
PotentialMaps:Remove( CurMap )
if self.Config.ConsiderSimilarMapsAsExtension then
-- Remove any maps that are similar to the current map from the pool too.
PotentialMaps:Filter( function( Map )
return not AreMapsSimilar( Map, CurMap )
end )
end
end
end
function Plugin:BuildMapChoices()
-- First we compile the list of maps that are going to be available to vote for.
local PotentialMaps = self:BuildPotentialMapChoices()
-- Now we build our actual map choices.
local FinalChoices = Shine.Set()
-- Add forced maps, these skip validity checks.
self:AddForcedMaps( PotentialMaps, FinalChoices )
-- Add all nominations that are allowed to the vote list.
self:AddNominations( PotentialMaps, FinalChoices, self.Vote.Nominated )
-- If we have map extension enabled and forced, ensure it's in the vote list.
self:AddCurrentMap( PotentialMaps, FinalChoices )
-- Get rid of any maps we've previously played based on the exclusion config.
self:RemoveLastMaps( PotentialMaps, FinalChoices )
local MaxOptions = self.Config.MaxOptions
local RemainingSpaces = MaxOptions - FinalChoices:GetCount()
-- Finally, if we have more room, add maps from the allowed list that weren't nominated.
if RemainingSpaces > 0 then
self:ChooseRandomMaps( PotentialMaps, FinalChoices, MaxOptions )
end
return FinalChoices:AsList()
end
--[[
Sets up and begins a map vote.
]]
function Plugin:StartVote( NextMap, Force )
if self:VoteStarted() then return end
if not Force and not NextMap and not self:CanStartVote() then return end
if not Force and not NextMap and not self.Config.EnableRTV then return end
self.StartingVote:Reset()
self.Vote.TotalVotes = 0
self.Vote.Voted = Shine.UnorderedMultimap()
self.Vote.NominationTracker = {}
self.Vote.NotifiedClients = {}
local MapList = self:BuildMapChoices()
self.Vote.MapList = MapList
self.Vote.Nominated = {}
self.Vote.VoteList = {}
for i = 1, #MapList do
self.Vote.VoteList[ MapList[ i ] ] = 0
end
local OptionsText = TableConcat( MapList, ", " )
local VoteLength = self.Config.VoteLengthInMinutes * 60
local EndTime = SharedTime() + VoteLength
-- Store these values for new clients.
self.Vote.EndTime = EndTime
self.Vote.OptionsText = OptionsText
self.NextMap.Voting = NextMap
self:SimpleTimer( 0.1, function()
if not NextMap then
self:NotifyTranslated( nil, "RTV_STARTED" )
else
self:NotifyTranslated( nil, "NEXT_MAP_STARTED" )
end
end )
-- For every map in the vote list that requires a mod, tell every client the mod ID
-- so they can load a preview for it if they hover the button.
self:SendMapMods( nil )
self:SendMapPrefixes( nil )
self:SendVoteOptions(
nil,
OptionsText,
VoteLength,
NextMap,
self:GetTimeRemaining(),
not self.VoteOnEnd,
self:GetCurrentMap()
)
self:CreateTimer( self.VoteTimer, VoteLength, 1, function()
self:ProcessResults( NextMap )
end )
for Client in Shine.IterateClients() do
self.Vote.NotifiedClients[ Client ] = true
end
-- Stop the game from starting if the current vote is player-initiated.
self.CheckGameStart = self.CheckGameStartDuringVote
self.UpdatePregame = self.UpdatePregameDuringVote
-- Notify other plugins that a map vote has started to allow them to stop any game start
-- they may be controlling.
Shine.Hook.Broadcast( "OnMapVoteStarted", self, NextMap, EndTime )
end
| 0 | 0.970477 | 1 | 0.970477 | game-dev | MEDIA | 0.844078 | game-dev | 0.985246 | 1 | 0.985246 |
ProjectIgnis/CardScripts | 2,999 | official/c60242223.lua | --深淵の獣サロニール
--Bystial Saronir
--scripted by Naim
local s,id=GetID()
function s.initial_effect(c)
--Special Summon itself from the hand (Ignition)
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetCategory(CATEGORY_REMOVE+CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetRange(LOCATION_HAND)
e1:SetCountLimit(1,id)
e1:SetCondition(aux.NOT(s.spquickcon))
e1:SetTarget(s.sptg)
e1:SetOperation(s.spop)
c:RegisterEffect(e1)
--Special Summon itself from the hand (Quick if the opponent controls monsters)
local e2=e1:Clone()
e2:SetType(EFFECT_TYPE_QUICK_O)
e2:SetCode(EVENT_FREE_CHAIN)
e2:SetHintTiming(0,TIMINGS_CHECK_MONSTER_E)
e2:SetCondition(s.spquickcon)
c:RegisterEffect(e2)
--Send 1 card from the Deck to the GY
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(id,1))
e3:SetCategory(CATEGORY_TOGRAVE)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e3:SetProperty(EFFECT_FLAG_DELAY)
e3:SetCode(EVENT_TO_GRAVE)
e3:SetCountLimit(1,{id,1})
e3:SetTarget(s.tgtg)
e3:SetOperation(s.tgop)
c:RegisterEffect(e3)
end
s.listed_names={id}
s.listed_series={SET_BRANDED,SET_BYSTIAL}
function s.spfilter(c,tp)
return c:IsAttribute(ATTRIBUTE_LIGHT|ATTRIBUTE_DARK) and c:IsAbleToRemove() and aux.SpElimFilter(c,true)
and c:IsFaceup() and Duel.GetMZoneCount(tp,c)>0
end
function s.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE|LOCATION_GRAVE) and s.spfilter(chkc,tp) end
local c=e:GetHandler()
if chk==0 then return Duel.IsExistingTarget(s.spfilter,tp,LOCATION_MZONE|LOCATION_GRAVE,LOCATION_GRAVE,1,nil,tp)
and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectTarget(tp,s.spfilter,tp,LOCATION_MZONE|LOCATION_GRAVE,LOCATION_GRAVE,1,1,nil,tp)
Duel.SetOperationInfo(0,CATEGORY_REMOVE,g,1,tp,0)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,c,1,tp,LOCATION_HAND)
end
function s.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and Duel.Remove(tc,POS_FACEUP,REASON_EFFECT)>0 and tc:IsLocation(LOCATION_REMOVED) and c:IsRelateToEffect(e) then
Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)
end
end
function s.spquickcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetFieldGroupCount(tp,0,LOCATION_MZONE)>0
end
function s.tgfilter(c)
return ((c:IsSetCard(SET_BYSTIAL) and c:IsMonster() and not c:IsCode(id))
or (c:IsSetCard(SET_BRANDED) and c:IsSpellTrap())) and c:IsAbleToGrave()
end
function s.tgtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(s.tgfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,tp,LOCATION_DECK)
end
function s.tgop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,s.tgfilter,tp,LOCATION_DECK,0,1,1,nil)
if #g>0 then
Duel.SendtoGrave(g,REASON_EFFECT)
end
end | 0 | 0.949057 | 1 | 0.949057 | game-dev | MEDIA | 0.987715 | game-dev | 0.976885 | 1 | 0.976885 |
goonstation/goonstation | 8,765 | code/modules/antagonists/wraith/abilties/plaguebringer/curses.dm | ////////////////////////
// Curses
////////////////////////
ABSTRACT_TYPE(/datum/targetable/wraithAbility/curse)
/datum/targetable/wraithAbility/curse
name = "Base curse"
icon_state = "skeleton"
desc = "This should never be seen."
targeted = 1
pointCost = 30
cooldown = 45 SECONDS
cast(atom/target)
if (..())
return 1
if (ishuman(target))
if (istype(get_area(target), /area/station/chapel)) //Dont spam curses in the chapel.
boutput(holder.owner, SPAN_ALERT("The holy ground this creature is standing on repels the curse immediately."))
boutput(target, SPAN_ALERT("You feel as though some weight was added to your soul, but the feeling immediately dissipates."))
return 0
//Lets let people know they have been cursed, might not be obvious at first glance
var/mob/living/carbon/H = target
if (H.traitHolder.hasTrait("training_chaplain"))
boutput(holder.owner, SPAN_NOTICE("A strange force prevents you from cursing this being, your energy is wasted."))
return 0
var/curseCount = 0
if (H.bioHolder.HasEffect("blood_curse"))
curseCount ++
if (H.bioHolder.HasEffect("blind_curse"))
curseCount ++
if (H.bioHolder.HasEffect("weak_curse"))
curseCount ++
if (H.bioHolder.HasEffect("rot_curse"))
curseCount ++
switch(curseCount)
if (1)
boutput(H, SPAN_NOTICE("You feel strangely sick."))
if (2)
boutput(H, SPAN_ALERT("You hear whispers in your head, pushing you towards your doom."))
H.playsound_local(H.loc, "sound/voice/wraith/wraithstaminadrain.ogg", 50)
if (3)
boutput(H, SPAN_ALERT("<b>A cacophony of otherworldly voices resonates within your mind. You sense a feeling of impending doom! You should seek salvation in the chapel or the purification of holy water.</b>"))
H.playsound_local(H.loc, "sound/voice/wraith/wraithraise1.ogg", 80)
/datum/targetable/wraithAbility/curse/blood
name = "Curse of blood"
icon_state = "bloodcurse"
desc = "Curse the living with a plague of blood."
targeted = 1
pointCost = 40
cooldown = 45 SECONDS
cast(atom/target)
if (..())
return 1
if (ishuman(target))
var/mob/living/carbon/human/H = target
if(H.bioHolder.HasEffect("blood_curse"))
boutput(holder.owner, "That curse is already applied to this being...")
return 1
usr.playsound_local(usr.loc, "sound/voice/wraith/wraithspook[rand(1, 2)].ogg", 80, 0)
H.bioHolder.AddEffect("blood_curse")
boutput(holder.owner, SPAN_NOTICE("We curse this being with a blood dripping curse."))
var/datum/targetable/ability = holder.getAbility(/datum/targetable/wraithAbility/curse/rot)
ability.doCooldown()
ability = holder.getAbility(/datum/targetable/wraithAbility/curse/blindness)
ability.doCooldown()
ability = holder.getAbility(/datum/targetable/wraithAbility/curse/enfeeble)
ability.doCooldown()
ability = holder.getAbility(/datum/targetable/wraithAbility/curse/death)
ability.doCooldown()
return 0
else
return 1
/datum/targetable/wraithAbility/curse/blindness
name = "Curse of blindness"
icon_state = "blindcurse"
desc = "Curse the living with blindness."
targeted = 1
pointCost = 40
cooldown = 45 SECONDS
cast(atom/target)
if (..())
return 1
if (ishuman(target))
var/mob/living/carbon/human/H = target
if(H.bioHolder.HasEffect("blind_curse"))
boutput(holder.owner, "That curse is already applied to this being...")
return 1
usr.playsound_local(usr.loc, "sound/voice/wraith/wraithspook[rand(1, 2)].ogg", 80, 0)
H.bioHolder.AddEffect("blind_curse")
boutput(holder.owner, SPAN_NOTICE("We curse this being with a blinding curse."))
var/datum/targetable/ability = holder.getAbility(/datum/targetable/wraithAbility/curse/blood)
ability.doCooldown()
ability = holder.getAbility(/datum/targetable/wraithAbility/curse/enfeeble)
ability.doCooldown()
ability = holder.getAbility(/datum/targetable/wraithAbility/curse/rot)
ability.doCooldown()
ability = holder.getAbility(/datum/targetable/wraithAbility/curse/death)
ability.doCooldown()
return 0
else
return 1
/datum/targetable/wraithAbility/curse/enfeeble
name = "Curse of weakness"
icon_state = "weakcurse"
desc = "Curse the living with weakness and lower stamina regeneration."
targeted = 1
pointCost = 40
cooldown = 45 SECONDS
cast(atom/target)
if (..())
return 1
if (ishuman(target))
var/mob/living/carbon/human/H = target
if(H.bioHolder.HasEffect("weak_curse"))
boutput(holder.owner, "That curse is already applied to this being...")
return 1
usr.playsound_local(usr.loc, "sound/voice/wraith/wraithspook[rand(1, 2)].ogg", 80, 0)
H.bioHolder.AddEffect("weak_curse")
boutput(holder.owner, SPAN_NOTICE("We curse this being with an enfeebling curse."))
var/datum/targetable/ability = holder.getAbility(/datum/targetable/wraithAbility/curse/blood)
ability.doCooldown()
ability = holder.getAbility(/datum/targetable/wraithAbility/curse/blindness)
ability.doCooldown()
ability = holder.getAbility(/datum/targetable/wraithAbility/curse/rot)
ability.doCooldown()
ability = holder.getAbility(/datum/targetable/wraithAbility/curse/death)
ability.doCooldown()
return 0
else
return 1
/datum/targetable/wraithAbility/curse/rot
name = "Curse of rot"
icon_state = "rotcurse"
desc = "Curse the living with a netherworldly plague."
targeted = 1
pointCost = 40
cooldown = 45 SECONDS
cast(atom/target)
if (..())
return 1
if (ishuman(target))
var/mob/living/carbon/human/H= target
if(H.bioHolder.HasEffect("rot_curse"))
boutput(holder.owner, "That curse is already applied to this being...")
return 1
usr.playsound_local(usr.loc, "sound/voice/wraith/wraithspook[rand(1, 2)].ogg", 80, 0)
H.bioHolder.AddEffect("rot_curse")
boutput(holder.owner, SPAN_NOTICE("We curse this being with a decaying curse."))
var/datum/targetable/ability = holder.getAbility(/datum/targetable/wraithAbility/curse/blood)
ability.doCooldown()
ability = holder.getAbility(/datum/targetable/wraithAbility/curse/blindness)
ability.doCooldown()
ability = holder.getAbility(/datum/targetable/wraithAbility/curse/enfeeble)
ability.doCooldown()
ability = holder.getAbility(/datum/targetable/wraithAbility/curse/death)
ability.doCooldown()
return 0
else
return 1
/datum/targetable/wraithAbility/curse/death //Only castable if you already put 4 curses on someone
name = "Curse of death"
icon_state = "deathcurse"
desc = "Reap a fully cursed being's soul!"
targeted = 1
pointCost = 80
cooldown = 45 SECONDS
cast(atom/target)
if (..())
return TRUE
if (ishuman(target))
var/mob/living/carbon/human/H = target
var/mob/living/intangible/wraith/W = holder.owner
if(H?.bioHolder.HasEffect("death_curse"))
boutput(holder.owner, "That curse is already applied to this being...")
return TRUE
if (H?.bioHolder.HasEffect("rot_curse") && H?.bioHolder.HasEffect("weak_curse") && H?.bioHolder.HasEffect("blind_curse") && H?.bioHolder.HasEffect("blood_curse"))
W.playsound_local(W.loc, 'sound/voice/wraith/wraithhaunt.ogg', 40, 0)
H.bioHolder.AddEffect("death_curse")
boutput(W, SPAN_ALERT("<b>That soul will be OURS!</b>"))
do_curse(H, W)
return FALSE
else
boutput(holder.owner, "That being's soul is not weakened enough. We need to curse it some more.")
return TRUE
proc/do_curse(var/mob/living/carbon/human/H, var/mob/living/intangible/wraith/W)
var/cycles = 0
var/active = TRUE
while (active)
if (!H?.bioHolder.GetEffect("death_curse"))
boutput(W, SPAN_ALERT("Those foolish mortals stopped your deadly curse before it claimed it's victim! You'll damn them all!"))
active = FALSE
return
if (!isdead(H))
hit_twitch(H)
random_brute_damage(H, (cycles / 3))
cycles ++
if (prob(6))
H.changeStatus("stunned", 2 SECONDS)
boutput(H, SPAN_ALERT("<b>You feel netherworldly hands grasping at your soul!</b>"))
if (prob(4))
boutput(H, SPAN_ALERT("IT'S COMING FOR YOU!"))
H.remove_stamina( rand(30, 70) )
if ((cycles > 10) && prob(15))
random_brute_damage(H, 1)
playsound(H.loc, 'sound/impact_sounds/Flesh_Tear_2.ogg', 70, 1)
H.visible_message(SPAN_ALERT("[H]'s flesh tears open before your very eyes!!"))
new /obj/decal/cleanable/blood/drip(get_turf(H))
else
var/turf/T = get_turf(H)
var/datum/effects/system/bad_smoke_spread/S = new /datum/effects/system/bad_smoke_spread/(T)
if (S)
S.set_up(8, 0, T, null, "#000000")
S.start()
T.fluid_react_single("miasma", 60, airborne = 1)
var/datum/abilityHolder/wraith/AH = W.abilityHolder
H.gib()
AH.regenRate += 2.0
AH.corpsecount++
active = FALSE
sleep (1.5 SECONDS)
| 0 | 0.952068 | 1 | 0.952068 | game-dev | MEDIA | 0.973855 | game-dev | 0.933058 | 1 | 0.933058 |
mrayy/mrayGStreamerUnity | 1,338 | Unity/UnityTests/Assets/GStreamerUnity/Components/CustomVideoStreamer.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading;
public class CustomVideoStreamer : MonoBehaviour,IDependencyNode {
public CameraCapture camCap;
public string Pipeline;
public int fps=30;
public bool _created=false;
GstCustomVideoStreamer _streamer;
public void OnDependencyStart(DependencyRoot root)
{
Debug.Log ("node start");
_streamer.SetGrabber (camCap._grabber);
_streamer.SetPipelineString (Pipeline);
_streamer.SetResolution(camCap.Width,camCap.Height,fps);
}
public void OnDependencyDestroyed(DependencyRoot root)
{
Debug.Log ("node destroyed");
Destroy ();
}
void Destroy()
{
_streamer.SetGrabber (null);
_streamer.Pause ();
Thread.Sleep (100);
_streamer.Stop ();
_streamer.Close ();
return;
//_streamer.SetGrabber (null);
_streamer.Destroy ();
_streamer = null;
}
// Use this for initialization
void Start () {
Debug.Log ("start");
_streamer = new GstCustomVideoStreamer ();
camCap.AddDependencyNode (this);
}
void OnDestroy()
{
Destroy ();
}
// Update is called once per frame
void Update () {
if (!_created && camCap._grabber!=null && camCap.HasData) {
//important to create stream after data is confirmed
_streamer.CreateStream ();
_streamer.Stream ();
_created = true;
}
}
}
| 0 | 0.726639 | 1 | 0.726639 | game-dev | MEDIA | 0.794531 | game-dev | 0.838692 | 1 | 0.838692 |
RagedUnicorn/wow-classic-gearmenu | 12,414 | gui/GM_GearBarConfigurationMenu.lua | --[[
MIT License
Copyright (c) 2025 Michael Wiesendanger
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.
]]--
-- luacheck: globals STANDARD_TEXT_FONT CreateFrame StaticPopupDialogs StaticPopup_Show
-- luacheck: globals FauxScrollFrame_Update FauxScrollFrame_GetOffset
--[[
The gearBarMenu (GM_GearBarConfigurationMenu) module has some similarities to the gearBar (GM_GearBar) module.
It is also heavily interacting with gearBarManager (GM_GearBarManager) module but unlike the gearBar module
its purpose is to change and create values in the gearBarManager. It is used to give the user a UI to create, delete
and modify new gearBars and slots.
]]--
--[[
Module for responsible for creating new gearBars and the submenus needed to configure them
]]--
local mod = rggm
local me = {}
mod.gearBarConfigurationMenu = me
me.tag = "GearBarConfigurationMenu"
--[[
Reference to the scrollable gearBar list
]]--
local gearBarList
-- track whether the menu was already built
local builtMenu = false
--[[
Holds the gearBarId to delete after clicking on the delete button. The static popup
to confirm the deletion will use this to delete the propere url if the user confirms
the deletion
]]
local deleteGearBarId;
--[[
Popup dialog for choosing a profile name
]]--
StaticPopupDialogs["RGGM_CHOOSE_GEAR_BAR_NAME"] = {
text = rggm.L["gear_bar_choose_name"],
button1 = rggm.L["gear_bar_choose_name_accept_button"],
button2 = rggm.L["gear_bar_choose_name_cancel_button"],
OnShow = function(self)
local editBox = self:GetParent().editBox
local button1 = self:GetParent().button1
if editBox ~= nil and button1 ~= nil then
button1:Disable()
editBox:SetText("") -- reset text to empty
end
end,
OnAccept = function(self)
me.CreateNewGearBar(self.editBox:GetText())
me.GearBarListOnUpdate(gearBarList)
end,
EditBoxOnTextChanged = function(self)
local editBox = self:GetParent().editBox
local button1 = self:GetParent().button1
if editBox ~= nil and button1 ~= nil then
if string.len(editBox:GetText()) > 0 then
button1:Enable()
else
button1:Disable()
end
end
end,
timeout = 0,
whileDead = true,
preferredIndex = 3,
hasEditBox = true,
maxLetters = RGGM_CONSTANTS.GEAR_BAR_NAME_MAX_LENGTH
}
--[[
Popup dialog for confirming the deletion of a gearBar
]]--
StaticPopupDialogs["RGGM_GEAR_BAR_CONFIRM_DELETE"] = {
text = rggm.L["gear_bar_confirm_delete"],
button1 = rggm.L["gear_bar_confirm_delete_yes_button"],
button2 = rggm.L["gear_bar_confirm_delete_no_button"],
OnAccept = function()
if deleteGearBarId then
mod.gearBarManager.RemoveGearBar(deleteGearBarId)
mod.gearBarStorage.RemoveGearBar(deleteGearBarId)
me.GearBarListOnUpdate(gearBarList)
mod.addonConfiguration.InterfaceOptionsRemoveCategory(deleteGearBarId)
mod.gearBarConfigurationSubMenu.RemoveGearBarContentFrame(deleteGearBarId)
deleteGearBarId = nil
end
end,
timeout = 0,
whileDead = true,
preferredIndex = 3
}
--[[
Build the ui for the general menu. The place where new gearBars are created.
@param {table} parentFrame
The addon configuration frame to attach to
]]--
function me.BuildUi(parentFrame)
if builtMenu then return end
local gearBarConfigurationContentFrame = CreateFrame(
"Frame", RGGM_CONSTANTS.ELEMENT_GEAR_BAR_CONFIGURATION_MENU, parentFrame)
gearBarConfigurationContentFrame:SetWidth(RGGM_CONSTANTS.INTERFACE_PANEL_CONTENT_FRAME_WIDTH)
gearBarConfigurationContentFrame:SetHeight(RGGM_CONSTANTS.INTERFACE_PANEL_CONTENT_FRAME_HEIGHT)
gearBarConfigurationContentFrame:SetPoint("TOPLEFT", parentFrame, 5, -7)
me.CreateConfigurationMenuTitle(gearBarConfigurationContentFrame)
me.CreateNewGearBarButton(gearBarConfigurationContentFrame)
gearBarList = me.CreateGearBarList(gearBarConfigurationContentFrame)
me.GearBarListOnUpdate(gearBarList)
builtMenu = true
end
--[[
@param {table} contentFrame
]]--
function me.CreateConfigurationMenuTitle(contentFrame)
local titleFontString = contentFrame:CreateFontString(
RGGM_CONSTANTS.ELEMENT_GEAR_BAR_CONFIGURATION_MENU_TITLE, "OVERLAY")
titleFontString:SetFont(STANDARD_TEXT_FONT, 20)
titleFontString:SetPoint("TOP", 0, -20)
titleFontString:SetSize(contentFrame:GetWidth(), 20)
titleFontString:SetText(rggm.L["gear_bar_configuration_category_name"])
end
--[[
Create a button to create new gearBars
@param {table} gearBarFrame
@return {table}
The created button
]]--
function me.CreateNewGearBarButton(gearBarFrame)
local button = CreateFrame(
"Button",
RGGM_CONSTANTS.ELEMENT_GEAR_BAR_CONFIGURATION_CREATE_BUTTON,
gearBarFrame,
"UIPanelButtonTemplate"
)
button:SetHeight(RGGM_CONSTANTS.BUTTON_DEFAULT_HEIGHT)
button:SetText(rggm.L["gear_bar_configuration_add_gearbar"])
button:SetPoint("TOPLEFT", 20, -80)
button:SetScript('OnClick', function()
StaticPopup_Show("RGGM_CHOOSE_GEAR_BAR_NAME")
end)
local buttonFontString = button:GetFontString()
button:SetWidth(
buttonFontString:GetStringWidth() + RGGM_CONSTANTS.BUTTON_DEFAULT_PADDING
)
return button
end
--[[
Create a new gearBar with the gearBarManager - then adds a new interface option
for the created gearBar
@param {string} name
]]--
function me.CreateNewGearBar(name)
if #mod.gearBarManager.GetGearBars() >= RGGM_CONSTANTS.MAX_GEAR_BARS then
mod.logger.PrintUserError(rggm.L["gear_bar_max_amount_of_gear_bars_reached"])
return
end
local gearBar = mod.gearBarManager.AddGearBar(name, true)
-- build visual gearBar representation
mod.gearBar.BuildGearBar(gearBar)
local category, menu = mod.addonConfiguration.BuildCategory(
RGGM_CONSTANTS.ELEMENT_GEAR_BAR_CONFIG_GEAR_BAR_SUB_CONFIG_FRAME .. gearBar.id,
mod.addonConfiguration.GetGearBarSubCategory(),
gearBar.displayName,
mod.gearBarConfigurationSubMenu.GearBarConfigurationCategoryContainerOnCallback
)
menu.gearBarId = gearBar.id
category.gearBarId = gearBar.id
mod.gearBar.UpdateGearBarVisual(gearBar) -- update visual representation of the newly created gearBar
end
--[[
Load all configured bar menus in Interfaces Options. This will create an entry for
each gearBar that is configured
]]--
function me.LoadConfiguredGearBars()
local gearBars = mod.gearBarManager.GetGearBars()
for i = 1, #gearBars do
mod.logger.LogDebug(me.tag, "Loading gearBar with id: " .. gearBars[i].id .. " from configuration")
local category, menu = mod.addonConfiguration.BuildCategory(
RGGM_CONSTANTS.ELEMENT_GEAR_BAR_CONFIG_GEAR_BAR_SUB_CONFIG_FRAME .. gearBars[i].id,
mod.addonConfiguration.GetGearBarSubCategory(),
gearBars[i].displayName,
mod.gearBarConfigurationSubMenu.GearBarConfigurationCategoryContainerOnCallback
)
menu.gearBarId = gearBars[i].id
category.gearBarId = gearBars[i].id
end
end
--[[
@param {table} parentFrame
@return {table}
The created scrollFrame
]]--
function me.CreateGearBarList(parentFrame)
local scrollFrame = CreateFrame(
"ScrollFrame",
RGGM_CONSTANTS.ELEMENT_GEAR_BAR_LIST,
parentFrame,
"FauxScrollFrameTemplate"
)
scrollFrame:SetWidth(RGGM_CONSTANTS.GEAR_BAR_LIST_WIDTH)
scrollFrame:SetHeight(
RGGM_CONSTANTS.GEAR_BAR_LIST_ROW_HEIGHT
* RGGM_CONSTANTS.GEAR_BAR_LIST_MAX_ROWS
)
scrollFrame:SetPoint("TOPLEFT", 20, -120)
scrollFrame:EnableMouseWheel(true)
scrollFrame:SetScript("OnVerticalScroll", me.GearBarListOnVerticalScroll)
parentFrame.rows = {}
for i = 1, RGGM_CONSTANTS.GEAR_BAR_LIST_MAX_ROWS do
table.insert(parentFrame.rows, me.CreateGearBarListRowFrame(scrollFrame, i))
end
return scrollFrame
end
--[[
OnVerticalScroll callback for scrollable slots list
@param {table} self
@param {number} offset
]]--
function me.GearBarListOnVerticalScroll(self, offset)
self.ScrollBar:SetValue(offset)
self.offset = math.floor(offset / RGGM_CONSTANTS.GEAR_BAR_LIST_ROW_HEIGHT + 0.5)
me.GearBarListOnUpdate(self)
end
--[[
@param {table} frame
@param {number} position
@return {table}
The created row
]]--
function me.CreateGearBarListRowFrame(frame, position)
local row = CreateFrame("Button", RGGM_CONSTANTS.ELEMENT_GEAR_BAR_ROW_FRAME .. position, frame, "BackdropTemplate")
row:SetSize(frame:GetWidth(), RGGM_CONSTANTS.GEAR_BAR_LIST_ROW_HEIGHT)
row:SetPoint("TOPLEFT", frame, 0, (position -1) * RGGM_CONSTANTS.GEAR_BAR_LIST_ROW_HEIGHT * -1)
row:SetBackdrop({
bgFile = "Interface\\AddOns\\GearMenu\\assets\\ui_slot_background",
insets = {left = 0, right = 0, top = 0, bottom = 0},
})
if math.fmod(position, 2) == 0 then
row:SetBackdropColor(0.37, 0.37, 0.37, .3)
else
row:SetBackdropColor(.25, .25, .25, .9)
end
row.gearBarName = me.CreateGearBarNameText(row)
row.removeGearBarButton = me.CreateRemoveGearBarButton(row, row.gearBarName, position)
return row
end
--[[
Create a fontstring for the gearbar name
@param {table} row
@return {table}
The created fontstring
]]--
function me.CreateGearBarNameText(row)
local gearBarNameFontString = row:CreateFontString(RGGM_CONSTANTS.ELEMENT_GEAR_BAR_NAME_TEXT, "OVERLAY")
gearBarNameFontString:SetFont(STANDARD_TEXT_FONT, 15)
gearBarNameFontString:SetWidth(RGGM_CONSTANTS.GEAR_BAR_LIST_NAME_TEXT_WIDTH)
gearBarNameFontString:SetPoint(
"TOPLEFT",
row,
"TOPLEFT",
20,
-20
)
gearBarNameFontString:SetJustifyH("LEFT");
gearBarNameFontString:SetTextColor(.95, .95, .95)
return gearBarNameFontString
end
--[[
@param {table} row
@param {table} parentFrame
@param {number} position
@return {table}
The created button
]]--
function me.CreateRemoveGearBarButton(row, parentFrame, position)
local button = CreateFrame(
"Button",
RGGM_CONSTANTS.ELEMENT_GEAR_BAR_REMOVE_BUTTON .. position,
row,
"UIPanelButtonTemplate"
)
button:SetHeight(RGGM_CONSTANTS.BUTTON_DEFAULT_HEIGHT)
button:SetText(rggm.L["gear_bar_remove_button"])
button:SetPoint(
"LEFT",
parentFrame,
"RIGHT",
0,
0
)
button:SetScript("OnClick", function(self)
deleteGearBarId = self.id
StaticPopup_Show("RGGM_GEAR_BAR_CONFIRM_DELETE")
end)
button:SetWidth(
button:GetFontString():GetStringWidth() + RGGM_CONSTANTS.BUTTON_DEFAULT_PADDING
)
return button
end
--[[
Update a scrollable list holding configuration frames for gearBar slots
@param {table} scrollFrame
]]--
function me.GearBarListOnUpdate(scrollFrame)
local rows = scrollFrame:GetParent().rows
local gearBars = mod.gearBarManager.GetGearBars()
local maxValue = #gearBars or 0
if maxValue <= RGGM_CONSTANTS.GEAR_BAR_LIST_MAX_ROWS then
maxValue = RGGM_CONSTANTS.GEAR_BAR_LIST_MAX_ROWS + 1
end
-- Note: maxValue needs to be at least max_rows + 1
FauxScrollFrame_Update(
scrollFrame,
maxValue,
RGGM_CONSTANTS.GEAR_BAR_LIST_MAX_ROWS,
RGGM_CONSTANTS.GEAR_BAR_LIST_ROW_HEIGHT
)
local offset = FauxScrollFrame_GetOffset(scrollFrame)
for index = 1, RGGM_CONSTANTS.GEAR_BAR_LIST_MAX_ROWS do
local rowPosition = index + offset
if rowPosition <= #gearBars then
local row = rows[index]
row.gearBarName:SetText(gearBars[rowPosition].displayName)
row.removeGearBarButton.id = gearBars[rowPosition].id
row:Show()
else
rows[index]:Hide()
end
end
end
| 0 | 0.910948 | 1 | 0.910948 | game-dev | MEDIA | 0.621238 | game-dev,desktop-app | 0.850518 | 1 | 0.850518 |
pshtif/RuntimeTransformHandle | 3,233 | Assets/Plugins/RuntimeTransformHandle/Scripts/Handles/Scale/ScaleHandle.cs | using System;
using System.Collections.Generic;
using UnityEngine;
namespace RuntimeHandle
{
/**
* Created by Peter @sHTiF Stefcek 20.10.2020
*/
public class ScaleHandle : MonoBehaviour
{
protected RuntimeTransformHandle _parentTransformHandle;
protected List<ScaleAxis> _axes;
protected ScaleGlobal _globalAxis;
public ScaleHandle Initialize(RuntimeTransformHandle p_parentTransformHandle)
{
_parentTransformHandle = p_parentTransformHandle;
transform.SetParent(_parentTransformHandle.transform, false);
_axes = new List<ScaleAxis>();
if (_parentTransformHandle.axes == HandleAxes.X || _parentTransformHandle.axes == HandleAxes.XY || _parentTransformHandle.axes == HandleAxes.XZ || _parentTransformHandle.axes == HandleAxes.XYZ)
_axes.Add(new GameObject().AddComponent<ScaleAxis>()
.Initialize(_parentTransformHandle, Vector3.right, Color.red));
if (_parentTransformHandle.axes == HandleAxes.Y || _parentTransformHandle.axes == HandleAxes.XY || _parentTransformHandle.axes == HandleAxes.YZ || _parentTransformHandle.axes == HandleAxes.XYZ)
_axes.Add(new GameObject().AddComponent<ScaleAxis>()
.Initialize(_parentTransformHandle, Vector3.up, Color.green));
if (_parentTransformHandle.axes == HandleAxes.Z || _parentTransformHandle.axes == HandleAxes.XZ || _parentTransformHandle.axes == HandleAxes.YZ || _parentTransformHandle.axes == HandleAxes.XYZ)
_axes.Add(new GameObject().AddComponent<ScaleAxis>()
.Initialize(_parentTransformHandle, Vector3.forward, Color.blue));
if (_parentTransformHandle.axes != HandleAxes.X && _parentTransformHandle.axes != HandleAxes.Y && _parentTransformHandle.axes != HandleAxes.Z)
{
_globalAxis = new GameObject().AddComponent<ScaleGlobal>()
.Initialize(_parentTransformHandle, HandleBase.GetVectorFromAxes(_parentTransformHandle.axes), Color.white);
_globalAxis.InteractionStart += OnGlobalInteractionStart;
_globalAxis.InteractionUpdate += OnGlobalInteractionUpdate;
_globalAxis.InteractionEnd += OnGlobalInteractionEnd;
}
return this;
}
void OnGlobalInteractionStart()
{
foreach (ScaleAxis axis in _axes)
{
axis.SetColor(Color.yellow);
}
}
void OnGlobalInteractionUpdate(float p_delta)
{
foreach (ScaleAxis axis in _axes)
{
axis.delta = p_delta;
}
}
void OnGlobalInteractionEnd()
{
foreach (ScaleAxis axis in _axes)
{
axis.SetDefaultColor();
axis.delta = 0;
}
}
public void Destroy()
{
foreach (ScaleAxis axis in _axes)
Destroy(axis.gameObject);
if (_globalAxis) Destroy(_globalAxis.gameObject);
Destroy(this);
}
}
} | 0 | 0.800294 | 1 | 0.800294 | game-dev | MEDIA | 0.836434 | game-dev,graphics-rendering | 0.922718 | 1 | 0.922718 |
Velaron/tf15-client | 13,517 | cl_dll/vgui_CustomObjects.cpp | //=========== (C) Copyright 1999 Valve, L.L.C. All rights reserved. ===========
//
// The copyright to the contents herein is the property of Valve, L.L.C.
// The contents may be used and/or copied only with the written permission of
// Valve, L.L.C., or in accordance with the terms and conditions stipulated in
// the agreement/contract under which the contents have been supplied.
//
// Purpose: Contains implementation of various VGUI-derived objects
//
// $Workfile: $
// $Date: $
//
//-----------------------------------------------------------------------------
// $Log: $
//
// $NoKeywords: $
//=============================================================================
#include "VGUI_Font.h"
#include "hud.h"
#include "cl_util.h"
#include "camera.h"
#include "kbutton.h"
#include "cvardef.h"
#include "usercmd.h"
#include "const.h"
#include "camera.h"
#include "in_defs.h"
#include "parsemsg.h"
#include "vgui_int.h"
#include "vgui_TeamFortressViewport.h"
#include "vgui_ServerBrowser.h"
#include "vgui_loadtga.h"
// Arrow filenames
char *sArrowFilenames[] = {
"arrowup",
"arrowdn",
"arrowlt",
"arrowrt",
};
// Get the name of TGA file, without a gamedir
char *GetTGANameForRes( const char *pszName )
{
int i;
char sz[256];
static char gd[256];
if ( ScreenWidth < 640 )
i = 320;
else
i = 640;
sprintf( sz, pszName, i );
sprintf( gd, "gfx/vgui/%s.tga", sz );
return gd;
}
//-----------------------------------------------------------------------------
// Purpose: Loads a .tga file and returns a pointer to the VGUI tga object
//-----------------------------------------------------------------------------
BitmapTGA *LoadTGAForRes( const char *pImageName )
{
BitmapTGA *pTGA;
char sz[256];
sprintf( sz, "%%d_%s", pImageName );
pTGA = vgui_LoadTGA( GetTGANameForRes( sz ) );
return pTGA;
}
//===========================================================
// All TFC Hud buttons are derived from this one.
CommandButton::CommandButton( const char *text, int x, int y, int wide, int tall, bool bNoHighlight ) :
Button( "", x, y, wide, tall )
{
m_iPlayerClass = 0;
m_bNoHighlight = bNoHighlight;
m_bFlat = false;
Init();
setText( text );
}
CommandButton::CommandButton( int iPlayerClass, const char *text, int x, int y, int wide, int tall, bool bFlat ) :
Button( "", x, y, wide, tall )
{
m_iPlayerClass = iPlayerClass;
m_bNoHighlight = false;
m_bFlat = bFlat;
Init();
setText( text );
}
CommandButton::CommandButton( const char *text, int x, int y, int wide, int tall, bool bNoHighlight, bool bFlat ) :
Button( "", x, y, wide, tall )
{
m_iPlayerClass = 0;
m_bFlat = bFlat;
m_bNoHighlight = bNoHighlight;
Init();
setText( text );
}
void CommandButton::Init( void )
{
m_pSubMenu = NULL;
m_pSubLabel = NULL;
m_pParentMenu = NULL;
// Set text color to orange
setFgColor( Scheme::sc_primary1 );
// left align
setContentAlignment( vgui::Label::a_west );
// Add the Highlight signal
if ( !m_bNoHighlight )
addInputSignal( new CHandler_CommandButtonHighlight( this ) );
// not bound to any button yet
m_cBoundKey = 0;
}
//-----------------------------------------------------------------------------
// Purpose: Prepends the button text with the current bound key
// if no bound key, then a clear space ' ' instead
//-----------------------------------------------------------------------------
void CommandButton::RecalculateText( void )
{
char szBuf[128];
if ( m_cBoundKey != 0 )
{
if ( m_cBoundKey == (char)255 )
{
strcpy( szBuf, m_sMainText );
}
else
{
sprintf( szBuf, " %c %s", m_cBoundKey, m_sMainText );
}
szBuf[MAX_BUTTON_SIZE - 1] = 0;
}
else
{
// just draw a space if no key bound
sprintf( szBuf, " %s", m_sMainText );
szBuf[MAX_BUTTON_SIZE - 1] = 0;
}
Button::setText( szBuf );
}
void CommandButton::setText( const char *text )
{
strncpy( m_sMainText, text, MAX_BUTTON_SIZE );
m_sMainText[MAX_BUTTON_SIZE - 1] = 0;
RecalculateText();
}
void CommandButton::setBoundKey( char boundKey )
{
m_cBoundKey = boundKey;
RecalculateText();
}
char CommandButton::getBoundKey( void )
{
return m_cBoundKey;
}
void CommandButton::AddSubMenu( CCommandMenu *pNewMenu )
{
m_pSubMenu = pNewMenu;
// Prevent this button from being pushed
setMouseClickEnabled( MOUSE_LEFT, false );
}
void CommandButton::UpdateSubMenus( int iAdjustment )
{
if ( m_pSubMenu )
m_pSubMenu->RecalculatePositions( iAdjustment );
}
void CommandButton::paint()
{
// Make the sub label paint the same as the button
if ( m_pSubLabel )
{
if ( isSelected() )
m_pSubLabel->PushDown();
else
m_pSubLabel->PushUp();
}
// draw armed button text in white
if ( isArmed() )
{
setFgColor( Scheme::sc_secondary2 );
}
else
{
setFgColor( Scheme::sc_primary1 );
}
Button::paint();
}
void CommandButton::paintBackground()
{
if ( m_bFlat )
{
if ( isArmed() )
{
// Orange Border
drawSetColor( Scheme::sc_secondary1 );
drawOutlinedRect( 0, 0, _size[0], _size[1] );
}
}
else
{
if ( isArmed() )
{
// Orange highlight background
drawSetColor( Scheme::sc_primary2 );
drawFilledRect( 0, 0, _size[0], _size[1] );
}
// Orange Border
drawSetColor( Scheme::sc_secondary1 );
drawOutlinedRect( 0, 0, _size[0], _size[1] );
}
}
//-----------------------------------------------------------------------------
// Purpose: Highlights the current button, and all it's parent menus
//-----------------------------------------------------------------------------
void CommandButton::cursorEntered( void )
{
// unarm all the other buttons in this menu
CCommandMenu *containingMenu = getParentMenu();
if ( containingMenu )
{
containingMenu->ClearButtonsOfArmedState();
// make all our higher buttons armed
CCommandMenu *pCParent = containingMenu->GetParentMenu();
if ( pCParent )
{
CommandButton *pParentButton = pCParent->FindButtonWithSubmenu( containingMenu );
pParentButton->cursorEntered();
}
}
// arm ourselves
setArmed( true );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CommandButton::cursorExited( void )
{
// only clear ourselves if we have do not have a containing menu
// only stay armed if we have a sub menu
// the buttons only unarm themselves when another button is armed instead
if ( !getParentMenu() || !GetSubMenu() )
{
setArmed( false );
}
}
//-----------------------------------------------------------------------------
// Purpose: Returns the command menu that the button is part of, if any
// Output : CCommandMenu *
//-----------------------------------------------------------------------------
CCommandMenu *CommandButton::getParentMenu( void )
{
return m_pParentMenu;
}
//-----------------------------------------------------------------------------
// Purpose: Sets the menu that contains this button
// Input : *pParentMenu -
//-----------------------------------------------------------------------------
void CommandButton::setParentMenu( CCommandMenu *pParentMenu )
{
m_pParentMenu = pParentMenu;
}
//===========================================================
int ClassButton::IsNotValid()
{
// If this is the main ChangeClass button, remove it if the player's only able to be civilians
if ( m_iPlayerClass == -1 )
{
if ( gViewPort->GetValidClasses( g_iTeamNumber ) == -1 )
return true;
return false;
}
// Is it an illegal class?
if ( ( gViewPort->GetValidClasses( 0 ) & sTFValidClassInts[m_iPlayerClass] ) || ( gViewPort->GetValidClasses( g_iTeamNumber ) & sTFValidClassInts[m_iPlayerClass] ) )
return true;
// Only check current class if they've got autokill on
bool bAutoKill = CVAR_GET_FLOAT( "hud_classautokill" ) != 0;
if ( bAutoKill )
{
// Is it the player's current class?
if (
( gViewPort->IsRandomPC() && m_iPlayerClass == PC_RANDOM ) || ( !gViewPort->IsRandomPC() && ( m_iPlayerClass == g_iPlayerClass ) ) )
return true;
}
return false;
}
//===========================================================
// Button with Class image beneath it
CImageLabel::CImageLabel( const char *pImageName, int x, int y ) :
Label( "", x, y )
{
setContentFitted( true );
m_pTGA = LoadTGAForRes( pImageName );
setImage( m_pTGA );
}
CImageLabel::CImageLabel( const char *pImageName, int x, int y, int wide, int tall ) :
Label( "", x, y, wide, tall )
{
setContentFitted( true );
m_pTGA = LoadTGAForRes( pImageName );
setImage( m_pTGA );
}
//===========================================================
// Image size
int CImageLabel::getImageWide( void )
{
if ( m_pTGA )
{
int iXSize, iYSize;
m_pTGA->getSize( iXSize, iYSize );
return iXSize;
}
else
{
return 1;
}
}
int CImageLabel::getImageTall( void )
{
if ( m_pTGA )
{
int iXSize, iYSize;
m_pTGA->getSize( iXSize, iYSize );
return iYSize;
}
else
{
return 1;
}
}
void CImageLabel::LoadImage( const char *pImageName )
{
if ( m_pTGA )
delete m_pTGA;
// Load the Image
m_pTGA = LoadTGAForRes( pImageName );
if ( m_pTGA == NULL )
{
// we didn't find a matching image file for this resolution
// try to load file resolution independent
char sz[256];
sprintf( sz, "%s/%s", gEngfuncs.pfnGetGameDirectory(), pImageName );
FileInputStream *fis = new FileInputStream( sz, false );
m_pTGA = new BitmapTGA( fis, true );
fis->close();
}
if ( m_pTGA == NULL )
return; // unable to load image
int w, t;
m_pTGA->getSize( w, t );
setSize( XRES( w ), YRES( t ) );
setImage( m_pTGA );
}
//===========================================================
// Various overloaded paint functions for Custom VGUI objects
void CCommandMenu::paintBackground()
{
// Transparent black background
if ( m_iSpectCmdMenu )
drawSetColor( 0, 0, 0, 64 );
else
drawSetColor( Scheme::sc_primary3 );
drawFilledRect( 0, 0, _size[0], _size[1] );
}
//=================================================================================
// CUSTOM SCROLLPANEL
//=================================================================================
CTFScrollButton::CTFScrollButton( int iArrow, const char *text, int x, int y, int wide, int tall ) :
CommandButton( text, x, y, wide, tall )
{
// Set text color to orange
setFgColor( Scheme::sc_primary1 );
// Load in the arrow
m_pTGA = LoadTGAForRes( sArrowFilenames[iArrow] );
setImage( m_pTGA );
// Highlight signal
InputSignal *pISignal = new CHandler_CommandButtonHighlight( this );
addInputSignal( pISignal );
}
void CTFScrollButton::paint( void )
{
if ( !m_pTGA )
return;
// draw armed button text in white
if ( isArmed() )
{
m_pTGA->setColor( Color( 255, 255, 255, 0 ) );
}
else
{
m_pTGA->setColor( Color( 255, 255, 255, 128 ) );
}
m_pTGA->doPaint( this );
}
void CTFScrollButton::paintBackground( void )
{
/*
if ( isArmed() )
{
// Orange highlight background
drawSetColor( Scheme::sc_primary2 );
drawFilledRect(0,0,_size[0],_size[1]);
}
// Orange Border
drawSetColor( Scheme::sc_secondary1 );
drawOutlinedRect(0,0,_size[0]-1,_size[1]);
*/
}
void CTFSlider::paintBackground( void )
{
int wide, tall, nobx, noby;
getPaintSize( wide, tall );
getNobPos( nobx, noby );
// Border
drawSetColor( Scheme::sc_secondary1 );
drawOutlinedRect( 0, 0, wide, tall );
if ( isVertical() )
{
// Nob Fill
drawSetColor( Scheme::sc_primary2 );
drawFilledRect( 0, nobx, wide, noby );
// Nob Outline
drawSetColor( Scheme::sc_primary1 );
drawOutlinedRect( 0, nobx, wide, noby );
}
else
{
// Nob Fill
drawSetColor( Scheme::sc_primary2 );
drawFilledRect( nobx, 0, noby, tall );
// Nob Outline
drawSetColor( Scheme::sc_primary1 );
drawOutlinedRect( nobx, 0, noby, tall );
}
}
CTFScrollPanel::CTFScrollPanel( int x, int y, int wide, int tall ) :
ScrollPanel( x, y, wide, tall )
{
ScrollBar *pScrollBar = getVerticalScrollBar();
pScrollBar->setButton( new CTFScrollButton( ARROW_UP, "", 0, 0, 16, 16 ), 0 );
pScrollBar->setButton( new CTFScrollButton( ARROW_DOWN, "", 0, 0, 16, 16 ), 1 );
pScrollBar->setSlider( new CTFSlider( 0, wide - 1, wide, ( tall - ( wide * 2 ) ) + 2, true ) );
pScrollBar->setPaintBorderEnabled( false );
pScrollBar->setPaintBackgroundEnabled( false );
pScrollBar->setPaintEnabled( false );
pScrollBar = getHorizontalScrollBar();
pScrollBar->setButton( new CTFScrollButton( ARROW_LEFT, "", 0, 0, 16, 16 ), 0 );
pScrollBar->setButton( new CTFScrollButton( ARROW_RIGHT, "", 0, 0, 16, 16 ), 1 );
pScrollBar->setSlider( new CTFSlider( tall, 0, wide - ( tall * 2 ), tall, false ) );
pScrollBar->setPaintBorderEnabled( false );
pScrollBar->setPaintBackgroundEnabled( false );
pScrollBar->setPaintEnabled( false );
}
//=================================================================================
// CUSTOM HANDLERS
//=================================================================================
void CHandler_MenuButtonOver::cursorEntered( Panel *panel )
{
if ( gViewPort && m_pMenuPanel )
{
m_pMenuPanel->SetActiveInfo( m_iButton );
}
}
void CMenuHandler_StringCommandClassSelect::actionPerformed( Panel *panel )
{
CMenuHandler_StringCommand::actionPerformed( panel );
// THIS IS NOW BEING DONE ON THE TFC SERVER TO AVOID KILLING SOMEONE THEN
// HAVE THE SERVER SAY "SORRY...YOU CAN'T BE THAT CLASS".
#if 0
bool bAutoKill = CVAR_GET_FLOAT( "hud_classautokill" ) != 0;
if ( bAutoKill && g_iPlayerClass != 0 )
gEngfuncs.pfnClientCmd( "kill" );
#endif
}
| 0 | 0.866209 | 1 | 0.866209 | game-dev | MEDIA | 0.524989 | game-dev,desktop-app | 0.935138 | 1 | 0.935138 |
ericraio/vanilla-wow-addons | 2,142 | s/SelfElite/SelfElite.lua | --
-- base unitframe handler
--
function SelfEliteFrameHandler(unittype)
if( unittype == "elite" ) then
PlayerFrameTexture:SetTexture("Interface\\TargetingFrame\\UI-TargetingFrame-Elite");
elseif( unittype == "rare" ) then
PlayerFrameTexture:SetTexture("Interface\\TargetingFrame\\UI-TargetingFrame-Rare");
elseif( unittype == "raremob" ) then
PlayerFrameTexture:SetTexture("Interface\\TargetingFrame\\UI-TargetingFrame-RareMob");
elseif( unittype == "normal" ) then
PlayerFrameTexture:SetTexture("Interface\\TargetingFrame\\UI-TargetingFrame");
else
PlayerFrameTexture:SetTexture(nil);
end
end
function SelfEliteChangeFrameType(checked,value)
if (value == 1) then
SelfEliteFrameHandler("normal");
elseif (value == 2) then
SelfEliteFrameHandler("rare");
elseif (value == 3) then
SelfEliteFrameHandler("elite");
elseif (value == 4) then
SelfEliteFrameHandler("raremob");
elseif (value == 5) then
SelfEliteFrameHandler();
end
end
function SelfElite_Onload()
if (UltimateUI_RegisterConfiguration) then
-- Example of Section
-- ========================
UltimateUI_RegisterConfiguration(
"UUI_SELFELITE", -- prefix that all options that should go in this section have to start with
"SECTION", -- Type
"Self Elite", -- Section Label
"Change your player frame!" -- Mouseover
);
-- Example of Separator
-- ========================
UltimateUI_RegisterConfiguration(
"UUI_SELFELITE_SEPARATOR", -- Keyword
"SEPARATOR", -- Type
"SelfElite Options", -- Separator Label
"Options for SelfElite" -- Mouseover
);
UltimateUI_RegisterConfiguration(
"UUI_SELFELITE_TYPE", -- CVar
"SLIDER", -- Type
"Set your frame type", -- Short description
"This slider sets the frame type you want.", -- Long description
SelfEliteChangeFrameType, -- Callback
1, -- Default Checked/Unchecked
1, -- Default slider value
1, -- Minimum slider value
5, -- max value
"Frame number type", -- slider "header" text
1, -- Slider steps
1, -- Text on slider?
"", -- slider text append
1 -- slider multiplier
);
end
end
| 0 | 0.713568 | 1 | 0.713568 | game-dev | MEDIA | 0.773166 | game-dev | 0.94001 | 1 | 0.94001 |
aumuell/open-inventor | 26,318 | lib/database/src/so/nodes/SoSeparator.c++ | /*
*
* Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
* Mountain View, CA 94043, or:
*
* http://www.sgi.com
*
* For further information regarding this notice, see:
*
* http://oss.sgi.com/projects/GenInfo/NoticeExplan/
*
*/
/*
* Copyright (C) 1990,91 Silicon Graphics, Inc.
*
_______________________________________________________________________
______________ S I L I C O N G R A P H I C S I N C . ____________
|
| $Revision: 1.1.1.1 $
|
| Classes:
| SoSeparator
|
| Author(s) : Paul S. Strauss, Nick Thompson
|
______________ S I L I C O N G R A P H I C S I N C . ____________
_______________________________________________________________________
*/
#include <Inventor/SbBox.h>
#include <Inventor/actions/SoAction.h>
#include <Inventor/actions/SoCallbackAction.h>
#include <Inventor/actions/SoGLRenderAction.h>
#include <Inventor/actions/SoGetBoundingBoxAction.h>
#include <Inventor/actions/SoGetMatrixAction.h>
#include <Inventor/actions/SoHandleEventAction.h>
#include <Inventor/actions/SoRayPickAction.h>
#include <Inventor/actions/SoSearchAction.h>
#include <Inventor/actions/SoWriteAction.h>
#include <Inventor/caches/SoBoundingBoxCache.h>
#include <Inventor/caches/SoGLCacheList.h>
#include <Inventor/elements/SoCacheElement.h>
#include <Inventor/elements/SoGLCacheContextElement.h>
#include <Inventor/elements/SoLocalBBoxMatrixElement.h>
#include <Inventor/elements/SoModelMatrixElement.h>
#include <Inventor/elements/SoViewportRegionElement.h>
#include <Inventor/misc/SoChildList.h>
#include <Inventor/misc/SoState.h>
#include <Inventor/nodes/SoSeparator.h>
#ifdef DEBUG
#include <SoDebug.h>
#endif
#include <cstdlib>
SO_NODE_SOURCE(SoSeparator);
int SoSeparator::numRenderCaches = 2;
////////////////////////////////////////////////////////////////////////
//
// Description:
// This initializes the SoSeparator class.
//
// Use: internal
void
SoSeparator::initClass()
//
////////////////////////////////////////////////////////////////////////
{
SO__NODE_INIT_CLASS(SoSeparator, "Separator", SoGroup);
// Enable cache element in those actions that support caching
SO_ENABLE(SoGetBoundingBoxAction, SoCacheElement);
SO_ENABLE(SoGLRenderAction, SoCacheElement);
SO_ENABLE(SoGLRenderAction, SoGLCacheContextElement);
// Allow environment var to control caching:
const char *NRC;
if ((NRC = getenv("IV_SEPARATOR_MAX_CACHES")) != NULL) {
numRenderCaches = atoi(NRC);
}
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Constructor
//
// Use: public
SoSeparator::SoSeparator()
//
////////////////////////////////////////////////////////////////////////
{
SO_NODE_CONSTRUCTOR(SoSeparator);
SO_NODE_ADD_FIELD(renderCaching, (AUTO));
SO_NODE_ADD_FIELD(boundingBoxCaching, (AUTO));
SO_NODE_ADD_FIELD(renderCulling, (AUTO));
SO_NODE_ADD_FIELD(pickCulling, (AUTO));
// Set up static info for enum fields
SO_NODE_DEFINE_ENUM_VALUE(CacheEnabled, ON);
SO_NODE_DEFINE_ENUM_VALUE(CacheEnabled, OFF);
SO_NODE_DEFINE_ENUM_VALUE(CacheEnabled, AUTO);
// Set up info in enumerated type fields
SO_NODE_SET_SF_ENUM_TYPE(renderCaching, CacheEnabled);
SO_NODE_SET_SF_ENUM_TYPE(boundingBoxCaching,CacheEnabled);
SO_NODE_SET_SF_ENUM_TYPE(renderCulling, CacheEnabled);
SO_NODE_SET_SF_ENUM_TYPE(pickCulling, CacheEnabled);
bboxCache = NULL;
cacheList = new SoGLCacheList(numRenderCaches);
isBuiltIn = TRUE;
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Constructor taking approximate number of children
//
// Use: public
SoSeparator::SoSeparator(int nChildren) : SoGroup(nChildren)
//
////////////////////////////////////////////////////////////////////////
{
SO_NODE_CONSTRUCTOR(SoSeparator);
SO_NODE_ADD_FIELD(renderCaching, (AUTO));
SO_NODE_ADD_FIELD(boundingBoxCaching, (AUTO));
SO_NODE_ADD_FIELD(renderCulling, (AUTO));
SO_NODE_ADD_FIELD(pickCulling, (AUTO));
// Set up static info for enum fields
SO_NODE_DEFINE_ENUM_VALUE(CacheEnabled, ON);
SO_NODE_DEFINE_ENUM_VALUE(CacheEnabled, OFF);
SO_NODE_DEFINE_ENUM_VALUE(CacheEnabled, AUTO);
// Set up info in enumerated type fields
SO_NODE_SET_SF_ENUM_TYPE(renderCaching, CacheEnabled);
SO_NODE_SET_SF_ENUM_TYPE(boundingBoxCaching,CacheEnabled);
SO_NODE_SET_SF_ENUM_TYPE(renderCulling, CacheEnabled);
SO_NODE_SET_SF_ENUM_TYPE(pickCulling, CacheEnabled);
bboxCache = NULL;
cacheList = new SoGLCacheList(numRenderCaches);
isBuiltIn = TRUE;
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Destructor has to free caches
//
// Use: private
SoSeparator::~SoSeparator()
//
////////////////////////////////////////////////////////////////////////
{
if (bboxCache != NULL)
bboxCache->unref();
delete cacheList;
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Overrides method in SoNode to return FALSE.
//
// Use: public
SbBool
SoSeparator::affectsState() const
//
////////////////////////////////////////////////////////////////////////
{
return FALSE;
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Set the number of render caches a newly created separator can
// have.
//
// Use: public, static
void
SoSeparator::setNumRenderCaches(int howMany)
//
////////////////////////////////////////////////////////////////////////
{
numRenderCaches = howMany;
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Returns the number of render caches newly created separators
// will have.
//
// Use: public, static
int
SoSeparator::getNumRenderCaches()
//
////////////////////////////////////////////////////////////////////////
{
return numRenderCaches;
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Turn off notification on fields to avoid notification when
// reading, so that caching works properly:
//
// Use: protected
SbBool
SoSeparator::readInstance(SoInput *in, unsigned short flags)
//
////////////////////////////////////////////////////////////////////////
{
int i;
SoFieldList myFields;
getFields(myFields);
for (i = 0; i < myFields.getLength(); i++) {
myFields[i]->enableNotify(FALSE);
}
SbBool result = SoGroup::readInstance(in, flags);
for (i = 0; i < myFields.getLength(); i++) {
myFields[i]->enableNotify(TRUE);
}
return result;
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Passes on notification after invalidating all caches and
// recording that notification has passed through a separator
//
// Use: internal
void
SoSeparator::notify(SoNotList *list)
//
////////////////////////////////////////////////////////////////////////
{
// Destroy all caches, if present
if (bboxCache != NULL) {
bboxCache->unref();
bboxCache = NULL;
}
cacheList->invalidateAll();
// Then do the usual stuff
SoGroup::notify(list);
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Implements typical traversal.
//
// Use: extender
void
SoSeparator::doAction(SoAction *action)
//
////////////////////////////////////////////////////////////////////////
{
int numIndices;
const int *indices;
// This differs from SoGroup: if the separator is not on the
// path, don't bother traversing its children
switch (action->getPathCode(numIndices, indices)) {
case SoAction::NO_PATH:
case SoAction::BELOW_PATH:
action->getState()->push();
children->traverse(action);
action->getState()->pop();
break;
case SoAction::IN_PATH:
action->getState()->push();
children->traverse(action, 0, indices[numIndices - 1]);
action->getState()->pop();
break;
case SoAction::OFF_PATH:
break;
}
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Implements callback action for separator nodes.
//
// Use: extender
void
SoSeparator::callback(SoCallbackAction *action)
//
////////////////////////////////////////////////////////////////////////
{
SoSeparator::doAction(action);
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Traversal for computing bounding box. This also takes care of
// creating the bounding box cache.
//
// Use: extender
void
SoSeparator::getBoundingBox(SoGetBoundingBoxAction *action)
//
////////////////////////////////////////////////////////////////////////
{
SbBool canCache;
SoState *state = action->getState();
int numIndices;
const int *indices;
switch (action->getPathCode(numIndices, indices)) {
case SoAction::OFF_PATH:
// If off the path, don't need to do anything.
return;
case SoAction::NO_PATH:
case SoAction::BELOW_PATH:
canCache = (boundingBoxCaching.getValue() != OFF &&
! action->isInCameraSpace() &&
! action->isResetPath());
break;
case SoAction::IN_PATH:
canCache = FALSE;
break;
}
// If we have a valid cache already, just use it
if (canCache && bboxCache != NULL && bboxCache->isValid(state)) {
SoCacheElement::addCacheDependency(state, bboxCache);
action->extendBy(bboxCache->getBox());
// We want the center to be transformed by the current local
// transformation, just as if we were a shape node
if (bboxCache->isCenterSet())
action->setCenter(bboxCache->getCenter(), TRUE);
// If our cache has lines or points, set the flag in any open
// caches above us
if (bboxCache->hasLinesOrPoints())
SoBoundingBoxCache::setHasLinesOrPoints(state);
}
// If we can't cache, just do what group does, with push/pop added
else if (! canCache) {
state->push();
SoGroup::getBoundingBox(action);
state->pop();
}
// Otherwise, we have to do some extra work
else {
// Save the current bounding box from the action and empty it.
// (We can assume the center has not been set, or else some
// group is not doing its job.)
SbXfBox3f savedBBox = action->getXfBoundingBox();
action->getXfBoundingBox().makeEmpty();
state->push();
// Set the local bbox matrix to identity, so shapes' bounding
// boxes will be transformed into our local space
SoLocalBBoxMatrixElement::makeIdentity(state);
// Build cache. We've already tested for a valid cache, so the
// only other possibility is for a NULL cache or an invalid one
if (bboxCache != NULL)
bboxCache->unref();
// Create a new cache:
bboxCache = new SoBoundingBoxCache(state);
bboxCache->ref();
SoCacheElement::set(state, bboxCache);
// Traverse the kids
SoGroup::getBoundingBox(action);
// This has to be done before the extendBy
state->pop();
// Save the bounding box around our kids and save the center
SbXfBox3f kidsBBox = action->getXfBoundingBox();
SbVec3f kidsCenter = action->getCenter();
SbBool kidsCenterSet = action->isCenterSet();
// Store it in the cache
// Note: bboxCache might be NULL if notification happened
// during traversal.
if (bboxCache != NULL)
bboxCache->set(kidsBBox, kidsCenterSet, kidsCenter);
#ifdef DEBUG
else {
SoDebugError::post("SoSeparator::getBoundingBox",
"Bbox cache was destroyed during "
"traversal, meaning a change was "
"made to the scene during a "
"getBoundingBox action. If you "
"must change the scene during an "
"action traversal, you should disable "
"notification first using methods "
"on SoFieldContainer or SoField.");
}
#endif
// If the bounding box was reset by one of our children, we
// don't want to restore the previous bounding box. Instead,
// we just set it to the children's bounding box so that the
// current local transformation is multiplied in. Otherwise,
// we have to restore the previous bounding box and extend it
// by the children's bounding box.
if (action->isResetPath() &&
(action->getWhatReset() & SoGetBoundingBoxAction::BBOX) != 0 &&
action->getResetPath()->containsNode(this))
action->getXfBoundingBox().makeEmpty();
else
action->getXfBoundingBox() = savedBBox;
// Extend the bounding box by the one our kids returned -
// this will multiply in the current local transformation
action->extendBy(kidsBBox);
// Set the center to be the computed center of our kids,
// transformed by the current local transformation
if (kidsCenterSet) {
action->resetCenter();
action->setCenter(kidsCenter, TRUE);
}
}
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Implements getMatrix action.
//
// Use: extender
void
SoSeparator::getMatrix(SoGetMatrixAction *action)
//
////////////////////////////////////////////////////////////////////////
{
int numIndices;
const int *indices;
// Only need to compute matrix if separator is a node in middle of
// current path chain. We don't need to push or pop the state,
// since this shouldn't have any effect on other nodes being
// traversed.
if (action->getPathCode(numIndices, indices) == SoAction::IN_PATH)
children->traverse(action, 0, indices[numIndices - 1]);
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Traversal for rendering. This is different from generic
// traversal because we may need to do caching.
//
// Use: extender
void
SoSeparator::GLRender(SoGLRenderAction *action)
//
////////////////////////////////////////////////////////////////////////
{
int numIndices;
const int *indices;
SoAction::PathCode pc = action->getPathCode(numIndices,indices);
if (pc == SoAction::NO_PATH || pc == SoAction::BELOW_PATH)
GLRenderBelowPath(action);
else if (pc == SoAction::IN_PATH)
GLRenderInPath(action);
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Renders all children. Also does caching and culling.
//
// Use: extender
void
SoSeparator::GLRenderBelowPath(SoGLRenderAction *action)
////////////////////////////////////////////////////////////////////////
{
SoState *state = action->getState();
// Do a cull test, if culling is turned on:
int savedCullBits;
// For now, just do culling if turned ON explicitly. Eventually,
// we might want to change this to:
// (cullFlag == AUTO && !state->isCacheOpen()) || (cullFlag == ON)
SbBool doCullTest = (renderCulling.getValue() == ON);
if (doCullTest) {
int cullBits = savedCullBits = action->getCullTestResults();
if (cullBits) {
#ifdef DEBUG
static int printCullInfo = -1;
if (printCullInfo == -1)
printCullInfo =
SoDebug::GetEnv("IV_DEBUG_RENDER_CULL") != NULL;
if (printCullInfo) {
if (getName().getLength() != 0)
SoDebug::RTPrintf("Separator named %s",
getName().getString());
else
SoDebug::RTPrintf("Separator 0x%x", this);
}
#endif
if (cullTest(action, cullBits)) {
#ifdef DEBUG
if (printCullInfo)
SoDebug::RTPrintf(" render culled\n");
#endif
// Don't cache above if doing culling:
SoGLCacheContextElement::shouldAutoCache(state,
SoGLCacheContextElement::DONT_AUTO_CACHE);
return;
}
#ifdef DEBUG
if (printCullInfo)
printf(" render cull results: %c%c%c\n",
cullBits&1 ? 'S' : 'i',
cullBits&2 ? 'S' : 'i',
cullBits&4 ? 'S' : 'i');
#endif
action->setCullTestResults(cullBits);
}
}
SbBool canCallCache = (renderCaching.getValue() != OFF);
SbBool canBuildCache = (canCallCache && ! state->isCacheOpen());
state->push();
// if we can't call a cache:
if (canCallCache && cacheList->call(action)) {
// Just pop the state
state->pop();
} else {
if (canBuildCache) {
// Let the cacheList open a new cache, if it can. This
// HAS to come after push() so that the cache element can
// be set correctly.
cacheList->open(action, renderCaching.getValue() == AUTO);
}
action->pushCurPath();
const int numKids = children->getLength();
for (int i = 0; i < numKids && !action->hasTerminated(); i++) {
action->popPushCurPath(i);
if (! action->abortNow())
((SoNode *)children->get(i))->GLRenderBelowPath(action);
else
SoCacheElement::invalidate(action->getState());
}
action->popCurPath();
state->pop();
if (canBuildCache) {
// Let the cacheList close the cache, if it decided to
// open one. This HAS to come after the pop() so that any
// GL commands executed by pop() are part of the display
// list.
cacheList->close(action);
}
}
// Reset cull bits, if did a cull test:
if (doCullTest) {
action->setCullTestResults(savedCullBits);
// Don't cache above if doing culling:
SoGLCacheContextElement::shouldAutoCache(state,
SoGLCacheContextElement::DONT_AUTO_CACHE);
}
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Does the GL render action
//
// Use: extender
void
SoSeparator::GLRenderInPath(SoGLRenderAction *action)
////////////////////////////////////////////////////////////////////////
{
int numIndices;
const int *indices;
SoAction::PathCode pc = action->getPathCode(numIndices, indices);
if (pc == SoAction::IN_PATH) { // still rendering in path:
SoState *state = action->getState();
state->push();
int whichChild = 0;
for (int i = 0; i < numIndices && !action->hasTerminated(); i++) {
while (whichChild < indices[i] && !action->hasTerminated()) {
SoNode *kid = (SoNode *)children->get(whichChild);
if (kid->affectsState()) {
action->pushCurPath(whichChild);
if (! action->abortNow())
kid->GLRenderOffPath(action);
else
SoCacheElement::invalidate(action->getState());
action->popCurPath(pc);
}
++whichChild;
}
action->pushCurPath(whichChild);
if (action->abortNow())
SoCacheElement::invalidate(action->getState());
else
((SoNode *)children->get(whichChild))->GLRenderInPath(action);
action->popCurPath(pc);
++whichChild;
}
state->pop();
} else if (pc == SoAction::BELOW_PATH) { // This must be tail node
GLRenderBelowPath(action);
} else { // This should NEVER happen:
#ifdef DEBUG
SoDebugError::post("SoSeparator::GLRenderInPath",
"PathCode went to NO_PATH or OFF_PATH!");
#endif
}
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Does the GL render action
//
// Use: extender
void
SoSeparator::GLRenderOffPath(SoGLRenderAction *)
////////////////////////////////////////////////////////////////////////
{
#ifdef DEBUG
SoDebugError::post("SoSeparator::GLRenderOffPath",
"affectsState() is FALSE");
#endif
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Implements handle event action for separator nodes.
//
// Use: extender
void
SoSeparator::handleEvent(SoHandleEventAction *action)
//
////////////////////////////////////////////////////////////////////////
{
SoSeparator::doAction(action);
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Figure out if this separator is culled or not. Returns TRUE if
// the separator is culled.
//
// Use: extender
SbBool
SoSeparator::cullTest(SoGLRenderAction *action, int &cullBits)
//
////////////////////////////////////////////////////////////////////////
{
// Don't bother if bbox caching is turned off:
if (boundingBoxCaching.getValue() == OFF) return FALSE;
SoState *state = action->getState();
// Next, get our bounding box. We do this in a way that is a
// little dangerous and hacky-- we use the state from the
// renderAction and pass to bounding box cache's isValid. This
// assumes that the state for the bounding box and render action
// can be compared, which happens to be true (all elements needed
// for getBoundingBox are also needed for glRender).
if (bboxCache == NULL || !bboxCache->isValid(state)) {
static SoGetBoundingBoxAction *bba = NULL;
if (!bba)
bba = new SoGetBoundingBoxAction(
SoViewportRegionElement::get(state));
else
bba->setViewportRegion(SoViewportRegionElement::get(state));
bba->apply((SoPath *)action->getCurPath());
}
if (bboxCache == NULL) return FALSE;
const SbBox3f &bbox = bboxCache->getProjectedBox();
const SbMatrix &cullMatrix =
SoModelMatrixElement::getCombinedCullMatrix(state);
return bbox.outside(cullMatrix, cullBits);
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Implements ray picking.
//
// Use: extender
void
SoSeparator::rayPick(SoRayPickAction *action)
//
////////////////////////////////////////////////////////////////////////
{
int numIndices;
const int *indices;
// Bail out if there is nothing to traverse...
if (action->getPathCode(numIndices, indices) == SoAction::OFF_PATH)
return;
// Note: even if we are only traversing some of our children we
// can still use the bounding box cache computed for all of our
// children for culling, because the bounding box for all of our
// children is guaranteed to be at least as big as the bounding
// box for some of them.
// The action may not have yet computed a world space ray. (This
// will be true if the pick was specified as a window-space point
// and no camera has yet been traversed. This could happen if
// there is no camera or the camera appears under this separator.)
// In this case, don't bother trying to intersect the ray with a
// cached bounding box, sine there ain't no ray!
if (action->isCullingEnabled() && pickCulling.getValue() != OFF &&
action->hasWorldSpaceRay()) {
// If we don't have a valid cache, try to build one by
// applying an SoGetBoundingBoxAction to the current path to
// the separator. (Testing if the cache is invalid uses the
// state of the pick action; this assumes that any element
// that is valid in a bounding box action will also be valid
// in a pick action.)
if (bboxCache == NULL || ! bboxCache->isValid(action->getState())) {
SoGetBoundingBoxAction ba(action->getViewportRegion());
ba.apply((SoPath *) action->getCurPath());
}
// It's conceivable somehow that the cache was not built, so
// check it again
if (bboxCache != NULL) {
// Test the bounding box in the cache for intersection
// with the pick ray. If none, traverse no further.
// If there are no lines or points in the cache, we can
// use a faster intersection test: intersect the picking
// ray with the bounding box. Otherwise, we have to use
// the picking view volume to make sure we pick near lines
// and points
action->setObjectSpace();
#ifdef DEBUG
static int printCullInfo = -1;
if (printCullInfo == -1)
printCullInfo =
SoDebug::GetEnv("IV_DEBUG_PICK_CULL") != NULL;
if (printCullInfo) {
if (getName().getLength() != 0)
SoDebug::RTPrintf("Separator named %s",
getName().getString());
else
SoDebug::RTPrintf("Separator 0x%x", this);
}
#endif
if (! action->intersect(bboxCache->getBox().project(),
bboxCache->hasLinesOrPoints())) {
#ifdef DEBUG
if (printCullInfo)
SoDebug::RTPrintf(" pick culled\n");
#endif
return;
}
#ifdef DEBUG
else if (printCullInfo) {
SoDebug::RTPrintf(" pick cull test passed\n");
}
#endif
}
}
// If we got here, we're supposed to traverse our children
action->getState()->push();
SoGroup::rayPick(action);
action->getState()->pop();
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Implements search action for separator nodes. This determines if
// the separator should be searched. If so, this calls the search
// method for SoGroup to do the work.
//
// Use: extender
void
SoSeparator::search(SoSearchAction *action)
//
////////////////////////////////////////////////////////////////////////
{
SbBool doSearch = TRUE;
// See if we're supposed to search only if the stuff under the
// separator is relevant to the search path
if (! action->isSearchingAll()) {
int numIndices;
const int *indices;
// Search through this separator node only if not searching along
// a path or this node is on the path
if (action->getPathCode(numIndices, indices) == SoAction::OFF_PATH)
doSearch = FALSE;
}
if (doSearch) {
action->getState()->push();
SoGroup::search(action);
action->getState()->pop();
}
}
| 0 | 0.94477 | 1 | 0.94477 | game-dev | MEDIA | 0.367738 | game-dev | 0.749343 | 1 | 0.749343 |
HbmMods/Hbm-s-Nuclear-Tech-GIT | 19,320 | src/main/java/com/hbm/items/weapon/sedna/factory/XFactory44.java | package com.hbm.items.weapon.sedna.factory;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
import com.hbm.entity.projectile.EntityBoxcar;
import com.hbm.entity.projectile.EntityBulletBaseMK4;
import com.hbm.entity.projectile.EntityTorpedo;
import com.hbm.items.ModItems;
import com.hbm.items.ItemEnums.EnumCasingType;
import com.hbm.items.weapon.sedna.BulletConfig;
import com.hbm.items.weapon.sedna.Crosshair;
import com.hbm.items.weapon.sedna.GunConfig;
import com.hbm.items.weapon.sedna.ItemGunBaseNT;
import com.hbm.items.weapon.sedna.Receiver;
import com.hbm.items.weapon.sedna.ItemGunBaseNT.GunState;
import com.hbm.items.weapon.sedna.ItemGunBaseNT.LambdaContext;
import com.hbm.items.weapon.sedna.ItemGunBaseNT.WeaponQuality;
import com.hbm.items.weapon.sedna.factory.GunFactory.EnumAmmo;
import com.hbm.items.weapon.sedna.factory.GunFactory.EnumAmmoSecret;
import com.hbm.items.weapon.sedna.mags.MagazineFullReload;
import com.hbm.items.weapon.sedna.mags.MagazineSingleReload;
import com.hbm.items.weapon.sedna.mods.WeaponModManager;
import com.hbm.lib.RefStrings;
import com.hbm.particle.SpentCasing;
import com.hbm.particle.SpentCasing.CasingType;
import com.hbm.render.anim.AnimationEnums.GunAnimation;
import com.hbm.render.anim.BusAnimation;
import com.hbm.render.anim.BusAnimationSequence;
import com.hbm.render.anim.BusAnimationKeyframe.IType;
import net.minecraft.item.ItemStack;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.ResourceLocation;
public class XFactory44 {
public static final ResourceLocation scope_lilmac = new ResourceLocation(RefStrings.MODID, "textures/misc/scope_44.png");
public static BulletConfig m44_bp;
public static BulletConfig m44_sp;
public static BulletConfig m44_fmj;
public static BulletConfig m44_jhp;
public static BulletConfig m44_ap;
public static BulletConfig m44_express;
public static BulletConfig m44_equestrian_pip;
public static BulletConfig m44_equestrian_mn7;
public static BiConsumer<EntityBulletBaseMK4, MovingObjectPosition> LAMBDA_BOXCAR = (bullet, mop) -> {
EntityBoxcar pippo = new EntityBoxcar(bullet.worldObj);
pippo.posX = mop.hitVec.xCoord;
pippo.posY = mop.hitVec.yCoord + 50;
pippo.posZ = mop.hitVec.zCoord;;
bullet.worldObj.spawnEntityInWorld(pippo);
bullet.worldObj.playSoundEffect(pippo.posX, pippo.posY + 50, pippo.posZ, "hbm:alarm.trainHorn", 100F, 1F);
bullet.setDead();
};
public static BiConsumer<EntityBulletBaseMK4, MovingObjectPosition> LAMBDA_TORPEDO = (bullet, mop) -> {
EntityTorpedo murky = new EntityTorpedo(bullet.worldObj);
murky.posX = mop.hitVec.xCoord;
murky.posY = mop.hitVec.yCoord + 50;
murky.posZ = mop.hitVec.zCoord;;
bullet.worldObj.spawnEntityInWorld(murky);
bullet.setDead();
};
public static void init() {
SpentCasing casing44 = new SpentCasing(CasingType.STRAIGHT).setColor(SpentCasing.COLOR_CASE_BRASS).setupSmoke(1F, 0.5D, 60, 20);
m44_bp = new BulletConfig().setItem(EnumAmmo.M44_BP).setCasing(EnumCasingType.SMALL, 12).setDamage(0.75F).setBlackPowder(true)
.setCasing(casing44.clone().register("m44bp"));
m44_sp = new BulletConfig().setItem(EnumAmmo.M44_SP).setCasing(EnumCasingType.SMALL, 6)
.setCasing(casing44.clone().register("m44"));
m44_fmj = new BulletConfig().setItem(EnumAmmo.M44_FMJ).setCasing(EnumCasingType.SMALL, 6).setDamage(0.8F).setThresholdNegation(3F).setArmorPiercing(0.1F)
.setCasing(casing44.clone().register("m44fmj"));
m44_jhp = new BulletConfig().setItem(EnumAmmo.M44_JHP).setCasing(EnumCasingType.SMALL, 6).setDamage(1.5F).setHeadshot(1.5F).setArmorPiercing(-0.25F)
.setCasing(casing44.clone().register("m44jhp"));
m44_ap = new BulletConfig().setItem(EnumAmmo.M44_AP).setCasing(EnumCasingType.SMALL_STEEL, 6).setDoesPenetrate(true).setDamageFalloffByPen(false).setDamage(1.25F).setThresholdNegation(7.5F).setArmorPiercing(0.15F)
.setCasing(casing44.clone().setColor(SpentCasing.COLOR_CASE_44).register("m44ap"));
m44_express = new BulletConfig().setItem(EnumAmmo.M44_EXPRESS).setCasing(EnumCasingType.SMALL, 6).setDoesPenetrate(true).setDamage(1.5F).setThresholdNegation(3F).setArmorPiercing(0.1F).setWear(1.5F)
.setCasing(casing44.clone().register("m44express"));
m44_equestrian_pip = new BulletConfig().setItem(EnumAmmoSecret.M44_EQUESTRIAN).setDamage(0F).setOnImpact(LAMBDA_BOXCAR)
.setCasing(casing44.clone().setColor(SpentCasing.COLOR_CASE_EQUESTRIAN).register("m44equestrianPip"));
m44_equestrian_mn7 = new BulletConfig().setItem(EnumAmmoSecret.M44_EQUESTRIAN).setDamage(0F).setOnImpact(LAMBDA_TORPEDO)
.setCasing(casing44.clone().setColor(SpentCasing.COLOR_CASE_EQUESTRIAN).register("m44equestrianMn7"));
ModItems.gun_henry = new ItemGunBaseNT(WeaponQuality.A_SIDE, new GunConfig()
.dura(300).draw(15).inspect(23).reloadSequential(true).crosshair(Crosshair.CIRCLE).smoke(Lego.LAMBDA_STANDARD_SMOKE)
.rec(new Receiver(0)
.dmg(10F).delay(20).reload(25, 11, 14, 8).jam(45).sound("hbm:weapon.fire.rifle", 1.0F, 1.0F)
.mag(new MagazineSingleReload(0, 14).addConfigs(m44_bp, m44_sp, m44_fmj, m44_jhp, m44_ap, m44_express))
.offset(0.75, -0.0625, -0.1875D)
.setupStandardFire().recoil(LAMBDA_RECOIL_HENRY))
.setupStandardConfiguration()
.anim(LAMBDA_HENRY_ANIMS).orchestra(Orchestras.ORCHESTRA_HENRY)
).setUnlocalizedName("gun_henry");
ModItems.gun_henry_lincoln = new ItemGunBaseNT(WeaponQuality.B_SIDE, new GunConfig()
.dura(300).draw(15).inspect(23).reloadSequential(true).crosshair(Crosshair.CIRCLE).smoke(Lego.LAMBDA_STANDARD_SMOKE)
.rec(new Receiver(0)
.dmg(20F).spreadHipfire(0F).delay(20).reload(25, 11, 14, 8).jam(45).sound("hbm:weapon.fire.rifle", 1.0F, 1.25F)
.mag(new MagazineSingleReload(0, 14).addConfigs(m44_bp, m44_sp, m44_fmj, m44_jhp, m44_ap, m44_express))
.offset(0.75, -0.0625, -0.1875D)
.setupStandardFire().recoil(LAMBDA_RECOIL_HENRY))
.setupStandardConfiguration()
.anim(LAMBDA_HENRY_ANIMS).orchestra(Orchestras.ORCHESTRA_HENRY)
).setUnlocalizedName("gun_henry_lincoln");
ModItems.gun_heavy_revolver = new ItemGunBaseNT(WeaponQuality.A_SIDE, new GunConfig()
.dura(600).draw(10).inspect(23).crosshair(Crosshair.L_CLASSIC).smoke(Lego.LAMBDA_STANDARD_SMOKE)
.rec(new Receiver(0)
.dmg(15F).delay(14).reload(46).jam(23).sound("hbm:weapon.44Shoot", 1.0F, 1.0F)
.mag(new MagazineFullReload(0, 6).addConfigs(m44_bp, m44_sp, m44_fmj, m44_jhp, m44_ap, m44_express))
.offset(0.75, -0.0625, -0.3125D)
.setupStandardFire().recoil(LAMBDA_RECOIL_NOPIP))
.setupStandardConfiguration()
.anim(LAMBDA_NOPIP_ANIMS).orchestra(Orchestras.ORCHESTRA_NOPIP)
).setNameMutator(LAMBDA_NAME_NOPIP)
.setUnlocalizedName("gun_heavy_revolver");
ModItems.gun_heavy_revolver_lilmac = new ItemGunBaseNT(WeaponQuality.LEGENDARY, new GunConfig()
.dura(31_000).draw(10).inspect(23).crosshair(Crosshair.L_CLASSIC).scopeTexture(scope_lilmac).smoke(Lego.LAMBDA_STANDARD_SMOKE)
.rec(new Receiver(0)
.dmg(30F).delay(14).reload(46).jam(23).sound("hbm:weapon.44Shoot", 1.0F, 1.0F)
.mag(new MagazineFullReload(0, 6).addConfigs(m44_equestrian_pip, m44_bp, m44_sp, m44_fmj, m44_jhp, m44_ap, m44_express))
.offset(0.75, -0.0625, -0.3125D)
.setupStandardFire().recoil(LAMBDA_RECOIL_NOPIP))
.setupStandardConfiguration()
.anim(LAMBDA_LILMAC_ANIMS).orchestra(Orchestras.ORCHESTRA_NOPIP)
).setUnlocalizedName("gun_heavy_revolver_lilmac");
ModItems.gun_heavy_revolver_protege = new ItemGunBaseNT(WeaponQuality.LEGENDARY, new GunConfig()
.dura(31_000).draw(10).inspect(23).crosshair(Crosshair.L_CLASSIC).smoke(Lego.LAMBDA_STANDARD_SMOKE)
.rec(new Receiver(0)
.dmg(30F).delay(14).reload(46).jam(23).sound("hbm:weapon.44Shoot", 1.0F, 0.8F)
.mag(new MagazineFullReload(0, 6).addConfigs(m44_equestrian_mn7, m44_bp, m44_sp, m44_fmj, m44_jhp, m44_ap, m44_express))
.offset(0.75, -0.0625, -0.3125D)
.setupStandardFire().recoil(LAMBDA_RECOIL_NOPIP))
.setupStandardConfiguration()
.anim(LAMBDA_LILMAC_ANIMS).orchestra(Orchestras.ORCHESTRA_NOPIP)
).setUnlocalizedName("gun_heavy_revolver_protege");
ModItems.gun_hangman = new ItemGunBaseNT(WeaponQuality.LEGENDARY, new GunConfig()
.dura(600).draw(10).inspect(31).inspectCancel(false).crosshair(Crosshair.CIRCLE).smoke(Lego.LAMBDA_STANDARD_SMOKE)
.rec(new Receiver(0)
.dmg(25F).delay(10).reload(46).jam(23).sound("hbm:weapon.44Shoot", 1.0F, 1.0F)
.mag(new MagazineFullReload(0, 8).addConfigs(m44_bp, m44_sp, m44_fmj, m44_jhp, m44_ap, m44_express))
.offset(1, -0.0625 * 2.5, -0.25D)
.setupStandardFire().recoil(LAMBDA_RECOIL_HANGMAN))
.setupStandardConfiguration().ps(SMACK_A_FUCKER)
.anim(LAMBDA_HANGMAN_ANIMS).orchestra(Orchestras.ORCHESTRA_HANGMAN)
).setUnlocalizedName("gun_hangman");
}
public static Function<ItemStack, String> LAMBDA_NAME_NOPIP = (stack) -> {
if(WeaponModManager.hasUpgrade(stack, 0, WeaponModManager.ID_SCOPE)) return stack.getUnlocalizedName() + "_scoped";
return null;
};
public static BiConsumer<ItemStack, LambdaContext> SMACK_A_FUCKER = (stack, ctx) -> {
if(ItemGunBaseNT.getState(stack, ctx.configIndex) == GunState.IDLE || ItemGunBaseNT.getLastAnim(stack, ctx.configIndex) == GunAnimation.CYCLE) {
ItemGunBaseNT.setIsAiming(stack, false);
ItemGunBaseNT.setState(stack, ctx.configIndex, GunState.DRAWING);
ItemGunBaseNT.setTimer(stack, ctx.configIndex, ctx.config.getInspectDuration(stack));
ItemGunBaseNT.playAnimation(ctx.getPlayer(), stack, GunAnimation.INSPECT, ctx.configIndex);
}
};
public static BiConsumer<ItemStack, LambdaContext> LAMBDA_RECOIL_HENRY = (stack, ctx) -> {
ItemGunBaseNT.setupRecoil(5, (float) (ctx.getPlayer().getRNG().nextGaussian() * 1));
};
public static BiConsumer<ItemStack, LambdaContext> LAMBDA_RECOIL_NOPIP = (stack, ctx) -> {
ItemGunBaseNT.setupRecoil(10, (float) (ctx.getPlayer().getRNG().nextGaussian() * 1.5));
};
public static BiConsumer<ItemStack, LambdaContext> LAMBDA_RECOIL_HANGMAN = (stack, ctx) -> {
ItemGunBaseNT.setupRecoil(5, (float) (ctx.getPlayer().getRNG().nextGaussian() * 1));
};
@SuppressWarnings("incomplete-switch") public static BiFunction<ItemStack, GunAnimation, BusAnimation> LAMBDA_HENRY_ANIMS = (stack, type) -> {
switch(type) {
case EQUIP: return new BusAnimation()
.addBus("EQUIP", new BusAnimationSequence().addPos(-90, 0, 0, 0).addPos(0, 0, -3, 350, IType.SIN_DOWN))
.addBus("SIGHT", new BusAnimationSequence().addPos(80, 0, 0, 0).addPos(80, 0, 0, 500).addPos(0, 0, -3, 250, IType.SIN_DOWN));
case CYCLE: return new BusAnimation()
.addBus("RECOIL", new BusAnimationSequence().addPos(0, 0, 0, 50).addPos(0, 0, -1, 50).addPos(0, 0, 0, 250))
.addBus("SIGHT", new BusAnimationSequence().addPos(35, 0, 0, 100, IType.SIN_DOWN).addPos(0, 0, 0, 100, IType.SIN_FULL))
.addBus("LEVER", new BusAnimationSequence().addPos(0, 0, 0, 600).addPos(-90, 0, 0, 200).addPos(0, 0, 0, 200))
.addBus("TURN", new BusAnimationSequence().addPos(0, 0, 0, 600).addPos(0, 0, 45, 200, IType.SIN_DOWN).addPos(0, 0, 0, 200, IType.SIN_UP))
.addBus("HAMMER", new BusAnimationSequence().addPos(30, 0, 0, 50).addPos(30, 0, 0, 550).addPos(0, 0, 0, 200));
case CYCLE_DRY: return new BusAnimation()
.addBus("LEVER", new BusAnimationSequence().addPos(0, 0, 0, 600).addPos(-90, 0, 0, 200).addPos(0, 0, 0, 200))
.addBus("TURN", new BusAnimationSequence().addPos(0, 0, 0, 600).addPos(0, 0, 45, 200, IType.SIN_DOWN).addPos(0, 0, 0, 200, IType.SIN_UP))
.addBus("HAMMER", new BusAnimationSequence().addPos(30, 0, 0, 50).addPos(30, 0, 0, 550).addPos(0, 0, 0, 200));
case RELOAD: return new BusAnimation()
.addBus("LIFT", new BusAnimationSequence().addPos(-60, 0, 0, 400, IType.SIN_FULL))
.addBus("TWIST", new BusAnimationSequence().addPos(0, 0, 0, 500).addPos(0, 0, -90, 200, IType.SIN_FULL))
.addBus("BULLET", new BusAnimationSequence().addPos(0, 0, 0, 700).addPos(3, 0, -6, 0).addPos(0, 0, 1, 300, IType.SIN_FULL).addPos(0, 0, 0, 250, IType.SIN_FULL));
case RELOAD_CYCLE: return new BusAnimation()
.addBus("LIFT", new BusAnimationSequence().addPos(-60, 0, 0, 0))
.addBus("TWIST", new BusAnimationSequence().addPos(0, 0, -90, 0))
.addBus("BULLET", new BusAnimationSequence().addPos(3, 0, -6, 0).addPos(0, 0, 1, 300, IType.SIN_FULL).addPos(0, 0, 0, 250, IType.SIN_FULL));
case RELOAD_END:
boolean empty = ((ItemGunBaseNT) stack.getItem()).getConfig(stack, 0).getReceivers(stack)[0].getMagazine(stack).getAmountBeforeReload(stack) <= 0;
return new BusAnimation()
.addBus("LIFT", new BusAnimationSequence().addPos(-60, 0, 0, 0).addPos(-60, 0, 0, 300).addPos(0, 0, 0, 400, IType.SIN_FULL))
.addBus("TWIST", new BusAnimationSequence().addPos(0, 0, -90, 0).addPos(0, 0, 0, 200, IType.SIN_FULL))
.addBus("LEVER", new BusAnimationSequence().addPos(0, 0, 0, 700).addPos(empty ? -90 : 0, 0, 0, 200).addPos(0, 0, 0, 200))
.addBus("TURN", new BusAnimationSequence().addPos(0, 0, 0, 700).addPos(0, 0, empty ? 45 : 0, 200, IType.SIN_DOWN).addPos(0, 0, 0, 200, IType.SIN_UP));
case JAMMED: return new BusAnimation()
.addBus("LIFT", new BusAnimationSequence().addPos(-60, 0, 0, 0).addPos(-60, 0, 0, 300).addPos(0, 0, 0, 400, IType.SIN_FULL))
.addBus("TWIST", new BusAnimationSequence().addPos(0, 0, -90, 0).addPos(0, 0, 0, 200, IType.SIN_FULL))
.addBus("LEVER", new BusAnimationSequence().addPos(0, 0, 0, 700).addPos(-90, 0, 0, 200).addPos(0, 0, 0, 200).addPos(0, 0, 0, 500).addPos(-90, 0, 0, 200).addPos(0, 0, 0, 200).addPos(0, 0, 0, 200).addPos(-90, 0, 0, 200).addPos(0, 0, 0, 200))
.addBus("TURN", new BusAnimationSequence().addPos(0, 0, 0, 700).addPos(0, 0, 45, 200, IType.SIN_DOWN).addPos(0, 0, 0, 200, IType.SIN_UP).addPos(0, 0, 0, 500).addPos(0, 0, 45, 200, IType.SIN_FULL).addPos(0, 0, 45, 600).addPos(0, 0, 0, 200, IType.SIN_FULL));
case INSPECT: return new BusAnimation()
.addBus("YEET", new BusAnimationSequence().addPos(0, 2, 0, 200, IType.SIN_DOWN).addPos(0, 0, 0, 200, IType.SIN_UP))
.addBus("ROLL", new BusAnimationSequence().addPos(0, 0, 360, 400));
}
return null;
};
@SuppressWarnings("incomplete-switch") public static BiFunction<ItemStack, GunAnimation, BusAnimation> LAMBDA_NOPIP_ANIMS = (stack, type) -> {
switch(type) {
case CYCLE: return new BusAnimation()
.addBus("RECOIL", new BusAnimationSequence().addPos(0, 0, 0, 50).addPos(0, 0, -3, 50).addPos(0, 0, 0, 250))
.addBus("HAMMER", new BusAnimationSequence().addPos(0, 0, 1, 50).addPos(0, 0, 1, 400).addPos(0, 0, 0, 200))
.addBus("DRUM", new BusAnimationSequence().addPos(0, 0, 0, 450).addPos(0, 0, 1, 200));
case CYCLE_DRY: return new BusAnimation()
.addBus("HAMMER", new BusAnimationSequence().addPos(0, 0, 1, 50).addPos(0, 0, 1, 300 + 100).addPos(0, 0, 0, 200))
.addBus("DRUM", new BusAnimationSequence().addPos(0, 0, 0, 450).addPos(0, 0, 1, 200));
case EQUIP: return new BusAnimation().addBus("ROTATE", new BusAnimationSequence().addPos(90, 0, 0, 0).addPos(0, 0, 0, 500, IType.SIN_DOWN));
case RELOAD: return new BusAnimation()
.addBus("RELAOD_TILT", new BusAnimationSequence().addPos(-15, 0, 0, 100).addPos(65, 0, 0, 100).addPos(45, 0, 0, 50).addPos(0, 0, 0, 200).addPos(0, 0, 0, 1450).addPos(-80, 0, 0, 100).addPos(-80, 0, 0, 100).addPos(0, 0, 0, 200))
.addBus("RELOAD_CYLINDER", new BusAnimationSequence().addPos(0, 0, 0, 200).addPos(90, 0, 0, 100).addPos(90, 0, 0, 1700).addPos(0, 0, 0, 70))
.addBus("RELOAD_LIFT", new BusAnimationSequence().addPos(0, 0, 0, 350).addPos(-45, 0, 0, 250).addPos(-45, 0, 0, 350).addPos(-15, 0, 0, 200).addPos(-15, 0, 0, 1050).addPos(0, 0, 0, 100))
.addBus("RELOAD_JOLT", new BusAnimationSequence().addPos(0, 0, 0, 600).addPos(2, 0, 0, 50).addPos(0, 0, 0, 100))
.addBus("RELOAD_BULLETS", new BusAnimationSequence().addPos(0, 0, 0, 650).addPos(10, 0, 0, 300).addPos(10, 0, 0, 200).addPos(0, 0, 0, 700))
.addBus("RELOAD_BULLETS_CON", new BusAnimationSequence().addPos(1, 0, 0, 0).addPos(1, 0, 0, 950).addPos(0, 0, 0, 1 ) );
case INSPECT:
case JAMMED: return new BusAnimation()
.addBus("RELAOD_TILT", new BusAnimationSequence().addPos(-15, 0, 0, 100).addPos(65, 0, 0, 100).addPos(45, 0, 0, 50).addPos(0, 0, 0, 200).addPos(0, 0, 0, 200).addPos(-80, 0, 0, 100).addPos(-80, 0, 0, 100).addPos(0, 0, 0, 200))
.addBus("RELOAD_CYLINDER", new BusAnimationSequence().addPos(0, 0, 0, 200).addPos(90, 0, 0, 100).addPos(90, 0, 0, 450).addPos(0, 0, 0, 70));
}
return null;
};
@SuppressWarnings("incomplete-switch") public static BiFunction<ItemStack, GunAnimation, BusAnimation> LAMBDA_LILMAC_ANIMS = (stack, type) -> {
switch(type) {
case EQUIP: return new BusAnimation().addBus("SPIN", new BusAnimationSequence().addPos(-360, 0, 0, 350));
}
return LAMBDA_NOPIP_ANIMS.apply(stack, type);
};
@SuppressWarnings("incomplete-switch") public static BiFunction<ItemStack, GunAnimation, BusAnimation> LAMBDA_HANGMAN_ANIMS = (stack, type) -> {
switch(type) {
case EQUIP: return new BusAnimation().addBus("EQUIP", new BusAnimationSequence().addPos(60, 0, 0, 0).addPos(0, 0, 0, 500, IType.SIN_DOWN));
case CYCLE: return new BusAnimation()
.addBus("RECOIL", new BusAnimationSequence().addPos(0, 0, 0, 50).addPos(0, 0, -3, 50).addPos(0, 0, 0, 250));
case RELOAD: return new BusAnimation()
.addBus("LID", new BusAnimationSequence().addPos(0, 0, -90, 250).addPos(0, 0, -90, 1500).addPos(0, 0, 0, 250))
.addBus("MAG", new BusAnimationSequence().addPos(0, 0, 0, 250).addPos(0, -10, 0, 250, IType.SIN_UP).addPos(0, -10, 0, 500).addPos(0, 0, 0, 350, IType.SIN_FULL))
.addBus("BULLETS", new BusAnimationSequence().addPos(1, 1, 1, 0).addPos(0, 0, 0, 500))
.addBus("EQUIP", new BusAnimationSequence().addPos(-15, 0, 0, 500, IType.SIN_FULL).addPos(-15, 0, 0, 850).addPos(-25, 0, 0, 100, IType.SIN_DOWN).addPos(0, 0, 0, 350, IType.SIN_FULL))
.addBus("ROLL", new BusAnimationSequence().addPos(0, 0, 0, 500).addPos(0, 0, 25, 250, IType.SIN_FULL).addPos(0, 0, 25, 1000).addPos(0, 0, 0, 250, IType.SIN_FULL));
case INSPECT: return new BusAnimation()
.addBus("TURN", new BusAnimationSequence().addPos(0, 170, 0, 500, IType.SIN_UP).addPos(0, 170, 0, 550).addPos(0, 0, 0, 500, IType.SIN_FULL))
.addBus("ROLL", new BusAnimationSequence().addPos(0, 0, 110, 500, IType.SIN_FULL).addPos(0, 0, 110, 550).addPos(0, 0, 0, 500, IType.SIN_FULL))
.addBus("SMACK", new BusAnimationSequence().addPos(0, 0, 0, 500).addPos(0, 0, 1, 150, IType.SIN_DOWN).addPos(0, 0, -3, 150, IType.SIN_UP).addPos(0, 0, 0, 350, IType.SIN_FULL));
case JAMMED: return new BusAnimation()
.addBus("LID", new BusAnimationSequence().addPos(0, 0, 0, 500).addPos(0, 0, -90, 250).addPos(0, 0, -90, 300).addPos(0, 0, 0, 250))
.addBus("MAG", new BusAnimationSequence().addPos(0, 0, 0, 500).addPos(0, 0, 0, 250).addPos(0, -3, 0, 150, IType.SIN_UP).addPos(0, 0, 0, 150, IType.SIN_FULL))
.addBus("EQUIP", new BusAnimationSequence().addPos(0, 0, 0, 1000).addPos(-10, 0, 0, 100, IType.SIN_DOWN).addPos(0, 0, 0, 350, IType.SIN_FULL))
.addBus("ROLL", new BusAnimationSequence().addPos(0, 0, 0, 500).addPos(0, 0, 25, 250, IType.SIN_FULL).addPos(0, 0, 25, 300).addPos(0, 0, 0, 250, IType.SIN_FULL));
}
return null;
};
}
| 0 | 0.659126 | 1 | 0.659126 | game-dev | MEDIA | 0.956406 | game-dev | 0.947011 | 1 | 0.947011 |
amazon-gamelift/amazon-gamelift-plugin-unreal | 1,764 | GameLiftPlugin/Source/GameLiftPlugin/Private/SMenu/SGameLiftSettingsUseCaseMenu.cpp | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
#include "SGameLiftSettingsUseCaseMenu.h"
#include "ImageUtils.h"
#include "Interfaces/IPluginManager.h"
#include "Widgets/Text/SRichTextBlock.h"
#include "GameLiftPluginConstants.h"
#include "GameLiftPluginStyle.h"
#include "SWidgets/SOnlineHyperlink.h"
#define LOCTEXT_NAMESPACE "SGameLiftSettingsUseCaseMenu"
void SGameLiftSettingsUseCaseMenu::Construct(const FArguments& InArgs)
{
LoadImages();
}
void SGameLiftSettingsUseCaseMenu::LoadImages()
{
// Stub for future development.
}
TSharedRef<SWidget> SGameLiftSettingsUseCaseMenu::MakeUseCaseWidget(const FText& GameName, const FText& DeveloperName, const FString& BlogLink, const FSlateBrush* ImageBrush, FVector2D ImageSize) const
{
return SNew(SVerticalBox)
// Image
+ SVerticalBox::Slot()
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
.AutoHeight()
.Padding(SPadding::Top_Bottom)
[
SNew(SBox)
.HAlign(HAlign_Fill)
.VAlign(VAlign_Fill)
.WidthOverride(ImageSize.X)
.HeightOverride(ImageSize.Y)
[
SNew(SImage)
.Image(ImageBrush)
]
]
// Title
+ SVerticalBox::Slot()
.Padding(SPadding::Top + SPadding::Left_Right)
.FillHeight(1.0)
[
SNew(SRichTextBlock)
.Text(FText::Format(Settings::UseCase::kUseCaseTitleFormatText, DeveloperName, GameName))
.TextStyle(FGameLiftPluginStyle::Get(), Style::Text::kParagraph)
.DecoratorStyleSet(&FGameLiftPluginStyle::Get())
.AutoWrapText(true)
]
// Blog link
+ SVerticalBox::Slot()
.HAlign(HAlign_Left)
.Padding(SPadding::All)
.AutoHeight()
[
SNew(SOnlineHyperlink)
.Text(Settings::UseCase::kUseCaseLearnMoreText)
.Link(BlogLink)
]
;
}
#undef LOCTEXT_NAMESPACE
| 0 | 0.866553 | 1 | 0.866553 | game-dev | MEDIA | 0.561742 | game-dev,graphics-rendering | 0.928861 | 1 | 0.928861 |
MegaMek/megamek | 3,077 | megamek/src/megamek/common/weapons/capitalWeapons/naval/NPPCWeaponMedium.java | /*
* Copyright (C) 2004, 2005 Ben Mazur (bmazur@sev.org)
* Copyright (C) 2008-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.capitalWeapons.naval;
import java.io.Serial;
import megamek.common.enums.AvailabilityValue;
import megamek.common.enums.Faction;
import megamek.common.enums.TechBase;
import megamek.common.enums.TechRating;
/**
* @author Jay Lawson
* @since Sep 25, 2004
*/
public class NPPCWeaponMedium extends NPPCWeapon {
@Serial
private static final long serialVersionUID = 8756042527483383101L;
public NPPCWeaponMedium() {
super();
name = "Naval PPC (Medium)";
setInternalName(this.name);
addLookupName("MediumNPPC");
addLookupName("Medium NPPC (Clan)");
shortName = "Medium NPPC";
sortingName = "PPC Naval C";
heat = 135;
damage = 9;
shortRange = 12;
mediumRange = 24;
longRange = 36;
extremeRange = 48;
tonnage = 1800.0;
bv = 2268.0;
cost = 3250000;
shortAV = 9;
medAV = 9;
longAV = 9;
extAV = 9;
maxRange = RANGE_EXT;
rulesRefs = "333, TO";
techAdvancement.setTechBase(TechBase.ALL)
.setIntroLevel(false)
.setUnofficial(false)
.setTechRating(TechRating.D)
.setAvailability(AvailabilityValue.D, AvailabilityValue.X, AvailabilityValue.E, AvailabilityValue.E)
.setISAdvancement(2350, 2356, DATE_NONE, 2950, 3052)
.setISApproximate(true, true, false, true, false)
.setClanAdvancement(2350, 2356, DATE_NONE, DATE_NONE, DATE_NONE)
.setClanApproximate(true, true, false, false, false)
.setProductionFactions(Faction.TH)
.setReintroductionFactions(Faction.DC);
}
}
| 0 | 0.714102 | 1 | 0.714102 | game-dev | MEDIA | 0.910259 | game-dev | 0.653725 | 1 | 0.653725 |
moq/labs | 1,597 | src/Moq.Tests/Mocks/IRefOutParentMock.cs | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using Moq.Tests.RefOut;
using System.Threading;
using Moq.Sdk;
using System;
using System.Collections.ObjectModel;
using System.Reflection;
using Stunts;
using System.Runtime.CompilerServices;
namespace Mocks
{
public partial class IRefOutParentMock : IRefOutParent, IStunt, IMocked
{
readonly BehaviorPipeline pipeline = new BehaviorPipeline();
IMock mock;
[CompilerGenerated]
ObservableCollection<IStuntBehavior> IStunt.Behaviors => pipeline.Behaviors;
IMock IMocked.Mock => LazyInitializer.EnsureInitialized(ref mock, () => new DefaultMock(this));
[CompilerGenerated]
public IRefOut RefOut => pipeline.Execute<IRefOut>(new MethodInvocation(this, MethodBase.GetCurrentMethod()));
[CompilerGenerated]
public override bool Equals(object obj) => pipeline.Execute<bool>(new MethodInvocation(this, MethodBase.GetCurrentMethod(), obj));
[CompilerGenerated]
public override int GetHashCode() => pipeline.Execute<int>(new MethodInvocation(this, MethodBase.GetCurrentMethod()));
[CompilerGenerated]
public override string ToString() => pipeline.Execute<string>(new MethodInvocation(this, MethodBase.GetCurrentMethod()));
}
} | 0 | 0.823046 | 1 | 0.823046 | game-dev | MEDIA | 0.245806 | game-dev | 0.588287 | 1 | 0.588287 |
BlueMap-Minecraft/BlueMap | 2,185 | core/src/main/java/de/bluecolored/bluemap/core/world/mca/data/LenientBlockEntityArrayDeserializer.java | /*
* This file is part of BlueMap, licensed under the MIT License (MIT).
*
* Copyright (c) Blue (Lukas Rieger) <https://bluecolored.de>
* Copyright (c) contributors
*
* 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 de.bluecolored.bluemap.core.world.mca.data;
import de.bluecolored.bluemap.core.world.BlockEntity;
import de.bluecolored.bluenbt.*;
import java.io.IOException;
/**
* TypeSerializer that returns a default value instead of failing when the serialized field is of the wrong type
*/
public class LenientBlockEntityArrayDeserializer implements TypeDeserializer<BlockEntity[]> {
private static final BlockEntity[] EMPTY_BLOCK_ENTITIES_ARRAY = new BlockEntity[0];
private final TypeDeserializer<BlockEntity[]> delegate;
public LenientBlockEntityArrayDeserializer(BlueNBT blueNBT) {
delegate = blueNBT.getTypeDeserializer(new TypeToken<>(){});
}
@Override
public BlockEntity[] read(NBTReader reader) throws IOException {
if (reader.peek() != TagType.LIST) {
reader.skip();
return EMPTY_BLOCK_ENTITIES_ARRAY;
}
return delegate.read(reader);
}
}
| 0 | 0.78741 | 1 | 0.78741 | game-dev | MEDIA | 0.796474 | game-dev | 0.606336 | 1 | 0.606336 |
bozimmerman/CoffeeMud | 5,348 | com/planet_ink/coffee_mud/Races/Calf.java | package com.planet_ink.coffee_mud.Races;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2002-2025 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class Calf extends Cow
{
@Override
public String ID()
{
return "Calf";
}
private final static String localizedStaticName = CMLib.lang().L("Cow");
@Override
public String name()
{
return localizedStaticName;
}
@Override
public int shortestMale()
{
return 36;
}
@Override
public int shortestFemale()
{
return 36;
}
@Override
public int heightVariance()
{
return 6;
}
@Override
public int lightestWeight()
{
return 150;
}
@Override
public int weightVariance()
{
return 100;
}
private final static String localizedStaticRacialCat = CMLib.lang().L("Bovine");
@Override
public String racialCategory()
{
return localizedStaticRacialCat;
}
private final String[] racialAbilityNames = { "CowSpeak", "Adorable", "Grazing" };
private final int[] racialAbilityLevels = { 1, 3, 1 };
private final int[] racialAbilityProficiencies = { 100, 100, 100 };
private final boolean[] racialAbilityQuals = { false, false, false };
private final String[] racialAbilityParms = { "", "", "" };
@Override
protected String[] racialAbilityNames()
{
return racialAbilityNames;
}
@Override
protected int[] racialAbilityLevels()
{
return racialAbilityLevels;
}
@Override
protected int[] racialAbilityProficiencies()
{
return racialAbilityProficiencies;
}
@Override
protected boolean[] racialAbilityQuals()
{
return racialAbilityQuals;
}
@Override
public String[] racialAbilityParms()
{
return racialAbilityParms;
}
// an ey ea he ne ar ha to le fo no gi mo wa ta wi
private static final int[] parts={0 ,2 ,2 ,1 ,1 ,0 ,0 ,1 ,4 ,4 ,1 ,0 ,1 ,1 ,1 ,0 };
@Override
public int[] bodyMask()
{
return parts;
}
protected static Vector<RawMaterial> resources=new Vector<RawMaterial>();
@Override
public void affectCharStats(final MOB affectedMOB, final CharStats affectableStats)
{
super.affectCharStats(affectedMOB, affectableStats);
affectableStats.setRacialStat(CharStats.STAT_STRENGTH,10);
affectableStats.setRacialStat(CharStats.STAT_DEXTERITY,5);
affectableStats.setRacialStat(CharStats.STAT_INTELLIGENCE,1);
}
@Override
public void unaffectCharStats(final MOB affectedMOB, final CharStats affectableStats)
{
super.unaffectCharStats(affectedMOB, affectableStats);
affectableStats.setStat(CharStats.STAT_STRENGTH,affectedMOB.baseCharStats().getStat(CharStats.STAT_STRENGTH));
affectableStats.setStat(CharStats.STAT_MAX_STRENGTH_ADJ,affectedMOB.baseCharStats().getStat(CharStats.STAT_MAX_STRENGTH_ADJ));
affectableStats.setStat(CharStats.STAT_DEXTERITY,affectedMOB.baseCharStats().getStat(CharStats.STAT_DEXTERITY));
affectableStats.setStat(CharStats.STAT_MAX_DEXTERITY_ADJ,affectedMOB.baseCharStats().getStat(CharStats.STAT_MAX_DEXTERITY_ADJ));
affectableStats.setStat(CharStats.STAT_INTELLIGENCE,affectedMOB.baseCharStats().getStat(CharStats.STAT_INTELLIGENCE));
affectableStats.setStat(CharStats.STAT_MAX_INTELLIGENCE_ADJ,affectedMOB.baseCharStats().getStat(CharStats.STAT_MAX_INTELLIGENCE_ADJ));
}
@Override
public boolean canBreedWith(final Race R, final boolean crossBreed)
{
return false; // too young
}
@Override
public List<RawMaterial> myResources()
{
synchronized(resources)
{
if(resources.size()==0)
{
resources.addElement(makeResource
(L("a pair of @x1 hooves",name().toLowerCase()),RawMaterial.RESOURCE_BONE));
resources.addElement(makeResource
(L("a strip of @x1 leather",name().toLowerCase()),RawMaterial.RESOURCE_LEATHER));
resources.addElement(makeResource
(L("some @x1 meat",name().toLowerCase()),RawMaterial.RESOURCE_BEEF));
resources.addElement(makeResource
(L("some @x1 blood",name().toLowerCase()),RawMaterial.RESOURCE_BLOOD));
resources.addElement(makeResource
(L("a pile of @x1 bones",name().toLowerCase()),RawMaterial.RESOURCE_BONE));
}
}
return resources;
}
}
| 0 | 0.872832 | 1 | 0.872832 | game-dev | MEDIA | 0.480238 | game-dev | 0.757283 | 1 | 0.757283 |
rudderbucky/shellcore | 4,313 | Assets/Scripts/Game Object Definitions/Flag.cs | using UnityEngine;
using UnityEngine.SceneManagement;
using static CoreScriptsManager;
using static CoreScriptsSequence;
[RequireComponent(typeof(SpriteRenderer))]
public class Flag : MonoBehaviour, IInteractable
{
public FlagInteractibility interactibility;
public string sectorName;
public string entityID;
public Sequence sequence;
public Context context;
public delegate void EntityRangeCheckDelegate(float range);
public EntityRangeCheckDelegate RangeCheckDelegate;
private void Update()
{
if (RangeCheckDelegate != null && PlayerCore.Instance)
{
RangeCheckDelegate.Invoke(Vector2.SqrMagnitude(PlayerCore.Instance.transform.position - transform.position));
}
}
public static void FindEntityAndWarpPlayer(string sectorName, string entityID, bool alsoCheckFlagName = false)
{
// need player to warp
if (!PlayerCore.Instance)
{
return;
}
// use sectorName and entityID to find the transform to warp to
var sector = SectorManager.GetSectorByName(sectorName);
if (sector == null)
{
Debug.LogWarning("<Flag> Cannot find specified sector");
return;
}
else
{
Debug.Log($"<Flag> Sector Name: {sector.sectorName}");
var dimensionChanged = PlayerCore.Instance.Dimension != sector.dimension;
PlayerCore.Instance.Dimension = sector.dimension;
// TODO: We currently nuke all characters when teleporting to a different dimension. It would be nicer to have
// a set dimension for each character which is appropriately used.
if (dimensionChanged)
{
foreach (var ent in AIData.entities)
{
if (!(PartyManager.instance && PartyManager.instance.partyMembers != null && ent is ShellCore shellCore &&
PartyManager.instance.partyMembers.Contains(shellCore)) && ent != PlayerCore.Instance)
foreach (var data in SectorManager.instance.characters)
{
if (data.ID == ent.ID)
{
Destroy(ent.gameObject);
}
}
}
}
}
bool found = false;
foreach (var ent in sector.entities)
{
if (ent.ID == entityID || (alsoCheckFlagName && ent.assetID == "flag" && ent.name == entityID))
{
// position is a global vector (i.e., not local to the sector itself), so this should work
PlayerCore.Instance.Warp(ent.position);
found = true;
break;
}
}
if (!found) Debug.LogWarning($"<Flag> Cannot find specified entityID: {entityID}");
}
public void Interact()
{
switch (interactibility)
{
case FlagInteractibility.Warp:
FindEntityAndWarpPlayer(sectorName, entityID);
break;
case FlagInteractibility.Sequence:
CoreScriptsSequence.RunSequence(sequence, context);
break;
}
}
public bool GetInteractible()
{
return interactibility != FlagInteractibility.None;
}
public Transform GetTransform()
{
return transform;
}
private void OnEnable()
{
if (SceneManager.GetActiveScene().name != "SectorCreator" && SceneManager.GetActiveScene().name != "WorldCreator")
{
AIData.flags.Add(this);
AIData.interactables.Add(this);
}
}
private void OnDisable()
{
if (SceneManager.GetActiveScene().name != "SectorCreator" && SceneManager.GetActiveScene().name != "WorldCreator")
{
AIData.flags.Remove(this);
AIData.interactables.Remove(this);
ProximityInteractScript.RemoveFlagText(this);
}
}
private void Start()
{
if (SceneManager.GetActiveScene().name != "SectorCreator" && SceneManager.GetActiveScene().name != "WorldCreator")
{
GetComponent<SpriteRenderer>().enabled = false;
}
}
}
| 0 | 0.908464 | 1 | 0.908464 | game-dev | MEDIA | 0.987158 | game-dev | 0.944403 | 1 | 0.944403 |
japsuu/KorpiEngine | 2,066 | src/Core/Entities/Entity.Systems.cs | using KorpiEngine.Utils;
namespace KorpiEngine.Entities;
public sealed partial class Entity
{
public void AddSystem<T>() where T : class, IEntitySystem, new()
{
if (IsDestroyed)
throw new InvalidOperationException($"Entity {InstanceID} has been destroyed.");
T system = new();
ulong typeId = TypeID.Get<T>();
if (system.IsSingleton && _systems.ContainsKey(typeId))
throw new InvalidOperationException($"Entity {InstanceID} already has a singleton system of type {typeof(T).Name}.");
if (system.UpdateStages.Length <= 0)
throw new InvalidOperationException($"System of type {typeof(T).Name} does not specify when it should be updated.");
_systems.Add(typeId, system);
_systemBuckets.AddSystem(typeId, system);
system.OnRegister(this);
}
public void RemoveSystem<T>() where T : class, IEntitySystem
{
if (IsDestroyed)
throw new InvalidOperationException($"Entity {InstanceID} has been destroyed.");
ulong typeId = TypeID.Get<T>();
if (!_systems.Remove(typeId, out IEntitySystem? system))
throw new InvalidOperationException($"Entity {InstanceID} does not have a system of type {typeof(T).Name}.");
_systemBuckets.RemoveSystem(typeId);
system.OnUnregister(this);
}
private void RemoveAllSystems()
{
foreach (IEntitySystem system in _systems.Values)
system.OnUnregister(this);
_systems.Clear();
_systemBuckets.Clear();
}
private void RegisterComponentWithSystems(EntityComponent component)
{
foreach (IEntitySystem system in _systems.Values)
system.TryRegisterComponent(component);
_scene?.RegisterComponent(component);
}
private void UnregisterComponentWithSystems(EntityComponent component)
{
foreach (IEntitySystem system in _systems.Values)
system.TryUnregisterComponent(component);
_scene?.UnregisterComponent(component);
}
} | 0 | 0.715804 | 1 | 0.715804 | game-dev | MEDIA | 0.909765 | game-dev | 0.695727 | 1 | 0.695727 |
NEIAPI/nei | 7,565 | public/src/lib/nej/src/util/region/zh.js | /*
* ------------------------------------------
* 三级联动区域选择控件实现文件
* @version 1.0
* @author genify(caijf@corp.netease.com)
* ------------------------------------------
*/
/** @module util/region/zh */
NEJ.define([
'base/global',
'base/klass',
'base/element',
'base/util',
'util/event'
],function(NEJ,_k,_e,_u,_t,_p,_o,_f,_r){
var _pro;
/**
* 三级联动区域选择控件
*
* 结构举例
* ```html
* <div>
* <select id="a"></select>
* <select id="b"></select>
* <select id="c"></select>
* </div>
* ```
*
* 脚本举例
* ```javascript
* NEJ.define([
* 'util/region/zh',
* 'util/data/region/zh'
* ],function(_t,_d){
* var _region = _t._$$RegionSelector._$allocate({
* province:'a',
* city:'b',
* area:'c',
* data:{province:'浙江省',city:'杭州市',area:'滨江区'},
* cache:_d._$$CacheRegionZH._$allocate(),
* onchange:function(_type){
* // 触发3次type,从area到province,搜索条件可能用到
* }
* });
* });
* ```
*
* @class module:util/region/zh._$$RegionSelector
* @extends module:util/event._$$EventTarget
*
* @param {Object} config - 可选配置参数
* @property {String|Node} province - 省份选择控件
* @property {String|Node} city - 城市选择控件
* @property {String|Node} area - 地区选择控件
* @property {module:util/cache/list._$$CacheList} cache - 数据缓存实例
* @property {Object} data - 初始地区信息,如{province:'浙江省',city:'杭州市',area:'滨江区'}
* @property {module:util/cache/abstract._$$CacheListAbstract} cache - 省市区数据缓存实例,默认可使用util/data/region/zh下的数据
*/
/**
* 区域变化触发事件
*
* @event module:util/region/zh._$$RegionSelector#onchange
* @param {String} event - 变化类型(province/city/area)
*/
_p._$$RegionSelector = _k._$klass();
_pro = _p._$$RegionSelector._$extend(_t._$$EventTarget);
/**
* 控件重置
*
* @protected
* @method module:util/region/zh._$$RegionSelector#__reset
* @param {Object} arg0 - 可选配置参数
* @return {Void}
*/
_pro.__reset = function(_options){
this.__super(_options);
this.__cache = _options.cache;
if (!this.__cache) return;
var _nmap = {
province:_e._$get(_options.province),
city:_e._$get(_options.city),
area:_e._$get(_options.area)
};
this.__selectors = _nmap;
this.__offset = _nmap.province.options.length||0;
this.__doInitDomEvent([
[_nmap.area,'change',this.__onChange._$bind(this,'area')]
,[_nmap.city,'change',this.__onChange._$bind(this,'city')]
,[_nmap.province,'change',this.__onChange._$bind(this,'province')]
]);
this.__cache._$setEvent(
'onlistload',
this.__onListLoad._$bind(this)
);
this.__doClearSelect(_nmap.province);
this._$setRegion(_options.data,!0);
this.__cache._$getList({key:'province'});
};
/**
* 控件销毁
*
* @protected
* @method module:util/region/zh._$$RegionSelector#__destroy
* @return {Void}
*/
_pro.__destroy = function(){
this.__super();
if (!!this.__cache){
this.__cache._$recycle();
delete this.__cache;
}
delete this.__cache;
delete this.__data;
delete this.__selectors;
};
/**
* 清理选择器
*
* @protected
* @method module:util/region/zh._$$RegionSelector#__doClearSelect
* @param {Node} arg0 - 选择器
* @return {Void}
*/
_pro.__doClearSelect = function(_selector){
if (!!_selector){
_selector.options.length = this.__offset;
}
};
/**
* 选择器填充数据
*
* @protected
* @method module:util/region/zh._$$RegionSelector#__doFillList
* @param {Node} arg0 - 选择器
* @param {Array} arg1 - 数据列表
* @return {Void}
*/
_pro.__doFillList = function(_selector,_list){
if (!_selector) return;
_u._$forEach(
_list,function(_value){
_selector.add(new Option(_value,_value));
}
);
_e._$setStyle(
_selector,'display',
!_list||!_list.length?'none':''
);
};
/**
* 设置值
*
* @protected
* @method module:util/region/zh._$$RegionSelector#__doSetValue
* @param {String} arg0 - 类型
* @return {Void}
*/
_pro.__doSetValue = function(_type){
var _value = this.__data[_type]||'';
if (!!_value){
this.__selectors[_type].value = _value;
delete this.__data[_type];
}
this.__onChange(_type);
};
/**
* 选择变化
*
* @protected
* @method module:util/region/zh._$$RegionSelector#__onChange
* @param {String} arg0 - 变化类型,province/city/area
* @return {Void}
*/
_pro.__onChange = function(_type){
var _nmap = this.__selectors,
_value = _nmap.province.value;
switch(_type){
case 'province':
this.__doClearSelect(_nmap.city);
this.__doClearSelect(_nmap.area);
// init show e.g. municipality
if (!this.__cache._$hasArea(_value)){
_e._$setStyle(_nmap.area,'display','none');
if (!_nmap.area){
_e._$setStyle(_nmap.city,'display','none');
break;
}else{
_e._$setStyle(_nmap.city,'display','');
}
}else{
_e._$setStyle(_nmap.area,'display','');
_e._$setStyle(_nmap.city,'display','');
}
// get city list
if (!!_nmap.city&&!!_value){
this.__cache._$getList({key:'city-'+_value});
}
break;
case 'city':
this.__doClearSelect(_nmap.area);
var _city = _nmap.city.value;
if (!_city) return;
this.__cache._$getList({key:'area-'+_value+'-'+_city});
break;
}
this._$dispatchEvent('onchange',_type);
};
/**
* 区域列表载入回调
*
* @protected
* @method module:util/region/zh._$$RegionSelector#__onListLoad
* @param {Object} arg0 - 列表信息
* @return {Void}
*/
_pro.__onListLoad = function(_options){
var _key = _options.key,
_type = _key.split('-')[0],
_node = this.__selectors[_type];
this.__doFillList(
_node,this.__cache.
_$getListInCache(_key)
);
this.__doSetValue(_type);
};
/**
* 设置区域信息
*
* 脚本举例
* ```javascript
* _region._$setRegion({
* province:'浙江省',
* city:'杭州市',
* area:'下城区'
* });
* ```
* @method module:util/region/zh._$$RegionSelector#_$setRegion
* @param {Object} arg0 - 区域信息,如{province:'浙江省',city:'杭州市',area:'滨江区'}
* @property {String} province - 省
* @property {String} city - 市
* @property {String} area - 区
* @return {Void}
*/
_pro._$setRegion = function(_data,_nochange){
this.__data = _data||_o;
if (!_nochange){
this.__doSetValue('province');
}
};
if (CMPT){
NEJ.copy(NEJ.P('nej.ut'),_p);
}
return _p;
});
| 0 | 0.954737 | 1 | 0.954737 | game-dev | MEDIA | 0.386874 | game-dev | 0.97808 | 1 | 0.97808 |
Gigantua/Gigantua | 15,271 | Gigantua/Gigantua.cpp | #include <iostream>
#include <chrono>
#include <random>
#include <cstring>
#include "Movelist.hpp"
#include "Chess_Test.hpp"
class MoveReciever
{
public:
static inline uint64_t nodes;
static _ForceInline void Init(Board& brd, uint64_t EPInit) {
MoveReciever::nodes = 0;
Movelist::Init(EPInit);
}
template<class BoardStatus status>
static _ForceInline void PerfT0()
{
nodes++;
}
template<class BoardStatus status>
static _ForceInline void PerfT1(Board& brd)
{
nodes += Movelist::count<status>(brd);
}
template<class BoardStatus status, int depth>
static _ForceInline void PerfT(Board& brd)
{
if constexpr (depth == 1)
PerfT1<status>(brd);
else
Movelist::EnumerateMoves<status, MoveReciever, depth>(brd);
}
#define ENABLEDBG 0
#define ENABLEPRINT 0
#define IFDBG if constexpr (ENABLEDBG)
#define IFPRN if constexpr (ENABLEPRINT)
template<class BoardStatus status, int depth>
static void Kingmove(const Board& brd, uint64_t from, uint64_t to)
{
Board next = Board::Move<BoardPiece::King, status.WhiteMove>(brd, from, to, to & Enemy<status.WhiteMove>(brd));
IFPRN std::cout << "Kingmove:\n" << _map(from, to, brd, next) << "\n";
//IFDBG Board::AssertBoardMove<status.WhiteMove>(brd, next, to & Enemy<status.WhiteMove>(brd));
PerfT<status.KingMove(), depth - 1>(next);
}
template<class BoardStatus status, int depth>
static void KingCastle(const Board& brd, uint64_t kingswitch, uint64_t rookswitch)
{
Board next = Board::MoveCastle<status.WhiteMove>(brd, kingswitch, rookswitch);
IFPRN std::cout << "KingCastle:\n" << _map(kingswitch, rookswitch, brd, next) << "\n";
//IFDBG Board::AssertBoardMove<status.WhiteMove>(brd, next, false);
PerfT<status.KingMove(), depth - 1>(next);
}
template<class BoardStatus status, int depth>
static void PawnCheck(map eking, uint64_t to) {
constexpr bool white = status.WhiteMove;
map pl = Pawn_AttackLeft<white>(to & Pawns_NotLeft());
map pr = Pawn_AttackRight<white>(to & Pawns_NotRight());
if (eking & (pl | pr)) Movestack::Check_Status[depth - 1] = to;
}
template<class BoardStatus status, int depth>
static void KnightCheck(map eking, uint64_t to) {
constexpr bool white = status.WhiteMove;
if (Lookup::Knight(SquareOf(eking)) & to) Movestack::Check_Status[depth - 1] = to;
}
template<class BoardStatus status, int depth>
static void Pawnmove(const Board& brd, uint64_t from, uint64_t to)
{
Board next = Board::Move<BoardPiece::Pawn, status.WhiteMove, false>(brd, from, to);
IFPRN std::cout << "Pawnmove:\n" << _map(from, to, brd, next) << "\n";
//IFDBG Board::AssertBoardMove<status.WhiteMove>(brd, next, to & Enemy<status.WhiteMove>(brd));
PawnCheck<status, depth>(EnemyKing<status.WhiteMove>(brd), to);
PerfT<status.SilentMove(), depth - 1>(next);
Movestack::Check_Status[depth - 1] = 0xffffffffffffffffull;
}
template<class BoardStatus status, int depth>
static void Pawnatk(const Board& brd, uint64_t from, uint64_t to)
{
Board next = Board::Move<BoardPiece::Pawn, status.WhiteMove, true>(brd, from, to);
IFPRN std::cout << "Pawntake:\n" << _map(from, to, brd, next) << "\n";
//IFDBG Board::AssertBoardMove<status.WhiteMove>(brd, next, to & Enemy<status.WhiteMove>(brd));
PawnCheck<status, depth>(EnemyKing<status.WhiteMove>(brd), to);
PerfT<status.SilentMove(), depth - 1>(next);
Movestack::Check_Status[depth - 1] = 0xffffffffffffffffull;
}
template<class BoardStatus status, int depth>
static void PawnEnpassantTake(const Board& brd, uint64_t from, uint64_t enemy, uint64_t to)
{
Board next = Board::MoveEP<status.WhiteMove>(brd, from, enemy, to);
IFPRN std::cout << "PawnEnpassantTake:\n" << _map(from | enemy, to, brd, next) << "\n";
//IFDBG Board::AssertBoardMove<status.WhiteMove>(brd, next, true);
PawnCheck<status, depth>(EnemyKing<status.WhiteMove>(brd), to);
PerfT<status.SilentMove(), depth - 1>(next);
Movestack::Check_Status[depth - 1] = 0xffffffffffffffffull;
}
template<class BoardStatus status, int depth>
static void Pawnpush(const Board& brd, uint64_t from, uint64_t to)
{
Board next = Board::Move <BoardPiece::Pawn, status.WhiteMove, false>(brd, from, to);
IFPRN std::cout << "Pawnpush:\n" << _map(from, to, brd, next) << "\n";
//IFDBG Board::AssertBoardMove<status.WhiteMove>(brd, next, to & Enemy<status.WhiteMove>(brd));
Movelist::EnPassantTarget = to;
PawnCheck<status, depth>(EnemyKing<status.WhiteMove>(brd), to);
PerfT<status.PawnPush(), depth - 1>(next);
Movestack::Check_Status[depth - 1] = 0xffffffffffffffffull;
}
template<class BoardStatus status, int depth>
static void Pawnpromote(const Board& brd, uint64_t from, uint64_t to)
{
Board next1 = Board::MovePromote<BoardPiece::Queen, status.WhiteMove>(brd, from, to);
IFPRN std::cout << "Pawnpromote:\n" << _map(from, to, brd, next1) << "\n";
//IFDBG Board::AssertBoardMove<status.WhiteMove>(brd, next1, to & Enemy<status.WhiteMove>(brd));
PerfT<status.SilentMove(), depth - 1>(next1);
Board next2 = Board::MovePromote<BoardPiece::Knight, status.WhiteMove>(brd, from, to);
KnightCheck<status, depth>(EnemyKing<status.WhiteMove>(brd), to);
PerfT<status.SilentMove(), depth - 1>(next2);
Movestack::Check_Status[depth - 1] = 0xffffffffffffffffull;
Board next3 = Board::MovePromote<BoardPiece::Bishop, status.WhiteMove>(brd, from, to);
PerfT<status.SilentMove(), depth - 1>(next3);
Board next4 = Board::MovePromote<BoardPiece::Rook, status.WhiteMove>(brd, from, to);
PerfT<status.SilentMove(), depth - 1>(next4);
}
template<class BoardStatus status, int depth>
static void Knightmove(const Board& brd, uint64_t from, uint64_t to)
{
Board next = Board::Move <BoardPiece::Knight, status.WhiteMove>(brd, from, to, to & Enemy<status.WhiteMove>(brd));
IFPRN std::cout << "Knightmove:\n" << _map(from, to, brd, next) << "\n";
//IFDBG Board::AssertBoardMove<status.WhiteMove>(brd, next, to & Enemy<status.WhiteMove>(brd));
KnightCheck<status, depth>(EnemyKing<status.WhiteMove>(brd), to);
PerfT<status.SilentMove(), depth - 1>(next);
Movestack::Check_Status[depth - 1] = 0xffffffffffffffffull;
}
template<class BoardStatus status, int depth>
static void Bishopmove(const Board& brd, uint64_t from, uint64_t to)
{
Board next = Board::Move <BoardPiece::Bishop, status.WhiteMove>(brd, from, to, to & Enemy<status.WhiteMove>(brd));
IFPRN std::cout << "Bishopmove:\n" << _map(from, to, brd, next) << "\n";
//IFDBG Board::AssertBoardMove<status.WhiteMove>(brd, next, to & Enemy<status.WhiteMove>(brd));
PerfT<status.SilentMove(), depth - 1>(next);
}
template<class BoardStatus status, int depth>
static void Rookmove(const Board& brd, uint64_t from, uint64_t to)
{
Board next = Board::Move<BoardPiece::Rook, status.WhiteMove>(brd, from, to, to & Enemy<status.WhiteMove>(brd));
IFPRN std::cout << "Rookmove:\n" << _map(from, to, brd, next) << "\n";
//IFDBG Board::AssertBoardMove<status.WhiteMove>(brd, next, to & Enemy<status.WhiteMove>(brd));
if constexpr (status.CanCastle()) {
if (status.IsLeftRook(from)) PerfT<status.RookMove_Left(), depth - 1>(next);
else if (status.IsRightRook(from)) PerfT<status.RookMove_Right(), depth - 1>(next);
else PerfT<status.SilentMove(), depth - 1>(next);
}
else PerfT<status.SilentMove(), depth - 1>(next);
}
template<class BoardStatus status, int depth>
static void Queenmove(const Board& brd, uint64_t from, uint64_t to)
{
Board next = Board::Move<BoardPiece::Queen, status.WhiteMove>(brd, from, to, to & Enemy<status.WhiteMove>(brd));
IFPRN std::cout << "Queenmove:\n" << _map(from, to, brd, next) << "\n";
//IFDBG Board::AssertBoardMove<status.WhiteMove>(brd, next, to & Enemy<status.WhiteMove>(brd));
PerfT<status.SilentMove(), depth - 1>(next);
}
};
template<class BoardStatus status>
static void PerfT(std::string_view def, Board& brd, int depth)
{
MoveReciever::Init(brd, FEN::FenEnpassant(def));
//Seemap see;
//Movegen::InitBoard<status>(see, brd.UnpackAll());
/// <summary>
/// Go into recursion on depth 2 - entry point for perft
/// </summary>
switch (depth)
{
case 0: Movelist::InitStack<status, 0>(brd); MoveReciever::PerfT0<status>(); return;
case 1: Movelist::InitStack<status, 1>(brd); MoveReciever::PerfT1<status>(brd); return; //Keep this as T1
case 2: Movelist::InitStack<status, 2>(brd); MoveReciever::PerfT<status, 2>(brd); return;
case 3: Movelist::InitStack<status, 3>(brd); MoveReciever::PerfT<status, 3>(brd); return;
case 4: Movelist::InitStack<status, 4>(brd); MoveReciever::PerfT<status, 4>(brd); return;
case 5: Movelist::InitStack<status, 5>(brd); MoveReciever::PerfT<status, 5>(brd); return;
case 6: Movelist::InitStack<status, 6>(brd); MoveReciever::PerfT<status, 6>(brd); return;
case 7: Movelist::InitStack<status, 7>(brd); MoveReciever::PerfT<status, 7>(brd); return;
case 8: Movelist::InitStack<status, 8>(brd); MoveReciever::PerfT<status, 8>(brd); return;
case 9: Movelist::InitStack<status, 9>(brd); MoveReciever::PerfT<status, 9>(brd); return;
case 10: Movelist::InitStack<status, 10>(brd); MoveReciever::PerfT<status, 10>(brd); return;
case 11: Movelist::InitStack<status, 11>(brd); MoveReciever::PerfT<status, 11>(brd); return;
case 12: Movelist::InitStack<status, 12>(brd); MoveReciever::PerfT<status, 12>(brd); return;
case 13: Movelist::InitStack<status, 13>(brd); MoveReciever::PerfT<status, 13>(brd); return;
case 14: Movelist::InitStack<status, 14>(brd); MoveReciever::PerfT<status, 14>(brd); return;
case 15: Movelist::InitStack<status, 15>(brd); MoveReciever::PerfT<status, 15>(brd); return;
case 16: Movelist::InitStack<status, 16>(brd); MoveReciever::PerfT<status, 16>(brd); return;
case 17: Movelist::InitStack<status, 17>(brd); MoveReciever::PerfT<status, 17>(brd); return;
case 18: Movelist::InitStack<status, 18>(brd); MoveReciever::PerfT<status, 18>(brd); return;
default:
std::cout << "Depth not impl yet" << std::endl;
return;
}
}
PositionToTemplate(PerfT);
void Chess_Test() {
for (auto pos : Test::Positions)
{
auto v = Test::GetElements(pos, ';');
std::string fen = v[0];
std::cout << fen << "\n";
int to = v.size();
for (int i = 1; i < to; i++) {
auto perftvals = Test::GetElements(v[i], ' ');
uint64_t expected = static_cast<uint64_t>(std::strtol(perftvals[1].c_str(), NULL, 10));
_PerfT(fen, i);
uint64_t result = MoveReciever::nodes;
std::string status = expected == result ? "OK" : "ERROR";
if (expected == result) std::cout << " " << i << ": " << result << " " << status << "\n";
else std::cout << "xxx -> " << i << ": " << result <<" vs " << expected << " " << status << "\n";
}
}
}
const auto _keep0 = _map(0);
const auto _keep1 = _map(0,0);
const auto _keep2 = _map(0,0,0);
const auto _keep4 = _map(0, 0, Board::Default(), Board::Default());
int main(int argc, char** argv)
{
std::vector<std::string> args(argv, argv + argc);
if (args.size() >= 4) {
std::string_view def(argv[1]);
uint64_t depth = static_cast<uint64_t>(std::strtol(args[2].c_str(), NULL, 10));
uint64_t exptected = static_cast<uint64_t>(std::strtol(args[3].c_str(), NULL, 10));
_PerfT(def, static_cast<int>(depth));
if (exptected == MoveReciever::nodes) return 0;
return 9;
}
if (args.size() == 3) {
std::string_view def(argv[1]);
uint64_t depth = static_cast<uint64_t>(std::strtol(args[2].c_str(), NULL, 10));
if (depth > 12) { std::cout << "Max depth limited to 12 for now!\n"; return 0; }
std::cout << "Depth: " << depth << " - " << def << "\n";
for (int i = 1; i <= depth; i++)
{
auto start = std::chrono::steady_clock::now();
_PerfT(def, i);
auto end = std::chrono::steady_clock::now();
long long delta = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
std::cout << "Perft " << i << ": " << MoveReciever::nodes << " " << delta / 1000 << "ms " << MoveReciever::nodes * 1.0 / delta << " MNodes/s\n";
}
std::cout << "\nPress any key to exit..."; getchar();
return 0;
}
//Chess_Test();
//return 0;
std::random_device rd;
std::mt19937_64 eng(rd());
std::uniform_int_distribution<unsigned long long> distr;
//std::string_view dbg = "rnbq1k1r/pp1Pbppp/2p5/8/2B5/8/PPP1NnPP/RNBQK2R w KQ - 1 8"
std::string_view def = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
std::string_view kiwi = "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1";
//std::string_view pintest = "6Q1/8/4k3/8/4r3/1K6/4R3/8 b - - 0 1";
//std::string_view def = "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq -";
std::string_view midgame = "r4rk1/1pp1qppp/p1np1n2/2b1p1B1/2B1P1b1/P1NP1N2/1PP1QPPP/R4RK1 w - - 0 10";
std::string_view endgame = "5nk1/pp3pp1/2p4p/q7/2PPB2P/P5P1/1P5K/3Q4 w - - 1 28";
//55.8
auto ts = std::chrono::steady_clock::now();
for (int i = 1; i <= 7; i++)
{
auto start = std::chrono::steady_clock::now();
_PerfT(def, i);
auto end = std::chrono::steady_clock::now();
long long delta = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
std::cout << "Perft Start " <<i<< ": "<< MoveReciever::nodes << " " << delta / 1000 <<"ms " << MoveReciever::nodes * 1.0 / delta << " MNodes/s\n";
}
if (MoveReciever::nodes == 3195901860ull) std::cout << "OK\n\n";
else std::cout << "ERROR!\n\n";
for (int i = 1; i <= 6; i++)
{
auto start = std::chrono::steady_clock::now();
_PerfT(kiwi, i);
auto end = std::chrono::steady_clock::now();
long long delta = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
std::cout << "Perft Kiwi " << i << ": " << MoveReciever::nodes << " " << delta / 1000 << "ms " << MoveReciever::nodes * 1.0 / delta << " MNodes/s\n";
}
if (MoveReciever::nodes == 8031647685ull) std::cout << "OK\n\n";
else std::cout << "ERROR!\n\n";
for (int i = 1; i <= 6; i++)
{
auto start = std::chrono::steady_clock::now();
_PerfT(midgame, i);
auto end = std::chrono::steady_clock::now();
long long delta = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
std::cout << "Perft Midgame " << i << ": " << MoveReciever::nodes << " " << delta / 1000 << "ms " << MoveReciever::nodes * 1.0 / delta << " MNodes/s\n";
}
if (MoveReciever::nodes == 6923051137ull) std::cout << "OK\n\n";
else std::cout << "ERROR!\n\n";
for (int i = 1; i <= 6; i++)
{
auto start = std::chrono::steady_clock::now();
_PerfT(endgame, i);
auto end = std::chrono::steady_clock::now();
long long delta = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
std::cout << "Perft Endgame " << i << ": " << MoveReciever::nodes << " " << delta / 1000 << "ms " << MoveReciever::nodes * 1.0 / delta << " MNodes/s\n";
}
if (MoveReciever::nodes == 849167880ull) std::cout << "OK\n\n";
else std::cout << "ERROR!\n\n";
//Total nodes
MoveReciever::nodes = (3195901860ull + 8031647685ull + 6923051137ull + 849167880ull);
auto te = std::chrono::steady_clock::now();
long long total = std::chrono::duration_cast<std::chrono::microseconds>(te - ts).count();
std::cout << "Perft aggregate: " << MoveReciever::nodes
<< " " << total / 1000 << "ms " << MoveReciever::nodes * 1.0 / total << " MNodes/s\n";
std::cout << "\nPress any key to exit..."; getchar();
}
| 0 | 0.922559 | 1 | 0.922559 | game-dev | MEDIA | 0.525115 | game-dev | 0.935489 | 1 | 0.935489 |
VideogameSources/gta3-decomp-alt | 36,683 | src/objects/ParticleObject.cpp | #include "common.h"
#include "ParticleObject.h"
#include "Timer.h"
#include "General.h"
#include "ParticleMgr.h"
#include "Particle.h"
#include "Camera.h"
#include "Game.h"
#include "DMAudio.h"
#include "screendroplets.h"
CParticleObject gPObjectArray[MAX_PARTICLEOBJECTS];
CParticleObject *CParticleObject::pCloseListHead;
CParticleObject *CParticleObject::pFarListHead;
CParticleObject *CParticleObject::pUnusedListHead;
CAudioHydrant List[MAX_AUDIOHYDRANTS];
CAudioHydrant *CAudioHydrant::Get(int n) { return &List[n]; }
bool
CAudioHydrant::Add(CParticleObject *particleobject)
{
for ( int32 i = 0; i < MAX_AUDIOHYDRANTS; i++ )
{
if ( List[i].AudioEntity == AEHANDLE_NONE )
{
List[i].AudioEntity = DMAudio.CreateEntity(AUDIOTYPE_FIREHYDRANT, particleobject);
if ( AEHANDLE_IS_FAILED(List[i].AudioEntity) )
return false;
DMAudio.SetEntityStatus(List[i].AudioEntity, true);
List[i].pParticleObject = particleobject;
return true;
}
}
return false;
}
void
CAudioHydrant::Remove(CParticleObject *particleobject)
{
for ( int32 i = 0; i < MAX_AUDIOHYDRANTS; i++ )
{
if ( List[i].pParticleObject == particleobject )
{
DMAudio.DestroyEntity(List[i].AudioEntity);
List[i].AudioEntity = AEHANDLE_NONE;
List[i].pParticleObject = NULL;
}
}
}
CParticleObject::CParticleObject() :
CPlaceable(),
m_nFrameCounter(0),
m_nState(POBJECTSTATE_INITIALISED),
m_pNext(NULL),
m_pPrev(NULL),
m_nRemoveTimer(0)
{
;
}
CParticleObject::~CParticleObject()
{
}
void
CParticleObject::Initialise()
{
pCloseListHead = NULL;
pFarListHead = NULL;
pUnusedListHead = &gPObjectArray[0];
for ( int32 i = 0; i < MAX_PARTICLEOBJECTS; i++ )
{
if ( i == 0 )
gPObjectArray[i].m_pPrev = NULL;
else
gPObjectArray[i].m_pPrev = &gPObjectArray[i - 1];
if ( i == MAX_PARTICLEOBJECTS-1 )
gPObjectArray[i].m_pNext = NULL;
else
gPObjectArray[i].m_pNext = &gPObjectArray[i + 1];
gPObjectArray[i].m_nState = POBJECTSTATE_FREE;
}
}
CParticleObject *
CParticleObject::AddObject(uint16 type, CVector const &pos, uint8 remove)
{
CRGBA color(0, 0, 0, 0);
CVector target(0.0f, 0.0f, 0.0f);
return AddObject(type, pos, target, 0.0f, 0, color, remove);
}
CParticleObject *
CParticleObject::AddObject(uint16 type, CVector const &pos, float size, uint8 remove)
{
CRGBA color(0, 0, 0, 0);
CVector target(0.0f, 0.0f, 0.0f);
return AddObject(type, pos, target, size, 0, color, remove);
}
CParticleObject *
CParticleObject::AddObject(uint16 type, CVector const &pos, CVector const &target, float size, uint8 remove)
{
CRGBA color(0, 0, 0, 0);
return AddObject(type, pos, target, size, 0, color, remove);
}
CParticleObject *
CParticleObject::AddObject(uint16 type, CVector const &pos, CVector const &target, float size, uint32 lifeTime, RwRGBA const &color, uint8 remove)
{
CParticleObject *pobj = pUnusedListHead;
ASSERT(pobj != NULL);
if ( pobj == NULL )
{
printf("Error: No particle objects available!\n");
return NULL;
}
MoveToList(&pUnusedListHead, &pCloseListHead, pobj);
pobj->m_nState = POBJECTSTATE_UPDATE_CLOSE;
pobj->m_Type = (eParticleObjectType)type;
pobj->SetPosition(pos);
pobj->m_vecTarget = target;
pobj->m_nNumEffectCycles = 1;
pobj->m_nSkipFrames = 1;
pobj->m_nCreationChance = 0;
pobj->m_nFrameCounter = 0;
pobj->m_bRemove = remove;
pobj->m_pParticle = NULL;
if ( lifeTime != 0 )
pobj->m_nRemoveTimer = CTimer::GetTimeInMilliseconds() + lifeTime;
else
pobj->m_nRemoveTimer = 0;
if ( color.alpha != 0 )
pobj->m_Color = color;
else
pobj->m_Color.alpha = 0;
pobj->m_fSize = size;
pobj->m_fRandVal = 0.0f;
if ( type <= POBJECT_CATALINAS_SHOTGUNFLASH )
{
switch ( type )
{
case POBJECT_PAVEMENT_STEAM:
{
pobj->m_ParticleType = PARTICLE_STEAM_NY;
pobj->m_nNumEffectCycles = 1;
#ifdef PC_PARTICLE
pobj->m_nSkipFrames = 3;
#else
pobj->m_nSkipFrames = 1;
#endif
pobj->m_nCreationChance = 8;
break;
}
case POBJECT_PAVEMENT_STEAM_SLOWMOTION:
{
pobj->m_ParticleType = PARTICLE_STEAM_NY_SLOWMOTION;
pobj->m_nNumEffectCycles = 1;
pobj->m_nSkipFrames = 1;
pobj->m_nCreationChance = 8;
break;
}
case POBJECT_WALL_STEAM:
{
pobj->m_ParticleType = PARTICLE_STEAM_NY;
pobj->m_nNumEffectCycles = 1;
#ifdef PC_PARTICLE
pobj->m_nSkipFrames = 3;
#else
pobj->m_nSkipFrames = 1;
#endif
pobj->m_nCreationChance = 8;
break;
}
case POBJECT_WALL_STEAM_SLOWMOTION:
{
pobj->m_ParticleType = PARTICLE_STEAM_NY_SLOWMOTION;
pobj->m_nNumEffectCycles = 1;
pobj->m_nSkipFrames = 1;
pobj->m_nCreationChance = 8;
break;
}
case POBJECT_DARK_SMOKE:
{
pobj->m_ParticleType = PARTICLE_STEAM_NY;
pobj->m_nNumEffectCycles = 1;
#ifdef PC_PARTICLE
pobj->m_nSkipFrames = 3;
#else
pobj->m_nSkipFrames = 1;
#endif
pobj->m_nCreationChance = 8;
pobj->m_Color = CRGBA(16, 16, 16, 255);
break;
}
case POBJECT_FIRE_HYDRANT:
{
pobj->m_ParticleType = PARTICLE_WATER_HYDRANT;
pobj->m_nNumEffectCycles = 4;
pobj->m_nSkipFrames = 1;
pobj->m_nCreationChance = 0;
pobj->m_vecTarget = CVector(0.0f, 0.0f, 0.3f);
pobj->m_nRemoveTimer = CTimer::GetTimeInMilliseconds() + 5000;
CAudioHydrant::Add(pobj);
break;
}
case POBJECT_CAR_WATER_SPLASH:
case POBJECT_PED_WATER_SPLASH:
{
pobj->m_ParticleType = PARTICLE_CAR_SPLASH;
pobj->m_nNumEffectCycles = 0;
#ifdef PC_PARTICLE
pobj->m_nSkipFrames = 1;
#else
pobj->m_nSkipFrames = 3;
#endif
pobj->m_nCreationChance = 0;
#ifdef SCREEN_DROPLETS
ScreenDroplets::RegisterSplash(pobj);
#endif
break;
}
case POBJECT_SPLASHES_AROUND:
{
pobj->m_ParticleType = PARTICLE_SPLASH;
#ifdef PC_PARTICLE
pobj->m_nNumEffectCycles = 15;
#else
pobj->m_nNumEffectCycles = 30;
#endif
pobj->m_nSkipFrames = 2;
pobj->m_nCreationChance = 0;
break;
}
case POBJECT_SMALL_FIRE:
{
pobj->m_ParticleType = PARTICLE_FLAME;
pobj->m_nNumEffectCycles = 1;
#ifdef PC_PARTICLE
pobj->m_nSkipFrames = 2;
#else
pobj->m_nSkipFrames = 1;
#endif
pobj->m_nCreationChance = 2;
pobj->m_vecTarget = CVector(0.0f, 0.0f, 0.0f);
break;
}
case POBJECT_BIG_FIRE:
{
pobj->m_ParticleType = PARTICLE_FLAME;
pobj->m_nNumEffectCycles = 1;
#ifdef PC_PARTICLE
pobj->m_nSkipFrames = 2;
#else
pobj->m_nSkipFrames = 1;
#endif
pobj->m_nCreationChance = 4;
pobj->m_vecTarget = CVector(0.0f, 0.0f, 0.0f);
break;
}
case POBJECT_DRY_ICE:
{
pobj->m_ParticleType = PARTICLE_SMOKE;
pobj->m_nNumEffectCycles = 1;
pobj->m_nSkipFrames = 1;
pobj->m_nCreationChance = 0;
pobj->m_vecTarget = CVector(0.0f, 0.0f, 0.0f);
break;
}
case POBJECT_DRY_ICE_SLOWMOTION:
{
pobj->m_ParticleType = PARTICLE_SMOKE_SLOWMOTION;
pobj->m_nNumEffectCycles = 1;
pobj->m_nSkipFrames = 1;
pobj->m_nCreationChance = 0;
pobj->m_vecTarget = CVector(0.0f, 0.0f, 0.0f);
break;
}
case POBJECT_FIRE_TRAIL:
{
pobj->m_ParticleType = PARTICLE_EXPLOSION_MEDIUM;
pobj->m_nNumEffectCycles = 1;
#ifdef PC_PARTICLE
pobj->m_nSkipFrames = 3;
#else
pobj->m_nSkipFrames = 1;
#endif
pobj->m_nCreationChance = 2;
pobj->m_fRandVal = 0.01f;
break;
}
case POBJECT_SMOKE_TRAIL:
{
pobj->m_ParticleType = PARTICLE_FIREBALL_SMOKE;
pobj->m_nNumEffectCycles = 1;
pobj->m_nSkipFrames = 1;
pobj->m_nCreationChance = 2;
pobj->m_fRandVal = 0.02f;
break;
}
case POBJECT_FIREBALL_AND_SMOKE:
{
pobj->m_ParticleType = PARTICLE_FLAME;
pobj->m_nNumEffectCycles = 1;
pobj->m_nSkipFrames = 1;
pobj->m_nCreationChance = 2;
pobj->m_fRandVal = 0.1f;
break;
}
case POBJECT_ROCKET_TRAIL:
{
pobj->m_ParticleType = PARTICLE_FLAME;
pobj->m_nNumEffectCycles = 1;
pobj->m_nSkipFrames = 2;
pobj->m_nCreationChance = 8;
pobj->m_fRandVal = 0.1f;
break;
}
case POBJECT_EXPLOSION_ONCE:
{
pobj->m_ParticleType = PARTICLE_EXPLOSION_LARGE;
pobj->m_nNumEffectCycles = 1;
pobj->m_nSkipFrames = 1;
pobj->m_nCreationChance = 0;
pobj->m_nRemoveTimer = CTimer::GetTimeInMilliseconds();
break;
}
case POBJECT_CATALINAS_GUNFLASH:
case POBJECT_CATALINAS_SHOTGUNFLASH:
{
pobj->m_ParticleType = PARTICLE_GUNFLASH_NOANIM;
pobj->m_nNumEffectCycles = 1;
pobj->m_nSkipFrames = 1;
pobj->m_nCreationChance = 0;
pobj->m_nRemoveTimer = CTimer::GetTimeInMilliseconds();
pobj->m_vecTarget.Normalise();
break;
}
}
}
return pobj;
}
void
CParticleObject::RemoveObject(void)
{
switch ( this->m_nState )
{
case POBJECTSTATE_UPDATE_CLOSE:
{
MoveToList(&pCloseListHead, &pUnusedListHead, this);
this->m_nState = POBJECTSTATE_FREE;
break;
}
case POBJECTSTATE_UPDATE_FAR:
{
MoveToList(&pFarListHead, &pUnusedListHead, this);
this->m_nState = POBJECTSTATE_FREE;
break;
}
}
}
void
CParticleObject::UpdateAll(void)
{
{
CParticleObject *pobj = pCloseListHead;
CParticleObject *nextpobj;
if ( pobj != NULL )
{
do
{
nextpobj = pobj->m_pNext;
pobj->UpdateClose();
pobj = nextpobj;
}
while ( nextpobj != NULL );
}
}
{
int32 frame = CTimer::GetFrameCounter() & 31;
int32 counter = 0;
CParticleObject *pobj = pFarListHead;
CParticleObject *nextpobj;
if ( pobj != NULL )
{
do
{
nextpobj = pobj->m_pNext;
if ( counter == frame )
{
pobj->UpdateFar();
frame += 32;
}
counter++;
pobj = nextpobj;
}
while ( nextpobj != NULL );
}
}
}
void CParticleObject::UpdateClose(void)
{
if ( !CGame::playingIntro )
{
if ( (this->GetPosition() - TheCamera.GetPosition()).MagnitudeSqr2D() > SQR(100.0f) )
{
if ( this->m_bRemove )
{
if ( this->m_Type == POBJECT_FIRE_HYDRANT )
CAudioHydrant::Remove(this);
MoveToList(&pCloseListHead, &pUnusedListHead, this);
this->m_nState = POBJECTSTATE_FREE;
}
else
{
MoveToList(&pCloseListHead, &pFarListHead, this);
this->m_nState = POBJECTSTATE_UPDATE_FAR;
}
return;
}
}
if ( ++this->m_nFrameCounter >= this->m_nSkipFrames )
{
this->m_nFrameCounter = 0;
int32 randVal;
if ( this->m_nCreationChance != 0 )
randVal = CGeneral::GetRandomNumber() % this->m_nCreationChance;
if ( this->m_nCreationChance == 0
|| randVal == 0 && this->m_nCreationChance < 0
|| randVal != 0 && this->m_nCreationChance > 0)
{
switch ( this->m_Type )
{
case POBJECT_SMALL_FIRE:
{
CVector pos = this->GetPosition();
CVector vel = this->m_vecTarget;
float size = this->m_fSize;
CVector flamevel;
flamevel.x = vel.x;
flamevel.y = vel.y;
flamevel.z = CGeneral::GetRandomNumberInRange(0.0125f*size, 0.1f*size);
CParticle::AddParticle(PARTICLE_FLAME, pos, flamevel, NULL, size);
CVector possmoke = pos;
possmoke.x += CGeneral::GetRandomNumberInRange(0.625f*-size, size*0.625f);
possmoke.y += CGeneral::GetRandomNumberInRange(0.625f*-size, size*0.625f);
possmoke.z += CGeneral::GetRandomNumberInRange(0.625f* size, size*2.5f);
CParticle::AddParticle(PARTICLE_CARFLAME_SMOKE, possmoke, vel);
break;
}
case POBJECT_BIG_FIRE:
{
CVector pos = this->GetPosition();
CVector vel = this->m_vecTarget;
float size = this->m_fSize;
float s = 0.7f*size;
CVector flamevel;
flamevel.x = vel.x;
flamevel.y = vel.y;
flamevel.z = CGeneral::GetRandomNumberInRange(0.0125f*s, 0.1f*s);
float flamesize = 0.8f*size;
CParticle::AddParticle(PARTICLE_FLAME, pos, flamevel, NULL, flamesize);
for ( int32 i = 0; i < 4; i++ )
{
CVector smokepos = pos;
smokepos.x += CGeneral::GetRandomNumberInRange(0.625f*-size, 0.625f*size);
smokepos.y += CGeneral::GetRandomNumberInRange(0.625f*-size, 0.625f*size);
smokepos.z += CGeneral::GetRandomNumberInRange(0.625f* size, 3.5f *size);
CParticle::AddParticle(PARTICLE_CARFLAME_SMOKE, smokepos, vel);
}
break;
}
case POBJECT_FIREBALL_AND_SMOKE:
{
if ( this->m_pParticle == NULL )
{
CVector pos = this->GetPosition();
CVector vel = this->m_vecTarget;
float size = this->m_fSize;
CVector expvel = 1.2f*vel;
float expsize = 1.2f*size;
this->m_pParticle = CParticle::AddParticle(PARTICLE_EXPLOSION_MEDIUM, pos, expvel, NULL, expsize);
}
else
{
CVector pos = this->GetPosition(); // this->m_pParticle->m_vecPosition ?
CVector vel = this->m_vecTarget;
float size = this->m_fSize;
CVector veloffset = 0.35f*vel;
CVector fireballvel = vel;
for ( int32 i = 0; i < this->m_nNumEffectCycles; i++ )
{
fireballvel.x += CGeneral::GetRandomNumberInRange(-veloffset.x, veloffset.x);
fireballvel.y += CGeneral::GetRandomNumberInRange(-veloffset.y, veloffset.y);
fireballvel.z += CGeneral::GetRandomNumberInRange(-veloffset.z, veloffset.z);
CParticle::AddParticle(PARTICLE_FIREBALL_SMOKE, pos, fireballvel, NULL, size);
}
}
break;
}
case POBJECT_ROCKET_TRAIL:
{
if ( this->m_pParticle == NULL )
{
CVector pos = this->GetPosition();
CVector vel = this->m_vecTarget;
float size = this->m_fSize;
this->m_pParticle = CParticle::AddParticle(PARTICLE_EXPLOSION_MEDIUM, pos, vel, NULL, size);
}
else
{
CVector pos = this->m_pParticle->m_vecPosition;
CVector vel = this->m_vecTarget;
float size = this->m_fSize;
float fireballsize = size * 1.5f;
CVector fireballvel = vel * -0.8f;
for ( int32 i = 0; i < this->m_nNumEffectCycles; i++ )
{
CParticle::AddParticle(PARTICLE_FIREBALL_SMOKE, pos, fireballvel, NULL, fireballsize);
}
}
break;
}
case POBJECT_FIRE_TRAIL:
{
for ( int32 i = 0; i < this->m_nNumEffectCycles; i++ )
{
CVector vel = this->m_vecTarget;
if ( vel.x != 0.0f )
vel.x += CGeneral::GetRandomNumberInRange(-this->m_fRandVal, this->m_fRandVal);
if ( vel.y != 0.0f )
vel.y += CGeneral::GetRandomNumberInRange(-this->m_fRandVal, this->m_fRandVal);
if ( vel.z != 0.0f )
vel.z += CGeneral::GetRandomNumberInRange(-this->m_fRandVal, this->m_fRandVal);
CParticle::AddParticle(this->m_ParticleType, this->GetPosition(), vel, NULL, this->m_fSize,
CGeneral::GetRandomNumberInRange(-6.0f, 6.0f));
}
break;
}
case POBJECT_PED_WATER_SPLASH:
{
#ifdef PC_PARTICLE
CRGBA colorsmoke(255, 255, 255, 196);
CVector pos = this->GetPosition();
CVector vel = this->m_vecTarget;
for ( int32 i = 0; i < 3; i++ )
{
int32 angle = 90 * i;
float fCos = CParticle::Cos(angle);
float fSin = CParticle::Sin(angle);
CVector splashpos;
CVector splashvel;
splashpos = pos + CVector(0.75f*fCos, 0.75f*fSin, 0.0f);
splashvel = vel + CVector(0.05f*fCos, 0.05f*fSin, CGeneral::GetRandomNumberInRange(0.04f, 0.08f));
CParticle::AddParticle(PARTICLE_RUBBER_SMOKE, splashpos, splashvel, NULL,
CGeneral::GetRandomNumberInRange(0.1f, 0.8f), colorsmoke);
CParticle::AddParticle(PARTICLE_CAR_SPLASH, splashpos, splashvel, NULL,
CGeneral::GetRandomNumberInRange(0.1f, 0.5f), this->m_Color);
splashpos = pos + CVector(0.75f*fCos, 0.75f*-fSin, 0.0f);
splashvel = vel + CVector(0.05f*fCos, 0.05f*-fSin, CGeneral::GetRandomNumberInRange(0.04f, 0.08f));
CParticle::AddParticle(PARTICLE_RUBBER_SMOKE, splashpos, splashvel, NULL,
CGeneral::GetRandomNumberInRange(0.1f, 0.8f), colorsmoke);
CParticle::AddParticle(PARTICLE_CAR_SPLASH, splashpos, splashvel, NULL,
CGeneral::GetRandomNumberInRange(0.1f, 0.5f), this->m_Color);
splashpos = pos + CVector(0.75f*-fCos, 0.75f*fSin, 0.0f);
splashvel = vel + CVector(0.05f*-fCos, 0.05f*fSin, CGeneral::GetRandomNumberInRange(0.04f, 0.08f));
CParticle::AddParticle(PARTICLE_RUBBER_SMOKE, splashpos, splashvel, NULL,
CGeneral::GetRandomNumberInRange(0.1f, 0.8f), colorsmoke);
CParticle::AddParticle(PARTICLE_CAR_SPLASH, splashpos, splashvel, NULL,
CGeneral::GetRandomNumberInRange(0.1f, 0.5f), this->m_Color);
splashpos = pos + CVector(0.75f*-fCos, 0.75f*-fSin, 0.0f);
splashvel = vel + CVector(0.05f*-fCos, 0.05f*-fSin, CGeneral::GetRandomNumberInRange(0.04f, 0.08f));
CParticle::AddParticle(PARTICLE_RUBBER_SMOKE, splashpos, splashvel, NULL,
CGeneral::GetRandomNumberInRange(0.1f, 0.8f), colorsmoke);
CParticle::AddParticle(PARTICLE_CAR_SPLASH, splashpos, splashvel, NULL,
CGeneral::GetRandomNumberInRange(0.1f, 0.5f), this->m_Color);
}
for ( int32 i = 0; i < 1; i++ )
{
int32 angle = 180 * (i + 1);
float fCos = CParticle::Cos(angle);
float fSin = CParticle::Sin(angle);
CVector splashpos;
CVector splashvel;
splashpos = pos + CVector(0.5f*fCos, 0.5f*fSin, 0.0f);
splashvel = vel;
splashvel.x += CGeneral::GetRandomNumberInRange(-0.25f, 0.25f) * fCos;
splashvel.y += CGeneral::GetRandomNumberInRange(-0.25f, 0.25f) * fSin;
splashvel.z += CGeneral::GetRandomNumberInRange(0.05f, 0.25f);
CParticle::AddParticle(PARTICLE_CAR_SPLASH, splashpos, splashvel, NULL,
CGeneral::GetRandomNumberInRange(0.4f, 1.0f), this->m_Color);
splashpos = pos + CVector(0.5f*fCos, 0.5f*-fSin, 0.0f);
splashvel = vel;
splashvel.x += CGeneral::GetRandomNumberInRange(-0.25f, 0.25f) * fCos;
splashvel.y += CGeneral::GetRandomNumberInRange(-0.25f, 0.25f) * -fSin;
splashvel.z += CGeneral::GetRandomNumberInRange(0.05f, 0.25f);
CParticle::AddParticle(PARTICLE_CAR_SPLASH, splashpos, splashvel, NULL,
CGeneral::GetRandomNumberInRange(0.4f, 1.0f), this->m_Color);
splashpos = pos + CVector(0.5f*-fCos, 0.5f*fSin, 0.0f);
splashvel = vel;
splashvel.x += CGeneral::GetRandomNumberInRange(-0.25f, 0.25f) * -fCos;
splashvel.y += CGeneral::GetRandomNumberInRange(-0.25f, 0.25f) * fSin;
splashvel.z += CGeneral::GetRandomNumberInRange(0.05f, 0.25f);
CParticle::AddParticle(PARTICLE_CAR_SPLASH, splashpos, splashvel, NULL,
CGeneral::GetRandomNumberInRange(0.4f, 1.0f), this->m_Color);
splashpos = pos + CVector(0.5f*-fCos, 0.5f*-fSin, 0.0f);
splashvel = vel;
splashvel.x += CGeneral::GetRandomNumberInRange(-0.25f, 0.25f) * -fCos;
splashvel.y += CGeneral::GetRandomNumberInRange(-0.25f, 0.25f) * -fSin;
splashvel.z += CGeneral::GetRandomNumberInRange(0.05f, 0.25f);
CParticle::AddParticle(PARTICLE_CAR_SPLASH, splashpos, splashvel, NULL,
CGeneral::GetRandomNumberInRange(0.4f, 1.0f), this->m_Color);
}
#else
CVector pos;
CVector vel;
for ( int32 i = -2; i < 2; i++ )
{
pos = this->GetPosition();
pos += CVector(-0.75f, 0.5f * float(i), 0.0f);
vel = this->m_vecTarget;
vel.x += -1.5 * CGeneral::GetRandomNumberInRange(0.001f, 0.006f);
vel.y += float(i) * CGeneral::GetRandomNumberInRange(0.001f, 0.006f);
vel.z += CGeneral::GetRandomNumberInRange(0.03f, 0.06f);
CParticle::AddParticle(PARTICLE_PED_SPLASH, pos, vel, NULL, 0.8f, this->m_Color);
pos = this->GetPosition();
pos += CVector(0.75f, 0.5f * float(i), 0.0f);
vel = this->m_vecTarget;
vel.x += 1.5f * CGeneral::GetRandomNumberInRange(0.001f, 0.006f);
vel.y += float(i) * CGeneral::GetRandomNumberInRange(0.001f, 0.006f);
vel.z += CGeneral::GetRandomNumberInRange(0.03f, 0.06f);
CParticle::AddParticle(PARTICLE_PED_SPLASH, pos, vel, NULL, 0.8f, this->m_Color);
pos = this->GetPosition();
pos += CVector(0.5f * float(i), -0.75, 0.0f);
vel = this->m_vecTarget;
vel.x += float(i) * CGeneral::GetRandomNumberInRange(0.001f, 0.006f);
vel.y += -1.5f * CGeneral::GetRandomNumberInRange(0.001f, 0.006f);
vel.z += CGeneral::GetRandomNumberInRange(0.03f, 0.06f);
CParticle::AddParticle(PARTICLE_PED_SPLASH, pos, vel, NULL, 0.8f, this->m_Color);
pos = this->GetPosition();
pos += CVector(0.5f * float(i), 0.75, 0.0f);
vel = this->m_vecTarget;
vel.x += float(i) * CGeneral::GetRandomNumberInRange(0.001f, 0.006f);
vel.y += 1.5f * CGeneral::GetRandomNumberInRange(0.001f, 0.006f);
vel.z += CGeneral::GetRandomNumberInRange(0.03f, 0.06f);
CParticle::AddParticle(PARTICLE_PED_SPLASH, pos, vel, NULL, 0.8f, this->m_Color);
}
for ( int32 i = 0; i < 4; i++ )
{
pos = this->GetPosition();
pos.x += CGeneral::GetRandomNumberInRange(-1.5f, 1.5f);
pos.y += CGeneral::GetRandomNumberInRange(-1.5f, 1.5f);
pos.z += CGeneral::GetRandomNumberInRange(0.03f, 0.06f);
vel = this->m_vecTarget;
CParticle::AddParticle(PARTICLE_PED_SPLASH, pos, vel, NULL, 0.8f, this->m_Color);
}
#endif
break;
}
case POBJECT_CAR_WATER_SPLASH:
{
#ifdef PC_PARTICLE
CRGBA colorsmoke(255, 255, 255, 196);
CVector pos = this->GetPosition();
CVector vel = this->m_vecTarget;
float size = CGeneral::GetRandomNumberInRange(1.0f, 2.5f);
for ( int32 i = 0; i < 3; i++ )
{
int32 angle = 90 * i;
float fCos = CParticle::Cos(angle);
float fSin = CParticle::Sin(angle);
CVector splashpos;
CVector splashvel;
splashpos = pos + CVector(2.0f*fCos, 2.0f*fSin, 0.0f);
splashvel = vel;
splashvel.x += CGeneral::GetRandomNumberInRange(-0.5f, 0.5f) * fCos;
splashvel.y += CGeneral::GetRandomNumberInRange(-0.5f, 0.5f) * fSin;
splashvel.z += CGeneral::GetRandomNumberInRange(0.01f, 0.03f);
CParticle::AddParticle(PARTICLE_RUBBER_SMOKE, splashpos, splashvel, NULL, size, colorsmoke);
CParticle::AddParticle(PARTICLE_CAR_SPLASH, splashpos, splashvel, NULL, 0.0f, this->m_Color);
splashpos = pos + CVector(2.0f*fCos, 2.0f*-fSin, 0.0f);
splashvel = vel;
splashvel.x += CGeneral::GetRandomNumberInRange(-0.5f, 0.5f) * fCos;
splashvel.y += CGeneral::GetRandomNumberInRange(-0.5f, 0.5f) * -fSin;
splashvel.z += CGeneral::GetRandomNumberInRange(0.01f, 0.03f);
CParticle::AddParticle(PARTICLE_RUBBER_SMOKE, splashpos, splashvel, NULL, size, colorsmoke);
CParticle::AddParticle(PARTICLE_CAR_SPLASH, splashpos, splashvel, NULL, 0.0f, this->m_Color);
splashpos = pos + CVector(2.0f*-fCos, 2.0f*fSin, 0.0f);
splashvel = vel;
splashvel.x += CGeneral::GetRandomNumberInRange(-0.5f, 0.5f) * -fCos;
splashvel.y += CGeneral::GetRandomNumberInRange(-0.5f, 0.5f) * fSin;
splashvel.z += CGeneral::GetRandomNumberInRange(0.01f, 0.03f);
CParticle::AddParticle(PARTICLE_RUBBER_SMOKE, splashpos, splashvel, NULL, size, colorsmoke);
CParticle::AddParticle(PARTICLE_CAR_SPLASH, splashpos, splashvel, NULL, 0.0f, this->m_Color);
splashpos = pos + CVector(2.0f*-fCos, 2.0f*-fSin, 0.0f);
splashvel = vel;
splashvel.x += CGeneral::GetRandomNumberInRange(-0.5f, 0.5f) * -fCos;
splashvel.y += CGeneral::GetRandomNumberInRange(-0.5f, 0.5f) * -fSin;
splashvel.z += CGeneral::GetRandomNumberInRange(0.01f, 0.03f);
CParticle::AddParticle(PARTICLE_RUBBER_SMOKE, splashpos, splashvel, NULL, size, colorsmoke);
CParticle::AddParticle(PARTICLE_CAR_SPLASH, splashpos, splashvel, NULL, 0.0f, this->m_Color);
}
for ( int32 i = 0; i < 1; i++ )
{
int32 angle = 180 * (i + 1);
float fCos = CParticle::Cos(angle);
float fSin = CParticle::Sin(angle);
CVector splashpos;
CVector splashvel;
splashpos = pos + CVector(1.25f*fCos, 1.25f*fSin, 0.0f);
splashvel = vel;
splashvel.x += CGeneral::GetRandomNumberInRange(-0.1f, 0.1f) * fCos;
splashvel.y += CGeneral::GetRandomNumberInRange(-0.1f, 0.1f) * fSin;
splashvel.z += CGeneral::GetRandomNumberInRange(0.26f, 0.53f);
CParticle::AddParticle(PARTICLE_CAR_SPLASH, splashpos, splashvel, NULL, 0.0f, this->m_Color);
splashpos = pos + CVector(1.25f*fCos, 1.25f*-fSin, 0.0f);
splashvel = vel;
splashvel.x += CGeneral::GetRandomNumberInRange(-0.1f, 0.1f) * fCos;
splashvel.y += CGeneral::GetRandomNumberInRange(-0.1f, 0.1f) * -fSin;
splashvel.z += CGeneral::GetRandomNumberInRange(0.26f, 0.53f);
CParticle::AddParticle(PARTICLE_CAR_SPLASH, splashpos, splashvel, NULL, 0.0f, this->m_Color);
splashpos = pos + CVector(1.25f*-fCos, 1.25f*fSin, 0.0f);
splashvel = vel;
splashvel.x += CGeneral::GetRandomNumberInRange(-0.1f, 0.1f) * -fCos;
splashvel.y += CGeneral::GetRandomNumberInRange(-0.1f, 0.1f) * fSin;
splashvel.z += CGeneral::GetRandomNumberInRange(0.26f, 0.53f);
CParticle::AddParticle(PARTICLE_CAR_SPLASH, splashpos, splashvel, NULL, 0.0f, this->m_Color);
splashpos = pos + CVector(1.25f*-fCos, 1.25f*-fSin, 0.0f);
splashvel = vel;
splashvel.x += CGeneral::GetRandomNumberInRange(-0.1f, 0.1f) * -fCos;
splashvel.y += CGeneral::GetRandomNumberInRange(-0.1f, 0.1f) * -fSin;
splashvel.z += CGeneral::GetRandomNumberInRange(0.26f, 0.53f);
CParticle::AddParticle(PARTICLE_CAR_SPLASH, splashpos, splashvel, NULL, 0.0f, this->m_Color);
}
#else
CVector pos;
CVector vel;
for ( int32 i = -3; i < 4; i++ )
{
pos = this->GetPosition();
pos += CVector(-1.5f, 0.5f * float(i), 0.0f);
vel = this->m_vecTarget;
vel.x += -3.0f * CGeneral::GetRandomNumberInRange(0.001f, 0.006f);
vel.y += float(i) * CGeneral::GetRandomNumberInRange(0.001f, 0.006f);
vel.z += CGeneral::GetRandomNumberInRange(0.03f, 0.06f);
CParticle::AddParticle(PARTICLE_CAR_SPLASH, pos, vel, NULL, 0.0f, this->m_Color);
pos = this->GetPosition();
pos += CVector(1.5f, 0.5f * float(i), 0.0f);
vel = this->m_vecTarget;
vel.x += 3.0f * CGeneral::GetRandomNumberInRange(0.001f, 0.006f);
vel.y += float(i) * CGeneral::GetRandomNumberInRange(0.001f, 0.006f);
vel.z += CGeneral::GetRandomNumberInRange(0.03f, 0.06f);
CParticle::AddParticle(PARTICLE_CAR_SPLASH, pos, vel, NULL, 0.0f, this->m_Color);
pos = this->GetPosition();
pos += CVector(0.5f * float(i), -1.5f, 0.0f);
vel = this->m_vecTarget;
vel.x += float(i) * CGeneral::GetRandomNumberInRange(0.001f, 0.006f);
vel.y += -3.0f * CGeneral::GetRandomNumberInRange(0.001f, 0.006f);
vel.z += CGeneral::GetRandomNumberInRange(0.03f, 0.06f);
CParticle::AddParticle(PARTICLE_CAR_SPLASH, pos, vel, NULL, 0.0f, this->m_Color);
pos = this->GetPosition();
pos += CVector(0.5f * float(i), 1.5f, 0.0f);
vel = this->m_vecTarget;
vel.x += float(i) * CGeneral::GetRandomNumberInRange(0.001f, 0.006f);
vel.y += 3.0f * CGeneral::GetRandomNumberInRange(0.001f, 0.006f);
vel.z += CGeneral::GetRandomNumberInRange(0.03f, 0.06f);
CParticle::AddParticle(PARTICLE_CAR_SPLASH, pos, vel, NULL, 0.0f, this->m_Color);
}
for ( int32 i = 0; i < 8; i++ )
{
pos = this->GetPosition();
pos.x += CGeneral::GetRandomNumberInRange(-3.0f, 3.0f);
pos.y += CGeneral::GetRandomNumberInRange(-3.0f, 3.0f);
vel = this->m_vecTarget;
vel.z += CGeneral::GetRandomNumberInRange(0.03f, 0.06f);
CParticle::AddParticle(PARTICLE_CAR_SPLASH, pos, vel, NULL, 0.0f, this->m_Color);
}
#endif
break;
}
case POBJECT_SPLASHES_AROUND:
{
CVector pos = this->GetPosition();
float size = this->m_fSize;
for ( int32 i = 0; i < this->m_nNumEffectCycles; i++ )
{
CVector splashpos = pos;
splashpos.x += CGeneral::GetRandomNumberInRange(-size, size);
splashpos.y += CGeneral::GetRandomNumberInRange(-size, size);
if ( CGeneral::GetRandomNumber() & 1 )
{
CParticle::AddParticle(PARTICLE_RAIN_SPLASH, splashpos, CVector(0.0f, 0.0f, 0.0f),
NULL, 0.1f, this->m_Color);
}
else
{
CParticle::AddParticle(PARTICLE_RAIN_SPLASHUP, splashpos, CVector(0.0f, 0.0f, 0.0f),
NULL, 0.12f, this->m_Color);
}
}
break;
}
case POBJECT_CATALINAS_GUNFLASH:
{
CRGBA flashcolor(120, 120, 120, 255);
CVector vel = this->m_vecTarget;
CVector pos = this->GetPosition();
float size = 1.0f;
if ( this->m_fSize != 0.0f )
size = this->m_fSize;
CParticle::AddParticle(PARTICLE_GUNFLASH, pos, CVector(0.0f, 0.0f, 0.0f), NULL, 0.12f*size, flashcolor);
pos += size * (0.06f * vel);
CParticle::AddParticle(PARTICLE_GUNFLASH, pos, CVector(0.0f, 0.0f, 0.0f), NULL, 0.08f*size, flashcolor);
pos += size * (0.04f * vel);
CParticle::AddParticle(PARTICLE_GUNFLASH, pos, CVector(0.0f, 0.0f, 0.0f), NULL, 0.04f*size, flashcolor);
CVector smokepos = this->GetPosition();
CVector smokevel = 0.1f * vel;
CParticle::AddParticle(PARTICLE_GUNSMOKE2, smokepos, smokevel, NULL, 0.005f*size);
break;
}
case POBJECT_CATALINAS_SHOTGUNFLASH:
{
CRGBA flashcolor(120, 120, 120, 255);
CVector vel = this->m_vecTarget;
float size = 1.0f;
if ( this->m_fSize != 0.0f )
size = this->m_fSize;
CVector pos = this->GetPosition();
CVector velstep = size * (0.1f * vel);
CVector flashpos = pos;
flashpos += velstep;
CParticle::AddParticle(PARTICLE_GUNFLASH, flashpos, CVector(0.0f, 0.0f, 0.0f), NULL, 0.0f, flashcolor);
flashpos += velstep;
CParticle::AddParticle(PARTICLE_GUNFLASH, flashpos, CVector(0.0f, 0.0f, 0.0f), NULL, 0.15f*size, flashcolor);
flashpos += velstep;
CParticle::AddParticle(PARTICLE_GUNFLASH, flashpos, CVector(0.0f, 0.0f, 0.0f), NULL, 0.2f*size, flashcolor);
CParticle::AddParticle(PARTICLE_GUNFLASH, pos, CVector(0.0f, 0.0f, 0.0f), NULL, 0.0f, flashcolor);
CVector smokepos = this->GetPosition();
CVector smokevel = 0.1f*vel;
CParticle::AddParticle(PARTICLE_GUNSMOKE2, smokepos, smokevel, NULL, 0.1f*size);
break;
}
default:
{
if ( this->m_fRandVal != 0.0f )
{
for ( int32 i = 0; i < this->m_nNumEffectCycles; i++ )
{
CVector vel = this->m_vecTarget;
if ( vel.x != 0.0f )
vel.x += CGeneral::GetRandomNumberInRange(-this->m_fRandVal, this->m_fRandVal);
if ( vel.y != 0.0f )
vel.y += CGeneral::GetRandomNumberInRange(-this->m_fRandVal, this->m_fRandVal);
if ( vel.z != 0.0f )
vel.z += CGeneral::GetRandomNumberInRange(-this->m_fRandVal, this->m_fRandVal);
CParticle::AddParticle(this->m_ParticleType, this->GetPosition(), vel, NULL,
this->m_fSize, this->m_Color);
}
}
else
{
for ( int32 i = 0; i < this->m_nNumEffectCycles; i++ )
{
CParticle::AddParticle(this->m_ParticleType, this->GetPosition(), this->m_vecTarget, NULL,
this->m_fSize, this->m_Color);
}
}
break;
}
}
}
}
if ( this->m_nRemoveTimer != 0 && this->m_nRemoveTimer < CTimer::GetTimeInMilliseconds() )
{
MoveToList(&pCloseListHead, &pUnusedListHead, this);
this->m_nState = POBJECTSTATE_FREE;
if ( this->m_Type == POBJECT_FIRE_HYDRANT )
CAudioHydrant::Remove(this);
}
}
void
CParticleObject::UpdateFar(void)
{
if ( this->m_nRemoveTimer != 0 && this->m_nRemoveTimer < CTimer::GetTimeInMilliseconds() )
{
MoveToList(&pFarListHead, &pUnusedListHead, this);
this->m_nState = POBJECTSTATE_FREE;
if ( this->m_Type == POBJECT_FIRE_HYDRANT )
CAudioHydrant::Remove(this);
}
CVector2D dist = this->GetPosition() - TheCamera.GetPosition();
if ( dist.MagnitudeSqr() < SQR(100.0f)/*10000.0f*/ )
{
MoveToList(&pFarListHead, &pCloseListHead, this);
this->m_nState = POBJECTSTATE_UPDATE_CLOSE;
}
}
bool
CParticleObject::SaveParticle(uint8 *buffer, uint32 *length)
{
ASSERT( buffer != NULL );
ASSERT( length != NULL );
int32 numObjects = 0;
for ( CParticleObject *p = pCloseListHead; p != NULL; p = p->m_pNext )
++numObjects;
for ( CParticleObject *p = pFarListHead; p != NULL; p = p->m_pNext )
++numObjects;
*(int32 *)buffer = numObjects;
buffer += sizeof(int32);
int32 objectsLength = sizeof(CParticleObject) * (numObjects + 1);
int32 dataLength = objectsLength + sizeof(int32);
for ( CParticleObject *p = pCloseListHead; p != NULL; p = p->m_pNext )
{
#if 0 // todo better
*(CParticleObject*)buffer = *p;
#else
memcpy(buffer, p, sizeof(CParticleObject));
#endif
buffer += sizeof(CParticleObject);
}
for ( CParticleObject *p = pFarListHead; p != NULL; p = p->m_pNext )
{
#if 0 // todo better
*(CParticleObject*)buffer = *p;
#else
memcpy(buffer, p, sizeof(CParticleObject));
#endif
buffer += sizeof(CParticleObject);
}
*length = dataLength;
return true;
}
bool
CParticleObject::LoadParticle(uint8 *buffer, uint32 length)
{
ASSERT( buffer != NULL );
RemoveAllParticleObjects();
int32 numObjects = *(int32 *)buffer;
buffer += sizeof(int32);
if ( length != sizeof(CParticleObject) * (numObjects + 1) + sizeof(int32) )
return false;
if ( numObjects == 0 )
return true;
int32 i = 0;
while ( i < numObjects )
{
CParticleObject *dst = pUnusedListHead;
CParticleObject *src = (CParticleObject *)buffer;
buffer += sizeof(CParticleObject);
if ( dst == NULL )
return false;
MoveToList(&pUnusedListHead, &pCloseListHead, dst);
dst->m_nState = POBJECTSTATE_UPDATE_CLOSE;
dst->m_Type = src->m_Type;
dst->m_ParticleType = src->m_ParticleType;
dst->SetPosition(src->GetPosition());
dst->m_vecTarget = src->m_vecTarget;
dst->m_nFrameCounter = src->m_nFrameCounter;
dst->m_bRemove = src->m_bRemove;
dst->m_pParticle = NULL;
dst->m_nRemoveTimer = src->m_nRemoveTimer;
dst->m_Color = src->m_Color;
dst->m_fSize = src->m_fSize;
dst->m_fRandVal = src->m_fRandVal;
dst->m_nNumEffectCycles = src->m_nNumEffectCycles;
dst->m_nSkipFrames = src->m_nSkipFrames;
dst->m_nCreationChance = src->m_nCreationChance;
i++;
}
return true;
}
void
CParticleObject::RemoveAllParticleObjects(void)
{
pUnusedListHead = &gPObjectArray[0];
pCloseListHead = NULL;
pFarListHead = NULL;
for ( int32 i = 0; i < MAX_PARTICLEOBJECTS; i++ )
{
if ( i == 0 )
gPObjectArray[i].m_pPrev = NULL;
else
gPObjectArray[i].m_pPrev = &gPObjectArray[i - 1];
if ( i == MAX_PARTICLEOBJECTS-1 )
gPObjectArray[i].m_pNext = NULL;
else
gPObjectArray[i].m_pNext = &gPObjectArray[i + 1];
gPObjectArray[i].m_nState = POBJECTSTATE_FREE;
}
}
void
CParticleObject::MoveToList(CParticleObject **from, CParticleObject **to, CParticleObject *obj)
{
ASSERT( from != NULL );
ASSERT( to != NULL );
ASSERT( obj != NULL );
if ( obj->m_pPrev == NULL )
{
*from = obj->m_pNext;
if ( *from )
(*from)->m_pPrev = NULL;
}
else
{
if ( obj->m_pNext == NULL )
obj->m_pPrev->m_pNext = NULL;
else
{
obj->m_pNext->m_pPrev = obj->m_pPrev;
obj->m_pPrev->m_pNext = obj->m_pNext;
}
}
obj->m_pNext = *to;
obj->m_pPrev = NULL;
*to = obj;
if ( obj->m_pNext )
obj->m_pNext->m_pPrev = obj;
}
| 0 | 0.911959 | 1 | 0.911959 | game-dev | MEDIA | 0.808094 | game-dev | 0.977544 | 1 | 0.977544 |
CriminalRETeam/gta2_re | 6,953 | Source/gtx_0x106C.hpp | #pragma once
#include "Function.hpp"
#include <cstdio>
#include <windows.h>
struct palette_base
{
u16 field_0_tile;
u16 field_2_sprite;
u16 field_4_car_remap;
u16 field_6_red_remap;
u16 field_8_code_obj_remap;
u16 field_A_map_obj_remap;
u16 field_C_user_remap;
u16 field_E_font_remap;
};
struct sprite_base
{
u16 field_0_car;
u16 field_2_ped;
u16 field_4_code_obj;
u16 field_6_map_obj;
u16 field_8_user;
u16 field_A_font;
};
struct font_base
{
u16 field_0_font_count;
u16 field_2_base[1]; // variable � see font_count
};
struct sprite_index
{
EXPORT void sub_5ABAA0(u8 a2);
EXPORT void sub_5ABB00(u8* dst_x);
BYTE* field_0_pData;
u8 field_4_width;
u8 field_5_height;
s16 field_6_pad;
};
struct object_info
{
u8 field_0_model;
u8 field_1_sprites;
};
struct palette_index
{
u16 field_0_phys_palette[16384];
};
struct tile_array
{
u16 field_0[1024];
};
struct delta_entry
{
s16 field_0_which_sprite;
char_type field_2_delta_count;
char_type field_3_pad;
s16 field_4_delta[2];
};
struct door_info
{
char_type rx, ry;
};
class car_info
{
public:
BYTE model;
BYTE sprite;
BYTE w;
BYTE h;
BYTE num_remaps;
BYTE passengers;
BYTE wreck;
BYTE rating;
char_type front_wheel_offset;
char_type rear_wheel_offset;
char_type front_window_offset;
char_type rear_window_offset;
BYTE info_flags;
BYTE info_flags_2;
BYTE remap[1]; // [variable � see num_remaps];
BYTE num_doors;
door_info doors[1]; // [variable � see num_doors];
bool has_remaps() const { return num_remaps > 1; }
};
struct car_info_container
{
car_info_container()
{
field_400_count = 0;
memset(field_0, 0, sizeof(field_0));
}
car_info* field_0[256];
u8 field_400_count;
//char_type field_401;// pad
//char_type field_402;// pad
//char_type field_403;// pad
};
struct delta_store_entry
{
s16 field_0_offset;
char_type field_2_len;
char_type field_3_data[1]; // variable � see field_2_len
};
namespace tile_spec
{
enum
{
none = 1,
grass_dirt_floor = 2,
road_junction_special = 3,
water = 4,
electrified_floor = 5,
electrified_platform_floor = 6,
wood_floor = 7,
metal_floor = 8,
metal_wall = 9,
grass_dirt_wall = 10,
};
//static_assert(sizeof(tile_spec) == 1)
} // namespace tile_spec
class gtx_0x106C
{
public:
// inline
bool has_tiles_4C2EE0() const
{
return field_3C_tiles != 0;
}
// inline
u8* get_tile_4C2EB0(u16 tile_num)
{
return &field_3C_tiles[(((tile_num & ~3) * 64) + (tile_num & 3)) * 64];
}
EXPORT car_info* get_car_info_5AA3B0(u8 idx);
EXPORT BYTE* get_car_remap_5AA3D0(u8 idx);
EXPORT s32 sub_5AA3F0(u16 a2, u8 a3);
EXPORT sprite_index* get_sprite_index_5AA440(u16 idx);
EXPORT u16 convert_sprite_pal_5AA460(s32 type, s16 sprite_pal);
EXPORT s16 sub_5AA4F0(s32 a2);
EXPORT s16 sub_5AA560(s32 a2);
EXPORT s16 convert_pal_type_5AA5F0(s32 type, s16 pal);
EXPORT BYTE* GetPalData_5AA6A0(u16 a2);
EXPORT u16 get_phys_pal_5AA6F0(u16 palId);
EXPORT u16 sub_5AA710(u16 a2, s16 a3);
EXPORT u16 sub_5AA760(u16* a2, wchar_t* a3);
EXPORT u16 space_width_5AA7B0(u16* a2);
EXPORT s16 sub_5AA800(u16* a2);
EXPORT bool sub_5AA850(u16 tile_idx);
EXPORT s16 sub_5AA870(u16 tile_idx);
EXPORT s16 sub_5AA890();
EXPORT void* GetTiles_5AA8C0();
EXPORT s16 get_physical_palettes_len_5AA900();
EXPORT object_info* get_map_object_info_5AA910(u16 idx);
EXPORT void sub_5AA930(u16 tile_idx, s16 tile_val);
EXPORT void create_tile_num_array_5AA950();
EXPORT void sub_5AA9A0(s32 a2);
EXPORT void sub_5AAB30(u32 delx_chunk_size);
EXPORT void sub_5AABF0();
EXPORT void SetSpriteIndexDataPtrs_5AAC40();
EXPORT void sub_5AAC70();
EXPORT void load_car_info_5AAD50(u32 cari_chunk_size);
EXPORT void load_delta_index_5AAD80(u32 delx_chunk_size);
EXPORT void load_delta_store_5AADD0(u32 dels_chunk_size);
EXPORT void load_tiles_5AADF0(u32 tile_chunk_len);
EXPORT void skip_ovly_5AAE20(u32 a1);
EXPORT void skip_psxt_5AAE30(u32 a1);
EXPORT void load_sprite_graphics_5AAE40(u32 sprg_chunk_len);
EXPORT void load_physical_palettes_5AAE70(u32 ppal_chunk_size);
EXPORT void load_palette_index_5AAEA0(u32 palx_chunk_len);
EXPORT void load_map_object_info_5AAF00(u32 obji_chunk_len);
EXPORT void load_sprite_index_5AAF80(u32 sprx_chunk_size);
EXPORT void sub_5AAFE0(u16 a1);
EXPORT void load_font_base_5AB0F0(u32 fonb_chunk_size);
EXPORT static u16 __stdcall ConvertToVirtualOffsets_5AB1A0(u16* pOffsets, u32 offsetsCount);
EXPORT static void __stdcall ConvertToVirtualOffsets_5AB1C0(u16* pBuffer, u32 len);
EXPORT void load_sprite_base_5AB210(u32 sprite_base_chunk_size);
EXPORT void load_palete_base_5AB2C0(u32 palette_base_chunk_len);
EXPORT bool sub_5AB380(u8 car_id);
EXPORT void load_car_recycling_info_5AB3C0(u32 recy_chunk_size);
EXPORT void read_spec_5AB3F0(u32 read_size2);
EXPORT void load_spec_5AB450();
EXPORT void LoadChunk_5AB4B0(const char_type* Str1, u32 chunk_len);
EXPORT void sub_5AB720();
EXPORT void LoadSty_5AB750(const char_type* pStyFileName);
// 0x5AB820
EXPORT gtx_0x106C();
// 0x5AB8A0
EXPORT ~gtx_0x106C();
// inlined v9.6f, 0x432850
u8 get_number_of_cars() const
{
return field_5C_cari->field_400_count;
}
// inlined v9.6f, 0x420200
u8 does_car_exist(u8 iParm1) const
{
return this->field_5C_cari->field_0[iParm1] != NULL;
}
s16 field_0_totalPalBase;
u16 field_2_font_base_total;
s16 field_4_sprite_index_count;
u16 field_6_map_object_info_len;
s16 field_8_physical_palettes_len;
s16 field_A;
palette_base* field_C_palette_base2;
palette_base* field_10_palette_base1;
sprite_base* field_14_sprite_base2;
sprite_base* field_18_sprite_base1;
font_base* field_1C_font_base;
sprite_index* field_20_sprite_index;
object_info* field_24_map_object_info;
palette_index* field_28_palette_index;
void* field_2C_physical_palettes;
void* field_30_physical_palettes_size;
BYTE* field_34_sprite_graphics;
void* field_38;
u8* field_3C_tiles;
tile_array* field_40_tile;
void* field_44_aligned_tiles_size;
delta_store_entry* field_48_delta_store;
delta_entry* field_4C_delta_index;
void* field_50_delta_buffer;
s32 field_54_del;
car_info** field_58_car_info;
car_info_container* field_5C_cari;
s32 field_60_delta_len;
u8* field_64_car_recycling_info;
s16 field_68_recy_chunk_size;
char_type field_6A;
char_type field_6B;
s32 field_6C_spec[1024];
};
EXTERN_GLOBAL(gtx_0x106C*, gGtx_0x106C_703DD4);
| 0 | 0.621473 | 1 | 0.621473 | game-dev | MEDIA | 0.431375 | game-dev | 0.591787 | 1 | 0.591787 |
EssentialsX/Essentials | 2,072 | Essentials/src/main/java/com/earth2me/essentials/commands/Commandsetwarp.java | package com.earth2me.essentials.commands;
import com.earth2me.essentials.User;
import com.earth2me.essentials.api.IWarps;
import com.earth2me.essentials.utils.NumberUtil;
import com.earth2me.essentials.utils.StringUtil;
import net.ess3.api.TranslatableException;
import net.essentialsx.api.v2.events.WarpModifyEvent;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Server;
public class Commandsetwarp extends EssentialsCommand {
public Commandsetwarp() {
super("setwarp");
}
@Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
if (args.length == 0) {
throw new NotEnoughArgumentsException();
}
if (NumberUtil.isInt(args[0]) || args[0].isEmpty()) {
throw new TranslatableException("invalidWarpName");
}
final IWarps warps = ess.getWarps();
Location warpLoc = null;
try {
warpLoc = warps.getWarp(args[0]);
} catch (final WarpNotFoundException ignored) {
}
if (warpLoc == null) {
final WarpModifyEvent event = new WarpModifyEvent(user, args[0], null, user.getLocation(), WarpModifyEvent.WarpModifyCause.CREATE);
Bukkit.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return;
}
warps.setWarp(user, args[0], user.getLocation());
} else if (user.isAuthorized("essentials.warp.overwrite." + StringUtil.safeString(args[0]))) {
final WarpModifyEvent event = new WarpModifyEvent(user, args[0], warpLoc, user.getLocation(), WarpModifyEvent.WarpModifyCause.UPDATE);
Bukkit.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return;
}
warps.setWarp(user, args[0], user.getLocation());
} else {
throw new TranslatableException("warpOverwrite");
}
user.sendTl("warpSet", args[0]);
}
}
| 0 | 0.924635 | 1 | 0.924635 | game-dev | MEDIA | 0.974787 | game-dev | 0.963979 | 1 | 0.963979 |
jhu-cisst/cisst | 1,850 | cisstParameterTypes/prmForceTorqueJointSet.cdg | // -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
// ex: set filetype=cpp softtabstop=4 shiftwidth=4 tabstop=4 cindent expandtab:
inline-header {
#include <cisstVector/vctDynamicVectorTypes.h>
#include <cisstMultiTask/mtsGenericObject.h>
#include <cisstParameterTypes/prmForwardDeclarations.h>
// Always include last
#include <cisstParameterTypes/prmExport.h>
}
class {
name prmForceTorqueJointSet; // required
attribute CISST_EXPORT;
base-class {
type mtsGenericObject;
is-data true;
}
member {
name ForceTorque;
type vctDynamicVector<double>;
description Desired effort;
}
member {
name Mask;
type vctDynamicVector<bool>;
default vctDynamicVector<bool>();
deprecated true;
}
// from original prmMotionBase
member {
name BlockingFlag;
type prmBlocking;
default prmBlocking::NO_WAIT;
deprecated true;
}
member {
name BlendingFactor;
type bool;
default false;
deprecated true;
}
member {
name IsPreemptable;
type bool;
default true;
deprecated true;
}
member {
name IsGoalOnly;
type bool;
default true;
deprecated true;
}
inline-header {
public:
inline CISST_DEPRECATED prmForceTorqueJointSet(const size_t size) {
mForceTorque.SetSize(size);
mForceTorque.SetAll(0.0);
}
void inline CISST_DEPRECATED SetSize(const size_t size) {
mForceTorque.SetSize(size);
mForceTorque.SetAll(0.0);
}
private:
CMN_DECLARE_SERVICES(CMN_DYNAMIC_CREATION, CMN_LOG_ALLOW_DEFAULT);
}
}
inline-header {
CMN_DECLARE_SERVICES_INSTANTIATION(prmForceTorqueJointSet);
}
| 0 | 0.963098 | 1 | 0.963098 | game-dev | MEDIA | 0.311859 | game-dev | 0.663588 | 1 | 0.663588 |
CICM/HoaLibrary | 5,879 | ThirdParty/JuceModules/juce_box2d/box2d/Dynamics/Joints/b2PrismaticJoint.h | /*
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* 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_PRISMATIC_JOINT_H
#define B2_PRISMATIC_JOINT_H
#include "b2Joint.h"
/// Prismatic joint definition. This requires defining a line of
/// motion using an axis and an anchor point. The definition uses local
/// anchor points and a local axis so that the initial configuration
/// can violate the constraint slightly. The joint translation is zero
/// when the local anchor points coincide in world space. Using local
/// anchors and a local axis helps when saving and loading a game.
struct b2PrismaticJointDef : public b2JointDef
{
b2PrismaticJointDef()
{
type = e_prismaticJoint;
localAnchorA.SetZero();
localAnchorB.SetZero();
localAxisA.Set(1.0f, 0.0f);
referenceAngle = 0.0f;
enableLimit = false;
lowerTranslation = 0.0f;
upperTranslation = 0.0f;
enableMotor = false;
maxMotorForce = 0.0f;
motorSpeed = 0.0f;
}
/// Initialize the bodies, anchors, axis, and reference angle using the world
/// anchor and unit world axis.
void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, const b2Vec2& axis);
/// The local anchor point relative to bodyA's origin.
b2Vec2 localAnchorA;
/// The local anchor point relative to bodyB's origin.
b2Vec2 localAnchorB;
/// The local translation unit axis in bodyA.
b2Vec2 localAxisA;
/// The constrained angle between the bodies: bodyB_angle - bodyA_angle.
float32 referenceAngle;
/// Enable/disable the joint limit.
bool enableLimit;
/// The lower translation limit, usually in meters.
float32 lowerTranslation;
/// The upper translation limit, usually in meters.
float32 upperTranslation;
/// Enable/disable the joint motor.
bool enableMotor;
/// The maximum motor torque, usually in N-m.
float32 maxMotorForce;
/// The desired motor speed in radians per second.
float32 motorSpeed;
};
/// A prismatic joint. This joint provides one degree of freedom: translation
/// along an axis fixed in bodyA. Relative rotation is prevented. You can
/// use a joint limit to restrict the range of motion and a joint motor to
/// drive the motion or to model joint friction.
class b2PrismaticJoint : public b2Joint
{
public:
b2Vec2 GetAnchorA() const;
b2Vec2 GetAnchorB() const;
b2Vec2 GetReactionForce(float32 inv_dt) const;
float32 GetReactionTorque(float32 inv_dt) const;
/// The local anchor point relative to bodyA's origin.
const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; }
/// The local anchor point relative to bodyB's origin.
const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; }
/// The local joint axis relative to bodyA.
const b2Vec2& GetLocalAxisA() const { return m_localXAxisA; }
/// Get the reference angle.
float32 GetReferenceAngle() const { return m_referenceAngle; }
/// Get the current joint translation, usually in meters.
float32 GetJointTranslation() const;
/// Get the current joint translation speed, usually in meters per second.
float32 GetJointSpeed() const;
/// Is the joint limit enabled?
bool IsLimitEnabled() const;
/// Enable/disable the joint limit.
void EnableLimit(bool flag);
/// Get the lower joint limit, usually in meters.
float32 GetLowerLimit() const;
/// Get the upper joint limit, usually in meters.
float32 GetUpperLimit() const;
/// Set the joint limits, usually in meters.
void SetLimits(float32 lower, float32 upper);
/// Is the joint motor enabled?
bool IsMotorEnabled() const;
/// Enable/disable the joint motor.
void EnableMotor(bool flag);
/// Set the motor speed, usually in meters per second.
void SetMotorSpeed(float32 speed);
/// Get the motor speed, usually in meters per second.
float32 GetMotorSpeed() const;
/// Set the maximum motor force, usually in N.
void SetMaxMotorForce(float32 force);
float32 GetMaxMotorForce() const { return m_maxMotorForce; }
/// Get the current motor force given the inverse time step, usually in N.
float32 GetMotorForce(float32 inv_dt) const;
/// Dump to b2Log
void Dump();
protected:
friend class b2Joint;
friend class b2GearJoint;
b2PrismaticJoint(const b2PrismaticJointDef* def);
void InitVelocityConstraints(const b2SolverData& data);
void SolveVelocityConstraints(const b2SolverData& data);
bool SolvePositionConstraints(const b2SolverData& data);
// Solver shared
b2Vec2 m_localAnchorA;
b2Vec2 m_localAnchorB;
b2Vec2 m_localXAxisA;
b2Vec2 m_localYAxisA;
float32 m_referenceAngle;
b2Vec3 m_impulse;
float32 m_motorImpulse;
float32 m_lowerTranslation;
float32 m_upperTranslation;
float32 m_maxMotorForce;
float32 m_motorSpeed;
bool m_enableLimit;
bool m_enableMotor;
b2LimitState m_limitState;
// Solver temp
int32 m_indexA;
int32 m_indexB;
b2Vec2 m_localCenterA;
b2Vec2 m_localCenterB;
float32 m_invMassA;
float32 m_invMassB;
float32 m_invIA;
float32 m_invIB;
b2Vec2 m_axis, m_perp;
float32 m_s1, m_s2;
float32 m_a1, m_a2;
b2Mat33 m_K;
float32 m_motorMass;
};
inline float32 b2PrismaticJoint::GetMotorSpeed() const
{
return m_motorSpeed;
}
#endif
| 0 | 0.888226 | 1 | 0.888226 | game-dev | MEDIA | 0.974018 | game-dev | 0.855136 | 1 | 0.855136 |
CleanroomMC/Cleanroom | 22,190 | src/main/java/net/minecraftforge/fml/relauncher/libraries/LibraryManager.java | /*
* Minecraft Forge
* Copyright (c) 2016-2020.
*
* This library 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 version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.relauncher.libraries;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.security.CodeSource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.maven.artifact.versioning.ArtifactVersion;
import com.google.common.io.ByteStreams;
import com.google.common.io.Files;
import net.minecraft.launchwrapper.Launch;
import net.minecraftforge.common.ForgeVersion;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.relauncher.FMLLaunchHandler;
public class LibraryManager
{
public static final boolean DISABLE_EXTERNAL_MANIFEST = Boolean.parseBoolean(System.getProperty("forge.disable_external_manifest", "false"));
public static final boolean ENABLE_AUTO_MOD_MOVEMENT = Boolean.parseBoolean(System.getProperty("forge.enable_auto_mod_movement", "false"));
private static final String LIBRARY_DIRECTORY_OVERRIDE = System.getProperty("forge.lib_folder", null);
private static final List<String> skipContainedDeps = Arrays.asList(System.getProperty("fml.skipContainedDeps","").split(",")); //TODO: Is this used by anyone in the real world? TODO: Remove in 1.13.
private static final FilenameFilter MOD_FILENAME_FILTER = (dir, name) -> name.endsWith(".jar") || name.endsWith(".zip"); //TODO: Disable support for zip in 1.13
private static final Comparator<File> FILE_NAME_SORTER_INSENSITVE = Comparator.comparing(o -> o.getName().toLowerCase(Locale.ENGLISH));
public static final Attributes.Name MODSIDE = new Attributes.Name("ModSide");
public static final Attributes.Name MODCONTAINSDEPS = new Attributes.Name("ContainedDeps");
private static final Attributes.Name MAVEN_ARTIFACT = new Attributes.Name("Maven-Artifact");
private static final Attributes.Name TIMESTAMP = new Attributes.Name("Timestamp");
private static final Attributes.Name MD5 = new Attributes.Name("MD5");
private static Repository libraries_dir = null;
private static Set<File> processed = new HashSet<File>();
public static void setup(File minecraftHome)
{
File libDir = findLibraryFolder(minecraftHome);
FMLLog.log.debug("Determined Minecraft Libraries Root: {}", libDir);
Repository old = Repository.replace(libDir, "libraries");
if (old != null)
FMLLog.log.debug(" Overwriting Previous: {}", old);
libraries_dir = Repository.get("libraries");
File mods = new File(minecraftHome, "mods");
File mods_ver = new File(mods, ForgeVersion.mcVersion);
ModList memory = null;
if (!ENABLE_AUTO_MOD_MOVEMENT)
{
Repository repo = new LinkRepository(new File(mods, "memory_repo"));
memory = new MemoryModList(repo);
ModList.cache.put("MEMORY", memory);
Repository.cache.put("MEMORY", repo);
}
for (File dir : new File[]{mods, mods_ver})
cleanDirectory(dir, ENABLE_AUTO_MOD_MOVEMENT ? ModList.create(new File(dir, "mod_list.json"), minecraftHome) : memory, mods_ver, mods);
for (ModList list : ModList.getKnownLists(minecraftHome))
{
Repository repo = list.getRepository() == null ? libraries_dir : list.getRepository();
List<Artifact> artifacts = list.getArtifacts();
// extractPacked adds artifacts to the list. As such, we can't use an Iterator to traverse it.
for (int i = 0; i < artifacts.size(); i++)
{
Artifact artifact = artifacts.get(i);
Artifact resolved = repo.resolve(artifact);
if (resolved != null)
{
File target = repo.getFile(resolved.getPath());
if (target.exists())
extractPacked(target, list, mods_ver, mods);
}
}
}
}
private static File findLibraryFolder(File minecraftHome)
{
if (LIBRARY_DIRECTORY_OVERRIDE != null)
{
FMLLog.log.error("System variable set to override Library Directory: {}", LIBRARY_DIRECTORY_OVERRIDE);
return new File(LIBRARY_DIRECTORY_OVERRIDE);
}
CodeSource source = ArtifactVersion.class.getProtectionDomain().getCodeSource();
if (source == null)
{
FMLLog.log.error("Unable to determine codesource for {}. Using default libraries directory.", ArtifactVersion.class.getName());
return new File(minecraftHome, "libraries");
}
try
{
File apache = new File(source.getLocation().toURI());
if (apache.isFile())
apache = apache.getParentFile(); //Get to a directory, this *should* always be the case...
apache = apache.getParentFile(); //Skip the version folder. In case we ever update the version, I don't want to edit this code again.
String comp = apache.getAbsolutePath().toLowerCase(Locale.ENGLISH).replace('\\', '/');
if (!comp.endsWith("/"))
comp += '/';
if (!comp.endsWith("/org/apache/maven/maven-artifact/"))
{
FMLLog.log.error("Apache Maven library folder was not in the format expected. Using default libraries directory.");
FMLLog.log.error("Full: {}", new File(source.getLocation().toURI()));
FMLLog.log.error("Trimmed: {}", comp);
return new File(minecraftHome, "libraries");
}
// maven-artifact /maven /apache /org /libraries
return apache .getParentFile().getParentFile().getParentFile().getParentFile();
}
catch (URISyntaxException e)
{
FMLLog.log.error(FMLLog.log.getMessageFactory().newMessage("Unable to determine file for {}. Using default libraries directory.", ArtifactVersion.class.getName()), e);
}
return new File(minecraftHome, "libraries"); //Everything else failed, return the default.
}
private static void cleanDirectory(File dir, ModList modlist, File... modDirs)
{
if (!dir.exists())
return;
FMLLog.log.debug("Cleaning up mods folder: {}", dir);
for (File file : dir.listFiles(f -> f.isFile() && f.getName().endsWith(".jar")))
{
Pair<Artifact, byte[]> ret = extractPacked(file, modlist, modDirs);
if (ret != null)
{
Artifact artifact = ret.getLeft();
Repository repo = modlist.getRepository() == null ? libraries_dir : modlist.getRepository();
File moved = repo.archive(artifact, file, ret.getRight());
processed.add(moved);
}
}
try
{
if (modlist.changed())
modlist.save();
}
catch (IOException e)
{
FMLLog.log.error(FMLLog.log.getMessageFactory().newMessage("Error updating modlist file {}", modlist.getName()), e);
}
}
private static Pair<Artifact, byte[]> extractPacked(File file, ModList modlist, File... modDirs)
{
if (processed.contains(file))
{
FMLLog.log.debug("File already proccessed {}, Skipping", file.getAbsolutePath());
return null;
}
JarFile jar = null;
try
{
jar = new JarFile(file);
FMLLog.log.debug("Examining file: {}", file.getName());
processed.add(file);
return extractPacked(jar, modlist, modDirs);
}
catch (IOException ioe)
{
FMLLog.log.error("Unable to read the jar file {} - ignoring", file.getName(), ioe);
}
finally
{
try {
if (jar != null)
jar.close();
} catch (IOException e) {}
}
return null;
}
private static Pair<Artifact, byte[]> extractPacked(JarFile jar, ModList modlist, File... modDirs) throws IOException
{
Attributes attrs;
if (jar.getManifest() == null)
return null;
JarEntry manifest_entry = jar.getJarEntry(JarFile.MANIFEST_NAME);
if (manifest_entry == null)
manifest_entry = jar.stream().filter(e -> JarFile.MANIFEST_NAME.equals(e.getName().toUpperCase(Locale.ENGLISH))).findFirst().get(); //We know that getManifest returned non-null so we know there is *some* entry that matches the manifest file. So we dont need to empty check.
attrs = jar.getManifest().getMainAttributes();
String modSide = attrs.getValue(LibraryManager.MODSIDE);
if (modSide != null && !"BOTH".equals(modSide) && !FMLLaunchHandler.side().name().equals(modSide))
return null;
if (attrs.containsKey(MODCONTAINSDEPS))
{
for (String dep : attrs.getValue(MODCONTAINSDEPS).split(" "))
{
if (!dep.endsWith(".jar"))
{
FMLLog.log.error("Contained Dep is not a jar file: {}", dep);
throw new IllegalStateException("Invalid contained dep, Must be jar: " + dep);
}
if (jar.getJarEntry(dep) == null && jar.getJarEntry("META-INF/libraries/" + dep) != null)
dep = "META-INF/libraries/" + dep;
JarEntry depEntry = jar.getJarEntry(dep);
if (depEntry == null)
{
FMLLog.log.error("Contained Dep is not in the jar: {}", dep);
throw new IllegalStateException("Invalid contained dep, Missing from jar: " + dep);
}
String depEndName = new File(dep).getName(); // extract last part of name
if (skipContainedDeps.contains(dep) || skipContainedDeps.contains(depEndName))
{
FMLLog.log.error("Skipping dep at request: {}", dep);
continue;
}
Attributes meta = null;
byte[] data = null;
byte[] manifest_data = null;
JarEntry metaEntry = jar.getJarEntry(dep + ".meta");
if (metaEntry != null)
{
manifest_data = readAll(jar.getInputStream(metaEntry));
meta = new Manifest(new ByteArrayInputStream(manifest_data)).getMainAttributes();
}
else
{
data = readAll(jar.getInputStream(depEntry));
try (ZipInputStream zi = new ZipInputStream(new ByteArrayInputStream(data))) //We use zip input stream directly, as the current Oracle implementation of JarInputStream only works when the manifest is the First/Second entry in the jar...
{
ZipEntry ze = null;
while ((ze = zi.getNextEntry()) != null)
{
if (ze.getName().equalsIgnoreCase(JarFile.MANIFEST_NAME))
{
manifest_data = readAll(zi);
meta = new Manifest(new ByteArrayInputStream(manifest_data)).getMainAttributes();
break;
}
}
}
}
if (meta == null || !meta.containsKey(MAVEN_ARTIFACT)) //Ugh I really don't want to do backwards compatibility here, I want to force modders to provide information... TODO: Remove in 1.13?
{
boolean found = false;
for (File dir : modDirs)
{
File target = new File(dir, depEndName);
if (target.exists())
{
FMLLog.log.debug("Found existing ContainDep extracted to {}, skipping extraction", target.getCanonicalPath());
found = true;
}
}
if (!found)
{
File target = new File(modDirs[0], depEndName);
FMLLog.log.debug("Extracting ContainedDep {} from {} to {}", dep, jar.getName(), target.getCanonicalPath());
try
{
Files.createParentDirs(target);
try
(
FileOutputStream out = new FileOutputStream(target);
InputStream in = data == null ? jar.getInputStream(depEntry) : new ByteArrayInputStream(data)
)
{
ByteStreams.copy(in, out);
}
FMLLog.log.debug("Extracted ContainedDep {} from {} to {}", dep, jar.getName(), target.getCanonicalPath());
extractPacked(target, modlist, modDirs);
}
catch (IOException e)
{
FMLLog.log.error("An error occurred extracting dependency", e);
}
}
}
else
{
try
{
Artifact artifact = readArtifact(modlist.getRepository(), meta);
File target = artifact.getFile();
if (target.exists())
{
FMLLog.log.debug("Found existing ContainedDep {}({}) from {} extracted to {}, skipping extraction", dep, artifact.toString(), target.getCanonicalPath(), jar.getName());
if (!ENABLE_AUTO_MOD_MOVEMENT)
{
Pair<?, ?> child = extractPacked(target, modlist, modDirs); //If we're not building a real list we have to re-build the dep list every run. So search down.
if (child == null && metaEntry != null) //External meta with no internal name... If there is a internal name, we trust that that name is the correct one.
{
modlist.add(artifact);
}
}
}
else
{
FMLLog.log.debug("Extracting ContainedDep {}({}) from {} to {}", dep, artifact.toString(), jar.getName(), target.getCanonicalPath());
Files.createParentDirs(target);
try
(
FileOutputStream out = new FileOutputStream(target);
InputStream in = data == null ? jar.getInputStream(depEntry) : new ByteArrayInputStream(data)
)
{
ByteStreams.copy(in, out);
}
FMLLog.log.debug("Extracted ContainedDep {}({}) from {} to {}", dep, artifact.toString(), jar.getName(), target.getCanonicalPath());
if (artifact.isSnapshot())
{
SnapshotJson json = SnapshotJson.create(artifact.getSnapshotMeta());
json.add(new SnapshotJson.Entry(artifact.getTimestamp(), meta.getValue(MD5)));
json.write(artifact.getSnapshotMeta());
}
if (!DISABLE_EXTERNAL_MANIFEST)
{
File meta_target = new File(target.getAbsolutePath() + ".meta");
Files.write(manifest_data, meta_target);
}
Pair<?, ?> child = extractPacked(target, modlist, modDirs);
if (child == null && metaEntry != null) //External meta with no internal name... If there is a internal name, we trust that that name is the correct one.
{
modlist.add(artifact);
}
}
}
catch (NumberFormatException nfe)
{
FMLLog.log.error(FMLLog.log.getMessageFactory().newMessage("An error occurred extracting dependency. Invalid Timestamp: {}", meta.getValue(TIMESTAMP)), nfe);
}
catch (IOException e)
{
FMLLog.log.error("An error occurred extracting dependency", e);
}
}
}
}
if (attrs.containsKey(MAVEN_ARTIFACT))
{
Artifact artifact = readArtifact(modlist.getRepository(), attrs);
modlist.add(artifact);
return Pair.of(artifact, readAll(jar.getInputStream(manifest_entry)));
}
return null;
}
private static Artifact readArtifact(Repository repo, Attributes meta)
{
String timestamp = meta.getValue(TIMESTAMP);
if (timestamp != null)
timestamp = SnapshotJson.TIMESTAMP.format(new Date(Long.parseLong(timestamp)));
return new Artifact(repo, meta.getValue(MAVEN_ARTIFACT), timestamp);
}
private static byte[] readAll(InputStream in) throws IOException
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
int read = -1;
byte[] data = new byte[1024 * 16];
while ((read = in.read(data, 0, data.length)) != -1)
out.write(data, 0, read);
out.flush();
return out.toByteArray();
}
public static List<Artifact> flattenLists(File mcDir)
{
List<Artifact> merged = new ArrayList<>();
for (ModList list : ModList.getBasicLists(mcDir))
{
for (Artifact art : list.flatten())
{
Optional<Artifact> old = merged.stream().filter(art::matchesID).findFirst();
if (!old.isPresent())
{
merged.add(art);
}
else if (old.get().getVersion().compareTo(art.getVersion()) < 0)
{
merged.add(merged.indexOf(old.get()), art);
merged.remove(old.get());
}
}
}
return merged;
}
public static List<File> gatherLegacyCanidates(File mcDir)
{
List<File> list = new ArrayList<>();
@SuppressWarnings("unchecked")
Map<String,String> args = (Map<String, String>)Launch.blackboard.get("forgeLaunchArgs");
String extraMods = args.get("--mods");
if (extraMods != null)
{
FMLLog.log.info("Found mods from the command line:");
for (String mod : extraMods.split(","))
{
File file = new File(mcDir, mod);
if (!file.exists())
{
FMLLog.log.info(" Failed to find mod file {} ({})", mod, file.getAbsolutePath());
}
else if (!list.contains(file))
{
FMLLog.log.debug(" Adding {} ({}) to the mod list", mod, file.getAbsolutePath());
list.add(file);
}
else if (!list.contains(file))
{
FMLLog.log.debug(" Duplicte command line mod detected {} ({})", mod, file.getAbsolutePath());
}
}
}
for (String dir : new String[]{"mods", "mods" + File.separatorChar + ForgeVersion.mcVersion})
{
File base = new File(mcDir, dir);
if (!base.isDirectory() || !base.exists())
continue;
FMLLog.log.info("Searching {} for mods", base.getAbsolutePath());
for (File f : base.listFiles(MOD_FILENAME_FILTER))
{
if (!list.contains(f))
{
FMLLog.log.debug(" Adding {} to the mod list", f.getName());
list.add(f);
}
}
}
ModList memory = ModList.cache.get("MEMORY");
if (!ENABLE_AUTO_MOD_MOVEMENT && memory != null && memory.getRepository() != null)
memory.getRepository().filterLegacy(list);
list.sort(FILE_NAME_SORTER_INSENSITVE);
return list;
}
public static Repository getDefaultRepo()
{
return libraries_dir;
}
}
| 0 | 0.987744 | 1 | 0.987744 | game-dev | MEDIA | 0.435767 | game-dev | 0.983752 | 1 | 0.983752 |
gomint/gomint | 1,705 | gomint-server/src/main/java/io/gomint/server/world/block/Beetroot.java | package io.gomint.server.world.block;
import io.gomint.inventory.item.ItemBeetroot;
import io.gomint.inventory.item.ItemBeetrootSeeds;
import io.gomint.inventory.item.ItemStack;
import io.gomint.server.registry.RegisterInfo;
import io.gomint.world.block.BlockBeetroot;
import io.gomint.world.block.BlockType;
import java.util.ArrayList;
import java.util.List;
/**
* @author geNAZt
* @version 1.0
*/
@RegisterInfo(sId = "minecraft:beetroot")
public class Beetroot extends Growable implements BlockBeetroot {
@Override
public boolean transparent() {
return true;
}
@Override
public boolean solid() {
return false;
}
@Override
public boolean canPassThrough() {
return true;
}
@Override
public long breakTime() {
return 0;
}
@Override
public List<ItemStack<?>> drops(ItemStack<?> itemInHand) {
if (GROWTH.maxed(this)) {
List<ItemStack<?>> drops = new ArrayList<>() {{
add(ItemBeetroot.create(1)); // Beetroot
}};
// Randomize seeds
int amountOfSeeds = SEED_RANDOMIZER.next();
if (amountOfSeeds > 0) {
drops.add(ItemBeetrootSeeds.create(amountOfSeeds)); // Seeds
}
return drops;
} else {
return new ArrayList<>() {{
add(ItemBeetrootSeeds.create(1)); // Seeds
}};
}
}
@Override
public float blastResistance() {
return 0.0f;
}
@Override
public BlockType blockType() {
return BlockType.BEETROOT;
}
@Override
public boolean canBeBrokenWithHand() {
return true;
}
}
| 0 | 0.847732 | 1 | 0.847732 | game-dev | MEDIA | 0.994392 | game-dev | 0.782113 | 1 | 0.782113 |
auQuiksilver/Apex-Framework | 4,095 | Apex_framework.terrain/code/functions/fn_searchNearbyBuilding.sqf | /*
File: fn_searchNearbyBuilding.sqf
Author:
Quiksilver
Last Modified:
28/05/2022 A3 2.10 by Quiksilver
Description:
search a building
https://community.bistudio.com/wiki/moveTo
https://community.bistudio.com/wiki/moveToCompleted
https://community.bistudio.com/wiki/moveToFailed
https://community.bistudio.com/wiki/Category:Command_Group:_Unit_Control
This function needs a bit of work, dont necessarily want to have it be a "guns up" search or at fast pace.
_QS_script = [_grp,[_targetBuilding,(count (_targetBuilding buildingPos -1))]] spawn (missionNamespace getVariable 'QS_fnc_searchNearbyBuilding');
_______________________________________________________________*/
params [
['_grp',grpNull],
['_buildingData',[objNull,0]],
['_timeout',180],
['_AISystem',TRUE]
];
_buildingData params [
['_building',objNull],
['_buildingPositionsCount',0]
];
if (isNull _building) then {
_buildingData = [_leader,100] call (missionNamespace getVariable 'QS_fnc_getNearestBuilding');
_buildingData params [
['_building',objNull],
['_buildingPositionsCount',0]
];
};
if (
(isNull _building) ||
{(_buildingPositionsCount isEqualTo 0)}
) exitWith {};
private _buildingPositions = [_building,_building buildingPos -1] call (missionNamespace getVariable 'QS_fnc_customBuildingPositions');
_buildingPositionsCount = count _buildingPositions;
private _leader = leader _grp;
private _startPos = getPosATL _leader;
private _behaviour = behaviour _leader;
_grp setBehaviour 'AWARE';
_grp setFormation 'DIAMOND';
private _attackEnabled = attackEnabled _grp;
if (_attackEnabled) then {
_grp enableAttack FALSE;
};
private _unit = objNull;
{
_unit = _x;
{
_grp forgetTarget _x;
_unit forgetTarget _x;
} forEach (_unit targets [TRUE,0]);
{
_unit enableAIFeature [_x,FALSE];
} forEach ['COVER','SUPPRESSION'];
_unit forceSpeed 24;
_unit setAnimSpeedCoef 1.2;
_unit enableStamina FALSE;
_unit enableFatigue FALSE;
} count (units _grp);
_grp move (getPosATL _building);
_grp setFormDir (_leader getDir _building);
doStop (units _grp);
uiSleep 0.1;
(units _grp) doMove (selectRandom _buildingPositions);
private _size = (sizeOf (typeOf _building)) * 2;
_duration = diag_tickTime + _timeout;
for '_x' from 0 to 1 step 0 do {
if (
(diag_tickTime > _duration) ||
{(!alive _building)} ||
{(_AISystem && {(!(_building in (missionNamespace getVariable ['QS_AI_hostileBuildings',[]])))})}
) exitWith {};
_aliveUnits = [];
{
_unit = _x;
if (alive _unit) then {
if ((({((lifeState _x) in ['HEALTHY','INJURED'])} count (units (group _x))) > 1) && (_unit isNotEqualTo (leader (group _unit)))) then {
_aliveUnits pushBack _unit;
} else {
if (({((lifeState _x) in ['HEALTHY','INJURED'])} count (units (group _unit))) < 2) then {
_aliveUnits pushBack _unit;
};
};
};
} forEach (units _grp);
if (_aliveUnits isEqualTo []) exitWith {};
_leader = leader _grp;
{
_unit = _x;
if ((_unit distance2D _building) > _size) then {
if (alive (getAttackTarget _unit)) then {
_unit forgetTarget (getAttackTarget _unit);
};
doStop _unit;
sleep 0.01;
_unit doMove (selectRandom _buildingPositions);
} else {
if (unitReady _unit) then {
doStop _unit;
sleep 0.01;
if ((random 1) > 0.5) then {
_unit doMove (_buildingPositions # _buildingPositionsCount);
if ((_unit distance2D _building) < _size) then {
_buildingPositionsCount = _buildingPositionsCount - 1;
};
} else {
_unit doMove (selectRandom _buildingPositions);
};
};
if (_buildingPositionsCount < 0) exitWith {};
};
} forEach _aliveUnits;
if (_buildingPositionsCount < 0) exitWith {};
uiSleep 10;
};
_leader = leader _grp;
{
if (alive _x) then {
resetSubgroupDirection _x;
doStop _x;
_x enableAIFeature ['COVER',TRUE];
_x enableAIFeature ['SUPPRESSION',TRUE];
_x forceSpeed -1;
_x doFollow _leader;
_x setAnimSpeedCoef 1;
};
} forEach (units _grp);
doStop _leader;
_leader doMove _startPos;
_grp setFormDir (_leader getDir _building);
_grp setBehaviour _behaviour;
_grp enableAttack _attackEnabled; | 0 | 0.871193 | 1 | 0.871193 | game-dev | MEDIA | 0.944245 | game-dev | 0.837881 | 1 | 0.837881 |
lostmyself8/Mekanism-Extras | 5,332 | src/main/java/com/jerry/generator_extras/client/gui/plasma/GuiPlasmaEvaporationController.java | package com.jerry.generator_extras.client.gui.plasma;
import com.jerry.generator_extras.common.ExtraGenLang;
import com.jerry.generator_extras.common.content.plasma.PlasmaEvaporationMultiblockData;
import com.jerry.generator_extras.common.tile.plasma.TileEntityPlasmaEvaporationController;
import mekanism.api.recipes.cache.CachedRecipe.OperationTracker.RecipeError;
import mekanism.client.gui.GuiMekanismTile;
import mekanism.client.gui.element.GuiInnerScreen;
import mekanism.client.gui.element.bar.GuiBar.IBarInfoHandler;
import mekanism.client.gui.element.bar.GuiHorizontalRateBar;
import mekanism.client.gui.element.gauge.GaugeType;
import mekanism.client.gui.element.gauge.GuiFluidGauge;
import mekanism.client.gui.element.gauge.GuiGasGauge;
import mekanism.client.gui.element.tab.GuiWarningTab;
import mekanism.common.MekanismLang;
import mekanism.common.content.evaporation.EvaporationMultiblockData;
import mekanism.common.inventory.container.tile.MekanismTileContainer;
import mekanism.common.inventory.warning.IWarningTracker;
import mekanism.common.inventory.warning.WarningTracker.WarningType;
import mekanism.common.util.MekanismUtils;
import mekanism.common.util.UnitDisplayUtils.TemperatureUnit;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.player.Inventory;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.function.BooleanSupplier;
public class GuiPlasmaEvaporationController extends GuiMekanismTile<TileEntityPlasmaEvaporationController, MekanismTileContainer<TileEntityPlasmaEvaporationController>> {
public GuiPlasmaEvaporationController(MekanismTileContainer<TileEntityPlasmaEvaporationController> container, Inventory inv, Component title) {
super(container, inv, title);
imageWidth = 196;
imageHeight += 29;
inventoryLabelX = 6;
inventoryLabelY = imageHeight - 96;
titleLabelY = 5;
dynamicSlots = true;
}
@Override
protected void addGuiElements() {
super.addGuiElements();
PlasmaEvaporationMultiblockData multiblock = tile.getMultiblock();
// Add inner screen
addRenderableWidget(new GuiInnerScreen(this, 49, 19, 100, 60, () -> List.of(
MekanismLang.MULTIBLOCK_FORMED.translate(),
MekanismLang.EVAPORATION_HEIGHT.translate(multiblock.height()),
MekanismLang.TEMPERATURE.translate(MekanismUtils.getTemperatureDisplay(multiblock.getTemperature(), TemperatureUnit.KELVIN, true)),
MekanismLang.FLUID_PRODUCTION.translate(Math.round(multiblock.lastGain * 100D) / 100D),
ExtraGenLang.PLASMA_CONSUMPTION.translate(Math.round(multiblock.lastPlasmaConsumption * 100D) / 100D)))
.spacing(1).jeiCategory(tile));
// Add rate bar
addRenderableWidget(new GuiHorizontalRateBar(this, new IBarInfoHandler() {
@Override
public Component getTooltip() {
return MekanismUtils.getTemperatureDisplay(tile.getMultiblock().getTemperature(), TemperatureUnit.KELVIN, true);
}
@Override
public double getLevel() {
return Math.min(1, tile.getMultiblock().getTemperature() / EvaporationMultiblockData.MAX_MULTIPLIER_TEMP); // Does not mean that it really has a rate cap
}
}, 59, 83))
.warning(WarningType.INPUT_DOESNT_PRODUCE_OUTPUT, getWarningCheck(RecipeError.INPUT_DOESNT_PRODUCE_OUTPUT));
// Add input tanks
addRenderableWidget(new GuiGasGauge(() -> tile.getMultiblock().plasmaInputTank,
() -> multiblock.getGasTanks(null),
GaugeType.STANDARD, this, 6, 13, 18, 80));
addRenderableWidget(new GuiFluidGauge(() -> tile.getMultiblock().inputTank,
() -> multiblock.getFluidTanks(null),
GaugeType.STANDARD, this, 28, 13, 18, 80))
.warning(WarningType.NO_MATCHING_RECIPE, getWarningCheck(RecipeError.NOT_ENOUGH_INPUT));
// Add output tanks
addRenderableWidget(new GuiFluidGauge(() -> tile.getMultiblock().outputTank,
() -> multiblock.getFluidTanks(null),
GaugeType.STANDARD, this, 152, 13, 18, 80))
.warning(WarningType.NO_SPACE_IN_OUTPUT, getWarningCheck(RecipeError.NOT_ENOUGH_OUTPUT_SPACE));
addRenderableWidget(new GuiGasGauge(() -> tile.getMultiblock().plasmaOutputTank,
() -> multiblock.getGasTanks(null),
GaugeType.STANDARD, this, 172, 13, 18, 80));
}
@Override
protected void addWarningTab(IWarningTracker warningTracker) {
// Put the warning tab where the energy tab is as we don't have energy
addRenderableWidget(new GuiWarningTab(this, warningTracker, 137));
}
@Override
protected void drawForegroundText(@NotNull GuiGraphics guiGraphics, int mouseX, int mouseY) {
renderTitleText(guiGraphics);
drawString(guiGraphics, playerInventoryTitle, inventoryLabelX, inventoryLabelY, titleTextColor());
super.drawForegroundText(guiGraphics, mouseX, mouseY);
}
private BooleanSupplier getWarningCheck(RecipeError error) {
return () -> tile.getMultiblock().hasWarning(error);
}
}
| 0 | 0.903586 | 1 | 0.903586 | game-dev | MEDIA | 0.894784 | game-dev | 0.938259 | 1 | 0.938259 |
emileb/OpenGames | 7,347 | opengames/src/main/jni/Doom/gzdoom_2/strifehelp.acs | #include "zcommon.acs"
#library "strfhelp"
#define VDOORSPEED 16
#define VDOORWAIT 150
str QuestItems[32] =
{
"QuestItemThatDoesNotExist",
"QuestItem1", "QuestItem2", "QuestItem3",
"QuestItem4", "QuestItem5", "QuestItem6", "QuestItem7",
"QuestItem8", "QuestItem9", "QuestItem10", "QuestItem11",
"QuestItem12", "QuestItem13", "QuestItem14", "QuestItem15",
"QuestItem16", "QuestItem17", "QuestItem18", "QuestItem19",
"QuestItem20", "QuestItem21", "QuestItem22", "QuestItem23",
"QuestItem24", "QuestItem25", "QuestItem26", "QuestItem27",
"QuestItem28", "QuestItem29", "QuestItem30", "QuestItem31"
};
str MusicNames[34] =
{
"",
"d_action",
"d_tavern",
"d_danger",
"d_fast",
"d_intro",
"d_darker",
"d_strike",
"d_slide",
"d_tribal",
"d_march",
"d_danger",
"d_mood",
"d_castle",
"d_darker",
"d_action",
"d_fight",
"d_spense",
"d_slide",
"d_strike",
"d_dark",
"d_tech",
"d_slide",
"d_drone",
"d_panthr",
"d_sad",
"d_instry",
"d_tech",
"d_action",
"d_instry",
"d_drone",
"d_fight",
"d_happy",
"d_end"
};
// Script 0 is used to implement several of Strife's unique line types.
// It's also used to implement the sky change after the Programmer dies.
script << 0 >> (int type, int tag)
{
int i;
switch (type)
{
// WALK TRIGGERS
case 230:
i = GetLineRowOffset() & 31;
if (CheckInventory (QuestItems[i]) || gametype() == GAME_NET_DEATHMATCH)
{
Door_Open (tag, VDOORSPEED);
clearlinespecial ();
}
break;
case 227:
i = GetLineRowOffset() & 31;
if (CheckInventory (QuestItems[i]) || gametype() == GAME_NET_DEATHMATCH)
{
Door_Close (tag, VDOORSPEED);
clearlinespecial ();
}
break;
case 228:
if (CheckInventory ("QuestItem24"))
{
if (CheckInventory ("QuestItem28"))
{
LocalAmbientSound ("svox/voc130", 127);
}
else
{
LocalAmbientSound ("svox/voc128", 127);
}
clearlinespecial ();
}
break;
case 196:
if (GetSigilPieces() > 1)
{
Floor_LowerToLowest (tag, 8);
clearlinespecial ();
}
break;
case 197:
if (GetSigilPieces() > 1)
{
Door_Close (tag, VDOORSPEED*4);
clearlinespecial ();
}
break;
case 212:
if (CheckInventory ("FlameThrower"))
{
Floor_LowerToLowest (tag, 8);
clearlinespecial ();
}
break;
case 193:
i = GetLineRowOffset() & 31;
if (CheckInventory (QuestItems[i]) || gametype() == GAME_NET_DEATHMATCH)
{
Floor_LowerToLowest (tag, 8);
clearlinespecial ();
}
break;
case 11:
if (tag == 0)
{
Exit_Normal (0);
}
else
{
Teleport_NewMap (tag, 0, FALSE);
}
break;
case 52:
tag /= 100;
if (tag == 0)
{
Exit_Normal (0);
}
else
{
Teleport_NewMap (tag, 0, FALSE);
}
break;
case 187:
i = GetLineRowOffset() & 31;
if (CheckInventory (QuestItems[i]) || gametype() == GAME_NET_DEATHMATCH)
{
ClearForceField (tag);
clearlinespecial ();
}
break;
case 188:
if (CheckInventory ("QuestItem16") || gametype() == GAME_NET_DEATHMATCH)
{
Door_Open (tag, VDOORSPEED);
clearlinespecial ();
}
break;
case 200:
if (CheckInventory ("Sigil"))
{
Door_Open (tag, VDOORSPEED);
clearlinespecial ();
}
break;
case 215:
i = (tag % 100) & 31;
if (CheckInventory (QuestItems[i]) || gametype() == GAME_NET_DEATHMATCH)
{
SendToCommunicator (tag/100, 0, 1, 0);
clearlinespecial ();
}
break;
case 204:
case 203:
if (tag >= 0 && tag <= 33)
{
SetMusic (MusicNames[tag]);
}
break;
// WALK RETRIGGERS
case 216:
i = GetLineRowOffset() & 31;
if (CheckInventory (QuestItems[i]) || gametype() == GAME_NET_DEATHMATCH)
{
Door_Raise (tag, VDOORSPEED, VDOORWAIT);
}
break;
case 186:
if (lineside() != LINE_FRONT)
break;
case 145:
if (gametype() == GAME_NET_DEATHMATCH)
{
Floor_RaiseByValue (tag, 128, 64);
clearlinespecial();
}
else
{
Teleport_NewMap (tag/100, tag%100, TRUE);
}
break;
case 175:
if (GetActorFloorZ(0) + 16.0 > GetActorZ(0))
{
NoiseAlert (0, 0);
}
break;
case 198:
if (!CheckInventory ("OfficersUniform"))
{
NoiseAlert (0, 0);
}
break;
case 208:
if (CheckInventory ("FlameThrower"))
{
NoiseAlert (0, 0);
}
break;
case 206:
if (CheckInventory ("OfferingChalice"))
{
NoiseAlert (0, 0);
}
break;
case 184:
if (Plat_UpNearestWaitDownStay (tag, 16, 35))
{
// FIXME
}
break;
case 213:
if (!CheckInventory ("OfferingChalice"))
{
print (s:"You need the chalice !");
activatorsound ("*usefail", 127);
SetResultValue (0);
}
else
{
SetResultValue (Door_Raise (0, VDOORSPEED, VDOORWAIT, tag));
}
break;
case 232:
if (!CheckInventory ("QuestItem18") && gametype() != GAME_NET_DEATHMATCH)
{
print (s:"You need the Oracle Pass!");
activatorsound ("*usefail", 127);
SetResultValue (0);
}
else
{
SetResultValue (Door_Raise (0, VDOORSPEED, VDOORWAIT, tag));
}
break;
case 180:
case 181:
SetResultValue (Floor_RaiseByValueTxTy (tag, 8, 512));
break;
case 194:
if (Door_Open (tag, VDOORSPEED))
{
print (s:"You've freed the prisoners!");
GiveInventory ("QuestItem13", 1);
}
else
{
SetResultValue (0);
}
break;
case 199:
if (Ceiling_LowerAndCrush (tag, 8, 10))
{
print (s:"You've destroyed the Converter!");
GiveInventory ("QuestItem25", 1);
GiveInventory ("UpgradeStamina", 10);
GiveInventory ("UpgradeAccuracy", 1);
}
else
{
SetResultValue (0);
}
break;
case 209:
if (CheckInventory ("OfferingChalice"))
{
SetResultValue (Generic_Stairs (tag, 16, 16, 0, 0));
}
else
{
print (s:"You need the chalice!");
activatorsound ("*usefail", 127);
SetResultValue (0);
}
break;
case 219:
case 220:
SetResultValue (Floor_LowerToHighest (tag, 8, 128));
break;
case 226:
if (Floor_LowerToHighest (tag, 8, 128))
{
GiveInventory ("UpgradeStamina", 10);
GiveInventory ("UpgradeAccuracy", 1);
print (s:"Congratulations! You have completed the training area");
}
else
{
SetResultValue (0);
}
break;
case 154:
SetResultValue (Plat_DownWaitUpStayLip (tag, 32, 105, 0));
break;
case 177:
SetResultValue (Plat_DownWaitUpStayLip (tag, 32, 105, 0));
break;
case 214: // This only needs to be ACS for the long delay
SetResultValue (Plat_DownWaitUpStayLip (tag, 8, 1050, 0, 1));
break;
case 235:
if (GetSigilPieces() < 5)
{
SetResultValue (0);
break;
}
// Intentional fall-through
case 174:
case 40:
case 189:
case 233:
i = Door_Open (tag, VDOORSPEED/2);
i = i | Floor_LowerToLowest (tag, VDOORSPEED/2);
SetResultValue (i);
if (type == 233 && i)
{
SendToCommunicator (70, 0, 0, 0);
}
break;
case 183:
i = Door_Open (tag, VDOORSPEED/2);
i = i | Floor_LowerToHighest (tag, VDOORSPEED/2, 128);
SetResultValue (i);
break;
case 229:
SetResultValue (0);
if (GetSigilPieces() == 5)
{
SetResultValue (Door_Animated (tag, 4, 105));
}
break;
case 234:
if (CheckInventory ("QuestItem3") || gametype() == GAME_NET_DEATHMATCH)
{
SetResultValue (Door_Raise (tag, VDOORSPEED, VDOORWAIT));
}
else
{
SetResultValue (Door_LockedRaise (0, 0, 0, 102));
}
break;
case 256:
// Not a line type, but used by the Programmer death script.
ChangeSky ("SKYMNT01", "SKYMNT01");
break;
}
}
| 0 | 0.937649 | 1 | 0.937649 | game-dev | MEDIA | 0.969521 | game-dev | 0.933295 | 1 | 0.933295 |
TTTReborn/tttreborn | 9,157 | code/player/Player.cs | using Sandbox;
using TTTReborn.Camera;
using TTTReborn.Items;
using TTTReborn.Roles;
using TTTReborn.WorldUI;
namespace TTTReborn
{
public partial class Player : Sandbox.Player
{
private static int CarriableDropVelocity { get; set; } = 300;
[Net, Local]
public int Credits { get; set; } = 0;
[Net]
public bool IsForcedSpectator { get; set; } = false;
public bool IsInitialSpawning { get; set; } = false;
public RoleWorldIcon RoleWorldIcon { get; set; }
public new Inventory Inventory
{
get => (Inventory) base.Inventory;
private init => base.Inventory = value;
}
public new DefaultWalkController Controller
{
get => (DefaultWalkController) base.Controller;
private set => base.Controller = value;
}
private DamageInfo _lastDamageInfo;
public Player()
{
Inventory = new Inventory(this);
}
// Important: Server-side only
public void InitialSpawn()
{
bool isPostRound = Gamemode.Game.Instance.Round is Rounds.PostRound;
IsInitialSpawning = true;
IsForcedSpectator = isPostRound || Gamemode.Game.Instance.Round is Rounds.InProgressRound;
NetworkableGameEvent.RegisterNetworked(new Events.Player.InitialSpawnEvent(Client));
Respawn();
// sync roles
using (Prediction.Off())
{
foreach (Player player in Utils.GetPlayers())
{
if (isPostRound || player.IsConfirmed)
{
player.SendClientRole(To.Single(this));
}
}
Client.SetValue("forcedspectator", IsForcedSpectator);
}
IsInitialSpawning = false;
IsForcedSpectator = false;
}
public static readonly Model WorldModel = Model.Load("models/citizen/citizen.vmdl");
// Important: Server-side only
// TODO: Convert to a player.RPC, event based system found inside of...
// TODO: https://github.com/TTTReborn/ttt-reborn/commit/1776803a4b26d6614eba13b363bbc8a4a4c14a2e#diff-d451f87d88459b7f181b1aa4bbd7846a4202c5650bd699912b88ff2906cacf37R30
public override void Respawn()
{
Model = WorldModel;
Animator = new StandardPlayerAnimator();
EnableHideInFirstPerson = true;
EnableShadowInFirstPerson = false;
EnableDrawing = true;
Credits = 0;
SetRole(new NoneRole());
IsMissingInAction = false;
using (Prediction.Off())
{
NetworkableGameEvent.RegisterNetworked(new Events.Player.SpawnEvent(this));
SendClientRole();
}
base.Respawn();
if (!IsForcedSpectator)
{
Controller = new DefaultWalkController();
CameraMode = new FirstPersonCamera();
EnableAllCollisions = true;
EnableDrawing = true;
}
else
{
MakeSpectator(false);
}
RemovePlayerCorpse();
Inventory.DeleteContents();
Gamemode.Game.Instance.Round.OnPlayerSpawn(this);
switch (Gamemode.Game.Instance.Round)
{
case Rounds.PreRound:
case Rounds.WaitingRound:
IsConfirmed = false;
CorpseConfirmer = null;
Client.SetValue("forcedspectator", IsForcedSpectator);
break;
}
}
public override void ClientSpawn()
{
base.ClientSpawn();
if (IsLocalPawn)
{
return;
}
RoleWorldIcon = new(this);
}
public override void OnKilled()
{
using (Prediction.Off())
{
NetworkableGameEvent.RegisterNetworked(new Events.Player.DiedEvent(this));
}
BecomePlayerCorpseOnServer(_lastDamageInfo.Force, GetHitboxBone(_lastDamageInfo.HitboxIndex));
ShowFlashlight(false, false);
IsMissingInAction = true;
using (Prediction.Off())
{
if (Gamemode.Game.Instance.Round is Rounds.InProgressRound)
{
SyncMIA();
}
else if (Gamemode.Game.Instance.Round is Rounds.PostRound && PlayerCorpse != null && !PlayerCorpse.Data.IsIdentified)
{
PlayerCorpse.Data.IsIdentified = true;
RPCs.ClientConfirmPlayer(null, PlayerCorpse, PlayerCorpse.GetSerializedData());
}
}
base.OnKilled();
Inventory.DropAll();
Inventory.DeleteContents();
}
public override void Simulate(Client client)
{
if (IsClient)
{
TickPlayerVoiceChat();
}
else
{
TickAFKSystem();
}
TickEntityHints();
if (LifeState != LifeState.Alive)
{
TickPlayerChangeSpectateCamera();
return;
}
// Input requested a carriable entity switch
if (Input.ActiveChild != null)
{
ActiveChild = Input.ActiveChild;
}
SimulateActiveChild(client, ActiveChild);
TickItemSimulate();
if (Host.IsServer)
{
TickPlayerUse();
TickPlayerDropCarriable();
TickPlayerFlashlight();
}
else
{
TickPlayerShop();
TickLogicButtonActivate();
}
PawnController controller = GetActiveController();
controller?.Simulate(client, this, GetActiveAnimator());
}
protected override void UseFail()
{
// Do nothing. By default this plays a sound that we don't want.
}
public override void StartTouch(Entity other)
{
if (IsClient)
{
return;
}
if (other is PickupTrigger && other.Parent is IPickupable pickupable)
{
pickupable.PickupStartTouch(this);
}
}
public override void EndTouch(Entity other)
{
if (IsClient)
{
return;
}
if (other is PickupTrigger && other.Parent is IPickupable pickupable)
{
pickupable.PickupEndTouch(this);
}
}
private void TickPlayerDropCarriable()
{
using (Prediction.Off())
{
if (Input.Pressed(InputButton.Drop) && !Input.Down(InputButton.Run) && ActiveChild != null && Inventory != null)
{
Entity droppedEntity = Inventory.DropActive();
if (droppedEntity != null)
{
if (droppedEntity.PhysicsGroup != null)
{
droppedEntity.PhysicsGroup.Velocity = Velocity + (EyeRotation.Forward + EyeRotation.Up) * CarriableDropVelocity;
}
}
}
}
}
private void TickPlayerChangeSpectateCamera()
{
if (!Input.Pressed(InputButton.Jump) || !IsServer)
{
return;
}
using (Prediction.Off())
{
CameraMode = CameraMode switch
{
RagdollSpectateCamera => new FreeSpectateCamera(),
FreeSpectateCamera => new ThirdPersonSpectateCamera(),
ThirdPersonSpectateCamera => new FirstPersonSpectatorCamera(),
FirstPersonSpectatorCamera => new FreeSpectateCamera(),
_ => CameraMode
};
}
}
private void TickItemSimulate()
{
if (Client == null)
{
return;
}
PerksInventory perks = Inventory.Perks;
for (int i = 0; i < perks.Count(); i++)
{
perks.Get(i).Simulate(Client);
}
}
protected override void OnDestroy()
{
RemovePlayerCorpse();
base.OnDestroy();
}
[Event("player_spawn")]
protected static void OnPlayerSpawn(Player player)
{
if (!player.IsValid())
{
return;
}
player.IsMissingInAction = false;
player.IsConfirmed = false;
player.CorpseConfirmer = null;
player.SetRole(new NoneRole());
}
}
}
| 0 | 0.985827 | 1 | 0.985827 | game-dev | MEDIA | 0.925054 | game-dev | 0.953913 | 1 | 0.953913 |
nelhage/taktician | 2,610 | tak/alloc.go | package tak
import "fmt"
type position3 struct {
Position
alloc struct {
Height [3 * 3]uint8
Stacks [3 * 3]uint64
Groups [6]uint64
}
}
type position4 struct {
Position
alloc struct {
Height [4 * 4]uint8
Stacks [4 * 4]uint64
Groups [8]uint64
}
}
type position5 struct {
Position
alloc struct {
Height [5 * 5]uint8
Stacks [5 * 5]uint64
Groups [10]uint64
}
}
type position6 struct {
Position
alloc struct {
Height [6 * 6]uint8
Stacks [6 * 6]uint64
Groups [12]uint64
}
}
type position7 struct {
Position
alloc struct {
Height [7 * 7]uint8
Stacks [7 * 7]uint64
Groups [14]uint64
}
}
type position8 struct {
Position
alloc struct {
Height [8 * 8]uint8
Stacks [8 * 8]uint64
Groups [16]uint64
}
}
func alloc(tpl *Position) *Position {
switch tpl.Size() {
case 3:
a := &position3{Position: *tpl}
a.Height = a.alloc.Height[:]
a.Stacks = a.alloc.Stacks[:]
a.analysis.WhiteGroups = a.alloc.Groups[:0]
copy(a.Height, tpl.Height)
copy(a.Stacks, tpl.Stacks)
return &a.Position
case 4:
a := &position4{Position: *tpl}
a.Height = a.alloc.Height[:]
a.Stacks = a.alloc.Stacks[:]
a.analysis.WhiteGroups = a.alloc.Groups[:0]
copy(a.Height, tpl.Height)
copy(a.Stacks, tpl.Stacks)
return &a.Position
case 5:
a := &position5{Position: *tpl}
a.Height = a.alloc.Height[:]
a.Stacks = a.alloc.Stacks[:]
a.analysis.WhiteGroups = a.alloc.Groups[:0]
copy(a.Height, tpl.Height)
copy(a.Stacks, tpl.Stacks)
return &a.Position
case 6:
a := &position6{Position: *tpl}
a.Height = a.alloc.Height[:]
a.Stacks = a.alloc.Stacks[:]
a.analysis.WhiteGroups = a.alloc.Groups[:0]
copy(a.Height, tpl.Height)
copy(a.Stacks, tpl.Stacks)
return &a.Position
case 7:
a := &position7{Position: *tpl}
a.Height = a.alloc.Height[:]
a.Stacks = a.alloc.Stacks[:]
a.analysis.WhiteGroups = a.alloc.Groups[:0]
copy(a.Height, tpl.Height)
copy(a.Stacks, tpl.Stacks)
return &a.Position
case 8:
a := &position8{Position: *tpl}
a.Height = a.alloc.Height[:]
a.Stacks = a.alloc.Stacks[:]
a.analysis.WhiteGroups = a.alloc.Groups[:0]
copy(a.Height, tpl.Height)
copy(a.Stacks, tpl.Stacks)
return &a.Position
default:
panic(fmt.Sprintf("illegal size: %d", tpl.Size()))
}
}
func copyPosition(p *Position, out *Position) {
h := out.Height
s := out.Stacks
g := out.analysis.WhiteGroups
*out = *p
out.Height = h
out.Stacks = s
out.analysis.WhiteGroups = g[:0]
copy(out.Height, p.Height)
copy(out.Stacks, p.Stacks)
}
func Alloc(size int) *Position {
p := Position{cfg: &Config{Size: size}}
return alloc(&p)
}
| 0 | 0.825197 | 1 | 0.825197 | game-dev | MEDIA | 0.520852 | game-dev | 0.884867 | 1 | 0.884867 |
id-Software/DOOM-3-BFG | 17,159 | neo/idlib/containers/StaticList.h | /*
===========================================================================
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.
===========================================================================
*/
#ifndef __STATICLIST_H__
#define __STATICLIST_H__
#include "List.h"
/*
===============================================================================
Static list template
A non-growing, memset-able list using no memory allocation.
===============================================================================
*/
template<class type,int size>
class idStaticList {
public:
idStaticList();
idStaticList( const idStaticList<type,size> &other );
~idStaticList<type,size>();
void Clear(); // marks the list as empty. does not deallocate or intialize data.
int Num() const; // returns number of elements in list
int Max() const; // returns the maximum number of elements in the list
void SetNum( int newnum ); // set number of elements in list
// sets the number of elements in list and initializes any newly allocated elements to the given value
void SetNum( int newNum, const type & initValue );
size_t Allocated() const; // returns total size of allocated memory
size_t Size() const; // returns total size of allocated memory including size of list type
size_t MemoryUsed() const; // returns size of the used elements in the list
const type & operator[]( int index ) const;
type & operator[]( int index );
type * Ptr(); // returns a pointer to the list
const type * Ptr() const; // returns a pointer to the list
type * Alloc(); // returns reference to a new data element at the end of the list. returns NULL when full.
int Append( const type & obj ); // append element
int Append( const idStaticList<type,size> &other ); // append list
int AddUnique( const type & obj ); // add unique element
int Insert( const type & obj, int index = 0 ); // insert the element at the given index
int FindIndex( const type & obj ) const; // find the index for the given element
type * Find( type const & obj ) const; // find pointer to the given element
int FindNull() const; // find the index for the first NULL pointer in the list
int IndexOf( const type *obj ) const; // returns the index for the pointer to an element in the list
bool RemoveIndex( int index ); // remove the element at the given index
bool RemoveIndexFast( int index ); // remove the element at the given index
bool Remove( const type & obj ); // remove the element
void Swap( idStaticList<type,size> &other ); // swap the contents of the lists
void DeleteContents( bool clear ); // delete the contents of the list
void Sort( const idSort<type> & sort = idSort_QuickDefault<type>() );
private:
int num;
type list[ size ];
private:
// resizes list to the given number of elements
void Resize( int newsize );
};
/*
================
idStaticList<type,size>::idStaticList()
================
*/
template<class type,int size>
ID_INLINE idStaticList<type,size>::idStaticList() {
num = 0;
}
/*
================
idStaticList<type,size>::idStaticList( const idStaticList<type,size> &other )
================
*/
template<class type,int size>
ID_INLINE idStaticList<type,size>::idStaticList( const idStaticList<type,size> &other ) {
*this = other;
}
/*
================
idStaticList<type,size>::~idStaticList<type,size>
================
*/
template<class type,int size>
ID_INLINE idStaticList<type,size>::~idStaticList() {
}
/*
================
idStaticList<type,size>::Clear
Sets the number of elements in the list to 0. Assumes that type automatically handles freeing up memory.
================
*/
template<class type,int size>
ID_INLINE void idStaticList<type,size>::Clear() {
num = 0;
}
/*
========================
idList<_type_,_tag_>::Sort
Performs a QuickSort on the list using the supplied sort algorithm.
Note: The data is merely moved around the list, so any pointers to data within the list may
no longer be valid.
========================
*/
template< class type,int size >
ID_INLINE void idStaticList<type,size>::Sort( const idSort<type> & sort ) {
if ( list == NULL ) {
return;
}
sort.Sort( Ptr(), Num() );
}
/*
================
idStaticList<type,size>::DeleteContents
Calls the destructor of all elements in the list. Conditionally frees up memory used by the list.
Note that this only works on lists containing pointers to objects and will cause a compiler error
if called with non-pointers. Since the list was not responsible for allocating the object, it has
no information on whether the object still exists or not, so care must be taken to ensure that
the pointers are still valid when this function is called. Function will set all pointers in the
list to NULL.
================
*/
template<class type,int size>
ID_INLINE void idStaticList<type,size>::DeleteContents( bool clear ) {
int i;
for( i = 0; i < num; i++ ) {
delete list[ i ];
list[ i ] = NULL;
}
if ( clear ) {
Clear();
} else {
memset( list, 0, sizeof( list ) );
}
}
/*
================
idStaticList<type,size>::Num
Returns the number of elements currently contained in the list.
================
*/
template<class type,int size>
ID_INLINE int idStaticList<type,size>::Num() const {
return num;
}
/*
================
idStaticList<type,size>::Num
Returns the maximum number of elements in the list.
================
*/
template<class type,int size>
ID_INLINE int idStaticList<type,size>::Max() const {
return size;
}
/*
================
idStaticList<type>::Allocated
================
*/
template<class type,int size>
ID_INLINE size_t idStaticList<type,size>::Allocated() const {
return size * sizeof( type );
}
/*
================
idStaticList<type>::Size
================
*/
template<class type,int size>
ID_INLINE size_t idStaticList<type,size>::Size() const {
return sizeof( idStaticList<type,size> ) + Allocated();
}
/*
================
idStaticList<type,size>::Num
================
*/
template<class type,int size>
ID_INLINE size_t idStaticList<type,size>::MemoryUsed() const {
return num * sizeof( list[ 0 ] );
}
/*
================
idStaticList<type,size>::SetNum
Set number of elements in list.
================
*/
template<class type,int size>
ID_INLINE void idStaticList<type,size>::SetNum( int newnum ) {
assert( newnum >= 0 );
assert( newnum <= size );
num = newnum;
}
/*
========================
idStaticList<_type_,_tag_>::SetNum
========================
*/
template< class type,int size >
ID_INLINE void idStaticList<type,size>::SetNum( int newNum, const type &initValue ) {
assert( newNum >= 0 );
newNum = Min( newNum, size );
assert( newNum <= size );
for ( int i = num; i < newNum; i++ ) {
list[i] = initValue;
}
num = newNum;
}
/*
================
idStaticList<type,size>::operator[] const
Access operator. Index must be within range or an assert will be issued in debug builds.
Release builds do no range checking.
================
*/
template<class type,int size>
ID_INLINE const type &idStaticList<type,size>::operator[]( int index ) const {
assert( index >= 0 );
assert( index < num );
return list[ index ];
}
/*
================
idStaticList<type,size>::operator[]
Access operator. Index must be within range or an assert will be issued in debug builds.
Release builds do no range checking.
================
*/
template<class type,int size>
ID_INLINE type &idStaticList<type,size>::operator[]( int index ) {
assert( index >= 0 );
assert( index < num );
return list[ index ];
}
/*
================
idStaticList<type,size>::Ptr
Returns a pointer to the begining of the array. Useful for iterating through the list in loops.
Note: may return NULL if the list is empty.
FIXME: Create an iterator template for this kind of thing.
================
*/
template<class type,int size>
ID_INLINE type *idStaticList<type,size>::Ptr() {
return &list[ 0 ];
}
/*
================
idStaticList<type,size>::Ptr
Returns a pointer to the begining of the array. Useful for iterating through the list in loops.
Note: may return NULL if the list is empty.
FIXME: Create an iterator template for this kind of thing.
================
*/
template<class type,int size>
ID_INLINE const type *idStaticList<type,size>::Ptr() const {
return &list[ 0 ];
}
/*
================
idStaticList<type,size>::Alloc
Returns a pointer to a new data element at the end of the list.
================
*/
template<class type,int size>
ID_INLINE type *idStaticList<type,size>::Alloc() {
if ( num >= size ) {
return NULL;
}
return &list[ num++ ];
}
/*
================
idStaticList<type,size>::Append
Increases the size of the list by one element and copies the supplied data into it.
Returns the index of the new element, or -1 when list is full.
================
*/
template<class type,int size>
ID_INLINE int idStaticList<type,size>::Append( type const & obj ) {
assert( num < size );
if ( num < size ) {
list[ num ] = obj;
num++;
return num - 1;
}
return -1;
}
/*
================
idStaticList<type,size>::Insert
Increases the size of the list by at leat one element if necessary
and inserts the supplied data into it.
Returns the index of the new element, or -1 when list is full.
================
*/
template<class type,int size>
ID_INLINE int idStaticList<type,size>::Insert( type const & obj, int index ) {
int i;
assert( num < size );
if ( num >= size ) {
return -1;
}
assert( index >= 0 );
if ( index < 0 ) {
index = 0;
} else if ( index > num ) {
index = num;
}
for( i = num; i > index; --i ) {
list[i] = list[i-1];
}
num++;
list[index] = obj;
return index;
}
/*
================
idStaticList<type,size>::Append
adds the other list to this one
Returns the size of the new combined list
================
*/
template<class type,int size>
ID_INLINE int idStaticList<type,size>::Append( const idStaticList<type,size> &other ) {
int i;
int n = other.Num();
if ( num + n > size ) {
n = size - num;
}
for( i = 0; i < n; i++ ) {
list[i + num] = other.list[i];
}
num += n;
return Num();
}
/*
================
idStaticList<type,size>::AddUnique
Adds the data to the list if it doesn't already exist. Returns the index of the data in the list.
================
*/
template<class type,int size>
ID_INLINE int idStaticList<type,size>::AddUnique( type const & obj ) {
int index;
index = FindIndex( obj );
if ( index < 0 ) {
index = Append( obj );
}
return index;
}
/*
================
idStaticList<type,size>::FindIndex
Searches for the specified data in the list and returns it's index. Returns -1 if the data is not found.
================
*/
template<class type,int size>
ID_INLINE int idStaticList<type,size>::FindIndex( type const & obj ) const {
int i;
for( i = 0; i < num; i++ ) {
if ( list[ i ] == obj ) {
return i;
}
}
// Not found
return -1;
}
/*
================
idStaticList<type,size>::Find
Searches for the specified data in the list and returns it's address. Returns NULL if the data is not found.
================
*/
template<class type,int size>
ID_INLINE type *idStaticList<type,size>::Find( type const & obj ) const {
int i;
i = FindIndex( obj );
if ( i >= 0 ) {
return (type *) &list[ i ];
}
return NULL;
}
/*
================
idStaticList<type,size>::FindNull
Searches for a NULL pointer in the list. Returns -1 if NULL is not found.
NOTE: This function can only be called on lists containing pointers. Calling it
on non-pointer lists will cause a compiler error.
================
*/
template<class type,int size>
ID_INLINE int idStaticList<type,size>::FindNull() const {
int i;
for( i = 0; i < num; i++ ) {
if ( list[ i ] == NULL ) {
return i;
}
}
// Not found
return -1;
}
/*
================
idStaticList<type,size>::IndexOf
Takes a pointer to an element in the list and returns the index of the element.
This is NOT a guarantee that the object is really in the list.
Function will assert in debug builds if pointer is outside the bounds of the list,
but remains silent in release builds.
================
*/
template<class type,int size>
ID_INLINE int idStaticList<type,size>::IndexOf( type const *objptr ) const {
int index;
index = objptr - list;
assert( index >= 0 );
assert( index < num );
return index;
}
/*
================
idStaticList<type,size>::RemoveIndex
Removes the element at the specified index and moves all data following the element down to fill in the gap.
The number of elements in the list is reduced by one. Returns false if the index is outside the bounds of the list.
Note that the element is not destroyed, so any memory used by it may not be freed until the destruction of the list.
================
*/
template<class type,int size>
ID_INLINE bool idStaticList<type,size>::RemoveIndex( int index ) {
int i;
assert( index >= 0 );
assert( index < num );
if ( ( index < 0 ) || ( index >= num ) ) {
return false;
}
num--;
for( i = index; i < num; i++ ) {
list[ i ] = list[ i + 1 ];
}
return true;
}
/*
========================
idList<_type_,_tag_>::RemoveIndexFast
Removes the element at the specified index and moves the last element into its spot, rather
than moving the whole array down by one. Of course, this doesn't maintain the order of
elements! The number of elements in the list is reduced by one.
return: bool - false if the data is not found in the list.
NOTE: The element is not destroyed, so any memory used by it may not be freed until the
destruction of the list.
========================
*/
template< typename _type_,int size >
ID_INLINE bool idStaticList<_type_,size>::RemoveIndexFast( int index ) {
if ( ( index < 0 ) || ( index >= num ) ) {
return false;
}
num--;
if ( index != num ) {
list[ index ] = list[ num ];
}
return true;
}
/*
================
idStaticList<type,size>::Remove
Removes the element if it is found within the list and moves all data following the element down to fill in the gap.
The number of elements in the list is reduced by one. Returns false if the data is not found in the list. Note that
the element is not destroyed, so any memory used by it may not be freed until the destruction of the list.
================
*/
template<class type,int size>
ID_INLINE bool idStaticList<type,size>::Remove( type const & obj ) {
int index;
index = FindIndex( obj );
if ( index >= 0 ) {
return RemoveIndex( index );
}
return false;
}
/*
================
idStaticList<type,size>::Swap
Swaps the contents of two lists
================
*/
template<class type,int size>
ID_INLINE void idStaticList<type,size>::Swap( idStaticList<type,size> &other ) {
idStaticList<type,size> temp = *this;
*this = other;
other = temp;
}
// debug tool to find uses of idlist that are dynamically growing
// Ideally, most lists on shipping titles will explicitly set their size correctly
// instead of relying on allocate-on-add
void BreakOnListGrowth();
void BreakOnListDefault();
/*
========================
idList<_type_,_tag_>::Resize
Allocates memory for the amount of elements requested while keeping the contents intact.
Contents are copied using their = operator so that data is correctly instantiated.
========================
*/
template< class type,int size >
ID_INLINE void idStaticList<type,size>::Resize( int newsize ) {
assert( newsize >= 0 );
// free up the list if no data is being reserved
if ( newsize <= 0 ) {
Clear();
return;
}
if ( newsize == size ) {
// not changing the size, so just exit
return;
}
assert( newsize < size );
return;
}
#endif /* !__STATICLIST_H__ */
| 0 | 0.962117 | 1 | 0.962117 | game-dev | MEDIA | 0.265172 | game-dev | 0.908728 | 1 | 0.908728 |
umuthopeyildirim/DOOM-Mistral | 31,397 | src/vizdoom/src/thingdef/thingdef_parse.cpp | /*
** thingdef-parse.cpp
**
** Actor definitions - all parser related code
**
**---------------------------------------------------------------------------
** Copyright 2002-2007 Christoph Oelckers
** Copyright 2004-2007 Randy Heit
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
** 1. Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** 2. Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** 3. The name of the author may not be used to endorse or promote products
** derived from this software without specific prior written permission.
** 4. When not used as part of ZDoom or a ZDoom derivative, this code will be
** covered by 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 SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**---------------------------------------------------------------------------
**
*/
#include "doomtype.h"
#include "actor.h"
#include "a_pickups.h"
#include "sc_man.h"
#include "thingdef.h"
#include "a_morph.h"
#include "cmdlib.h"
#include "templates.h"
#include "v_palette.h"
#include "doomerrors.h"
#include "i_system.h"
#include "thingdef_exp.h"
#include "w_wad.h"
#include "v_video.h"
#include "version.h"
#include "v_text.h"
#include "m_argv.h"
void ParseOldDecoration(FScanner &sc, EDefinitionType def);
//==========================================================================
//
// ParseParameter
//
// Parses a parameter - either a default in a function declaration
// or an argument in a function call.
//
//==========================================================================
FxExpression *ParseParameter(FScanner &sc, PClass *cls, char type, bool constant)
{
FxExpression *x = NULL;
int v;
switch(type)
{
case 'S':
case 's': // Sound name
sc.MustGetString();
x = new FxConstant(FSoundID(sc.String), sc);
break;
case 'M':
case 'm': // Actor name
sc.SetEscape(true);
sc.MustGetString();
sc.SetEscape(false);
x = new FxClassTypeCast(RUNTIME_CLASS(AActor), new FxConstant(FName(sc.String), sc));
break;
case 'T':
case 't': // String
sc.SetEscape(true);
sc.MustGetString();
sc.SetEscape(false);
x = new FxConstant(sc.String[0]? FName(sc.String) : NAME_None, sc);
break;
case 'C':
case 'c': // Color
sc.MustGetString ();
if (sc.Compare("none"))
{
v = -1;
}
else if (sc.Compare(""))
{
v = 0;
}
else
{
int c = V_GetColor (NULL, sc.String);
// 0 needs to be the default so we have to mark the color.
v = MAKEARGB(1, RPART(c), GPART(c), BPART(c));
}
{
ExpVal val;
val.Type = VAL_Color;
val.Int = v;
x = new FxConstant(val, sc);
break;
}
case 'L':
case 'l':
{
// This forces quotation marks around the state name.
sc.MustGetToken(TK_StringConst);
if (sc.String[0] == 0 || sc.Compare("None"))
{
x = new FxConstant((FState*)NULL, sc);
}
else if (sc.Compare("*"))
{
if (constant)
{
x = new FxConstant((FState*)(intptr_t)-1, sc);
}
else sc.ScriptError("Invalid state name '*'");
}
else
{
x = new FxMultiNameState(sc.String, sc);
}
break;
}
case 'X':
case 'x':
case 'Y':
case 'y':
x = ParseExpression (sc, cls);
if (constant && !x->isConstant())
{
sc.ScriptMessage("Default parameter must be constant.");
FScriptPosition::ErrorCounter++;
}
break;
default:
assert(false);
return NULL;
}
return x;
}
//==========================================================================
//
// ActorConstDef
//
// Parses a constant definition.
//
//==========================================================================
static void ParseConstant (FScanner &sc, PSymbolTable * symt, PClass *cls)
{
// Read the type and make sure it's int or float.
if (sc.CheckToken(TK_Int) || sc.CheckToken(TK_Float))
{
int type = sc.TokenType;
sc.MustGetToken(TK_Identifier);
FName symname = sc.String;
sc.MustGetToken('=');
FxExpression *expr = ParseExpression (sc, cls);
sc.MustGetToken(';');
ExpVal val = expr->EvalExpression(NULL);
delete expr;
PSymbolConst *sym = new PSymbolConst(symname);
if (type == TK_Int)
{
sym->ValueType = VAL_Int;
sym->Value = val.GetInt();
}
else
{
sym->ValueType = VAL_Float;
sym->Float = val.GetFloat();
}
if (symt->AddSymbol (sym) == NULL)
{
delete sym;
sc.ScriptMessage ("'%s' is already defined in '%s'.",
symname.GetChars(), cls? cls->TypeName.GetChars() : "Global");
FScriptPosition::ErrorCounter++;
}
}
else
{
sc.ScriptMessage("Numeric type required for constant");
FScriptPosition::ErrorCounter++;
}
}
//==========================================================================
//
// ActorEnumDef
//
// Parses an enum definition.
//
//==========================================================================
static void ParseEnum (FScanner &sc, PSymbolTable *symt, PClass *cls)
{
int currvalue = 0;
sc.MustGetToken('{');
while (!sc.CheckToken('}'))
{
sc.MustGetToken(TK_Identifier);
FName symname = sc.String;
if (sc.CheckToken('='))
{
FxExpression *expr = ParseExpression (sc, cls);
currvalue = expr->EvalExpression(NULL).GetInt();
delete expr;
}
PSymbolConst *sym = new PSymbolConst(symname);
sym->ValueType = VAL_Int;
sym->Value = currvalue;
if (symt->AddSymbol (sym) == NULL)
{
delete sym;
sc.ScriptMessage ("'%s' is already defined in '%s'.",
symname.GetChars(), cls? cls->TypeName.GetChars() : "Global");
FScriptPosition::ErrorCounter++;
}
// This allows a comma after the last value but doesn't enforce it.
if (sc.CheckToken('}')) break;
sc.MustGetToken(',');
currvalue++;
}
sc.MustGetToken(';');
}
//==========================================================================
//
// ParseNativeVariable
//
// Parses a native variable declaration.
//
//==========================================================================
static void ParseNativeVariable (FScanner &sc, PSymbolTable * symt, PClass *cls)
{
FExpressionType valuetype;
if (sc.LumpNum == -1 || Wads.GetLumpFile(sc.LumpNum) > 0)
{
sc.ScriptMessage ("variables can only be imported by internal class and actor definitions!");
FScriptPosition::ErrorCounter++;
}
// Read the type and make sure it's int or float.
sc.MustGetAnyToken();
switch (sc.TokenType)
{
case TK_Int:
valuetype = VAL_Int;
break;
case TK_Float:
valuetype = VAL_Float;
break;
case TK_Angle_t:
valuetype = VAL_Angle;
break;
case TK_Fixed_t:
valuetype = VAL_Fixed;
break;
case TK_Bool:
valuetype = VAL_Bool;
break;
case TK_Identifier:
valuetype = VAL_Object;
// Todo: Object type
sc.ScriptError("Object type variables not implemented yet!");
break;
default:
sc.ScriptError("Invalid variable type %s", sc.String);
return;
}
sc.MustGetToken(TK_Identifier);
FName symname = sc.String;
if (sc.CheckToken('['))
{
FxExpression *expr = ParseExpression (sc, cls);
int maxelems = expr->EvalExpression(NULL).GetInt();
delete expr;
sc.MustGetToken(']');
valuetype.MakeArray(maxelems);
}
sc.MustGetToken(';');
const FVariableInfo *vi = FindVariable(symname, cls);
if (vi == NULL)
{
sc.ScriptError("Unknown native variable '%s'", symname.GetChars());
}
PSymbolVariable *sym = new PSymbolVariable(symname);
sym->offset = vi->address; // todo
sym->ValueType = valuetype;
sym->bUserVar = false;
if (symt->AddSymbol (sym) == NULL)
{
delete sym;
sc.ScriptMessage ("'%s' is already defined in '%s'.",
symname.GetChars(), cls? cls->TypeName.GetChars() : "Global");
FScriptPosition::ErrorCounter++;
}
}
//==========================================================================
//
// ParseUserVariable
//
// Parses a user variable declaration.
//
//==========================================================================
static void ParseUserVariable (FScanner &sc, PSymbolTable *symt, PClass *cls)
{
FExpressionType valuetype;
// Only non-native classes may have user variables.
if (!cls->bRuntimeClass)
{
sc.ScriptError("Native classes may not have user variables");
}
// Read the type and make sure it's int.
sc.MustGetAnyToken();
if (sc.TokenType != TK_Int)
{
sc.ScriptMessage("User variables must be of type int");
FScriptPosition::ErrorCounter++;
}
valuetype = VAL_Int;
sc.MustGetToken(TK_Identifier);
// For now, restrict user variables to those that begin with "user_" to guarantee
// no clashes with internal member variable names.
if (sc.StringLen < 6 || strnicmp("user_", sc.String, 5) != 0)
{
sc.ScriptMessage("User variable names must begin with \"user_\"");
FScriptPosition::ErrorCounter++;
}
FName symname = sc.String;
if (sc.CheckToken('['))
{
FxExpression *expr = ParseExpression(sc, cls);
int maxelems = expr->EvalExpression(NULL).GetInt();
delete expr;
sc.MustGetToken(']');
if (maxelems <= 0)
{
sc.ScriptMessage("Array size must be positive");
FScriptPosition::ErrorCounter++;
maxelems = 1;
}
valuetype.MakeArray(maxelems);
}
sc.MustGetToken(';');
// We must ensure that we do not define duplicates, even when they come from a parent table.
if (symt->FindSymbol(symname, true) != NULL)
{
sc.ScriptMessage ("'%s' is already defined in '%s' or one of its ancestors.",
symname.GetChars(), cls ? cls->TypeName.GetChars() : "Global");
FScriptPosition::ErrorCounter++;
return;
}
PSymbolVariable *sym = new PSymbolVariable(symname);
sym->offset = cls->Extend(sizeof(int) * (valuetype.Type == VAL_Array ? valuetype.size : 1));
sym->ValueType = valuetype;
sym->bUserVar = true;
if (symt->AddSymbol(sym) == NULL)
{
delete sym;
sc.ScriptMessage ("'%s' is already defined in '%s'.",
symname.GetChars(), cls ? cls->TypeName.GetChars() : "Global");
FScriptPosition::ErrorCounter++;
}
}
//==========================================================================
//
// Parses a flag name
//
//==========================================================================
static void ParseActorFlag (FScanner &sc, Baggage &bag, int mod)
{
sc.MustGetString ();
FString part1 = sc.String;
const char *part2 = NULL;
if (sc.CheckString ("."))
{
sc.MustGetString ();
part2 = sc.String;
}
HandleActorFlag(sc, bag, part1, part2, mod);
}
//==========================================================================
//
// Processes a flag. Also used by olddecorations.cpp
//
//==========================================================================
void HandleActorFlag(FScanner &sc, Baggage &bag, const char *part1, const char *part2, int mod)
{
FFlagDef *fd;
if ( (fd = FindFlag (bag.Info->Class, part1, part2)) )
{
AActor *defaults = (AActor*)bag.Info->Class->Defaults;
if (fd->structoffset == -1) // this is a deprecated flag that has been changed into a real property
{
HandleDeprecatedFlags(defaults, bag.Info, mod=='+', fd->flagbit);
}
else
{
ModActorFlag(defaults, fd, mod == '+');
}
}
else
{
if (part2 == NULL)
{
sc.ScriptMessage("\"%s\" is an unknown flag\n", part1);
}
else
{
sc.ScriptMessage("\"%s.%s\" is an unknown flag\n", part1, part2);
}
FScriptPosition::ErrorCounter++;
}
}
//==========================================================================
//
// [MH] parses a morph style expression
//
//==========================================================================
struct FParseValue
{
const char *Name;
int Flag;
};
int ParseFlagExpressionString(FScanner &sc, const FParseValue *vals)
{
// May be given flags by number...
if (sc.CheckNumber())
{
sc.MustGetNumber();
return sc.Number;
}
// ... else should be flags by name.
// NOTE: Later this should be removed and a normal expression used.
// The current DECORATE parser can't handle this though.
bool gotparen = sc.CheckString("(");
int style = 0;
do
{
sc.MustGetString();
style |= vals[sc.MustMatchString(&vals->Name, sizeof (*vals))].Flag;
}
while (sc.CheckString("|"));
if (gotparen)
{
sc.MustGetStringName(")");
}
return style;
}
static int ParseMorphStyle (FScanner &sc)
{
static const FParseValue morphstyles[]={
{ "MRF_ADDSTAMINA", MORPH_ADDSTAMINA},
{ "MRF_FULLHEALTH", MORPH_FULLHEALTH},
{ "MRF_UNDOBYTOMEOFPOWER", MORPH_UNDOBYTOMEOFPOWER},
{ "MRF_UNDOBYCHAOSDEVICE", MORPH_UNDOBYCHAOSDEVICE},
{ "MRF_FAILNOTELEFRAG", MORPH_FAILNOTELEFRAG},
{ "MRF_FAILNOLAUGH", MORPH_FAILNOLAUGH},
{ "MRF_WHENINVULNERABLE", MORPH_WHENINVULNERABLE},
{ "MRF_LOSEACTUALWEAPON", MORPH_LOSEACTUALWEAPON},
{ "MRF_NEWTIDBEHAVIOUR", MORPH_NEWTIDBEHAVIOUR},
{ "MRF_UNDOBYDEATH", MORPH_UNDOBYDEATH},
{ "MRF_UNDOBYDEATHFORCED", MORPH_UNDOBYDEATHFORCED},
{ "MRF_UNDOBYDEATHSAVES", MORPH_UNDOBYDEATHSAVES},
{ "MRF_UNDOALWAYS", MORPH_UNDOALWAYS },
{ NULL, 0 }
};
return ParseFlagExpressionString(sc, morphstyles);
}
static int ParseThingActivation (FScanner &sc)
{
static const FParseValue activationstyles[]={
{ "THINGSPEC_Default", THINGSPEC_Default},
{ "THINGSPEC_ThingActs", THINGSPEC_ThingActs},
{ "THINGSPEC_ThingTargets", THINGSPEC_ThingTargets},
{ "THINGSPEC_TriggerTargets", THINGSPEC_TriggerTargets},
{ "THINGSPEC_MonsterTrigger", THINGSPEC_MonsterTrigger},
{ "THINGSPEC_MissileTrigger", THINGSPEC_MissileTrigger},
{ "THINGSPEC_ClearSpecial", THINGSPEC_ClearSpecial},
{ "THINGSPEC_NoDeathSpecial", THINGSPEC_NoDeathSpecial},
{ "THINGSPEC_TriggerActs", THINGSPEC_TriggerActs},
{ "THINGSPEC_Activate", THINGSPEC_Activate},
{ "THINGSPEC_Deactivate", THINGSPEC_Deactivate},
{ "THINGSPEC_Switch", THINGSPEC_Switch},
{ NULL, 0 }
};
return ParseFlagExpressionString(sc, activationstyles);
}
//==========================================================================
//
// For getting a state address from the parent
// No attempts have been made to add new functionality here
// This is strictly for keeping compatibility with old WADs!
//
//==========================================================================
static FState *CheckState(FScanner &sc, PClass *type)
{
int v=0;
if (sc.GetString() && !sc.Crossed)
{
if (sc.Compare("0")) return NULL;
else if (sc.Compare("PARENT"))
{
FState * state = NULL;
sc.MustGetString();
FActorInfo * info = type->ParentClass->ActorInfo;
if (info != NULL)
{
state = info->FindState(FName(sc.String));
}
if (sc.GetString ())
{
if (sc.Compare ("+"))
{
sc.MustGetNumber ();
v = sc.Number;
}
else
{
sc.UnGet ();
}
}
if (state == NULL && v==0) return NULL;
if (v!=0 && state==NULL)
{
sc.ScriptMessage("Attempt to get invalid state from actor %s\n", type->ParentClass->TypeName.GetChars());
FScriptPosition::ErrorCounter++;
return NULL;
}
state+=v;
return state;
}
else
{
sc.ScriptMessage("Invalid state assignment");
FScriptPosition::ErrorCounter++;
}
}
return NULL;
}
//==========================================================================
//
// Parses an actor property's parameters and calls the handler
//
//==========================================================================
static bool ParsePropertyParams(FScanner &sc, FPropertyInfo *prop, AActor *defaults, Baggage &bag)
{
static TArray<FPropParam> params;
static TArray<FString> strings;
params.Clear();
strings.Clear();
params.Reserve(1);
params[0].i = 0;
if (prop->params[0] != '0')
{
const char * p = prop->params;
bool nocomma;
bool optcomma;
while (*p)
{
FPropParam conv;
FPropParam pref;
nocomma = false;
conv.s = NULL;
pref.s = NULL;
pref.i = -1;
switch ((*p) & 223)
{
case 'X': // Expression in parentheses or number.
if (sc.CheckString ("("))
{
FxExpression *x = ParseExpression(sc, bag.Info->Class);
conv.i = 0x40000000 | StateParams.Add(x, bag.Info->Class, false);
params.Push(conv);
sc.MustGetStringName(")");
break;
}
// fall through
case 'I':
sc.MustGetNumber();
conv.i = sc.Number;
break;
case 'F':
sc.MustGetFloat();
conv.f = float(sc.Float);
break;
case 'Z': // an optional string. Does not allow any numerical value.
if (sc.CheckFloat())
{
nocomma = true;
sc.UnGet();
break;
}
// fall through
case 'S':
sc.MustGetString();
conv.s = strings[strings.Reserve(1)] = sc.String;
break;
case 'T':
sc.MustGetString();
conv.s = strings[strings.Reserve(1)] = strbin1(sc.String);
break;
case 'C':
if (sc.CheckNumber ())
{
int R, G, B;
R = clamp (sc.Number, 0, 255);
sc.CheckString (",");
sc.MustGetNumber ();
G = clamp (sc.Number, 0, 255);
sc.CheckString (",");
sc.MustGetNumber ();
B = clamp (sc.Number, 0, 255);
conv.i = MAKERGB(R, G, B);
pref.i = 0;
}
else
{
sc.MustGetString ();
conv.s = strings[strings.Reserve(1)] = sc.String;
pref.i = 1;
}
break;
case 'M': // special case. An expression-aware parser will not need this.
conv.i = ParseMorphStyle(sc);
break;
case 'N': // special case. An expression-aware parser will not need this.
conv.i = ParseThingActivation(sc);
break;
case 'L': // Either a number or a list of strings
if (sc.CheckNumber())
{
pref.i = 0;
conv.i = sc.Number;
}
else
{
pref.i = 1;
params.Push(pref);
params[0].i++;
do
{
sc.MustGetString ();
conv.s = strings[strings.Reserve(1)] = sc.String;
params.Push(conv);
params[0].i++;
}
while (sc.CheckString(","));
goto endofparm;
}
break;
default:
assert(false);
break;
}
if (pref.i != -1)
{
params.Push(pref);
params[0].i++;
}
params.Push(conv);
params[0].i++;
endofparm:
p++;
// Hack for some properties that have to allow comma less
// parameter lists for compatibility.
if ((optcomma = (*p == '_')))
p++;
if (nocomma)
{
continue;
}
else if (*p == 0)
{
break;
}
else if (*p >= 'a')
{
if (!sc.CheckString(","))
{
if (optcomma)
{
if (!sc.CheckFloat()) break;
else sc.UnGet();
}
else break;
}
}
else
{
if (!optcomma) sc.MustGetStringName(",");
else sc.CheckString(",");
}
}
}
// call the handler
try
{
prop->Handler(defaults, bag.Info, bag, ¶ms[0]);
}
catch (CRecoverableError &error)
{
sc.ScriptError("%s", error.GetMessage());
}
return true;
}
//==========================================================================
//
// Parses an actor property
//
//==========================================================================
static void ParseActorProperty(FScanner &sc, Baggage &bag)
{
static const char *statenames[] = {
"Spawn", "See", "Melee", "Missile", "Pain", "Death", "XDeath", "Burn",
"Ice", "Raise", "Crash", "Crush", "Wound", "Disintegrate", "Heal", NULL };
strlwr (sc.String);
FString propname = sc.String;
if (sc.CheckString ("."))
{
sc.MustGetString ();
propname += '.';
strlwr (sc.String);
propname += sc.String;
}
else
{
sc.UnGet ();
}
FPropertyInfo *prop = FindProperty(propname);
if (prop != NULL)
{
if (bag.Info->Class->IsDescendantOf(prop->cls))
{
ParsePropertyParams(sc, prop, (AActor *)bag.Info->Class->Defaults, bag);
}
else
{
sc.ScriptMessage("\"%s\" requires an actor of type \"%s\"\n", propname.GetChars(), prop->cls->TypeName.GetChars());
FScriptPosition::ErrorCounter++;
}
}
else if (!propname.CompareNoCase("States"))
{
if (bag.StateSet)
{
sc.ScriptMessage("'%s' contains multiple state declarations", bag.Info->Class->TypeName.GetChars());
FScriptPosition::ErrorCounter++;
}
ParseStates(sc, bag.Info, (AActor *)bag.Info->Class->Defaults, bag);
bag.StateSet=true;
}
else if (MatchString(propname, statenames) != -1)
{
bag.statedef.SetStateLabel(propname, CheckState (sc, bag.Info->Class));
}
else
{
sc.ScriptError("\"%s\" is an unknown actor property\n", propname.GetChars());
}
}
//==========================================================================
//
// ActorActionDef
//
// Parses an action function definition. A lot of this is essentially
// documentation in the declaration for when I have a proper language
// ready.
//
//==========================================================================
static void ParseActionDef (FScanner &sc, PClass *cls)
{
enum
{
OPTIONAL = 1
};
unsigned int error = 0;
const AFuncDesc *afd;
FName funcname;
FString args;
TArray<FxExpression *> DefaultParams;
bool hasdefaults = false;
if (sc.LumpNum == -1 || Wads.GetLumpFile(sc.LumpNum) > 0)
{
sc.ScriptMessage ("Action functions can only be imported by internal class and actor definitions!");
++error;
}
sc.MustGetToken(TK_Native);
sc.MustGetToken(TK_Identifier);
funcname = sc.String;
afd = FindFunction(sc.String);
if (afd == NULL)
{
sc.ScriptMessage ("The function '%s' has not been exported from the executable.", sc.String);
++error;
}
sc.MustGetToken('(');
if (!sc.CheckToken(')'))
{
while (sc.TokenType != ')')
{
int flags = 0;
char type = '@';
// Retrieve flags before type name
for (;;)
{
if (sc.CheckToken(TK_Coerce) || sc.CheckToken(TK_Native))
{
}
else
{
break;
}
}
// Read the variable type
sc.MustGetAnyToken();
switch (sc.TokenType)
{
case TK_Bool:
case TK_Int:
type = 'x';
break;
case TK_Float:
type = 'y';
break;
case TK_Sound: type = 's'; break;
case TK_String: type = 't'; break;
case TK_Name: type = 't'; break;
case TK_State: type = 'l'; break;
case TK_Color: type = 'c'; break;
case TK_Class:
sc.MustGetToken('<');
sc.MustGetToken(TK_Identifier); // Skip class name, since the parser doesn't care
sc.MustGetToken('>');
type = 'm';
break;
case TK_Ellipsis:
type = '+';
sc.MustGetToken(')');
sc.UnGet();
break;
default:
sc.ScriptMessage ("Unknown variable type %s", sc.TokenName(sc.TokenType, sc.String).GetChars());
type = 'x';
FScriptPosition::ErrorCounter++;
break;
}
// Read the optional variable name
if (!sc.CheckToken(',') && !sc.CheckToken(')'))
{
sc.MustGetToken(TK_Identifier);
}
else
{
sc.UnGet();
}
FxExpression *def;
if (sc.CheckToken('='))
{
hasdefaults = true;
flags |= OPTIONAL;
def = ParseParameter(sc, cls, type, true);
}
else
{
def = NULL;
}
DefaultParams.Push(def);
if (!(flags & OPTIONAL) && type != '+')
{
type -= 'a' - 'A';
}
args += type;
sc.MustGetAnyToken();
if (sc.TokenType != ',' && sc.TokenType != ')')
{
sc.ScriptError ("Expected ',' or ')' but got %s instead", sc.TokenName(sc.TokenType, sc.String).GetChars());
}
}
}
sc.MustGetToken(';');
if (afd != NULL)
{
PSymbolActionFunction *sym = new PSymbolActionFunction(funcname);
sym->Arguments = args;
sym->Function = afd->Function;
if (hasdefaults)
{
sym->defaultparameterindex = StateParams.Size();
for(unsigned int i = 0; i < DefaultParams.Size(); i++)
{
StateParams.Add(DefaultParams[i], cls, true);
}
}
else
{
sym->defaultparameterindex = -1;
}
if (error)
{
FScriptPosition::ErrorCounter += error;
}
else if (cls->Symbols.AddSymbol (sym) == NULL)
{
delete sym;
sc.ScriptMessage ("'%s' is already defined in class '%s'.",
funcname.GetChars(), cls->TypeName.GetChars());
FScriptPosition::ErrorCounter++;
}
}
}
//==========================================================================
//
// Starts a new actor definition
//
//==========================================================================
static FActorInfo *ParseActorHeader(FScanner &sc, Baggage *bag)
{
FName typeName;
FName parentName;
FName replaceName;
bool native = false;
int DoomEdNum = -1;
// Get actor name
sc.MustGetString();
char *colon = strchr(sc.String, ':');
if (colon != NULL)
{
*colon++ = 0;
}
typeName = sc.String;
// Do some tweaking so that a definition like 'Actor:Parent' which is read as a single token is recognized as well
// without having resort to C-mode (which disallows periods in actor names.)
if (colon == NULL)
{
sc.MustGetString ();
if (sc.String[0]==':')
{
colon = sc.String + 1;
}
}
if (colon != NULL)
{
if (colon[0] == 0)
{
sc.MustGetString ();
colon = sc.String;
}
}
if (colon == NULL)
{
sc.UnGet();
}
parentName = colon;
// Check for "replaces"
if (sc.CheckString ("replaces"))
{
// Get actor name
sc.MustGetString ();
replaceName = sc.String;
if (replaceName == typeName)
{
sc.ScriptMessage ("Cannot replace class %s with itself", typeName.GetChars());
FScriptPosition::ErrorCounter++;
}
}
// Now, after the actor names have been parsed, it is time to switch to C-mode
// for the rest of the actor definition.
sc.SetCMode (true);
if (sc.CheckNumber())
{
if (sc.Number>=-1 && sc.Number<32768) DoomEdNum = sc.Number;
else
{
// does not need to be fatal.
sc.ScriptMessage ("DoomEdNum must be in the range [-1,32767]");
FScriptPosition::ErrorCounter++;
}
}
if (sc.CheckString("native"))
{
native = true;
}
try
{
FActorInfo *info = CreateNewActor(sc, typeName, parentName, native);
info->DoomEdNum = DoomEdNum > 0? DoomEdNum : -1;
info->Class->Meta.SetMetaString (ACMETA_Lump, Wads.GetLumpFullPath(sc.LumpNum));
SetReplacement(sc, info, replaceName);
ResetBaggage (bag, info->Class->ParentClass);
bag->Info = info;
bag->Lumpnum = sc.LumpNum;
#ifdef _DEBUG
bag->ClassName = typeName;
#endif
return info;
}
catch (CRecoverableError &err)
{
sc.ScriptError("%s", err.GetMessage());
return NULL;
}
}
//==========================================================================
//
// Reads an actor definition
//
//==========================================================================
static void ParseActor(FScanner &sc)
{
FActorInfo * info=NULL;
Baggage bag;
info = ParseActorHeader(sc, &bag);
sc.MustGetToken('{');
while (sc.MustGetAnyToken(), sc.TokenType != '}')
{
switch (sc.TokenType)
{
case TK_Action:
ParseActionDef (sc, info->Class);
break;
case TK_Const:
ParseConstant (sc, &info->Class->Symbols, info->Class);
break;
case TK_Enum:
ParseEnum (sc, &info->Class->Symbols, info->Class);
break;
case TK_Native:
ParseNativeVariable (sc, &info->Class->Symbols, info->Class);
break;
case TK_Var:
ParseUserVariable (sc, &info->Class->Symbols, info->Class);
break;
case TK_Identifier:
ParseActorProperty(sc, bag);
break;
case '+':
case '-':
ParseActorFlag(sc, bag, sc.TokenType);
break;
default:
sc.ScriptError("Unexpected '%s' in definition of '%s'", sc.String, bag.Info->Class->TypeName.GetChars());
break;
}
}
FinishActor(sc, info, bag);
sc.SetCMode (false);
}
//==========================================================================
//
// Reads a damage definition
//
//==========================================================================
static void ParseDamageDefinition(FScanner &sc)
{
sc.SetCMode (true); // This may be 100% irrelevant for such a simple syntax, but I don't know
// Get DamageType
sc.MustGetString();
FName damageType = sc.String;
DamageTypeDefinition dtd;
sc.MustGetToken('{');
while (sc.MustGetAnyToken(), sc.TokenType != '}')
{
if (sc.Compare("FACTOR"))
{
sc.MustGetFloat();
dtd.DefaultFactor = FLOAT2FIXED(sc.Float);
if (!dtd.DefaultFactor) dtd.ReplaceFactor = true; // Multiply by 0 yields 0: FixedMul(damage, FixedMul(factor, 0)) is more wasteful than FixedMul(factor, 0)
}
else if (sc.Compare("REPLACEFACTOR"))
{
dtd.ReplaceFactor = true;
}
else if (sc.Compare("NOARMOR"))
{
dtd.NoArmor = true;
}
else
{
sc.ScriptError("Unexpected data (%s) in damagetype definition.", sc.String);
}
}
dtd.Apply(damageType);
sc.SetCMode (false); // (set to true earlier in function)
}
//==========================================================================
//
// ParseDecorate
//
// Parses a single DECORATE lump
//
//==========================================================================
void ParseDecorate (FScanner &sc)
{
// Get actor class name.
for(;;)
{
FScanner::SavedPos pos = sc.SavePos();
if (!sc.GetToken ())
{
return;
}
switch (sc.TokenType)
{
case TK_Include:
{
sc.MustGetString();
// This check needs to remain overridable for testing purposes.
if (Wads.GetLumpFile(sc.LumpNum) == 0 && !Args->CheckParm("-allowdecoratecrossincludes"))
{
int includefile = Wads.GetLumpFile(Wads.CheckNumForFullName(sc.String, true));
if (includefile != 0)
{
I_FatalError("File %s is overriding core lump %s.",
Wads.GetWadFullName(includefile), sc.String);
}
}
FScanner newscanner;
newscanner.Open(sc.String);
ParseDecorate(newscanner);
break;
}
case TK_Const:
ParseConstant (sc, &GlobalSymbols, NULL);
break;
case TK_Enum:
ParseEnum (sc, &GlobalSymbols, NULL);
break;
case TK_Native:
ParseNativeVariable(sc, &GlobalSymbols, NULL);
break;
case ';':
// ';' is the start of a comment in the non-cmode parser which
// is used to parse parts of the DECORATE lump. If we don't add
// a check here the user will only get weird non-informative
// error messages if a semicolon is found.
sc.ScriptError("Unexpected ';'");
break;
case TK_Identifier:
// 'ACTOR' cannot be a keyword because it is also needed as a class identifier
// so let's do a special case for this.
if (sc.Compare("ACTOR"))
{
ParseActor (sc);
break;
}
else if (sc.Compare("PICKUP"))
{
ParseOldDecoration (sc, DEF_Pickup);
break;
}
else if (sc.Compare("BREAKABLE"))
{
ParseOldDecoration (sc, DEF_BreakableDecoration);
break;
}
else if (sc.Compare("PROJECTILE"))
{
ParseOldDecoration (sc, DEF_Projectile);
break;
}
else if (sc.Compare("DAMAGETYPE"))
{
ParseDamageDefinition(sc);
break;
}
default:
sc.RestorePos(pos);
ParseOldDecoration(sc, DEF_Decoration);
break;
}
}
}
| 0 | 0.953717 | 1 | 0.953717 | game-dev | MEDIA | 0.355466 | game-dev | 0.953287 | 1 | 0.953287 |
jsm174/vpx-standalone-scripts | 4,659 | The Dark Crystal (Original 2020) 1.2/The Dark Crystal (Original 2020) 1.2.patch | --- "The Dark Crystal (Original 2020) 1.2.vbs.original" 2024-10-31 18:42:01.296800700 -0400
+++ "The Dark Crystal (Original 2020) 1.2.vbs" 2024-10-31 18:20:20.730918500 -0400
@@ -11,6 +11,7 @@
Const BallSize = 50 ' 50 is the normal size used in the core.vbs, VP kicker routines uses this value divided by 2
Const BallMass = 1
Const SongVolume = 0.5 ' 1 is full volume. Value is from 0 to 1
+Const FlexDMDHighQuality = True ' If using RealDMD set to False
' Load the core.vbs for supporting Subs and functions
LoadCoreFiles
@@ -34,6 +35,14 @@
Const BallsPerGame = 3 ' usually 3 or 5
Const MaxMultiballs = 5 ' max number of balls during multiballs
+' Use FlexDMD if in FS mode
+Dim UseFlexDMD
+If Table1.ShowDT = True then
+ UseFlexDMD = False
+Else
+ UseFlexDMD = True
+End If
+
' Define Global Variables
Dim PlayersPlayingGame
Dim CurrentPlayer
@@ -322,6 +331,7 @@
Sub Table1_Exit
Savehs
+ If UseFlexDMD Then FlexDMD.Run = False
If B2SOn = true Then Controller.Stop
End Sub
@@ -1668,7 +1678,67 @@
Dim dqbFlush(64)
Dim dqSound(64)
+Dim FlexDMD
+Dim DMDScene
+
Sub DMD_Init() 'default/startup values
+ If UseFlexDMD Then
+ Set FlexDMD = CreateObject("FlexDMD.FlexDMD")
+ If Not FlexDMD is Nothing Then
+ If FlexDMDHighQuality Then
+ FlexDMD.TableFile = Table1.Filename & ".vpx"
+ FlexDMD.RenderMode = 2
+ FlexDMD.Width = 256
+ FlexDMD.Height = 64
+ FlexDMD.Clear = True
+ FlexDMD.GameName = cGameName
+ FlexDMD.Run = True
+ Set DMDScene = FlexDMD.NewGroup("Scene")
+ DMDScene.AddActor FlexDMD.NewImage("Back", "VPX.bkborder")
+ DMDScene.GetImage("Back").SetSize FlexDMD.Width, FlexDMD.Height
+ For i = 0 to 35
+ DMDScene.AddActor FlexDMD.NewImage("Dig" & i, "VPX.dempty&dmd=2")
+ Digits(i).Visible = False
+ Next
+ 'digitgrid.Visible = False
+ For i = 0 to 19 ' Top
+ DMDScene.GetImage("Dig" & i).SetBounds 8 + i * 12, 6, 12, 22
+ Next
+ For i = 20 to 35 ' Bottom
+ DMDScene.GetImage("Dig" & i).SetBounds 8 + (i - 20) * 12, 34, 12, 22
+ Next
+ FlexDMD.LockRenderThread
+ FlexDMD.Stage.AddActor DMDScene
+ FlexDMD.UnlockRenderThread
+ Else
+ FlexDMD.TableFile = Table1.Filename & ".vpx"
+ FlexDMD.RenderMode = 2
+ FlexDMD.Width = 128
+ FlexDMD.Height = 32
+ FlexDMD.Clear = True
+ FlexDMD.GameName = cGameName
+ FlexDMD.Run = True
+ Set DMDScene = FlexDMD.NewGroup("Scene")
+ DMDScene.AddActor FlexDMD.NewImage("Back", "VPX.bkborder")
+ DMDScene.GetImage("Back").SetSize FlexDMD.Width, FlexDMD.Height
+ For i = 0 to 35
+ DMDScene.AddActor FlexDMD.NewImage("Dig" & i, "VPX.dempty&dmd=2")
+ Digits(i).Visible = False
+ Next
+ digitgrid.Visible = False
+ For i = 0 to 19 ' Top
+ DMDScene.GetImage("Dig" & i).SetBounds 4 + i * 6, 3, 6, 11
+ Next
+ For i = 20 to 35 ' Bottom
+ DMDScene.GetImage("Dig" & i).SetBounds 4 + (i - 20) * 6, 17, 6, 11
+ Next
+ FlexDMD.LockRenderThread
+ FlexDMD.Stage.AddActor DMDScene
+ FlexDMD.UnlockRenderThread
+ End If
+ End If
+ End If
+
Dim i, j
DMDFlush()
deSpeed = 20
@@ -1944,7 +2014,7 @@
Sub DMDUpdate(id)
Dim digit, value
-
+ If UseFlexDMD Then FlexDMD.LockRenderThread
Select Case id
Case 0 'top text line
For digit = 20 to 35
@@ -1957,13 +2027,16 @@
Case 2 ' back image - back animations
If dLine(2) = "" OR dLine(2) = " " Then dLine(2) = "bkempty"
DigitsBack(0).ImageA = dLine(2)
+ If UseFlexDMD Then DMDScene.GetImage("Back").Bitmap = FlexDMD.NewImage("", "VPX." & dLine(2) & "&dmd=2").Bitmap
End Select
+ If UseFlexDMD Then FlexDMD.UnlockRenderThread
End Sub
Sub DMDDisplayChar(achar, adigit)
If achar = "" Then achar = " "
achar = ASC(achar)
Digits(adigit).ImageA = Chars(achar)
+ If UseFlexDMD Then DMDScene.GetImage("Dig" & adigit).Bitmap = FlexDMD.NewImage("", "VPX." & Chars(achar) & "&dmd=2&add").Bitmap
End Sub
'****************************
| 0 | 0.803541 | 1 | 0.803541 | game-dev | MEDIA | 0.342154 | game-dev | 0.897279 | 1 | 0.897279 |
lua9520/source-engine-2018-cstrike15_src | 1,238 | materialsystem/stdshaders/fxctmp9/gamecontrols_ps20.inc | // ALL SKIP STATEMENTS THAT AFFECT THIS SHADER!!!
#include "shaderlib/cshader.h"
class gamecontrols_ps20_Static_Index
{
public:
// CONSTRUCTOR
gamecontrols_ps20_Static_Index( IShaderShadow *pShaderShadow, IMaterialVar **params )
{
}
int GetIndex()
{
// Asserts to make sure that we aren't using any skipped combinations.
// Asserts to make sure that we are setting all of the combination vars.
#ifdef _DEBUG
#endif // _DEBUG
return 0;
}
};
#define shaderStaticTest_gamecontrols_ps20 0
class gamecontrols_ps20_Dynamic_Index
{
public:
// CONSTRUCTOR
gamecontrols_ps20_Dynamic_Index( IShaderDynamicAPI *pShaderAPI )
{
}
int GetIndex()
{
// Asserts to make sure that we aren't using any skipped combinations.
// Asserts to make sure that we are setting all of the combination vars.
#ifdef _DEBUG
#endif // _DEBUG
return 0;
}
};
#define shaderDynamicTest_gamecontrols_ps20 0
static const ShaderComboSemantics_t gamecontrols_ps20_combos =
{
"gamecontrols_ps20", NULL, 0, NULL, 0
};
class ConstructMe_gamecontrols_ps20
{
public:
ConstructMe_gamecontrols_ps20()
{
GetShaderDLL()->AddShaderComboInformation( &gamecontrols_ps20_combos );
}
};
static ConstructMe_gamecontrols_ps20 s_ConstructMe_gamecontrols_ps20;
| 0 | 0.788829 | 1 | 0.788829 | game-dev | MEDIA | 0.781935 | game-dev | 0.695236 | 1 | 0.695236 |
CapyKing10/CapyAddon | 1,446 | src/main/java/com/capy/capyaddon/utils/cPlaceBreakUtils.java | package com.capy.capyaddon.utils;
import net.minecraft.network.packet.c2s.play.HandSwingC2SPacket;
import net.minecraft.network.packet.c2s.play.PlayerInteractBlockC2SPacket;
import net.minecraft.util.Hand;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.util.math.Vec3d;
import static meteordevelopment.meteorclient.MeteorClient.mc;
import static meteordevelopment.meteorclient.utils.world.BlockUtils.canBreak;
public class cPlaceBreakUtils {
public static boolean breaking;
private static boolean breakingThisTick;
public static void placeBlock(Hand hand, Vec3d blockHitVec, Direction blockDirection, BlockPos pos, Integer slot, Boolean swing) {
Vec3d eyes = mc.player.getEyePos();
boolean inside =
eyes.x > pos.getX() && eyes.x < pos.getX() + 1 &&
eyes.y > pos.getY() && eyes.y < pos.getY() + 1 &&
eyes.z > pos.getZ() && eyes.z < pos.getZ() + 1;
PlayerInteractBlockC2SPacket packet = new PlayerInteractBlockC2SPacket(
hand,
new BlockHitResult(blockHitVec, blockDirection, pos, inside),
slot
);
if (mc.getNetworkHandler() != null) {
mc.getNetworkHandler().sendPacket(packet);
if (swing) mc.getNetworkHandler().sendPacket(new HandSwingC2SPacket(Hand.MAIN_HAND));
}
}
}
| 0 | 0.753664 | 1 | 0.753664 | game-dev | MEDIA | 0.967081 | game-dev | 0.882906 | 1 | 0.882906 |
Naton1/osrs-pvp-reinforcement-learning | 1,644 | simulation-rsps/ElvargServer/src/main/java/com/elvarg/game/content/combat/method/impl/specials/AbyssalWhipCombatMethod.java | package com.elvarg.game.content.combat.method.impl.specials;
import com.elvarg.game.content.combat.CombatSpecial;
import com.elvarg.game.content.combat.hit.PendingHit;
import com.elvarg.game.content.combat.method.impl.MeleeCombatMethod;
import com.elvarg.game.entity.impl.Mobile;
import com.elvarg.game.entity.impl.player.Player;
import com.elvarg.game.model.Animation;
import com.elvarg.game.model.Graphic;
import com.elvarg.game.model.GraphicHeight;
import com.elvarg.game.model.Priority;
public class AbyssalWhipCombatMethod extends MeleeCombatMethod {
private static final Animation ANIMATION = new Animation(1658, Priority.HIGH);
private static final Graphic GRAPHIC = new Graphic(341, GraphicHeight.HIGH, Priority.HIGH);
@Override
public void start(Mobile character, Mobile target) {
CombatSpecial.drain(character, CombatSpecial.ABYSSAL_WHIP.getDrainAmount());
character.performAnimation(ANIMATION);
}
@Override
public void handleAfterHitEffects(PendingHit hit) {
Mobile target = hit.getTarget();
if (target.getHitpoints() <= 0) {
return;
}
target.performGraphic(GRAPHIC);
if (target.isPlayer()) {
Player p = (Player) target;
int totalRunEnergy = p.getRunEnergy() - 25;
if (totalRunEnergy < 0) {
totalRunEnergy = 0;
}
p.setRunEnergy(totalRunEnergy);
p.getPacketSender().sendRunEnergy();
if (totalRunEnergy == 0) {
p.setRunning(false);
p.getPacketSender().sendRunStatus();
}
}
}
} | 0 | 0.819257 | 1 | 0.819257 | game-dev | MEDIA | 0.949324 | game-dev | 0.996899 | 1 | 0.996899 |
Siv3D/OpenSiv3D | 1,985 | Siv3D/src/Siv3D/Physics2D/P2MouseJointDetail.cpp | //-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2025 Ryo Suzuki
// Copyright (c) 2016-2025 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# include <Siv3D/Physics2D/P2Body.hpp>
# include "P2MouseJointDetail.hpp"
# include "P2WorldDetail.hpp"
# include "P2BodyDetail.hpp"
namespace s3d
{
detail::P2MouseJointDetail::P2MouseJointDetail(const std::shared_ptr<detail::P2WorldDetail>& world, const P2Body& body, const Vec2& worldTargetPos)
: m_world{ world }
, m_body{ body.getWeakPtr() }
{
{
b2BodyDef bodyDef;
m_placeholderBody = m_world->getWorldPtr()->CreateBody(&bodyDef);
}
b2MouseJointDef def;
def.bodyA = m_placeholderBody;
def.bodyB = m_body.lock()->getBodyPtr();
def.target = detail::ToB2Vec2(worldTargetPos);
m_joint = static_cast<b2MouseJoint*>(m_world->getWorldPtr()->CreateJoint(&def));
}
detail::P2MouseJointDetail::~P2MouseJointDetail()
{
if (not m_joint)
{
return;
}
if (m_body.expired())
{
return;
}
m_world->getWorldPtr()->DestroyJoint(m_joint);
if (m_placeholderBody)
{
m_world->getWorldPtr()->DestroyBody(m_placeholderBody);
m_placeholderBody = nullptr;
}
}
b2MouseJoint& detail::P2MouseJointDetail::getJoint()
{
assert(m_joint);
return *m_joint;
}
[[nodiscard]]
const b2MouseJoint& detail::P2MouseJointDetail::getJoint() const
{
assert(m_joint);
return *m_joint;
}
void detail::P2MouseJointDetail::setLinearStiffness(const double frequencyHz, const double dampingRatio) noexcept
{
assert(m_joint);
auto pA = m_placeholderBody;
auto pB = m_body.lock();
if (not pA || not pB)
{
return;
}
float stiffness, damping;
b2LinearStiffness(stiffness, damping, static_cast<float>(frequencyHz), static_cast<float>(dampingRatio),
pA, pB->getBodyPtr());
m_joint->SetStiffness(stiffness);
m_joint->SetDamping(damping);
}
}
| 0 | 0.90932 | 1 | 0.90932 | game-dev | MEDIA | 0.919065 | game-dev | 0.764089 | 1 | 0.764089 |
JiepengTan/LockstepEngine_ARPGDemo | 7,238 | Unity/Assets/Scripts/Logic/Components/CSkill.cs | #define DEBUG_SKILL
using System;
using System.Collections.Generic;
using AIToolkitDemo;
using Lockstep.BehaviourTree;
using Lockstep.Collision2D;
using Lockstep.Math;
using UnityEngine;
using Debug = Lockstep.Logging.Debug;
namespace Lockstep.Logic {
public class CSkill : MonoBehaviour {
[HideInInspector] public BaseEntity owner => view?.owner;
public LFloat CD;
public LFloat cdTimer;
public EAnimDefine animName;
public KeyCode fireKeyCode;
public LFloat doneDelay;
public int targetLayer;
public List<SkillPart> parts = new List<SkillPart>();
public enum ESkillState {
Idle,
Firing,
}
private ESkillState state;
[Header("__Debug")] [SerializeField] public LFloat maxPartTime;
[SerializeField] private LFloat skillTimer;
[SerializeField] private bool __DebugFireOnce = false;
private PlayerView view;
void Start(){
ResortSkill();
view = GetComponent<PlayerView>();
skillTimer = maxPartTime;
}
void ResortSkill(){
parts.Sort((a, b) => LMath.Sign(a.startTimer - b.startTimer));
var time = LFloat.MinValue;
foreach (var part in parts) {
part.startTimer = part.startTimer * SkillPart.AnimFrameScale;
var partDeadTime = part.DeadTimer;
if (partDeadTime > time) {
time = partDeadTime;
}
}
maxPartTime = time + doneDelay;
}
public void Fire(){
if (cdTimer <= 0 && state == ESkillState.Idle) {
cdTimer = CD;
skillTimer = LFloat.zero;
foreach (var part in parts) {
part.counter = 0;
}
state = ESkillState.Firing;
owner.animator?.Play(animName.ToString());
((Player) owner).CMover.needMove = false;
OnFire();
}
}
public void OnFire(){
owner.isInvincible = true;
owner.isFire = true;
}
public void Done(){
owner.isFire = false;
owner.isInvincible = false;
state = ESkillState.Idle;
owner.animator?.Play(AnimDefine.Idle);
}
public void _Update(){
if (__DebugFireOnce) {
if (Input.GetKey(fireKeyCode)) {
Fire();
}
}
DoUpdate(Time.deltaTime.ToLFloat());
}
public void DoUpdate(LFloat deltaTime){
cdTimer -= deltaTime;
skillTimer += deltaTime;
if (skillTimer < maxPartTime) {
foreach (var part in parts) {
CheckSkillPart(part);
}
}
else {
_curPart = null;
if (state == ESkillState.Firing) {
Done();
}
}
#if DEBUG_SKILL
if (_showTimer < Time.realtimeSinceStartup) {
_curPart = null;
}
#endif
}
void CheckSkillPart(SkillPart part){
if (part.counter > part.otherCount) return;
if (skillTimer > part.NextTriggerTimer()) {
TriggerPart(part);
part.counter++;
}
}
public SkillPart _curPart;
#if DEBUG_SKILL
public float _showTimer;
#endif
void TriggerPart(SkillPart part){
_curPart = part;
#if DEBUG_SKILL
_showTimer = Time.realtimeSinceStartup + 0.1f;
#endif
var col = part.collider;
if (col.radius > 0) {
//circle
CollisionManager.QueryRegion(targetLayer, owner.transform.TransformPoint(col.pos), col.radius,
_OnTriggerEnter);
}
else {
//aabb
CollisionManager.QueryRegion(targetLayer, owner.transform.TransformPoint(col.pos), col.size,
owner.transform.forward,
_OnTriggerEnter);
}
foreach (var other in _tempTargets) {
other.Entity.TakeDamage(_curPart.damage, other.Entity.transform.pos.ToLVector3());
}
//add force
if (part.needForce ) {
var force = part.impulseForce;
var forward = owner.transform.forward;
var right = forward.RightVec();
var z = forward * force.z + right * force.x;
force.x = z.x;
force.z = z.y;
foreach (var other in _tempTargets) {
other.Entity.rigidbody.AddImpulse(force);
}
}
if (part.isResetForce) {
foreach (var other in _tempTargets) {
other.Entity.rigidbody.ResetSpeed(new LFloat(3));
}
}
_tempTargets.Clear();
}
static readonly HashSet<ColliderProxy> _tempTargets = new HashSet<ColliderProxy>();
private void _OnTriggerEnter(ColliderProxy other){
if (_curPart.collider.IsCircle && _curPart.collider.deg > 0) {
var deg = (other.Transform2D.pos - owner.transform.pos).ToDeg();
var degDiff = owner.transform.deg.Abs() - deg;
if (LMath.Abs(degDiff) <= _curPart.collider.deg) {
_tempTargets.Add(other);
}
}
else {
_tempTargets.Add(other);
}
}
public void Interrupt(){ }
private void OnDrawGizmos(){
#if DEBUG_SKILL
float tintVal = 0.3f;
Gizmos.color = new Color(0, 1.0f - tintVal, tintVal, 0.25f);
if (Application.isPlaying) {
if (owner == null) return;
if (_curPart == null) return;
ShowPartGizmons(_curPart);
}
else {
foreach (var part in parts) {
if (part._DebugShow) {
ShowPartGizmons(part);
}
}
}
Gizmos.color = Color.white;
#endif
}
private void ShowPartGizmons(SkillPart part){
var col = part.collider;
if (col.radius > 0) {
//circle
var pos = owner?.transform.TransformPoint(col.pos) ?? col.pos;
Gizmos.DrawSphere(pos.ToVector3XZ(LFloat.one), col.radius.ToFloat());
}
else {
//aabb
var pos = owner?.transform.TransformPoint(col.pos) ?? col.pos;
Gizmos.DrawCube(pos.ToVector3XZ(LFloat.one), col.size.ToVector3XZ(LFloat.one));
DebugExtension.DebugLocalCube(Matrix4x4.TRS(
pos.ToVector3XZ(LFloat.one),
Quaternion.Euler(0, owner.transform.deg.ToFloat(), 0),
Vector3.one),
col.size.ToVector3XZ(LFloat.one), Gizmos.color);
}
}
}
} | 0 | 0.941072 | 1 | 0.941072 | game-dev | MEDIA | 0.974368 | game-dev | 0.96743 | 1 | 0.96743 |
DecartAI/Decart-XR | 1,884 | DecartAI-Quest-Unity/Assets/metaVoiceSdk/Lib/Wit.ai/Scripts/Runtime/Utilities/Events/FloatToStringEvent.cs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using Meta.WitAi.Attributes;
using UnityEngine;
using UnityEngine.Serialization;
namespace Meta.WitAi.Utilities
{
[AddComponentMenu("Wit.ai/Utilities/Conversions/Float to String")]
public class FloatToStringEvent : MonoBehaviour
{
[FormerlySerializedAs("format")]
[Tooltip("The format value to be used on the float")]
[SerializeField] private string _floatFormat;
[Tooltip("The format of the string itself. {0} will represent the float value provided")]
[SerializeField] private string _stringFormat;
[Space(WitRuntimeStyles.HeaderPaddingTop)]
[TooltipBox("Triggered when ConvertFloatToString(float) is called. The string in this event will be formatted based on the format fields.")]
[SerializeField] private StringEvent onFloatToString = new StringEvent();
/// <summary>
/// Converts a float to a string using the component format values and emits an onFloatToString event.
/// </summary>
/// <param name="value"></param>
public void ConvertFloatToString(float value)
{
string floatStringValue;
if (string.IsNullOrEmpty(_floatFormat))
{
floatStringValue = value.ToString();
}
else
{
floatStringValue = value.ToString(_floatFormat);
}
if (string.IsNullOrEmpty(_stringFormat))
{
onFloatToString?.Invoke(floatStringValue);
}
else
{
onFloatToString?.Invoke(string.Format(_stringFormat, floatStringValue));
}
}
}
}
| 0 | 0.768122 | 1 | 0.768122 | game-dev | MEDIA | 0.890648 | game-dev | 0.678476 | 1 | 0.678476 |
EpicSkookumScript/SkookumScript-Plugin | 3,116 | Source/SkookumScriptRuntime/Private/SkookumScriptListenerManager.hpp | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
//=======================================================================================
// SkookumScript Plugin for Unreal Engine 4
//
// Factory/manager class for USkookumScriptListener objects
//=======================================================================================
#pragma once
//=======================================================================================
// Includes
//=======================================================================================
#include "SkookumScriptListener.h"
#include <AgogCore/APArray.hpp>
#include <SkookumScript/SkInstance.hpp>
//=======================================================================================
// Global Defines / Macros
//=======================================================================================
//=======================================================================================
// Global Structures
//=======================================================================================
//---------------------------------------------------------------------------------------
// Keep track of USkookumScriptListener instances
class SkookumScriptListenerManager
{
public:
static SkookumScriptListenerManager * get_singleton();
// Methods
SkookumScriptListenerManager(uint32_t pool_init, uint32_t pool_incr);
~SkookumScriptListenerManager();
USkookumScriptListener * alloc_listener(UObject * obj_p, SkInvokedCoroutine * coro_p, USkookumScriptListener::tUnregisterCallback callback_p);
void free_listener(USkookumScriptListener * listener_p);
USkookumScriptListener::EventInfo * alloc_event();
void free_event(USkookumScriptListener::EventInfo * event_p, uint32_t num_arguments_to_free);
protected:
typedef APArray<USkookumScriptListener> tObjPool;
typedef AObjReusePool<USkookumScriptListener::EventInfo> tEventPool;
void grow_inactive_list(uint32_t pool_incr);
tObjPool m_inactive_list;
tObjPool m_active_list;
uint32_t m_pool_incr;
tEventPool m_event_pool;
UPackage * m_module_package_p;
}; // SkookumScriptListenerManager
//=======================================================================================
// Inline Functions
//=======================================================================================
//---------------------------------------------------------------------------------------
inline USkookumScriptListener::EventInfo * SkookumScriptListenerManager::alloc_event()
{
return m_event_pool.allocate();
}
//---------------------------------------------------------------------------------------
inline void SkookumScriptListenerManager::free_event(USkookumScriptListener::EventInfo * event_p, uint32_t num_arguments_to_free)
{
for (uint32_t i = 0; i < num_arguments_to_free; ++i)
{
event_p->m_argument_p[i]->dereference();
}
m_event_pool.recycle(event_p);
}
| 0 | 0.844298 | 1 | 0.844298 | game-dev | MEDIA | 0.876691 | game-dev | 0.650143 | 1 | 0.650143 |
nginnever/zogminer | 2,231 | src/mruset.h | // Copyright (c) 2012-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_MRUSET_H
#define BITCOIN_MRUSET_H
#include <set>
#include <vector>
#include <utility>
/** STL-like set container that only keeps the most recent N elements. */
template <typename T>
class mruset
{
public:
typedef T key_type;
typedef T value_type;
typedef typename std::set<T>::iterator iterator;
typedef typename std::set<T>::const_iterator const_iterator;
typedef typename std::set<T>::size_type size_type;
protected:
std::set<T> set;
std::vector<iterator> order;
size_type first_used;
size_type first_unused;
const size_type nMaxSize;
public:
mruset(size_type nMaxSizeIn = 1) : nMaxSize(nMaxSizeIn) { clear(); }
iterator begin() const { return set.begin(); }
iterator end() const { return set.end(); }
size_type size() const { return set.size(); }
bool empty() const { return set.empty(); }
iterator find(const key_type& k) const { return set.find(k); }
size_type count(const key_type& k) const { return set.count(k); }
void clear()
{
set.clear();
order.assign(nMaxSize, set.end());
first_used = 0;
first_unused = 0;
}
bool inline friend operator==(const mruset<T>& a, const mruset<T>& b) { return a.set == b.set; }
bool inline friend operator==(const mruset<T>& a, const std::set<T>& b) { return a.set == b; }
bool inline friend operator<(const mruset<T>& a, const mruset<T>& b) { return a.set < b.set; }
std::pair<iterator, bool> insert(const key_type& x)
{
std::pair<iterator, bool> ret = set.insert(x);
if (ret.second) {
if (set.size() == nMaxSize + 1) {
set.erase(order[first_used]);
order[first_used] = set.end();
if (++first_used == nMaxSize) first_used = 0;
}
order[first_unused] = ret.first;
if (++first_unused == nMaxSize) first_unused = 0;
}
return ret;
}
size_type max_size() const { return nMaxSize; }
};
#endif // BITCOIN_MRUSET_H
| 0 | 0.97838 | 1 | 0.97838 | game-dev | MEDIA | 0.15115 | game-dev | 0.977716 | 1 | 0.977716 |
FlaxEngine/FlaxAPI | 4,777 | FlaxEditor/API/Editor/GameCooker.cs | // Copyright (c) 2012-2020 Wojciech Figat. All rights reserved.
using System;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using FlaxEngine;
namespace FlaxEditor
{
partial class GameCooker
{
/// <summary>
/// Build options data.
/// </summary>
public struct Options
{
/// <summary>
/// The platform.
/// </summary>
public BuildPlatform Platform;
/// <summary>
/// The build configuration.
/// </summary>
public BuildConfiguration Configuration;
/// <summary>
/// The options.
/// </summary>
public BuildOptions Flags;
/// <summary>
/// The output path (normalized, absolute).
/// </summary>
public string OutputPath;
/// <summary>
/// The custom defines.
/// </summary>
public string[] Defines;
}
/// <summary>
/// Building event type.
/// </summary>
public enum EventType
{
/// <summary>
/// The build started.
/// </summary>
BuildStarted = 0,
/// <summary>
/// The build failed.
/// </summary>
BuildFailed = 1,
/// <summary>
/// The build done.
/// </summary>
BuildDone = 2,
}
/// <summary>
/// Game building event delegate.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="options">The build options (read only).</param>
public delegate void BuildEventDelegate(EventType type);
/// <summary>
/// Game building progress reporting delegate type.
/// </summary>
/// <param name="info">The information text.</param>
/// <param name="totalProgress">The total progress percentage (normalized to 0-1).</param>
public delegate void BuildProgressDelegate(string info, float totalProgress);
/// <summary>
/// Occurs when building event rises.
/// </summary>
public static event BuildEventDelegate Event;
/// <summary>
/// Occurs when building game progress fires.
/// </summary>
public static event BuildProgressDelegate Progress;
/// <summary>
/// Gets the type of the platform from the game build platform type.
/// </summary>
/// <param name="buildPlatform">The build platform.</param>
/// <returns>The run-type platform type.</returns>
public static PlatformType GetPlatformType(BuildPlatform buildPlatform)
{
switch (buildPlatform)
{
case BuildPlatform.Windows32:
case BuildPlatform.Windows64: return PlatformType.Windows;
case BuildPlatform.WindowsStoreX86:
case BuildPlatform.WindowsStoreX64: return PlatformType.WindowsStore;
case BuildPlatform.XboxOne: return PlatformType.XboxOne;
case BuildPlatform.LinuxX64: return PlatformType.Linux;
case BuildPlatform.PS4: return PlatformType.PS4;
default: throw new ArgumentOutOfRangeException(nameof(buildPlatform), buildPlatform, null);
}
}
internal static void Internal_OnEvent(EventType type)
{
Event?.Invoke(type);
}
internal static void Internal_OnProgress(string info, float totalProgress)
{
Progress?.Invoke(info, totalProgress);
}
internal static void Internal_CanDeployPlugin(BuildPlatform buildPlatform, Assembly assembly, out bool result)
{
// Find plugin (game only plugins are used to deploy)
var plugin = PluginManager.GamePlugins.FirstOrDefault(x => x.GetType().Assembly == assembly);
if (plugin == null)
{
Debug.Write(LogType.Info, "No loaded game plugins from assembly " + assembly.FullName);
result = true;
return;
}
var desc = plugin.Description;
// Check if plugins supports the given platform
var platform = GetPlatformType(buildPlatform);
if (desc.SupportedPlatforms != null && !desc.SupportedPlatforms.Contains(platform))
{
Debug.Write(LogType.Info, "Skip game plugin from assembly " + assembly.FullName);
result = false;
return;
}
Debug.Write(LogType.Info, "Use game plugin from assembly " + assembly.FullName);
result = true;
}
}
}
| 0 | 0.753379 | 1 | 0.753379 | game-dev | MEDIA | 0.603025 | game-dev | 0.675061 | 1 | 0.675061 |
LostCityRS/Content | 8,290 | scripts/skill_mining/scripts/mining.rs2 | // normal rocks
[oploc1,_mining_rock_normal] @mining_firstswing(get_ore_normal);
[oploc3,_mining_rock_normal] @mining_continue(get_ore_normal);
// fast rocks. iron, granite
[oploc1,_mining_rock_fast] @mining_firstswing(get_ore_fast);
[oploc3,_mining_rock_fast] @mining_continue(get_ore_fast);
// Essence mine
[oploc1,loc_2491] @mining_firstswing(get_ore_essence);
[oploc3,loc_2491] @mining_continue(get_ore_essence);
// gem rocks
[oploc1,gemrock] @mining_firstswing(get_ore_gem_rock);
[oploc3,gemrock] @mining_continue(get_ore_gem_rock);
[label,mining_firstswing](label $get_ore)
def_int $is_empty = loc_param(mining_rock_empty);
if ($is_empty = ^true) {
anim(null, 0);
mes("There is no ore currently available in this rock.");
sound_synth(prospect, 0, 0);
return;
}
db_find(mining_table:rock, loc_type);
def_dbrow $data = db_findnext;
if ($data = null) {
~displaymessage(^dm_default);
return;
}
if (inv_freespace(inv) < 1) {
anim(null, 0);
~mesbox("Your inventory is too full to hold any more <db_getfield($data, mining_table:ore_name, 0)>.");
return;
}
def_int $levelreq = db_getfield($data, mining_table:rock_level, 0);
if (stat(mining) < $levelreq) {
anim(null, 0);
~mesbox("You need a mining level of <tostring($levelreq)> to mine this rock.");
return;
}
// Macro events
if (afk_event = ^true & loc_category ! mining_rock_macro_gas) {
if (loc_param(macro_gas) = null) jump(macro_randomminingrune);
jump(macro_randommining);
}
def_obj $pickaxe = ~pickaxe_checker;
if ($pickaxe = null) {
anim(null, 0);
~mesbox("You need a pickaxe to mine this rock. You do not have a pickaxe which you have the Mining level to use.");
return;
}
def_int $mining_rate = oc_param($pickaxe, mining_rate);
if (%action_delay < map_clock) {
%action_delay = calc(map_clock + $mining_rate);
p_oploc(1);
return;
}
anim(oc_param($pickaxe, mining_animation), 0);
mes("You swing your pick at the rock.");
if (%action_delay = map_clock) {
jump($get_ore);
}
p_oploc(3);
[label,mining_continue](label $get_ore)
db_find(mining_table:rock, loc_type);
def_dbrow $data = db_findnext;
if ($data = null) {
~displaymessage(^dm_default);
return;
}
if (inv_freespace(inv) < 1) {
anim(null, 0);
~mesbox("Your inventory is too full to hold any more <db_getfield($data, mining_table:ore_name, 0)>.");
return;
}
def_int $levelreq = db_getfield($data, mining_table:rock_level, 0);
if (stat(mining) < $levelreq) {
anim(null, 0);
~mesbox("You need a mining level of <tostring($levelreq)> to mine this rock.");
return;
}
def_obj $pickaxe = ~pickaxe_checker;
if ($pickaxe = null) {
anim(null, 0);
~mesbox("You need a pickaxe to mine this rock. You do not have a pickaxe which you have the Mining level to use.");
return;
}
def_int $mining_rate = oc_param($pickaxe, mining_rate);
// sounds and skill anim is based off https://youtu.be/ix4_VVi9Xm4
sound_synth(mine_quick, 0, 0);
// if roll is due
if (%action_delay < map_clock) {
%action_delay = calc(map_clock + $mining_rate);
} else if (%action_delay = map_clock) {
anim(oc_param($pickaxe, mining_animation), 0);
jump($get_ore);
}
p_oploc(3);
[label,get_ore_normal]
db_find(mining_table:rock, loc_type);
def_dbrow $data = db_findnext;
if ($data = null) {
~displaymessage(^dm_default);
return;
}
// roll for gem
def_int $chance = 256;
def_obj $neck = inv_getobj(worn, ^wearpos_front);
if ($neck ! null & oc_category($neck) = category_557 & map_members = ^true) {
$chance = 86;
}
if (random($chance) = ^true) {
def_namedobj $gem = ~mining_gem_table;
if ($gem ! null) {
inv_add(inv, $gem, 1);
db_find(gem_cutting_table:uncut_gem, $gem);
$data = db_findnext;
mes("You just found <~add_article(oc_name(db_getfield($data, gem_cutting_table:cut_gem, 0)))>!");
}
} else if (stat_random(mining, db_getfield($data, mining_table:rock_successchance, 0)) = true) {
// They added a 1t p_delay in this update: https://oldschool.runescape.wiki/w/Update:Special_Attacks
p_delay(0);
// deplete
def_int $respawn = ~scale_by_playercount(db_getfield($data, mining_table:rock_respawnrate, 0));
// Temp note: dur does not need updated
loc_change(loc_param(next_loc_stage_mining), $respawn);
sound_synth(sound_230, 0, 0); // Sudden says its sound_230
anim(null, 0);
// The 'perfect' gold rocks in Family Crest are the same ID as regular gold rocks, so check to
// give out the right ore if we're in that location. Only gold rocks are in this room.
def_namedobj $output = db_getfield($data, mining_table:rock_output, 0);
if(inzone(^crest_perfect_mine_lower_bound, ^crest_perfect_mine_upper_bound, coord) = true) {
$output = perfect_gold_ore;
}
inv_add(inv, $output, 1);
stat_advance(mining, db_getfield($data, mining_table:rock_exp, 0));
mes("You manage to mine some <db_getfield($data, mining_table:ore_name, 0)>.");
return;
}
p_oploc(3);
// used for iron, granite, sandstone
[label,get_ore_fast]
db_find(mining_table:rock, loc_type);
def_dbrow $data = db_findnext;
if ($data = null) {
~displaymessage(^dm_default);
return;
}
// roll for gem
def_int $chance = 256;
def_obj $neck = inv_getobj(worn, ^wearpos_front);
if ($neck ! null & oc_category($neck) = category_557 & map_members = ^true) {
$chance = 86;
}
if (random($chance) = ^true) {
def_namedobj $gem = ~mining_gem_table;
if ($gem ! null) {
inv_add(inv, $gem, 1);
db_find(gem_cutting_table:uncut_gem, $gem);
$data = db_findnext;
mes("You just found <~add_article(oc_name(db_getfield($data, gem_cutting_table:cut_gem, 0)))>!");
}
} else if (stat_random(mining, db_getfield($data, mining_table:rock_successchance, 0)) = true) {
// deplete
def_int $respawn = ~scale_by_playercount(db_getfield($data, mining_table:rock_respawnrate, 0));
// Temp note: dur does not need updated
loc_change(loc_param(next_loc_stage_mining), $respawn);
sound_synth(sound_230, 0, 0); // Sudden says its sound_230
anim(null, 0);
inv_add(inv, db_getfield($data, mining_table:rock_output, 0), 1);
stat_advance(mining, db_getfield($data, mining_table:rock_exp, 0));
mes("You manage to mine some <db_getfield($data, mining_table:ore_name, 0)>.");
return;
}
p_oploc(3);
[label,get_ore_essence]
db_find(mining_table:rock, loc_type);
def_dbrow $data = db_findnext;
if ($data = null) {
~displaymessage(^dm_default);
return;
}
inv_add(inv, db_getfield($data, mining_table:rock_output, 0), 1);
stat_advance(mining, db_getfield($data, mining_table:rock_exp, 0));
mes("You manage to mine an unbound rune stone.");
p_oploc(3);
[label,get_ore_gem_rock]
db_find(mining_table:rock, loc_type);
def_dbrow $data = db_findnext;
if ($data = null) {
~displaymessage(^dm_default);
return;
}
def_int $low;
def_int $high;
$low, $high = db_getfield($data, mining_table:rock_successchance, 0);
def_obj $neck = inv_getobj(worn, ^wearpos_front);
if ($neck ! null & oc_category($neck) = category_557 & map_members = ^true) {
$low = multiply($low, 3);
$high = multiply($high, 3);
}
if (stat_random(mining, $low, $high) = true) {
// They added a 1t p_delay in this update: https://oldschool.runescape.wiki/w/Update:Special_Attacks
// p_delay(0);
// deplete
def_int $respawn = ~scale_by_playercount(db_getfield($data, mining_table:rock_respawnrate, 0));
// Temp note: dur does not need updated
loc_change(loc_param(next_loc_stage_mining), $respawn);
// stop mining, give ore and xp.
sound_synth(found_gem, 0, 0);
anim(null, 0);
def_namedobj $gem;
def_int $count;
$gem, $count = ~roll_on_drop_table(gem_rock_table);
inv_add(inv, $gem, 1);
stat_advance(mining, db_getfield($data, mining_table:rock_exp, 0));
db_find(gem_cutting_table:uncut_gem, $gem);
$data = db_findnext;
mes("You just mined <~add_article(oc_name(db_getfield($data, gem_cutting_table:cut_gem, 0)))>!");
return;
}
p_oploc(3);
[proc,mining_gem_table]()(namedobj)
def_int $rand = random(128);
if ($rand < 2) return (uncut_diamond);
if ($rand < 10) return (uncut_ruby);
if ($rand < 26) return (uncut_emerald);
if ($rand < 58) return (uncut_sapphire);
else return(null);
| 0 | 0.819388 | 1 | 0.819388 | game-dev | MEDIA | 0.873199 | game-dev | 0.918674 | 1 | 0.918674 |
Wemino/VorpalFix | 12,164 | src/helper.hpp | namespace MemoryHelper
{
template <typename T> static bool WriteMemory(uintptr_t address, T value, bool disableProtection = true)
{
DWORD oldProtect;
if (disableProtection)
{
if (!VirtualProtect(reinterpret_cast <LPVOID> (address), sizeof(T), PAGE_EXECUTE_READWRITE, &oldProtect)) return false;
}
*reinterpret_cast <T*> (address) = value;
if (disableProtection)
{
VirtualProtect(reinterpret_cast <LPVOID> (address), sizeof(T), oldProtect, &oldProtect);
}
return true;
}
static bool WriteMemoryRaw(uintptr_t address, const void* data, size_t size, bool disableProtection = true)
{
DWORD oldProtect;
if (disableProtection)
{
if (!VirtualProtect(reinterpret_cast <LPVOID> (address), size, PAGE_EXECUTE_READWRITE, &oldProtect)) return false;
}
std::memcpy(reinterpret_cast <void*> (address), data, size);
if (disableProtection)
{
VirtualProtect(reinterpret_cast <LPVOID> (address), size, oldProtect, &oldProtect);
}
return true;
}
static bool MakeNOP(uintptr_t address, size_t count, bool disableProtection = true)
{
DWORD oldProtect;
if (disableProtection)
{
if (!VirtualProtect(reinterpret_cast <LPVOID> (address), count, PAGE_EXECUTE_READWRITE, &oldProtect)) return false;
}
std::memset(reinterpret_cast <void*> (address), 0x90, count);
if (disableProtection)
{
VirtualProtect(reinterpret_cast <LPVOID> (address), count, oldProtect, &oldProtect);
}
return true;
}
static bool MakeCALL(uintptr_t srcAddress, uintptr_t destAddress, bool disableProtection = true)
{
DWORD oldProtect;
if (disableProtection)
{
if (!VirtualProtect(reinterpret_cast <LPVOID> (srcAddress), 5, PAGE_EXECUTE_READWRITE, &oldProtect)) return false;
}
uintptr_t relativeAddress = destAddress - srcAddress - 5; *reinterpret_cast <uint8_t*> (srcAddress) = 0xE8; // CALL opcode
*reinterpret_cast <uintptr_t*> (srcAddress + 1) = relativeAddress;
if (disableProtection)
{
VirtualProtect(reinterpret_cast <LPVOID> (srcAddress), 5, oldProtect, &oldProtect);
}
return true;
}
static bool MakeJMP(uintptr_t srcAddress, uintptr_t destAddress, bool disableProtection = true)
{
DWORD oldProtect;
if (disableProtection)
{
if (!VirtualProtect(reinterpret_cast <LPVOID> (srcAddress), 5, PAGE_EXECUTE_READWRITE, &oldProtect)) return false;
}
uintptr_t relativeAddress = destAddress - srcAddress - 5; *reinterpret_cast <uint8_t*> (srcAddress) = 0xE9; // JMP opcode
*reinterpret_cast <uintptr_t*> (srcAddress + 1) = relativeAddress;
if (disableProtection)
{
VirtualProtect(reinterpret_cast <LPVOID> (srcAddress), 5, oldProtect, &oldProtect);
}
return true;
}
template <typename T> static T ReadMemory(uintptr_t address, bool disableProtection = false)
{
DWORD oldProtect;
if (disableProtection)
{
if (!VirtualProtect(reinterpret_cast <LPVOID> (address), sizeof(T), PAGE_EXECUTE_READ, &oldProtect)) return T();
}
T value = *reinterpret_cast <T*> (address);
if (disableProtection)
{
VirtualProtect(reinterpret_cast <LPVOID> (address), sizeof(T), oldProtect, &oldProtect);
}
return value;
}
};
namespace IniHelper
{
mINI::INIFile iniFile("VorpalFix.ini");
mINI::INIStructure iniReader;
void Init()
{
iniFile.read(iniReader);
}
void Save()
{
iniFile.write(iniReader);
}
char* ReadString(const char* sectionName, const char* valueName, const char* defaultValue)
{
char* result = new char[255];
try
{
if (iniReader.has(sectionName) && iniReader.get(sectionName).has(valueName))
{
std::string value = iniReader.get(sectionName).get(valueName);
if (!value.empty() && (value.front() == '\"' || value.front() == '\''))
value.erase(0, 1);
if (!value.empty() && (value.back() == '\"' || value.back() == '\''))
value.erase(value.size() - 1);
strncpy(result, value.c_str(), 254);
result[254] = '\0';
return result;
}
}
catch (...) {}
strncpy(result, defaultValue, 254);
result[254] = '\0';
return result;
}
float ReadFloat(const char* sectionName, const char* valueName, float defaultValue)
{
try
{
if (iniReader.has(sectionName) && iniReader.get(sectionName).has(valueName))
{
const std::string& s = iniReader.get(sectionName).get(valueName);
if (!s.empty())
return std::stof(s);
}
}
catch (...) {}
return defaultValue;
}
int ReadInteger(const char* sectionName, const char* valueName, int defaultValue)
{
try
{
if (iniReader.has(sectionName) && iniReader.get(sectionName).has(valueName))
{
const std::string& s = iniReader.get(sectionName).get(valueName);
if (!s.empty())
return std::stoi(s);
}
}
catch (...) {}
return defaultValue;
}
};
namespace GameHelper
{
bool DisableCursorScaling = false;
int(__cdecl* GetKeyId)(const char*) = (int(__cdecl*)(const char*))0x4076F0;
int(__cdecl* Bind)(int, const char*) = (int(__cdecl*)(int, const char*))0x407870;
int(__cdecl* VidRestart)() = (int(__cdecl*)())0x40B2F0;
int(__cdecl* UpdateCvar)(const char*, const char*, int) = (int(__cdecl*)(const char*, const char*, int))0x418D90;
char* (__cdecl* GetWeaponName)(int) = (char* (__cdecl*)(int))0x441D60;
int(__cdecl* UI_GetStaticMap)(unsigned int, const char*) = (int(__cdecl*)(unsigned int, const char*))0x44A300;
int(__cdecl* IsControllerConnected)() = (int(__cdecl*)())0x463130;
static void AssignCmdKeyId(int keyId, const char* cmd)
{
char* KeyCommandName = *(char**)(0x14EA2A8 + 0xC * keyId);
if (strcmp(KeyCommandName, cmd) != 0)
{
Bind(keyId, cmd);
}
}
static int FindShaderIndex(const char* texturePath)
{
int ShaderNum = MemoryHelper::ReadMemory<int>(0x1BCCEEC);
int ShaderIndex = 0x1BCCEF0;
for (int i = 0; i < ShaderNum; i++)
{
const char* currentTexture = (const char*)ShaderIndex;
if (strcmp(currentTexture, texturePath) == 0)
{
return ShaderIndex;
}
ShaderIndex += 0x80;
}
return -1;
}
static void __cdecl ResizeCursor(bool hide, int width, int height)
{
int ImageIndex = FindShaderIndex("gfx/2d/mouse_arrow.tga");
if (ImageIndex == -1) return;
const int originalWidth = 640;
const int originalHeight = 480;
const int mouseWidth = 16;
const int mouseHeight = 32;
if (hide)
{
MemoryHelper::WriteMemory<int>(ImageIndex + 0x40, 0, false);
MemoryHelper::WriteMemory<int>(ImageIndex + 0x44, 0, false);
return;
}
float widthScale = static_cast<float>(width) / originalWidth;
float heightScale = static_cast<float>(height) / originalHeight;
float scaleFactor = std::min(widthScale, heightScale);
int scaledMouseWidth = static_cast<int>(mouseWidth * scaleFactor);
int scaledMouseHeight = static_cast<int>(mouseHeight * scaleFactor);
if (DisableCursorScaling)
{
MemoryHelper::WriteMemory<int>(ImageIndex + 0x40, mouseWidth, false);
MemoryHelper::WriteMemory<int>(ImageIndex + 0x44, mouseHeight, false);
}
else
{
MemoryHelper::WriteMemory<int>(ImageIndex + 0x40, scaledMouseWidth, false);
MemoryHelper::WriteMemory<int>(ImageIndex + 0x44, scaledMouseHeight, false);
}
}
static void __cdecl ResizePopupMessage(int width, int height)
{
int ImageIndex = FindShaderIndex("ui/control/press_any_key.tga");
if (ImageIndex == -1) return;
int image_width = MemoryHelper::ReadMemory<int>(ImageIndex + 0x48);
float current_width = static_cast<float>(width);
float current_height = static_cast<float>(height);
float target_width = current_height * 4.0f / 3.0f;
float scale_factor = target_width / current_width;
image_width = static_cast<int>(image_width * scale_factor);
MemoryHelper::WriteMemory<int>(ImageIndex + 0x48, image_width, false);
}
};
namespace SystemHelper
{
static DWORD GetCurrentDisplayFrequency()
{
DEVMODE devMode = {};
devMode.dmSize = sizeof(DEVMODE);
if (EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &devMode))
{
return devMode.dmDisplayFrequency;
}
return 60;
}
static std::pair<DWORD, DWORD> GetScreenResolution()
{
DEVMODE devMode = {};
devMode.dmSize = sizeof(DEVMODE);
if (EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &devMode))
{
return { devMode.dmPelsWidth, devMode.dmPelsHeight };
}
return { 0, 0 };
}
std::vector<std::string> GetLocPk3Files(const std::string& path)
{
std::vector<std::string> pk3Files;
if (!std::filesystem::exists(path) || !std::filesystem::is_directory(path))
{
return pk3Files;
}
for (const auto& entry : std::filesystem::recursive_directory_iterator(path))
{
if (entry.is_regular_file() && entry.path().extension() == ".pk3")
{
std::string relativePath = entry.path().string();
relativePath = relativePath.substr(relativePath.find("loc/"));
pk3Files.push_back(relativePath);
}
}
return pk3Files;
}
static void LoadProxyLibrary()
{
wchar_t systemPath[MAX_PATH];
GetSystemDirectoryW(systemPath, MAX_PATH);
lstrcatW(systemPath, L"\\winmm.dll");
HINSTANCE hL = LoadLibraryExW(systemPath, 0, LOAD_WITH_ALTERED_SEARCH_PATH);
if (!hL)
{
DWORD errorCode = GetLastError();
wchar_t errorMessage[512];
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorCode, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), errorMessage, sizeof(errorMessage) / sizeof(wchar_t), NULL);
MessageBoxW(NULL, errorMessage, L"Error Loading winmm.dll", MB_ICONERROR);
return;
}
winmm.ProxySetup(hL);
}
};
namespace HookHelper
{
bool isMHInitialized = false;
static bool InitializeMinHook()
{
if (!isMHInitialized)
{
if (MH_Initialize() == MH_OK)
{
isMHInitialized = true;
}
else
{
MessageBoxA(NULL, "Failed to initialize MinHook!", "Error", MB_ICONERROR | MB_OK);
return false;
}
}
return true;
}
static void ApplyHook(void* addr, LPVOID hookFunc, LPVOID* originalFunc)
{
if (!InitializeMinHook()) return;
MH_STATUS status = MH_CreateHook(addr, hookFunc, originalFunc);
if (status != MH_OK)
{
char errorMsg[0x100];
sprintf_s(errorMsg, "Failed to create hook at address: %p\nError: %s", addr, MH_StatusToString(status));
MessageBoxA(NULL, errorMsg, "Error", MB_ICONERROR | MB_OK);
return;
}
status = MH_EnableHook(addr);
if (status != MH_OK)
{
char errorMsg[0x100];
sprintf_s(errorMsg, "Failed to enable hook at address: %p\nError: %s", addr, MH_StatusToString(status));
MessageBoxA(NULL, errorMsg, "Error", MB_ICONERROR | MB_OK);
return;
}
}
static void ApplyHookAPI(LPCWSTR moduleName, LPCSTR apiName, LPVOID hookFunc, LPVOID* originalFunc)
{
if (!InitializeMinHook()) return;
MH_STATUS status = MH_CreateHookApi(moduleName, apiName, hookFunc, originalFunc);
if (status != MH_OK)
{
char errorMsg[0x100];
sprintf_s(errorMsg, "Failed to create hook for API: %s\nError: %s", apiName, MH_StatusToString(status));
MessageBoxA(NULL, errorMsg, "Error", MB_ICONERROR | MB_OK);
return;
}
status = MH_EnableHook(MH_ALL_HOOKS);
if (status != MH_OK)
{
char errorMsg[0x100];
sprintf_s(errorMsg, "Failed to enable hook for API: %s\nError: %s", apiName, MH_StatusToString(status));
MessageBoxA(NULL, errorMsg, "Error", MB_ICONERROR | MB_OK);
return;
}
}
};
namespace StringHelper
{
const char* IntegerToCString(int value)
{
static thread_local char buffer[32];
snprintf(buffer, sizeof(buffer), "%d", value);
return buffer;
}
const char* FloatToCString(float value)
{
static thread_local char buffer[32];
snprintf(buffer, sizeof(buffer), "%.0f", value);
return buffer;
}
const char* BoolToCString(bool value)
{
return value ? "1" : "0";
}
bool stricmp(const char* str1, const char* str2)
{
if (!str1 || !str2)
{
return false;
}
while (*str1 && *str2)
{
if (tolower(static_cast<unsigned char>(*str1)) != tolower(static_cast<unsigned char>(*str2)))
{
return false;
}
++str1;
++str2;
}
return *str1 == '\0' && *str2 == '\0';
}
char* ConstructPath(const char* prefix, const char* suffix)
{
size_t len = strlen(prefix) + strlen(suffix) + 1;
char* path = (char*)malloc(len);
if (path)
{
snprintf(path, len, "%s%s", prefix, suffix);
}
return path;
}
}; | 0 | 0.986247 | 1 | 0.986247 | game-dev | MEDIA | 0.545008 | game-dev | 0.977248 | 1 | 0.977248 |
etternagame/etterna | 6,805 | Docs/legacy/Themerdocs/Examples/Example_Screens/ScreenMapControllers.lua | -- This is the example for how to theme ScreenMapControllers, the Config
-- Key/Joy Mappings screen.
-- The contents of this file will actually be in several sections, each
-- intended to be placed in its own file.
-- Sections will be seperated by lines of dashes to make the separation clear.
-- The first line inside the dashes will have the name of the file to copy the
-- section to.
-- The rest of the area inside the dashes will discuss general aspects of the
-- section being discussed.
----------------------------------------------------------------
-- metrics.ini - the metrics you might want to set
-- See the ScreenMapControllers section of _fallback/metrics.ini
----------------------------------------------------------------
----------------------------------------------------------------
-- overlay, underlay, decorations, transitions
-- ScreenMapControllers supports the standard layers and transitions:
-- Layers: overlay, underlay, decorations
-- Transitions: in, out, cancel
-- Details of creating the layers and transitions for a screen are covered in
-- ScreenWithLayersAndTransitions.lua.
-- Previous versions of ScreenMapControllers had the warning in the overlay.
-- The warning has been moved to Graphics/ScreenMapControllers warning.lua. If
-- you have previously made a theme, update your theme to match the new
-- convention.
----------------------------------------------------------------
----------------------------------------------------------------
-- Graphics/ScreenMapControllers warning.lua
-- The warning that is displayed when entering the screen.
-- The _fallback warning uses the WarningHeader and WarningText strings from
-- en.ini. If all you want to do is change the text, add those entries to your
-- en.ini.
-- The actor returned by your lua file must handle TweenOn and TweenOff commands.
-- TweenOn will occur when the screen starts.
-- TweenOff will occur when the warning is dismissed.
-- Here is a simple actor that dims the screen and displays the text.
----------------------------------------------------------------
return Def.ActorFrame{
InitCommand=function(self)
self:xy(SCREEN_CENTER_X, SCREEN_CENTER_Y)
end,
Def.Quad{
TweenOnCommand=function(self)
self:zoomto(SCREEN_WIDTH, SCREEN_HEIGHT):diffuse(Color.Black)
end,
TweenOffCommand=function(self)
self:linear(0.5):diffusealpha(0)
end,
},
Def.BitmapText{
Font="Common Normal",
Text=ScreenString("WarningHeader"),
TweenOnCommand=function(self)
self:y(-80):diffuse(Color.Red)
end,
TweenOffCommand=function(self)
self:linear(0.5):diffusealpha(0)
end,
},
Def.BitmapText{
Font="Common Normal",
Text=ScreenString("WarningText"),
TweenOnCommand=function(self)
self:y(10):wrapwidthpixels(SCREEN_WIDTH-48)
end,
TweenOffCommand=function(self)
self:linear(0.5):diffusealpha(0)
end,
},
}
----------------------------------------------------------------
-- Graphics/ScreenMapControllers action.lua
-- The fallback actor that is used when there isn't a specific actor for an
-- action. At a minimum, this should display the name of the action, in order
-- to correctly handle the possibility of actions being added in the future.
-- _fallback's version accomplishes this by being a BitmapText and fetching the
-- text from en.ini.
----------------------------------------------------------------
return Def.BitmapText{
Font="Common Normal",
InitCommand= function(self)
self:x(SCREEN_CENTER_X):zoom(.75):diffuse(color("#808080"))
end,
OnCommand= function(self)
self:diffusealpha(0)
self:decelerate(0.5)
self:diffusealpha(1)
-- This code is in the OnCommand because the screen sets the name of this
-- actor after loading it. If this code was in the InitCommand, it would
-- not work because the name is blank at that point.
-- fancy effect: Look at the name (which is set by the screen) to set text
-- The name is concatenated with "Action" so that the strings used will be
-- unique, next to each other in the language file, and clear in usage.
self:settext(
THEME:GetString("ScreenMapControllers", "Action" .. self:GetName()))
end,
OffCommand=function(self)
self:stoptweening():accelerate(0.3):diffusealpha(0):queuecommand("Hide")
end,
HideCommand=function(self)
self:visible(false)
end,
GainFocusCommand=function(self)
self:diffuseshift():effectcolor2(color("#808080")):effectcolor1(color("#FFFFFF"))
end,
LoseFocusCommand=function(self)
self:stopeffect()
end,
}
----------------------------------------------------------------
-- Graphics/ScreenMapControllers <action name>.lua
-- Every action can have its own special actor which will be used if it exists.
-- Replace "<action name>" with the lowercase name of the action you are making
-- an actor for and create the actor you want for that action.
-- As of this writing, action names are:
-- "clear", "reload", "save", "setlist", "exit"
-- Creating actors is discussed in Examples/anatomy_of_an_actor.lua, so an
-- example is not provided here.
----------------------------------------------------------------
----------------------------------------------------------------
-- Graphics/ScreenMapControllers nosetlistprompt.lua
-- This is the actor that is displayed when the player attempts to use the
-- SetList (or "Assign List") action without anything in the list.
-- It should tell the player that the list is empty and how to add things to
-- the list.
-- It must handle TweenOn and TweenOff commands.
-- TweenOn occurs when the player tries to perform the action and fails.
-- TweenOff occurs when the prompt is dismissed.
-- _fallback's does this by dimming the screen with a quad and using a
-- BitmapText to display the string from the language file.
-- Note the use of stoptweening in TweenOn and TweenOff. This is to prevent
-- the player from overflowing the tween stack by mashing.
----------------------------------------------------------------
return Def.ActorFrame{
InitCommand=function(self)
self:x(SCREEN_CENTER_X):y(SCREEN_CENTER_Y)
end,
Def.Quad{
InitCommand=function(self)
self:zoomto(SCREEN_WIDTH,SCREEN_HEIGHT):diffuse(Color.Black):diffusealpha(0)
end,
TweenOnCommand=function(self)
self:stoptweening():diffusealpha(1):linear(0.5):diffusealpha(0.8)
end,
TweenOffCommand=function(self)
self:stoptweening():linear(0.5):diffusealpha(0)
end,
},
Def.ActorFrame{
Def.BitmapText{
Font="Common Normal",
Text=ScreenString("NoSetListPrompt"),
InitCommand=function(self)
self:y(10):wrapwidthpixels(SCREEN_WIDTH-48):diffusealpha(0)
end,
TweenOnCommand=function(self)
self:stoptweening():diffusealpha(0):sleep(0.5125):linear(0.125):diffusealpha(1)
end,
TweenOffCommand=function(self)
self:stoptweening():linear(0.5):diffusealpha(0)
end,
},
},
}
| 0 | 0.932753 | 1 | 0.932753 | game-dev | MEDIA | 0.691745 | game-dev,desktop-app | 0.985861 | 1 | 0.985861 |
Samsung/GearVRf | 2,361 | GVRf/Extensions/gvrf-physics/src/main/jni/bullet3/include/BulletCollision/NarrowPhaseCollision/btConvexCast.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
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 BT_CONVEX_CAST_H
#define BT_CONVEX_CAST_H
#include "LinearMath/btTransform.h"
#include "LinearMath/btVector3.h"
#include "LinearMath/btScalar.h"
class btMinkowskiSumShape;
#include "LinearMath/btIDebugDraw.h"
/// btConvexCast is an interface for Casting
class btConvexCast
{
public:
virtual ~btConvexCast();
///RayResult stores the closest result
/// alternatively, add a callback method to decide about closest/all results
struct CastResult
{
//virtual bool addRayResult(const btVector3& normal,btScalar fraction) = 0;
virtual void DebugDraw(btScalar fraction) {(void)fraction;}
virtual void drawCoordSystem(const btTransform& trans) {(void)trans;}
virtual void reportFailure(int errNo, int numIterations) {(void)errNo;(void)numIterations;}
CastResult()
:m_fraction(btScalar(BT_LARGE_FLOAT)),
m_debugDrawer(0),
m_allowedPenetration(btScalar(0))
{
}
virtual ~CastResult() {};
btTransform m_hitTransformA;
btTransform m_hitTransformB;
btVector3 m_normal;
btVector3 m_hitPoint;
btScalar m_fraction; //input and output
btIDebugDraw* m_debugDrawer;
btScalar m_allowedPenetration;
};
/// cast a convex against another convex object
virtual bool calcTimeOfImpact(
const btTransform& fromA,
const btTransform& toA,
const btTransform& fromB,
const btTransform& toB,
CastResult& result) = 0;
};
#endif //BT_CONVEX_CAST_H
| 0 | 0.958802 | 1 | 0.958802 | game-dev | MEDIA | 0.978243 | game-dev | 0.941296 | 1 | 0.941296 |
gilbutITbook/006772 | 4,481 | Unity 5.1/08/toufu_no_tumori/Assets/Scripts/Misc/ExtensionGameObject.cs | using UnityEngine;
using System.Collections;
using System.Collections.Generic;
// 확장 메소드.
namespace GameObjectExtension {
static class _List {
// 선두 요소.
public static T front<T>(this List<T> list)
{
return(list[0]);
}
// 마지막 요소.
public static T back<T>(this List<T> list)
{
return(list[list.Count - 1]);
}
}
static class _MonoBehaviour {
// 포지션을 설정합니다.
public static void setPosition(this MonoBehaviour mono, Vector3 position)
{
mono.gameObject.transform.position = position;
}
// 위치를 구합니다.
public static Vector3 getPosition(this MonoBehaviour mono)
{
return(mono.gameObject.transform.position);
}
// 로컬 포지션을 설정합니다.
public static void setLocalPosition(this MonoBehaviour mono, Vector3 local_position)
{
mono.gameObject.transform.localPosition = local_position;
}
// 로컬 스케일을 설정합니다.
public static void setLocalScale(this MonoBehaviour mono, Vector3 local_scale)
{
mono.gameObject.transform.localScale = local_scale;
}
// ================================================================ //
// 부모를 설정합니다.
public static void setParent(this MonoBehaviour mono, GameObject parent)
{
if(parent != null) {
mono.gameObject.transform.parent = parent.transform;
} else {
mono.gameObject.transform.parent = null;
}
}
// ================================================================ //
};
static class _GameObject {
// 프리팹으로부터 인스턴스를 생성합니다.
public static GameObject instantiate(this GameObject prefab)
{
return(GameObject.Instantiate(prefab) as GameObject);
}
// 자기 자신을 폐기합니다.
public static void destroy(this GameObject go)
{
GameObject.Destroy(go);
}
// ================================================================ //
// 표시/비표시를 설정합니다.
public static void setVisible(this GameObject go, bool is_visible)
{
Renderer[] renders = go.GetComponentsInChildren<Renderer>();
foreach(var render in renders) {
render.enabled = is_visible;
}
}
// ================================================================ //
// 포지션을 설정합니다.
public static void setPosition(this GameObject go, Vector3 position)
{
go.transform.position = position;
}
// 위치를 구합니다.
public static Vector3 getPosition(this GameObject go)
{
return(go.transform.position);
}
// 로테이션을 설정합니다.
public static void setRotation(this GameObject go, Quaternion rotation)
{
go.transform.rotation = rotation;
}
// 로컬 포지션을 설정합니다.
public static void setLocalPosition(this GameObject go, Vector3 local_position)
{
go.transform.localPosition = local_position;
}
// 로컬 스케일을 설정합니다.
public static void setLocalScale(this GameObject go, Vector3 local_scale)
{
go.transform.localScale = local_scale;
}
// ================================================================ //
// 부모를 설정합니다.
public static void setParent(this GameObject go, GameObject parent)
{
if(parent != null) {
go.transform.parent = parent.transform;
} else {
go.transform.parent = null;
}
}
// 자식의 게임 오브젝트를 찾습니다.
public static GameObject findChildGameObject(this GameObject go, string child_name)
{
GameObject child_go = null;
Transform child = go.transform.FindChild(child_name);
if(child != null) {
child_go = child.gameObject;
}
return(child_go);
}
// 자식(과, 그 이하 노드)의 게임 오브젝트를 찾습니다.
public static GameObject findDescendant(this GameObject go, string name)
{
GameObject descendant = null;
descendant = go.findChildGameObject(name);
if(descendant == null) {
foreach(Transform child in go.transform) {
descendant = child.gameObject.findDescendant(name);
if(descendant != null) {
break;
}
}
}
return(descendant);
}
// ================================================================ //
// 머티리얼 프로퍼티를 변경합니다(float).
public static void setMaterialProperty(this GameObject go, string name, float value)
{
SkinnedMeshRenderer[] renders = go.GetComponentsInChildren<SkinnedMeshRenderer>();
foreach(var render in renders) {
render.material.SetFloat(name, value);
}
}
// 머티리얼 프로퍼티를 변경합니다(Color).
public static void setMaterialProperty(this GameObject go, string name, Color color)
{
SkinnedMeshRenderer[] renders = go.GetComponentsInChildren<SkinnedMeshRenderer>();
foreach(var render in renders) {
render.material.SetColor(name, color);
}
}
}
};
| 0 | 0.86068 | 1 | 0.86068 | game-dev | MEDIA | 0.959391 | game-dev | 0.976746 | 1 | 0.976746 |
folgerwang/UnrealEngine | 6,109 | Engine/Extras/ThirdPartyNotUE/emsdk/emscripten/1.38.20/system/include/SDL/SDL_joystick.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2011 Sam Lantinga <slouken@libsdl.org>
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.
*/
/**
* \file SDL_joystick.h
*
* Include file for SDL joystick event handling
*/
#ifndef _SDL_joystick_h
#define _SDL_joystick_h
#include "SDL_stdinc.h"
#include "SDL_error.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
/* *INDENT-OFF* */
extern "C" {
/* *INDENT-ON* */
#endif
/**
* \file SDL_joystick.h
*
* In order to use these functions, SDL_Init() must have been called
* with the ::SDL_INIT_JOYSTICK flag. This causes SDL to scan the system
* for joysticks, and load appropriate drivers.
*/
/* The joystick structure used to identify an SDL joystick */
struct _SDL_Joystick;
typedef struct _SDL_Joystick SDL_Joystick;
/* Function prototypes */
/**
* Count the number of joysticks attached to the system
*/
extern DECLSPEC int SDLCALL SDL_NumJoysticks(void);
/**
* Get the implementation dependent name of a joystick.
* This can be called before any joysticks are opened.
* If no name can be found, this function returns NULL.
*/
extern DECLSPEC const char *SDLCALL SDL_JoystickName(int device_index);
/**
* Open a joystick for use.
* The index passed as an argument refers tothe N'th joystick on the system.
* This index is the value which will identify this joystick in future joystick
* events.
*
* \return A joystick identifier, or NULL if an error occurred.
*/
extern DECLSPEC SDL_Joystick *SDLCALL SDL_JoystickOpen(int device_index);
/**
* Returns 1 if the joystick has been opened, or 0 if it has not.
*/
extern DECLSPEC int SDLCALL SDL_JoystickOpened(int device_index);
/**
* Get the device index of an opened joystick.
*/
extern DECLSPEC int SDLCALL SDL_JoystickIndex(SDL_Joystick * joystick);
/**
* Get the number of general axis controls on a joystick.
*/
extern DECLSPEC int SDLCALL SDL_JoystickNumAxes(SDL_Joystick * joystick);
/**
* Get the number of trackballs on a joystick.
*
* Joystick trackballs have only relative motion events associated
* with them and their state cannot be polled.
*/
extern DECLSPEC int SDLCALL SDL_JoystickNumBalls(SDL_Joystick * joystick);
/**
* Get the number of POV hats on a joystick.
*/
extern DECLSPEC int SDLCALL SDL_JoystickNumHats(SDL_Joystick * joystick);
/**
* Get the number of buttons on a joystick.
*/
extern DECLSPEC int SDLCALL SDL_JoystickNumButtons(SDL_Joystick * joystick);
/**
* Update the current state of the open joysticks.
*
* This is called automatically by the event loop if any joystick
* events are enabled.
*/
extern DECLSPEC void SDLCALL SDL_JoystickUpdate(void);
/**
* Enable/disable joystick event polling.
*
* If joystick events are disabled, you must call SDL_JoystickUpdate()
* yourself and check the state of the joystick when you want joystick
* information.
*
* The state can be one of ::SDL_QUERY, ::SDL_ENABLE or ::SDL_IGNORE.
*/
extern DECLSPEC int SDLCALL SDL_JoystickEventState(int state);
/**
* Get the current state of an axis control on a joystick.
*
* The state is a value ranging from -32768 to 32767.
*
* The axis indices start at index 0.
*/
extern DECLSPEC Sint16 SDLCALL SDL_JoystickGetAxis(SDL_Joystick * joystick,
int axis);
/**
* \name Hat positions
*/
/*@{*/
#define SDL_HAT_CENTERED 0x00
#define SDL_HAT_UP 0x01
#define SDL_HAT_RIGHT 0x02
#define SDL_HAT_DOWN 0x04
#define SDL_HAT_LEFT 0x08
#define SDL_HAT_RIGHTUP (SDL_HAT_RIGHT|SDL_HAT_UP)
#define SDL_HAT_RIGHTDOWN (SDL_HAT_RIGHT|SDL_HAT_DOWN)
#define SDL_HAT_LEFTUP (SDL_HAT_LEFT|SDL_HAT_UP)
#define SDL_HAT_LEFTDOWN (SDL_HAT_LEFT|SDL_HAT_DOWN)
/*@}*/
/**
* Get the current state of a POV hat on a joystick.
*
* The hat indices start at index 0.
*
* \return The return value is one of the following positions:
* - ::SDL_HAT_CENTERED
* - ::SDL_HAT_UP
* - ::SDL_HAT_RIGHT
* - ::SDL_HAT_DOWN
* - ::SDL_HAT_LEFT
* - ::SDL_HAT_RIGHTUP
* - ::SDL_HAT_RIGHTDOWN
* - ::SDL_HAT_LEFTUP
* - ::SDL_HAT_LEFTDOWN
*/
extern DECLSPEC Uint8 SDLCALL SDL_JoystickGetHat(SDL_Joystick * joystick,
int hat);
/**
* Get the ball axis change since the last poll.
*
* \return 0, or -1 if you passed it invalid parameters.
*
* The ball indices start at index 0.
*/
extern DECLSPEC int SDLCALL SDL_JoystickGetBall(SDL_Joystick * joystick,
int ball, int *dx, int *dy);
/**
* Get the current state of a button on a joystick.
*
* The button indices start at index 0.
*/
extern DECLSPEC Uint8 SDLCALL SDL_JoystickGetButton(SDL_Joystick * joystick,
int button);
/**
* Close a joystick previously opened with SDL_JoystickOpen().
*/
extern DECLSPEC void SDLCALL SDL_JoystickClose(SDL_Joystick * joystick);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
/* *INDENT-OFF* */
}
/* *INDENT-ON* */
#endif
#include "close_code.h"
#endif /* _SDL_joystick_h */
/* vi: set ts=4 sw=4 expandtab: */
| 0 | 0.753264 | 1 | 0.753264 | game-dev | MEDIA | 0.945365 | game-dev | 0.574945 | 1 | 0.574945 |
HighwayFrogs/frogger2-vss | 2,015 | teamSpirit/DC Frogger2 MsDev/common/evenfunc.h | /*
This file is part of Frogger2, (c) 1999 Interactive Studios Ltd.
File : event.h
Programmer : Jim Hubbard
Date : 30/06/99
----------------------------------------------------------------------------------------------- */
#ifndef EVENTFUNCS_H_INCLUDED
#define EVENTFUNCS_H_INCLUDED
#include "maths.h"
#include "define.h"
#include "event.h"
typedef struct TAG_SPRINGINFO
{
SVECTOR S, V, H;
GAMETILE *dest;
int start, end, frog;
} SPRINGINFO;
#ifdef __cplusplus
extern "C" {
#endif
/*----- [ TRIGGER PROTOTYPES ] -----------------------------------------------------------------*/
extern int EnemyOnTile( TRIGGER *trigger );
extern int FrogOnTile( TRIGGER *trigger );
extern int FrogOnPlatform( TRIGGER *trigger );
extern int ActorWithinRadius( TRIGGER *trigger );
extern int OnTimeout( TRIGGER *trigger );
extern int OnRandomTimeout( TRIGGER *trigger );
extern int OnTrigger( TRIGGER *trigger );
extern int LogicalAND( TRIGGER *trigger );
extern int LogicalOR( TRIGGER *trigger );
extern int FrogOnFrog( TRIGGER *trigger );
extern int EnemyAtFlag( TRIGGER *trigger );
extern int PlatformAtFlag( TRIGGER *trigger );
extern int ActorNearActor( TRIGGER *trigger );
extern int PathAtFlag( TRIGGER *trigger );
extern int BitCheck( TRIGGER *trigger );
extern int FrogIsDead( TRIGGER *trigger );
extern int LevelIsOpen( TRIGGER *trigger );
extern int EnemyAtFlag(TRIGGER *trigger);
extern int PlatformAtFlag(TRIGGER *trigger);
/*----- [ EVENT PROTOTYPES ] -------------------------------------------------------------------*/
extern void ChangeActorScale( EVENT *event );
extern void AssignFloatToFloat( EVENT *event );
extern void AssignIntToInt( EVENT *event );
extern void TogglePlatformMove( EVENT *event );
extern void ToggleEnemyMove( EVENT *event );
extern void ToggleTileLink( EVENT *event );
extern void PlaySFX( EVENT *event );
extern void EvAnimateActor( EVENT *event );
extern void TeleportFrog( EVENT *event );
extern void DeathAnim( EVENT *event );
#ifdef __cplusplus
}
#endif
#endif | 0 | 0.720331 | 1 | 0.720331 | game-dev | MEDIA | 0.934863 | game-dev | 0.70292 | 1 | 0.70292 |
moonforce/ObliqueMap | 13,043 | Assets/unity-ui-extensions/Scripts/ToolTips/HoverTooltip.cs | /// Credit drHogan
/// Sourced from - http://www.hammerandravens.com/multi-use-tooltip-system-in-unity3d/
namespace UnityEngine.UI.Extensions
{
[AddComponentMenu("UI/Extensions/HoverTooltip")]
public class HoverTooltip : MonoBehaviour
{
//manually selectable padding for the background image
public int horizontalPadding;
public int verticalPadding;
//tooltip text
public Text thisText;
//horizontal layout of the tooltip
public HorizontalLayoutGroup hlG;
//tooltip background image
public RectTransform bgImage;
Image bgImageSource;
//needed as the layout refreshes only on the first Update() call
bool firstUpdate;
//if the tooltip is inside a UI element
bool inside;
//size of the tooltip, needed to track if out of screen
// public float width;
// public float height;
//detect canvas mode so to apply different behaviors to different canvas modes, currently only RenderMode.ScreenSpaceCamera implemented
//int canvasMode;
RenderMode GUIMode;
//the scene GUI camera
Camera GUICamera;
//the default tooltip object has the following pivots, so that the offset from the mouse is always proportional to the screen resolution (the y pivot)
//Pivot(0.5,-0.5)
//screen viewport corners for out of screen detection
Vector3 lowerLeft;
Vector3 upperRight;
//scale factor of proportionality to the reference resolution (1280x720)
float currentYScaleFactor;
float currentXScaleFactor;
//standard X and Y offsets of the new tooltip
float defaultYOffset;
float defaultXOffset;
//real on screen sizes of the tooltip object
float tooltipRealHeight;
float tooltipRealWidth;
// Use this for initialization
void Start()
{
//in this line you need to change the string in order to get your Camera //TODO MAYBE DO IT FROM THE INSPECTOR
GUICamera = GameObject.Find("GUICamera").GetComponent<Camera>();
GUIMode = this.transform.parent.parent.GetComponent<Canvas>().renderMode;
bgImageSource = bgImage.GetComponent<Image>();
//at start the pointer is never to be considered over and UI element
inside = false;
//assign the tooltip to the singleton GUI class manager for fast access
//TacticalGUIManager.tgm.mmttp = this;
//hide the tooltip
HideTooltipVisibility();
this.transform.parent.gameObject.SetActive(false);
}
//single string input tooltip
public void SetTooltip(string text)
{
NewTooltip();
//init tooltip string
thisText.text = text;
//call the position function
OnScreenSpaceCamera();
}
//multi string/line input tooltip (each string of the input array is a new line)
public void SetTooltip(string[] texts)
{
NewTooltip();
//build up the tooltip line after line with the input
string tooltipText = "";
int index = 0;
foreach (string newLine in texts)
{
if (index == 0)
{
tooltipText += newLine;
}
else
{
tooltipText += ("\n" + newLine);
}
index++;
}
//init tooltip string
thisText.text = tooltipText;
//call the position function
OnScreenSpaceCamera();
}
//temporary call to don't fuck up old code, will be removed
public void SetTooltip(string text, bool test)
{
NewTooltip();
//init tooltip string
thisText.text = text;
//call the position function
OnScreenSpaceCamera();
}
//position function, currently not working correctly due to the use of pivots and not manual offsets, soon to be fixed
public void OnScreenSpaceCamera()
{
//get the dynamic position of the pous in viewport coordinates
Vector3 newPos = GUICamera.ScreenToViewportPoint(Input.mousePosition);
// store in val the updated position (x or y) of the tooltip edge of interest
float val;
//store the new offset to impose in case of out of screen
float yOffSet = 0f;
float xOffSet = 0f;
//check for right edge of screen
//obtain the x coordinate of the right edge of the tooltip
val = ((GUICamera.ViewportToScreenPoint(newPos).x) + (tooltipRealWidth * bgImage.pivot.x));
//evaluate if the right edge of the tooltip goes out of screen
if (val > (upperRight.x))
{
float distFromRight = upperRight.x - val;
if (distFromRight > (defaultXOffset * 0.75))
{
//shorten the temporary offset up to a certain distance from the tooltip
xOffSet = distFromRight;
}
else
{
//if the distance becomes too short flip the tooltip to below the pointer (by offset+twice the height of the tooltip)
xOffSet = ((defaultXOffset) - (tooltipRealWidth) * 2f);
}
//assign the new modified coordinates to the tooltip and convert to screen coordinates
Vector3 newTooltipPos = new Vector3(GUICamera.ViewportToScreenPoint(newPos).x + xOffSet, 0f, 0f);
newPos.x = GUICamera.ScreenToViewportPoint(newTooltipPos).x;
}
//check for left edge of screen
//obtain the x coordinate of the left edge of the tooltip
val = ((GUICamera.ViewportToScreenPoint(newPos).x) - (tooltipRealWidth * bgImage.pivot.x));
//evaluate if the left edge of the tooltip goes out of screen
if (val < (lowerLeft.x))
{
float distFromLeft = lowerLeft.x - val;
if (distFromLeft < (defaultXOffset * 0.75 - tooltipRealWidth))
{
//shorten the temporary offset up to a certain distance from the tooltip
xOffSet = -distFromLeft;
}
else
{
//if the distance becomes too short flip the tooltip to above the pointer (by twice the height of the tooltip)
xOffSet = ((tooltipRealWidth) * 2f);
}
//assign the new modified coordinates to the tooltip and convert to screen coordinates
Vector3 newTooltipPos = new Vector3(GUICamera.ViewportToScreenPoint(newPos).x - xOffSet, 0f, 0f);
newPos.x = GUICamera.ScreenToViewportPoint(newTooltipPos).x;
}
//check for upper edge of the screen
//obtain the y coordinate of the upper edge of the tooltip
val = ((GUICamera.ViewportToScreenPoint(newPos).y) - ((bgImage.sizeDelta.y * currentYScaleFactor * (bgImage.pivot.y)) - (tooltipRealHeight)));
//evaluate if the upper edge of the tooltip goes out of screen
if (val > (upperRight.y))
{
float distFromUpper = upperRight.y - val;
yOffSet = (bgImage.sizeDelta.y * currentYScaleFactor * (bgImage.pivot.y));
if (distFromUpper > (defaultYOffset * 0.75))
{
//shorten the temporary offset up to a certain distance from the tooltip
yOffSet = distFromUpper;
}
else
{
//if the distance becomes too short flip the tooltip to below the pointer (by offset+twice the height of the tooltip)
yOffSet = ((defaultYOffset) - (tooltipRealHeight) * 2f);
}
//assign the new modified coordinates to the tooltip and convert to screen coordinates
Vector3 newTooltipPos = new Vector3(newPos.x, GUICamera.ViewportToScreenPoint(newPos).y + yOffSet, 0f);
newPos.y = GUICamera.ScreenToViewportPoint(newTooltipPos).y;
}
//check for lower edge of the screen
//obtain the y coordinate of the lower edge of the tooltip
val = ((GUICamera.ViewportToScreenPoint(newPos).y) - ((bgImage.sizeDelta.y * currentYScaleFactor * (bgImage.pivot.y))));
//evaluate if the upper edge of the tooltip goes out of screen
if (val < (lowerLeft.y))
{
float distFromLower = lowerLeft.y - val;
yOffSet = (bgImage.sizeDelta.y * currentYScaleFactor * (bgImage.pivot.y));
if (distFromLower < (defaultYOffset * 0.75 - tooltipRealHeight))
{
//shorten the temporary offset up to a certain distance from the tooltip
yOffSet = distFromLower;
}
else
{
//if the distance becomes too short flip the tooltip to above the pointer (by twice the height of the tooltip)
yOffSet = ((tooltipRealHeight) * 2f);
}
//assign the new modified coordinates to the tooltip and convert to screen coordinates
Vector3 newTooltipPos = new Vector3(newPos.x, GUICamera.ViewportToScreenPoint(newPos).y + yOffSet, 0f);
newPos.y = GUICamera.ScreenToViewportPoint(newTooltipPos).y;
}
this.transform.parent.transform.position = new Vector3(GUICamera.ViewportToWorldPoint(newPos).x, GUICamera.ViewportToWorldPoint(newPos).y, 0f);
this.transform.parent.gameObject.SetActive(true);
inside = true;
}
//call to hide tooltip when hovering out from the object
public void HideTooltip()
{
if (GUIMode == RenderMode.ScreenSpaceCamera)
{
if (this != null)
{
this.transform.parent.gameObject.SetActive(false);
inside = false;
HideTooltipVisibility();
}
}
}
// Update is called once per frame
void Update()
{
LayoutInit();
if (inside)
{
if (GUIMode == RenderMode.ScreenSpaceCamera)
{
OnScreenSpaceCamera();
}
}
}
//this function is used in order to setup the size of the tooltip by cheating on the HorizontalLayoutBehavior. The resize is done in the first update.
void LayoutInit()
{
if (firstUpdate)
{
firstUpdate = false;
bgImage.sizeDelta = new Vector2(hlG.preferredWidth + horizontalPadding, hlG.preferredHeight + verticalPadding);
defaultYOffset = (bgImage.sizeDelta.y * currentYScaleFactor * (bgImage.pivot.y));
defaultXOffset = (bgImage.sizeDelta.x * currentXScaleFactor * (bgImage.pivot.x));
tooltipRealHeight = bgImage.sizeDelta.y * currentYScaleFactor;
tooltipRealWidth = bgImage.sizeDelta.x * currentXScaleFactor;
ActivateTooltipVisibility();
}
}
//init basic variables on a new tooltip set
void NewTooltip()
{
firstUpdate = true;
lowerLeft = GUICamera.ViewportToScreenPoint(new Vector3(0.0f, 0.0f, 0.0f));
upperRight = GUICamera.ViewportToScreenPoint(new Vector3(1.0f, 1.0f, 0.0f));
currentYScaleFactor = Screen.height / this.transform.root.GetComponent<CanvasScaler>().referenceResolution.y;
currentXScaleFactor = Screen.width / this.transform.root.GetComponent<CanvasScaler>().referenceResolution.x;
}
//used to visualize the tooltip one update call after it has been built (to avoid flickers)
public void ActivateTooltipVisibility()
{
Color textColor = thisText.color;
thisText.color = new Color(textColor.r, textColor.g, textColor.b, 1f);
bgImageSource.color = new Color(bgImageSource.color.r, bgImageSource.color.g, bgImageSource.color.b, 0.8f);
}
//used to hide the tooltip so that it can be made visible one update call after it has been built (to avoid flickers)
public void HideTooltipVisibility()
{
Color textColor = thisText.color;
thisText.color = new Color(textColor.r, textColor.g, textColor.b, 0f);
bgImageSource.color = new Color(bgImageSource.color.r, bgImageSource.color.g, bgImageSource.color.b, 0f);
}
}
} | 0 | 0.925823 | 1 | 0.925823 | game-dev | MEDIA | 0.619501 | game-dev,graphics-rendering | 0.921623 | 1 | 0.921623 |
folgerwang/UnrealEngine | 60,373 | Engine/Source/Runtime/GameplayTags/Private/GameplayTagsManager.cpp | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
#include "GameplayTagsManager.h"
#include "Engine/Engine.h"
#include "HAL/PlatformFilemanager.h"
#include "HAL/FileManager.h"
#include "Misc/Paths.h"
#include "Misc/ScopeLock.h"
#include "Stats/StatsMisc.h"
#include "Misc/ConfigCacheIni.h"
#include "UObject/UObjectHash.h"
#include "UObject/UObjectIterator.h"
#include "UObject/LinkerLoad.h"
#include "UObject/Package.h"
#include "GameplayTagsSettings.h"
#include "GameplayTagsModule.h"
#include "Framework/Notifications/NotificationManager.h"
#include "Widgets/Notifications/SNotificationList.h"
#include "Misc/CoreDelegates.h"
#if WITH_EDITOR
#include "SourceControlHelpers.h"
#include "ISourceControlModule.h"
#include "Editor.h"
#include "PropertyHandle.h"
FSimpleMulticastDelegate UGameplayTagsManager::OnEditorRefreshGameplayTagTree;
#endif
#include "HAL/IConsoleManager.h"
const static FName NAME_Categories("Categories");
const static FName NAME_GameplayTagFilter("GameplayTagFilter");
#define LOCTEXT_NAMESPACE "GameplayTagManager"
UGameplayTagsManager* UGameplayTagsManager::SingletonManager = nullptr;
UGameplayTagsManager::UGameplayTagsManager(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
bUseFastReplication = false;
bShouldWarnOnInvalidTags = true;
bDoneAddingNativeTags = false;
NetIndexFirstBitSegment = 16;
NetIndexTrueBitNum = 16;
NumBitsForContainerSize = 6;
}
// Enable to turn on detailed startup logging
#define GAMEPLAYTAGS_VERBOSE 0
#if STATS && GAMEPLAYTAGS_VERBOSE
#define SCOPE_LOG_GAMEPLAYTAGS(Name) SCOPE_LOG_TIME_IN_SECONDS(Name, nullptr)
#else
#define SCOPE_LOG_GAMEPLAYTAGS(Name)
#endif
void UGameplayTagsManager::LoadGameplayTagTables(bool bAllowAsyncLoad)
{
UGameplayTagsSettings* MutableDefault = GetMutableDefault<UGameplayTagsSettings>();
GameplayTagTables.Empty();
// If we're a cooked build and in a safe spot, start an async load so we can pipeline it
if (bAllowAsyncLoad && !WITH_EDITOR && !IsLoading() && MutableDefault->GameplayTagTableList.Num() > 0)
{
for (FSoftObjectPath DataTablePath : MutableDefault->GameplayTagTableList)
{
LoadPackageAsync(DataTablePath.GetLongPackageName());
}
return;
}
SCOPE_LOG_GAMEPLAYTAGS(TEXT("UGameplayTagsManager::LoadGameplayTagTables"));
for (FSoftObjectPath DataTablePath : MutableDefault->GameplayTagTableList)
{
UDataTable* TagTable = LoadObject<UDataTable>(nullptr, *DataTablePath.ToString(), nullptr, LOAD_None, nullptr);
// Handle case where the module is dynamically-loaded within a LoadPackage stack, which would otherwise
// result in the tag table not having its RowStruct serialized in time. Without the RowStruct, the tags manager
// will not be initialized correctly.
if (TagTable)
{
FLinkerLoad* TagLinker = TagTable->GetLinker();
if (TagLinker)
{
TagTable->GetLinker()->Preload(TagTable);
}
}
GameplayTagTables.Add(TagTable);
}
}
struct FCompareFGameplayTagNodeByTag
{
FORCEINLINE bool operator()( const TSharedPtr<FGameplayTagNode>& A, const TSharedPtr<FGameplayTagNode>& B ) const
{
// Note: GetSimpleTagName() is not good enough here. The individual tag nodes are share frequently (E.g, Dog.Tail, Cat.Tail have sub nodes with the same simple tag name)
// Compare with equal FNames will look at the backing number/indice to the FName. For FNames used elsewhere, like "A" for example, this can cause non determinism in platforms
// (For example if static order initialization differs on two platforms, the "version" of the "A" FName that two places get could be different, causing this comparison to also be)
return (A->GetCompleteTagName().Compare(B->GetCompleteTagName())) < 0;
}
};
void UGameplayTagsManager::ConstructGameplayTagTree()
{
SCOPE_LOG_GAMEPLAYTAGS(TEXT("UGameplayTagsManager::ConstructGameplayTagTree"));
if (!GameplayRootTag.IsValid())
{
GameplayRootTag = MakeShareable(new FGameplayTagNode());
UGameplayTagsSettings* MutableDefault = GetMutableDefault<UGameplayTagsSettings>();
TArray<FName> RestrictedGameplayTagSourceNames;
// Copy invalid characters, then add internal ones
InvalidTagCharacters = MutableDefault->InvalidTagCharacters;
InvalidTagCharacters.Append(TEXT("\r\n\t"));
// Add prefixes first
if (ShouldImportTagsFromINI())
{
SCOPE_LOG_GAMEPLAYTAGS(TEXT("UGameplayTagsManager::ConstructGameplayTagTree: ImportINI prefixes"));
TArray<FString> RestrictedGameplayTagFiles;
GetRestrictedTagConfigFiles(RestrictedGameplayTagFiles);
RestrictedGameplayTagFiles.Sort();
for (const FString& FileName : RestrictedGameplayTagFiles)
{
FName TagSource = FName(*FPaths::GetCleanFilename(FileName));
if (TagSource == NAME_None)
{
continue;
}
RestrictedGameplayTagSourceNames.Add(TagSource);
FGameplayTagSource* FoundSource = FindOrAddTagSource(TagSource, EGameplayTagSourceType::RestrictedTagList);
// Make sure we have regular tag sources to match the restricted tag sources but don't try to read any tags from them yet.
FindOrAddTagSource(TagSource, EGameplayTagSourceType::TagList);
if (FoundSource && FoundSource->SourceRestrictedTagList)
{
FoundSource->SourceRestrictedTagList->LoadConfig(URestrictedGameplayTagsList::StaticClass(), *FileName);
#if WITH_EDITOR
if (GIsEditor || IsRunningCommandlet()) // Sort tags for UI Purposes but don't sort in -game scenario since this would break compat with noneditor cooked builds
{
FoundSource->SourceRestrictedTagList->SortTags();
}
#endif
for (const FRestrictedGameplayTagTableRow& TableRow : FoundSource->SourceRestrictedTagList->RestrictedGameplayTagList)
{
AddTagTableRow(TableRow, TagSource, true);
}
}
}
}
{
SCOPE_LOG_GAMEPLAYTAGS(TEXT("UGameplayTagsManager::ConstructGameplayTagTree: Add native tags"));
// Add native tags before other tags
for (FName TagToAdd : NativeTagsToAdd)
{
AddTagTableRow(FGameplayTagTableRow(TagToAdd), FGameplayTagSource::GetNativeName());
}
}
// If we didn't load any tables it might be async loading, so load again with a flush
if (GameplayTagTables.Num() == 0)
{
LoadGameplayTagTables(false);
}
{
SCOPE_LOG_GAMEPLAYTAGS(TEXT("UGameplayTagsManager::ConstructGameplayTagTree: Construct from data asset"));
for (UDataTable* DataTable : GameplayTagTables)
{
if (DataTable)
{
PopulateTreeFromDataTable(DataTable);
}
}
}
// Create native source
FindOrAddTagSource(FGameplayTagSource::GetNativeName(), EGameplayTagSourceType::Native);
if (ShouldImportTagsFromINI())
{
SCOPE_LOG_GAMEPLAYTAGS(TEXT("UGameplayTagsManager::ConstructGameplayTagTree: ImportINI tags"));
// Copy from deprecated list in DefaultEngine.ini
TArray<FString> EngineConfigTags;
GConfig->GetArray(TEXT("/Script/GameplayTags.GameplayTagsSettings"), TEXT("+GameplayTags"), EngineConfigTags, GEngineIni);
for (const FString& EngineConfigTag : EngineConfigTags)
{
MutableDefault->GameplayTagList.AddUnique(FGameplayTagTableRow(FName(*EngineConfigTag)));
}
// Copy from deprecated list in DefaultGamplayTags.ini
EngineConfigTags.Empty();
GConfig->GetArray(TEXT("/Script/GameplayTags.GameplayTagsSettings"), TEXT("+GameplayTags"), EngineConfigTags, MutableDefault->GetDefaultConfigFilename());
for (const FString& EngineConfigTag : EngineConfigTags)
{
MutableDefault->GameplayTagList.AddUnique(FGameplayTagTableRow(FName(*EngineConfigTag)));
}
#if WITH_EDITOR
MutableDefault->SortTags();
#endif
FName TagSource = FGameplayTagSource::GetDefaultName();
FGameplayTagSource* DefaultSource = FindOrAddTagSource(TagSource, EGameplayTagSourceType::DefaultTagList);
for (const FGameplayTagTableRow& TableRow : MutableDefault->GameplayTagList)
{
AddTagTableRow(TableRow, TagSource);
}
// Extra tags
// Read all tags from the ini
TArray<FString> FilesInDirectory;
IFileManager::Get().FindFilesRecursive(FilesInDirectory, *(FPaths::ProjectConfigDir() / TEXT("Tags")), TEXT("*.ini"), true, false);
FilesInDirectory.Sort();
for (FString& FileName : FilesInDirectory)
{
TagSource = FName(*FPaths::GetCleanFilename(FileName));
// skip the restricted tag files
bool bIsRestrictedTagFile = false;
for (const FName& RestrictedTagSource : RestrictedGameplayTagSourceNames)
{
if (TagSource == RestrictedTagSource)
{
bIsRestrictedTagFile = true;
break;
}
}
if (bIsRestrictedTagFile)
{
continue;
}
FGameplayTagSource* FoundSource = FindOrAddTagSource(TagSource, EGameplayTagSourceType::TagList);
UE_CLOG(GAMEPLAYTAGS_VERBOSE, LogGameplayTags, Display, TEXT("Loading Tag File: %s"), *FileName);
if (FoundSource && FoundSource->SourceTagList)
{
// Check deprecated locations
TArray<FString> Tags;
if (GConfig->GetArray(TEXT("UserTags"), TEXT("GameplayTags"), Tags, FileName))
{
for (const FString& Tag : Tags)
{
FoundSource->SourceTagList->GameplayTagList.AddUnique(FGameplayTagTableRow(FName(*Tag)));
}
}
else
{
// Load from new ini
FoundSource->SourceTagList->LoadConfig(UGameplayTagsList::StaticClass(), *FileName);
}
#if WITH_EDITOR
if (GIsEditor || IsRunningCommandlet()) // Sort tags for UI Purposes but don't sort in -game scenario since this would break compat with noneditor cooked builds
{
FoundSource->SourceTagList->SortTags();
}
#endif
for (const FGameplayTagTableRow& TableRow : FoundSource->SourceTagList->GameplayTagList)
{
AddTagTableRow(TableRow, TagSource);
}
}
}
}
#if WITH_EDITOR
// Add any transient editor-only tags
for (FName TransientTag : TransientEditorTags)
{
AddTagTableRow(FGameplayTagTableRow(TransientTag), FGameplayTagSource::GetTransientEditorName());
}
#endif
{
SCOPE_LOG_GAMEPLAYTAGS(TEXT("UGameplayTagsManager::ConstructGameplayTagTree: Request common tags"));
// Grab the commonly replicated tags
CommonlyReplicatedTags.Empty();
for (FName TagName : MutableDefault->CommonlyReplicatedTags)
{
FGameplayTag Tag = RequestGameplayTag(TagName);
if (Tag.IsValid())
{
CommonlyReplicatedTags.Add(Tag);
}
else
{
UE_LOG(LogGameplayTags, Warning, TEXT("%s was found in the CommonlyReplicatedTags list but doesn't appear to be a valid tag!"), *TagName.ToString());
}
}
bUseFastReplication = MutableDefault->FastReplication;
bShouldWarnOnInvalidTags = MutableDefault->WarnOnInvalidTags;
NumBitsForContainerSize = MutableDefault->NumBitsForContainerSize;
NetIndexFirstBitSegment = MutableDefault->NetIndexFirstBitSegment;
}
if (ShouldUseFastReplication())
{
SCOPE_LOG_GAMEPLAYTAGS(TEXT("UGameplayTagsManager::ConstructGameplayTagTree: Reconstruct NetIndex"));
ConstructNetIndex();
}
{
SCOPE_LOG_GAMEPLAYTAGS(TEXT("UGameplayTagsManager::ConstructGameplayTagTree: GameplayTagTreeChangedEvent.Broadcast"));
IGameplayTagsModule::OnGameplayTagTreeChanged.Broadcast();
}
{
SCOPE_LOG_GAMEPLAYTAGS(TEXT("UGameplayTagsManager::ConstructGameplayTagTree: Load redirects"));
// Update the TagRedirects map
TagRedirects.Empty();
// Check the deprecated location
bool bFoundDeprecated = false;
FConfigSection* PackageRedirects = GConfig->GetSectionPrivate(TEXT("/Script/Engine.Engine"), false, true, GEngineIni);
if (PackageRedirects)
{
for (FConfigSection::TIterator It(*PackageRedirects); It; ++It)
{
if (It.Key() == TEXT("+GameplayTagRedirects"))
{
FName OldTagName = NAME_None;
FName NewTagName;
if (FParse::Value(*It.Value().GetValue(), TEXT("OldTagName="), OldTagName))
{
if (FParse::Value(*It.Value().GetValue(), TEXT("NewTagName="), NewTagName))
{
FGameplayTagRedirect Redirect;
Redirect.OldTagName = OldTagName;
Redirect.NewTagName = NewTagName;
MutableDefault->GameplayTagRedirects.AddUnique(Redirect);
bFoundDeprecated = true;
}
}
}
}
}
if (bFoundDeprecated)
{
UE_LOG(LogGameplayTags, Log, TEXT("GameplayTagRedirects is in a deprecated location, after editing GameplayTags developer settings you must remove these manually"));
}
// Check settings object
for (const FGameplayTagRedirect& Redirect : MutableDefault->GameplayTagRedirects)
{
FName OldTagName = Redirect.OldTagName;
FName NewTagName = Redirect.NewTagName;
if (ensureMsgf(!TagRedirects.Contains(OldTagName), TEXT("Old tag %s is being redirected to more than one tag. Please remove all the redirections except for one."), *OldTagName.ToString()))
{
FGameplayTag OldTag = RequestGameplayTag(OldTagName, false); //< This only succeeds if OldTag is in the Table!
if (OldTag.IsValid())
{
FGameplayTagContainer MatchingChildren = RequestGameplayTagChildren(OldTag);
FString Msg = FString::Printf(TEXT("Old tag (%s) which is being redirected still exists in the table! Generally you should "
TEXT("remove the old tags from the table when you are redirecting to new tags, or else users will ")
TEXT("still be able to add the old tags to containers.")), *OldTagName.ToString());
if (MatchingChildren.Num() == 0)
{
UE_LOG(LogGameplayTags, Warning, TEXT("%s"), *Msg);
}
else
{
Msg += TEXT("\nSuppressed warning due to redirected tag being a single component that matched other hierarchy elements.");
UE_LOG(LogGameplayTags, Log, TEXT("%s"), *Msg);
}
}
FGameplayTag NewTag = (NewTagName != NAME_None) ? RequestGameplayTag(NewTagName, false) : FGameplayTag();
// Basic infinite recursion guard
int32 IterationsLeft = 10;
while (!NewTag.IsValid() && NewTagName != NAME_None)
{
bool bFoundRedirect = false;
// See if it got redirected again
for (const FGameplayTagRedirect& SecondRedirect : MutableDefault->GameplayTagRedirects)
{
if (SecondRedirect.OldTagName == NewTagName)
{
NewTagName = SecondRedirect.NewTagName;
NewTag = RequestGameplayTag(NewTagName, false);
bFoundRedirect = true;
break;
}
}
IterationsLeft--;
if (!bFoundRedirect || IterationsLeft <= 0)
{
UE_LOG(LogGameplayTags, Warning, TEXT("Invalid new tag %s! Cannot replace old tag %s."),
*Redirect.NewTagName.ToString(), *Redirect.OldTagName.ToString());
break;
}
}
if (NewTag.IsValid())
{
// Populate the map
TagRedirects.Add(OldTagName, NewTag);
}
}
}
}
}
}
int32 PrintNetIndiceAssignment = 0;
static FAutoConsoleVariableRef CVarPrintNetIndiceAssignment(TEXT("GameplayTags.PrintNetIndiceAssignment"), PrintNetIndiceAssignment, TEXT("Logs GameplayTag NetIndice assignment"), ECVF_Default );
void UGameplayTagsManager::ConstructNetIndex()
{
NetworkGameplayTagNodeIndex.Empty();
GameplayTagNodeMap.GenerateValueArray(NetworkGameplayTagNodeIndex);
NetworkGameplayTagNodeIndex.Sort(FCompareFGameplayTagNodeByTag());
check(CommonlyReplicatedTags.Num() <= NetworkGameplayTagNodeIndex.Num());
// Put the common indices up front
for (int32 CommonIdx=0; CommonIdx < CommonlyReplicatedTags.Num(); ++CommonIdx)
{
int32 BaseIdx=0;
FGameplayTag& Tag = CommonlyReplicatedTags[CommonIdx];
bool Found = false;
for (int32 findidx=0; findidx < NetworkGameplayTagNodeIndex.Num(); ++findidx)
{
if (NetworkGameplayTagNodeIndex[findidx]->GetCompleteTag() == Tag)
{
NetworkGameplayTagNodeIndex.Swap(findidx, CommonIdx);
Found = true;
break;
}
}
// A non fatal error should have been thrown when parsing the CommonlyReplicatedTags list. If we make it here, something is seriously wrong.
checkf( Found, TEXT("Tag %s not found in NetworkGameplayTagNodeIndex"), *Tag.ToString() );
}
InvalidTagNetIndex = NetworkGameplayTagNodeIndex.Num()+1;
NetIndexTrueBitNum = FMath::CeilToInt(FMath::Log2(InvalidTagNetIndex));
// This should never be smaller than NetIndexTrueBitNum
NetIndexFirstBitSegment = FMath::Min<int64>(NetIndexFirstBitSegment, NetIndexTrueBitNum);
// This is now sorted and it should be the same on both client and server
if (NetworkGameplayTagNodeIndex.Num() >= INVALID_TAGNETINDEX)
{
ensureMsgf(false, TEXT("Too many tags in dictionary for networking! Remove tags or increase tag net index size"));
NetworkGameplayTagNodeIndex.SetNum(INVALID_TAGNETINDEX - 1);
}
UE_CLOG(PrintNetIndiceAssignment, LogGameplayTags, Display, TEXT("Assigning NetIndices to %d tags."), NetworkGameplayTagNodeIndex.Num() );
for (FGameplayTagNetIndex i = 0; i < NetworkGameplayTagNodeIndex.Num(); i++)
{
if (NetworkGameplayTagNodeIndex[i].IsValid())
{
NetworkGameplayTagNodeIndex[i]->NetIndex = i;
UE_CLOG(PrintNetIndiceAssignment, LogGameplayTags, Display, TEXT("Assigning NetIndex (%d) to Tag (%s)"), i, *NetworkGameplayTagNodeIndex[i]->GetCompleteTag().ToString());
}
else
{
UE_LOG(LogGameplayTags, Warning, TEXT("TagNode Indice %d is invalid!"), i);
}
}
}
FName UGameplayTagsManager::GetTagNameFromNetIndex(FGameplayTagNetIndex Index) const
{
if (Index >= NetworkGameplayTagNodeIndex.Num())
{
// Ensure Index is the invalid index. If its higher than that, then something is wrong.
ensureMsgf(Index == InvalidTagNetIndex, TEXT("Received invalid tag net index %d! Tag index is out of sync on client!"), Index);
return NAME_None;
}
return NetworkGameplayTagNodeIndex[Index]->GetCompleteTagName();
}
FGameplayTagNetIndex UGameplayTagsManager::GetNetIndexFromTag(const FGameplayTag &InTag) const
{
TSharedPtr<FGameplayTagNode> GameplayTagNode = FindTagNode(InTag);
if (GameplayTagNode.IsValid())
{
return GameplayTagNode->GetNetIndex();
}
return InvalidTagNetIndex;
}
bool UGameplayTagsManager::ShouldImportTagsFromINI() const
{
UGameplayTagsSettings* MutableDefault = GetMutableDefault<UGameplayTagsSettings>();
// Deprecated path
bool ImportFromINI = false;
if (GConfig->GetBool(TEXT("GameplayTags"), TEXT("ImportTagsFromConfig"), ImportFromINI, GEngineIni))
{
if (ImportFromINI)
{
MutableDefault->ImportTagsFromConfig = ImportFromINI;
UE_LOG(LogGameplayTags, Log, TEXT("ImportTagsFromConfig is in a deprecated location, open and save GameplayTag settings to fix"));
}
return ImportFromINI;
}
return MutableDefault->ImportTagsFromConfig;
}
void UGameplayTagsManager::GetRestrictedTagConfigFiles(TArray<FString>& RestrictedConfigFiles) const
{
UGameplayTagsSettings* MutableDefault = GetMutableDefault<UGameplayTagsSettings>();
if (MutableDefault)
{
for (const FRestrictedConfigInfo& Config : MutableDefault->RestrictedConfigFiles)
{
RestrictedConfigFiles.Add(FString::Printf(TEXT("%sTags/%s"), *FPaths::SourceConfigDir(), *Config.RestrictedConfigName));
}
}
}
void UGameplayTagsManager::GetRestrictedTagSources(TArray<const FGameplayTagSource*>& Sources) const
{
UGameplayTagsSettings* MutableDefault = GetMutableDefault<UGameplayTagsSettings>();
if (MutableDefault)
{
for (const FRestrictedConfigInfo& Config : MutableDefault->RestrictedConfigFiles)
{
const FGameplayTagSource* Source = FindTagSource(*Config.RestrictedConfigName);
if (Source)
{
Sources.Add(Source);
}
}
}
}
void UGameplayTagsManager::GetOwnersForTagSource(const FString& SourceName, TArray<FString>& OutOwners) const
{
UGameplayTagsSettings* MutableDefault = GetMutableDefault<UGameplayTagsSettings>();
if (MutableDefault)
{
for (const FRestrictedConfigInfo& Config : MutableDefault->RestrictedConfigFiles)
{
if (Config.RestrictedConfigName.Equals(SourceName))
{
OutOwners = Config.Owners;
return;
}
}
}
}
void UGameplayTagsManager::RedirectTagsForContainer(FGameplayTagContainer& Container, UProperty* SerializingProperty) const
{
TSet<FName> NamesToRemove;
TSet<const FGameplayTag*> TagsToAdd;
// First populate the NamesToRemove and TagsToAdd sets by finding tags in the container that have redirects
for (auto TagIt = Container.CreateConstIterator(); TagIt; ++TagIt)
{
const FName TagName = TagIt->GetTagName();
const FGameplayTag* NewTag = TagRedirects.Find(TagName);
if (NewTag)
{
NamesToRemove.Add(TagName);
if (NewTag->IsValid())
{
TagsToAdd.Add(NewTag);
}
}
#if WITH_EDITOR
else if (SerializingProperty)
{
// Warn about invalid tags at load time in editor builds, too late to fix it in cooked builds
FGameplayTag OldTag = RequestGameplayTag(TagName, false);
if (!OldTag.IsValid() && ShouldWarnOnInvalidTags())
{
UE_LOG(LogGameplayTags, Warning, TEXT("Invalid GameplayTag %s found while loading property %s."), *TagName.ToString(), *GetPathNameSafe(SerializingProperty));
}
}
#endif
}
// Remove all tags from the NamesToRemove set
for (FName RemoveName : NamesToRemove)
{
FGameplayTag OldTag = RequestGameplayTag(RemoveName, false);
if (OldTag.IsValid())
{
Container.RemoveTag(OldTag);
}
else
{
Container.RemoveTagByExplicitName(RemoveName);
}
}
// Add all tags from the TagsToAdd set
for (const FGameplayTag* AddTag : TagsToAdd)
{
check(AddTag);
Container.AddTag(*AddTag);
}
}
void UGameplayTagsManager::RedirectSingleGameplayTag(FGameplayTag& Tag, UProperty* SerializingProperty) const
{
const FName TagName = Tag.GetTagName();
const FGameplayTag* NewTag = TagRedirects.Find(TagName);
if (NewTag)
{
if (NewTag->IsValid())
{
Tag = *NewTag;
}
}
#if WITH_EDITOR
else if (TagName != NAME_None && SerializingProperty)
{
// Warn about invalid tags at load time in editor builds, too late to fix it in cooked builds
FGameplayTag OldTag = RequestGameplayTag(TagName, false);
if (!OldTag.IsValid() && ShouldWarnOnInvalidTags())
{
UE_LOG(LogGameplayTags, Warning, TEXT("Invalid GameplayTag %s found while loading property %s."), *TagName.ToString(), *GetPathNameSafe(SerializingProperty));
}
}
#endif
}
bool UGameplayTagsManager::ImportSingleGameplayTag(FGameplayTag& Tag, FName ImportedTagName) const
{
if (const FGameplayTag* RedirectedTag = TagRedirects.Find(ImportedTagName))
{
Tag = *RedirectedTag;
return true;
}
else if (ValidateTagCreation(ImportedTagName))
{
// The tag name is valid
Tag.TagName = ImportedTagName;
return true;
}
// No valid tag established in this attempt
Tag.TagName = NAME_None;
return false;
}
void UGameplayTagsManager::InitializeManager()
{
check(!SingletonManager);
SCOPE_LOG_TIME_IN_SECONDS(TEXT("UGameplayTagsManager::InitializeManager"), nullptr);
SingletonManager = NewObject<UGameplayTagsManager>(GetTransientPackage(), NAME_None);
SingletonManager->AddToRoot();
UGameplayTagsSettings* MutableDefault = nullptr;
{
SCOPE_LOG_GAMEPLAYTAGS(TEXT("UGameplayTagsManager::InitializeManager: Load settings"));
MutableDefault = GetMutableDefault<UGameplayTagsSettings>();
}
{
SCOPE_LOG_GAMEPLAYTAGS(TEXT("UGameplayTagsManager::InitializeManager: Load deprecated"));
TArray<FString> GameplayTagTablePaths;
GConfig->GetArray(TEXT("GameplayTags"), TEXT("+GameplayTagTableList"), GameplayTagTablePaths, GEngineIni);
// Report deprecation
if (GameplayTagTablePaths.Num() > 0)
{
UE_LOG(LogGameplayTags, Log, TEXT("GameplayTagTableList is in a deprecated location, open and save GameplayTag settings to fix"));
for (const FString& DataTable : GameplayTagTablePaths)
{
MutableDefault->GameplayTagTableList.AddUnique(DataTable);
}
}
}
SingletonManager->LoadGameplayTagTables(true);
SingletonManager->ConstructGameplayTagTree();
// Bind to end of engine init to be done adding native tags
FCoreDelegates::OnPostEngineInit.AddUObject(SingletonManager, &UGameplayTagsManager::DoneAddingNativeTags);
}
void UGameplayTagsManager::PopulateTreeFromDataTable(class UDataTable* InTable)
{
checkf(GameplayRootTag.IsValid(), TEXT("ConstructGameplayTagTree() must be called before PopulateTreeFromDataTable()"));
static const FString ContextString(TEXT("UGameplayTagsManager::PopulateTreeFromDataTable"));
TArray<FGameplayTagTableRow*> TagTableRows;
InTable->GetAllRows<FGameplayTagTableRow>(ContextString, TagTableRows);
FName SourceName = InTable->GetOutermost()->GetFName();
FGameplayTagSource* FoundSource = FindOrAddTagSource(SourceName, EGameplayTagSourceType::DataTable);
for (const FGameplayTagTableRow* TagRow : TagTableRows)
{
if (TagRow)
{
AddTagTableRow(*TagRow, SourceName);
}
}
}
void UGameplayTagsManager::AddTagTableRow(const FGameplayTagTableRow& TagRow, FName SourceName, bool bIsRestrictedTag)
{
TSharedPtr<FGameplayTagNode> CurNode = GameplayRootTag;
TArray<TSharedPtr<FGameplayTagNode>> AncestorNodes;
bool bAllowNonRestrictedChildren = true;
const FRestrictedGameplayTagTableRow* RestrictedTagRow = static_cast<const FRestrictedGameplayTagTableRow*>(&TagRow);
if (bIsRestrictedTag && RestrictedTagRow)
{
bAllowNonRestrictedChildren = RestrictedTagRow->bAllowNonRestrictedChildren;
}
// Split the tag text on the "." delimiter to establish tag depth and then insert each tag into the gameplay tag tree
// We try to avoid as many FString->FName conversions as possible as they are slow
FName OriginalTagName = TagRow.Tag;
FString FullTagString = OriginalTagName.ToString();
#if WITH_EDITOR
{
// In editor builds, validate string
// These must get fixed up cooking to work properly
FText ErrorText;
FString FixedString;
if (!IsValidGameplayTagString(FullTagString, &ErrorText, &FixedString))
{
if (FixedString.IsEmpty())
{
// No way to fix it
UE_LOG(LogGameplayTags, Error, TEXT("Invalid tag %s from source %s: %s!"), *FullTagString, *SourceName.ToString(), *ErrorText.ToString());
return;
}
else
{
UE_LOG(LogGameplayTags, Error, TEXT("Invalid tag %s from source %s: %s! Replacing with %s, you may need to modify InvalidTagCharacters"), *FullTagString, *SourceName.ToString(), *ErrorText.ToString(), *FixedString);
FullTagString = FixedString;
OriginalTagName = FName(*FixedString);
}
}
}
#endif
TArray<FString> SubTags;
FullTagString.ParseIntoArray(SubTags, TEXT("."), true);
// We will build this back up as we go
FullTagString.Reset();
int32 NumSubTags = SubTags.Num();
bool bHasSeenConflict = false;
for (int32 SubTagIdx = 0; SubTagIdx < NumSubTags; ++SubTagIdx)
{
bool bIsExplicitTag = (SubTagIdx == (NumSubTags - 1));
FName ShortTagName = *SubTags[SubTagIdx];
FName FullTagName;
if (bIsExplicitTag)
{
// We already know the final name
FullTagName = OriginalTagName;
}
else if (SubTagIdx == 0)
{
// Full tag is the same as short tag, and start building full tag string
FullTagName = ShortTagName;
FullTagString = SubTags[SubTagIdx];
}
else
{
// Add .Tag and use that as full tag
FullTagString += TEXT(".");
FullTagString += SubTags[SubTagIdx];
FullTagName = FName(*FullTagString);
}
TArray< TSharedPtr<FGameplayTagNode> >& ChildTags = CurNode.Get()->GetChildTagNodes();
int32 InsertionIdx = InsertTagIntoNodeArray(ShortTagName, FullTagName, CurNode, ChildTags, SourceName, TagRow.DevComment, bIsExplicitTag, bIsRestrictedTag, bAllowNonRestrictedChildren);
CurNode = ChildTags[InsertionIdx];
// Tag conflicts only affect the editor so we don't look for them in the game
#if WITH_EDITORONLY_DATA
if (bIsRestrictedTag)
{
CurNode->bAncestorHasConflict = bHasSeenConflict;
// If the sources don't match and the tag is explicit and we should've added the tag explicitly here, we have a conflict
if (CurNode->SourceName != SourceName && (CurNode->bIsExplicitTag && bIsExplicitTag))
{
// mark all ancestors as having a bad descendant
for (TSharedPtr<FGameplayTagNode> CurAncestorNode : AncestorNodes)
{
CurAncestorNode->bDescendantHasConflict = true;
}
// mark the current tag as having a conflict
CurNode->bNodeHasConflict = true;
// append source names
FString CombinedSources = CurNode->SourceName.ToString();
CombinedSources.Append(TEXT(" and "));
CombinedSources.Append(SourceName.ToString());
CurNode->SourceName = FName(*CombinedSources);
// mark all current descendants as having a bad ancestor
MarkChildrenOfNodeConflict(CurNode);
}
// mark any children we add later in this function as having a bad ancestor
if (CurNode->bNodeHasConflict)
{
bHasSeenConflict = true;
}
AncestorNodes.Add(CurNode);
}
#endif
}
}
void UGameplayTagsManager::MarkChildrenOfNodeConflict(TSharedPtr<FGameplayTagNode> CurNode)
{
#if WITH_EDITORONLY_DATA
TArray< TSharedPtr<FGameplayTagNode> >& ChildTags = CurNode.Get()->GetChildTagNodes();
for (TSharedPtr<FGameplayTagNode> ChildNode : ChildTags)
{
ChildNode->bAncestorHasConflict = true;
MarkChildrenOfNodeConflict(ChildNode);
}
#endif
}
UGameplayTagsManager::~UGameplayTagsManager()
{
DestroyGameplayTagTree();
SingletonManager = nullptr;
}
void UGameplayTagsManager::DestroyGameplayTagTree()
{
if (GameplayRootTag.IsValid())
{
GameplayRootTag->ResetNode();
GameplayRootTag.Reset();
GameplayTagNodeMap.Reset();
}
}
bool UGameplayTagsManager::IsNativelyAddedTag(FGameplayTag Tag) const
{
return NativeTagsToAdd.Contains(Tag.GetTagName());
}
int32 UGameplayTagsManager::InsertTagIntoNodeArray(FName Tag, FName FullTag, TSharedPtr<FGameplayTagNode> ParentNode, TArray< TSharedPtr<FGameplayTagNode> >& NodeArray, FName SourceName, const FString& DevComment, bool bIsExplicitTag, bool bIsRestrictedTag, bool bAllowNonRestrictedChildren)
{
int32 FoundNodeIdx = INDEX_NONE;
int32 WhereToInsert = INDEX_NONE;
// See if the tag is already in the array
for (int32 CurIdx = 0; CurIdx < NodeArray.Num(); ++CurIdx)
{
FGameplayTagNode* CurrNode = NodeArray[CurIdx].Get();
if (CurrNode)
{
FName SimpleTagName = CurrNode->GetSimpleTagName();
if (SimpleTagName == Tag)
{
FoundNodeIdx = CurIdx;
#if WITH_EDITORONLY_DATA
// If we are explicitly adding this tag then overwrite the existing children restrictions with whatever is in the ini
// If we restrict children in the input data, make sure we restrict them in the existing node. This applies to explicit and implicitly defined nodes
if (bAllowNonRestrictedChildren == false || bIsExplicitTag)
{
// check if the tag is explicitly being created in more than one place.
if (CurrNode->bIsExplicitTag && bIsExplicitTag)
{
// restricted tags always get added first
//
// There are two possibilities if we're adding a restricted tag.
// If the existing tag is non-restricted the restricted tag should take precedence. This may invalidate some child tags of the existing tag.
// If the existing tag is restricted we have a conflict. This is explicitly not allowed.
if (bIsRestrictedTag)
{
}
}
CurrNode->bAllowNonRestrictedChildren = bAllowNonRestrictedChildren;
CurrNode->bIsExplicitTag = CurrNode->bIsExplicitTag || bIsExplicitTag;
}
#endif
break;
}
else if (SimpleTagName > Tag && WhereToInsert == INDEX_NONE)
{
// Insert new node before this
WhereToInsert = CurIdx;
}
}
}
if (FoundNodeIdx == INDEX_NONE)
{
if (WhereToInsert == INDEX_NONE)
{
// Insert at end
WhereToInsert = NodeArray.Num();
}
// Don't add the root node as parent
TSharedPtr<FGameplayTagNode> TagNode = MakeShareable(new FGameplayTagNode(Tag, FullTag, ParentNode != GameplayRootTag ? ParentNode : nullptr, bIsExplicitTag, bIsRestrictedTag, bAllowNonRestrictedChildren));
// Add at the sorted location
FoundNodeIdx = NodeArray.Insert(TagNode, WhereToInsert);
FGameplayTag GameplayTag = TagNode->GetCompleteTag();
// These should always match
ensure(GameplayTag.GetTagName() == FullTag);
{
#if WITH_EDITOR
// This critical section is to handle an editor-only issue where tag requests come from another thread when async loading from a background thread in FGameplayTagContainer::Serialize.
// This function is not generically threadsafe.
FScopeLock Lock(&GameplayTagMapCritical);
#endif
GameplayTagNodeMap.Add(GameplayTag, TagNode);
}
}
#if WITH_EDITOR
static FName NativeSourceName = FGameplayTagSource::GetNativeName();
// Set/update editor only data
if (NodeArray[FoundNodeIdx]->SourceName.IsNone() && !SourceName.IsNone())
{
NodeArray[FoundNodeIdx]->SourceName = SourceName;
}
else if (SourceName == NativeSourceName)
{
// Native overrides other types
NodeArray[FoundNodeIdx]->SourceName = SourceName;
}
if (NodeArray[FoundNodeIdx]->DevComment.IsEmpty() && !DevComment.IsEmpty())
{
NodeArray[FoundNodeIdx]->DevComment = DevComment;
}
#endif
return FoundNodeIdx;
}
void UGameplayTagsManager::PrintReplicationIndices()
{
UE_LOG(LogGameplayTags, Display, TEXT("::PrintReplicationIndices (TOTAL %d"), GameplayTagNodeMap.Num());
for (auto It : GameplayTagNodeMap)
{
FGameplayTag Tag = It.Key;
TSharedPtr<FGameplayTagNode> Node = It.Value;
UE_LOG(LogGameplayTags, Display, TEXT("Tag %s NetIndex: %d"), *Tag.ToString(), Node->GetNetIndex());
}
}
#if !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
void UGameplayTagsManager::PrintReplicationFrequencyReport()
{
UE_LOG(LogGameplayTags, Warning, TEXT("================================="));
UE_LOG(LogGameplayTags, Warning, TEXT("Gameplay Tags Replication Report"));
UE_LOG(LogGameplayTags, Warning, TEXT("\nTags replicated solo:"));
ReplicationCountMap_SingleTags.ValueSort(TGreater<int32>());
for (auto& It : ReplicationCountMap_SingleTags)
{
UE_LOG(LogGameplayTags, Warning, TEXT("%s - %d"), *It.Key.ToString(), It.Value);
}
// ---------------------------------------
UE_LOG(LogGameplayTags, Warning, TEXT("\nTags replicated in containers:"));
ReplicationCountMap_Containers.ValueSort(TGreater<int32>());
for (auto& It : ReplicationCountMap_Containers)
{
UE_LOG(LogGameplayTags, Warning, TEXT("%s - %d"), *It.Key.ToString(), It.Value);
}
// ---------------------------------------
UE_LOG(LogGameplayTags, Warning, TEXT("\nAll Tags replicated:"));
ReplicationCountMap.ValueSort(TGreater<int32>());
for (auto& It : ReplicationCountMap)
{
UE_LOG(LogGameplayTags, Warning, TEXT("%s - %d"), *It.Key.ToString(), It.Value);
}
TMap<int32, int32> SavingsMap;
int32 BaselineCost = 0;
for (int32 Bits=1; Bits < NetIndexTrueBitNum; ++Bits)
{
int32 TotalSavings = 0;
BaselineCost = 0;
FGameplayTagNetIndex ExpectedNetIndex=0;
for (auto& It : ReplicationCountMap)
{
int32 ExpectedCostBits = 0;
bool FirstSeg = ExpectedNetIndex < FMath::Pow(2, Bits);
if (FirstSeg)
{
// This would fit in the first Bits segment
ExpectedCostBits = Bits+1;
}
else
{
// Would go in the second segment, so we pay the +1 cost
ExpectedCostBits = NetIndexTrueBitNum+1;
}
int32 Savings = (NetIndexTrueBitNum - ExpectedCostBits) * It.Value;
BaselineCost += NetIndexTrueBitNum * It.Value;
//UE_LOG(LogGameplayTags, Warning, TEXT("[Bits: %d] Tag %s would save %d bits"), Bits, *It.Key.ToString(), Savings);
ExpectedNetIndex++;
TotalSavings += Savings;
}
SavingsMap.FindOrAdd(Bits) = TotalSavings;
}
SavingsMap.ValueSort(TGreater<int32>());
int32 BestBits = 0;
for (auto& It : SavingsMap)
{
if (BestBits == 0)
{
BestBits = It.Key;
}
UE_LOG(LogGameplayTags, Warning, TEXT("%d bits would save %d (%.2f)"), It.Key, It.Value, (float)It.Value / (float)BaselineCost);
}
UE_LOG(LogGameplayTags, Warning, TEXT("\nSuggested config:"));
// Write out a nice copy pastable config
int32 Count=0;
for (auto& It : ReplicationCountMap)
{
UE_LOG(LogGameplayTags, Warning, TEXT("+CommonlyReplicatedTags=%s"), *It.Key.ToString());
if (Count == FMath::Pow(2, BestBits))
{
// Print a blank line out, indicating tags after this are not necessary but still may be useful if the user wants to manually edit the list.
UE_LOG(LogGameplayTags, Warning, TEXT(""));
}
if (Count++ >= FMath::Pow(2, BestBits+1))
{
break;
}
}
UE_LOG(LogGameplayTags, Warning, TEXT("NetIndexFirstBitSegment=%d"), BestBits);
UE_LOG(LogGameplayTags, Warning, TEXT("================================="));
}
void UGameplayTagsManager::NotifyTagReplicated(FGameplayTag Tag, bool WasInContainer)
{
ReplicationCountMap.FindOrAdd(Tag)++;
if (WasInContainer)
{
ReplicationCountMap_Containers.FindOrAdd(Tag)++;
}
else
{
ReplicationCountMap_SingleTags.FindOrAdd(Tag)++;
}
}
#endif
#if WITH_EDITOR
static void RecursiveRootTagSearch(const FString& InFilterString, const TArray<TSharedPtr<FGameplayTagNode> >& GameplayRootTags, TArray< TSharedPtr<FGameplayTagNode> >& OutTagArray)
{
FString CurrentFilter, RestOfFilter;
if (!InFilterString.Split(TEXT("."), &CurrentFilter, &RestOfFilter))
{
CurrentFilter = InFilterString;
}
for (int32 iTag = 0; iTag < GameplayRootTags.Num(); ++iTag)
{
FString RootTagName = GameplayRootTags[iTag].Get()->GetSimpleTagName().ToString();
if (RootTagName.Equals(CurrentFilter) == true)
{
if (RestOfFilter.IsEmpty())
{
// We've reached the end of the filter, add tags
OutTagArray.Add(GameplayRootTags[iTag]);
}
else
{
// Recurse into our children
RecursiveRootTagSearch(RestOfFilter, GameplayRootTags[iTag]->GetChildTagNodes(), OutTagArray);
}
}
}
}
void UGameplayTagsManager::GetFilteredGameplayRootTags(const FString& InFilterString, TArray< TSharedPtr<FGameplayTagNode> >& OutTagArray) const
{
TArray<FString> PreRemappedFilters;
TArray<FString> Filters;
TArray<TSharedPtr<FGameplayTagNode>>& GameplayRootTags = GameplayRootTag->GetChildTagNodes();
OutTagArray.Empty();
if( InFilterString.ParseIntoArray( PreRemappedFilters, TEXT( "," ), true ) > 0 )
{
const UGameplayTagsSettings* CDO = GetDefault<UGameplayTagsSettings>();
for (FString& Str : PreRemappedFilters)
{
bool Remapped = false;
for (const FGameplayTagCategoryRemap& RemapInfo : CDO->CategoryRemapping)
{
if (RemapInfo.BaseCategory == Str)
{
Remapped = true;
Filters.Append(RemapInfo.RemapCategories);
}
}
if (Remapped == false)
{
Filters.Add(Str);
}
}
// Check all filters in the list
for (int32 iFilter = 0; iFilter < Filters.Num(); ++iFilter)
{
RecursiveRootTagSearch(Filters[iFilter], GameplayRootTags, OutTagArray);
}
if (OutTagArray.Num() == 0)
{
// We had filters but nothing matched. Ignore the filters.
// This makes sense to do with engine level filters that games can optionally specify/override.
// We never want to impose tag structure on projects, but still give them the ability to do so for their project.
OutTagArray = GameplayRootTags;
}
}
else
{
// No Filters just return them all
OutTagArray = GameplayRootTags;
}
}
FString UGameplayTagsManager::GetCategoriesMetaFromField(UField* Field) const
{
check(Field);
if (Field->HasMetaData(NAME_Categories))
{
return Field->GetMetaData(NAME_Categories);
}
return FString();
}
FString UGameplayTagsManager::GetCategoriesMetaFromPropertyHandle(TSharedPtr<IPropertyHandle> PropertyHandle) const
{
// Global delegate override. Useful for parent structs that want to override tag categories based on their data (e.g. not static property meta data)
FString DelegateOverrideString;
OnGetCategoriesMetaFromPropertyHandle.Broadcast(PropertyHandle, DelegateOverrideString);
if (DelegateOverrideString.IsEmpty() == false)
{
return DelegateOverrideString;
}
FString Categories;
auto GetMetaData = ([&](UField* Field)
{
if (Field->HasMetaData(NAME_Categories))
{
Categories = Field->GetMetaData(NAME_Categories);
return true;
}
return false;
});
while(PropertyHandle.IsValid())
{
if (UProperty* Property = PropertyHandle->GetProperty())
{
/**
* UPROPERTY(EditAnywhere, BlueprintReadWrite, meta = (Categories="GameplayCue"))
* FGameplayTag GameplayCueTag;
*/
if (GetMetaData(Property))
{
break;
}
/**
* USTRUCT(meta=(Categories="EventKeyword"))
* struct FGameplayEventKeywordTag : public FGameplayTag
*/
if (UStructProperty* StructProperty = Cast<UStructProperty>(Property))
{
if (GetMetaData(StructProperty->Struct))
{
break;
}
}
/** TArray<FGameplayEventKeywordTag> QualifierTagTestList; */
if (UArrayProperty* ArrayProperty = Cast<UArrayProperty>(Property))
{
if (GetMetaData(ArrayProperty->Inner))
{
break;
}
}
}
PropertyHandle = PropertyHandle->GetParentHandle();
}
return Categories;
}
FString UGameplayTagsManager::GetCategoriesMetaFromFunction(UFunction* ThisFunction) const
{
FString FilterString;
if (ThisFunction->HasMetaData(NAME_GameplayTagFilter))
{
FilterString = ThisFunction->GetMetaData(NAME_GameplayTagFilter);
}
return FilterString;
}
void UGameplayTagsManager::GetAllTagsFromSource(FName TagSource, TArray< TSharedPtr<FGameplayTagNode> >& OutTagArray) const
{
for (const TPair<FGameplayTag, TSharedPtr<FGameplayTagNode>>& NodePair : GameplayTagNodeMap)
{
if (NodePair.Value->SourceName == TagSource)
{
OutTagArray.Add(NodePair.Value);
}
}
}
bool UGameplayTagsManager::IsDictionaryTag(FName TagName) const
{
TSharedPtr<FGameplayTagNode> Node = FindTagNode(TagName);
if (Node.IsValid() && Node->bIsExplicitTag)
{
return true;
}
return false;
}
bool UGameplayTagsManager::GetTagEditorData(FName TagName, FString& OutComment, FName& OutTagSource, bool& bOutIsTagExplicit, bool &bOutIsRestrictedTag, bool &bOutAllowNonRestrictedChildren) const
{
TSharedPtr<FGameplayTagNode> Node = FindTagNode(TagName);
if (Node.IsValid())
{
OutComment = Node->DevComment;
OutTagSource = Node->SourceName;
bOutIsTagExplicit = Node->bIsExplicitTag;
bOutIsRestrictedTag = Node->bIsRestrictedTag;
bOutAllowNonRestrictedChildren = Node->bAllowNonRestrictedChildren;
return true;
}
return false;
}
void UGameplayTagsManager::EditorRefreshGameplayTagTree()
{
DestroyGameplayTagTree();
LoadGameplayTagTables(false);
ConstructGameplayTagTree();
OnEditorRefreshGameplayTagTree.Broadcast();
}
FGameplayTagContainer UGameplayTagsManager::RequestGameplayTagChildrenInDictionary(const FGameplayTag& GameplayTag) const
{
// Note this purposefully does not include the passed in GameplayTag in the container.
FGameplayTagContainer TagContainer;
TSharedPtr<FGameplayTagNode> GameplayTagNode = FindTagNode(GameplayTag);
if (GameplayTagNode.IsValid())
{
AddChildrenTags(TagContainer, GameplayTagNode, true, true);
}
return TagContainer;
}
#if WITH_EDITORONLY_DATA
FGameplayTagContainer UGameplayTagsManager::RequestGameplayTagDirectDescendantsInDictionary(const FGameplayTag& GameplayTag, EGameplayTagSelectionType SelectionType) const
{
bool bIncludeRestrictedTags = (SelectionType == EGameplayTagSelectionType::RestrictedOnly || SelectionType == EGameplayTagSelectionType::All);
bool bIncludeNonRestrictedTags = (SelectionType == EGameplayTagSelectionType::NonRestrictedOnly || SelectionType == EGameplayTagSelectionType::All);
// Note this purposefully does not include the passed in GameplayTag in the container.
FGameplayTagContainer TagContainer;
TSharedPtr<FGameplayTagNode> GameplayTagNode = FindTagNode(GameplayTag);
if (GameplayTagNode.IsValid())
{
TArray< TSharedPtr<FGameplayTagNode> >& ChildrenNodes = GameplayTagNode->GetChildTagNodes();
int32 CurrArraySize = ChildrenNodes.Num();
for (int32 Idx = 0; Idx < CurrArraySize; ++Idx)
{
TSharedPtr<FGameplayTagNode> ChildNode = ChildrenNodes[Idx];
if (ChildNode.IsValid())
{
// if the tag isn't in the dictionary, add its children to the list
if (ChildNode->SourceName == NAME_None)
{
TArray< TSharedPtr<FGameplayTagNode> >& GrandChildrenNodes = ChildNode->GetChildTagNodes();
ChildrenNodes.Append(GrandChildrenNodes);
CurrArraySize = ChildrenNodes.Num();
}
else
{
// this tag is in the dictionary so add it to the list
if ((ChildNode->bIsRestrictedTag && bIncludeRestrictedTags) ||
(!ChildNode->bIsRestrictedTag && bIncludeNonRestrictedTags))
{
TagContainer.AddTag(ChildNode->GetCompleteTag());
}
}
}
}
}
return TagContainer;
}
#endif // WITH_EDITORONLY_DATA
void UGameplayTagsManager::NotifyGameplayTagDoubleClickedEditor(FString TagName)
{
FGameplayTag Tag = RequestGameplayTag(FName(*TagName), false);
if(Tag.IsValid())
{
FSimpleMulticastDelegate Delegate;
OnGatherGameplayTagDoubleClickedEditor.Broadcast(Tag, Delegate);
Delegate.Broadcast();
}
}
bool UGameplayTagsManager::ShowGameplayTagAsHyperLinkEditor(FString TagName)
{
FGameplayTag Tag = RequestGameplayTag(FName(*TagName), false);
if(Tag.IsValid())
{
FSimpleMulticastDelegate Delegate;
OnGatherGameplayTagDoubleClickedEditor.Broadcast(Tag, Delegate);
return Delegate.IsBound();
}
return false;
}
#endif // WITH_EDITOR
const FGameplayTagSource* UGameplayTagsManager::FindTagSource(FName TagSourceName) const
{
for (const FGameplayTagSource& TagSource : TagSources)
{
if (TagSource.SourceName == TagSourceName)
{
return &TagSource;
}
}
return nullptr;
}
FGameplayTagSource* UGameplayTagsManager::FindTagSource(FName TagSourceName)
{
for (FGameplayTagSource& TagSource : TagSources)
{
if (TagSource.SourceName == TagSourceName)
{
return &TagSource;
}
}
return nullptr;
}
void UGameplayTagsManager::FindTagSourcesWithType(EGameplayTagSourceType TagSourceType, TArray<const FGameplayTagSource*>& OutArray) const
{
for (const FGameplayTagSource& TagSource : TagSources)
{
if (TagSource.SourceType == TagSourceType)
{
OutArray.Add(&TagSource);
}
}
}
FGameplayTagSource* UGameplayTagsManager::FindOrAddTagSource(FName TagSourceName, EGameplayTagSourceType SourceType)
{
FGameplayTagSource* FoundSource = FindTagSource(TagSourceName);
if (FoundSource)
{
if (SourceType == FoundSource->SourceType)
{
return FoundSource;
}
return nullptr;
}
// Need to make a new one
FGameplayTagSource* NewSource = new(TagSources) FGameplayTagSource(TagSourceName, SourceType);
if (SourceType == EGameplayTagSourceType::DefaultTagList)
{
NewSource->SourceTagList = GetMutableDefault<UGameplayTagsSettings>();
}
else if (SourceType == EGameplayTagSourceType::TagList)
{
NewSource->SourceTagList = NewObject<UGameplayTagsList>(this, TagSourceName, RF_Transient);
NewSource->SourceTagList->ConfigFileName = FString::Printf(TEXT("%sTags/%s"), *FPaths::SourceConfigDir(), *TagSourceName.ToString());
}
else if (SourceType == EGameplayTagSourceType::RestrictedTagList)
{
NewSource->SourceRestrictedTagList = NewObject<URestrictedGameplayTagsList>(this, TagSourceName, RF_Transient);
NewSource->SourceRestrictedTagList->ConfigFileName = FString::Printf(TEXT("%sTags/%s"), *FPaths::SourceConfigDir(), *TagSourceName.ToString());
}
return NewSource;
}
DECLARE_CYCLE_STAT(TEXT("UGameplayTagsManager::RequestGameplayTag"), STAT_UGameplayTagsManager_RequestGameplayTag, STATGROUP_GameplayTags);
void UGameplayTagsManager::RequestGameplayTagContainer(const TArray<FString>& TagStrings, FGameplayTagContainer& OutTagsContainer, bool bErrorIfNotFound/*=true*/) const
{
for (const FString& CurrentTagString : TagStrings)
{
FGameplayTag RequestedTag = RequestGameplayTag(FName(*(CurrentTagString.TrimStartAndEnd())), bErrorIfNotFound);
if (RequestedTag.IsValid())
{
OutTagsContainer.AddTag(RequestedTag);
}
}
}
FGameplayTag UGameplayTagsManager::RequestGameplayTag(FName TagName, bool ErrorIfNotFound) const
{
SCOPE_CYCLE_COUNTER(STAT_UGameplayTagsManager_RequestGameplayTag);
#if WITH_EDITOR
// This critical section is to handle and editor-only issue where tag requests come from another thread when async loading from a background thread in FGameplayTagContainer::Serialize.
// This function is not generically threadsafe.
FScopeLock Lock(&GameplayTagMapCritical);
#endif
FGameplayTag PossibleTag(TagName);
if (GameplayTagNodeMap.Contains(PossibleTag))
{
return PossibleTag;
}
else if (ErrorIfNotFound)
{
static TSet<FName> MissingTagName;
if (!MissingTagName.Contains(TagName))
{
ensureAlwaysMsgf(false, TEXT("Requested Tag %s was not found. Check tag data table."), *TagName.ToString());
MissingTagName.Add(TagName);
}
}
return FGameplayTag();
}
bool UGameplayTagsManager::IsValidGameplayTagString(const FString& TagString, FText* OutError, FString* OutFixedString)
{
bool bIsValid = true;
FString FixedString = TagString;
FText ErrorText;
if (FixedString.IsEmpty())
{
ErrorText = LOCTEXT("EmptyStringError", "Tag is empty");
bIsValid = false;
}
while (FixedString.StartsWith(TEXT("."), ESearchCase::CaseSensitive))
{
ErrorText = LOCTEXT("StartWithPeriod", "Tag starts with .");
FixedString.RemoveAt(0);
bIsValid = false;
}
while (FixedString.EndsWith(TEXT("."), ESearchCase::CaseSensitive))
{
ErrorText = LOCTEXT("EndWithPeriod", "Tag ends with .");
FixedString.RemoveAt(FixedString.Len() - 1);
bIsValid = false;
}
while (FixedString.StartsWith(TEXT(" "), ESearchCase::CaseSensitive))
{
ErrorText = LOCTEXT("StartWithSpace", "Tag starts with space");
FixedString.RemoveAt(0);
bIsValid = false;
}
while (FixedString.EndsWith(TEXT(" "), ESearchCase::CaseSensitive))
{
ErrorText = LOCTEXT("EndWithSpace", "Tag ends with space");
FixedString.RemoveAt(FixedString.Len() - 1);
bIsValid = false;
}
FText TagContext = LOCTEXT("GameplayTagContext", "Tag");
if (!FName::IsValidXName(TagString, InvalidTagCharacters, &ErrorText, &TagContext))
{
for (TCHAR& TestChar : FixedString)
{
for (TCHAR BadChar : InvalidTagCharacters)
{
if (TestChar == BadChar)
{
TestChar = TEXT('_');
}
}
}
bIsValid = false;
}
if (OutError)
{
*OutError = ErrorText;
}
if (OutFixedString)
{
*OutFixedString = FixedString;
}
return bIsValid;
}
FGameplayTag UGameplayTagsManager::FindGameplayTagFromPartialString_Slow(FString PartialString) const
{
#if WITH_EDITOR
// This critical section is to handle and editor-only issue where tag requests come from another thread when async loading from a background thread in FGameplayTagContainer::Serialize.
// This function is not generically threadsafe.
FScopeLock Lock(&GameplayTagMapCritical);
#endif
// Exact match first
FGameplayTag PossibleTag(*PartialString);
if (GameplayTagNodeMap.Contains(PossibleTag))
{
return PossibleTag;
}
// Find shortest tag name that contains the match string
FGameplayTag FoundTag;
FGameplayTagContainer AllTags;
RequestAllGameplayTags(AllTags, false);
int32 BestMatchLength = MAX_int32;
for (FGameplayTag MatchTag : AllTags)
{
FString Str = MatchTag.ToString();
if (Str.Contains(PartialString))
{
if (Str.Len() < BestMatchLength)
{
FoundTag = MatchTag;
BestMatchLength = Str.Len();
}
}
}
return FoundTag;
}
FGameplayTag UGameplayTagsManager::AddNativeGameplayTag(FName TagName, const FString& TagDevComment)
{
if (TagName.IsNone())
{
return FGameplayTag();
}
// Unsafe to call after done adding
if (ensure(!bDoneAddingNativeTags))
{
FGameplayTag NewTag = FGameplayTag(TagName);
if (!NativeTagsToAdd.Contains(TagName))
{
NativeTagsToAdd.Add(TagName);
}
AddTagTableRow(FGameplayTagTableRow(TagName, TagDevComment), FGameplayTagSource::GetNativeName());
return NewTag;
}
return FGameplayTag();
}
void UGameplayTagsManager::CallOrRegister_OnDoneAddingNativeTagsDelegate(FSimpleMulticastDelegate::FDelegate Delegate)
{
if (bDoneAddingNativeTags)
{
Delegate.Execute();
}
else
{
bool bAlreadyBound = Delegate.GetUObject() != nullptr ? OnDoneAddingNativeTagsDelegate().IsBoundToObject(Delegate.GetUObject()) : false;
if (!bAlreadyBound)
{
OnDoneAddingNativeTagsDelegate().Add(Delegate);
}
}
}
FSimpleMulticastDelegate& UGameplayTagsManager::OnDoneAddingNativeTagsDelegate()
{
static FSimpleMulticastDelegate Delegate;
return Delegate;
}
FSimpleMulticastDelegate& UGameplayTagsManager::OnLastChanceToAddNativeTags()
{
static FSimpleMulticastDelegate Delegate;
return Delegate;
}
void UGameplayTagsManager::DoneAddingNativeTags()
{
// Safe to call multiple times, only works the first time, must be called after the engine
// is initialized (DoneAddingNativeTags is bound to PostEngineInit to cover anything that's skipped).
if (GEngine && !bDoneAddingNativeTags)
{
UE_CLOG(GAMEPLAYTAGS_VERBOSE, LogGameplayTags, Display, TEXT("UGameplayTagsManager::DoneAddingNativeTags. DelegateIsBound: %d"), (int32)OnLastChanceToAddNativeTags().IsBound());
OnLastChanceToAddNativeTags().Broadcast();
bDoneAddingNativeTags = true;
// We may add native tags that are needed for redirectors, so reconstruct the GameplayTag tree
DestroyGameplayTagTree();
ConstructGameplayTagTree();
OnDoneAddingNativeTagsDelegate().Broadcast();
}
}
FGameplayTagContainer UGameplayTagsManager::RequestGameplayTagParents(const FGameplayTag& GameplayTag) const
{
const FGameplayTagContainer* ParentTags = GetSingleTagContainer(GameplayTag);
if (ParentTags)
{
return ParentTags->GetGameplayTagParents();
}
return FGameplayTagContainer();
}
void UGameplayTagsManager::RequestAllGameplayTags(FGameplayTagContainer& TagContainer, bool OnlyIncludeDictionaryTags) const
{
TArray<TSharedPtr<FGameplayTagNode>> ValueArray;
GameplayTagNodeMap.GenerateValueArray(ValueArray);
for (const TSharedPtr<FGameplayTagNode>& TagNode : ValueArray)
{
#if WITH_EDITOR
bool DictTag = IsDictionaryTag(TagNode->GetCompleteTagName());
#else
bool DictTag = false;
#endif
if (!OnlyIncludeDictionaryTags || DictTag)
{
const FGameplayTag* Tag = GameplayTagNodeMap.FindKey(TagNode);
check(Tag);
TagContainer.AddTagFast(*Tag);
}
}
}
FGameplayTagContainer UGameplayTagsManager::RequestGameplayTagChildren(const FGameplayTag& GameplayTag) const
{
FGameplayTagContainer TagContainer;
// Note this purposefully does not include the passed in GameplayTag in the container.
TSharedPtr<FGameplayTagNode> GameplayTagNode = FindTagNode(GameplayTag);
if (GameplayTagNode.IsValid())
{
AddChildrenTags(TagContainer, GameplayTagNode, true, false);
}
return TagContainer;
}
FGameplayTag UGameplayTagsManager::RequestGameplayTagDirectParent(const FGameplayTag& GameplayTag) const
{
TSharedPtr<FGameplayTagNode> GameplayTagNode = FindTagNode(GameplayTag);
if (GameplayTagNode.IsValid())
{
TSharedPtr<FGameplayTagNode> Parent = GameplayTagNode->GetParentTagNode();
if (Parent.IsValid())
{
return Parent->GetCompleteTag();
}
}
return FGameplayTag();
}
void UGameplayTagsManager::AddChildrenTags(FGameplayTagContainer& TagContainer, TSharedPtr<FGameplayTagNode> GameplayTagNode, bool RecurseAll, bool OnlyIncludeDictionaryTags) const
{
if (GameplayTagNode.IsValid())
{
TArray< TSharedPtr<FGameplayTagNode> >& ChildrenNodes = GameplayTagNode->GetChildTagNodes();
for (TSharedPtr<FGameplayTagNode> ChildNode : ChildrenNodes)
{
if (ChildNode.IsValid())
{
bool bShouldInclude = true;
#if WITH_EDITORONLY_DATA
if (OnlyIncludeDictionaryTags && ChildNode->SourceName == NAME_None)
{
// Only have info to do this in editor builds
bShouldInclude = false;
}
#endif
if (bShouldInclude)
{
TagContainer.AddTag(ChildNode->GetCompleteTag());
}
if (RecurseAll)
{
AddChildrenTags(TagContainer, ChildNode, true, OnlyIncludeDictionaryTags);
}
}
}
}
}
void UGameplayTagsManager::SplitGameplayTagFName(const FGameplayTag& Tag, TArray<FName>& OutNames) const
{
TSharedPtr<FGameplayTagNode> CurNode = FindTagNode(Tag);
while (CurNode.IsValid())
{
OutNames.Insert(CurNode->GetSimpleTagName(), 0);
CurNode = CurNode->GetParentTagNode();
}
}
int32 UGameplayTagsManager::GameplayTagsMatchDepth(const FGameplayTag& GameplayTagOne, const FGameplayTag& GameplayTagTwo) const
{
TSet<FName> Tags1;
TSet<FName> Tags2;
TSharedPtr<FGameplayTagNode> TagNode = FindTagNode(GameplayTagOne);
if (TagNode.IsValid())
{
GetAllParentNodeNames(Tags1, TagNode);
}
TagNode = FindTagNode(GameplayTagTwo);
if (TagNode.IsValid())
{
GetAllParentNodeNames(Tags2, TagNode);
}
return Tags1.Intersect(Tags2).Num();
}
DECLARE_CYCLE_STAT(TEXT("UGameplayTagsManager::GetAllParentNodeNames"), STAT_UGameplayTagsManager_GetAllParentNodeNames, STATGROUP_GameplayTags);
void UGameplayTagsManager::GetAllParentNodeNames(TSet<FName>& NamesList, TSharedPtr<FGameplayTagNode> GameplayTag) const
{
SCOPE_CYCLE_COUNTER(STAT_UGameplayTagsManager_GetAllParentNodeNames);
NamesList.Add(GameplayTag->GetCompleteTagName());
TSharedPtr<FGameplayTagNode> Parent = GameplayTag->GetParentTagNode();
if (Parent.IsValid())
{
GetAllParentNodeNames(NamesList, Parent);
}
}
DECLARE_CYCLE_STAT(TEXT("UGameplayTagsManager::ValidateTagCreation"), STAT_UGameplayTagsManager_ValidateTagCreation, STATGROUP_GameplayTags);
bool UGameplayTagsManager::ValidateTagCreation(FName TagName) const
{
SCOPE_CYCLE_COUNTER(STAT_UGameplayTagsManager_ValidateTagCreation);
return FindTagNode(TagName).IsValid();
}
FGameplayTagTableRow::FGameplayTagTableRow(FGameplayTagTableRow const& Other)
{
*this = Other;
}
FGameplayTagTableRow& FGameplayTagTableRow::operator=(FGameplayTagTableRow const& Other)
{
// Guard against self-assignment
if (this == &Other)
{
return *this;
}
Tag = Other.Tag;
DevComment = Other.DevComment;
return *this;
}
bool FGameplayTagTableRow::operator==(FGameplayTagTableRow const& Other) const
{
return (Tag == Other.Tag);
}
bool FGameplayTagTableRow::operator!=(FGameplayTagTableRow const& Other) const
{
return (Tag != Other.Tag);
}
bool FGameplayTagTableRow::operator<(FGameplayTagTableRow const& Other) const
{
return (Tag < Other.Tag);
}
FRestrictedGameplayTagTableRow::FRestrictedGameplayTagTableRow(FRestrictedGameplayTagTableRow const& Other)
{
*this = Other;
}
FRestrictedGameplayTagTableRow& FRestrictedGameplayTagTableRow::operator=(FRestrictedGameplayTagTableRow const& Other)
{
// Guard against self-assignment
if (this == &Other)
{
return *this;
}
Super::operator=(Other);
bAllowNonRestrictedChildren = Other.bAllowNonRestrictedChildren;
return *this;
}
bool FRestrictedGameplayTagTableRow::operator==(FRestrictedGameplayTagTableRow const& Other) const
{
if (bAllowNonRestrictedChildren != Other.bAllowNonRestrictedChildren)
{
return false;
}
if (Tag != Other.Tag)
{
return false;
}
return true;
}
bool FRestrictedGameplayTagTableRow::operator!=(FRestrictedGameplayTagTableRow const& Other) const
{
if (bAllowNonRestrictedChildren == Other.bAllowNonRestrictedChildren)
{
return false;
}
if (Tag == Other.Tag)
{
return false;
}
return true;
}
FGameplayTagNode::FGameplayTagNode(FName InTag, FName InFullTag, TSharedPtr<FGameplayTagNode> InParentNode, bool InIsExplicitTag, bool InIsRestrictedTag, bool InAllowNonRestrictedChildren)
: Tag(InTag)
, ParentNode(InParentNode)
, NetIndex(INVALID_TAGNETINDEX)
{
// Manually construct the tag container as we want to bypass the safety checks
CompleteTagWithParents.GameplayTags.Add(FGameplayTag(InFullTag));
FGameplayTagNode* RawParentNode = ParentNode.Get();
if (RawParentNode && RawParentNode->GetSimpleTagName() != NAME_None)
{
// Our parent nodes are already constructed, and must have it's tag in GameplayTags[0]
const FGameplayTagContainer ParentContainer = RawParentNode->GetSingleTagContainer();
CompleteTagWithParents.ParentTags.Add(ParentContainer.GameplayTags[0]);
CompleteTagWithParents.ParentTags.Append(ParentContainer.ParentTags);
}
#if WITH_EDITORONLY_DATA
bIsExplicitTag = InIsExplicitTag;
bIsRestrictedTag = InIsRestrictedTag;
bAllowNonRestrictedChildren = InAllowNonRestrictedChildren;
bDescendantHasConflict = false;
bNodeHasConflict = false;
bAncestorHasConflict = false;
#endif
}
void FGameplayTagNode::ResetNode()
{
Tag = NAME_None;
CompleteTagWithParents.Reset();
NetIndex = INVALID_TAGNETINDEX;
for (int32 ChildIdx = 0; ChildIdx < ChildTags.Num(); ++ChildIdx)
{
ChildTags[ChildIdx]->ResetNode();
}
ChildTags.Empty();
ParentNode.Reset();
#if WITH_EDITORONLY_DATA
SourceName = NAME_None;
DevComment = "";
bIsExplicitTag = false;
bIsRestrictedTag = false;
bAllowNonRestrictedChildren = false;
bDescendantHasConflict = false;
bNodeHasConflict = false;
bAncestorHasConflict = false;
#endif
}
#undef LOCTEXT_NAMESPACE
| 0 | 0.881287 | 1 | 0.881287 | game-dev | MEDIA | 0.819796 | game-dev | 0.921715 | 1 | 0.921715 |
ProjectIgnis/CardScripts | 3,912 | official/c41443249.lua | --R-ACEプリベンター
--Rescue-ACE Preventer
--scripted by fiftyfour
local s,id=GetID()
function s.initial_effect(c)
--Special Summon this card from your hand
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_HAND)
e1:SetCountLimit(1,id)
e1:SetCost(s.selfspcost)
e1:SetTarget(s.selfsptg)
e1:SetOperation(s.selfspop)
c:RegisterEffect(e1)
--Flip 1 opponent's Effect Monster face-down
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(id,1))
e2:SetCategory(CATEGORY_POSITION)
e2:SetType(EFFECT_TYPE_QUICK_O)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetCode(EVENT_FREE_CHAIN)
e2:SetRange(LOCATION_MZONE)
e2:SetHintTiming(0,TIMINGS_CHECK_MONSTER_E)
e2:SetCountLimit(1,{id,1})
e2:SetCondition(s.setcon)
e2:SetTarget(s.settg)
e2:SetOperation(s.setop)
c:RegisterEffect(e2)
--Special Summon 1 banished non-Level 8 "Rescue-ACE" monster
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(id,2))
e3:SetCategory(CATEGORY_SPECIAL_SUMMON)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e3:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DELAY)
e3:SetCode(EVENT_TO_GRAVE)
e3:SetCountLimit(1,{id,2})
e3:SetTarget(s.sptg)
e3:SetOperation(s.spop)
c:RegisterEffect(e3)
end
s.listed_series={SET_RESCUE_ACE}
function s.rmcfilter(c,tp)
return c:IsSetCard(SET_RESCUE_ACE) and c:IsAbleToRemoveAsCost() and Duel.GetMZoneCount(tp,c)>0
and aux.SpElimFilter(c,true)
end
function s.selfspcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(s.rmcfilter,tp,LOCATION_MZONE|LOCATION_GRAVE,0,1,nil,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,s.rmcfilter,tp,LOCATION_MZONE|LOCATION_GRAVE,0,1,1,nil,tp)
Duel.Remove(g,POS_FACEUP,REASON_COST)
end
function s.selfsptg(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
if chk==0 then return c:IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,c,1,tp,0)
end
function s.selfspop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)
end
end
function s.setcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsExistingMatchingCard(aux.FaceupFilter(Card.IsSetCard,SET_RESCUE_ACE),tp,LOCATION_MZONE,0,1,e:GetHandler())
end
function s.setfilter(c)
return c:IsFaceup() and c:IsCanTurnSet() and c:IsType(TYPE_EFFECT)
end
function s.settg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(1-tp) and chkc:IsLocation(LOCATION_MZONE) and s.setfilter(chkc) end
if chk==0 then return Duel.IsExistingTarget(s.setfilter,tp,0,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
local g=Duel.SelectTarget(tp,s.setfilter,tp,0,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_POSITION,g,1,0,0)
end
function s.setop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and tc:IsFaceup() then
Duel.ChangePosition(tc,POS_FACEDOWN_DEFENSE)
end
end
function s.spfilter(c,e,tp)
return c:IsFaceup() and c:IsSetCard(SET_RESCUE_ACE) and not c:IsLevel(8) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function s.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_REMOVED) 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_REMOVED,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,s.spfilter,tp,LOCATION_REMOVED,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,tp,LOCATION_REMOVED)
end
function s.spop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)
end
end | 0 | 0.953932 | 1 | 0.953932 | game-dev | MEDIA | 0.985821 | game-dev | 0.941343 | 1 | 0.941343 |
Solarint/SAIN | 8,591 | Classes/Player/Equipment/WeaponInfo.cs | using EFT;
using EFT.InventoryLogic;
using SAIN.Helpers;
using SAIN.Plugin;
using SAIN.Preset;
using System;
using System.Collections.Generic;
using UnityEngine;
namespace SAIN.SAINComponent.Classes.Info
{
public class WeaponInfo
{
public WeaponInfo(Weapon weapon)
{
Weapon = weapon;
WeaponClass = TryGetWeaponClass(weapon);
AmmoCaliber = TryGetAmmoCaliber(weapon);
updateSettings(SAINPresetClass.Instance);
PresetHandler.OnPresetUpdated += updateSettings;
}
public EWeaponClass WeaponClass { get; private set; }
public ECaliber AmmoCaliber { get; private set; }
public float CalculatedAudibleRange { get; private set; }
public AISoundType AISoundType => HasSuppressor ? AISoundType.silencedGun : AISoundType.gun;
public SAINSoundType SoundType => HasSuppressor ? SAINSoundType.SuppressedShot : SAINSoundType.Shot;
public bool HasRedDot => RedDot != null;
public bool HasOptic => Optic != null;
public bool HasSuppressor { get; private set; }
public float BaseAudibleRange { get; private set; } = 150f;
public float MuzzleLoudness { get; private set; }
public bool Subsonic => Weapon != null && BulletSpeed < SuperSonicSpeed;
public Mod Suppressor { get; private set; }
public Mod RedDot { get; private set; }
public Mod Optic { get; private set; }
public float BulletSpeed { get; private set; } = 600f;
public float EngagementDistance { get; private set; } = 150f;
public Weapon Weapon { get; private set; }
public float Durability => Weapon.Repairable.Durability / (float)Weapon.Repairable.TemplateDurability;
private void updateSettings(SAINPresetClass preset)
{
if (preset.GlobalSettings.Shoot.EngagementDistance.TryGetValue(WeaponClass, out float distance))
{
EngagementDistance = distance;
}
if (preset.GlobalSettings.Hearing.HearingDistances.TryGetValue(AmmoCaliber, out float range))
{
BaseAudibleRange = range;
}
}
public void Update(Player Player)
{
if (Weapon != null)
{
UpdateWeaponData(Player, Weapon.Mods);
}
}
private void UpdateWeaponData(Player Player, IEnumerable<Mod> mods)
{
Suppressor = FindModType(mods, EModType.Suppressor);
RedDot = FindModType(mods, EModType.RedDot);
Optic = FindModType(mods, EModType.Optic);
MuzzleLoudness = Suppressor != null ? Suppressor.Template.Loudness : 0f;
BulletSpeed = Weapon.CurrentAmmoTemplate.InitialSpeed * Weapon.SpeedFactor;
CalculatedAudibleRange = BaseAudibleRange + MuzzleLoudness;
if (Suppressor != null || (Player.HandsController is Player.FirearmController firearmController && firearmController.IsSilenced))
{
CalculatedAudibleRange *= SuppressorModifier(BulletSpeed);
HasSuppressor = true;
}
else
{
HasSuppressor = false;
}
//Log();
}
public void WeaponEquiped(Player player)
{
Update(player);
}
public void WeaponModified(Player player)
{
Update(player);
}
public void Dispose()
{
PresetHandler.OnPresetUpdated -= updateSettings;
}
private static Mod FindModType(IEnumerable<Mod> mods, EModType ModType)
{
if (mods != null)
{
foreach (Mod mod in mods)
{
if (CheckItemType(mod.GetType()) == ModType)
return mod;
Slot[] Slots = mod.Slots;
foreach (Slot slot in Slots)
if (slot.ContainedItem is Mod ContainedMod && CheckItemType(ContainedMod.GetType()) == ModType)
return ContainedMod;
}
}
return null;
}
private static float SuppressorModifier(float bulletspeed)
{
if (bulletspeed < SuperSonicSpeed)
{
return SAINPlugin.LoadedPreset.GlobalSettings.Hearing.SubsonicModifier;
}
return SAINPlugin.LoadedPreset.GlobalSettings.Hearing.SuppressorModifier;
}
private static EModType CheckItemType(Type type)
{
if (CheckTemplateType(type, SuppressorTypeId))
{
return EModType.Suppressor;
}
for (int i = 0; i < RedDotTypes.Length; i++)
{
if (CheckTemplateType(type, RedDotTypes[i]))
{
return EModType.RedDot;
}
}
for (int i = 0; i < OpticTypes.Length; i++)
{
if (CheckTemplateType(type, OpticTypes[i]))
{
return EModType.Optic;
}
}
return EModType.None;
}
private static bool CheckTemplateType(Type modType, string id)
{
if (TemplateIdToObjectMappingsClass.TypeTable.TryGetValue(id, out Type result) && result == modType)
{
return true;
}
if (TemplateIdToObjectMappingsClass.TemplateTypeTable.TryGetValue(id, out result) && result == modType)
{
return true;
}
return false;
}
private static EWeaponClass TryGetWeaponClass(Weapon weapon)
{
EWeaponClass WeaponClass = EnumValues.TryParse<EWeaponClass>(weapon.Template.weapClass);
if (WeaponClass == default)
{
WeaponClass = EnumValues.TryParse<EWeaponClass>(weapon.WeapClass);
}
return WeaponClass;
}
private static ECaliber TryGetAmmoCaliber(Weapon weapon)
{
ECaliber caliber = EnumValues.TryParse<ECaliber>(weapon.Template.ammoCaliber);
if (caliber == default)
{
caliber = EnumValues.TryParse<ECaliber>(weapon.AmmoCaliber);
}
return caliber;
}
private void Log()
{
Logger.LogDebug(
$"Found Weapon Info: " +
$"Weapon: [{Weapon.ShortName}] " +
$"Weapon Class: [{WeaponClass}] " +
$"Ammo Caliber: [{AmmoCaliber}] " +
$"Calculated Audible Range: [{CalculatedAudibleRange}] " +
$"Base Audible Range: [{BaseAudibleRange}] " +
$"Muzzle Loudness: [{MuzzleLoudness}] " +
$"Speed Factor: [{Weapon.SpeedFactor}] " +
$"Subsonic: [{Subsonic}] " +
$"Has Red Dot? [{HasRedDot}] " +
$"Has Optic? [{HasOptic}] " +
$"Has Suppressor? [{HasSuppressor}]");
}
private const float SuperSonicSpeed = 343.2f;
//private static readonly string FlashHiderTypeId = "550aa4bf4bdc2dd6348b456b";
//private static readonly string MuzzleTypeId = "5448fe394bdc2d0d028b456c";
private static readonly string SuppressorTypeId = "550aa4cd4bdc2dd8348b456c";
private static readonly string CollimatorTypeId = "55818ad54bdc2ddc698b4569";
private static readonly string CompactCollimatorTypeId = "55818acf4bdc2dde698b456b";
private static readonly string AssaultScopeTypeId = "55818add4bdc2d5b648b456f";
private static readonly string OpticScopeTypeId = "55818ae44bdc2dde698b456c";
private static readonly string SpecialScopeTypeId = "55818aeb4bdc2ddc698b456a";
private static readonly string[] OpticTypes = { AssaultScopeTypeId, OpticScopeTypeId, SpecialScopeTypeId };
private static readonly string[] RedDotTypes = { CollimatorTypeId, CompactCollimatorTypeId };
}
public enum EModType
{
None,
Suppressor,
RedDot,
Optic,
}
public class OpticAIConfig
{
public string Name;
public string TypeId;
public float FarDistanceScaleStart;
public float FarDistanceScaleEnd;
public float FarMultiplier;
public float CloseDistanceScaleStart;
public float CloseDistanceScaleEnd;
public float CloseMultiplier;
}
} | 0 | 0.850068 | 1 | 0.850068 | game-dev | MEDIA | 0.961455 | game-dev | 0.757181 | 1 | 0.757181 |
ggnkua/Atari_ST_Sources | 66,935 | C/Christophe Fontanel/ReDMCSB_Release2/OBJECT/ENGINE/FULL/DM13aFR/GROUP1.S | BSS SEG "bss"
G375_ps_Ac:/* global */
.WORD #4
G376_ui_Ma:/* global */
.WORD #2
CODE SEG "init!"
MOVE #0,G377_ui_Cu(A4)
BSS SEG "bss"
G377_ui_Cu:/* global */
.WORD #2
G378_i_Cur:/* global */
.WORD #2
G379_i_Cur:/* global */
.WORD #2
G380_T_Cur:/* global */
.WORD #2
G381_ui_Cu:/* global */
.WORD #2
G382_i_Cur:/* global */
.WORD #2
G383_i_Cur:/* global */
.WORD #2
G384_ac_Gr:/* global */
.WORD #4
G385_ac_Fl:/* global */
.WORD #4
G386_ui_Fl:/* global */
.WORD #2
G387_B_Gro:/* global */
.WORD #2
G388_T_Gro:/* global */
.WORD #2
G389_B_Gro:/* global */
.WORD #2
G390_B_Gro:/* global */
.WORD #2
G391_i_Dro:/* global */
.WORD #2
G392_auc_D:/* global */
.WORD #4
G393_ac_Co:/* global */
.WORD #68
CODE SEG "dunman"
F175_gzzz_:/* global */
LINK A6,L$0
MOVE D7,-(A7)
MOVE 10(A6),-(A7)
MOVE 8(A6),-(A7)
JSR F161_szzz_(PC)
ADDQ.L #4,A7
MOVE D0,D7
BRA.S L2
L3:
L4:
MOVE D7,-(A7)
JSR F159_rzzz_(PC)
ADDQ.L #2,A7
MOVE D0,D7
L2:
CMPI #-2,D7
BEQ.S L6
MOVE D7,D0
AND #15360,D0
LSR #2,D0
LSR #8,D0
CMPI #4,D0
BNE.S L3
L6:
L5:
MOVE D7,D0
L1:
MOVE (A7)+,D7
UNLK A6
RTS
L$0: .EQU #0
F176_avzz_:/* global */
LINK A6,L$7
MOVEM.L A3/D7-D4,-(A7)
MOVE.L 8(A6),A3
MOVE 12(A6),D7
MOVE G272_i_Cur(A4),-(A7)
MOVE.L A3,-(A7)
JSR F145_rzzz_(PC)
ADDQ.L #6,A7
MOVE.B D0,D6
AND #255,D0
CMP #255,D0
BNE.S L9
MOVE #1,D0
BRA L8(PC)
L9:
MOVE 14(A3),D5
AND #96,D5
LSR #5,D5
MOVE.B 4(A3),D0
AND #255,D0
MULS #26,D0
LEA G243_as_Gr+2(A4),A0
ADDA D0,A0
MOVE (A0),D0
AND #3,D0
CMPI #1,D0
BNE.S L10
MOVE G272_i_Cur(A4),-(A7)
MOVE.L A3,-(A7)
JSR F147_aawz_(PC)
ADDQ.L #6,A7
AND #1,D0
MOVE D7,D1
AND #1,D1
CMP D1,D0
BNE.S L11
MOVE D7,D0
SUBQ #1,D0
AND #3,D0
MOVE D0,D7
L11:
L12:
MOVE.B D6,D0
MOVE.B D5,D1
AND #255,D1
ASL #1,D1
AND #255,D0
ASR D1,D0
AND #3,D0
MOVE.B D0,D4
AND #255,D0
CMP D7,D0
BEQ.S L16
MOVE.B D4,D0
MOVE D7,D1
ADDQ #1,D1
AND #3,D1
AND #255,D0
CMP D1,D0
BNE.S L15
L16:
MOVE.B D5,D0
AND #255,D0
ADDQ #1,D0
BRA.S L8
L15:
L13:
MOVE.B D5,D0
AND #255,D0
SUBQ.B #1,D5
TST.B D0
BNE.S L12
L14:
BRA.S L17
L10:
L18:
MOVE.B D6,D0
MOVE.B D5,D1
AND #255,D1
ASL #1,D1
AND #255,D0
ASR D1,D0
AND #3,D0
CMP D7,D0
BNE.S L21
MOVE.B D5,D0
AND #255,D0
ADDQ #1,D0
BRA.S L8
L21:
L19:
MOVE.B D5,D0
AND #255,D0
SUBQ.B #1,D5
TST.B D0
BNE.S L18
L20:
L17:
MOVE #0,D0
L8:
MOVEM.L (A7)+,D4-D7/A3
UNLK A6
RTS
L$7: .EQU #0
F177_aszz_:/* global */
LINK A6,L$22
MOVEM.L A3/D7-D5,-(A7)
MOVE 10(A6),-(A7)
MOVE 8(A6),-(A7)
JSR F175_gzzz_(PC)
ADDQ.L #4,A7
MOVE D0,D5
CMPI #-2,D0
BNE.S L24
MOVE #0,D0
BRA.S L23
L24:
MOVE D5,-(A7)
JSR F156_afzz_(PC)
ADDQ.L #2,A7
MOVE.L D0,A3
MOVE 16(A6),-(A7)
MOVE 14(A6),-(A7)
MOVE 12(A6),-(A7)
MOVE 10(A6),-(A7)
MOVE 8(A6),-(A7)
PEA -4(A6)
JSR F229_hzzz_(PC)
ADDA #14,A7
CLR D7
L26:
MOVE D7,D0
LEA -4(A6),A0
ADDA D0,A0
MOVE.B (A0),D0
AND #255,D0
MOVE D0,-(A7)
MOVE.L A3,-(A7)
JSR F176_avzz_(PC)
ADDQ.L #6,A7
MOVE D0,D6
BEQ.S L28
MOVE D6,D0
BRA.S L23
L28:
ADDQ #1,D7
L25:
BRA.S L26
L27:
L23:
MOVEM.L (A7)+,D5-D7/A3
UNLK A6
RTS
L$22: .EQU #-4
F178_aazz_:/* global */
LINK A6,L$29
MOVEM.L D7-D6,-(A7)
MOVE 10(A6),D7
MOVE 12(A6),D6
AND #3,D6
MOVE D7,D1
ASL #1,D1
MOVE D1,D7
MOVE D6,D0
ASL D1,D0
MOVE D0,D6
MOVE 8(A6),D0
MOVE #3,D1
ASL D7,D1
NOT D1
AND D1,D0
MOVE D0,-10(A6)
MOVE D6,D0
OR -10(A6),D0
L30:
MOVEM.L (A7)+,D6-D7
UNLK A6
RTS
L$29: .EQU #-10
F179_xxxx_:/* global */
LINK A6,L$31
MOVEM.L A3-A2/D7-D4,-(A7)
MOVE.L 8(A6),A3
MOVE 12(A6),D7
MOVE (A3),D0
MOVE.L G284_apuc_+16(A4),D1
MULS #16,D0
MOVE.L D1,A0
ADDA D0,A0
LEA (A0),A0
MOVE.L A0,A2
MOVE.B 4(A2),D5
AND #255,D5
MOVE D5,-4(A6)
MULS #26,D5
LEA G243_as_Gr+4(A4),A0
ADDA D5,A0
MOVE (A0),D5
CMPI #0,D7
SLT D0
AND #1,D0
MOVE D0,-2(A6)
BEQ.S L33
MOVE 14(A2),D7
AND #96,D7
LSR #5,D7
L33:
L34:
LEA 12(A3),A0
ADDA D7,A0
MOVE.B (A0),D6
AND #255,D6
AND #192,D6
MOVE D5,D4
LSR #4,D4
LSR #8,D4
AND #3,D4
BEQ.S L37
JSR F027_AA59_(PC)
AND.L #65535,D0
DIVU D4,D0
SWAP D0
MOVE D0,D4
JSR F028_a000_(PC)
TST D0
BEQ.S L38
MOVE D4,D0
NEG D0
AND #7,D0
MOVE D0,D4
L38:
OR D4,D6
L37:
MOVE D5,D4
LSR #6,D4
LSR #8,D4
AND #3,D4
BEQ.S L39
JSR F027_AA59_(PC)
AND.L #65535,D0
DIVU D4,D0
SWAP D0
MOVE D0,D4
JSR F028_a000_(PC)
TST D0
BEQ.S L40
MOVE D4,D0
NEG D0
AND #7,D0
MOVE D0,D4
L40:
MOVE D4,D0
ASL #3,D0
OR D0,D6
L39:
MOVE 14(A6),D0
BEQ.S L41
MOVE D5,D0
AND #512,D0
BEQ.S L42
MOVE D6,D0
AND #128,D0
BEQ.S L43
CMPI #18,-4(A6)
BNE.S L43
JSR F028_a000_(PC)
TST D0
BEQ.S L44
MOVE #64,D0
EOR D0,D6
MOVE #1,-(A7)
MOVE G379_i_Cur(A4),-(A7)
MOVE G378_i_Cur(A4),-(A7)
MOVE #16,-(A7)
JSR F064_aadz_(PC)
ADDQ.L #8,A7
L44:
BRA.S L45
L43:
MOVE D6,D0
AND #128,D0
BEQ.S L47
MOVE D5,D0
AND #1024,D0
BNE.S L46
L47:
JSR F028_a000_(PC)
TST D0
BEQ.S L48
OR #64,D6
BRA.S L49
L48:
AND #-65,D6
L49:
L46:
L45:
BRA.S L50
L42:
AND #-65,D6
L50:
OR #128,D6
BRA.S L51
L41:
MOVE D5,D0
AND #4,D0
BEQ.S L52
JSR F028_a000_(PC)
TST D0
BEQ.S L53
OR #64,D6
BRA.S L54
L53:
AND #-65,D6
L54:
BRA.S L55
L52:
AND #-65,D6
L55:
AND #-129,D6
L51:
MOVE D6,D0
LEA 12(A3),A0
ADDA D7,A0
MOVE.B D0,(A0)
L35:
MOVE -2(A6),D0
BEQ.S L56
MOVE D7,D0
SUBQ #1,D7
TST D0
BNE L34(PC)
L56:
L36:
MOVE.B 4(A2),D6
AND #255,D6
MULS #26,D6
LEA G243_as_Gr+20(A4),A0
ADDA D6,A0
MOVE (A0),D6
MOVE.L G313_ul_Ga(A4),D0
MOVE 14(A6),D1
BEQ.S L57
MOVE D6,D1
LSR #8,D1
AND #15,D1
BRA.S L58
L57:
MOVE D6,D1
LSR #4,D1
AND #15,D1
L58:
AND.L #65535,D1
ADD.L D1,D0
MOVE.L D0,-(A7)
JSR F028_a000_(PC)
MOVE.L D0,D1
MOVE.L (A7)+,D0
AND.L #65535,D1
ADD.L D1,D0
L32:
MOVEM.L (A7)+,D4-D7/A2-A3
UNLK A6
RTS
L$31: .EQU #-4
F180_hzzz_:/* global */
LINK A6,L$59
MOVE.L A3,-(A7)
MOVE 10(A6),-(A7)
MOVE 8(A6),-(A7)
JSR F175_gzzz_(PC)
ADDQ.L #4,A7
MOVE D0,-(A7)
JSR F156_afzz_(PC)
ADDQ.L #2,A7
MOVE.L D0,A3
MOVE 14(A3),D0
AND #15,D0
CMPI #4,D0
BCS.S L61
MOVE #0,D0
AND #15,D0
MOVE D0,D3
ANDI #-16,14(A3)
OR D3,14(A3)
L61:
MOVE.L G313_ul_Ga(A4),D0
ADDQ.L #1,D0
MOVE G272_i_Cur(A4),D1
EXT.L D1
MOVE.L #24,D3
ASL.L D3,D1
OR.L D1,D0
MOVE.L D0,-10(A6)
MOVE.B #37,-6(A6)
MOVE #255,D0
MOVE.B 4(A3),D1
AND #255,D1
MULS #26,D1
LEA G243_as_Gr+6(A4),A0
ADDA D1,A0
MOVE.B (A0),D3
AND #255,D3
SUB D3,D0
MOVE.B D0,-5(A6)
CLR.B -2(A6)
MOVE 8(A6),D0
MOVE.B D0,-4(A6)
MOVE 10(A6),D0
MOVE.B D0,-3(A6)
PEA -10(A6)
JSR F238_pzzz_(PC)
ADDQ.L #4,A7
L60:
MOVE.L (A7)+,A3
UNLK A6
RTS
L$59: .EQU #-10
F181_czzz_:/* global */
LINK A6,L$62
MOVEM.L A3/D7-D4,-(A7)
MOVE 8(A6),D7
MOVE 10(A6),D6
MOVE #0,D0
MOVE D0,D5
MOVE.L G370_ps_Ev(A4),D0
MOVE.L D0,A3
BRA.S L64
L65:
MOVE.L (A3),D0
MOVE.L #24,D3
ASR.L D3,D0
MOVE G272_i_Cur(A4),D1
CMP D1,D0
BNE.S L67
MOVE.B 4(A3),D0
AND #255,D0
MOVE D0,D4
CMPI #28,D0
BLS.S L67
CMPI #42,D4
BCC.S L67
MOVE.B 6(A3),D0
AND #255,D0
CMP D7,D0
BNE.S L67
MOVE.B 7(A3),D0
AND #255,D0
CMP D6,D0
BNE.S L67
MOVE D5,-(A7)
JSR F237_rzzz_(PC)
ADDQ.L #2,A7
L67:
MOVE.L A3,D0
ADDA #10,A3
MOVE D5,D0
ADDQ #1,D5
L64:
MOVE D5,D0
CMP G369_ui_Ev(A4),D0
BCS.S L65
L66:
L63:
MOVEM.L (A7)+,D4-D7/A3
UNLK A6
RTS
L$62: .EQU #0
F182_aqzz_:/* global */
LINK A6,L$68
MOVE D7,-(A7)
CLR D7
BRA.S L70
L71:
MOVE D7,D0
ADDQ #1,D7
MOVE.L 8(A6),A0
LEA 12(A0),A0
ADDA D0,A0
ANDI.B #-129,(A0)
L70:
CMPI #4,D7
BLT.S L71
L72:
MOVE 14(A6),-(A7)
MOVE 12(A6),-(A7)
JSR F181_czzz_(PC)
ADDQ.L #4,A7
L69:
MOVE (A7)+,D7
UNLK A6
RTS
L$68: .EQU #0
F183_kzzz_:/* global */
LINK A6,L$73
MOVEM.L A3-A2/D7-D6,-(A7)
MOVE.L G375_ps_Ac(A4),A2
CLR -8(A6)
BRA.S L75
L76:
ADDQ #1,-8(A6)
MOVE -8(A6),D0
CMP G376_ui_Ma(A4),D0
BCS.S L78
BRA L74(PC)
L78:
ADDA #16,A2
L75:
CMPI #0,(A2)
BGE.S L76
L77:
ADDQ #1,G377_ui_Cu(A4)
MOVE 8(A6),D1
AND #1023,D1
MOVE D1,(A2)
MULS #16,D1
MOVE.L G284_apuc_+16(A4),D0
ADD.L D1,D0
MOVE.L D0,A3
MOVE.B 5(A3),3(A2)
MOVE -8(A6),D0
MOVE.B D0,5(A3)
MOVE 10(A6),D0
MOVE.B D0,10(A2)
MOVE.B D0,8(A2)
MOVE 12(A6),D0
MOVE.B D0,11(A2)
MOVE.B D0,9(A2)
MOVE.L G313_ul_Ga(A4),D0
SUB.L #127,D0
MOVE.B D0,4(A2)
MOVE.B 4(A3),D0
AND #255,D0
MULS #26,D0
LEA G243_as_Gr+2(A4),A0
ADDA D0,A0
MOVE (A0),D0
AND #3,D0
CMPI #1,D0
SEQ D0
AND #1,D0
MOVE D0,-6(A6)
MOVE 14(A3),D6
AND #96,D6
LSR #5,D6
L79:
MOVE 14(A3),D0
AND #768,D0
LSR #8,D0
MOVE D0,-(A7)
MOVE D6,-(A7)
MOVE.B 2(A2),D0
AND #255,D0
MOVE D0,-(A7)
JSR F178_aazz_(PC)
ADDQ.L #6,A7
MOVE.B D0,2(A2)
MOVE D6,D0
LEA 12(A2),A0
ADDA D0,A0
CLR.B (A0)
L80:
MOVE D6,D0
SUBQ #1,D6
TST D0
BNE.S L79
L81:
CLR -(A7)
MOVE #-1,-(A7)
MOVE.L A2,-(A7)
JSR F179_xxxx_(PC)
ADDQ.L #8,A7
L74:
MOVEM.L (A7)+,D6-D7/A2-A3
UNLK A6
RTS
L$73: .EQU #-8
F184_ahzz_:/* global */
LINK A6,L$82
MOVEM.L A3-A2/D7-D6,-(A7)
MOVE 8(A6),D0
CMP G376_ui_Ma(A4),D0
BHI.S L85
MOVE 8(A6),D0
MULS #16,D0
MOVE.L G375_ps_Ac(A4),A0
ADDA D0,A0
CMPI #0,(A0)
BGE.S L84
L85:
BRA.S L83
L84:
MOVE 8(A6),D0
MULS #16,D0
MOVE.L G375_ps_Ac(A4),A0
ADDA D0,A0
LEA (A0),A0
MOVE.L A0,A3
MOVE (A3),D0
MOVE.L G284_apuc_+16(A4),D1
MULS #16,D0
MOVE.L D1,A0
ADDA D0,A0
LEA (A0),A0
MOVE.L A0,A2
SUBQ #1,G377_ui_Cu(A4)
MOVE.B 3(A3),5(A2)
MOVE.B 2(A3),D0
AND #255,D0
AND #3,D0
AND #3,D0
MOVE D0,D3
ASL #8,D3
ANDI #-769,14(A2)
OR D3,14(A2)
MOVE 14(A2),D0
AND #15,D0
CMPI #4,D0
BCS.S L86
MOVE #0,D0
AND #15,D0
MOVE D0,D3
ANDI #-16,14(A2)
OR D3,14(A2)
L86:
MOVE #-1,(A3)
L83:
MOVEM.L (A7)+,D6-D7/A2-A3
UNLK A6
RTS
L$82: .EQU #0
F185_auzz_:/* global */
LINK A6,L$87
MOVEM.L A3-A2/D7-D4,-(A7)
MOVE G377_ui_Cu(A4),D0
MOVE G376_ui_Ma(A4),D1
SUBQ #5,D1
CMP D1,D0
BCS.S L91
MOVE G272_i_Cur(A4),D0
CMP G309_i_Par(A4),D0
BEQ.S L90
L91:
MOVE #4,-(A7)
JSR F166_szzz_(PC)
ADDQ.L #2,A7
MOVE D0,D7
CMPI #-1,D0
BNE.S L89
L90:
MOVE #-1,D0
BRA L88(PC)
L89:
MOVE D7,-(A7)
JSR F156_afzz_(PC)
ADDQ.L #2,A7
MOVE.L D0,A3
MOVE #-2,2(A3)
MOVE #0,D0
AND #1,D0
MOVE D0,D3
ASL #2,D3
ASL #8,D3
ANDI #-1025,14(A3)
OR D3,14(A3)
MOVE 14(A6),D0
AND #3,D0
MOVE D0,D3
ASL #8,D3
ANDI #-769,14(A3)
OR D3,14(A3)
MOVE 12(A6),D0
AND #3,D0
MOVE D0,D3
ASL #5,D3
ANDI #-97,14(A3)
OR D3,14(A3)
MOVE 12(A6),-2(A6)
BEQ.S L92
JSR F029_AA19_(PC)
MOVE D0,D5
BRA.S L93
L92:
MOVE #255,D4
L93:
MOVE 8(A6),D0
MOVE.B D0,4(A3)
AND #255,D0
MULS #26,D0
LEA G243_as_Gr(A4),A0
ADDA D0,A0
LEA (A0),A0
MOVE.L A0,A2
MOVE.B 9(A2),D6
AND #255,D6
L94:
JSR F027_AA59_(PC)
MOVE D6,D1
LSR #2,D1
ADDQ #1,D1
AND.L #65535,D0
DIVU D1,D0
SWAP D0
MOVE D0,-12(A6)
MOVE D6,D0
MULU 10(A6),D0
ADD -12(A6),D0
MOVE 12(A6),D1
ASL.L #1,D1
LEA 6(A3),A0
ADDA D1,A0
MOVE D0,(A0)
MOVE -2(A6),D0
BEQ.S L97
MOVE D5,D0
ADDQ #1,D5
MOVE D0,-(A7)
MOVE 12(A6),-(A7)
MOVE D4,-(A7)
JSR F178_aazz_(PC)
ADDQ.L #6,A7
MOVE D0,D4
MOVE 2(A2),D0
AND #3,D0
CMPI #1,D0
BNE.S L98
ADDQ #1,D5
L98:
AND #3,D5
L97:
L95:
MOVE 12(A6),D0
SUBQ #1,12(A6)
TST D0
BNE.S L94
L96:
MOVE D4,D0
MOVE.B D0,5(A3)
MOVE 18(A6),-(A7)
MOVE 16(A6),-(A7)
CLR -(A7)
MOVE #-1,-(A7)
MOVE D7,-(A7)
JSR F267_dzzz_(PC)
ADDA #10,A7
TST D0
BEQ.S L99
MOVE #-1,D0
BRA.S L88
L99:
MOVE #1,-(A7)
MOVE 18(A6),-(A7)
MOVE 16(A6),-(A7)
MOVE #17,-(A7)
JSR F064_aadz_(PC)
ADDQ.L #8,A7
MOVE D7,D0
L88:
MOVEM.L (A7)+,D4-D7/A2-A3
UNLK A6
RTS
L$87: .EQU #-12
F186_xxxx_:/* global */
LINK A6,L$100
MOVEM.L A3-A2/D7-D5,-(A7)
CLR -2(A6)
CLR -4(A6)
MOVE 8(A6),D0
BRA.S L102
L103:
BRA L101(PC)
BRA.S L105
L102:
CMP #12,D0
BEQ.S L105
BRA.S L106
L105:
LEA G245_aui_G(A4),A0
MOVE.L A0,A3
BRA L104(PC)
BRA.S L107
L106:
CMP #9,D0
BEQ.S L107
BRA.S L108
L107:
LEA G246_aui_G(A4),A0
MOVE.L A0,A3
BRA L104(PC)
BRA.S L109
L108:
CMP #16,D0
BEQ.S L109
BRA.S L110
L109:
LEA G247_aui_G(A4),A0
MOVE.L A0,A3
BRA.S L104
BRA.S L111
L110:
CMP #18,D0
BEQ.S L111
BRA.S L112
L111:
MOVE #1,-2(A6)
LEA G248_aui_G(A4),A0
MOVE.L A0,A3
BRA.S L104
BRA.S L113
L112:
CMP #7,D0
BEQ.S L113
BRA.S L114
L113:
LEA G249_aui_G(A4),A0
MOVE.L A0,A3
BRA.S L104
BRA.S L115
L114:
CMP #4,D0
BEQ.S L115
BRA.S L116
L115:
LEA G250_aui_G(A4),A0
MOVE.L A0,A3
BRA.S L104
BRA.S L117
L116:
CMP #6,D0
BEQ.S L117
BRA.S L118
L117:
LEA G251_aui_G(A4),A0
MOVE.L A0,A3
BRA.S L104
BRA.S L119
L118:
CMP #15,D0
BEQ.S L119
BRA.S L120
L119:
LEA G252_aui_G(A4),A0
MOVE.L A0,A3
BRA.S L104
BRA.S L121
L120:
CMP #24,D0
BEQ.S L121
BRA.S L122
L121:
LEA G253_aui_G(A4),A0
MOVE.L A0,A3
BRA.S L123
L122:
BRA L103(PC)
L123:
L104:
BRA L124(PC)
L125:
MOVE D7,D0
AND #-32768,D0
BEQ.S L127
JSR F028_a000_(PC)
TST D0
BEQ.S L127
BRA L124(PC)
L127:
MOVE D7,D0
AND #32767,D0
MOVE D0,D7
CMPI #127,D0
BCS.S L128
MOVE #10,D6
SUB #127,D7
BRA.S L129
L128:
CMPI #69,D7
BCS.S L130
MOVE #6,D6
SUB #69,D7
BRA.S L131
L130:
MOVE #1,-4(A6)
MOVE #5,D6
SUB #23,D7
L131:
L129:
MOVE D6,-(A7)
JSR F166_szzz_(PC)
ADDQ.L #2,A7
MOVE D0,D5
CMPI #-1,D0
BNE.S L132
BRA.S L124
L132:
MOVE D5,-(A7)
JSR F156_afzz_(PC)
ADDQ.L #2,A7
MOVE.L D0,A2
MOVE D7,D0
AND #127,D0
MOVE D0,D3
ANDI #-128,2(A2)
OR D3,2(A2)
MOVE -2(A6),D0
AND #1,D0
MOVE D0,D3
ASL #8,D3
ANDI #-257,2(A2)
OR D3,2(A2)
CMPI #255,14(A6)
BEQ.S L134
JSR F029_AA19_(PC)
MOVE.L D0,D1
TST D1
BNE.S L133
L134:
JSR F029_AA19_(PC)
MOVE.L D0,D1
BRA.S L135
L133:
MOVE 14(A6),D1
L135:
ASL #6,D1
ASL #8,D1
MOVE D5,D0
AND #16383,D0
OR D1,D0
MOVE D0,D5
MOVE 12(A6),-(A7)
MOVE 10(A6),-(A7)
CLR -(A7)
MOVE #-1,-(A7)
MOVE D5,-(A7)
JSR F267_dzzz_(PC)
ADDA #10,A7
L124:
MOVE (A3)+,D7
BNE L125(PC)
L126:
MOVE 16(A6),-(A7)
MOVE 12(A6),-(A7)
MOVE 10(A6),-(A7)
MOVE -4(A6),D0
BEQ.S L136
MOVE #0,D0
BRA.S L137
L136:
MOVE #4,D0
L137:
MOVE D0,-(A7)
JSR F064_aadz_(PC)
ADDQ.L #8,A7
L101:
MOVEM.L (A7)+,D5-D7/A2-A3
UNLK A6
RTS
L$100: .EQU #-4
F187_czzz_:/* global */
LINK A6,L$138
MOVE G391_i_Dro(A4),D0
BEQ.S L140
MOVE 8(A6),-(A7)
JSR F156_afzz_(PC)
ADDQ.L #2,A7
MOVE.L D0,-4(A6)
MOVE.L -4(A6),A0
MOVE.B 4(A0),D0
AND #255,D0
MOVE D0,-6(A6)
BRA.S L141
L142:
MOVE #2,-(A7)
SUBQ #1,G391_i_Dro(A4)
MOVE G391_i_Dro(A4),D0
LEA G392_auc_D(A4),A0
ADDA D0,A0
MOVE.B (A0),D0
AND #255,D0
MOVE D0,-(A7)
MOVE 12(A6),-(A7)
MOVE 10(A6),-(A7)
MOVE -6(A6),-(A7)
JSR F186_xxxx_(PC)
ADDA #10,A7
L141:
MOVE G391_i_Dro(A4),D0
BNE.S L142
L143:
L140:
L139:
UNLK A6
RTS
L$138: .EQU #-6
F188_aozz_:/* global */
LINK A6,L$144
MOVEM.L A3/D7-D4,-(A7)
MOVE 8(A6),D7
MOVE 10(A6),D6
MOVE 12(A6),-(A7)
JSR F156_afzz_(PC)
ADDQ.L #2,A7
MOVE.L D0,A3
CMPI #0,14(A6)
BLT.S L146
MOVE.B 4(A3),D0
AND #255,D0
MOVE D0,-2(A6)
MULS #26,D0
LEA G243_as_Gr+2(A4),A0
ADDA D0,A0
MOVE (A0),D0
AND #512,D0
BEQ.S L146
MOVE 14(A3),D0
AND #96,D0
LSR #5,D0
MOVE D0,-4(A6)
MOVE G272_i_Cur(A4),-(A7)
MOVE.L A3,-(A7)
JSR F145_rzzz_(PC)
ADDQ.L #6,A7
MOVE D0,-6(A6)
L147:
MOVE 14(A6),-(A7)
CMPI #255,-6(A6)
BNE.S L150
MOVE #255,D0
BRA.S L151
L150:
MOVE -6(A6),D0
MOVE -4(A6),D1
ASL #1,D1
LSR D1,D0
AND #3,D0
L151:
MOVE D0,-(A7)
MOVE D6,-(A7)
MOVE D7,-(A7)
MOVE -2(A6),-(A7)
JSR F186_xxxx_(PC)
ADDA #10,A7
L148:
MOVE -4(A6),D0
SUBQ #1,-4(A6)
TST D0
BNE.S L147
L149:
L146:
MOVE 2(A3),D0
MOVE D0,D5
CMPI #-2,D0
BEQ L152(PC)
CLR -8(A6)
L153:
MOVE D5,-(A7)
JSR F159_rzzz_(PC)
ADDQ.L #2,A7
MOVE D0,D4
JSR F029_AA19_(PC)
MOVE.L D0,D1
ASL #6,D1
ASL #8,D1
MOVE D5,D0
AND #16383,D0
OR D1,D0
MOVE D0,D5
MOVE D5,D0
AND #15360,D0
LSR #2,D0
LSR #8,D0
CMPI #5,D0
BNE.S L156
MOVE #1,-8(A6)
L156:
MOVE D6,-(A7)
MOVE D7,-(A7)
CLR -(A7)
MOVE #-1,-(A7)
MOVE D5,-(A7)
JSR F267_dzzz_(PC)
ADDA #10,A7
L154:
MOVE D4,D0
MOVE D0,D5
CMPI #-2,D0
BNE.S L153
L155:
CMPI #0,14(A6)
BLT.S L157
MOVE 14(A6),-(A7)
MOVE D6,-(A7)
MOVE D7,-(A7)
MOVE -8(A6),D0
BEQ.S L158
MOVE #0,D0
BRA.S L159
L158:
MOVE #4,D0
L159:
MOVE D0,-(A7)
JSR F064_aadz_(PC)
ADDQ.L #8,A7
L157:
L152:
L145:
MOVEM.L (A7)+,D4-D7/A3
UNLK A6
RTS
L$144: .EQU #-8
F189_awzz_:/* global */
LINK A6,L$160
MOVEM.L A3/D7,-(A7)
MOVE 10(A6),-(A7)
MOVE 8(A6),-(A7)
JSR F175_gzzz_(PC)
ADDQ.L #4,A7
MOVE D0,D7
CMPI #-2,D0
BNE.S L162
BRA.S L161
L162:
MOVE D7,-(A7)
JSR F156_afzz_(PC)
ADDQ.L #2,A7
MOVE.L D0,A3
MOVE #8,-(A7)
LEA 6(A3),A0
MOVE.L A0,-(A7)
JSR F008_aA19_(PC)
ADDQ.L #6,A7
CLR -(A7)
MOVE #-1,-(A7)
MOVE 10(A6),-(A7)
MOVE 8(A6),-(A7)
MOVE D7,-(A7)
JSR F267_dzzz_(PC)
ADDA #10,A7
MOVE #-1,(A3)
MOVE G272_i_Cur(A4),D0
CMP G309_i_Par(A4),D0
BNE.S L163
MOVE.B 5(A3),D0
AND #255,D0
MULS #16,D0
MOVE.L G375_ps_Ac(A4),A0
ADDA D0,A0
MOVE #-1,(A0)
SUBQ #1,G377_ui_Cu(A4)
L163:
MOVE 10(A6),-(A7)
MOVE 8(A6),-(A7)
JSR F181_czzz_(PC)
ADDQ.L #4,A7
L161:
MOVEM.L (A7)+,D7/A3
UNLK A6
RTS
L$160: .EQU #0
F190_zzzz_:/* global */
LINK A6,L$164
MOVEM.L A3-A2/D7-D4,-(A7)
MOVE.L 8(A6),A3
MOVE 14(A6),D7
MOVE 16(A6),D6
MOVE.B 4(A3),D0
AND #255,D0
MOVE D0,-12(A6)
MULS #26,D0
LEA G243_as_Gr(A4),A0
ADDA D0,A0
LEA (A0),A0
MOVE.L A0,A2
MOVE 2(A2),D0
AND #8192,D0
BEQ.S L166
BRA L167(PC)
L166:
MOVE 12(A6),D0
ASL.L #1,D0
LEA 6(A3),A0
ADDA D0,A0
MOVE (A0),D0
MOVE 18(A6),D1
CMP D1,D0
BHI L168(PC)
MOVE G272_i_Cur(A4),-(A7)
MOVE.L A3,-(A7)
JSR F145_rzzz_(PC)
ADDQ.L #6,A7
MOVE D0,-14(A6)
CMPI #255,-14(A6)
BNE.S L169
MOVE #255,D0
BRA.S L170
L169:
MOVE -14(A6),D0
MOVE 12(A6),D1
ASL #1,D1
LSR D1,D0
AND #3,D0
L170:
MOVE D0,-20(A6)
MOVE 14(A3),D0
AND #96,D0
LSR #5,D0
MOVE D0,-10(A6)
BNE.S L171
MOVE 20(A6),D0
BEQ.S L172
MOVE #2,-(A7)
MOVE D6,-(A7)
MOVE D7,-(A7)
JSR F175_gzzz_(PC)
ADDQ.L #4,A7
MOVE D0,-(A7)
MOVE D6,-(A7)
MOVE D7,-(A7)
JSR F188_aozz_(PC)
ADDQ.L #8,A7
MOVE D6,-(A7)
MOVE D7,-(A7)
JSR F189_awzz_(PC)
ADDQ.L #4,A7
L172:
MOVE #2,D4
BRA L173(PC)
L171:
MOVE G272_i_Cur(A4),-(A7)
MOVE.L A3,-(A7)
JSR F147_aawz_(PC)
ADDQ.L #6,A7
MOVE D0,-16(A6)
MOVE 2(A2),D0
AND #512,D0
BEQ.S L174
MOVE 20(A6),D0
BEQ.S L175
MOVE #2,-(A7)
MOVE -20(A6),-(A7)
MOVE D6,-(A7)
MOVE D7,-(A7)
MOVE -12(A6),-(A7)
JSR F186_xxxx_(PC)
ADDA #10,A7
BRA.S L176
L175:
MOVE -20(A6),D0
MOVE G391_i_Dro(A4),D1
ADDQ #1,G391_i_Dro(A4)
LEA G392_auc_D(A4),A0
ADDA D1,A0
MOVE.B D0,(A0)
L176:
L174:
MOVE G272_i_Cur(A4),D0
CMP G309_i_Par(A4),D0
SEQ D0
AND #1,D0
MOVE D0,-18(A6)
BEQ.S L177
MOVE.B 5(A3),D0
AND #255,D0
MULS #16,D0
MOVE.L G375_ps_Ac(A4),A0
ADDA D0,A0
LEA (A0),A0
MOVE.L A0,-8(A6)
L177:
MOVE 14(A3),D0
AND #15,D0
CMPI #6,D0
BNE L178(PC)
MOVE #0,D0
MOVE D0,D5
MOVE.L G370_ps_Ev(A4),D0
MOVE.L D0,-4(A6)
BRA L179(PC)
L180:
MOVE.L -4(A6),A0
MOVE.L (A0),D0
MOVE.L #24,D3
ASR.L D3,D0
MOVE G272_i_Cur(A4),D1
CMP D1,D0
BNE.S L182
MOVE.L -4(A6),A0
MOVE.B 6(A0),D0
AND #255,D0
CMP D7,D0
BNE.S L182
MOVE.L -4(A6),A0
MOVE.B 7(A0),D0
AND #255,D0
CMP D6,D0
BNE.S L182
MOVE.L -4(A6),A0
MOVE.B 4(A0),D0
AND #255,D0
MOVE D0,D4
CMPI #32,D0
BLS.S L182
CMPI #42,D4
BCC.S L182
CMPI #37,D4
BCC.S L183
SUB #33,D4
BRA.S L184
L183:
SUB #38,D4
L184:
MOVE D4,D0
CMP 12(A6),D0
BNE.S L185
MOVE D5,-(A7)
JSR F237_rzzz_(PC)
ADDQ.L #2,A7
BRA.S L186
L185:
MOVE D4,D0
CMP 12(A6),D0
BLS.S L187
MOVE.L -4(A6),A0
SUBQ.B #1,4(A0)
MOVE D5,-(A7)
JSR F235_bzzz_(PC)
ADDQ.L #2,A7
MOVE D0,-(A7)
JSR F236_pzzz_(PC)
ADDQ.L #2,A7
L187:
L186:
L182:
MOVE.L -4(A6),D0
ADDI.L #10,-4(A6)
MOVE D5,D0
ADDQ #1,D5
L179:
MOVE D5,D0
CMP G369_ui_Ev(A4),D0
BCS L180(PC)
L181:
MOVE -18(A6),D0
BEQ.S L188
MOVE 16(A2),D0
LSR #4,D0
AND #15,D0
MOVE D0,-12(A6)
CMPI #15,D0
BEQ.S L188
MOVE -10(A6),D1
SUBQ #1,D1
MOVE -12(A6),D0
ADD D1,D0
MOVE D0,-12(A6)
MOVE.L D0,-(A7)
JSR F027_AA59_(PC)
MOVE.L D0,D1
MOVE.L (A7)+,D0
AND #15,D1
CMP D1,D0
BCC.S L188
JSR F027_AA59_(PC)
MOVE #100,D1
MOVE -12(A6),D2
ASL #2,D2
SUB D2,D1
AND.L #65535,D0
DIVU D1,D0
SWAP D0
ADD #20,D0
MOVE.L -8(A6),A0
MOVE.B D0,5(A0)
MOVE #5,D0
AND #15,D0
MOVE D0,D3
ANDI #-16,14(A3)
OR D3,14(A3)
L188:
L178:
MOVE 12(A6),D4
MOVE D4,D5
BRA L189(PC)
L190:
ADDQ #1,D4
MOVE D4,D0
ASL.L #1,D0
LEA 6(A3),A0
ADDA D0,A0
MOVE (A0),D0
MOVE D5,D1
ASL.L #1,D1
LEA 6(A3),A0
ADDA D1,A0
MOVE D0,(A0)
MOVE -16(A6),D0
MOVE D4,D1
ASL #1,D1
LSR D1,D0
AND #3,D0
MOVE D0,-(A7)
MOVE D5,-(A7)
MOVE -16(A6),-(A7)
JSR F178_aazz_(PC)
ADDQ.L #6,A7
MOVE D0,-16(A6)
MOVE -14(A6),D0
MOVE D4,D1
ASL #1,D1
LSR D1,D0
AND #3,D0
MOVE D0,-(A7)
MOVE D5,-(A7)
MOVE -14(A6),-(A7)
JSR F178_aazz_(PC)
ADDQ.L #6,A7
MOVE D0,-14(A6)
MOVE -18(A6),D0
BEQ.S L193
MOVE D4,D0
MOVE.L -8(A6),A0
LEA 12(A0),A0
ADDA D0,A0
MOVE.B (A0),D0
MOVE D5,D1
MOVE.L -8(A6),A0
LEA 12(A0),A0
ADDA D1,A0
AND #255,D0
MOVE.B D0,(A0)
L193:
L191:
ADDQ #1,D5
L189:
MOVE D5,D0
CMP -10(A6),D0
BCS L190(PC)
L192:
ANDI #63,-14(A6)
MOVE G272_i_Cur(A4),-(A7)
MOVE -14(A6),-(A7)
MOVE.L A3,-(A7)
JSR F146_aczz_(PC)
ADDQ.L #8,A7
MOVE G272_i_Cur(A4),-(A7)
MOVE -16(A6),-(A7)
MOVE.L A3,-(A7)
JSR F148_aayz_(PC)
ADDQ.L #8,A7
MOVE 14(A3),D0
AND #96,D0
LSR #5,D0
SUBQ #1,D0
AND #3,D0
MOVE D0,D3
ASL #5,D3
ANDI #-97,14(A3)
OR D3,14(A3)
MOVE #1,D4
L173:
MOVE 2(A2),D0
AND #3,D0
MOVE D0,D5
CMPI #0,D0
BNE.S L194
MOVE #110,D5
BRA.S L195
L194:
CMPI #1,D5
BNE.S L196
MOVE #190,D5
BRA.S L197
L196:
MOVE #255,D5
L197:
L195:
MOVE -20(A6),-(A7)
MOVE D6,-(A7)
MOVE D7,-(A7)
MOVE D5,-(A7)
MOVE #-88,-(A7)
JSR F213_hzzz_(PC)
ADDA #10,A7
MOVE D4,D0
BRA.S L165
L168:
CMPI #0,18(A6)
BLE.S L198
MOVE 12(A6),D0
ASL.L #1,D0
LEA 6(A3),A0
ADDA D0,A0
MOVE (A0),D0
SUB 18(A6),D0
MOVE D0,(A0)
L198:
L167:
MOVE #0,D0
L165:
MOVEM.L (A7)+,D4-D7/A2-A3
UNLK A6
RTS
L$164: .EQU #-20
F191_aayz_:/* global */
LINK A6,L$199
MOVEM.L A3/D7-D6,-(A7)
MOVE.L 8(A6),A3
MOVE 16(A6),D7
CLR -6(A6)
MOVE #1,-8(A6)
CLR G391_i_Dro(A4)
CMPI #0,D7
BLE L201(PC)
MOVE 14(A3),D0
AND #96,D0
LSR #5,D0
MOVE D0,-2(A6)
MOVE D7,D0
ASR #3,D0
ADDQ #1,D0
MOVE D0,D6
SUB D0,D7
MOVE D6,D0
ASL #1,D0
MOVE D0,D6
L202:
MOVE 18(A6),-(A7)
JSR F027_AA59_(PC)
MOVE.L D0,D1
AND.L #65535,D1
DIVU D6,D1
SWAP D1
MOVE D7,D0
ADD D1,D0
MOVE D0,-(A7)
MOVE 14(A6),-(A7)
MOVE 12(A6),-(A7)
MOVE -2(A6),-(A7)
MOVE.L A3,-(A7)
JSR F190_zzzz_(PC)
ADDA #14,A7
MOVE D0,-4(A6)
BEQ.S L205
MOVE -8(A6),D0
L205:
SNE D0
AND #1,D0
MOVE D0,-8(A6)
MOVE -6(A6),D0
BNE.S L206
MOVE -4(A6),D0
L206:
SNE D0
AND #1,D0
MOVE D0,-6(A6)
L203:
MOVE -2(A6),D0
SUBQ #1,-2(A6)
TST D0
BNE.S L202
L204:
MOVE -8(A6),D0
BEQ.S L207
MOVE #2,D0
BRA.S L200
L207:
MOVE -6(A6),D0
BEQ.S L208
MOVE #1,D0
BRA.S L200
L208:
MOVE #0,D0
BRA.S L200
BRA.S L209
L201:
MOVE #0,D0
L209:
L200:
MOVEM.L (A7)+,D6-D7/A3
UNLK A6
RTS
L$199: .EQU #-8
F192_ayzz_:/* global */
LINK A6,L$210
MOVE D7,-(A7)
MOVE 10(A6),D0
BEQ.S L213
MOVE 8(A6),D0
MULS #26,D0
LEA G243_as_Gr+18(A4),A0
ADDA D0,A0
MOVE (A0),D0
LSR #8,D0
AND #15,D0
MOVE D0,D7
CMPI #15,D0
BNE.S L212
L213:
MOVE #0,D0
BRA.S L211
L212:
JSR F029_AA19_(PC)
MOVE D0,-10(A6)
MOVE 10(A6),D0
ADD -10(A6),D0
ASL #3,D0
ADDQ #1,D7
MOVE D7,D1
AND.L #65535,D0
DIVU D1,D0
L211:
MOVE (A7)+,D7
UNLK A6
RTS
L$210: .EQU #-10
F193_xxxx_:/* global */
LINK A6,L$214
BSS SEG "bss"
19G394_auc:
.WORD #8
CODE SEG "dunman"
MOVEM.L A3-A2/D7-D4,-(A7)
MOVE.L 8(A6),A3
CLR -2(A6)
MOVE 12(A6),D0
MULS #800,D0
LEA G407_s_Par(A4),A0
ADDA D0,A0
LEA (A0),A0
MOVE.L A0,D0
MOVE.L D0,A2
MOVE.L D0,-(A7)
JSR F311_wzzz_(PC)
ADDQ.L #4,A7
MOVE.L D0,D1
MOVE #100,D0
SUB D1,D0
MOVE D0,D7
JSR F027_AA59_(PC)
AND #7,D0
MOVE D0,D5
BRA L216(PC)
L217:
MOVE D5,D0
LEA 19G394_auc(A4),A0
ADDA D0,A0
MOVE.B (A0),D0
AND #255,D0
MOVE D0,D6
CMPI #13,D0
BNE.S L219
JSR F027_AA59_(PC)
AND.L #65535,D0
DIVU #17,D0
SWAP D0
ADD D0,D6
L219:
MOVE D6,D0
ASL.L #1,D0
LEA 212(A2),A0
ADDA D0,A0
MOVE (A0),D0
MOVE D0,D4
CMPI #-1,D0
BEQ.S L220
MOVE #1,-2(A6)
MOVE D6,-(A7)
MOVE 12(A6),-(A7)
JSR F300_aozz_(PC)
ADDQ.L #4,A7
MOVE D0,D4
CMPI #-2,2(A3)
BNE.S L221
MOVE D4,2(A3)
BRA.S L222
L221:
CLR -(A7)
MOVE #-1,-(A7)
MOVE 2(A3),-(A7)
MOVE D4,-(A7)
JSR F163_amzz_(PC)
ADDQ.L #8,A7
L222:
MOVE 12(A6),-(A7)
JSR F292_arzz_(PC)
ADDQ.L #2,A7
L220:
ADDQ #1,D5
AND #7,D5
SUB #20,D7
L216:
CMPI #0,D7
BLE.S L223
MOVE D7,-(A7)
MOVE.L A2,-(A7)
JSR F308_vzzz_(PC)
ADDQ.L #6,A7
TST D0
BEQ L217(PC)
L223:
L218:
JSR F027_AA59_(PC)
AND #7,D0
BEQ.S L225
MOVE -2(A6),D0
BEQ.S L224
JSR F028_a000_(PC)
TST D0
BEQ.S L224
L225:
JSR F027_AA59_(PC)
AND #63,D0
ADD #20,D0
MOVE.B 5(A3),D1
AND #255,D1
MULS #16,D1
MOVE.L G375_ps_Ac(A4),A0
ADDA D1,A0
MOVE.B D0,5(A0)
MOVE #5,D0
AND #15,D0
MOVE D0,D3
ANDI #-16,14(A3)
OR D3,14(A3)
L224:
L215:
MOVEM.L (A7)+,D4-D7/A2-A3
UNLK A6
RTS
L$214: .EQU #-2
F194_hzzz_:/* global */
LINK A6,L$226
MOVE D7,-(A7)
CLR D7
BRA.S L228
L229:
MOVE D7,D0
MULS #16,D0
MOVE.L G375_ps_Ac(A4),A0
ADDA D0,A0
CMPI #0,(A0)
BLT.S L231
MOVE D7,-(A7)
JSR F184_ahzz_(PC)
ADDQ.L #2,A7
L231:
ADDQ #1,D7
L228:
CMPI #0,G377_ui_Cu(A4)
BHI.S L229
L230:
L227:
MOVE (A7)+,D7
UNLK A6
RTS
L$226: .EQU #0
F195_akzz_:/* global */
LINK A6,L$232
MOVEM.L A3-A2/D7-D5,-(A7)
MOVE.L G271_ppuc_(A4),A0
MOVE.L (A0),A3
MOVE.L G270_pui_C(A4),A0
MOVE (A0),D0
ASL.L #1,D0
MOVE.L G283_pT_Sq(A4),A0
ADDA D0,A0
LEA (A0),A0
MOVE.L A0,A2
CLR D7
BRA.S L234
L235:
CLR D6
BRA.S L238
L239:
MOVE.B (A3)+,D0
AND #255,D0
AND #16,D0
BEQ.S L242
MOVE (A2)+,D5
L243:
MOVE D5,D0
AND #15360,D0
LSR #2,D0
LSR #8,D0
CMPI #4,D0
BNE.S L246
MOVE D6,-(A7)
MOVE D7,-(A7)
JSR F181_czzz_(PC)
ADDQ.L #4,A7
MOVE D6,-(A7)
MOVE D7,-(A7)
MOVE D5,-(A7)
JSR F183_kzzz_(PC)
ADDQ.L #6,A7
MOVE D6,-(A7)
MOVE D7,-(A7)
JSR F180_hzzz_(PC)
ADDQ.L #4,A7
BRA.S L245
L246:
L244:
MOVE D5,-(A7)
JSR F159_rzzz_(PC)
ADDQ.L #2,A7
MOVE D0,D5
CMPI #-2,D0
BNE.S L243
L245:
L242:
L240:
ADDQ #1,D6
L238:
MOVE D6,D0
MOVE G274_i_Cur(A4),D1
CMP D1,D0
BCS.S L239
L241:
L236:
ADDQ #1,D7
L234:
MOVE D7,D0
MOVE G273_i_Cur(A4),D1
CMP D1,D0
BCS.S L235
L237:
L233:
MOVEM.L (A7)+,D5-D7/A2-A3
UNLK A6
RTS
L$232: .EQU #0
F196_aozz_:/* global */
LINK A6,L$247
MOVE D7,-(A7)
MOVE G298_B_New(A4),D0
BEQ.S L249
MOVE #60,G376_ui_Ma(A4)
L249:
MOVE #1,-(A7)
MOVE G376_ui_Ma(A4),D0
MULU #16,D0
AND.L #65535,D0
MOVE.L D0,-(A7)
JSR F468_ozzz_(PC)
ADDQ.L #6,A7
MOVE.L D0,G375_ps_Ac(A4)
CLR D7
BRA.S L250
L251:
MOVE D7,D0
ADDQ #1,D7
MULS #16,D0
MOVE.L G375_ps_Ac(A4),A0
ADDA D0,A0
MOVE #-1,(A0)
L250:
MOVE D7,D0
CMP G376_ui_Ma(A4),D0
BCS.S L251
L252:
L248:
MOVE (A7)+,D7
UNLK A6
RTS
L$247: .EQU #0
F197_xxxx_:/* global */
LINK A6,L$253
MOVEM.L A3/D7-D5,-(A7)
MOVE 10(A6),D0
MOVE 8(A6),D1
ASL.L #2,D1
MOVE.L G271_ppuc_(A4),A0
ADDA D1,A0
MOVE.L (A0),A0
ADDA D0,A0
MOVE.B (A0),D0
AND #255,D0
MOVE D0,D7
LSR #5,D0
MOVE D0,D6
CMPI #4,D0
BNE.S L255
MOVE 10(A6),-(A7)
MOVE 8(A6),-(A7)
JSR F157_rzzz_(PC)
ADDQ.L #4,A7
MOVE.L D0,A3
MOVE D7,D0
AND #7,D0
MOVE D0,D5
CMPI #3,D0
SEQ D0
TST.B D0
BNE.S L257
CMPI #4,D5
SEQ D0
TST.B D0
L257:
TST.B D0
BEQ.S L256
MOVE 2(A3),D0
AND #1,D0
ASL.L #1,D0
LEA G275_as_Cu(A4),A0
ADDA D0,A0
MOVE.B (A0),D0
AND #255,D0
AND #1,D0
SEQ D0
TST.B D0
L256:
AND #1,D0
BRA.S L254
L255:
CMPI #0,D6
SEQ D0
TST.B D0
BNE.S L258
CMPI #6,D6
SEQ D0
TST.B D0
BEQ.S L259
MOVE D7,D0
AND #4,D0
SEQ D0
TST.B D0
L259:
TST.B D0
L258:
AND #1,D0
L254:
MOVEM.L (A7)+,D5-D7/A3
UNLK A6
RTS
L$253: .EQU #0
F198_xxxx_:/* global */
LINK A6,L$260
MOVEM.L D7-D6,-(A7)
MOVE 10(A6),D0
MOVE 8(A6),D1
ASL.L #2,D1
MOVE.L G271_ppuc_(A4),A0
ADDA D1,A0
MOVE.L (A0),A0
ADDA D0,A0
MOVE.B (A0),D0
AND #255,D0
MOVE D0,D7
LSR #5,D0
MOVE D0,D6
CMPI #0,D0
SEQ D0
TST.B D0
BNE.S L262
CMPI #6,D6
SEQ D0
TST.B D0
BEQ.S L263
MOVE D7,D0
AND #4,D0
SEQ D0
TST.B D0
L263:
TST.B D0
L262:
AND #1,D0
L261:
MOVEM.L (A7)+,D6-D7
UNLK A6
RTS
L$260: .EQU #0
F199_xxxx_:/* global */
LINK A6,L$264
MOVEM.L A3/D7-D4,-(A7)
MOVE.L 16(A6),A3
MOVE 8(A6),D0
MOVE 12(A6),D1
SUB D1,D0
MOVE D0,-(A7)
JSR F023_aarz_(PC)
ADDQ.L #2,A7
MOVE.L D0,-(A7)
MOVE 10(A6),D0
MOVE 14(A6),D1
SUB D1,D0
MOVE D0,-(A7)
JSR F023_aarz_(PC)
ADDQ.L #2,A7
MOVE.L D0,D1
MOVE.L (A7)+,D0
ADD D1,D0
CMPI #1,D0
BGT.S L266
MOVE #1,D0
BRA L265(PC)
L266:
MOVE 12(A6),D0
SUB 8(A6),D0
MOVE D0,D5
CMPI #0,D0
BGE.S L267
MOVE D5,D0
NEG D0
BRA.S L268
L267:
MOVE D5,D0
L268:
MOVE D0,D5
MOVE 14(A6),D1
SUB 10(A6),D1
MOVE D1,D4
CMPI #0,D1
BGE.S L269
MOVE D4,D1
NEG D1
BRA.S L270
L269:
MOVE D4,D1
L270:
MOVE D1,D4
CMP D1,D0
SLT D0
AND #1,D0
MOVE D0,-4(A6)
MOVE D5,D0
CMP D4,D0
SEQ D0
AND #1,D0
MOVE D0,-10(A6)
MOVE 12(A6),D7
MOVE D7,D5
SUB 8(A6),D7
CMPI #0,D7
BLE.S L271
MOVE #-1,D7
BRA.S L272
L271:
MOVE #1,D7
L272:
MOVE 14(A6),D6
MOVE D6,D4
SUB 10(A6),D6
CMPI #0,D6
BLE.S L273
MOVE #-1,D6
BRA.S L274
L273:
MOVE #1,D6
L274:
MOVE -4(A6),D0
BEQ.S L275
MOVE D4,D0
SUB 10(A6),D0
MOVE D0,-2(A6)
BEQ.S L276
MOVE D5,D0
SUB 8(A6),D0
ASL #6,D0
EXT.L D0
DIVS -2(A6),D0
BRA.S L277
L276:
MOVE #128,D0
L277:
BRA.S L278
L275:
MOVE D5,D0
SUB 8(A6),D0
MOVE D0,-2(A6)
BEQ.S L279
MOVE D4,D0
SUB 10(A6),D0
ASL #6,D0
EXT.L D0
DIVS -2(A6),D0
BRA.S L280
L279:
MOVE #128,D0
L280:
L278:
MOVE D0,-12(A6)
L281:
MOVE -10(A6),D0
BEQ.S L284
MOVE D4,-(A7)
MOVE D5,D0
ADD D7,D0
MOVE D0,-(A7)
JSR (A3)
ADDQ.L #4,A7
TST D0
BEQ.S L287
MOVE D4,D0
ADD D6,D0
MOVE D0,-(A7)
MOVE D5,-(A7)
JSR (A3)
ADDQ.L #4,A7
TST D0
BNE.S L286
L287:
MOVE D4,D0
ADD D6,D0
MOVE D0,D4
MOVE D0,-(A7)
MOVE D5,D0
ADD D7,D0
MOVE D0,D5
MOVE D0,-(A7)
JSR (A3)
ADDQ.L #4,A7
TST D0
BEQ.S L285
L286:
MOVE #0,D0
BRA L265(PC)
L285:
BRA L288(PC)
L284:
MOVE -4(A6),D0
BEQ.S L291
MOVE D4,D0
SUB 10(A6),D0
MOVE D0,-2(A6)
BEQ.S L292
MOVE D5,D0
ADD D7,D0
SUB 8(A6),D0
ASL #6,D0
EXT.L D0
DIVS -2(A6),D0
BRA.S L293
L292:
MOVE #128,D0
L293:
BRA.S L294
L291:
MOVE D5,D0
ADD D7,D0
SUB 8(A6),D0
MOVE D0,-2(A6)
BEQ.S L295
MOVE D4,D0
SUB 10(A6),D0
ASL #6,D0
EXT.L D0
DIVS -2(A6),D0
BRA.S L296
L295:
MOVE #128,D0
L296:
L294:
SUB -12(A6),D0
MOVE D0,-2(A6)
CMPI #0,D0
BGE.S L290
MOVE -2(A6),D0
NEG D0
BRA.S L297
L290:
MOVE -2(A6),D0
L297:
MOVE D0,-6(A6)
MOVE -4(A6),D1
BEQ.S L299
MOVE D4,D1
ADD D6,D1
SUB 10(A6),D1
MOVE D1,-2(A6)
BEQ.S L300
MOVE D5,D1
SUB 8(A6),D1
ASL #6,D1
EXT.L D1
DIVS -2(A6),D1
BRA.S L301
L300:
MOVE #128,D1
L301:
BRA.S L302
L299:
MOVE D5,D1
SUB 8(A6),D1
MOVE D1,-2(A6)
BEQ.S L303
MOVE D4,D1
ADD D6,D1
SUB 10(A6),D1
ASL #6,D1
EXT.L D1
DIVS -2(A6),D1
BRA.S L304
L303:
MOVE #128,D1
L304:
L302:
SUB -12(A6),D1
MOVE D1,-2(A6)
CMPI #0,D1
BGE.S L298
MOVE -2(A6),D1
NEG D1
BRA.S L305
L298:
MOVE -2(A6),D1
L305:
MOVE D1,-8(A6)
CMP D1,D0
BGE.S L289
ADD D7,D5
BRA.S L306
L289:
ADD D6,D4
L306:
MOVE D4,-(A7)
MOVE D5,-(A7)
JSR (A3)
ADDQ.L #4,A7
TST D0
BEQ.S L307
MOVE -6(A6),D0
CMP -8(A6),D0
BNE.S L308
MOVE D4,D0
SUB D6,D0
MOVE D0,D4
MOVE D0,-(A7)
MOVE D5,D0
ADD D7,D0
MOVE D0,D5
MOVE D0,-(A7)
JSR (A3)
ADDQ.L #4,A7
TST D0
BEQ.S L307
L308:
MOVE #0,D0
BRA.S L265
L307:
L288:
L282:
MOVE D5,D0
MOVE 8(A6),D1
SUB D1,D0
MOVE D0,-(A7)
JSR F023_aarz_(PC)
ADDQ.L #2,A7
MOVE.L D0,-(A7)
MOVE D4,D0
MOVE 10(A6),D1
SUB D1,D0
MOVE D0,-(A7)
JSR F023_aarz_(PC)
ADDQ.L #2,A7
MOVE.L D0,D1
MOVE.L (A7)+,D0
ADD D1,D0
CMPI #1,D0
BGT L281(PC)
L283:
MOVE 14(A6),-(A7)
MOVE 12(A6),-(A7)
MOVE 10(A6),-(A7)
MOVE 8(A6),-(A7)
JSR F226_ozzz_(PC)
ADDQ.L #8,A7
L265:
MOVEM.L (A7)+,D4-D7/A3
UNLK A6
RTS
L$264: .EQU #-12
F200_xxxx_:/* global */
LINK A6,L$309
MOVEM.L A3-A2/D7-D4,-(A7)
MOVE.L 8(A6),A3
MOVE.B 4(A3),D0
AND #255,D0
MULS #26,D0
LEA G243_as_Gr(A4),A0
ADDA D0,A0
LEA (A0),A0
MOVE.L A0,A2
MOVE.B G407_s_Par+3286(A4),D0
BEQ.S L311
MOVE 2(A2),D0
AND #2048,D0
BNE.S L311
MOVE #0,D0
BRA L310(PC)
L311:
MOVE 2(A2),D0
AND #4,D0
BEQ.S L312
BRA L26T200_011(PC)
L312:
MOVE.B 5(A3),D4
AND #255,D4
MULS #16,D4
MOVE.L G375_ps_Ac(A4),A0
ADDA D4,A0
MOVE.B 2(A0),D4
AND #255,D4
CMPI #0,12(A6)
BGE.S L313
CLR D6
MOVE 14(A3),D0
AND #96,D0
LSR #5,D0
MOVE D0,12(A6)
BRA.S L314
L315:
MOVE D4,D7
MOVE 12(A6),D1
ASL #1,D1
LSR D1,D7
AND #3,D7
MOVE D6,D5
BRA.S L317
L318:
MOVE D5,D0
ASL.L #1,D0
LEA -8(A6),A0
ADDA D0,A0
MOVE (A0),D0
CMP D7,D0
BNE.S L320
BRA.S L26T200_006
L320:
L317:
MOVE D5,D0
SUBQ #1,D5
TST D0
BNE.S L318
L319:
MOVE D6,D0
ADDQ #1,D6
ASL.L #1,D0
LEA -8(A6),A0
ADDA D0,A0
MOVE D7,(A0)
L26T200_006:
SUBQ #1,12(A6)
L314:
CMPI #0,12(A6)
BGE.S L315
L316:
BRA.S L321
L313:
MOVE D4,D0
MOVE 12(A6),D1
ASL #1,D1
LSR D1,D0
AND #3,D0
MOVE D0,-8(A6)
MOVE #1,D6
L321:
BRA L322(PC)
L323:
MOVE G307_i_Par(A4),-(A7)
MOVE G306_i_Par(A4),-(A7)
MOVE 16(A6),-(A7)
MOVE 14(A6),-(A7)
MOVE D6,D0
ASL.L #1,D0
LEA -8(A6),A0
ADDA D0,A0
MOVE (A0),-(A7)
JSR F227_qzzz_(PC)
ADDA #10,A7
TST D0
BEQ.S L325
L26T200_011:
MOVE 14(A2),D5
AND #15,D5
MOVE 2(A2),D0
AND #4096,D0
BNE.S L326
MOVE G304_i_Dun(A4),D0
ASR #1,D0
SUB D0,D5
L326:
MOVE D5,-(A7)
MOVE #1,-(A7)
JSR F025_aatz_(PC)
ADDQ.L #4,A7
MOVE D0,-18(A6)
MOVE G381_ui_Cu(A4),D0
CMP -18(A6),D0
BLS.S L327
MOVE #0,D0
BRA.S L310
L327:
PEA F197_xxxx_(PC)
MOVE G307_i_Par(A4),-(A7)
MOVE G306_i_Par(A4),-(A7)
MOVE 16(A6),-(A7)
MOVE 14(A6),-(A7)
JSR F199_xxxx_(PC)
ADDA #12,A7
BRA.S L310
L325:
L322:
MOVE D6,D0
SUBQ #1,D6
TST D0
BNE L323(PC)
L324:
MOVE #0,D0
L310:
MOVEM.L (A7)+,D4-D7/A2-A3
UNLK A6
RTS
L$309: .EQU #-18
F201_xxxx_:/* global */
LINK A6,L$328
MOVEM.L D7-D6,-(A7)
MOVE.L 8(A6),A0
MOVE 14(A0),D0
LSR #8,D0
AND #15,D0
MOVE D0,D7
BNE.S L330
MOVE #0,D0
BRA L329(PC)
L330:
MOVE D7,D0
ADDQ #1,D0
LSR #1,D0
CMP G381_ui_Cu(A4),D0
BCS.S L331
PEA F198_xxxx_(PC)
MOVE G307_i_Par(A4),-(A7)
MOVE G306_i_Par(A4),-(A7)
MOVE 14(A6),-(A7)
MOVE 12(A6),-(A7)
JSR F199_xxxx_(PC)
ADDA #12,A7
TST D0
BEQ.S L331
MOVE G383_i_Cur(A4),G363_i_Sec(A4)
MOVE G382_i_Cur(A4),D0
ADDQ #1,D0
BRA.S L329
L331:
MOVE 14(A6),-(A7)
MOVE 12(A6),-(A7)
JSR F315_arzz_(PC)
ADDQ.L #4,A7
MOVE D0,D6
BEQ.S L332
JSR F029_AA19_(PC)
MOVE D0,-10(A6)
LEA G407_s_Par+3261(A4),A0
ADDA D6,A0
MOVE.B (A0),D0
AND #255,D0
ADD -10(A6),D0
MOVE #30,D1
MOVE D7,D2
ASL #1,D2
SUB D2,D1
CMP D1,D0
BLS.S L332
MOVE D6,D0
ASL.L #1,D0
LEA G407_s_Par+3214(A4),A0
ADDA D0,A0
MOVE (A0),D0
AND #992,D0
LSR #5,D0
MOVE D0,-(A7)
MOVE D6,D0
ASL.L #1,D0
LEA G407_s_Par+3214(A4),A0
ADDA D0,A0
MOVE (A0),D0
AND #31,D0
MOVE D0,-(A7)
MOVE 14(A6),-(A7)
MOVE 12(A6),-(A7)
JSR F228_uzzz_(PC)
ADDQ.L #8,A7
ADDQ #1,D0
BRA.S L329
L332:
MOVE #0,D0
L329:
MOVEM.L (A7)+,D6-D7
UNLK A6
RTS
L$328: .EQU #-10
F202_xxxx_:/* global */
LINK A6,L$333
MOVEM.L A3-A2/D7-D4,-(A7)
MOVE.L 8(A6),A3
MOVE 16(A6),D0
LEA G384_ac_Gr(A4),A0
ADDA D0,A0
MOVE.B #1,(A0)
MOVE #-2,G388_T_Gro(A4)
CLR G389_B_Gro(A4)
CLR G390_B_Gro(A4)
MOVE.B 6(A3),D0
AND #255,D0
CMP #255,D0
BNE.S L335
MOVE #0,D0
BRA L334(PC)
L335:
PEA 14(A6)
PEA 12(A6)
CLR -(A7)
MOVE #1,-(A7)
MOVE 16(A6),-(A7)
JSR F150_wzzz_(PC)
ADDA #14,A7
MOVE 12(A6),D7
MOVE 14(A6),D6
CMPI #0,D7
SGE D0
TST.B D0
BEQ.S L342
MOVE D7,D0
CMP G273_i_Cur(A4),D0
SLT D0
TST.B D0
L342:
TST.B D0
BEQ.S L341
CMPI #0,D6
SGE D0
TST.B D0
BEQ.S L343
MOVE D6,D0
CMP G274_i_Cur(A4),D0
SLT D0
TST.B D0
L343:
TST.B D0
L341:
TST.B D0
BEQ.S L340
MOVE D7,D0
ASL.L #2,D0
MOVE.L G271_ppuc_(A4),A0
ADDA D0,A0
MOVE.L (A0),A0
ADDA D6,A0
MOVE.B (A0),D0
AND #255,D0
MOVE D0,D5
LSR #5,D0
MOVE D0,D4
CMPI #0,D0
SNE D0
TST.B D0
L340:
TST.B D0
BEQ.S L339
CMPI #3,D4
SNE D0
TST.B D0
L339:
TST.B D0
BEQ.S L338
CMPI #2,D4
SNE D0
TST.B D0
BNE.S L346
MOVE D5,D0
AND #1,D0
BEQ.S L347
MOVE 18(A6),D0
L347:
SNE D0
TST.B D0
L346:
TST.B D0
BNE.S L345
MOVE D5,D0
AND #8,D0
SEQ D0
TST.B D0
L345:
TST.B D0
BNE.S L344
MOVE 2(A3),D0
AND #32,D0
L344:
SNE D0
TST.B D0
L338:
TST.B D0
BEQ.S L337
CMPI #6,D4
SNE D0
TST.B D0
BNE.S L349
MOVE D5,D0
AND #4,D0
L349:
SNE D0
TST.B D0
BNE.S L348
MOVE D5,D0
AND #1,D0
BEQ.S L350
MOVE 18(A6),D0
L350:
SNE D0
TST.B D0
L348:
TST.B D0
L337:
TST.B D0
SEQ D0
AND #1,D0
MOVE D0,G387_B_Gro(A4)
BEQ.S L336
MOVE #0,D0
BRA L334(PC)
L336:
MOVE 2(A3),D0
AND #8192,D0
BEQ.S L351
MOVE D6,-(A7)
MOVE D7,-(A7)
JSR F161_szzz_(PC)
ADDQ.L #4,A7
MOVE D0,-2(A6)
BRA.S L352
L353:
MOVE -2(A6),D0
AND #15360,D0
LSR #2,D0
LSR #8,D0
CMPI #15,D0
BNE.S L356
MOVE -2(A6),-(A7)
JSR F156_afzz_(PC)
ADDQ.L #2,A7
MOVE.L D0,A2
MOVE.L A2,D0
MOVE.L D0,A0
MOVE 2(A0),D0
AND #127,D0
CMPI #50,D0
BNE.S L357
MOVE 16(A6),D0
LEA G385_ac_Fl(A4),A0
ADDA D0,A0
MOVE.B #1,(A0)
ADDQ #1,G386_ui_Fl(A4)
MOVE #1,G387_B_Gro(A4)
MOVE #0,D0
BRA L334(PC)
L357:
L356:
L354:
MOVE -2(A6),-(A7)
JSR F159_rzzz_(PC)
ADDQ.L #2,A7
MOVE D0,-2(A6)
L352:
CMPI #-2,-2(A6)
BNE.S L353
L355:
L351:
CMPI #5,D4
BNE.S L358
MOVE D5,D0
AND #8,D0
BEQ.S L358
MOVE 16(A3),D0
LSR #4,D0
LSR #8,D0
CMPI #10,D0
BCS.S L358
MOVE D6,-(A7)
MOVE D7,-(A7)
JSR F157_rzzz_(PC)
ADDQ.L #4,A7
MOVE.L D0,A2
MOVE 2(A2),D0
AND #24576,D0
LSR #5,D0
LSR #8,D0
AND #1,D0
BEQ.S L359
MOVE 4(A2),D0
AND #-256,D0
LSR #8,D0
MOVE D0,-(A7)
MOVE G380_T_Cur(A4),-(A7)
JSR F139_aqzz_(PC)
ADDQ.L #4,A7
TST D0
BNE.S L359
MOVE #1,G387_B_Gro(A4)
MOVE #0,D0
BRA L334(PC)
L359:
L358:
MOVE G272_i_Cur(A4),D0
CMP G309_i_Par(A4),D0
SEQ D0
TST.B D0
BEQ.S L362
MOVE D7,D0
CMP G306_i_Par(A4),D0
SEQ D0
TST.B D0
L362:
TST.B D0
BEQ.S L361
MOVE D6,D0
CMP G307_i_Par(A4),D0
SEQ D0
TST.B D0
L361:
AND #1,D0
MOVE D0,G390_B_Gro(A4)
BEQ.S L360
MOVE #0,D0
BRA.S L334
L360:
CMPI #4,D4
BNE.S L363
MOVE D6,-(A7)
MOVE D7,-(A7)
JSR F157_rzzz_(PC)
ADDQ.L #4,A7
MOVE.L D0,A2
MOVE D5,D0
AND #7,D0
MOVE.L A2,D1
MOVE.L D1,A0
MOVE 2(A0),D1
AND #32,D1
LSR #5,D1
BEQ.S L365
MOVE 2(A3),D1
LSR #7,D1
AND #3,D1
BRA.S L366
L365:
MOVE #1,D1
L366:
CMP D1,D0
BLS.S L364
MOVE D5,D0
AND #7,D0
CMPI #5,D0
BEQ.S L364
MOVE 2(A3),D0
AND #64,D0
BNE.S L364
MOVE #1,G389_B_Gro(A4)
MOVE #0,D0
BRA.S L334
L364:
L363:
MOVE D6,-(A7)
MOVE D7,-(A7)
JSR F175_gzzz_(PC)
ADDQ.L #4,A7
MOVE D0,G388_T_Gro(A4)
CMPI #-2,D0
SEQ D0
AND #1,D0
L334:
MOVEM.L (A7)+,D4-D7/A2-A3
UNLK A6
RTS
L$333: .EQU #-2
F203_xxxx_:/* global */
LINK A6,L$367
MOVE D7,-(A7)
CLR D7
BRA.S L369
L370:
LEA G384_ac_Gr(A4),A0
ADDA D7,A0
MOVE.B (A0),D0
BNE.S L373
MOVE 16(A6),-(A7)
MOVE D7,-(A7)
MOVE 14(A6),-(A7)
MOVE 12(A6),-(A7)
MOVE.L 8(A6),-(A7)
JSR F202_xxxx_(PC)
ADDA #12,A7
TST D0
BEQ.S L373
MOVE D7,D0
ADDQ #1,D0
BRA.S L368
L373:
L371:
ADDQ #1,D7
L369:
CMPI #3,D7
BLE.S L370
L372:
MOVE #0,D0
L368:
MOVE (A7)+,D7
UNLK A6
RTS
L$367: .EQU #0
F204_xxxx_:/* global */
LINK A6,L$374
MOVE D7,-(A7)
MOVE 16(A6),D7
MOVE D7,D0
LEA G385_ac_Fl(A4),A0
ADDA D0,A0
MOVE.B (A0),D0
BEQ.S L376
MOVE #0,D0
BRA.S L375
L376:
MOVE D7,D1
ASL.L #1,D1
LEA G233_ai_Gr(A4),A0
ADDA D1,A0
MOVE (A0),D1
MOVE 12(A6),D0
ADD D1,D0
MOVE D0,12(A6)
MOVE D7,D1
ASL.L #1,D1
LEA G234_ai_Gr(A4),A0
ADDA D1,A0
MOVE (A0),D1
MOVE 14(A6),D0
ADD D1,D0
MOVE D0,14(A6)
CLR -(A7)
MOVE D7,-(A7)
MOVE 14(A6),-(A7)
MOVE 12(A6),-(A7)
MOVE.L 8(A6),-(A7)
JSR F202_xxxx_(PC)
ADDA #12,A7
L375:
MOVE (A7)+,D7
UNLK A6
RTS
L$374: .EQU #0
F205_xxxx_:/* global */
LINK A6,L$377
BSS SEG "bss"
32G395_l_T:
.WORD #4
33G396_ps_:
.WORD #4
CODE SEG "dunman"
MOVEM.L A3/D7-D5,-(A7)
MOVE.L 8(A6),A3
MOVE 12(A6),D7
MOVE 14(A6),D6
MOVE 16(A6),D0
BEQ.S L379
MOVE.L G313_ul_Ga(A4),D0
CMP.L 32G395_l_T(A4),D0
BNE.S L379
MOVE.L A3,D0
CMP.L 33G396_ps_(A4),D0
BNE.S L379
BRA.S L378
L379:
MOVE.B 2(A3),D0
AND #255,D0
MOVE D0,D5
MOVE D6,D1
ASL #1,D1
LSR D1,D0
AND #3,D0
SUB D7,D0
AND #3,D0
CMPI #2,D0
BNE.S L380
JSR F027_AA59_(PC)
AND #2,D0
ADD D7,D0
ADDQ #1,D0
AND #3,D0
MOVE D0,D7
MOVE D0,-(A7)
MOVE D6,-(A7)
MOVE D5,-(A7)
JSR F178_aazz_(PC)
ADDQ.L #6,A7
MOVE D0,D5
BRA.S L381
L380:
MOVE D7,-(A7)
MOVE D6,-(A7)
MOVE D5,-(A7)
JSR F178_aazz_(PC)
ADDQ.L #6,A7
MOVE D0,D5
L381:
MOVE 16(A6),D0
BEQ.S L382
MOVE D7,-(A7)
MOVE D6,D0
MOVE #1,D3
EOR D3,D0
MOVE D0,-(A7)
MOVE D5,-(A7)
JSR F178_aazz_(PC)
ADDQ.L #6,A7
MOVE D0,D5
MOVE.L G313_ul_Ga(A4),32G395_l_T(A4)
MOVE.L A3,33G396_ps_(A4)
L382:
MOVE D5,D0
MOVE.B D0,2(A3)
L378:
MOVEM.L (A7)+,D5-D7/A3
UNLK A6
RTS
L$377: .EQU #0
F206_xxxx_:/* global */
LINK A6,L$383
MOVEM.L D7-D6,-(A7)
MOVE 14(A6),D7
MOVE D7,D6
BEQ.S L386
CMPI #1,16(A6)
SEQ D6
TST.B D6
L386:
SNE D6
AND #1,D6
BEQ.S L385
SUBQ #1,D7
L385:
L387:
MOVE D7,D0
BEQ.S L391
JSR F028_a000_(PC)
TST D0
BEQ.S L390
L391:
MOVE D6,-(A7)
MOVE D7,-(A7)
MOVE 12(A6),-(A7)
MOVE.L 8(A6),-(A7)
JSR F205_xxxx_(PC)
ADDA #10,A7
L390:
L388:
MOVE D7,D0
SUBQ #1,D7
TST D0
BNE.S L387
L389:
L384:
MOVEM.L (A7)+,D6-D7
UNLK A6
RTS
L$383: .EQU #0
F207_xxxx_:/* global */
LINK A6,L$392
MOVEM.L A3-A2/D7-D4,-(A7)
MOVE.L 8(A6),A3
MOVE.L G313_ul_Ga(A4),G361_l_Las(A4)
MOVE.B 5(A3),D0
AND #255,D0
MULS #16,D0
MOVE.L G375_ps_Ac(A4),A0
ADDA D0,A0
LEA (A0),A1
LEA -20(A6),A0
MOVEQ #7,D0
JSR _blockmv(PC)
MOVE.B 4(A3),D0
AND #255,D0
MOVE D0,D7
MULS #26,D0
LEA G243_as_Gr(A4),A0
ADDA D0,A0
LEA (A0),A0
MOVE.L A0,A2
MOVE G382_i_Cur(A4),D6
MOVE.B -17(A6),D0
AND #255,D0
MOVE D0,D5
CMPI #255,D0
BNE.S L394
JSR F028_a000_(PC)
MOVE D0,D5
BRA.S L395
L394:
MOVE D5,D0
MOVE 16(A6),D1
ASL #1,D1
ASR D1,D0
AND #3,D0
ADDQ #5,D0
SUB D6,D0
AND #2,D0
LSR #1,D0
MOVE D0,D5
L395:
ADD D6,D5
AND #3,D5
MOVE 14(A2),D0
LSR #4,D0
LSR #8,D0
CMPI #1,D0
BLS L396(PC)
CMPI #1,G381_ui_Cu(A4)
BHI.S L397
JSR F028_a000_(PC)
TST D0
BEQ L396(PC)
L397:
MOVE D7,D0
L398:
CMP #14,D0
BEQ.S L399
L401:
CMP #23,D0
BEQ.S L399
BRA.S L402
L399:
JSR F028_a000_(PC)
TST D0
BEQ.S L404
MOVE #-128,D7
BRA.S L405
L404:
JSR F029_AA19_(PC)
L406:
CMP #0,D0
BEQ.S L407
BRA.S L409
L407:
MOVE #-125,D7
BRA.S L408
BRA.S L410
L409:
CMP #1,D0
BEQ.S L410
BRA.S L411
L410:
MOVE #-126,D7
BRA.S L408
BRA.S L412
L411:
CMP #2,D0
BEQ.S L412
BRA.S L413
L412:
MOVE #-121,D7
BRA.S L408
BRA.S L414
L413:
CMP #3,D0
BEQ.S L414
BRA.S L415
L414:
MOVE #-124,D7
L415:
L416:
L408:
L405:
BRA.S L400
BRA.S L403
L402:
CMP #1,D0
BEQ.S L403
BRA.S L417
L403:
MOVE #-127,D7
BRA.S L400
BRA.S L418
L417:
CMP #3,D0
BEQ.S L418
BRA.S L419
L418:
JSR F027_AA59_(PC)
AND #7,D0
BEQ.S L421
MOVE #-126,D7
BRA.S L422
L421:
MOVE #-124,D7
L422:
BRA.S L400
BRA.S L420
L419:
CMP #19,D0
BEQ.S L420
BRA.S L423
L420:
JSR F028_a000_(PC)
TST D0
BEQ.S L425
MOVE #-121,D7
BRA.S L400
L425:
BRA.S L424
L423:
CMP #22,D0
BEQ.S L424
L426:
CMP #24,D0
BEQ.S L424
BRA.S L427
L424:
MOVE #-128,D7
L427:
L428:
L400:
MOVE.B 10(A2),D4
AND #255,D4
ASR #2,D4
ADDQ #1,D4
JSR F027_AA59_(PC)
AND.L #65535,D0
DIVU D4,D0
SWAP D0
ADD D0,D4
JSR F027_AA59_(PC)
AND.L #65535,D0
DIVU D4,D0
SWAP D0
ADD D0,D4
MOVE #8,-(A7)
MOVE.B 12(A2),D0
AND #255,D0
MOVE D0,-(A7)
MOVE #255,-(A7)
MOVE D4,-(A7)
MOVE #20,-(A7)
JSR F026_a003_(PC)
ADDQ.L #6,A7
MOVE D0,-(A7)
MOVE G382_i_Cur(A4),-(A7)
MOVE D5,-(A7)
MOVE 14(A6),-(A7)
MOVE 12(A6),-(A7)
MOVE D7,-(A7)
JSR F212_mzzz_(PC)
ADDA #16,A7
BRA L429(PC)
L396:
MOVE 2(A2),D0
AND #16,D0
BEQ.S L430
MOVE #0,D0
MOVE D0,D4
JSR F029_AA19_(PC)
MOVE D0,D5
BRA.S L431
L432:
MOVE D4,D0
ADDQ #1,D4
MOVE D5,D0
ADDQ #1,D0
AND #3,D0
MOVE D0,D5
L431:
CMPI #4,D4
BGE.S L434
MOVE D5,D0
MULS #800,D0
LEA G407_s_Par+52(A4),A0
ADDA D0,A0
MOVE (A0),D0
BEQ.S L432
L434:
L433:
CMPI #4,D4
BNE.S L435
MOVE #0,D0
BRA L393(PC)
L435:
BRA.S L436
L430:
MOVE D5,-(A7)
MOVE 14(A6),-(A7)
MOVE 12(A6),-(A7)
JSR F286_hzzz_(PC)
ADDQ.L #6,A7
MOVE D0,D5
CMPI #0,D0
BGE.S L437
MOVE #0,D0
BRA L393(PC)
L437:
L436:
CMPI #2,D7
BNE.S L438
MOVE D5,-(A7)
MOVE.L A3,-(A7)
JSR F193_xxxx_(PC)
ADDQ.L #6,A7
BRA.S L439
L438:
MOVE D5,-(A7)
MOVE.L A3,-(A7)
JSR F230_ezzz_(PC)
ADDQ.L #6,A7
ADDQ #1,D0
MOVE D0,D4
MOVE D5,D0
MULS #800,D0
LEA G407_s_Par(A4),A0
ADDA D0,A0
LEA (A0),A0
MOVE.L A0,-4(A6)
MOVE D4,D0
MOVE.L -4(A6),A0
MOVE.B 41(A0),D1
AND #255,D1
CMP D1,D0
BLE.S L440
MOVE D4,D0
MOVE.L -4(A6),A0
MOVE.B D0,41(A0)
MOVE D6,D0
ADDQ #2,D0
AND #3,D0
MOVE.L -4(A6),A0
MOVE.B D0,40(A0)
L440:
L439:
L429:
MOVE.B 1(A2),D4
AND #255,D4
BEQ.S L441
MOVE #1,-(A7)
MOVE 14(A6),-(A7)
MOVE 12(A6),-(A7)
SUBQ #1,D4
MOVE D4,D0
LEA G244_auc_G(A4),A0
ADDA D0,A0
MOVE.B (A0),D0
AND #255,D0
MOVE D0,-(A7)
JSR F064_aadz_(PC)
ADDQ.L #8,A7
L441:
MOVE #1,D0
L393:
MOVEM.L (A7)+,D4-D7/A2-A3
UNLK A6
RTS
L$392: .EQU #-20
F208_xxxx_:/* global */
LINK A6,L$442
MOVEM.L A3/D7,-(A7)
MOVE.L 8(A6),A3
MOVE.L 12(A6),D7
MOVE.L D7,D0
MOVE.L (A3),D1
AND.L #16777215,D1
CMP.L D1,D0
BGE.S L444
SUBQ.B #5,4(A3)
MOVE.L (A3),D0
AND.L #16777215,D0
SUB.L D7,D0
MOVE.B D0,8(A3)
MOVE.L (A3),D0
AND.L #-16777216,D0
OR.L D7,D0
MOVE.L D0,(A3)
BRA.S L445
L444:
MOVE.L D7,D0
MOVE.L (A3),D1
AND.L #16777215,D1
SUB.L D1,D0
MOVE.B D0,8(A3)
L445:
MOVE.L A3,-(A7)
JSR F238_pzzz_(PC)
ADDQ.L #4,A7
L443:
MOVEM.L (A7)+,D7/A3
UNLK A6
RTS
L$442: .EQU #0
F209_xzzz_:/* global */
LINK A6,L$446
MOVEM.L A3-A2/D7-D4,-(A7)
MOVE 8(A6),D7
MOVE 10(A6),D6
MOVE G272_i_Cur(A4),D0
CMP G309_i_Par(A4),D0
BEQ.S L448
MOVE 12(A6),D0
MOVE D0,D5
CMPI #37,D0
BEQ.S L448
CMPI #32,D5
BEQ.S L448
CMPI #38,D5
BEQ.S L448
CMPI #33,D5
BEQ.S L448
BRA L447(PC)
L448:
MOVE D6,-(A7)
MOVE D7,-(A7)
JSR F175_gzzz_(PC)
ADDQ.L #4,A7
MOVE D0,-28(A6)
CMPI #-2,D0
BNE.S L449
BRA L447(PC)
L449:
MOVE -28(A6),-(A7)
JSR F156_afzz_(PC)
ADDQ.L #2,A7
MOVE.L D0,A3
MOVE.B 4(A3),D0
AND #255,D0
MULS #26,D0
LEA G243_as_Gr(A4),A0
ADDA D0,A0
LEA (A0),A1
LEA -26(A6),A0
MOVEQ #12,D0
JSR _blockmv(PC)
MOVE.L G313_ul_Ga(A4),D0
MOVE G272_i_Cur(A4),D1
EXT.L D1
MOVE.L #24,D3
ASL.L D3,D1
OR.L D1,D0
MOVE.L D0,-70(A6)
MOVE #255,D0
MOVE.B -20(A6),D3
AND #255,D3
SUB D3,D0
MOVE.B D0,-65(A6)
MOVE D7,D0
MOVE.B D0,-64(A6)
MOVE D6,D0
MOVE.B D0,-63(A6)
MOVE G272_i_Cur(A4),D0
CMP G309_i_Par(A4),D0
BEQ L450(PC)
CLR -(A7)
JSR F029_AA19_(PC)
MOVE D0,D5
MOVE D0,-(A7)
MOVE D6,-(A7)
MOVE D7,-(A7)
PEA -26(A6)
JSR F202_xxxx_(PC)
ADDA #12,A7
TST D0
BEQ.S L451
MOVE D7,-30(A6)
MOVE D6,-32(A6)
MOVE D5,D1
ASL.L #1,D1
LEA G233_ai_Gr(A4),A0
ADDA D1,A0
MOVE (A0),D1
MOVE -30(A6),D0
ADD D1,D0
MOVE D0,-30(A6)
MOVE D5,D1
ASL.L #1,D1
LEA G234_ai_Gr(A4),A0
ADDA D1,A0
MOVE (A0),D1
MOVE -32(A6),D0
ADD D1,D0
MOVE D0,-32(A6)
MOVE -32(A6),-(A7)
MOVE -30(A6),-(A7)
MOVE D6,-(A7)
MOVE D7,-(A7)
MOVE -28(A6),-(A7)
JSR F267_dzzz_(PC)
ADDA #10,A7
TST D0
BEQ.S L452
BRA L447(PC)
L452:
MOVE G397_i_Mov(A4),D0
MOVE.B D0,-64(A6)
MOVE G398_i_Mov(A4),D0
MOVE.B D0,-63(A6)
L451:
MOVE.B #37,-66(A6)
MOVE.B -20(A6),D0
AND #255,D0
ASL #1,D0
MOVE D0,-(A7)
MOVE G272_i_Cur(A4),D0
SUB G309_i_Par(A4),D0
MOVE D0,-(A7)
JSR F023_aarz_(PC)
ADDQ.L #2,A7
ASL #4,D0
MOVE D0,-(A7)
JSR F025_aatz_(PC)
ADDQ.L #4,A7
MOVE D0,D5
L37T209_005:
MOVE D5,D0
EXT.L D0
ADD.L D0,-70(A6)
PEA -70(A6)
JSR F238_pzzz_(PC)
ADDQ.L #4,A7
BRA L447(PC)
L450:
MOVE -24(A6),D0
AND #8192,D0
MOVE D0,-56(A6)
BEQ.S L453
MOVE G302_B_Gam(A4),D0
BEQ.S L454
BRA L447(PC)
L454:
CLR G386_ui_Fl(A4)
LEA G385_ac_Fl(A4),A0
MOVE.L A0,D0
MOVE.L D0,A0
CLR.L (A0)
L453:
MOVE.B 5(A3),D0
AND #255,D0
MULS #16,D0
MOVE.L G375_ps_Ac(A4),A0
ADDA D0,A0
LEA (A0),A0
MOVE.L A0,A2
MOVE.L G313_ul_Ga(A4),D0
AND #255,D0
MOVE.B 4(A2),D3
AND #255,D3
SUB D3,D0
MOVE D0,-54(A6)
CMPI #0,D0
BGE.S L455
ADDI #256,-54(A6)
L455:
MOVE.B -20(A6),D0
AND #255,D0
MOVE D0,-52(A6)
CMPI #255,D0
BNE.S L456
MOVE #100,-52(A6)
L456:
MOVE.B G407_s_Par+3211(A4),D0
BEQ.S L457
MOVE -56(A6),D0
BNE.S L457
CMPI #0,12(A6)
BGE.S L458
BRA L447(PC)
L458:
MOVE 12(A6),D0
MOVE.B D0,-66(A6)
MOVE 14(A6),D0
MOVE.B D0,-62(A6)
MOVE #4,D5
BRA L37T209_005(PC)
L457:
CMPI #0,12(A6)
BGE.S L459
MOVE 12(A6),D0
ADD #32,D0
MOVE.B D0,-66(A6)
CMPI #-1,12(A6)
BEQ.S L461
MOVE -52(A6),D0
ADDQ #2,D0
ASR #2,D0
SUB -54(A6),D0
MOVE D0,D5
CMPI #1,D0
BGE.S L460
L461:
MOVE #1,D5
L460:
BRA L37T209_005(PC)
L459:
MOVE 14(A3),D4
AND #15,D4
MOVE 14(A3),D0
AND #96,D0
LSR #5,D0
MOVE D0,-50(A6)
MOVE -24(A6),D0
AND #3,D0
MOVE D0,-48(A6)
MOVE D7,D0
SUB G306_i_Par(A4),D0
MOVE D0,D5
CMPI #0,D0
BGE.S L462
MOVE D5,D0
NEG D0
BRA.S L463
L462:
MOVE D5,D0
L463:
MOVE D0,-30(A6)
MOVE D6,D0
SUB G307_i_Par(A4),D0
MOVE D0,D5
CMPI #0,D0
BGE.S L464
MOVE D5,D0
NEG D0
BRA.S L465
L464:
MOVE D5,D0
L465:
MOVE D0,-32(A6)
MOVE D7,G378_i_Cur(A4)
MOVE D6,G379_i_Cur(A4)
MOVE -28(A6),G380_T_Cur(A4)
LEA G384_ac_Gr(A4),A0
MOVE.L A0,D0
MOVE.L D0,A0
CLR.L (A0)
MOVE G307_i_Par(A4),-(A7)
MOVE G306_i_Par(A4),-(A7)
MOVE D6,-(A7)
MOVE D7,-(A7)
JSR F226_ozzz_(PC)
ADDQ.L #8,A7
MOVE D0,G381_ui_Cu(A4)
MOVE G307_i_Par(A4),-(A7)
MOVE G306_i_Par(A4),-(A7)
MOVE D6,-(A7)
MOVE D7,-(A7)
JSR F228_uzzz_(PC)
ADDQ.L #8,A7
MOVE D0,G382_i_Cur(A4)
MOVE G363_i_Sec(A4),G383_i_Cur(A4)
CLR.L -60(A6)
MOVE #1,-40(A6)
CMPI #31,12(A6)
BGT L466(PC)
MOVE 12(A6),D0
SUB #32,D0
MOVE D0,12(A6)
L467:
CMP #-1,D0
BEQ.S L468
BRA.S L470
L468:
CMPI #6,D4
BEQ.S L472
CMPI #5,D4
BEQ.S L472
MOVE D6,-(A7)
MOVE D7,-(A7)
JSR F181_czzz_(PC)
ADDQ.L #4,A7
BRA L37T209_044(PC)
L472:
MOVE G306_i_Par(A4),D0
MOVE.B D0,6(A2)
MOVE G307_i_Par(A4),D0
MOVE.B D0,7(A2)
BRA L447(PC)
BRA.S L471
L470:
CMP #-2,D0
BEQ.S L471
BRA.S L473
L471:
CMPI #6,D4
BEQ.S L476
CMPI #5,D4
BNE.S L475
L476:
BRA L447(PC)
L475:
CMPI #3,D4
SEQ D0
TST.B D0
BNE.S L479
CMPI #2,D4
SEQ D0
TST.B D0
L479:
AND #1,D0
MOVE D0,D5
BNE.S L478
JSR F029_AA19_(PC)
TST D0
BEQ.S L477
L478:
MOVE D6,-(A7)
MOVE D7,-(A7)
MOVE #-1,-(A7)
MOVE.L A3,-(A7)
JSR F200_xxxx_(PC)
ADDA #10,A7
TST D0
BNE.S L480
MOVE #0,D0
MOVE D0,-36(A6)
MOVE D0,-46(A6)
BRA L37T209_073(PC)
L480:
MOVE D5,D0
BNE.S L482
JSR F029_AA19_(PC)
TST D0
BEQ.S L481
L482:
BRA L447(PC)
L481:
L477:
BRA.S L474
L473:
CMP #-3,D0
BEQ.S L474
BRA.S L483
L474:
CMPI #6,D4
SEQ D0
AND #1,D0
MOVE D0,-46(A6)
CLR -36(A6)
BRA L37T209_058(PC)
L483:
L484:
L469:
L466:
CMPI #37,12(A6)
BGE L485(PC)
MOVE 12(A6),D0
ADDQ #5,D0
MOVE.B D0,-66(A6)
MOVE D6,-(A7)
MOVE D7,-(A7)
MOVE #-1,-(A7)
MOVE.L A3,-(A7)
JSR F200_xxxx_(PC)
ADDA #10,A7
TST D0
BEQ.S L486
CMPI #6,D4
BEQ.S L487
CMPI #5,D4
BEQ.S L487
MOVE G306_i_Par(A4),D0
MOVE D7,D1
SUB D1,D0
MOVE D0,-(A7)
JSR F023_aarz_(PC)
ADDQ.L #2,A7
MOVE.L D0,-(A7)
MOVE G307_i_Par(A4),D0
MOVE D6,D1
SUB D1,D0
MOVE D0,-(A7)
JSR F023_aarz_(PC)
ADDQ.L #2,A7
MOVE.L D0,D1
MOVE.L (A7)+,D0
ADD D1,D0
CMPI #1,D0
BGT.S L488
BRA L37T209_044(PC)
L488:
CMPI #0,D4
BEQ.S L490
CMPI #3,D4
BNE.S L489
L490:
CMPI #7,D4
BEQ.S L489
BRA L37T209_054(PC)
L489:
L487:
MOVE G306_i_Par(A4),D0
MOVE.B D0,6(A2)
MOVE G307_i_Par(A4),D0
MOVE.B D0,7(A2)
L486:
CMPI #6,D4
BNE.S L491
MOVE 12(A6),D5
SUB #33,D5
LEA 12(A2),A0
ADDA D5,A0
MOVE.B (A0),D0
AND #255,D0
AND #128,D0
MOVE D0,-(A7)
MOVE D5,-(A7)
MOVE.L A2,-(A7)
JSR F179_xxxx_(PC)
ADDQ.L #8,A7
MOVE.L D0,-60(A6)
BRA L37T209_136(PC)
L491:
CMPI #3,-30(A6)
BGT.S L493
CMPI #3,-32(A6)
BLE.S L492
L493:
MOVE.L G313_ul_Ga(A4),D0
MOVE -6(A6),D1
LSR #4,D1
AND #15,D1
AND.L #65535,D1
ADD.L D1,D0
MOVE.L D0,-60(A6)
BRA L37T209_136(PC)
L492:
BRA L494(PC)
L485:
CLR -40(A6)
MOVE 14(A6),D0
BEQ.S L495
MOVE.L G313_ul_Ga(A4),-60(A6)
L495:
CMPI #37,12(A6)
BNE L496(PC)
CMPI #0,D4
BEQ.S L498
CMPI #2,D4
BEQ.S L498
CMPI #3,D4
BNE L497(PC)
L498:
MOVE D6,-(A7)
MOVE D7,-(A7)
MOVE #-1,-(A7)
MOVE.L A3,-(A7)
JSR F200_xxxx_(PC)
ADDA #10,A7
MOVE D0,-34(A6)
BEQ L499(PC)
MOVE -34(A6),D0
MOVE -12(A6),D1
LSR #4,D1
LSR #8,D1
CMP D1,D0
BHI L500(PC)
MOVE -30(A6),D0
BEQ.S L501
MOVE -32(A6),D0
BNE L500(PC)
L501:
L37T209_044:
CMPI #-2,12(A6)
BNE.S L502
MOVE D6,-(A7)
MOVE D7,-(A7)
JSR F181_czzz_(PC)
ADDQ.L #4,A7
L502:
MOVE G306_i_Par(A4),D0
MOVE.B D0,6(A2)
MOVE G307_i_Par(A4),D0
MOVE.B D0,7(A2)
MOVE #6,D0
AND #15,D0
MOVE D0,D3
ANDI #-16,14(A3)
OR D3,14(A3)
MOVE G382_i_Cur(A4),D5
MOVE -50(A6),D4
BRA L503(PC)
L504:
MOVE.B 2(A2),D0
MOVE D4,D1
ASL #1,D1
AND #255,D0
ASR D1,D0
AND #3,D0
CMP D5,D0
BEQ.S L507
MOVE D4,D0
BEQ.S L508
JSR F028_a000_(PC)
TST D0
BNE.S L507
L508:
MOVE -50(A6),D0
BEQ.S L509
CMPI #1,-48(A6)
SEQ D0
TST.B D0
L509:
SNE D0
AND #1,D0
MOVE D0,-(A7)
MOVE D4,-(A7)
MOVE D5,-(A7)
MOVE.L A2,-(A7)
JSR F205_xxxx_(PC)
ADDA #10,A7
JSR F029_AA19_(PC)
MOVE.L D0,D1
MOVE D1,-80(A6)
MOVE.L G313_ul_Ga(A4),D1
MOVE -80(A6),D3
AND.L #65535,D3
ADD.L D3,D1
ADDQ.L #2,D1
MOVE.L -70(A6),D0
AND.L #-16777216,D0
OR.L D1,D0
MOVE.L D0,-70(A6)
BRA.S L510
L507:
MOVE.L -70(A6),D0
AND.L #-16777216,D0
MOVE.L G313_ul_Ga(A4),D1
ADDQ.L #1,D1
OR.L D1,D0
MOVE.L D0,-70(A6)
L510:
MOVE -40(A6),D0
BEQ.S L511
MOVE 14(A6),-(A7)
JSR F029_AA19_(PC)
MOVE.L D0,D1
MOVE.B -19(A6),D0
AND #255,D0
ASR #1,D0
ADD D1,D0
MOVE D0,-(A7)
JSR F024_aatz_(PC)
ADDQ.L #4,A7
EXT.L D0
ADD.L D0,-70(A6)
L511:
MOVE #38,D0
ADD D4,D0
MOVE.B D0,-66(A6)
CLR -(A7)
MOVE D4,-(A7)
MOVE.L A2,-(A7)
JSR F179_xxxx_(PC)
ADDQ.L #8,A7
MOVE.L D0,-(A7)
PEA -70(A6)
JSR F208_xxxx_(PC)
ADDQ.L #8,A7
L505:
SUBQ #1,D4
L503:
CMPI #0,D4
BGE L504(PC)
L506:
BRA L447(PC)
L500:
CMPI #2,D4
BEQ.S L512
L37T209_054:
MOVE #7,D0
AND #15,D0
MOVE D0,D3
ANDI #-16,14(A3)
OR D3,14(A3)
MOVE G306_i_Par(A4),D0
MOVE.B D0,6(A2)
MOVE G307_i_Par(A4),D0
MOVE.B D0,7(A2)
ADDQ.L #1,-70(A6)
BRA L37T209_134(PC)
L512:
BRA L513(PC)
L499:
CMPI #0,D4
BNE L514(PC)
MOVE D6,-(A7)
MOVE D7,-(A7)
PEA -26(A6)
JSR F201_xxxx_(PC)
ADDQ.L #8,A7
MOVE D0,-38(A6)
BEQ.S L515
SUBQ #1,-38(A6)
CLR -42(A6)
BRA L37T209_085(PC)
L515:
CLR -36(A6)
JSR F028_a000_(PC)
TST D0
BEQ L516(PC)
L37T209_058:
JSR F029_AA19_(PC)
MOVE D0,D5
MOVE D5,D4
CLR -44(A6)
L517:
MOVE D7,-30(A6)
MOVE D6,-32(A6)
MOVE D5,D1
ASL.L #1,D1
LEA G233_ai_Gr(A4),A0
ADDA D1,A0
MOVE (A0),D1
MOVE -30(A6),D0
ADD D1,D0
MOVE D0,-30(A6)
MOVE D5,D1
ASL.L #1,D1
LEA G234_ai_Gr(A4),A0
ADDA D1,A0
MOVE (A0),D1
MOVE -32(A6),D0
ADD D1,D0
MOVE D0,-32(A6)
MOVE.B 8(A2),D0
AND #255,D0
CMP -30(A6),D0
BNE.S L521
MOVE.B 9(A2),D0
AND #255,D0
CMP -32(A6),D0
BNE.S L521
JSR F029_AA19_(PC)
TST D0
SEQ D0
AND #1,D0
MOVE D0,-44(A6)
BEQ L520(PC)
L521:
CLR -(A7)
MOVE D5,-(A7)
MOVE D6,-(A7)
MOVE D7,-(A7)
PEA -26(A6)
JSR F202_xxxx_(PC)
ADDA #12,A7
TST D0
BEQ.S L520
L37T209_061:
MOVE -52(A6),D0
ASR #1,D0
SUB -54(A6),D0
MOVE D0,D4
CMPI #0,D0
SLE D0
AND #1,D0
MOVE D0,-36(A6)
BEQ.S L522
MOVE -32(A6),-(A7)
MOVE -30(A6),-(A7)
MOVE D6,-(A7)
MOVE D7,-(A7)
MOVE -28(A6),-(A7)
JSR F267_dzzz_(PC)
ADDA #10,A7
TST D0
BEQ.S L523
BRA L447(PC)
L523:
MOVE G397_i_Mov(A4),D0
MOVE.B D0,-64(A6)
MOVE G398_i_Mov(A4),D0
MOVE.B D0,-63(A6)
MOVE D7,D0
MOVE.B D0,8(A2)
MOVE D6,D0
MOVE.B D0,9(A2)
MOVE.L G313_ul_Ga(A4),D0
MOVE.B D0,4(A2)
BRA.S L524
L522:
MOVE D4,-52(A6)
MOVE #-1,-54(A6)
L524:
BRA.S L519
L520:
MOVE G390_B_Gro(A4),D0
BEQ.S L525
CMPI #-3,12(A6)
BEQ.S L526
MOVE 14(A3),D0
AND #15,D0
CMPI #5,D0
BNE.S L527
CLR -(A7)
MOVE D6,-(A7)
MOVE D7,-(A7)
PEA -26(A6)
JSR F203_xxxx_(PC)
ADDA #10,A7
TST D0
BEQ.S L527
JSR F028_a000_(PC)
TST D0
BEQ.S L526
L527:
BRA L37T209_044(PC)
L526:
MOVE G306_i_Par(A4),D0
MOVE.B D0,6(A2)
MOVE G307_i_Par(A4),D0
MOVE.B D0,7(A2)
L525:
L518:
MOVE D5,D0
ADDQ #1,D0
AND #3,D0
MOVE D0,D5
CMP D4,D0
BNE L517(PC)
L519:
L516:
MOVE -36(A6),D0
BNE.S L528
CMPI #-1,-54(A6)
BEQ.S L528
MOVE -56(A6),D0
BEQ.S L528
CMPI #-3,12(A6)
BEQ.S L529
JSR F029_AA19_(PC)
TST D0
BNE.S L528
L529:
BRA L37T209_089(PC)
L528:
MOVE -36(A6),D0
BNE.S L531
JSR F029_AA19_(PC)
TST D0
BEQ.S L532
MOVE -34(A6),D0
MOVE -12(A6),D1
LSR #8,D1
AND #15,D1
CMP D1,D0
BHI.S L530
L532:
CMPI #-3,12(A6)
BEQ.S L530
L531:
L37T209_073:
MOVE -36(A6),D0
BNE.S L533
CMPI #0,-54(A6)
BLT.S L533
JSR F029_AA19_(PC)
MOVE D0,D5
L533:
MOVE -48(A6),-(A7)
MOVE -50(A6),-(A7)
MOVE D5,-(A7)
MOVE.L A2,-(A7)
JSR F206_xxxx_(PC)
ADDA #10,A7
L530:
CMPI #-1,12(A6)
BGE.S L534
MOVE -36(A6),D0
BNE.S L535
BRA L447(PC)
L535:
MOVE -46(A6),D0
BEQ.S L536
MOVE #7,D0
AND #15,D0
MOVE D0,D3
ANDI #-16,14(A3)
OR D3,14(A3)
L536:
MOVE D6,-(A7)
MOVE D7,-(A7)
MOVE.L A2,-(A7)
JSR F182_aqzz_(PC)
ADDQ.L #8,A7
L534:
L514:
L513:
BRA L537(PC)
L497:
CMPI #7,D4
BNE L538(PC)
MOVE D6,-(A7)
MOVE D7,-(A7)
MOVE #-1,-(A7)
MOVE.L A3,-(A7)
JSR F200_xxxx_(PC)
ADDA #10,A7
MOVE D0,-34(A6)
BEQ.S L539
MOVE -34(A6),D0
MOVE -12(A6),D1
LSR #4,D1
LSR #8,D1
CMP D1,D0
BHI.S L540
MOVE -30(A6),D0
BEQ.S L541
MOVE -32(A6),D0
BNE.S L540
L541:
BRA L37T209_044(PC)
L540:
L37T209_081:
ADDQ #1,-52(A6)
MOVE -52(A6),D0
ASR #1,D0
MOVE D0,-52(A6)
MOVE G306_i_Par(A4),D0
MOVE.B D0,6(A2)
AND #255,D0
MOVE D0,-30(A6)
MOVE G307_i_Par(A4),D0
MOVE.B D0,7(A2)
AND #255,D0
MOVE D0,-32(A6)
BRA.S L542
L539:
L37T209_082:
MOVE.B 6(A2),D0
AND #255,D0
MOVE D0,-30(A6)
MOVE.B 7(A2),D0
AND #255,D0
MOVE D0,-32(A6)
MOVE D7,D0
CMP -30(A6),D0
BNE.S L543
MOVE D6,D0
CMP -32(A6),D0
BNE.S L543
CLR -36(A6)
MOVE #0,D0
AND #15,D0
MOVE D0,D3
ANDI #-16,14(A3)
OR D3,14(A3)
BRA L37T209_073(PC)
L543:
L542:
MOVE #1,-42(A6)
L37T209_084:
MOVE -32(A6),-(A7)
MOVE -30(A6),-(A7)
MOVE D6,-(A7)
MOVE D7,-(A7)
JSR F228_uzzz_(PC)
ADDQ.L #8,A7
MOVE D0,-38(A6)
L37T209_085:
MOVE -42(A6),-(A7)
MOVE -38(A6),D0
MOVE D0,D5
MOVE D0,-(A7)
MOVE D6,-(A7)
MOVE D7,-(A7)
PEA -26(A6)
JSR F202_xxxx_(PC)
ADDA #12,A7
TST D0
BNE L545(PC)
MOVE -42(A6),D0
BEQ.S L546
JSR F028_a000_(PC)
TST D0
L546:
SNE D0
AND #1,D0
MOVE D0,-(A7)
MOVE G363_i_Sec(A4),D0
MOVE D0,D5
MOVE D0,-(A7)
MOVE D6,-(A7)
MOVE D7,-(A7)
PEA -26(A6)
JSR F202_xxxx_(PC)
ADDA #12,A7
TST D0
BNE.S L545
CLR -(A7)
MOVE D5,D0
ADDQ #2,D0
AND #3,D0
MOVE D0,D5
MOVE D0,-(A7)
MOVE D6,-(A7)
MOVE D7,-(A7)
PEA -26(A6)
JSR F202_xxxx_(PC)
ADDA #12,A7
TST D0
BNE.S L545
JSR F029_AA19_(PC)
TST D0
BNE.S L544
CLR -(A7)
MOVE -38(A6),D0
ADDQ #2,D0
AND #3,D0
MOVE D0,D5
MOVE D0,-(A7)
MOVE D6,-(A7)
MOVE D7,-(A7)
PEA -26(A6)
JSR F202_xxxx_(PC)
ADDA #12,A7
TST D0
BEQ.S L544
L545:
MOVE D7,-30(A6)
MOVE D6,-32(A6)
MOVE D5,D1
ASL.L #1,D1
LEA G233_ai_Gr(A4),A0
ADDA D1,A0
MOVE (A0),D1
MOVE -30(A6),D0
ADD D1,D0
MOVE D0,-30(A6)
MOVE D5,D1
ASL.L #1,D1
LEA G234_ai_Gr(A4),A0
ADDA D1,A0
MOVE (A0),D1
MOVE -32(A6),D0
ADD D1,D0
MOVE D0,-32(A6)
BRA L37T209_061(PC)
L544:
MOVE -56(A6),D0
BEQ L547(PC)
L37T209_089:
CLR -(A7)
MOVE D6,-(A7)
MOVE D7,-(A7)
PEA -26(A6)
JSR F203_xxxx_(PC)
ADDA #10,A7
MOVE -38(A6),D0
MOVE D0,D5
MOVE D0,-(A7)
MOVE D6,-(A7)
MOVE D7,-(A7)
PEA -26(A6)
JSR F204_xxxx_(PC)
ADDA #10,A7
TST D0
BNE.S L549
MOVE G363_i_Sec(A4),D0
MOVE D0,D5
MOVE D0,-(A7)
MOVE D6,-(A7)
MOVE D7,-(A7)
PEA -26(A6)
JSR F204_xxxx_(PC)
ADDA #10,A7
TST D0
BNE.S L549
MOVE G386_ui_Fl(A4),D0
BEQ.S L550
MOVE D5,D0
ADDQ #2,D0
AND #3,D0
MOVE D0,D5
MOVE D0,-(A7)
MOVE D6,-(A7)
MOVE D7,-(A7)
PEA -26(A6)
JSR F204_xxxx_(PC)
ADDA #10,A7
TST D0
BNE.S L549
L550:
CMPI #2,G386_ui_Fl(A4)
BCS.S L548
MOVE -38(A6),D0
ADDQ #2,D0
AND #3,D0
MOVE D0,D5
MOVE D0,-(A7)
MOVE D6,-(A7)
MOVE D7,-(A7)
PEA -26(A6)
JSR F204_xxxx_(PC)
ADDA #10,A7
TST D0
BEQ.S L548
L549:
MOVE D7,-30(A6)
MOVE D6,-32(A6)
MOVE D5,D1
ASL.L #1,D1
LEA G233_ai_Gr(A4),A0
ADDA D1,A0
MOVE (A0),D1
MULS #2,D1
MOVE -30(A6),D0
ADD D1,D0
MOVE D0,-30(A6)
MOVE D5,D1
ASL.L #1,D1
LEA G234_ai_Gr(A4),A0
ADDA D1,A0
MOVE (A0),D1
MULS #2,D1
MOVE -32(A6),D0
ADD D1,D0
MOVE D0,-32(A6)
MOVE #1,-(A7)
MOVE -32(A6),-(A7)
MOVE -30(A6),-(A7)
MOVE #17,-(A7)
JSR F064_aadz_(PC)
ADDQ.L #8,A7
BRA L37T209_061(PC)
L548:
L547:
MOVE -48(A6),-(A7)
MOVE -50(A6),-(A7)
MOVE -38(A6),-(A7)
MOVE.L A2,-(A7)
JSR F206_xxxx_(PC)
ADDA #10,A7
BRA L551(PC)
L538:
CMPI #5,D4
BNE L552(PC)
L37T209_094:
MOVE #1,-42(A6)
MOVE D6,-(A7)
MOVE D7,-(A7)
MOVE #-1,-(A7)
MOVE.L A3,-(A7)
JSR F200_xxxx_(PC)
ADDA #10,A7
MOVE D0,-34(A6)
BEQ.S L553
MOVE G306_i_Par(A4),D0
MOVE.B D0,6(A2)
AND #255,D0
MOVE D0,-30(A6)
MOVE G307_i_Par(A4),D0
MOVE.B D0,7(A2)
AND #255,D0
MOVE D0,-32(A6)
BRA L554(PC)
L553:
AND #255,D0
SUBQ.B #1,5(A2)
MOVE.B 5(A2),D0
BNE.S L555
L37T209_096:
CLR -36(A6)
MOVE #0,D0
AND #15,D0
MOVE D0,D3
ANDI #-16,14(A3)
OR D3,14(A3)
BRA L37T209_073(PC)
L555:
JSR F028_a000_(PC)
TST D0
BEQ.S L556
CLR -(A7)
MOVE D6,-(A7)
MOVE D7,-(A7)
PEA -26(A6)
JSR F203_xxxx_(PC)
ADDA #10,A7
TST D0
BNE.S L557
MOVE D7,D0
MOVE G306_i_Par(A4),D1
SUB D1,D0
MOVE D0,-(A7)
JSR F023_aarz_(PC)
ADDQ.L #2,A7
MOVE.L D0,-(A7)
MOVE D6,D0
MOVE G307_i_Par(A4),D1
SUB D1,D0
MOVE D0,-(A7)
JSR F023_aarz_(PC)
ADDQ.L #2,A7
MOVE.L D0,D1
MOVE.L (A7)+,D0
ADD D1,D0
CMPI #1,D0
BGT.S L558
BRA.S L37T209_096
L558:
L557:
MOVE.B 10(A2),D0
AND #255,D0
MOVE D0,-30(A6)
MOVE.B 11(A2),D0
AND #255,D0
MOVE D0,-32(A6)
BRA L37T209_084(PC)
L556:
MOVE.B 6(A2),D0
AND #255,D0
MOVE D0,-30(A6)
MOVE.B 7(A2),D0
AND #255,D0
MOVE D0,-32(A6)
L554:
MOVE -32(A6),-(A7)
MOVE -30(A6),-(A7)
MOVE D6,-(A7)
MOVE D7,-(A7)
JSR F228_uzzz_(PC)
ADDQ.L #8,A7
ADDQ #2,D0
AND #3,D0
MOVE D0,-38(A6)
MOVE G363_i_Sec(A4),D0
ADDQ #2,D0
AND #3,D0
MOVE D0,G363_i_Sec(A4)
MOVE -52(A6),D0
ASR #2,D0
SUB D0,-52(A6)
BRA L37T209_085(PC)
L552:
L551:
L537:
BRA L559(PC)
L496:
CMPI #5,D4
BNE.S L560
MOVE -50(A6),D0
BEQ.S L561
MOVE D6,-(A7)
MOVE D7,-(A7)
MOVE.L A2,-(A7)
JSR F182_aqzz_(PC)
ADDQ.L #8,A7
L561:
BRA L37T209_094(PC)
L560:
MOVE 12(A6),D0
SUB #38,D0
MOVE D0,D4
LEA 12(A2),A0
ADDA D0,A0
MOVE.B (A0),D0
AND #255,D0
AND #128,D0
BEQ.S L562
CLR -(A7)
MOVE D4,-(A7)
MOVE.L A2,-(A7)
JSR F179_xxxx_(PC)
ADDQ.L #8,A7
MOVE.L D0,-60(A6)
JSR F029_AA19_(PC)
MOVE D0,-90(A6)
MOVE.B -19(A6),D0
AND #255,D0
MOVE D0,D4
ADD -90(A6),D0
SUBQ #1,D0
AND.L #65535,D0
ADD.L D0,-70(A6)
CMPI #15,D4
BLE.S L563
JSR F027_AA59_(PC)
AND #7,D0
SUBQ #2,D0
AND.L #65535,D0
ADD.L D0,-70(A6)
L563:
BRA L564(PC)
L562:
MOVE D4,D0
CMP -50(A6),D0
BLS.S L565
BRA L447(PC)
L565:
MOVE G382_i_Cur(A4),-38(A6)
MOVE D6,-(A7)
MOVE D7,-(A7)
MOVE D4,-(A7)
MOVE.L A3,-(A7)
JSR F200_xxxx_(PC)
ADDA #10,A7
MOVE D0,-34(A6)
BEQ.S L566
MOVE G306_i_Par(A4),D0
MOVE.B D0,6(A2)
MOVE G307_i_Par(A4),D0
MOVE.B D0,7(A2)
L566:
MOVE -50(A6),D0
BNE L567(PC)
CMPI #2,-48(A6)
BEQ L567(PC)
JSR F027_AA59_(PC)
MOVE D0,D5
AND #192,D0
BNE L567(PC)
MOVE.B 3(A2),D0
AND #255,D0
CMP #255,D0
BEQ.S L568
MOVE D5,D0
AND #56,D0
BEQ.S L569
MOVE.B #-1,3(A2)
BRA.S L570
L569:
MOVE.B 3(A2),D0
AND #255,D0
AND #3,D0
MOVE D5,D1
AND #1,D1
BEQ.S L571
MOVE #1,D1
BRA.S L572
L571:
MOVE #-1,D1
L572:
ADD D1,D0
AND #3,D0
MOVE D0,D5
L570:
L568:
MOVE D5,D0
AND #56,D0
BNE.S L573
CMPI #1,-34(A6)
BEQ.S L573
CMPI #0,-48(A6)
BNE.S L573
MOVE.B 3(A2),D0
AND #255,D0
MOVE D0,-(A7)
MOVE D6,-(A7)
MOVE D7,-(A7)
MOVE #-1,-(A7)
JSR F218_ezzz_(PC)
ADDQ.L #8,A7
TST D0
BEQ.S L574
CMPI #2,G364_i_Cre(A4)
BNE.S L574
BRA L447(PC)
L574:
MOVE D5,D0
AND #3,D0
MOVE.B D0,3(A2)
L573:
L567:
MOVE -34(A6),D0
BEQ L575(PC)
MOVE -24(A6),D0
AND #4,D0
BNE.S L576
MOVE.B 2(A2),D0
MOVE D4,D1
ASL #1,D1
AND #255,D0
ASR D1,D0
AND #3,D0
CMP -38(A6),D0
BNE L575(PC)
L576:
MOVE -34(A6),D0
MOVE -12(A6),D1
LSR #4,D1
LSR #8,D1
MOVE D1,D5
CMP D1,D0
BGT L577(PC)
MOVE -30(A6),D0
BEQ.S L578
MOVE -32(A6),D0
BNE L577(PC)
L578:
JSR F027_AA59_(PC)
AND #15,D0
ADDQ #1,D0
MOVE D0,-100(A6)
MOVE D5,D0
CMP -100(A6),D0
BHI L577(PC)
CMPI #1,D5
BNE L579(PC)
MOVE -24(A6),D0
MOVE D0,D5
AND #8,D0
BEQ.S L580
JSR F029_AA19_(PC)
TST D0
BEQ.S L580
MOVE D5,D0
AND #16,D0
BNE L579(PC)
L580:
CMPI #0,-48(A6)
BNE L579(PC)
MOVE.B 3(A2),D0
AND #255,D0
CMP #255,D0
BEQ L579(PC)
MOVE.B 3(A2),D0
MOVE D4,D1
ASL #1,D1
AND #255,D0
ASR D1,D0
AND #3,D0
MOVE D0,D5
CMP -38(A6),D0
BEQ L579(PC)
MOVE D5,D0
MOVE -38(A6),D1
ADDQ #1,D1
AND #3,D1
CMP D1,D0
BEQ L579(PC)
MOVE -50(A6),D0
BNE.S L581
JSR F028_a000_(PC)
TST D0
BEQ.S L581
MOVE.B #-1,3(A2)
BRA L582(PC)
L581:
MOVE -38(A6),D0
AND #1,D0
MOVE D5,D1
AND #1,D1
CMP D1,D0
BNE.S L583
SUBQ #1,D5
BRA.S L584
L583:
ADDQ #1,D5
L584:
MOVE D5,D0
AND #3,D0
MOVE D0,D5
MOVE D0,-(A7)
MOVE.L A3,-(A7)
JSR F176_avzz_(PC)
ADDQ.L #6,A7
TST D0
BEQ.S L586
JSR F028_a000_(PC)
TST D0
BEQ.S L585
MOVE D5,D0
ADDQ #2,D0
AND #3,D0
MOVE D0,D5
MOVE D0,-(A7)
MOVE.L A3,-(A7)
JSR F176_avzz_(PC)
ADDQ.L #6,A7
TST D0
BNE.S L585
L586:
MOVE.B 3(A2),D0
AND #255,D0
MOVE D0,-(A7)
MOVE D6,-(A7)
MOVE D7,-(A7)
MOVE #-1,-(A7)
JSR F218_ezzz_(PC)
ADDQ.L #8,A7
TST D0
BEQ.S L587
CMPI #2,G364_i_Cre(A4)
BNE.S L587
BRA L447(PC)
L587:
CMPI #1,G364_i_Cre(A4)
BEQ.S L588
MOVE D5,-(A7)
MOVE D4,-(A7)
MOVE.B 3(A2),D0
AND #255,D0
MOVE D0,-(A7)
JSR F178_aazz_(PC)
ADDQ.L #6,A7
MOVE.B D0,3(A2)
L588:
L585:
L582:
JSR F028_a000_(PC)
MOVE.L D0,D1
MOVE.B -20(A6),D0
AND #255,D0
ASR #1,D0
ADD D1,D0
MOVE D0,-(A7)
MOVE #1,-(A7)
JSR F025_aatz_(PC)
ADDQ.L #4,A7
EXT.L D0
ADD.L D0,-70(A6)
MOVE 12(A6),D0
MOVE.B D0,-66(A6)
BRA L37T209_135(PC)
L579:
MOVE D4,-(A7)
MOVE D6,-(A7)
MOVE D7,-(A7)
MOVE.L A3,-(A7)
JSR F207_xxxx_(PC)
ADDA #10,A7
MOVE D0,-(A7)
MOVE D4,-(A7)
MOVE.L A2,-(A7)
JSR F179_xxxx_(PC)
ADDQ.L #8,A7
MOVE.L D0,-60(A6)
JSR F028_a000_(PC)
MOVE D0,-110(A6)
MOVE -6(A6),D0
AND #15,D0
ADD -110(A6),D0
AND.L #65535,D0
ADD.L D0,-70(A6)
BRA.S L589
L577:
MOVE #7,D0
AND #15,D0
MOVE D0,D3
ANDI #-16,14(A3)
OR D3,14(A3)
MOVE -50(A6),D0
BEQ.S L590
MOVE D6,-(A7)
MOVE D7,-(A7)
MOVE.L A2,-(A7)
JSR F182_aqzz_(PC)
ADDQ.L #8,A7
L590:
BRA L37T209_081(PC)
L589:
BRA L591(PC)
L575:
MOVE D6,-(A7)
MOVE D7,-(A7)
MOVE #-1,-(A7)
MOVE.L A3,-(A7)
JSR F200_xxxx_(PC)
ADDA #10,A7
TST D0
BEQ.S L592
MOVE G306_i_Par(A4),D0
MOVE.B D0,6(A2)
MOVE G307_i_Par(A4),D0
MOVE.B D0,7(A2)
MOVE -50(A6),D0
BEQ.S L593
CMPI #1,-48(A6)
SEQ D0
TST.B D0
L593:
SNE D0
AND #1,D0
MOVE D0,-(A7)
MOVE D4,-(A7)
MOVE -38(A6),-(A7)
MOVE.L A2,-(A7)
JSR F205_xxxx_(PC)
ADDA #10,A7
ADDQ.L #2,-70(A6)
MOVE.L -70(A6),D0
AND.L #16777215,D0
MOVE.L D0,-60(A6)
BRA.S L594
L592:
MOVE #7,D0
AND #15,D0
MOVE D0,D3
ANDI #-16,14(A3)
OR D3,14(A3)
MOVE -50(A6),D0
BEQ.S L595
MOVE D6,-(A7)
MOVE D7,-(A7)
MOVE.L A2,-(A7)
JSR F182_aqzz_(PC)
ADDQ.L #8,A7
L595:
BRA L37T209_082(PC)
L594:
L591:
L564:
MOVE 12(A6),D0
MOVE.B D0,-66(A6)
BRA.S L37T209_136
L559:
JSR F029_AA19_(PC)
ADD -52(A6),D0
SUBQ #1,D0
MOVE D0,-(A7)
MOVE #1,-(A7)
JSR F025_aatz_(PC)
ADDQ.L #4,A7
EXT.L D0
ADD.L D0,-70(A6)
L37T209_134:
MOVE.B #37,-66(A6)
L494:
L37T209_135:
MOVE.L -60(A6),D0
BNE.S L596
CLR -(A7)
MOVE #-1,-(A7)
MOVE.L A2,-(A7)
JSR F179_xxxx_(PC)
ADDQ.L #8,A7
MOVE.L D0,-60(A6)
L596:
L37T209_136:
MOVE -40(A6),D0
BEQ.S L597
MOVE 14(A6),D0
AND.L #65535,D0
ADD.L D0,-70(A6)
BRA.S L598
L597:
MOVE 14(A6),D0
AND.L #65535,D0
ADD.L D0,-60(A6)
L598:
MOVE.L -60(A6),-(A7)
PEA -70(A6)
JSR F208_xxxx_(PC)
ADDQ.L #8,A7
L447:
MOVEM.L (A7)+,D4-D7/A2-A3
UNLK A6
RTS
L$446: .EQU #-110
| 0 | 0.851562 | 1 | 0.851562 | game-dev | MEDIA | 0.662745 | game-dev | 0.981889 | 1 | 0.981889 |
didimoinc/didimo-digital-human-unity-sdk | 6,098 | com.didimo.sdk.core/Runtime/Scripts/Utility/ID/ShortId.cs | using System;
using System.Text;
namespace Didimo.DarkestFayte
{
/*
MIT License
Copyright (c) 2017 Bolorunduro Winner-Timothy B
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.
*/
public static class ShortId
{
private const string UPPERS = "ABCDEFGHIJKLMNOPQRSTUVWXY";
private const string LOWERS = "abcdefghjlkmnopqrstuvwxyz";
private const string NUMBERS = "0123456789";
private const string SPECIALS = "-_";
// app variables
private static Random random = new Random();
private static string pool = $"{LOWERS}{UPPERS}";
// thread management variables
private static readonly object ThreadLock = new object();
/// <summary>
/// Resets the random number generator and character set
/// </summary>
public static void Reset()
{
lock (ThreadLock)
{
random = new Random();
pool = $"{LOWERS}{UPPERS}";
}
}
/// <summary>
/// Generates a random string of varying length with special characters and without numbers
/// </summary>
/// <param name="useNumbers">Whether or not to include numbers</param>
/// <param name="useSpecial">Whether or not special characters are included</param>
/// <returns>A random string</returns>
public static string Generate(bool useNumbers = false, bool useSpecial = true)
{
int length = random.Next(7, 15);
return Generate(useNumbers, useSpecial, length);
}
/// <summary>
/// Generates a random string of a specified length with the option to add numbers and special characters
/// </summary>
/// <param name="useNumbers">Whether or not numbers are included in the string</param>
/// <param name="useSpecial">Whether or not special characters are included</param>
/// <param name="length">The length of the generated string</param>
/// <returns>A random string</returns>
public static string Generate(bool useNumbers, bool useSpecial, int length)
{
if (length < 7)
{
throw new ArgumentException($"The specified length of {length} is less than the lower limit of 7.");
}
string __pool;
Random rand;
lock (ThreadLock)
{
__pool = ShortId.pool;
rand = random;
}
StringBuilder poolBuilder = new StringBuilder(__pool);
if (useNumbers)
{
poolBuilder.Append(NUMBERS);
}
if (useSpecial)
{
poolBuilder.Append(SPECIALS);
}
string pool = poolBuilder.ToString();
char[] output = new char[length];
for (int i = 0; i < length; i++)
{
int charIndex = rand.Next(0, pool.Length);
output[i] = pool[charIndex];
}
return new string(output);
}
/// <summary>
/// Generates a random string of a specified length with special characters and without numbers
/// </summary>
/// <param name="length">The length of the generated string</param>
/// <returns>A random string</returns>
public static string Generate(int length) => Generate(false, true, length);
/// <summary>
/// Changes the character set that id's are generated from
/// </summary>
/// <param name="characters">The new character set</param>
/// <exception cref="InvalidOperationException">Thrown when the new character
/// set is less than 20 characters</exception>
public static void SetCharacters(string characters)
{
if (string.IsNullOrWhiteSpace(characters))
{
throw new ArgumentException("The replacement characters must not be null or empty.");
}
StringBuilder stringBuilder = new StringBuilder();
foreach (char character in characters)
{
if (!char.IsWhiteSpace(character))
{
stringBuilder.Append(character);
}
}
if (stringBuilder.Length < 20)
{
throw new InvalidOperationException("The replacement characters must be at "
+ "least 20 letters in length and without whitespace.");
}
pool = stringBuilder.ToString();
}
/// <summary>
/// Sets the seed that the random generator works with.
/// </summary>
/// <param name="seed">The seed for the random number generator</param>
public static void SetSeed(int seed)
{
lock (ThreadLock)
{
random = new Random(seed);
}
}
}
} | 0 | 0.91994 | 1 | 0.91994 | game-dev | MEDIA | 0.691578 | game-dev | 0.902924 | 1 | 0.902924 |
baileyholl/Ars-Nouveau | 3,433 | src/main/java/com/hollingsworth/arsnouveau/api/registry/PotionProviderRegistry.java | package com.hollingsworth.arsnouveau.api.registry;
import com.hollingsworth.arsnouveau.api.potion.IPotionProvider;
import com.hollingsworth.arsnouveau.setup.registry.DataComponentRegistry;
import com.hollingsworth.arsnouveau.setup.registry.ItemsRegistry;
import net.minecraft.core.component.DataComponents;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.*;
import net.minecraft.world.item.alchemy.PotionContents;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nullable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
public class PotionProviderRegistry {
private static final ConcurrentHashMap<Item, Function<ItemStack, IPotionProvider>> MAP = new ConcurrentHashMap<>();
private static final IPotionProvider DEFAULT = new IPotionProvider() {
@Override
@NotNull
public PotionContents getPotionData(ItemStack stack) {
return stack.getOrDefault(DataComponents.POTION_CONTENTS, PotionContents.EMPTY);
}
@Override
public int usesRemaining(ItemStack stack) {
PotionContents contents = stack.get(DataComponents.POTION_CONTENTS);
if (contents == null) {
return 0;
}
return contents == PotionContents.EMPTY ? 0 : 1;
}
@Override
public int maxUses(ItemStack stack) {
return 1;
}
@Override
public void consumeUses(ItemStack stack, int amount, @Nullable LivingEntity entity) {
if (stack.getItem() instanceof PotionItem potionItem) {
if (entity instanceof Player player) {
if (!player.hasInfiniteMaterials()) {
stack.shrink(1);
}
player.inventory.add(new ItemStack(Items.GLASS_BOTTLE));
} else {
stack.shrink(1);
}
}
}
@Override
public void addUse(ItemStack stack, int amount, @Nullable LivingEntity entity) {
if (stack.getItem() instanceof BottleItem bottleItem) {
ItemStack bottle = new ItemStack(Items.GLASS_BOTTLE);
bottle.set(DataComponents.POTION_CONTENTS, stack.get(DataComponents.POTION_CONTENTS));
if (entity instanceof Player player) {
if (!player.hasInfiniteMaterials()) {
stack.shrink(1);
}
player.inventory.add(bottle);
}
}
}
@Override
public void setData(PotionContents contents, int usesRemaining, int maxUses, ItemStack stack) {
stack.set(DataComponents.POTION_CONTENTS, contents);
}
};
static {
MAP.put(ItemsRegistry.POTION_FLASK.asItem(), (stack) -> stack.get(DataComponentRegistry.MULTI_POTION));
MAP.put(ItemsRegistry.POTION_FLASK_AMPLIFY.asItem(), (stack) -> stack.get(DataComponentRegistry.MULTI_POTION));
MAP.put(ItemsRegistry.POTION_FLASK_EXTEND_TIME.asItem(), (stack) -> stack.get(DataComponentRegistry.MULTI_POTION));
MAP.put(Items.POTION, (stack) -> DEFAULT);
}
public static @Nullable IPotionProvider from(ItemStack stack) {
return MAP.getOrDefault(stack.getItem(), (item) -> null).apply(stack);
}
}
| 0 | 0.886499 | 1 | 0.886499 | game-dev | MEDIA | 0.996472 | game-dev | 0.964143 | 1 | 0.964143 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.