Name | Type | is_array | initial_value |
ACE_SummonedUnit_UT | unitcode | Yes | |
AfterDamageEvent | real | No | |
AnimalHerdGroup | group | No | |
AOEDamageEvent | real | No | |
AOEDamageSource | unit | No | |
ARMOR_TYPE_ETHEREAL | integer | No | |
ARMOR_TYPE_FLESH | integer | No | |
ARMOR_TYPE_METAL | integer | No | |
ARMOR_TYPE_NONE | integer | No | |
ARMOR_TYPE_STONE | integer | No | |
ARMOR_TYPE_WOOD | integer | No | |
ArmorDamageEvent | real | No | |
ArmorTypeDebugStr | string | Yes | |
ATTACK_TYPE_CHAOS | integer | No | |
ATTACK_TYPE_HERO | integer | No | |
ATTACK_TYPE_MAGIC | integer | No | |
ATTACK_TYPE_NORMAL | integer | No | |
ATTACK_TYPE_PIERCE | integer | No | |
ATTACK_TYPE_SIEGE | integer | No | |
ATTACK_TYPE_SPELLS | integer | No | |
AttackTypeDebugStr | string | Yes | |
BOM_AuraSpell_SS | abilcode | Yes | |
BOM_CaptainGroup_UG | group | No | |
CallToArmsGroup | group | No | |
CameraDistance | real | No | |
CameraDistance_Real | real | No | |
CinSkipped | boolean | No | |
CONVERTED_ATTACK_TYPE | attacktype | Yes | |
CONVERTED_DAMAGE_TYPE | damagetype | Yes | |
COTD_HeroSpellUnitType_UT | unitcode | No | |
COTD_SpellUnitType_UT | unitcode | No | |
CR_CallToArms_UL | integer | No | 10 |
CR_CallToArms_UT | unitcode | No | |
CW_CorruptedCapNames_SS | string | Yes | |
CW_CorruptedUnitTypes_UT | unitcode | Yes | |
CW_EndEventTimer_TT | timer | No | |
CW_EventIsEnabled | boolean | No | true |
CW_GhostUnitGroup_UG | group | No | |
CW_SelectedGroupReg_UR | rect | No | |
CW_SpawnGroupTimer_TT | timer | No | |
CW_SpawnRegions_UR | rect | Yes | |
CW_SpiritBlessingTimer_TT | timer | No | |
CW_SpiritBlessingUnit_UB | unit | No | |
DAMAGE_TYPE_ACID | integer | No | |
DAMAGE_TYPE_COLD | integer | No | |
DAMAGE_TYPE_DEATH | integer | No | |
DAMAGE_TYPE_DEFENSIVE | integer | No | |
DAMAGE_TYPE_DEMOLITION | integer | No | |
DAMAGE_TYPE_DISEASE | integer | No | |
DAMAGE_TYPE_DIVINE | integer | No | |
DAMAGE_TYPE_ENHANCED | integer | No | |
DAMAGE_TYPE_FIRE | integer | No | |
DAMAGE_TYPE_FORCE | integer | No | |
DAMAGE_TYPE_LIGHTNING | integer | No | |
DAMAGE_TYPE_MAGIC | integer | No | |
DAMAGE_TYPE_MIND | integer | No | |
DAMAGE_TYPE_NORMAL | integer | No | |
DAMAGE_TYPE_PLANT | integer | No | |
DAMAGE_TYPE_POISON | integer | No | |
DAMAGE_TYPE_SHADOW_STRIKE | integer | No | |
DAMAGE_TYPE_SLOW_POISON | integer | No | |
DAMAGE_TYPE_SONIC | integer | No | |
DAMAGE_TYPE_SPIRIT_LINK | integer | No | |
DAMAGE_TYPE_UNIVERSAL | integer | No | |
DAMAGE_TYPE_UNKNOWN | integer | No | |
DamageEngineEnabled | boolean | No | |
DamageEvent | real | No | |
DamageEventAmount | real | No | |
DamageEventAOE | integer | No | |
DamageEventAOEGroup | group | No | |
DamageEventArmorPierced | real | No | |
DamageEventArmorT | integer | No | |
DamageEventAttackT | integer | No | |
DamageEventDamageT | integer | No | |
DamageEventDefenseT | integer | No | |
DamageEventLevel | integer | No | |
DamageEventOverride | boolean | No | |
DamageEventPrevAmt | real | No | |
DamageEventSource | unit | No | |
DamageEventTarget | unit | No | |
DamageEventType | integer | No | |
DamageEventUserAmt | real | No | |
DamageEventWeaponT | integer | No | |
DamageFilterAttackT | integer | No | |
DamageFilterConfigured | boolean | No | |
DamageFilterDamageT | integer | No | |
DamageFilterFailChance | real | No | |
DamageFilterMinAmount | real | No | |
DamageFilterRunChance | real | No | |
DamageFilterSource | unit | No | |
DamageFilterSourceA | abilcode | No | |
DamageFilterSourceB | buffcode | No | |
DamageFilterSourceC | integer | No | |
DamageFilterSourceI | itemcode | No | |
DamageFilterSourceT | unitcode | No | |
DamageFilterTarget | unit | No | |
DamageFilterTargetA | abilcode | No | |
DamageFilterTargetB | buffcode | No | |
DamageFilterTargetC | integer | No | |
DamageFilterTargetI | itemcode | No | |
DamageFilterTargetT | unitcode | No | |
DamageFilterType | integer | No | |
DamageModifierEvent | real | No | |
DamageScalingUser | real | No | |
DamageScalingWC3 | real | No | |
DamageTypeBlocked | integer | No | |
DamageTypeCode | integer | No | |
DamageTypeCriticalStrike | integer | No | |
DamageTypeDebugStr | string | Yes | |
DamageTypeExplosive | integer | No | |
DamageTypeHeal | integer | No | |
DamageTypePure | integer | No | |
DamageTypePureExplosive | integer | No | |
DamageTypeReduced | integer | No | |
DarrowshireGuards | group | No | |
DarrowshireRain | weathereffect | No | |
DC_EndEventTimer_TT | timer | No | |
DC_GreenFogEffect_WA | weathereffect | Yes | |
DC_GreenFogEffect_WE | weathereffect | No | |
DC_IsEventEnabled | boolean | No | true |
DC_SelectedVictim_UU | unit | No | |
DC_ZombiefiedGroup_UG | group | No | |
DC_ZombifyUnitTimer_TT | timer | No | |
DD_BattleTimerStarted | boolean | No | |
DD_BrutalDifficultySelected | boolean | No | |
DD_CratesDoodad_Array | destructable | Yes | |
DD_EasyDifficultySelected | boolean | No | |
DD_HardDifficultySelected | boolean | No | |
DD_MapRestartCircle_CC | integer | No | |
DD_MapRestartCircle_PR_II | integer | No | |
DD_MapRestartCircle_PR_TA | string | Yes | |
DD_NormalDifficultySelected | boolean | No | |
DD_UndeadKillCount_CC | integer | No | |
DD_UndeadKillMax_MC | integer | No | |
DE_EvilKelen_Respawn_TT | timer | No | |
DE_EvilKellen_ST_TT | timer | No | |
DE_EvilKellenTW | timerdialog | No | |
DE_EvilModi_Respawn_TT | timer | No | |
DE_EvilModi_ST_TT | timer | No | |
DE_EvilModiTW | timerdialog | No | |
DE_EvilRedpath_Respawn_TT | timer | No | |
DE_EvilRedpath_ST_TT | timer | No | |
DE_EvilRedpathTW | timerdialog | No | |
DE_HorgusHero_Unit | unit | No | |
DE_HorgusRespawn_TT | timer | No | |
DE_HorgusRespawnPoint | location | No | |
DE_HorgusShadow | unit | No | |
DE_HorgusSpawnTimer_TT | timer | No | |
DE_HorgusTimerWindow_TW | timerdialog | No | |
DE_KelenRespawnPoint | location | No | |
DE_KelenResVisibility | fogmodifier | No | |
DE_KelenShadow | unit | No | |
DE_MardukHero_Unit | unit | No | |
DE_MardukRespawn_TT | timer | No | |
DE_MardukRespawnPoint | location | No | |
DE_MardukResVisibility | fogmodifier | No | |
DE_MardukShadow | unit | No | |
DE_MardukSpawnTimer_TT | timer | No | |
DE_MardukTimerWindow_TW | timerdialog | No | |
DE_ModiRespawnPoint | location | No | |
DE_ModiResVisibility | fogmodifier | No | |
DE_ModiShadow | unit | No | |
DE_MultiboardEnemy_CE | unitcode | No | |
DE_MultiboardEnemy_E01 | unitcode | No | |
DE_MultiboardEnemy_E02 | unitcode | No | |
DE_MultiboardEnemy_GE | unitcode | No | |
DE_MultiboardEnemy_HE | unitcode | No | |
DE_MultiboardEnemy_SE | unitcode | No | |
DE_MultiboardEnemy_ZE | unitcode | No | |
DE_RedpathRespawnPoint | location | No | |
DE_RedpathResVisibility | fogmodifier | No | |
DE_RedpathShadow | unit | No | |
DE_ScrougeUpgrade_TT | timer | No | |
DE_UndeadCultist_ST | timer | No | |
DE_UndeadCultist_TT | timer | No | |
DE_UndeadElite01_ST | timer | No | |
DE_UndeadElite01_TT | timer | No | |
DE_UndeadElite02_ST | timer | No | |
DE_UndeadElite02_TT | timer | No | |
DE_UndeadEnemy_CT | unitcode | Yes | |
DE_UndeadEnemy_E01 | unitcode | Yes | |
DE_UndeadEnemy_E02 | unitcode | Yes | |
DE_UndeadEnemy_GT | unitcode | Yes | |
DE_UndeadEnemy_HT | unitcode | Yes | |
DE_UndeadEnemy_ST | unitcode | Yes | |
DE_UndeadEnemy_ZT | unitcode | Yes | |
DE_UndeadGhost_ST | timer | No | |
DE_UndeadGhost_TT | timer | No | |
DE_UndeadGhoul_ST | timer | No | |
DE_UndeadGhoul_TT | timer | No | |
DE_UndeadSkeleton_ST | timer | No | |
DE_UndeadSpawnRect_A | rect | Yes | |
DE_UndeadZombie_ST | timer | No | |
DE_UndeadZombie_TT | timer | No | |
DE_VectusHero_Unit | unit | No | |
DE_VectusRespawn_TT | timer | No | |
DE_VectusRespawnPoint | location | No | |
DE_VectusResVisibility | fogmodifier | No | |
DE_VectusShadow | unit | No | |
DE_VectusSpawnTimer_TT | timer | No | |
DE_VectusTimerWindom_TW | timerdialog | No | |
DE_VisionDummyUnit_UU | unit | No | |
DE_XorgusResVisibility | fogmodifier | No | |
DEFENSE_TYPE_DIVINE | integer | No | |
DEFENSE_TYPE_FORTIFIED | integer | No | |
DEFENSE_TYPE_HEAVY | integer | No | |
DEFENSE_TYPE_HERO | integer | No | |
DEFENSE_TYPE_LIGHT | integer | No | |
DEFENSE_TYPE_MEDIUM | integer | No | |
DEFENSE_TYPE_NORMAL | integer | No | |
DEFENSE_TYPE_UNARMORED | integer | No | |
DefenseTypeDebugStr | string | Yes | |
DefilementBonus01 | abilcode | No | |
DefilementBonus02 | abilcode | No | |
DefilementBonus03 | abilcode | No | |
DefilementBonus04 | abilcode | No | |
DefilementBonus05 | abilcode | No | |
DefilementGroup | group | No | |
DefilementTarget | unit | No | |
DM_CultistName_AA | string | Yes | |
DM_CultKillCount | integer | No | |
DM_CultRandom_INT | integer | No | |
DM_E01KillCount | integer | No | |
DM_E02KillCount | integer | No | |
DM_Elite01Name_AA | string | Yes | |
DM_Elite01Random_INT | integer | No | |
DM_Elite02Name_AA | string | Yes | |
DM_Elite02Random_INT | integer | No | |
DM_EventString_01 | string | No | |
DM_EventString_02 | string | No | |
DM_EventString_03 | string | No | |
DM_EventString_04 | string | No | |
DM_EventString_05 | string | No | |
DM_GhostKillCount | integer | No | |
DM_GhostName_AA | string | Yes | |
DM_GhostRandom_INT | integer | No | |
DM_GhoulKillCount | integer | No | |
DM_GhoulName_AA | string | Yes | |
DM_GhoulRandom_INT | integer | No | |
DM_HorgusHero_H01 | string | No | |
DM_HorgusKillCount | integer | No | |
DM_KelenHero_C02 | string | No | |
DM_KelenKillCount | integer | No | |
DM_MardukHero_H02 | string | No | |
DM_MardukKillCount | integer | No | |
DM_ModiHero_C03 | string | No | |
DM_ModiKillCount | integer | No | |
DM_MultiboardDifficulty_MM | string | No | |
DM_MultiboardName_MM | string | No | |
DM_RedpathHero_C01 | string | No | |
DM_RedpathKillCount | integer | No | |
DM_SkeletonKillCount | integer | No | |
DM_SkeletonName_AA | string | Yes | |
DM_SkeletonRandom_INT | integer | No | |
DM_SummonsKillCount | integer | No | |
DM_UndeadCultist_UT | string | No | |
DM_UndeadElite_UT01 | string | No | |
DM_UndeadElite_UT02 | string | No | |
DM_UndeadGhost_UT | string | No | |
DM_UndeadGhoul_UT | string | No | |
DM_UndeadMulitboard_MM | multiboard | No | |
DM_UndeadSkeleton_UT | string | No | |
DM_UndeadZombie_UT | string | No | |
DM_VectusHero_H03 | string | No | |
DM_VectusKillCount | integer | No | |
DM_ZombieKillCount | integer | No | |
DM_ZombieName_AA | string | Yes | |
DM_ZombieRandom_INT | integer | No | |
DP_ArmoryBuilding_UU | unit | No | |
DP_BarricadeBuildingUnit_UA | unit | Yes | |
DP_BarricadeSpawnRegion_RR | rect | Yes | |
DP_BlindageBuildingUnit_UA | unit | Yes | |
DP_BlindageSpawnRegion_RR | rect | Yes | |
DP_BonusEffect_RA | rect | Yes | |
DP_BonusPicker_Unit | unit | No | |
DP_ChildVilliagerUnit_RR | rect | Yes | |
DP_ChildVilliagerUnit_UA | unit | Yes | |
DP_DarrowshireBattleTimer_TT | timer | No | |
DP_DarrowshireBattleTimer_TW | timerdialog | No | |
DP_DavilHero_Unit | unit | No | |
DP_DavilKilled | boolean | No | |
DP_DavilLevel_LL | integer | No | 1 |
DP_DifficultyPicker_Unit | unit | No | |
DP_EasyBattleStart_Unit | unit | No | |
DP_FemaleVilliagerUnit_RR | rect | Yes | |
DP_FemaleVilliagerUnit_UA | unit | Yes | |
DP_FootmanUnit_UA | unit | Yes | |
DP_FootmanUnitFacing_FF | real | Yes | |
DP_KelenHero_Unit | unit | No | |
DP_KelenKilled | boolean | No | |
DP_KelenLevel_LL | integer | No | 2 |
DP_MagicianUnitFacing_FF | real | Yes | |
DP_MilitiaUnit_RR | rect | Yes | |
DP_MilitiaUnit_UA | unit | Yes | |
DP_MilitiaUnitFacing_FF | real | Yes | |
DP_ModiHero_Unit | unit | No | |
DP_ModiLevel_LL | integer | No | 2 |
DP_ModKilled | boolean | No | |
DP_PriestUnitFacing_FF | real | Yes | |
DP_RedpathHero_Unit | unit | No | |
DP_RedpathKilled | boolean | No | |
DP_RedpathLevel_LL | integer | No | 1 |
DP_RiflemanUnit_UA | unit | Yes | |
DP_RiflemanUnitFacing_FF | real | Yes | |
DP_RiflementUnit_RR | rect | Yes | |
DP_SetPicker_Unit | unit | No | |
DP_Surv_Seconds | real | No | |
DP_Survived_TT | timer | No | |
DP_Survived_TW | timerdialog | No | |
DP_Survived_UT | timer | No | |
DP_TentBuilding_RR | rect | Yes | |
DP_TentBuilding_UA | unit | Yes | |
DP_TowerBuildingUnit_UA | unit | Yes | |
DP_TowerSpawnRegion_RR | rect | Yes | |
DP_TownHallBuilding_UU | unit | No | |
DP_VictoryBoolean_BB | boolean | No | |
DP_WarriorUnit_RR | rect | Yes | |
DP_WarriorUnit_UA | unit | Yes | |
DP_WarriorUnitFacing_FF | real | Yes | |
EmergencyPromotion_HH | real | No | |
EmergencyPromotion_UG | group | No | |
EnhancedDamageTarget | unit | No | |
EventTimeStart | real | No | |
EvilAllianceHeroRespawn | real | No | |
FP_EventIsEnabled | boolean | No | true |
FP_EventTimer_TT | timer | No | |
FP_PeasantGroup_UG | group | No | |
FP_PeasantSpawn_TT | timer | No | |
FP_PeasantSR_UI | integer | No | |
FP_PeasantType_UT | unitcode | Yes | |
HeroPaladin_IncreaseCR | integer | No | 50 |
HF_AnimalEliteTypes_UT | unitcode | Yes | |
HF_AnimalEnemyTypes_UT | unitcode | Yes | |
HF_AnimalGroup_UG | group | No | |
HF_AnimalSpawnRandom_IR | integer | No | |
HF_ChooseAnimalType_IR | integer | No | |
HF_EndEventTimer_TT | timer | No | |
HF_EventIsEnabled | boolean | No | true |
HF_EventReward_EI | integer | No | |
HF_SpawnAnimalElite_TT | timer | No | |
HF_SpawnUndeadAnimals_TT | timer | No | |
HintWasShowed | boolean | No | |
HorgusIsNext | boolean | No | |
HorgusKillcount | real | No | |
IB_BarnQuestMarker_QM | minimapicon | No | |
IB_CratesSpawnPoint_PP | location | No | |
IB_CratesUnitGroup_UG | group | No | |
IB_EndEventTimer_TT | timer | No | |
IB_InfestedBarnZone_ZZ | rect | No | |
IB_InfestedUnitsGroup_UG | group | No | |
IB_IsEventEnabled | boolean | No | true |
IB_RatsSpawnTimer_TT | timer | No | |
IB_SpawnCratesTimer_TT | timer | No | |
InCinema | boolean | No | |
IsDamageAttack | boolean | No | |
IsDamageCode | boolean | No | |
IsDamageMelee | boolean | No | |
IsDamageRanged | boolean | No | |
IsDamageSpell | boolean | No | |
LethalDamageEvent | real | No | |
LethalDamageHP | real | No | |
MapRerun_UnitFacing | real | Yes | |
MapRerun_UnitPositions | location | Yes | |
MardukIsNext | boolean | No | |
ModiDefilementTarget | unit | No | |
MultiboardChangeTimer | timer | No | |
MultiTimer_Minutes | integer | No | |
MultiTimer_Seconds | integer | No | |
NB_CorruptedEnt_IR | itemcode | No | |
NB_CorruptedEnt_UG | group | No | |
NB_CorruptedEnt_UR | integer | No | |
NB_CorruptedEnt_UT | unitcode | Yes | |
NB_EndEventTimer_TT | timer | No | |
NB_EventTimer_TT | timer | No | |
NB_IsEventEnabled | boolean | No | true |
NB_TreeCorruption_ST | timer | No | |
NB_TreeVictim_DD | destructable | No | |
NB_TreeVictim_DR | rect | No | |
NextDamageIsAttack | boolean | No | |
NextDamageIsMelee | boolean | No | |
NextDamageIsRanged | boolean | No | |
NextDamageType | integer | No | |
NextDamageWeaponT | integer | No | |
NR_EndEventTimer_TT | timer | No | |
NR_GhostNecroCaster_UU | unit | No | |
NR_IsEventEnabled_BB | boolean | No | true |
NR_ZombieGroup_ET | group | No | |
NR_ZombieGroupSpawn_P1 | location | No | |
NR_ZombieGroupSpawn_PP | location | No | |
NR_ZombieSpawnType_UT | unitcode | No | |
NR_ZombieSpawnZone_RR | rect | Yes | |
NR_ZombieSpawnZone_T1 | timer | No | |
NR_ZombieSpawnZone_T2 | timer | No | |
OnDamageEvent | real | No | |
PaladinSquad | group | No | |
PC_CaravanEndReg_RR | rect | No | |
PC_CaravanEnemyTypes_UT | unitcode | Yes | |
PC_CaravanGroup_UG | group | No | |
PC_EndEventTimer_TT | timer | No | |
PC_EventIsEnabled | boolean | No | true |
PC_LumberReward_II | integer | No | |
PC_SpawnCaravanTimer_TT | timer | No | |
PD_Consecration_PP | location | No | |
PD_Consecration_TL | integer | No | |
PD_Consecration_UG | group | No | |
PD_Consecration_UT | unitcode | No | |
PlayerRestoreUnits | group | No | |
PlayerUnits | group | No | |
PreDamageEvent | real | No | |
QuestBattleForDarrowshire | quest | No | |
QuestBattleForDarrowshireReq01 | questitem | No | |
QuestBattleForDarrowshireReq02 | questitem | No | |
RandomEventPicker | integer | No | |
RedpathSpecialRespawn | integer | No | |
RedpathSpellPos | location | No | |
RedpathZombieGroup | group | No | |
RemoveDamageEvent | boolean | No | |
ReportLife | real | No | |
RerunDialog | dialog | No | |
RerunDialogButtons | button | Yes | |
SA_EndEventTimer_TT | timer | No | |
SA_IsEventEnabled | boolean | No | true |
SA_ShadowSpawnPoint_SP | location | No | |
SA_ShadowSpawnTimer_TT | timer | No | |
SA_ShadowUnitGroup_UG | group | No | |
SA_ShadowUnitType_UT | unitcode | No | |
SC_CheckEliteDeath | timer | No | |
SC_EliteDeathReward_IT | itemcode | Yes | |
SC_EliteSpawnPoint_PP | location | No | |
SC_EliteUndeadGroup_UG | group | No | |
SC_EliteUndeadType_UT | unitcode | Yes | |
SC_EventIsEnabled | boolean | No | true |
SC_SelectedItemReward_IT | itemcode | No | |
SCA_CultistQuest_QQ | quest | No | |
SCA_CultistQuest_QR | questitem | Yes | |
SCA_CultistQuest_SR | string | Yes | |
SCA_CultistReq01 | string | No | |
SCA_CultistReq02 | string | No | |
SCA_Elite01Quest_QQ | quest | No | |
SCA_Elite01Quest_QR | questitem | Yes | |
SCA_Elite01Quest_SR | string | Yes | |
SCA_Elite02Quest_QQ | quest | No | |
SCA_Elite02Quest_QR | questitem | Yes | |
SCA_Elite02Quest_SR | string | Yes | |
SCA_GhostQuest_QQ | quest | No | |
SCA_GhostQuest_QR | questitem | Yes | |
SCA_GhostQuest_SR | string | Yes | |
SCA_GhostReq01 | string | No | |
SCA_GhostReq02 | string | No | |
SCA_GhoulQuest_QQ | quest | No | |
SCA_GhoulQuest_QR | questitem | Yes | |
SCA_GhoulQuest_SR | string | Yes | |
SCA_GhoulReq01 | string | No | |
SCA_GhoulReq02 | string | No | |
SCA_HorgusQuest_QQ | quest | No | |
SCA_HorgusQuest_QR | questitem | Yes | |
SCA_KelenQuest_QQ | quest | No | |
SCA_KelenQuest_QR | questitem | Yes | |
SCA_MardukQuest_QQ | quest | No | |
SCA_MardukQuest_QR | questitem | Yes | |
SCA_ModiQuest_QQ | quest | No | |
SCA_ModiQuest_QR | questitem | Yes | |
SCA_RedpathQuest_QQ | quest | No | |
SCA_RedpathQuest_QR | questitem | Yes | |
SCA_SkeletonQuest_QQ | quest | No | |
SCA_SkeletonQuest_QR | questitem | Yes | |
SCA_SkeletonQuest_SR | string | Yes | |
SCA_SkeletonReq01 | string | No | |
SCA_SkeletonReq02 | string | No | |
SCA_VectusQuest_QQ | quest | No | |
SCA_VectusQuest_QR | questitem | Yes | |
SCA_ZombieQuest_QQ | quest | No | |
SCA_ZombieQuest_QR | questitem | Yes | |
SCA_ZombieQuest_SR | string | Yes | |
SCA_ZombieReq01 | string | No | |
SCA_ZombieReq02 | string | No | |
ScourgeAssaultStarted | boolean | No | |
ScourgeHeroRespawn | real | No | |
ScourgePlayerGroup | force | No | |
ScourgeUnlockPrimaryTimer | timer | No | |
ScourgeUnlockSecondaryTimer | timer | No | |
ScourgeUpdateTime_RT | real | No | |
SourceDamageEvent | real | No | |
SR_EndEventTimer_TT | timer | No | |
SR_EventReward_IT | itemcode | Yes | |
SR_IsEventEnabled | boolean | No | true |
SR_SelectedStoneRegion_RR | rect | No | |
SR_SkeletonUnitGroup_UG | group | No | |
SR_SkeletonUnitTypes_UT | unitcode | Yes | |
SR_SpawnEliteUnit_TT | timer | No | |
SR_SpawnNormalUnit_TT | timer | No | |
SR_StoneSpawnReg_RR | rect | Yes | |
SR_SummoningStoneUnit_UU | unit | No | |
TempAbilityCode01 | abilcode | No | |
TempAbilityCode02 | abilcode | No | |
TempCaster | unit | No | |
TempDummyUnit01 | unit | No | |
TempPos | location | No | |
TempReal | real | No | |
TempRitualSFX | effect | No | |
TempSpellCode | abilcode | No | |
TempTimer | timer | No | |
TideOfWarCinGroup | group | No | |
TimerEventSelector_TT | timer | No | |
UndeadUnits | group | No | |
UNIT_CLASS_ANCIENT | integer | No | |
UNIT_CLASS_ATTACKS_FLYING | integer | No | |
UNIT_CLASS_ATTACKS_GROUND | integer | No | |
UNIT_CLASS_DEAD | integer | No | |
UNIT_CLASS_ETHEREAL | integer | No | |
UNIT_CLASS_FLYING | integer | No | |
UNIT_CLASS_GIANT | integer | No | |
UNIT_CLASS_GROUND | integer | No | |
UNIT_CLASS_HERO | integer | No | |
UNIT_CLASS_MAGIC_IMMUNE | integer | No | |
UNIT_CLASS_MECHANICAL | integer | No | |
UNIT_CLASS_MELEE | integer | No | |
UNIT_CLASS_PEON | integer | No | |
UNIT_CLASS_PLAGUED | integer | No | |
UNIT_CLASS_POISONED | integer | No | |
UNIT_CLASS_POLYMORPHED | integer | No | |
UNIT_CLASS_RANGED | integer | No | |
UNIT_CLASS_RESISTANT | integer | No | |
UNIT_CLASS_SAPPER | integer | No | |
UNIT_CLASS_SLEEPING | integer | No | |
UNIT_CLASS_SNARED | integer | No | |
UNIT_CLASS_STRUCTURE | integer | No | |
UNIT_CLASS_STUNNED | integer | No | |
UNIT_CLASS_SUMMONED | integer | No | |
UNIT_CLASS_TAUREN | integer | No | |
UNIT_CLASS_TOWNHALL | integer | No | |
UNIT_CLASS_UNDEAD | integer | No | |
VectusIsNext | boolean | No | |
WEAPON_TYPE_AM_CHOP | integer | No | |
WEAPON_TYPE_CH_SLICE | integer | No | |
WEAPON_TYPE_CL_SLICE | integer | No | |
WEAPON_TYPE_CM_SLICE | integer | No | |
WEAPON_TYPE_MH_BASH | integer | No | |
WEAPON_TYPE_MH_CHOP | integer | No | |
WEAPON_TYPE_MH_SLICE | integer | No | |
WEAPON_TYPE_MH_STAB | integer | No | |
WEAPON_TYPE_ML_CHOP | integer | No | |
WEAPON_TYPE_ML_SLICE | integer | No | |
WEAPON_TYPE_MM_BASH | integer | No | |
WEAPON_TYPE_MM_CHOP | integer | No | |
WEAPON_TYPE_MM_SLICE | integer | No | |
WEAPON_TYPE_MM_STAB | integer | No | |
WEAPON_TYPE_NONE | integer | No | |
WEAPON_TYPE_RH_BASH | integer | No | |
WEAPON_TYPE_WH_BASH | integer | No | |
WEAPON_TYPE_WH_SLICE | integer | No | |
WEAPON_TYPE_WL_BASH | integer | No | |
WEAPON_TYPE_WL_SLICE | integer | No | |
WEAPON_TYPE_WL_STAB | integer | No | |
WEAPON_TYPE_WM_BASH | integer | No | |
WEAPON_TYPE_WM_SLICE | integer | No | |
WEAPON_TYPE_WM_STAB | integer | No | |
WeaponTypeDebugStr | string | Yes | |
ZeroDamageEvent | real | No |
---@diagnostic disable: undefined-global
if Debug then Debug.beginFile 'TotalInitialization' end
--[[——————————————————————————————————————————————————————
Total Initialization version 5.3.1
Created by: Bribe
Contributors: Eikonium, HerlySQR, Tasyen, Luashine, Forsakn
Inspiration: Almia, ScorpioT1000, Troll-Brain
Hosted at: https://github.com/BribeFromTheHive/Lua/blob/master/TotalInitialization.lua
Debug library hosted at: https://www.hiveworkshop.com/threads/debug-utils-ingame-console-etc.330758/
————————————————————————————————————————————————————————————]]
---Calls the user's initialization function during the map's loading process. The first argument should either be the init function,
---or it should be the string to give the initializer a name (works similarly to a module name/identically to a vJass library name).
---
---To use requirements, call `Require.strict 'LibraryName'` or `Require.optional 'LibraryName'`. Alternatively, the OnInit callback
---function can take the `Require` table as a single parameter: `OnInit(function(import) import.strict 'ThisIsTheSameAsRequire' end)`.
---
-- - `OnInit.global` or just `OnInit` is called after InitGlobals and is the standard point to initialize.
-- - `OnInit.trig` is called after InitCustomTriggers, and is useful for removing hooks that should only apply to GUI events.
-- - `OnInit.map` is the last point in initialization before the loading screen is completed.
-- - `OnInit.final` occurs immediately after the loading screen has disappeared, and the game has started.
---@class OnInit
--
--Simple Initialization without declaring a library name:
---@overload async fun(initCallback: Initializer.Callback)
--
--Advanced initialization with a library name and an optional third argument to signal to Eikonium's DebugUtils that the file has ended.
---@overload async fun(libraryName: string, initCallback: Initializer.Callback, debugLineNum?: integer)
--
--A way to yield your library to allow other libraries in the same initialization sequence to load, then resume once they have loaded.
---@overload async fun(customInitializerName: string)
OnInit = {}
---@alias Initializer.Callback fun(require?: Requirement | {[string]: Requirement}):...?
---@alias Requirement async fun(reqName: string, source?: table): unknown
-- `Require` will yield the calling `OnInit` initialization function until the requirement (referenced as a string) exists. It will check the
-- global API (for example, does 'GlobalRemap' exist) and then check for any named OnInit resources which might use that same string as its name.
--
-- Due to the way Sumneko's syntax highlighter works, the return value will only be linted for defined @class objects (and doesn't work for regular
-- globals like `TimerStart`). I tried to request the functionality here: https://github.com/sumneko/lua-language-server/issues/1792 , however it
-- was closed. Presumably, there are other requests asking for it, but I wouldn't count on it.
--
-- To declare a requirement, use: `Require.strict 'SomeLibrary'` or (if you don't care about the missing linting functionality) `Require 'SomeLibrary'`
--
-- To optionally require something, use any other suffix (such as `.optionally` or `.nonstrict`): `Require.optional 'SomeLibrary'`
--
---@class Require: { [string]: Requirement }
---@overload async fun(reqName: string, source?: table): string
Require = {}
do
local library = {} --You can change this to false if you don't use `Require` nor the `OnInit.library` API.
--CONFIGURABLE LEGACY API FUNCTION:
---@param _ENV table
---@param OnInit any
local function assignLegacyAPI(_ENV, OnInit)
OnGlobalInit = OnInit; OnTrigInit = OnInit.trig; OnMapInit = OnInit.map; OnGameStart = OnInit.final --Global Initialization Lite API
--OnMainInit = OnInit.main; OnLibraryInit = OnInit.library; OnGameInit = OnInit.final --short-lived experimental API
--onGlobalInit = OnInit; onTriggerInit = OnInit.trig; onInitialization = OnInit.map; onGameStart = OnInit.final --original Global Initialization API
--OnTriggerInit = OnInit.trig; OnInitialization = OnInit.map --Forsakn's Ordered Indices API
end
--END CONFIGURABLES
local _G, rawget, insert =
_G, rawget, table.insert
local initFuncQueue = {}
---@param name string
---@param continue? function
local function runInitializers(name, continue)
--print('running:', name, tostring(initFuncQueue[name]))
if initFuncQueue[name] then
for _,func in ipairs(initFuncQueue[name]) do
coroutine.wrap(func)(Require)
end
initFuncQueue[name] = nil
end
if library then
library:resume()
end
if continue then
continue()
end
end
local function initEverything()
---@param hookName string
---@param continue? function
local function hook(hookName, continue)
local hookedFunc = rawget(_G, hookName)
if hookedFunc then
rawset(_G, hookName,
function()
hookedFunc()
runInitializers(hookName, continue)
end
)
else
runInitializers(hookName, continue)
end
end
hook(
'InitGlobals',
function()
hook(
'InitCustomTriggers',
function()
hook('RunInitializationTriggers')
end
)
end
)
hook(
'MarkGameStarted',
function()
if library then
for _,func in ipairs(library.queuedInitializerList) do
func(nil, true) --run errors for missing requirements.
end
for _,func in pairs(library.yieldedModuleMatrix) do
func(true) --run errors for modules that aren't required.
end
end
OnInit = nil
Require = nil
end
)
end
---@param initName string
---@param libraryName string | Initializer.Callback
---@param func? Initializer.Callback
---@param debugLineNum? integer
---@param incDebugLevel? boolean
local function addUserFunc(initName, libraryName, func, debugLineNum, incDebugLevel)
if not func then
---@cast libraryName Initializer.Callback
func = libraryName
else
assert(type(libraryName) == 'string')
if debugLineNum and Debug then
Debug.beginFile(libraryName, incDebugLevel and 3 or 2)
Debug.data.sourceMap[#Debug.data.sourceMap].lastLine = debugLineNum
end
if library then
func = library:create(libraryName, func)
end
end
assert(type(func) == 'function')
--print('adding user func: ' , initName , libraryName, debugLineNum, incDebugLevel)
initFuncQueue[initName] = initFuncQueue[initName] or {}
insert(initFuncQueue[initName], func)
if initName == 'root' or initName == 'module' then
runInitializers(initName)
end
end
---@param name string
local function createInit(name)
---@async
---@param libraryName string --Assign your callback a unique name, allowing other OnInit callbacks can use it as a requirement.
---@param userInitFunc Initializer.Callback --Define a function to be called at the chosen point in the initialization process. It can optionally take the `Require` object as a parameter. Its optional return value(s) are passed to a requiring library via the `Require` object (defaults to `true`).
---@param debugLineNum? integer --If the Debug library is present, you can call Debug.getLine() for this parameter (which should coincide with the last line of your script file). This will neatly tie-in with OnInit's built-in Debug library functionality to define a starting line and an ending line for your module.
---@overload async fun(userInitFunc: Initializer.Callback)
return function(libraryName, userInitFunc, debugLineNum)
addUserFunc(name, libraryName, userInitFunc, debugLineNum)
end
end
OnInit.global = createInit 'InitGlobals' -- Called after InitGlobals, and is the standard point to initialize.
OnInit.trig = createInit 'InitCustomTriggers' -- Called after InitCustomTriggers, and is useful for removing hooks that should only apply to GUI events.
OnInit.map = createInit 'RunInitializationTriggers' -- Called last in the script's loading screen sequence. Runs after the GUI "Map Initialization" events have run.
OnInit.final = createInit 'MarkGameStarted' -- Called immediately after the loading screen has disappeared, and the game has started.
do
---@param self table
---@param libraryNameOrInitFunc function | string
---@param userInitFunc function
---@param debugLineNum number
local function __call(
self,
libraryNameOrInitFunc,
userInitFunc,
debugLineNum
)
if userInitFunc or type(libraryNameOrInitFunc) == 'function' then
addUserFunc(
'InitGlobals', --Calling OnInit directly defaults to OnInit.global (AKA OnGlobalInit)
libraryNameOrInitFunc,
userInitFunc,
debugLineNum,
true
)
elseif library then
library:declare(libraryNameOrInitFunc) --API handler for OnInit "Custom initializer"
else
error(
"Bad OnInit args: "..
tostring(libraryNameOrInitFunc) .. ", " ..
tostring(userInitFunc)
)
end
end
setmetatable(OnInit --[[@as table]], { __call = __call })
end
do --if you don't need the initializers for 'root', 'config' and 'main', you can delete this do...end block.
local gmt = getmetatable(_G) or
getmetatable(setmetatable(_G, {}))
local rawIndex = gmt.__newindex or rawset
local hookMainAndConfig
---@param _G table
---@param key string
---@param fnOrDiscard unknown
function hookMainAndConfig(_G, key, fnOrDiscard)
if key == 'main' or key == 'config' then
---@cast fnOrDiscard function
if key == 'main' then
runInitializers 'root'
end
rawIndex(_G, key, function()
if key == 'config' then
fnOrDiscard()
elseif gmt.__newindex == hookMainAndConfig then
gmt.__newindex = rawIndex --restore the original __newindex if no further hooks on __newindex exist.
end
runInitializers(key)
if key == 'main' then
fnOrDiscard()
end
end)
else
rawIndex(_G, key, fnOrDiscard)
end
end
gmt.__newindex = hookMainAndConfig
OnInit.root = createInit 'root' -- Runs immediately during the Lua root, but is yieldable (allowing requirements) and pcalled.
OnInit.config = createInit 'config' -- Runs when `config` is called. Credit to @Luashine: https://www.hiveworkshop.com/threads/inject-main-config-from-we-trigger-code-like-jasshelper.338201/
OnInit.main = createInit 'main' -- Runs when `main` is called. Idea from @Tasyen: https://www.hiveworkshop.com/threads/global-initialization.317099/post-3374063
end
if library then
library.queuedInitializerList = {}
library.customDeclarationList = {}
library.yieldedModuleMatrix = {}
library.moduleValueMatrix = {}
function library:pack(name, ...)
self.moduleValueMatrix[name] = table.pack(...)
end
function library:resume()
if self.queuedInitializerList[1] then
local continue, tempQueue, forceOptional
::initLibraries::
repeat
continue=false
self.queuedInitializerList, tempQueue =
{}, self.queuedInitializerList
for _,func in ipairs(tempQueue) do
if func(forceOptional) then
continue=true --Something was initialized; therefore further systems might be able to initialize.
else
insert(self.queuedInitializerList, func) --If the queued initializer returns false, that means its requirement wasn't met, so we re-queue it.
end
end
until not continue or not self.queuedInitializerList[1]
if self.customDeclarationList[1] then
self.customDeclarationList, tempQueue =
{}, self.customDeclarationList
for _,func in ipairs(tempQueue) do
func() --unfreeze any custom initializers.
end
elseif not forceOptional then
forceOptional = true
else
return
end
goto initLibraries
end
end
local function declareName(name, initialValue)
assert(type(name) == 'string')
assert(library.moduleValueMatrix[name] == nil)
library.moduleValueMatrix[name] =
initialValue and { true, n = 1 }
end
function library:create(name, userFunc)
assert(type(userFunc) == 'function')
declareName(name, false) --declare itself as a non-loaded library.
return function()
self:pack(name, userFunc(Require)) --pack return values to allow multiple values to be communicated.
if self.moduleValueMatrix[name].n == 0 then
self:pack(name, true) --No values were returned; therefore simply package the value as `true`
end
end
end
---@async
function library:declare(name)
declareName(name, true) --declare itself as a loaded library.
local co = coroutine.running()
insert(
self.customDeclarationList,
function()
coroutine.resume(co)
end
)
coroutine.yield() --yields the calling function until after all currently-queued initializers have run.
end
local processRequirement
---@async
function processRequirement(
optional,
requirement,
explicitSource
)
if type(optional) == 'string' then
optional, requirement, explicitSource =
true, optional, requirement --optional requirement (processed by the __index method)
else
optional = false --strict requirement (processed by the __call method)
end
local source = explicitSource or _G
assert(type(source)=='table')
assert(type(requirement)=='string')
::reindex::
local subSource, subReq =
requirement:match("([\x25w_]+)\x25.(.+)") --Check if user is requiring using "table.property" syntax
if subSource and subReq then
source,
requirement =
processRequirement(subSource, source), --If the container is nil, yield until it is not.
subReq
if type(source)=='table' then
explicitSource = source
goto reindex --check for further nested properties ("table.property.subProperty.anyOthers").
else
return --The source table for the requirement wasn't found, so disregard the rest (this only happens with optional requirements).
end
end
local function loadRequirement(unpack)
local package = rawget(source, requirement) --check if the requirement exists in the host table.
if not package and not explicitSource then
if library.yieldedModuleMatrix[requirement] then
library.yieldedModuleMatrix[requirement]() --load module if it exists
end
package = library.moduleValueMatrix[requirement] --retrieve the return value from the module.
if unpack and type(package)=='table' then
return table.unpack(package, 1, package.n) --using unpack allows any number of values to be returned by the required library.
end
end
return package
end
local co, loaded
local function checkReqs(forceOptional, printErrors)
if not loaded then
loaded = loadRequirement()
loaded = loaded or optional and
(loaded==nil or forceOptional)
if loaded then
if co then coroutine.resume(co) end --resume only if it was yielded in the first place.
return loaded
elseif printErrors then
coroutine.resume(co, true)
end
end
end
if not checkReqs() then --only yield if the requirement doesn't already exist.
co = coroutine.running()
insert(library.queuedInitializerList, checkReqs)
if coroutine.yield() then
error("Missing Requirement: "..requirement) --handle the error within the user's function to get an accurate stack trace via the `try` function.
end
end
return loadRequirement(true)
end
---@type Requirement
function Require.strict(name, explicitSource)
return processRequirement(nil, name, explicitSource)
end
setmetatable(Require --[[@as table]], {
__call = processRequirement,
__index = function()
return processRequirement
end
})
local module = createInit 'module'
--- `OnInit.module` will only call the OnInit function if the module is required by another resource, rather than being called at a pre-
--- specified point in the loading process. It works similarly to Go, in that including modules in your map that are not actually being
--- required will throw an error message.
---@param name string
---@param func fun(require?: Initializer.Callback):any
---@param debugLineNum? integer
OnInit.module = function(name, func, debugLineNum)
if func then
local userFunc = func
func = function(require)
local co = coroutine.running()
library.yieldedModuleMatrix[name] =
function(failure)
library.yieldedModuleMatrix[name] = nil
coroutine.resume(co, failure)
end
if coroutine.yield() then
error("Module declared but not required: "..name)
end
return userFunc(require)
end
end
module(name, func, debugLineNum)
end
end
if assignLegacyAPI then --This block handles legacy code.
---Allows packaging multiple requirements into one table and queues the initialization for later.
---@deprecated
---@param initList string | table
---@param userFunc function
function OnInit.library(initList, userFunc)
local typeOf = type(initList)
assert(typeOf=='table' or typeOf=='string')
assert(type(userFunc) == 'function')
local function caller(use)
if typeOf=='string' then
use(initList)
else
for _,initName in ipairs(initList) do
use(initName)
end
if initList.optional then
for _,initName in ipairs(initList.optional) do
use.lazily(initName)
end
end
end
end
if initList.name then
OnInit(initList.name, caller)
else
OnInit(caller)
end
end
local legacyTable = {}
assignLegacyAPI(legacyTable, OnInit)
for key,func in pairs(legacyTable) do
rawset(_G, key, func)
end
OnInit.final(function()
for key in pairs(legacyTable) do
rawset(_G, key, nil)
end
end)
end
initEverything()
end
if Debug then Debug.endFile() end
do; local _, codeLoc = pcall(error, "", 2) --get line number where DebugUtils begins.
--[[
--------------------------
-- | Debug Utils 2.0a | --
--------------------------
--> https://www.hiveworkshop.com/threads/debug-utils-ingame-console-etc.330758/
- by Eikonium, with special thanks to:
- @Bribe, for pretty table print, showing that xpcall's message handler executes before the stack unwinds and useful suggestions like name caching and stack trace improvements.
- @Jampion, for useful suggestions like print caching and applying Debug.try to all code entry points
- @Luashine, for useful feedback and building "WC3 Debug Console Paste Helper" (https://github.com/Luashine/wc3-debug-console-paste-helper#readme)
- @HerlySQR, for showing a way to get a stack trace in Wc3 (https://www.hiveworkshop.com/threads/lua-getstacktrace.340841/)
- @Macadamia, for showing a way to print warnings upon accessing undeclared globals, where this all started with (https://www.hiveworkshop.com/threads/lua-very-simply-trick-to-help-lua-users-track-syntax-errors.326266/)
-----------------------------------------------------------------------------------------------------------------------------
| Provides debugging utility for Wc3-maps using Lua. |
| |
| Including: |
| 1. Automatic ingame error messages upon running erroneous code from triggers or timers. |
| 2. Ingame Console that allows you to execute code via Wc3 ingame chat. |
| 3. Automatic warnings upon reading undeclared globals (which also triggers after misspelling globals) |
| 4. Debug-Library functions for manual error handling. |
| 5. Caching of loading screen print messages until game start (which simplifies error handling during loading screen) |
| 6. Overwritten tostring/print-functions to show the actual string-name of an object instead of the memory position. |
| 7. Conversion of war3map.lua-error messages to local file error messages. |
| 8. Other useful debug utility (table.print and Debug.wc3Type) |
-----------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Installation: |
| |
| 1. Copy the code (DebugUtils.lua, StringWidth.lua and IngameConsole.lua) into your map. Use script files (Ctrl+U) in your trigger editor, not text-based triggers! |
| 2. Order the files: DebugUtils above StringWidth above IngameConsole. Make sure they are above ALL other scripts (crucial for local line number feature). |
| 3. Adjust the settings in the settings-section further below to receive the debug environment that fits your needs. |
| |
| Deinstallation: |
| |
| - Debug Utils is meant to provide debugging utility and as such, shall be removed or invalidated from the map closely before release. |
| - Optimally delete the whole Debug library. If that isn't suitable (because you have used library functions at too many places), you can instead replace Debug Utils |
| by the following line of code that will invalidate all Debug functionality (without breaking your code): |
| Debug = setmetatable({try = function(...) return select(2,pcall(...)) end}, {__index = function(t,k) return DoNothing end}); try = Debug.try |
| - If that is also not suitable for you (because your systems rely on the Debug functionality to some degree), at least set ALLOW_INGAME_CODE_EXECUTION to false. |
| - Be sure to test your map thoroughly after removing Debug Utils. |
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
* Documentation and API-Functions:
*
* - All automatic functionality provided by Debug Utils can be deactivated using the settings directly below the documentation.
*
* -------------------------
* | Ingame Code Execution |
* -------------------------
* - Debug Utils provides the ability to run code via chat command from within Wc3, if you have conducted step 3 from the installation section.
* - You can either open the ingame console by typing "-console" into the chat, or directly execute code by typing "-exec <code>".
* - See IngameConsole script for further documentation.
*
* ------------------
* | Error Handling |
* ------------------
* - Debug Utils automatically applies error handling (i.e. Debug.try) to code executed by your triggers and timers (error handling means that error messages are printed on screen, if anything doesn't run properly).
* - You can still use the below library functions for manual debugging.
*
* Debug.try(funcToExecute, ...) / try(funcToExecute, ...) -> ...
* - Calls the specified function with the specified parameters in protected mode (i.e. code after Debug.try will continue to run even if the function fails to execute).
* - If the call is successful, returns the specified function's original return values (so p1 = Debug.try(Player, 0) will work fine).
* - If the call is unsuccessful, prints an error message on screen (including stack trace and parameters you have potentially logged before the error occured)
* - By default, the error message consists of a line-reference to war3map.lua (which you can look into by forcing a syntax error in WE or by exporting it from your map via File -> Export Script).
* You can get more helpful references to local script files instead, see section about "Local script references".
* - Example: Assume you have a code line like "func(param1,param2)", which doesn't work and you want to know why.
* Option 1: Change it to "Debug.try(func, param1, param2)", i.e. separate the function from the parameters.
* Option 2: Change it to "Debug.try(function() return func(param1, param2) end)", i.e. pack it into an anonymous function (optionally skip the return statement).
* Debug.log(...)
* - Logs the specified parameters to the Debug-log. The Debug-log will be printed upon the next error being catched by Debug.try, Debug.assert or Debug.throwError.
* - The Debug-log will only hold one set of parameters per code-location. That means, if you call Debug.log() inside any function, only the params saved within the latest call of that function will be kept.
* Debug.throwError(...)
* - Prints an error message including document, line number, stack trace, previously logged parameters and all specified parameters on screen. Parameters can have any type.
* - In contrast to Lua's native error function, this can be called outside of protected mode and doesn't halt code execution.
* Debug.assert(condition:boolean, errorMsg:string, ...) -> ...
* - Prints the specified error message including document, line number, stack trace and previously logged parameters on screen, IF the specified condition fails (i.e. resolves to false/nil).
* - Returns ..., IF the specified condition holds.
* - This works exactly like Lua's native assert, except that it also works outside of protected mode and does not halt code execution.
* Debug.traceback() -> string
* - Returns the stack trace at the position where this is called. You need to manually print it.
* Debug.getLine([depth: integer]) -> integer?
* - Returns the line in war3map.lua, where this function is executed.
* - You can specify a depth d >= 1 to instead return the line, where the d-th function in the stack trace was called. I.e. depth = 2 will return the line of execution of the function that calls Debug.getLine.
* - Due to Wc3's limited stack trace ability, this might sometimes return nil for depth >= 3, so better apply nil-checks on the result.
* Debug.getLocalErrorMsg(errorMsg:string) -> string
* - Takes an error message containing a file and a linenumber and converts war3map.lua-lines to local document lines as defined by uses of Debug.beginFile() and Debug.endFile().
* - Error Msg must be formatted like "<document>:<linenumber><Rest>".
*
* -----------------------------------
* | Warnings for undeclared globals |
* -----------------------------------
* - DebugUtils will print warnings on screen, if you read an undeclared global variable.
* - This is technically the case, when you misspelled on a function name, like calling CraeteUnit instead of CreateUnit.
* - Keep in mind though that the same warning will pop up after reading a global that was intentionally nilled. If you don't like this, turn of this feature in the settings.
*
* -----------------
* | Print Caching |
* -----------------
* - DebugUtils caches print()-calls occuring during loading screen and delays them to after game start.
* - This also applies to loading screen error messages, so you can wrap erroneous parts of your Lua root in Debug.try-blocks and see the message after game start.
*
* -------------------------
* | Local File Stacktrace |
* -------------------------
* - By default, error messages and stack traces printed by the error handling functionality of Debug Utils contain references to war3map.lua (a big file just appending all your local scripts).
* - The Debug-library provides the two functions below to index your local scripts, activating local file names and line numbers (matching those in your IDE) instead of the war3map.lua ones.
* - This allows you to inspect errors within your IDE (VSCode) instead of the World Editor.
*
* Debug.beginFile(fileName: string [, depth: integer])
* - Tells the Debug library that the specified file begins exactly here (i.e. in the line, where this is called).
* - Using this improves stack traces of error messages. "war3map.lua"-references between <here> and the next Debug.endFile() will be converted to file-specific references.
* - All war3map.lua-lines located between the call of Debug.beginFile(fileName) and the next call of Debug.beginFile OR Debug.endFile are treated to be part of "fileName".
* - !!! To be called in the Lua root in Line 1 of every document you wish to track. Line 1 means exactly line 1, before any comment! This way, the line shown in the trace will exactly match your IDE.
* - Depth can be ignored, except if you want to use a custom wrapper around Debug.beginFile(), in which case you need to set the depth parameter to 1 to record the line of the wrapper instead of the line of Debug.beginFile().
* Debug.endFile([depth: integer])
* - Ends the current file that was previously begun by using Debug.beginFile(). War3map.lua-lines after this will not be converted until the next instance of Debug.beginFile().
* - The next call of Debug.beginFile() will also end the previous one, so using Debug.endFile() is optional. Mainly recommended to use, if you prefer to have war3map.lua-references in a certain part of your script (such as within GUI triggers).
* - Depth can be ignored, except if you want to use a custom wrapper around Debug.endFile(), you need to increase the depth parameter to 1 to record the line of the wrapper instead of the line of Debug.endFile().
*
* ----------------
* | Name Caching |
* ----------------
* - DebugUtils overwrites the tostring-function so that it prints the name of a non-primitive object (if available) instead of its memory position. The same applies to print().
* - For instance, print(CreateUnit) will show "function: CreateUnit" on screen instead of "function: 0063A698".
* - The table holding all those names is referred to as "Name Cache".
* - All names of objects in global scope will automatically be added to the Name Cache both within Lua root and again at game start (to get names for overwritten natives and your own objects).
* - New names entering global scope will also automatically be added, even after game start. The same applies to subtables of _G up to a depth of Debug.settings.NAME_CACHE_DEPTH.
* - Objects within subtables will be named after their parent tables and keys. For instance, the name of the function within T = {{bla = function() end}} is "T[1].bla".
* - The automatic adding doesn't work for objects saved into existing variables/keys after game start (because it's based on __newindex metamethod which simply doesn't trigger)
* - You can manually add names to the name cache by using the following API-functions:
*
* Debug.registerName(whichObject:any, name:string)
* - Adds the specified object under the specified name to the name cache, letting tostring and print output "<type>: <name>" going foward.
* - The object must be non-primitive, i.e. this won't work on strings, numbers and booleans.
* - This will overwrite existing names for the specified object with the specified name.
* Debug.registerNamesFrom(parentTable:table [, parentTableName:string] [, depth])
* - Adds names for all values from within the specified parentTable to the name cache.
* - Names for entries will be like "<parentTableName>.<key>" or "<parentTableName>[<key>]" (depending on the key type), using the existing name of the parentTable from the name cache.
* - You can optionally specify a parentTableName to use that for the entry naming instead of the existing name. Doing so will also register that name for the parentTable, if it doesn't already has one.
* - Specifying the empty string as parentTableName will suppress it in the naming and just register all values as "<key>". Note that only string keys will be considered this way.
* - In contrast to Debug.registerName(), this function will NOT overwrite existing names, but just add names for new objects.
* Debug.oldTostring(object:any) -> string
* - The old tostring-function in case you still need outputs like "function: 0063A698".
*
* -----------------
* | Other Utility |
* -----------------
*
* Debug.wc3Type(object:any) -> string
* - Returns the Warcraft3-type of the input object. E.g. Debug.wc3Type(Player(0)) will return "player".
* - Returns type(object), if used on Lua-objects.
* table.tostring(whichTable [, depth:integer] [, pretty_yn:boolean])
* - Creates a list of all (key,value)-pairs from the specified table. Also lists subtable entries up to the specified depth (unlimited, if not specified).
* - E.g. for T = {"a", 5, {7}}, table.tostring(T) would output '{(1, "a"), (2, 5), (3, {(1, 7)})}' (if using concise style, i.e. pretty_yn being nil or false).
* - Not specifying a depth can potentially lead to a stack overflow for self-referential tables (e.g X = {}; X[1] = X). Choose a sensible depth to prevent this (in doubt start with 1 and test upwards).
* - Supports pretty style by setting pretty_yn to true. Pretty style is linebreak-separated, uses indentations and has other visual improvements. Use it on small tables only, because Wc3 can't show that many linebreaks at once.
* - All of the following is valid syntax: table.tostring(T), table.tostring(T, depth), table.tostring(T, pretty_yn) or table.tostring(T, depth, pretty_yn).
* - table.tostring is not multiplayer-synced.
* table.print(whichTable [, depth:integer] [, pretty_yn:boolean])
* - Prints table.tostring(...).
*
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------]]
----------------
--| Settings |--
----------------
Debug = {
--BEGIN OF SETTINGS--
settings = {
SHOW_TRACE_ON_ERROR = true ---Set to true to show a stack trace on every error in addition to the regular message (msg sources: automatic error handling, Debug.try, Debug.throwError, ...)
, USE_TRY_ON_TRIGGERADDACTION = true ---Set to true for automatic error handling on TriggerAddAction (applies Debug.try on every trigger action).
, USE_TRY_ON_CONDITION = true ---Set to true for automatic error handling on boolexpressions created via Condition() or Filter() (essentially applies Debug.try on every trigger condition).
, USE_TRY_ON_TIMERSTART = true ---Set to true for automatic error handling on TimerStart (applies Debug.try on every timer callback).
, USE_TRY_ON_COROUTINES = true ---Set to true for improved stack traces on errors within coroutines (applies Debug.try on coroutine.create and coroutine.wrap). This lets stack traces point to the erroneous function executed within the coroutine (instead of the function creating the coroutine).
, ALLOW_INGAME_CODE_EXECUTION = false ---Set to true to enable IngameConsole and -exec command.
, WARNING_FOR_UNDECLARED_GLOBALS = true ---Set to true to print warnings upon accessing undeclared globals (i.e. globals with nil-value). This is technically the case after having misspelled on a function name (like CraeteUnit instead of CreateUnit).
, SHOW_TRACE_FOR_UNDECLARED_GLOBALS = false ---Set to true to include a stack trace into undeclared global warnings. Only takes effect, if WARNING_FOR_UNDECLARED_GLOBALS is also true.
, USE_PRINT_CACHE = true ---Set to true to let print()-calls during loading screen be cached until the game starts.
, PRINT_DURATION = nil ---Adjust the duration in seconds that values printed by print() last on screen. Set to nil to use default duration (which depends on string length).
, USE_NAME_CACHE = true ---Set to true to let tostring/print output the string-name of an object instead of its memory location (except for booleans/numbers/strings). E.g. print(CreateUnit) will output "function: CreateUnit" instead of "function: 0063A698".
, AUTO_REGISTER_NEW_NAMES = true ---Automatically adds new names from global scope (and subtables of _G up to NAME_CACHE_DEPTH) to the name cache by adding metatables with the __newindex metamethod to ALL tables accessible from global scope.
, NAME_CACHE_DEPTH = 0 ---Set to 0 to only affect globals. Experimental feature: Set to an integer > 0 to also cache names for subtables of _G (up to the specified depth). Warning: This will alter the __newindex metamethod of subtables of _G (but not break existing functionality).
}
--END OF SETTINGS--
--START OF CODE--
, data = {
nameCache = {} ---@type table<any,string> contains the string names of any object in global scope (random for objects that have multiple names)
, nameCacheMirror = {} ---@type table<string,any> contains the (name,object)-pairs of all objects in the name cache. Used to prevent name duplicates that might otherwise occur upon reassigning globals.
, nameDepths = {} ---@type table<any,integer> contains the depth of the name used by by any object in the name cache (i.e. the depth within the parentTable).
, autoIndexedTables = {} ---@type table<table,boolean> contains (t,true), if DebugUtils already set a __newindex metamethod for name caching in t. Prevents double application.
, paramLog = {} ---@type table<string,string> saves logged information per code location. to be filled by Debug.log(), to be printed by Debug.try()
, sourceMap = {{firstLine= 1,file='DebugUtils'}} ---@type table<integer,{firstLine:integer,file:string,lastLine?:integer}> saves lines and file names of all documents registered via Debug.beginFile().
, printCache = {n=0} ---@type string[] contains the strings that were attempted to print during loading screen.
}
}
--localization
local settings, paramLog, nameCache, nameDepths, autoIndexedTables, nameCacheMirror, sourceMap, printCache = Debug.settings, Debug.data.paramLog, Debug.data.nameCache, Debug.data.nameDepths, Debug.data.autoIndexedTables, Debug.data.nameCacheMirror, Debug.data.sourceMap, Debug.data.printCache
--Write DebugUtils first line number to sourceMap:
---@diagnostic disable-next-line: need-check-nil
Debug.data.sourceMap[1].firstLine = tonumber(codeLoc:match(":\x25d+"):sub(2,-1))
-------------------------------------------------
--| File Indexing for local Error Msg Support |--
-------------------------------------------------
-- Functions for war3map.lua -> local file conversion for error messages.
---Returns the line number in war3map.lua, where this is called (for depth = 0).
---Choose a depth > 0 to instead return the line, where the corresponding function in the stack leading to this call is executed.
---@param depth? integer default: 0.
---@return number?
function Debug.getLine(depth)
depth = depth or 0
local _, location = pcall(error, "", depth + 3) ---@diagnostic disable-next-line: need-check-nil
local line = location:match(":\x25d+") --extracts ":1000" from "war3map.lua:1000:..."
return tonumber(line and line:sub(2,-1)) --check if line is nil before applying string.sub to prevent errors (nil can result from string.match above, although it should never do so in our case)
end
---Tells the Debug library that the specified file begins exactly here (i.e. in the line, where this is called).
---
---Using this improves stack traces of error messages. Stack trace will have "war3map.lua"-references between this and the next Debug.endFile() converted to file-specific references.
---
---To be called in the Lua root in Line 1 of every file you wish to track! Line 1 means exactly line 1, before any comment! This way, the line shown in the trace will exactly match your IDE.
---
---If you want to use a custom wrapper around Debug.beginFile(), you need to increase the depth parameter to 1 to record the line of the wrapper instead of the line of Debug.beginFile().
---@param fileName string
---@param depth? integer default: 0. Set to 1, if you call this from a wrapper (and use the wrapper in line 1 of every document).
---@param lastLine? integer Ignore this. For compatibility with Total Initialization.
function Debug.beginFile(fileName, depth, lastLine)
depth, fileName = depth or 0, fileName or '' --filename is not actually optional, we just default to '' to prevent crashes.
local line = Debug.getLine(depth + 1)
if line then --for safety reasons. we don't want to add a non-existing line to the sourceMap
table.insert(sourceMap, {firstLine = line, file = fileName, lastLine = lastLine}) --automatically sorted list, because calls of Debug.beginFile happen logically in the order of the map script.
end
end
---Tells the Debug library that the file previously started with Debug.beginFile() ends here.
---This is in theory optional to use, as the next call of Debug.beginFile will also end the previous. Still good practice to always use this in the last line of every file.
---If you want to use a custom wrapper around Debug.endFile(), you need to increase the depth parameter to 1 to record the line of the wrapper instead of the line of Debug.endFile().
---@param depth? integer
function Debug.endFile(depth)
depth = depth or 0
local line = Debug.getLine(depth + 1)
sourceMap[#sourceMap].lastLine = line
end
---Takes an error message containing a file and a linenumber and converts both to local file and line as saved to Debug.sourceMap.
---@param errorMsg string must be formatted like "<document>:<linenumber><RestOfMsg>".
---@return string convertedMsg a string of the form "<localDocument>:<localLinenumber><RestOfMsg>"
function Debug.getLocalErrorMsg(errorMsg)
local startPos, endPos = errorMsg:find(":\x25d*") --start and end position of line number. The part before that is the document, part after the error msg.
if startPos and endPos then --can be nil, if input string was not of the desired form "<document>:<linenumber><RestOfMsg>".
local document, line, rest = errorMsg:sub(1, startPos), tonumber(errorMsg:sub(startPos+1, endPos)), errorMsg:sub(endPos+1, -1) --get error line in war3map.lua
if document == 'war3map.lua:' and line then --only convert war3map.lua-references to local position. Other files such as Blizzard.j.lua are not converted (obiously).
for i = #sourceMap, 1, -1 do --find local file containing the war3map.lua error line.
if line >= sourceMap[i].firstLine then --war3map.lua line is part of sourceMap[i].file
if not sourceMap[i].lastLine or line <= sourceMap[i].lastLine then --if lastLine is given, we must also check for it
return sourceMap[i].file .. ":" .. (line - sourceMap[i].firstLine + 1) .. rest
else --if line is larger than firstLine and lastLine of sourceMap[i], it is not part of a tracked file -> return global war3map.lua position.
break --prevent return within next step of the loop ("line >= sourceMap[i].firstLine" would be true again, but wrong file)
end
end
end
end
end
return errorMsg
end
local convertToLocalErrorMsg = Debug.getLocalErrorMsg
----------------------
--| Error Handling |--
----------------------
local concat
---Applies tostring() on all input params and concatenates them 4-space-separated.
---@param firstParam any
---@param ... any
---@return string
concat = function(firstParam, ...)
if select('#', ...) == 0 then
return tostring(firstParam)
end
return tostring(firstParam) .. ' ' .. concat(...)
end
---Returns the stack trace between the specified startDepth and endDepth.
---The trace lists file names and line numbers. File name is only listed, if it has changed from the previous traced line.
---The previous file can also be specified as an input parameter to suppress the first file name in case it's identical.
---@param startDepth integer
---@param endDepth integer
---@return string trace
local function getStackTrace(startDepth, endDepth)
local trace, separator = "", ""
local _, lastFile, tracePiece, lastTracePiece
for loopDepth = startDepth, endDepth do --get trace on different depth level
_, tracePiece = pcall(error, "", loopDepth) ---@type boolean, string
tracePiece = convertToLocalErrorMsg(tracePiece)
if #tracePiece > 0 and lastTracePiece ~= tracePiece then --some trace pieces can be empty, but there can still be valid ones beyond that
trace = trace .. separator .. ((tracePiece:match("^.-:") == lastFile) and tracePiece:match(":\x25d+"):sub(2,-1) or tracePiece:match("^.-:\x25d+"))
lastFile, lastTracePiece, separator = tracePiece:match("^.-:"), tracePiece, " <- "
end
end
return trace
end
---Message Handler to be used by the try-function below.
---Adds stack trace plus formatting to the message and prints it.
---@param errorMsg string
---@param startDepth? integer default: 4 for use in xpcall
local function errorHandler(errorMsg, startDepth)
startDepth = startDepth or 4 --xpcall doesn't specify this param, so it defaults to 4 in this case
errorMsg = convertToLocalErrorMsg(errorMsg)
--Print original error message and stack trace.
print("|cffff5555ERROR at " .. errorMsg .. "|r")
if settings.SHOW_TRACE_ON_ERROR then
print("|cffff5555Traceback (most recent call first):|r")
print("|cffff5555" .. getStackTrace(startDepth,200) .. "|r")
end
--Also print entries from param log, if there are any.
for location, loggedParams in pairs(paramLog) do
print("|cff888888Logged at " .. convertToLocalErrorMsg(location) .. loggedParams .. "|r")
paramLog[location] = nil
end
end
---Tries to execute the specified function with the specified parameters in protected mode and prints an error message (including stack trace), if unsuccessful.
---
---Example use: Assume you have a code line like "CreateUnit(0,1,2)", which doesn't work and you want to know why.
---* Option 1: Change it to "Debug.try(CreateUnit, 0, 1, 2)", i.e. separate the function from the parameters.
---* Option 2: Change it to "Debug.try(function() return CreateUnit(0,1,2) end)", i.e. pack it into an anonymous function. You can skip the "return", if you don't need the return values.
---When no error occured, the try-function will return all values returned by the input function.
---When an error occurs, try will print the resulting error and stack trace.
---@param funcToExecute function the function to call in protected mode
---@param ... any params for the input-function
---@return ... any
function Debug.try(funcToExecute, ...)
return select(2, xpcall(funcToExecute, errorHandler,...))
end
try = Debug.try
---Prints "ERROR:" and the specified error objects on the Screen. Also prints the stack trace leading to the error. You can specify as many arguments as you wish.
---
---In contrast to Lua's native error function, this can be called outside of protected mode and doesn't halt code execution.
---@param ... any objects/errormessages to be printed (doesn't have to be strings)
function Debug.throwError(...)
errorHandler(getStackTrace(4,4) .. ": " .. concat(...), 5)
end
---Prints the specified error message, if the specified condition fails (i.e. if it resolves to false or nil).
---
---Returns all specified arguments after the errorMsg, if the condition holds.
---
---In contrast to Lua's native assert function, this can be called outside of protected mode and doesn't halt code execution (even in case of condition failure).
---@param condition any actually a boolean, but you can use any object as a boolean.
---@param errorMsg string the message to be printed, if the condition fails
---@param ... any will be returned, if the condition holds
function Debug.assert(condition, errorMsg, ...)
if condition then
return ...
else
errorHandler(getStackTrace(4,4) .. ": " .. errorMsg, 5)
end
end
---Returns the stack trace at the code position where this function is called.
---The returned string includes war3map.lua/blizzard.j.lua code positions of all functions from the stack trace in the order of execution (most recent call last). It does NOT include function names.
---@return string
function Debug.traceback()
return getStackTrace(3,200)
end
---Saves the specified parameters to the debug log at the location where this function is called. The Debug-log will be printed for all affected locations upon the try-function catching an error.
---The log is unique per code location: Parameters logged at code line x will overwrite the previous ones logged at x. Parameters logged at different locations will all persist and be printed.
---@param ... any save any information, for instance the parameters of the function call that you are logging.
function Debug.log(...)
local _, location = pcall(error, "", 3) ---@diagnostic disable-next-line: need-check-nil
paramLog[location or ''] = concat(...)
end
------------------------------------
--| Name Caching (API-functions) |--
------------------------------------
--Help-table. The registerName-functions below shall not work on call-by-value-types, i.e. booleans, strings and numbers (renaming a value of any primitive type doesn't make sense).
local skipType = {boolean = true, string = true, number = true, ['nil'] = true}
--Set weak keys to nameCache and nameDepths and weak values for nameCacheMirror to prevent garbage collection issues
setmetatable(nameCache, {__mode = 'k'})
setmetatable(nameDepths, getmetatable(nameCache))
setmetatable(nameCacheMirror, {__mode = 'v'})
---Removes the name from the name cache, if already used for any object (freeing it for the new object). This makes sure that a name is always unique.
---This doesn't solve the
---@param name string
local function removeNameIfNecessary(name)
if nameCacheMirror[name] then
nameCache[nameCacheMirror[name]] = nil
nameCacheMirror[name] = nil
end
end
---Registers a name for the specified object, which will be the future output for tostring(whichObject).
---You can overwrite existing names for whichObject by using this.
---@param whichObject any
---@param name string
function Debug.registerName(whichObject, name)
if not skipType[type(whichObject)] then
removeNameIfNecessary(name)
nameCache[whichObject] = name
nameCacheMirror[name] = whichObject
nameDepths[name] = 0
end
end
---Registers a new name to the nameCache as either just <key> (if parentTableName is the empty string), <table>.<key> (if parentTableName is given and string key doesn't contain whitespace) or <name>[<key>] notation (for other keys in existing tables).
---Only string keys without whitespace support <key>- and <table>.<key>-notation. All other keys require a parentTableName.
---@param parentTableName string | '""' empty string suppresses <table>-affix.
---@param key any
---@param object any only call-be-ref types allowed
---@param parentTableDepth? integer
local function addNameToCache(parentTableName, key, object, parentTableDepth)
parentTableDepth = parentTableDepth or -1
--Don't overwrite existing names for the same object, don't add names for primitive types.
if nameCache[object] or skipType[type(object)] then
return
end
local name
--apply dot-syntax for string keys without whitespace
if type(key) == 'string' and not string.find(key, "\x25s") then
if parentTableName == "" then
name = key
nameDepths[object] = 0
else
name = parentTableName .. "." .. key
nameDepths[object] = parentTableDepth + 1
end
--apply bracket-syntax for all other keys. This requires a parentTableName.
elseif parentTableName ~= "" then
name = type(key) == 'string' and ('"' .. key .. '"') or key
name = parentTableName .. "[" .. tostring(name) .. "]"
nameDepths[object] = parentTableDepth + 1
end
--Stop in cases without valid name (like parentTableName = "" and key = [1])
if name then
removeNameIfNecessary(name)
nameCache[object] = name
nameCacheMirror[name] = object
end
end
---Registers all call-by-reference objects in the given parentTable to the nameCache.
---Automatically filters out primitive objects and already registed Objects.
---@param parentTable table
---@param parentTableName? string
local function registerAllObjectsInTable(parentTable, parentTableName)
parentTableName = parentTableName or nameCache[parentTable] or ""
--Register all call-by-ref-objects in parentTable
for key, object in pairs(parentTable) do
addNameToCache(parentTableName, key, object, nameDepths[parentTable])
end
end
---Adds names for all values of the specified parentTable to the name cache. Names will be "<parentTableName>.<key>" or "<parentTableName>[<key>]", depending on the key type.
---
---Example: Given a table T = {f = function() end, [1] = {}}, tostring(T.f) and tostring(T[1]) will output "function: T.f" and "table: T[1]" respectively after running Debug.registerNamesFrom(T).
---The name of T itself must either be specified as an input parameter OR have previously been registered. It can also be suppressed by inputting the empty string (so objects will just display by their own names).
---The names of objects in global scope are automatically registered during loading screen.
---@param parentTable table base table of which all entries shall be registered (in the Form parentTableName.objectName).
---@param parentTableName? string|'""' Nil: takes <parentTableName> as previously registered. Empty String: Skips <parentTableName> completely. String <s>: Objects will show up as "<s>.<objectName>".
---@param depth? integer objects within sub-tables up to the specified depth will also be added. Default: 1 (only elements of whichTable). Must be >= 1.
---@overload fun(parentTable:table, depth:integer)
function Debug.registerNamesFrom(parentTable, parentTableName, depth)
--Support overloaded definition fun(parentTable:table, depth:integer)
if type(parentTableName) == 'number' then
depth = parentTableName
parentTableName = nil
end
--Apply default values
depth = depth or 1
parentTableName = parentTableName or nameCache[parentTable] or ""
--add name of T in case it hasn't already
if not nameCache[parentTable] and parentTableName ~= "" then
Debug.registerName(parentTable, parentTableName)
end
--Register all call-by-ref-objects in parentTable. To be preferred over simple recursive approach to ensure that top level names are preferred.
registerAllObjectsInTable(parentTable, parentTableName)
--if depth > 1 was specified, also register Names from subtables.
if depth > 1 then
for _, object in pairs(parentTable) do
if type(object) == 'table' then
Debug.registerNamesFrom(object, nil, depth - 1)
end
end
end
end
-------------------------------------------
--| Name Caching (Loading Screen setup) |--
-------------------------------------------
---Registers all existing object names from global scope and Lua incorporated libraries to be used by tostring() overwrite below.
local function registerNamesFromGlobalScope()
--Add all names from global scope to the name cache.
Debug.registerNamesFrom(_G, "")
--Add all names of Warcraft-enabled Lua libraries as well:
--Could instead add a depth to the function call above, but we want to ensure that these libraries are added even if the user has chosen depth 0.
for _, lib in ipairs({coroutine, math, os, string, table, utf8, Debug}) do
Debug.registerNamesFrom(lib)
end
--Add further names that are not accessible from global scope:
--Player(i)
for i = 0, GetBJMaxPlayerSlots() - 1 do
Debug.registerName(Player(i), "Player(" .. i .. ")")
end
end
--Set empty metatable to _G. __index is added when game starts (for "attempt to read undeclared global"-errors), __newindex is added right below (for building the name cache).
setmetatable(_G, getmetatable(_G) or {}) --getmetatable(_G) should always return nil provided that DebugUtils is the topmost script file in the trigger editor, but we still include this for safety-
-- Save old tostring into Debug Library before overwriting it.
Debug.oldTostring = tostring
if settings.USE_NAME_CACHE then
local oldTostring = tostring
tostring = function(obj) --new tostring(CreateUnit) prints "function: CreateUnit"
--tostring of non-primitive object is NOT guaranteed to be like "<type>:<hex>", because it might have been changed by some __tostring-metamethod.
if settings.USE_NAME_CACHE then --return names from name cache only if setting is enabled. This allows turning it off during runtime (via Ingame Console) to revert to old tostring.
return nameCache[obj] and ((oldTostring(obj):match("^.-: ") or (oldTostring(obj) .. ": ")) .. nameCache[obj]) or oldTostring(obj)
end
return Debug.oldTostring(obj)
end
--Add names to Debug.data.objectNames within Lua root. Called below the other Debug-stuff to get the overwritten versions instead of the original ones.
registerNamesFromGlobalScope()
--Prepare __newindex-metamethod to automatically add new names to the name cache
if settings.AUTO_REGISTER_NEW_NAMES then
local nameRegisterNewIndex
---__newindex to be used for _G (and subtables up to a certain depth) to automatically register new names to the nameCache.
---Tables in global scope will use their own name. Subtables of them will use <parentName>.<childName> syntax.
---Global names don't support container[key]-notation (because "_G[...]" is probably not desired), so we only register string type keys instead of using prettyTostring.
---@param t table
---@param k any
---@param v any
---@param skipRawset? boolean set this to true when combined with another __newindex. Suppresses rawset(t,k,v) (because the other __newindex is responsible for that).
nameRegisterNewIndex = function(t,k,v, skipRawset)
local parentDepth = nameDepths[t] or 0
--Make sure the parent table has an existing name before using it as part of the child name
if t == _G or nameCache[t] then
local existingName = nameCache[v]
if not existingName then
addNameToCache((t == _G and "") or nameCache[t], k, v, parentDepth)
end
--If v is a table and the parent table has a valid name, inherit __newindex to v's existing metatable (or create a new one), if that wasn't already done.
if type(v) == 'table' and nameDepths[v] < settings.NAME_CACHE_DEPTH then
if not existingName then
--If v didn't have a name before, also add names for elements contained in v by construction (like v = {x = function() end} ).
Debug.registerNamesFrom(v, settings.NAME_CACHE_DEPTH - nameDepths[v])
end
--Apply __newindex to new tables.
if not autoIndexedTables[v] then
autoIndexedTables[v] = true
local mt = getmetatable(v)
if not mt then
mt = {}
setmetatable(v, mt) --only use setmetatable when we are sure there wasn't any before to prevent issues with "__metatable"-metamethod.
end
local existingNewIndex = mt.__newindex
local isTable_yn = (type(existingNewIndex) == 'table')
--If mt has an existing __newindex, add the name-register effect to it (effectively create a new __newindex using the old)
if existingNewIndex then
mt.__newindex = function(t,k,v)
nameRegisterNewIndex(t,k,v, true) --setting t[k] = v might not be desired in case of existing newindex. Skip it and let existingNewIndex make the decision.
if isTable_yn then
existingNewIndex[k] = v
else
return existingNewIndex(t,k,v)
end
end
else
--If mt doesn't have an existing __newindex, add one that adds the object to the name cache.
mt.__newindex = nameRegisterNewIndex
end
end
end
end
--Set t[k] = v.
if not skipRawset then
rawset(t,k,v)
end
end
--Apply metamethod to _G.
local existingNewIndex = getmetatable(_G).__newindex --should always be nil provided that DebugUtils is the topmost script in your trigger editor. Still included for safety.
local isTable_yn = (type(existingNewIndex) == 'table')
if existingNewIndex then
getmetatable(_G).__newindex = function(t,k,v)
nameRegisterNewIndex(t,k,v, true)
if isTable_yn then
existingNewIndex[k] = v
else
existingNewIndex(t,k,v)
end
end
else
getmetatable(_G).__newindex = nameRegisterNewIndex
end
end
end
------------------------------------------------------
--| Native Overwrite for Automatic Error Handling |--
------------------------------------------------------
--A table to store the try-wrapper for each function. This avoids endless re-creation of wrapper functions within the hooks below.
--Weak keys ensure that garbage collection continues as normal.
local tryWrappers = setmetatable({}, {__mode = 'k'}) ---@type table<function,function>
local try = Debug.try
---Takes a function and returns a wrapper executing the same function within Debug.try.
---Wrappers are permanently stored (until the original function is garbage collected) to ensure that they don't have to be created twice for the same function.
---@param func? function
---@return function
local function getTryWrapper(func)
if func then
tryWrappers[func] = tryWrappers[func] or function(...) return try(func, ...) end
end
return tryWrappers[func] --returns nil for func = nil (important for TimerStart overwrite below)
end
--Overwrite TriggerAddAction, TimerStart, Condition and Filter natives to let them automatically apply Debug.try.
--Also overwrites coroutine.create and coroutine.wrap to let stack traces point to the function executed within instead of the function creating the coroutine.
if settings.USE_TRY_ON_TRIGGERADDACTION then
local originalTriggerAddAction = TriggerAddAction
TriggerAddAction = function(whichTrigger, actionFunc)
return originalTriggerAddAction(whichTrigger, getTryWrapper(actionFunc))
end
end
if settings.USE_TRY_ON_TIMERSTART then
local originalTimerStart = TimerStart
TimerStart = function(whichTimer, timeout, periodic, handlerFunc)
originalTimerStart(whichTimer, timeout, periodic, getTryWrapper(handlerFunc))
end
end
if settings.USE_TRY_ON_CONDITION then
local originalCondition = Condition
Condition = function(func)
return originalCondition(getTryWrapper(func))
end
Filter = Condition
end
if settings.USE_TRY_ON_COROUTINES then
local originalCoroutineCreate = coroutine.create
---@diagnostic disable-next-line: duplicate-set-field
coroutine.create = function(f)
return originalCoroutineCreate(getTryWrapper(f))
end
local originalCoroutineWrap = coroutine.wrap
---@diagnostic disable-next-line: duplicate-set-field
coroutine.wrap = function(f)
return originalCoroutineWrap(getTryWrapper(f))
end
end
------------------------------------------
--| Cache prints during Loading Screen |--
------------------------------------------
-- Apply the duration as specified in the settings.
if settings.PRINT_DURATION then
local display, getLocalPlayer, dur = DisplayTimedTextToPlayer, GetLocalPlayer, settings.PRINT_DURATION
print = function(...)
display(getLocalPlayer(), 0, 0, dur, concat(...))
end
end
-- Delay loading screen prints to after game start.
if settings.USE_PRINT_CACHE then
local oldPrint = print
--loading screen print will write the values into the printCache
print = function(...)
if bj_gameStarted then
oldPrint(...)
else --during loading screen only: concatenate input arguments 4-space-separated, implicitely apply tostring on each, cache to table
printCache.n = printCache.n + 1
printCache[printCache.n] = concat(...)
end
end
end
-------------------------
--| Modify Game Start |--
-------------------------
local originalMarkGameStarted = MarkGameStarted
--Hook certain actions into the start of the game.
MarkGameStarted = function()
originalMarkGameStarted()
if settings.WARNING_FOR_UNDECLARED_GLOBALS then
local existingIndex = getmetatable(_G).__index
local isTable_yn = (type(existingIndex) == 'table')
getmetatable(_G).__index = function(t, k) --we made sure that _G has a metatable further above.
--if string.sub(tostring(k),1,3) ~= 'bj_' then
print("Trying to read undeclared global at " .. getStackTrace(4,4) .. ": " .. tostring(k)
.. (settings.SHOW_TRACE_FOR_UNDECLARED_GLOBALS and "\nTraceback (most recent call first):\n" .. getStackTrace(4,200) or ""))
--end
if existingIndex then
if isTable_yn then
return existingIndex[k]
end
return existingIndex(t,k)
end
return rawget(t,k)
end
end
--Add names to Debug.data.objectNames again to ensure that overwritten natives also make it to the name cache.
--Overwritten natives have a new value, but the old key, so __newindex didn't trigger. But we can be sure that objectNames[v] doesn't yet exist, so adding again is safe.
if settings.USE_NAME_CACHE then
for _,v in pairs(_G) do
nameCache[v] = nil
end
registerNamesFromGlobalScope()
end
--Print messages that have been cached during loading screen.
if settings.USE_PRINT_CACHE then
--Note that we don't restore the old print. The overwritten variant only applies caching behaviour to loading screen prints anyway and "unhooking" always adds other risks.
for _, str in ipairs(printCache) do
print(str)
end
printCache = nil --frees reference for the garbage collector
end
--Create triggers listening to "-console" and "-exec" chat input.
if settings.ALLOW_INGAME_CODE_EXECUTION and IngameConsole then
IngameConsole.createTriggers()
end
end
---------------------
--| Other Utility |--
---------------------
do
---Returns the type of a warcraft object as string, e.g. "unit" upon inputting a unit.
---@param input any
---@return string
function Debug.wc3Type(input)
local typeString = type(input)
if typeString == 'userdata' then
typeString = tostring(input) --tostring returns the warcraft type plus a colon and some hashstuff.
return typeString:sub(1, (typeString:find(":", nil, true) or 0) -1) --string.find returns nil, if the argument is not found, which would break string.sub. So we need to replace by 0.
else
return typeString
end
end
Wc3Type = Debug.wc3Type --for backwards compatibility
local conciseTostring, prettyTostring
---Translates a table into a comma-separated list of its (key,value)-pairs. Also translates subtables up to the specified depth.
---E.g. {"a", 5, {7}} will display as '{(1, "a"), (2, 5), (3, {(1, 7)})}'.
---@param object any
---@param depth? integer default: unlimited. Unlimited depth will throw a stack overflow error on self-referential tables.
---@return string
conciseTostring = function (object, depth)
depth = depth or -1
if type(object) == 'string' then
return '"' .. object .. '"'
elseif depth ~= 0 and type(object) == 'table' then
local elementArray = {}
local keyAsString
for k,v in pairs(object) do
keyAsString = type(k) == 'string' and ('"' .. tostring(k) .. '"') or tostring(k)
table.insert(elementArray, '(' .. keyAsString .. ', ' .. conciseTostring(v, depth -1) .. ')')
end
return '{' .. table.concat(elementArray, ', ') .. '}'
end
return tostring(object)
end
---Creates a list of all (key,value)-pairs from the specified table. Also lists subtable entries up to the specified depth.
---Major differences to concise print are:
--- * Format: Linebreak-formatted instead of one-liner, uses "[key] = value" instead of "(key,value)"
--- * Will also unpack tables used as keys
--- * Also includes the table's memory position as returned by tostring(table).
--- * Tables referenced multiple times will only be unpacked upon first encounter and abbreviated on subsequent encounters
--- * As a consequence, pretty version can be executed with unlimited depth on self-referential tables.
---@param object any
---@param depth? integer default: unlimited.
---@param constTable table
---@param indent string
---@return string
prettyTostring = function(object, depth, constTable, indent)
depth = depth or -1
local objType = type(object)
if objType == "string" then
return '"'..object..'"' --wrap the string in quotes.
elseif objType == 'table' and depth ~= 0 then
if not constTable[object] then
constTable[object] = tostring(object):gsub(":","")
if next(object)==nil then
return constTable[object]..": {}"
else
local mappedKV = {}
for k,v in pairs(object) do
table.insert(mappedKV, '\n ' .. indent ..'[' .. prettyTostring(k, depth - 1, constTable, indent .. " ") .. '] = ' .. prettyTostring(v, depth - 1, constTable, indent .. " "))
end
return constTable[object]..': {'.. table.concat(mappedKV, ',') .. '\n'..indent..'}'
end
end
end
return constTable[object] or tostring(object)
end
---Creates a list of all (key,value)-pairs from the specified table. Also lists subtable entries up to the specified depth.
---Supports concise style and pretty style.
---Concise will display {"a", 5, {7}} as '{(1, "a"), (2, 5), (3, {(1, 7)})}'.
---Pretty is linebreak-separated, so consider table size before converting. Pretty also abbreviates tables referenced multiple times.
---Can be called like table.tostring(T), table.tostring(T, depth), table.tostring(T, pretty_yn) or table.tostring(T, depth, pretty_yn).
---table.tostring is not multiplayer-synced.
---@param whichTable table
---@param depth? integer default: unlimited
---@param pretty_yn? boolean default: false (concise)
---@return string
---@overload fun(whichTable:table, pretty_yn?:boolean):string
function table.tostring(whichTable, depth, pretty_yn)
--reassign input params, if function was called as table.tostring(whichTable, pretty_yn)
if type(depth) == 'boolean' then
pretty_yn = depth
depth = -1
end
return pretty_yn and prettyTostring(whichTable, depth, {}, "") or conciseTostring(whichTable, depth)
end
---Prints a list of (key,value)-pairs contained in the specified table and its subtables up to the specified depth.
---Supports concise style and pretty style. Pretty is linebreak-separated, so consider table size before printing.
---Can be called like table.print(T), table.print(T, depth), table.print(T, pretty_yn) or table.print(T, depth, pretty_yn).
---@param whichTable table
---@param depth? integer default: unlimited
---@param pretty_yn? boolean default: false (concise)
---@overload fun(whichTable:table, pretty_yn?:boolean)
function table.print(whichTable, depth, pretty_yn)
print(table.tostring(whichTable, depth, pretty_yn))
end
end
end
Debug.endFile()
------------------------
----| String Width |----
------------------------
--[[
offers functions to measure the width of a string (i.e. the space it takes on screen, not the number of chars). Wc3 font is not monospace, so the system below has protocolled every char width and simply sums up all chars in a string.
output measures are:
1. Multiboard-width (i.e. 1-based screen share used in Multiboards column functions)
2. Line-width for screen prints
every unknown char will be treated as having default width (see constants below)
--]]
do
----------------------------
----| String Width API |----
----------------------------
local multiboardCharTable = {} ---@type table -- saves the width in screen percent (on 1920 pixel width resolutions) that each char takes up, when displayed in a multiboard.
local DEFAULT_MULTIBOARD_CHAR_WIDTH = 1. / 128. ---@type number -- used for unknown chars (where we didn't define a width in the char table)
local MULTIBOARD_TO_PRINT_FACTOR = 1. / 36. ---@type number -- 36 is actually the lower border (longest width of a non-breaking string only consisting of the letter "i")
---Returns the width of a char in a multiboard, when inputting a char (string of length 1) and 0 otherwise.
---also returns 0 for non-recorded chars (like ` and ´ and ß and § and €)
---@param char string | integer integer bytecode representations of chars are also allowed, i.e. the results of string.byte().
---@param textlanguage? '"ger"'| '"eng"' (default: 'eng'), depending on the text language in the Warcraft 3 installation settings.
---@return number
function string.charMultiboardWidth(char, textlanguage)
return multiboardCharTable[textlanguage or 'eng'][char] or DEFAULT_MULTIBOARD_CHAR_WIDTH
end
---returns the width of a string in a multiboard (i.e. output is in screen percent)
---unknown chars will be measured with default width (see constants above)
---@param multichar string
---@param textlanguage? '"ger"'| '"eng"' (default: 'eng'), depending on the text language in the Warcraft 3 installation settings.
---@return number
function string.multiboardWidth(multichar, textlanguage)
local chartable = table.pack(multichar:byte(1,-1)) --packs all bytecode char representations into a table
local charWidth = 0.
for i = 1, chartable.n do
charWidth = charWidth + string.charMultiboardWidth(chartable[i], textlanguage)
end
return charWidth
end
---The function should match the following criteria: If the value returned by this function is smaller than 1.0, than the string fits into a single line on screen.
---The opposite is not necessarily true (but should be true in the majority of cases): If the function returns bigger than 1.0, the string doesn't necessarily break.
---@param char string | integer integer bytecode representations of chars are also allowed, i.e. the results of string.byte().
---@param textlanguage? '"ger"'| '"eng"' (default: 'eng'), depending on the text language in the Warcraft 3 installation settings.
---@return number
function string.charPrintWidth(char, textlanguage)
return string.charMultiboardWidth(char, textlanguage) * MULTIBOARD_TO_PRINT_FACTOR
end
---The function should match the following criteria: If the value returned by this function is smaller than 1.0, than the string fits into a single line on screen.
---The opposite is not necessarily true (but should be true in the majority of cases): If the function returns bigger than 1.0, the string doesn't necessarily break.
---@param multichar string
---@param textlanguage? '"ger"'| '"eng"' (default: 'eng'), depending on the text language in the Warcraft 3 installation settings.
---@return number
function string.printWidth(multichar, textlanguage)
return string.multiboardWidth(multichar, textlanguage) * MULTIBOARD_TO_PRINT_FACTOR
end
----------------------------------
----| String Width Internals |----
----------------------------------
---@param charset '"ger"'| '"eng"' (default: 'eng'), depending on the text language in the Warcraft 3 installation settings.
---@param char string|integer either the char or its bytecode
---@param lengthInScreenWidth number
local function setMultiboardCharWidth(charset, char, lengthInScreenWidth)
multiboardCharTable[charset] = multiboardCharTable[charset] or {}
multiboardCharTable[charset][char] = lengthInScreenWidth
end
---numberPlacements says how often the char can be placed in a multiboard column, before reaching into the right bound.
---@param charset '"ger"'| '"eng"' (default: 'eng'), depending on the text language in the Warcraft 3 installation settings.
---@param char string|integer either the char or its bytecode
---@param numberPlacements integer
local function setMultiboardCharWidthBase80(charset, char, numberPlacements)
setMultiboardCharWidth(charset, char, 0.8 / numberPlacements) --1-based measure. 80./numberPlacements would result in Screen Percent.
setMultiboardCharWidth(charset, char:byte(1,-1), 0.8 / numberPlacements)
end
-- Set Char Width for all printable ascii chars in screen width (1920 pixels). Measured on a 80percent screen width multiboard column by counting the number of chars that fit into it.
-- Font size differs by text install language and patch (1.32- vs. 1.33+)
if BlzGetUnitOrderCount then --identifies patch 1.33+
--German font size for patch 1.33+
setMultiboardCharWidthBase80('ger', "a", 144)
setMultiboardCharWidthBase80('ger', "b", 131)
setMultiboardCharWidthBase80('ger', "c", 144)
setMultiboardCharWidthBase80('ger', "d", 120)
setMultiboardCharWidthBase80('ger', "e", 131)
setMultiboardCharWidthBase80('ger', "f", 240)
setMultiboardCharWidthBase80('ger', "g", 120)
setMultiboardCharWidthBase80('ger', "h", 131)
setMultiboardCharWidthBase80('ger', "i", 288)
setMultiboardCharWidthBase80('ger', "j", 288)
setMultiboardCharWidthBase80('ger', "k", 144)
setMultiboardCharWidthBase80('ger', "l", 288)
setMultiboardCharWidthBase80('ger', "m", 85)
setMultiboardCharWidthBase80('ger', "n", 131)
setMultiboardCharWidthBase80('ger', "o", 120)
setMultiboardCharWidthBase80('ger', "p", 120)
setMultiboardCharWidthBase80('ger', "q", 120)
setMultiboardCharWidthBase80('ger', "r", 206)
setMultiboardCharWidthBase80('ger', "s", 160)
setMultiboardCharWidthBase80('ger', "t", 206)
setMultiboardCharWidthBase80('ger', "u", 131)
setMultiboardCharWidthBase80('ger', "v", 131)
setMultiboardCharWidthBase80('ger', "w", 96)
setMultiboardCharWidthBase80('ger', "x", 144)
setMultiboardCharWidthBase80('ger', "y", 131)
setMultiboardCharWidthBase80('ger', "z", 144)
setMultiboardCharWidthBase80('ger', "A", 103)
setMultiboardCharWidthBase80('ger', "B", 120)
setMultiboardCharWidthBase80('ger', "C", 111)
setMultiboardCharWidthBase80('ger', "D", 103)
setMultiboardCharWidthBase80('ger', "E", 144)
setMultiboardCharWidthBase80('ger', "F", 160)
setMultiboardCharWidthBase80('ger', "G", 96)
setMultiboardCharWidthBase80('ger', "H", 96)
setMultiboardCharWidthBase80('ger', "I", 240)
setMultiboardCharWidthBase80('ger', "J", 240)
setMultiboardCharWidthBase80('ger', "K", 120)
setMultiboardCharWidthBase80('ger', "L", 144)
setMultiboardCharWidthBase80('ger', "M", 76)
setMultiboardCharWidthBase80('ger', "N", 96)
setMultiboardCharWidthBase80('ger', "O", 90)
setMultiboardCharWidthBase80('ger', "P", 131)
setMultiboardCharWidthBase80('ger', "Q", 90)
setMultiboardCharWidthBase80('ger', "R", 120)
setMultiboardCharWidthBase80('ger', "S", 131)
setMultiboardCharWidthBase80('ger', "T", 144)
setMultiboardCharWidthBase80('ger', "U", 103)
setMultiboardCharWidthBase80('ger', "V", 120)
setMultiboardCharWidthBase80('ger', "W", 76)
setMultiboardCharWidthBase80('ger', "X", 111)
setMultiboardCharWidthBase80('ger', "Y", 120)
setMultiboardCharWidthBase80('ger', "Z", 120)
setMultiboardCharWidthBase80('ger', "1", 144)
setMultiboardCharWidthBase80('ger', "2", 120)
setMultiboardCharWidthBase80('ger', "3", 120)
setMultiboardCharWidthBase80('ger', "4", 120)
setMultiboardCharWidthBase80('ger', "5", 120)
setMultiboardCharWidthBase80('ger', "6", 120)
setMultiboardCharWidthBase80('ger', "7", 131)
setMultiboardCharWidthBase80('ger', "8", 120)
setMultiboardCharWidthBase80('ger', "9", 120)
setMultiboardCharWidthBase80('ger', "0", 120)
setMultiboardCharWidthBase80('ger', ":", 288)
setMultiboardCharWidthBase80('ger', ";", 288)
setMultiboardCharWidthBase80('ger', ".", 288)
setMultiboardCharWidthBase80('ger', "#", 120)
setMultiboardCharWidthBase80('ger', ",", 288)
setMultiboardCharWidthBase80('ger', " ", 286) --space
setMultiboardCharWidthBase80('ger', "'", 180)
setMultiboardCharWidthBase80('ger', "!", 180)
setMultiboardCharWidthBase80('ger', "$", 131)
setMultiboardCharWidthBase80('ger', "&", 90)
setMultiboardCharWidthBase80('ger', "/", 180)
setMultiboardCharWidthBase80('ger', "(", 240)
setMultiboardCharWidthBase80('ger', ")", 240)
setMultiboardCharWidthBase80('ger', "=", 120)
setMultiboardCharWidthBase80('ger', "?", 144)
setMultiboardCharWidthBase80('ger', "^", 144)
setMultiboardCharWidthBase80('ger', "<", 144)
setMultiboardCharWidthBase80('ger', ">", 144)
setMultiboardCharWidthBase80('ger', "-", 180)
setMultiboardCharWidthBase80('ger', "+", 120)
setMultiboardCharWidthBase80('ger', "*", 180)
setMultiboardCharWidthBase80('ger', "|", 287) --2 vertical bars in a row escape to one. So you could print 960 ones in a line, 480 would display. Maybe need to adapt to this before calculating string width.
setMultiboardCharWidthBase80('ger', "~", 111)
setMultiboardCharWidthBase80('ger', "{", 240)
setMultiboardCharWidthBase80('ger', "}", 240)
setMultiboardCharWidthBase80('ger', "[", 240)
setMultiboardCharWidthBase80('ger', "]", 240)
setMultiboardCharWidthBase80('ger', "_", 144)
setMultiboardCharWidthBase80('ger', "\x25", 103) --percent
setMultiboardCharWidthBase80('ger', "\x5C", 205) --backslash
setMultiboardCharWidthBase80('ger', "\x22", 120) --double quotation mark
setMultiboardCharWidthBase80('ger', "\x40", 90) --at sign
setMultiboardCharWidthBase80('ger', "\x60", 144) --Gravis (Accent)
--English font size for patch 1.33+
setMultiboardCharWidthBase80('eng', "a", 144)
setMultiboardCharWidthBase80('eng', "b", 120)
setMultiboardCharWidthBase80('eng', "c", 131)
setMultiboardCharWidthBase80('eng', "d", 120)
setMultiboardCharWidthBase80('eng', "e", 120)
setMultiboardCharWidthBase80('eng', "f", 240)
setMultiboardCharWidthBase80('eng', "g", 120)
setMultiboardCharWidthBase80('eng', "h", 120)
setMultiboardCharWidthBase80('eng', "i", 288)
setMultiboardCharWidthBase80('eng', "j", 288)
setMultiboardCharWidthBase80('eng', "k", 144)
setMultiboardCharWidthBase80('eng', "l", 288)
setMultiboardCharWidthBase80('eng', "m", 80)
setMultiboardCharWidthBase80('eng', "n", 120)
setMultiboardCharWidthBase80('eng', "o", 111)
setMultiboardCharWidthBase80('eng', "p", 111)
setMultiboardCharWidthBase80('eng', "q", 111)
setMultiboardCharWidthBase80('eng', "r", 206)
setMultiboardCharWidthBase80('eng', "s", 160)
setMultiboardCharWidthBase80('eng', "t", 206)
setMultiboardCharWidthBase80('eng', "u", 120)
setMultiboardCharWidthBase80('eng', "v", 144)
setMultiboardCharWidthBase80('eng', "w", 90)
setMultiboardCharWidthBase80('eng', "x", 131)
setMultiboardCharWidthBase80('eng', "y", 144)
setMultiboardCharWidthBase80('eng', "z", 144)
setMultiboardCharWidthBase80('eng', "A", 103)
setMultiboardCharWidthBase80('eng', "B", 120)
setMultiboardCharWidthBase80('eng', "C", 103)
setMultiboardCharWidthBase80('eng', "D", 96)
setMultiboardCharWidthBase80('eng', "E", 131)
setMultiboardCharWidthBase80('eng', "F", 160)
setMultiboardCharWidthBase80('eng', "G", 96)
setMultiboardCharWidthBase80('eng', "H", 90)
setMultiboardCharWidthBase80('eng', "I", 240)
setMultiboardCharWidthBase80('eng', "J", 240)
setMultiboardCharWidthBase80('eng', "K", 120)
setMultiboardCharWidthBase80('eng', "L", 131)
setMultiboardCharWidthBase80('eng', "M", 76)
setMultiboardCharWidthBase80('eng', "N", 90)
setMultiboardCharWidthBase80('eng', "O", 85)
setMultiboardCharWidthBase80('eng', "P", 120)
setMultiboardCharWidthBase80('eng', "Q", 85)
setMultiboardCharWidthBase80('eng', "R", 120)
setMultiboardCharWidthBase80('eng', "S", 131)
setMultiboardCharWidthBase80('eng', "T", 144)
setMultiboardCharWidthBase80('eng', "U", 96)
setMultiboardCharWidthBase80('eng', "V", 120)
setMultiboardCharWidthBase80('eng', "W", 76)
setMultiboardCharWidthBase80('eng', "X", 111)
setMultiboardCharWidthBase80('eng', "Y", 120)
setMultiboardCharWidthBase80('eng', "Z", 111)
setMultiboardCharWidthBase80('eng', "1", 103)
setMultiboardCharWidthBase80('eng', "2", 111)
setMultiboardCharWidthBase80('eng', "3", 111)
setMultiboardCharWidthBase80('eng', "4", 111)
setMultiboardCharWidthBase80('eng', "5", 111)
setMultiboardCharWidthBase80('eng', "6", 111)
setMultiboardCharWidthBase80('eng', "7", 111)
setMultiboardCharWidthBase80('eng', "8", 111)
setMultiboardCharWidthBase80('eng', "9", 111)
setMultiboardCharWidthBase80('eng', "0", 111)
setMultiboardCharWidthBase80('eng', ":", 288)
setMultiboardCharWidthBase80('eng', ";", 288)
setMultiboardCharWidthBase80('eng', ".", 288)
setMultiboardCharWidthBase80('eng', "#", 103)
setMultiboardCharWidthBase80('eng', ",", 288)
setMultiboardCharWidthBase80('eng', " ", 286) --space
setMultiboardCharWidthBase80('eng', "'", 360)
setMultiboardCharWidthBase80('eng', "!", 288)
setMultiboardCharWidthBase80('eng', "$", 131)
setMultiboardCharWidthBase80('eng', "&", 120)
setMultiboardCharWidthBase80('eng', "/", 180)
setMultiboardCharWidthBase80('eng', "(", 206)
setMultiboardCharWidthBase80('eng', ")", 206)
setMultiboardCharWidthBase80('eng', "=", 111)
setMultiboardCharWidthBase80('eng', "?", 180)
setMultiboardCharWidthBase80('eng', "^", 144)
setMultiboardCharWidthBase80('eng', "<", 111)
setMultiboardCharWidthBase80('eng', ">", 111)
setMultiboardCharWidthBase80('eng', "-", 160)
setMultiboardCharWidthBase80('eng', "+", 111)
setMultiboardCharWidthBase80('eng', "*", 144)
setMultiboardCharWidthBase80('eng', "|", 479) --2 vertical bars in a row escape to one. So you could print 960 ones in a line, 480 would display. Maybe need to adapt to this before calculating string width.
setMultiboardCharWidthBase80('eng', "~", 144)
setMultiboardCharWidthBase80('eng', "{", 160)
setMultiboardCharWidthBase80('eng', "}", 160)
setMultiboardCharWidthBase80('eng', "[", 206)
setMultiboardCharWidthBase80('eng', "]", 206)
setMultiboardCharWidthBase80('eng', "_", 120)
setMultiboardCharWidthBase80('eng', "\x25", 103) --percent
setMultiboardCharWidthBase80('eng', "\x5C", 180) --backslash
setMultiboardCharWidthBase80('eng', "\x22", 180) --double quotation mark
setMultiboardCharWidthBase80('eng', "\x40", 85) --at sign
setMultiboardCharWidthBase80('eng', "\x60", 206) --Gravis (Accent)
else
--German font size up to patch 1.32
setMultiboardCharWidthBase80('ger', "a", 144)
setMultiboardCharWidthBase80('ger', "b", 144)
setMultiboardCharWidthBase80('ger', "c", 144)
setMultiboardCharWidthBase80('ger', "d", 131)
setMultiboardCharWidthBase80('ger', "e", 144)
setMultiboardCharWidthBase80('ger', "f", 240)
setMultiboardCharWidthBase80('ger', "g", 120)
setMultiboardCharWidthBase80('ger', "h", 144)
setMultiboardCharWidthBase80('ger', "i", 360)
setMultiboardCharWidthBase80('ger', "j", 288)
setMultiboardCharWidthBase80('ger', "k", 144)
setMultiboardCharWidthBase80('ger', "l", 360)
setMultiboardCharWidthBase80('ger', "m", 90)
setMultiboardCharWidthBase80('ger', "n", 144)
setMultiboardCharWidthBase80('ger', "o", 131)
setMultiboardCharWidthBase80('ger', "p", 131)
setMultiboardCharWidthBase80('ger', "q", 131)
setMultiboardCharWidthBase80('ger', "r", 206)
setMultiboardCharWidthBase80('ger', "s", 180)
setMultiboardCharWidthBase80('ger', "t", 206)
setMultiboardCharWidthBase80('ger', "u", 144)
setMultiboardCharWidthBase80('ger', "v", 131)
setMultiboardCharWidthBase80('ger', "w", 96)
setMultiboardCharWidthBase80('ger', "x", 144)
setMultiboardCharWidthBase80('ger', "y", 131)
setMultiboardCharWidthBase80('ger', "z", 144)
setMultiboardCharWidthBase80('ger', "A", 103)
setMultiboardCharWidthBase80('ger', "B", 131)
setMultiboardCharWidthBase80('ger', "C", 120)
setMultiboardCharWidthBase80('ger', "D", 111)
setMultiboardCharWidthBase80('ger', "E", 144)
setMultiboardCharWidthBase80('ger', "F", 180)
setMultiboardCharWidthBase80('ger', "G", 103)
setMultiboardCharWidthBase80('ger', "H", 103)
setMultiboardCharWidthBase80('ger', "I", 288)
setMultiboardCharWidthBase80('ger', "J", 240)
setMultiboardCharWidthBase80('ger', "K", 120)
setMultiboardCharWidthBase80('ger', "L", 144)
setMultiboardCharWidthBase80('ger', "M", 80)
setMultiboardCharWidthBase80('ger', "N", 103)
setMultiboardCharWidthBase80('ger', "O", 96)
setMultiboardCharWidthBase80('ger', "P", 144)
setMultiboardCharWidthBase80('ger', "Q", 90)
setMultiboardCharWidthBase80('ger', "R", 120)
setMultiboardCharWidthBase80('ger', "S", 144)
setMultiboardCharWidthBase80('ger', "T", 144)
setMultiboardCharWidthBase80('ger', "U", 111)
setMultiboardCharWidthBase80('ger', "V", 120)
setMultiboardCharWidthBase80('ger', "W", 76)
setMultiboardCharWidthBase80('ger', "X", 111)
setMultiboardCharWidthBase80('ger', "Y", 120)
setMultiboardCharWidthBase80('ger', "Z", 120)
setMultiboardCharWidthBase80('ger', "1", 288)
setMultiboardCharWidthBase80('ger', "2", 131)
setMultiboardCharWidthBase80('ger', "3", 144)
setMultiboardCharWidthBase80('ger', "4", 120)
setMultiboardCharWidthBase80('ger', "5", 144)
setMultiboardCharWidthBase80('ger', "6", 131)
setMultiboardCharWidthBase80('ger', "7", 144)
setMultiboardCharWidthBase80('ger', "8", 131)
setMultiboardCharWidthBase80('ger', "9", 131)
setMultiboardCharWidthBase80('ger', "0", 131)
setMultiboardCharWidthBase80('ger', ":", 480)
setMultiboardCharWidthBase80('ger', ";", 360)
setMultiboardCharWidthBase80('ger', ".", 480)
setMultiboardCharWidthBase80('ger', "#", 120)
setMultiboardCharWidthBase80('ger', ",", 360)
setMultiboardCharWidthBase80('ger', " ", 288) --space
setMultiboardCharWidthBase80('ger', "'", 480)
setMultiboardCharWidthBase80('ger', "!", 360)
setMultiboardCharWidthBase80('ger', "$", 160)
setMultiboardCharWidthBase80('ger', "&", 96)
setMultiboardCharWidthBase80('ger', "/", 180)
setMultiboardCharWidthBase80('ger', "(", 288)
setMultiboardCharWidthBase80('ger', ")", 288)
setMultiboardCharWidthBase80('ger', "=", 160)
setMultiboardCharWidthBase80('ger', "?", 180)
setMultiboardCharWidthBase80('ger', "^", 144)
setMultiboardCharWidthBase80('ger', "<", 160)
setMultiboardCharWidthBase80('ger', ">", 160)
setMultiboardCharWidthBase80('ger', "-", 144)
setMultiboardCharWidthBase80('ger', "+", 160)
setMultiboardCharWidthBase80('ger', "*", 206)
setMultiboardCharWidthBase80('ger', "|", 480) --2 vertical bars in a row escape to one. So you could print 960 ones in a line, 480 would display. Maybe need to adapt to this before calculating string width.
setMultiboardCharWidthBase80('ger', "~", 144)
setMultiboardCharWidthBase80('ger', "{", 240)
setMultiboardCharWidthBase80('ger', "}", 240)
setMultiboardCharWidthBase80('ger', "[", 240)
setMultiboardCharWidthBase80('ger', "]", 288)
setMultiboardCharWidthBase80('ger', "_", 144)
setMultiboardCharWidthBase80('ger', "\x25", 111) --percent
setMultiboardCharWidthBase80('ger', "\x5C", 206) --backslash
setMultiboardCharWidthBase80('ger', "\x22", 240) --double quotation mark
setMultiboardCharWidthBase80('ger', "\x40", 103) --at sign
setMultiboardCharWidthBase80('ger', "\x60", 240) --Gravis (Accent)
--English Font size up to patch 1.32
setMultiboardCharWidthBase80('eng', "a", 144)
setMultiboardCharWidthBase80('eng', "b", 120)
setMultiboardCharWidthBase80('eng', "c", 131)
setMultiboardCharWidthBase80('eng', "d", 120)
setMultiboardCharWidthBase80('eng', "e", 131)
setMultiboardCharWidthBase80('eng', "f", 240)
setMultiboardCharWidthBase80('eng', "g", 120)
setMultiboardCharWidthBase80('eng', "h", 131)
setMultiboardCharWidthBase80('eng', "i", 360)
setMultiboardCharWidthBase80('eng', "j", 288)
setMultiboardCharWidthBase80('eng', "k", 144)
setMultiboardCharWidthBase80('eng', "l", 360)
setMultiboardCharWidthBase80('eng', "m", 80)
setMultiboardCharWidthBase80('eng', "n", 131)
setMultiboardCharWidthBase80('eng', "o", 120)
setMultiboardCharWidthBase80('eng', "p", 120)
setMultiboardCharWidthBase80('eng', "q", 120)
setMultiboardCharWidthBase80('eng', "r", 206)
setMultiboardCharWidthBase80('eng', "s", 160)
setMultiboardCharWidthBase80('eng', "t", 206)
setMultiboardCharWidthBase80('eng', "u", 131)
setMultiboardCharWidthBase80('eng', "v", 144)
setMultiboardCharWidthBase80('eng', "w", 90)
setMultiboardCharWidthBase80('eng', "x", 131)
setMultiboardCharWidthBase80('eng', "y", 144)
setMultiboardCharWidthBase80('eng', "z", 144)
setMultiboardCharWidthBase80('eng', "A", 103)
setMultiboardCharWidthBase80('eng', "B", 120)
setMultiboardCharWidthBase80('eng', "C", 103)
setMultiboardCharWidthBase80('eng', "D", 103)
setMultiboardCharWidthBase80('eng', "E", 131)
setMultiboardCharWidthBase80('eng', "F", 160)
setMultiboardCharWidthBase80('eng', "G", 103)
setMultiboardCharWidthBase80('eng', "H", 96)
setMultiboardCharWidthBase80('eng', "I", 288)
setMultiboardCharWidthBase80('eng', "J", 240)
setMultiboardCharWidthBase80('eng', "K", 120)
setMultiboardCharWidthBase80('eng', "L", 131)
setMultiboardCharWidthBase80('eng', "M", 76)
setMultiboardCharWidthBase80('eng', "N", 96)
setMultiboardCharWidthBase80('eng', "O", 85)
setMultiboardCharWidthBase80('eng', "P", 131)
setMultiboardCharWidthBase80('eng', "Q", 85)
setMultiboardCharWidthBase80('eng', "R", 120)
setMultiboardCharWidthBase80('eng', "S", 131)
setMultiboardCharWidthBase80('eng', "T", 144)
setMultiboardCharWidthBase80('eng', "U", 103)
setMultiboardCharWidthBase80('eng', "V", 120)
setMultiboardCharWidthBase80('eng', "W", 76)
setMultiboardCharWidthBase80('eng', "X", 111)
setMultiboardCharWidthBase80('eng', "Y", 120)
setMultiboardCharWidthBase80('eng', "Z", 111)
setMultiboardCharWidthBase80('eng', "1", 206)
setMultiboardCharWidthBase80('eng', "2", 131)
setMultiboardCharWidthBase80('eng', "3", 131)
setMultiboardCharWidthBase80('eng', "4", 111)
setMultiboardCharWidthBase80('eng', "5", 131)
setMultiboardCharWidthBase80('eng', "6", 120)
setMultiboardCharWidthBase80('eng', "7", 131)
setMultiboardCharWidthBase80('eng', "8", 111)
setMultiboardCharWidthBase80('eng', "9", 120)
setMultiboardCharWidthBase80('eng', "0", 111)
setMultiboardCharWidthBase80('eng', ":", 360)
setMultiboardCharWidthBase80('eng', ";", 360)
setMultiboardCharWidthBase80('eng', ".", 360)
setMultiboardCharWidthBase80('eng', "#", 103)
setMultiboardCharWidthBase80('eng', ",", 360)
setMultiboardCharWidthBase80('eng', " ", 288) --space
setMultiboardCharWidthBase80('eng', "'", 480)
setMultiboardCharWidthBase80('eng', "!", 360)
setMultiboardCharWidthBase80('eng', "$", 131)
setMultiboardCharWidthBase80('eng', "&", 120)
setMultiboardCharWidthBase80('eng', "/", 180)
setMultiboardCharWidthBase80('eng', "(", 240)
setMultiboardCharWidthBase80('eng', ")", 240)
setMultiboardCharWidthBase80('eng', "=", 111)
setMultiboardCharWidthBase80('eng', "?", 180)
setMultiboardCharWidthBase80('eng', "^", 144)
setMultiboardCharWidthBase80('eng', "<", 131)
setMultiboardCharWidthBase80('eng', ">", 131)
setMultiboardCharWidthBase80('eng', "-", 180)
setMultiboardCharWidthBase80('eng', "+", 111)
setMultiboardCharWidthBase80('eng', "*", 180)
setMultiboardCharWidthBase80('eng', "|", 480) --2 vertical bars in a row escape to one. So you could print 960 ones in a line, 480 would display. Maybe need to adapt to this before calculating string width.
setMultiboardCharWidthBase80('eng', "~", 144)
setMultiboardCharWidthBase80('eng', "{", 240)
setMultiboardCharWidthBase80('eng', "}", 240)
setMultiboardCharWidthBase80('eng', "[", 240)
setMultiboardCharWidthBase80('eng', "]", 240)
setMultiboardCharWidthBase80('eng', "_", 120)
setMultiboardCharWidthBase80('eng', "\x25", 103) --percent
setMultiboardCharWidthBase80('eng', "\x5C", 180) --backslash
setMultiboardCharWidthBase80('eng', "\x22", 206) --double quotation mark
setMultiboardCharWidthBase80('eng', "\x40", 96) --at sign
setMultiboardCharWidthBase80('eng', "\x60", 206) --Gravis (Accent)
end
end
Debug.beginFile("IngameConsole")
--[[
--------------------------
----| Ingame Console |----
--------------------------
/**********************************************
* Allows you to use the following ingame commands:
* "-exec <code>" to execute any code ingame.
* "-console" to start an ingame console interpreting any further chat input as code and showing both return values of function calls and error messages. Furthermore, the print function will print
* directly to the console after it got started. You can still look up all print messages in the F12-log.
***********************
* -------------------
* |Using the console|
* -------------------
* Any (well, most) chat input by any player after starting the console is interpreted as code and directly executed. You can enter terms (like 4+5 or just any variable name), function calls (like print("bla"))
* and set-statements (like y = 5). If the code has any return values, all of them are printed to the console. Erroneous code will print an error message.
* Chat input starting with a hyphen is being ignored by the console, i.e. neither executed as code nor printed to the console. This allows you to still use other chat commands like "-exec" without prompting errors.
***********************
* ------------------
* |Multiline-Inputs|
* ------------------
* You can prevent a chat input from being immediately executed by preceeding it with the '>' character. All lines entered this way are halted, until any line not starting with '>' is being entered.
* The first input without '>' will execute all halted lines (and itself) in one chunk.
* Example of a chat input (the console will add an additional '>' to every line):
* >function a(x)
* >return x
* end
***********************
* Note that multiline inputs don't accept pure term evaluations, e.g. the following input is not supported and will prompt an error, while the same lines would have worked as two single-line inputs:
* >x = 5
* x
***********************
* -------------------
* |Reserved Keywords|
* -------------------
* The following keywords have a reserved functionality, i.e. are direct commands for the console and will not be interpreted as code:
* - 'help' - will show a list of all reserved keywords along very short explanations.
* - 'exit' - will shut down the console
* - 'share' - will share the players console with every other player, allowing others to read and write into it. Will force-close other players consoles, if they have one active.
* - 'clear' - will clear all text from the console, except the word 'clear'
* - 'lasttrace' - will show the stack trace of the latest error that occured within IngameConsole
* - 'show' - will show the console, after it was accidently hidden (you can accidently hide it by showing another multiboard, while the console functionality is still up and running).
* - 'printtochat' - will let the print function return to normal behaviour (i.e. print to the chat instead of the console).
* - 'printtoconsole'- will let the print function print to the console (which is default behaviour).
* - 'autosize on' - will enable automatic console resize depending on the longest string in the display. This is turned on by default.
* - 'autosize off' - will disable automatic console resize and instead linebreak long strings into multiple lines.
* - 'textlang eng' - lets the console use english Wc3 text language font size to compute linebreaks (look in your Blizzard launcher settings to find out)
* - 'textlang ger' - lets the console use german Wc3 text language font size to compute linebreaks (look in your Blizzard launcher settings to find out)
***********************
* --------------
* |Paste Helper|
* --------------
* @Luashine has created a tool that simplifies pasting multiple lines of code from outside Wc3 into the IngameConsole.
* This is particularly useful, when you want to execute a large chunk of testcode containing several linebreaks.
* Goto: https://github.com/Luashine/wc3-debug-console-paste-helper#readme
*
*************************************************/
--]]
----------------
--| Settings |--
----------------
---@class IngameConsole
IngameConsole = {
--Settings
numRows = 20 ---@type integer Number of Rows of the console (multiboard), excluding the title row. So putting 20 here will show 21 rows, first being the title row.
, autosize = true ---@type boolean Defines, whether the width of the main Column automatically adjusts with the longest string in the display.
, currentWidth = 0.5 ---@type number Current and starting Screen Share of the console main column.
, mainColMinWidth = 0.3 ---@type number Minimum Screen share of the console main column.
, mainColMaxWidth = 0.8 ---@type number Maximum Scren share of the console main column.
, tsColumnWidth = 0.06 ---@type number Screen Share of the Timestamp Column
, linebreakBuffer = 0.008 ---@type number Screen Share that is added to longest string in display to calculate the screen share for the console main column. Compensates for the small inaccuracy of the String Width function.
, maxLinebreaks = 8 ---@type integer Defines the maximum amount of linebreaks, before the remaining output string will be cut and not further displayed.
, printToConsole = true ---@type boolean defines, if the print function should print to the console or to the chat
, sharedConsole = false ---@type boolean defines, if the console is displayed to each player at the same time (accepting all players input) or if all players much start their own console.
, showTraceOnError = false ---@type boolean defines, if the console shows a trace upon printing errors. Usually not too useful within console, because you have just initiated the erroneous call.
, textLanguage = 'eng' ---@type string text language of your Wc3 installation, which influences font size (look in the settings of your Blizzard launcher). Currently only supports 'eng' and 'ger'.
, colors = {
timestamp = "bbbbbb" ---@type string Timestamp Color
, singleLineInput = "ffffaa" ---@type string Color to be applied to single line console inputs
, multiLineInput = "ffcc55" ---@type string Color to be applied to multi line console inputs
, returnValue = "00ffff" ---@type string Color applied to return values
, error = "ff5555" ---@type string Color to be applied to errors resulting of function calls
, keywordInput = "ff00ff" ---@type string Color to be applied to reserved keyword inputs (console reserved keywords)
, info = "bbbbbb" ---@type string Color to be applied to info messages from the console itself (for instance after creation or after printrestore)
}
--Privates
, numCols = 2 ---@type integer Number of Columns of the console (multiboard). Adjusting this requires further changes on code base.
, player = nil ---@type player player for whom the console is being created
, currentLine = 0 ---@type integer Current Output Line of the console.
, inputload = '' ---@type string Input Holder for multi-line-inputs
, output = {} ---@type string[] Array of all output strings
, outputTimestamps = {} ---@type string[] Array of all output string timestamps
, outputWidths = {} ---@type number[] remembers all string widths to allow for multiboard resize
, trigger = nil ---@type trigger trigger processing all inputs during console lifetime
, multiboard = nil ---@type multiboard
, timer = nil ---@type timer gets started upon console creation to measure timestamps
, errorHandler = nil ---@type fun(errorMsg:string):string error handler to be used within xpcall. We create one per console to make it compatible with console-specific settings.
, lastTrace = '' ---@type string trace of last error occured within console. To be printed via reserved keyword "lasttrace"
--Statics
, keywords = {} ---@type table<string,function> saves functions to be executed for all reserved keywords
, playerConsoles = {} ---@type table<player,IngameConsole> Consoles currently being active. up to one per player.
, originalPrint = print ---@type function original print function to restore, after the console gets closed.
}
IngameConsole.__index = IngameConsole
IngameConsole.__name = 'IngameConsole'
------------------------
--| Console Creation |--
------------------------
---Creates and opens up a new console.
---@param consolePlayer player player for whom the console is being created
---@return IngameConsole
function IngameConsole.create(consolePlayer)
local new = {} ---@type IngameConsole
setmetatable(new, IngameConsole)
---setup Object data
new.player = consolePlayer
new.output = {}
new.outputTimestamps = {}
new.outputWidths = {}
--Timer
new.timer = CreateTimer()
TimerStart(new.timer, 3600., true, nil) --just to get TimeElapsed for printing Timestamps.
--Trigger to be created after short delay, because otherwise it would fire on "-console" input immediately and lead to stack overflow.
new:setupTrigger()
--Multiboard
new:setupMultiboard()
--Create own error handler per console to be compatible with console-specific settings
new:setupErrorHandler()
--Share, if settings say so
if IngameConsole.sharedConsole then
new:makeShared() --we don't have to exit other players consoles, because we look for the setting directly in the class and there just logically can't be other active consoles.
end
--Welcome Message
new:out('info', 0, false, "Console started. Any further chat input will be executed as code, except when beginning with \x22-\x22.")
return new
end
---Creates the multiboard used for console display.
function IngameConsole:setupMultiboard()
self.multiboard = CreateMultiboard()
MultiboardSetRowCount(self.multiboard, self.numRows + 1) --title row adds 1
MultiboardSetColumnCount(self.multiboard, self.numCols)
MultiboardSetTitleText(self.multiboard, "Console")
local mbitem
for col = 1, self.numCols do
for row = 1, self.numRows + 1 do --Title row adds 1
mbitem = MultiboardGetItem(self.multiboard, row -1, col -1)
MultiboardSetItemStyle(mbitem, true, false)
MultiboardSetItemValueColor(mbitem, 255, 255, 255, 255) -- Colors get applied via text color code
MultiboardSetItemWidth(mbitem, (col == 1 and self.tsColumnWidth) or self.currentWidth )
MultiboardReleaseItem(mbitem)
end
end
mbitem = MultiboardGetItem(self.multiboard, 0, 0)
MultiboardSetItemValue(mbitem, "|cffffcc00Timestamp|r")
MultiboardReleaseItem(mbitem)
mbitem = MultiboardGetItem(self.multiboard, 0, 1)
MultiboardSetItemValue(mbitem, "|cffffcc00Line|r")
MultiboardReleaseItem(mbitem)
self:showToOwners()
end
---Creates the trigger that responds to chat events.
function IngameConsole:setupTrigger()
self.trigger = CreateTrigger()
TriggerRegisterPlayerChatEvent(self.trigger, self.player, "", false) --triggers on any input of self.player
TriggerAddCondition(self.trigger, Condition(function() return string.sub(GetEventPlayerChatString(),1,1) ~= '-' end)) --console will not react to entered stuff starting with '-'. This still allows to use other chat orders like "-exec".
TriggerAddAction(self.trigger, function() self:processInput(GetEventPlayerChatString()) end)
end
---Creates an Error Handler to be used by xpcall below.
---Adds stack trace plus formatting to the message.
function IngameConsole:setupErrorHandler()
self.errorHandler = function(errorMsg)
errorMsg = Debug.getLocalErrorMsg(errorMsg)
local _, tracePiece, lastFile = nil, "", errorMsg:match("^.-:") or "<unknown>" -- errors on objects created within Ingame Console don't have a file and linenumber. Consider "x = {}; x[nil] = 5".
local fullMsg = errorMsg .. "\nTraceback (most recent call first):\n" .. (errorMsg:match("^.-:\x25d+") or "<unknown>")
--Get Stack Trace. Starting at depth 5 ensures that "error", "messageHandler", "xpcall" and the input error message are not included.
for loopDepth = 5, 50 do --get trace on depth levels up to 50
---@diagnostic disable-next-line: cast-local-type, assign-type-mismatch
_, tracePiece = pcall(error, "", loopDepth) ---@type boolean, string
tracePiece = Debug.getLocalErrorMsg(tracePiece)
if #tracePiece > 0 then --some trace pieces can be empty, but there can still be valid ones beyond that
fullMsg = fullMsg .. " <- " .. ((tracePiece:match("^.-:") == lastFile) and tracePiece:match(":\x25d+"):sub(2,-1) or tracePiece:match("^.-:\x25d+"))
lastFile = tracePiece:match("^.-:")
end
end
self.lastTrace = fullMsg
return "ERROR: " .. (self.showTraceOnError and fullMsg or errorMsg)
end
end
---Shares this console with all players.
function IngameConsole:makeShared()
local player
for i = 0, GetBJMaxPlayers() -1 do
player = Player(i)
if (GetPlayerSlotState(player) == PLAYER_SLOT_STATE_PLAYING) and (IngameConsole.playerConsoles[player] ~= self) then --second condition ensures that the player chat event is not added twice for the same player.
IngameConsole.playerConsoles[player] = self
TriggerRegisterPlayerChatEvent(self.trigger, player, "", false) --triggers on any input
end
end
self.sharedConsole = true
end
---------------------
--| In |--
---------------------
---Processes a chat string. Each input will be printed. Incomplete multiline-inputs will be halted until completion. Completed inputs will be converted to a function and executed. If they have an output, it will be printed.
---@param inputString string
function IngameConsole:processInput(inputString)
--if the input is a reserved keyword, conduct respective actions and skip remaining actions.
if IngameConsole.keywords[inputString] then --if the input string is a reserved keyword
self:out('keywordInput', 1, false, inputString)
IngameConsole.keywords[inputString](self) --then call the method with the same name. IngameConsole.keywords["exit"](self) is just self.keywords:exit().
return
end
--if the input is a multi-line-input, queue it into the string buffer (inputLoad), but don't yet execute anything
if string.sub(inputString, 1, 1) == '>' then --multiLineInput
inputString = string.sub(inputString, 2, -1)
self:out('multiLineInput',2, false, inputString)
self.inputload = self.inputload .. inputString .. '\r' --carriage return
else --if the input is either singleLineInput OR the last line of multiLineInput, execute the whole thing.
self:out(self.inputload == '' and 'singleLineInput' or 'multiLineInput', 1, false, inputString)
self.inputload = self.inputload .. inputString
local loadedFunc, errorMsg = load("return " .. self.inputload) --adds return statements, if possible (works for term statements)
if loadedFunc == nil then
loadedFunc, errorMsg = load(self.inputload)
end
self.inputload = '' --empty inputload before execution of pcall. pcall can break (rare case, can for example be provoked with metatable.__tostring = {}), which would corrupt future console inputs.
--manually catch case, where the input did not define a proper Lua statement (i.e. loadfunc is nil)
local results = loadedFunc and table.pack(xpcall(loadedFunc, self.errorHandler)) or {false, "Input is not a valid Lua-statement: " .. errorMsg}
--output error message (unsuccessful case) or return values (successful case)
if not results[1] then --results[1] is the error status that pcall always returns. False stands for: error occured.
self:out('error', 0, true, results[2]) -- second result of pcall is the error message in case an error occured
elseif results.n > 1 then --Check, if there was at least one valid output argument. We check results.n instead of results[2], because we also get nil as a proper return value this way.
self:out('returnValue', 0, true, table.unpack(results, 2, results.n))
end
end
end
----------------------
--| Out |--
----------------------
-- split color codes, split linebreaks, print lines separately, print load-errors, update string width, update text, error handling with stack trace.
---Duplicates Color coding around linebreaks to make each line printable separately.
---Operates incorrectly on lookalike color codes invalidated by preceeding escaped vertical bar (like "||cffffcc00bla|r").
---Also operates incorrectly on multiple color codes, where the first is missing the end sequence (like "|cffffcc00Hello |cff0000ffWorld|r")
---@param inputString string
---@return string, integer
function IngameConsole.spreadColorCodes(inputString)
local replacementTable = {} --remembers all substrings to be replaced and their replacements.
for foundInstance, color in inputString:gmatch("((|c\x25x\x25x\x25x\x25x\x25x\x25x\x25x\x25x).-|r)") do
replacementTable[foundInstance] = foundInstance:gsub("(\r?\n)", "|r\x251" .. color)
end
return inputString:gsub("((|c\x25x\x25x\x25x\x25x\x25x\x25x\x25x\x25x).-|r)", replacementTable)
end
---Concatenates all inputs to one string, spreads color codes around line breaks and prints each line to the console separately.
---@param colorTheme? '"timestamp"'| '"singleLineInput"' | '"multiLineInput"' | '"result"' | '"keywordInput"' | '"info"' | '"error"' | '"returnValue"' Decides about the color to be applied. Currently accepted: 'timestamp', 'singleLineInput', 'multiLineInput', 'result', nil. (nil equals no colorTheme, i.e. white color)
---@param numIndentations integer Number of '>' chars that shall preceed the output
---@param hideTimestamp boolean Set to false to hide the timestamp column and instead show a "->" symbol.
---@param ... any the things to be printed in the console.
function IngameConsole:out(colorTheme, numIndentations, hideTimestamp, ...)
local inputs = table.pack(...)
for i = 1, inputs.n do
inputs[i] = tostring(inputs[i]) --apply tostring on every input param in preparation for table.concat
end
--Concatenate all inputs (4-space-separated)
local printOutput = table.concat(inputs, ' ', 1, inputs.n)
printOutput = printOutput:find("(\r?\n)") and IngameConsole.spreadColorCodes(printOutput) or printOutput
local substrStart, substrEnd = 1, 1
local numLinebreaks, completePrint = 0, true
repeat
substrEnd = (printOutput:find("(\r?\n)", substrStart) or 0) - 1
numLinebreaks, completePrint = self:lineOut(colorTheme, numIndentations, hideTimestamp, numLinebreaks, printOutput:sub(substrStart, substrEnd))
hideTimestamp = true
substrStart = substrEnd + 2
until substrEnd == -1 or numLinebreaks > self.maxLinebreaks
if substrEnd ~= -1 or not completePrint then
self:lineOut('info', 0, false, 0, "Previous value not entirely printed after exceeding maximum number of linebreaks. Consider adjusting 'IngameConsole.maxLinebreaks'.")
end
self:updateMultiboard()
end
---Prints the given string to the console with the specified colorTheme and the specified number of indentations.
---Only supports one-liners (no \n) due to how multiboards work. Will add linebreaks though, if the one-liner doesn't fit into the given multiboard space.
---@param colorTheme? '"timestamp"'| '"singleLineInput"' | '"multiLineInput"' | '"result"' | '"keywordInput"' | '"info"' | '"error"' | '"returnValue"' Decides about the color to be applied. Currently accepted: 'timestamp', 'singleLineInput', 'multiLineInput', 'result', nil. (nil equals no colorTheme, i.e. white color)
---@param numIndentations integer Number of greater '>' chars that shall preceed the output
---@param hideTimestamp boolean Set to false to hide the timestamp column and instead show a "->" symbol.
---@param numLinebreaks integer
---@param printOutput string the line to be printed in the console.
---@return integer numLinebreaks, boolean hasPrintedEverything returns true, if everything could be printed. Returns false otherwise (can happen for very long strings).
function IngameConsole:lineOut(colorTheme, numIndentations, hideTimestamp, numLinebreaks, printOutput)
--add preceeding greater chars
printOutput = ('>'):rep(numIndentations) .. printOutput
--Print a space instead of the empty string. This allows the console to identify, if the string has already been fully printed (see while-loop below).
if printOutput == '' then
printOutput = ' '
end
--Compute Linebreaks.
local linebreakWidth = ((self.autosize and self.mainColMaxWidth) or self.currentWidth )
local partialOutput = nil
local maxPrintableCharPosition
local printWidth
while string.len(printOutput) > 0 and numLinebreaks <= self.maxLinebreaks do --break, if the input string has reached length 0 OR when the maximum number of linebreaks would be surpassed.
--compute max printable substring (in one multiboard line)
maxPrintableCharPosition, printWidth = IngameConsole.getLinebreakData(printOutput, linebreakWidth - self.linebreakBuffer, self.textLanguage)
--adds timestamp to the first line of any output
if numLinebreaks == 0 then
partialOutput = printOutput:sub(1, numIndentations) .. ((IngameConsole.colors[colorTheme] and "|cff" .. IngameConsole.colors[colorTheme] .. printOutput:sub(numIndentations + 1, maxPrintableCharPosition) .. "|r") or printOutput:sub(numIndentations + 1, maxPrintableCharPosition)) --Colorize the output string, if a color theme was specified. IngameConsole.colors[colorTheme] can be nil.
table.insert(self.outputTimestamps, "|cff" .. IngameConsole.colors['timestamp'] .. ((hideTimestamp and ' ->') or IngameConsole.formatTimerElapsed(TimerGetElapsed(self.timer))) .. "|r")
else
partialOutput = (IngameConsole.colors[colorTheme] and "|cff" .. IngameConsole.colors[colorTheme] .. printOutput:sub(1, maxPrintableCharPosition) .. "|r") or printOutput:sub(1, maxPrintableCharPosition) --Colorize the output string, if a color theme was specified. IngameConsole.colors[colorTheme] can be nil.
table.insert(self.outputTimestamps, ' ..') --need a dummy entry in the timestamp list to make it line-progress with the normal output.
end
numLinebreaks = numLinebreaks + 1
--writes output string and width to the console tables.
table.insert(self.output, partialOutput)
table.insert(self.outputWidths, printWidth + self.linebreakBuffer) --remember the Width of this printed string to adjust the multiboard size in case. 0.5 percent is added to avoid the case, where the multiboard width is too small by a tiny bit, thus not showing some string without spaces.
--compute remaining string to print
printOutput = string.sub(printOutput, maxPrintableCharPosition + 1, -1) --remaining string until the end. Returns empty string, if there is nothing left
end
self.currentLine = #self.output
return numLinebreaks, string.len(printOutput) == 0 --printOutput is the empty string, if and only if everything has been printed
end
---Lets the multiboard show the recently printed lines.
function IngameConsole:updateMultiboard()
local startIndex = math.max(self.currentLine - self.numRows, 0) --to be added to loop counter to get to the index of output table to print
local outputIndex = 0
local maxWidth = 0.
local mbitem
for i = 1, self.numRows do --doesn't include title row (index 0)
outputIndex = i + startIndex
mbitem = MultiboardGetItem(self.multiboard, i, 0)
MultiboardSetItemValue(mbitem, self.outputTimestamps[outputIndex] or '')
MultiboardReleaseItem(mbitem)
mbitem = MultiboardGetItem(self.multiboard, i, 1)
MultiboardSetItemValue(mbitem, self.output[outputIndex] or '')
MultiboardReleaseItem(mbitem)
maxWidth = math.max(maxWidth, self.outputWidths[outputIndex] or 0.) --looping through non-defined widths, so need to coalesce with 0
end
--Adjust Multiboard Width, if necessary.
maxWidth = math.min(math.max(maxWidth, self.mainColMinWidth), self.mainColMaxWidth)
if self.autosize and self.currentWidth ~= maxWidth then
self.currentWidth = maxWidth
for i = 1, self.numRows +1 do
mbitem = MultiboardGetItem(self.multiboard, i-1, 1)
MultiboardSetItemWidth(mbitem, maxWidth)
MultiboardReleaseItem(mbitem)
end
self:showToOwners() --reshow multiboard to update item widths on the frontend
end
end
---Shows the multiboard to all owners (one or all players)
function IngameConsole:showToOwners()
if self.sharedConsole or GetLocalPlayer() == self.player then
MultiboardDisplay(self.multiboard, true)
MultiboardMinimize(self.multiboard, false)
end
end
---Formats the elapsed time as "mm: ss. hh" (h being a hundreds of a sec)
function IngameConsole.formatTimerElapsed(elapsedInSeconds)
return string.format("\x2502d: \x2502.f. \x2502.f", elapsedInSeconds // 60, math.fmod(elapsedInSeconds, 60.) // 1, math.fmod(elapsedInSeconds, 1) * 100)
end
---Computes the max printable substring for a given string and a given linebreakWidth (regarding a single line of console).
---Returns both the substrings last char position and its total width in the multiboard.
---@param stringToPrint string the string supposed to be printed in the multiboard console.
---@param linebreakWidth number the maximum allowed width in one line of the console, before a string must linebreak
---@param textLanguage string 'ger' or 'eng'
---@return integer maxPrintableCharPosition, number printWidth
function IngameConsole.getLinebreakData(stringToPrint, linebreakWidth, textLanguage)
local loopWidth = 0.
local bytecodes = table.pack(string.byte(stringToPrint, 1, -1))
for i = 1, bytecodes.n do
loopWidth = loopWidth + string.charMultiboardWidth(bytecodes[i], textLanguage)
if loopWidth > linebreakWidth then
return i-1, loopWidth - string.charMultiboardWidth(bytecodes[i], textLanguage)
end
end
return bytecodes.n, loopWidth
end
-------------------------
--| Reserved Keywords |--
-------------------------
---Exits the Console
---@param self IngameConsole
function IngameConsole.keywords.exit(self)
DestroyMultiboard(self.multiboard)
DestroyTrigger(self.trigger)
DestroyTimer(self.timer)
IngameConsole.playerConsoles[self.player] = nil
if next(IngameConsole.playerConsoles) == nil then --set print function back to original, when no one has an active console left.
print = IngameConsole.originalPrint
end
end
---Lets the console print to chat
---@param self IngameConsole
function IngameConsole.keywords.printtochat(self)
self.printToConsole = false
self:out('info', 0, false, "The print function will print to the normal chat.")
end
---Lets the console print to itself (default)
---@param self IngameConsole
function IngameConsole.keywords.printtoconsole(self)
self.printToConsole = true
self:out('info', 0, false, "The print function will print to the console.")
end
---Shows the console in case it was hidden by another multiboard before
---@param self IngameConsole
function IngameConsole.keywords.show(self)
self:showToOwners() --might be necessary to do, if another multiboard has shown up and thereby hidden the console.
self:out('info', 0, false, "Console is showing.")
end
---Prints all available reserved keywords plus explanations.
---@param self IngameConsole
function IngameConsole.keywords.help(self)
self:out('info', 0, false, "The Console currently reserves the following keywords:")
self:out('info', 0, false, "'help' shows the text you are currently reading.")
self:out('info', 0, false, "'exit' closes the console.")
self:out('info', 0, false, "'lasttrace' shows the stack trace of the latest error that occured within IngameConsole.")
self:out('info', 0, false, "'share' allows other players to read and write into your console, but also force-closes their own consoles.")
self:out('info', 0, false, "'clear' clears all text from the console.")
self:out('info', 0, false, "'show' shows the console. Sensible to use, when displaced by another multiboard.")
self:out('info', 0, false, "'printtochat' lets Wc3 print text to normal chat again.")
self:out('info', 0, false, "'printtoconsole' lets Wc3 print text to the console (default).")
self:out('info', 0, false, "'autosize on' enables automatic console resize depending on the longest line in the display.")
self:out('info', 0, false, "'autosize off' retains the current console size.")
self:out('info', 0, false, "'textlang eng' will use english text installation font size to compute linebreaks (default).")
self:out('info', 0, false, "'textlang ger' will use german text installation font size to compute linebreaks.")
self:out('info', 0, false, "Preceeding a line with '>' prevents immediate execution, until a line not starting with '>' has been entered.")
end
---Clears the display of the console.
---@param self IngameConsole
function IngameConsole.keywords.clear(self)
self.output = {}
self.outputTimestamps = {}
self.outputWidths = {}
self.currentLine = 0
self:out('keywordInput', 1, false, 'clear') --we print 'clear' again. The keyword was already printed by self:processInput, but cleared immediately after.
end
---Shares the console with other players in the same game.
---@param self IngameConsole
function IngameConsole.keywords.share(self)
for _, console in pairs(IngameConsole.playerConsoles) do
if console ~= self then
IngameConsole.keywords['exit'](console) --share was triggered during console runtime, so there potentially are active consoles of others players that need to exit.
end
end
self:makeShared()
self:showToOwners() --showing it to the other players.
self:out('info', 0,false, "The console of player " .. GetConvertedPlayerId(self.player) .. " is now shared with all players.")
end
---Enables auto-sizing of console (will grow and shrink together with text size)
---@param self IngameConsole
IngameConsole.keywords["autosize on"] = function(self)
self.autosize = true
self:out('info', 0,false, "The console will now change size depending on its content.")
end
---Disables auto-sizing of console
---@param self IngameConsole
IngameConsole.keywords["autosize off"] = function(self)
self.autosize = false
self:out('info', 0,false, "The console will retain the width that it currently has.")
end
---Lets linebreaks be computed by german font size
---@param self IngameConsole
IngameConsole.keywords["textlang ger"] = function(self)
self.textLanguage = 'ger'
self:out('info', 0,false, "Linebreaks will now compute with respect to german text installation font size.")
end
---Lets linebreaks be computed by english font size
---@param self IngameConsole
IngameConsole.keywords["textlang eng"] = function(self)
self.textLanguage = 'eng'
self:out('info', 0,false, "Linebreaks will now compute with respect to english text installation font size.")
end
---Prints the stack trace of the latest error that occured within IngameConsole.
---@param self IngameConsole
IngameConsole.keywords["lasttrace"] = function(self)
self:out('error', 0,false, self.lastTrace)
end
--------------------
--| Main Trigger |--
--------------------
do
--Actions to be executed upon typing -exec
local function execCommand_Actions()
local input = string.sub(GetEventPlayerChatString(),7,-1)
print("Executing input: |cffffff44" .. input .. "|r")
--try preceeding the input by a return statement (preparation for printing below)
local loadedFunc, errorMsg = load("return ".. input)
if not loadedFunc then --if that doesn't produce valid code, try without return statement
loadedFunc, errorMsg = load(input)
end
--execute loaded function in case the string defined a valid function. Otherwise print error.
if errorMsg then
print("|cffff5555Invalid Lua-statement: " .. Debug.getLocalErrorMsg(errorMsg) .. "|r")
else
---@diagnostic disable-next-line: param-type-mismatch
local results = table.pack(Debug.try(loadedFunc))
if results[1] ~= nil or results.n > 1 then
for i = 1, results.n do
results[i] = tostring(results[i])
end
--concatenate all function return values to one colorized string
print("|cff00ffff" .. table.concat(results, ' ', 1, results.n) .. "|r")
end
end
end
local function execCommand_Condition()
return string.sub(GetEventPlayerChatString(), 1, 6) == "-exec "
end
local function startIngameConsole()
--if the triggering player already has a console, show that console and stop executing further actions
if IngameConsole.playerConsoles[GetTriggerPlayer()] then
IngameConsole.playerConsoles[GetTriggerPlayer()]:showToOwners()
return
end
--create Ingame Console object
IngameConsole.playerConsoles[GetTriggerPlayer()] = IngameConsole.create(GetTriggerPlayer())
--overwrite print function
print = function(...)
IngameConsole.originalPrint(...) --the new print function will also print "normally", but clear the text immediately after. This is to add the message to the F12-log.
if IngameConsole.playerConsoles[GetLocalPlayer()] and IngameConsole.playerConsoles[GetLocalPlayer()].printToConsole then
ClearTextMessages() --clear text messages for all players having an active console
end
for player, console in pairs(IngameConsole.playerConsoles) do
if console.printToConsole and (player == console.player) then --player == console.player ensures that the console only prints once, even if the console was shared among all players
console:out(nil, 0, false, ...)
end
end
end
end
---Creates the triggers listening to "-console" and "-exec" chat input.
---Being executed within DebugUtils (MarkGameStart overwrite).
function IngameConsole.createTriggers()
--Exec
local execTrigger = CreateTrigger()
TriggerAddCondition(execTrigger, Condition(execCommand_Condition))
TriggerAddAction(execTrigger, execCommand_Actions)
--Real Console
local consoleTrigger = CreateTrigger()
TriggerAddAction(consoleTrigger, startIngameConsole)
--Events
for i = 0, GetBJMaxPlayers() -1 do
TriggerRegisterPlayerChatEvent(execTrigger, Player(i), "-exec ", false)
TriggerRegisterPlayerChatEvent(consoleTrigger, Player(i), "-console", true)
end
end
end
Debug.endFile()
do LIBRARY_ClickAndHoldMovement = true
local SCOPE_PREFIX = "ClickAndHoldMovement_" ---@type string
--[[
===========================================================================================
Click-And-Hold Movement
by Antares
Enable click-and-hold movement (hold the right mouse-button to move your hero) for hero maps
like aeon of strife, hero arenas, or rpgs.
Requires totalInitialization.
===========================================================================================
]]
--====================================================
--Config
--====================================================
local IGNORE_MOUSE_SPELL_DURATION = 0.5 ---@type number --Disables the click-and-hold trigger for this many seconds when a unit in the selected group casts a spell. This enables the user to cast a spell without releasing the right mouse-button.
local IGNORE_MOUSE_CLICK_DURATION = 0.25 ---@type number --Disables the click-and-hold trigger for this many seconds right after the right mouse-button is pressed. This prevents the trigger from firing on a simple right-click.
local MOUSE_MOVE_COOLDOWN_DURATION = 0.1 ---@type number --Duration of the cooldown on the click-and-hold trigger on giving orders.
local DISABLE_IF_MULTIPLE_SELECTED = false ---@type boolean
local STOP_MOVING_ON_RELEASE = false ---@type boolean --The commanded units will stop moving as soon as the right mouse-button is released. They will also ignore pathing blockers between the mouse-cursor and the unit.
local CUSTOM_CALLBACK = false ---@type boolean --Enable if you want to write your own callback function for the click-and-hold trigger. Otherwise, it will be a replaced by a simple smart command.
--====================================================
local mouseMoveTrigger={} ---@type trigger[]
MouseX = {} ---@type number[]
MouseY = {} ---@type number[]
local rightClickOn = {} ---@type boolean[]
local ignoreMouseTimer = {} ---@type timer[]
local data = {}
local selectedUnits={} ---@type group[]
local setGroup = {} ---@type boolean[]
local noOrders = {} ---@type boolean[]
--====================================================
---@param whichUnit unit
---@param x number
---@param y number
local function CustomCallback(whichUnit, x, y)
--Define your custom callback code here.
end
--====================================================
---@param P player
---@return boolean
local function SetAndCheckSelection(P)
local invalidSelection ---@type boolean
local first ---@type unit
selectedUnits[P] = CreateGroup()
GroupEnumUnitsSelected(selectedUnits[P] , P , nil)
if DISABLE_IF_MULTIPLE_SELECTED then
invalidSelection = BlzGroupGetSize(selectedUnits[P]) ~= 1
else
invalidSelection = BlzGroupGetSize(selectedUnits[P]) == 0
end
setGroup[P] = false
if invalidSelection then
DestroyGroup(selectedUnits[P])
return false
else
first = FirstOfGroup(selectedUnits[P])
if GetOwningPlayer(first) == P or (IsUnitAlly(first,P) and GetPlayerAlliance(GetOwningPlayer(first),P,ALLIANCE_SHARED_CONTROL)) then
return true
else
DestroyGroup(selectedUnits[P])
return false
end
end
end
---@param P player
local function CommandGroup(P)
local i = BlzGroupGetSize(selectedUnits[P]) - 1 ---@type integer
local u ---@type unit
local angle ---@type number
while i >= 0 do
if CUSTOM_CALLBACK then
CustomCallback( BlzGroupUnitAt(selectedUnits[P] , i) , MouseX[P] , MouseY[P] )
elseif STOP_MOVING_ON_RELEASE then
u = BlzGroupUnitAt(selectedUnits[P] , i)
angle = Atan2( MouseY[P] - GetUnitY(u) , MouseX[P] - GetUnitX(u) )
IssuePointOrderById( BlzGroupUnitAt(selectedUnits[P] , i) , 851971 , GetUnitX(u) + 50*Cos(angle) , GetUnitY(u) + 50*Sin(angle) )
else
IssuePointOrderById( BlzGroupUnitAt(selectedUnits[P] , i) , 851971 , MouseX[P] , MouseY[P] )
end
i = i - 1
end
end
local function Enable()
local P = data[GetExpiredTimer()] ---@type player
noOrders[P] = false
if rightClickOn[P] then
if setGroup[P] then
if SetAndCheckSelection(P) then
CommandGroup(P)
end
else
CommandGroup(P)
end
end
end
local function MouseSpellIgnore()
local whichUnit = GetSpellAbilityUnit() ---@type unit
local P = GetOwningPlayer(whichUnit) ---@type player
if IsUnitInGroup(whichUnit , selectedUnits[P]) then
noOrders[P] = true
TimerStart( ignoreMouseTimer[P] , IGNORE_MOUSE_SPELL_DURATION , false , Enable )
end
end
local function MouseMove()
local P = GetTriggerPlayer() ---@type player
local mX = BlzGetTriggerPlayerMouseX() ---@type number
local mY = BlzGetTriggerPlayerMouseY() ---@type number
if mY ~= 0 or mX ~= 0 then
MouseX[P] = mX
MouseY[P] = mY
end
if noOrders[P] then
return
end
if MOUSE_MOVE_COOLDOWN_DURATION > 0 then
noOrders[P] = true
TimerStart( ignoreMouseTimer[P] , MOUSE_MOVE_COOLDOWN_DURATION , false , Enable )
end
CommandGroup(P)
end
local function MouseRightClick()
local P ---@type player
if BlzGetTriggerPlayerMouseButton() == MOUSE_BUTTON_TYPE_RIGHT then
P = GetTriggerPlayer()
rightClickOn[P] = true
noOrders[P] = true
setGroup[P] = true
MouseX[P] = BlzGetTriggerPlayerMouseX()
MouseY[P] = BlzGetTriggerPlayerMouseY()
TimerStart( ignoreMouseTimer[P] , IGNORE_MOUSE_CLICK_DURATION , false , Enable )
EnableTrigger(mouseMoveTrigger[P])
end
end
local function MouseRightRelease()
local P ---@type player
if BlzGetTriggerPlayerMouseButton() == MOUSE_BUTTON_TYPE_RIGHT then
P = GetTriggerPlayer()
DestroyGroup(selectedUnits[P])
rightClickOn[P] = false
DisableTrigger(mouseMoveTrigger[P])
end
end
local function At0s()
local P ---@type player
local trigDown = CreateTrigger() ---@type trigger
local trigUp = CreateTrigger() ---@type trigger
local trigIgnore = CreateTrigger() ---@type trigger
for p = 0, 23 do
P = Player(p)
if GetPlayerSlotState(P) == PLAYER_SLOT_STATE_PLAYING and GetPlayerController(P) == MAP_CONTROL_USER then
mouseMoveTrigger[P] = CreateTrigger()
TriggerRegisterPlayerEvent( trigDown, P, EVENT_PLAYER_MOUSE_DOWN )
TriggerRegisterPlayerEvent( trigUp, P, EVENT_PLAYER_MOUSE_UP )
TriggerRegisterPlayerEvent( mouseMoveTrigger[P], P, EVENT_PLAYER_MOUSE_MOVE )
TriggerAddAction( mouseMoveTrigger[P] , MouseMove )
DisableTrigger(mouseMoveTrigger[P])
ignoreMouseTimer[P] = CreateTimer()
data[ignoreMouseTimer[P]] = P
end
p = p + 1
end
DestroyTrigger(GetTriggeringTrigger())
TriggerAddAction( trigDown , MouseRightClick )
TriggerAddAction( trigUp , MouseRightRelease )
TriggerRegisterAnyUnitEventBJ( trigIgnore, EVENT_PLAYER_UNIT_SPELL_CAST )
TriggerAddAction( trigIgnore , MouseSpellIgnore )
end
OnInit.global(function()
local at0sTrigger = CreateTrigger() ---@type trigger
TriggerRegisterTimerEvent( at0sTrigger , 0.0 , false )
TriggerAddAction( at0sTrigger , At0s )
end)
end
-- HideMinDamageV3 NOFDF
do
local realFunction = MarkGameStarted
local timer, damageA, damageB, parentA, parentB, damageA2, damageB2, text, index
local function update(sourceFrame, targetFrame)
text = BlzFrameGetText(sourceFrame)
index = string.find(text, " - ", 1, true)
BlzFrameSetText(targetFrame, string.sub( text, index + 3))
end
local function Init()
if not timer then timer = CreateTimer() end
damageA = BlzGetFrameByName("InfoPanelIconValue", 0)
damageB = BlzGetFrameByName("InfoPanelIconValue", 1)
parentA = BlzGetFrameByName("SimpleInfoPanelIconDamage",0)
parentB = BlzGetFrameByName("SimpleInfoPanelIconDamage",1)
BlzCreateSimpleFrame("SimpleInfoPanelDestructableDetail", parentA, 11)
damageA2 = BlzGetFrameByName("SimpleDestructableNameValue", 11)
BlzFrameClearAllPoints(damageA2)
BlzFrameSetPoint(damageA2, FRAMEPOINT_TOPLEFT, BlzGetFrameByName("InfoPanelIconLabel", 0), FRAMEPOINT_BOTTOMLEFT, 0.002625, -0.003)
if SkinManagerGetLocalPath then BlzFrameSetFont(damageA2, SkinManagerGetLocalPath("InfoPanelTextFont"), 0.008, 0) else BlzFrameSetFont(damageA2, "Fonts/frizqt__.ttf", 0.008, 0) end
BlzCreateSimpleFrame("SimpleInfoPanelDestructableDetail", parentB, 12)
damageB2 = BlzGetFrameByName("SimpleDestructableNameValue", 12)
BlzFrameSetFont(damageA, "", 0, 0)
BlzFrameSetFont(damageB, "", 0, 0)
BlzFrameClearAllPoints(damageB2)
BlzFrameSetPoint(damageB2, FRAMEPOINT_TOPLEFT, BlzGetFrameByName("InfoPanelIconLabel", 1), FRAMEPOINT_BOTTOMLEFT, 0.002625, -0.003)
if SkinManagerGetLocalPath then BlzFrameSetFont(damageB2, SkinManagerGetLocalPath("InfoPanelTextFont"), 0.008, 0) else BlzFrameSetFont(damageB2, "Fonts/frizqt__.ttf", 0.008, 0) end
TimerStart(timer, 0.05, true, function()
if BlzFrameIsVisible(parentA) then
update(damageA, damageA2)
end
if BlzFrameIsVisible(parentB) then
update(damageB, damageB2)
end
end)
end
function MarkGameStarted()
realFunction()
realFunction = nil
Init()
if FrameLoaderAdd then FrameLoaderAdd(Init) end
end
end
-- in 1.31 and upto 1.32.9 PTR (when I wrote this). Frames are not correctly saved and loaded, breaking the game.
-- This runs all functions added to it with a 0s delay after the game was loaded.
FrameLoader = {
OnLoadTimer = function ()
for _,v in ipairs(FrameLoader) do v() end
end
,OnLoadAction = function()
for _,v in ipairs(FrameLoader) do v() end
TimerStart(FrameLoader.Timer, 0, false, FrameLoader.OnLoadTimer)
end
}
function FrameLoaderAdd(func)
if not FrameLoader.Timer then
FrameLoader.Trigger = CreateTrigger()
FrameLoader.Timer = CreateTimer()
TriggerRegisterGameEvent(FrameLoader.Trigger, EVENT_GAME_LOADED)
TriggerAddAction(FrameLoader.Trigger, FrameLoader.OnLoadAction)
end
table.insert(FrameLoader, func)
end
if Debug then Debug.beginFile "NeatTextMessages" end
do
--[[
===========================================================================================
Neat Text Messages
by Antares
Recreation of the default text messages with more customizability.
How to import:
Copy this library into your map. To get better looking messages with text shadow and an optional
tooltip-like box around the text, copy the "NeatTextMessage.fdf" and "NeatMessageTemplates.toc"
files from the test map into your map without a subpath.
Edit the parameters in the config section to your liking.
Replace all DisplayTextToForce calls etc. with the appropriate function from this library.
GUI users: You can use the REPLACE_BLIZZARD_FUNCTION_CALLS feature. This will replace all calls
automatically. You don't need to do anything else. This feature requires the Hook library. The
text messages created by the replacement will use the default window and format.
WARNING: Calling neat message functions (but not clear functions) from within local player code
with REPLACE_BLIZZARD_FUNCTION_CALLS will cause a desync!
Default text formatting can be overwritten by setting up NeatFormats. Examples are given in the
test section. All formatting parameters that aren't set for a NeatFormat will use the default
values instead.
NeatMessage creator functions return an integer. This integer is a pointer to the created message
that can be used to edit, extend, or remove the message. The returned integer is asynchronous
and will be 0 for all players for whom the message isn't displayed.
You can set up additional text windows with NeatWindow.create. If you create a neat message
without specifying the window in which it should be created, it will always be created in the
default window specified in the config.
===========================================================================================
API
===========================================================================================
NeatMessage(whichMessage)
NeatMessageToPlayer(whichPlayer, whichMessage)
NeatMessageToForce(whichForce, whichMessage)
NeatMessageTimed(duration, whichMessage)
NeatMessageToPlayerTimed(whichPlayer, duration, whichMessage)
NeatMessageToForceTimed(whichForce, duration, whichMessage)
NeatMessageFormatted(whichMessage, whichFormat)
NeatMessageToPlayerFormatted(whichPlayer, whichMessage, whichFormat)
NeatMessageToForceFormatted(whichForce, whichMessage, whichFormat)
NeatMessageTimedFormatted(duration, whichMessage, whichFormat)
NeatMessageToPlayerTimedFormatted(whichPlayer, duration, whichMessage, whichFormat)
NeatMessageToForceTimedFormatted(whichForce, duration, whichMessage, whichFormat)
NeatMessageInWindow(whichMessage, whichWindow)
NeatMessageToPlayerInWindow(whichPlayer, whichMessage, whichWindow)
NeatMessageToForceInWindow(whichForce, whichMessage, whichWindow)
NeatMessageTimedInWindow(duration, whichMessage, whichWindow)
NeatMessageToPlayerTimedInWindow(whichPlayer, duration, whichMessage, whichWindow)
NeatMessageToForceTimedInWindow(whichForce, duration, whichMessage, whichWindow)
NeatMessageFormattedInWindow(whichMessage, whichFormat, whichWindow)
NeatMessageToPlayerFormattedInWindow(whichPlayer, whichMessage, whichFormat, whichWindow)
NeatMessageToForceFormattedInWindow(whichForce, whichMessage, whichFormat, whichWindow)
NeatMessageTimedFormattedInWindow(duration, whichMessage, whichFormat, whichWindow)
NeatMessageToPlayerTimedFormattedInWindow(whichPlayer, duration, whichMessage, whichFormat, whichWindow)
NeatMessageToForceTimedFormattedInWindow(whichForce, duration, whichMessage, whichFormat, whichWindow)
===========================================================================================
EditNeatMessage(messagePointer, newText)
AddNeatMessageTimeRemaining(messagePointer, additionalTime)
SetNeatMessageTimeRemaining(messagePointer, newTime)
RemoveNeatMessage(messagePointer)
AutoSetNeatMessageTimeRemaining(messagePointer, accountForTimeElapsed)
IsMessageDisplayed(messagePointer)
NeatMessageAddIcon(messagePointer, width, height, orientation, texture)
(valid arguments for orientation are "topleft", "topright", "bottomleft", "bottomright")
NeatMessageHideIcon(messagePointer)
ClearNeatMessages()
ClearNeatMessagesForPlayer(whichPlayer)
ClearNeatMessagesForForce(whichForce)
ClearNeatMessagesInWindow(whichWindow)
ClearNeatMessagesForPlayerInWindow(whichPlayer, whichWindow)
ClearNeatMessagesForForceInWindow(whichForce, whichWindow)
set myFormat = NeatFormat.create()
set myFormat.spacing =
set myFormat.fadeOutTime =
set myFormat.fadeInTime =
set myFormat.fontSize =
set myFormat.minDuration =
set myFormat.durationIncrease =
set myFormat.verticalAlignment =
set myFormat.horizontalAlignment =
set myFormat.isBoxed =
call myFormat:copy(copiedFormat)
set myWindow = NeatWindow.create(xPosition, yPosition, width, height, maxMessages, topToBottom)
===========================================================================================
]]
--=========================================================================================
--Config
--=========================================================================================
--Default text formatting. Can be overwritten by setting up neatFormats.
local MESSAGE_MINIMUM_DURATION = 2.5 ---@type number --Display duration of a message with zero characters.
local MESSAGE_DURATION_INCREASE_PER_CHARACTER = 0.12 ---@type number
local TEXT_MESSAGE_FONT_SIZE = 14 ---@type number
local SPACING_BETWEEN_MESSAGES = 0.0 ---@type number
local FADE_IN_TIME = 0.0 ---@type number
local FADE_OUT_TIME = 1.8 ---@type number
local VERTICAL_ALIGNMENT = TEXT_JUSTIFY_MIDDLE ---@type textaligntype --TEXT_JUSTIFY_BOTTOM, TEXT_JUSTIFY_MIDDLE, or TEXT_JUSTIFY_TOP
local HORIZONTAL_ALIGNMENT = TEXT_JUSTIFY_CENTER ---@type textaligntype --TEXT_JUSTIFY_LEFT, TEXT_JUSTIFY_CENTER, or TEXT_JUSTIFY_RIGHT
local BOXED_MESSAGES = true ---@type boolean --Create tooltip box around text messages? Requires .fdf file and INCLUDE_FDF enabled.
--Default text window parameters.
TEXT_MESSAGE_X_POSITION = 0.225 ---@type number --0 = left, 1 = right (bottom-left corner)
TEXT_MESSAGE_Y_POSITION = 0.16 ---@type number --0 = bottom, 0.6 = top (bottom-left corner)
TEXT_MESSAGE_BLOCK_MAX_HEIGHT = 0.2 ---@type number --Maximum height of the entire text message block. Messages pushed out of that area will be removed.
TEXT_MESSAGE_BLOCK_WIDTH = 0.35 ---@type number
MAX_TEXT_MESSAGES = 5 ---@type integer --Maximum number of messages on the screen at the same time. If you want a non-scrolling window, simply set this number to 1.
MESSAGE_ORDER_TOP_TO_BOTTOM = false ---@type boolean --Set true if new messages should appear above old messages.
--Config
local INCLUDE_FDF = true ---@type boolean --NeatMessage.fdf has been imported?
local COPY_TO_MESSAGE_LOG = true ---@type boolean --(Only singleplayer) Copies messages to message log by printing out the message with DisplayTextToPlayer, then clearing all text. Will interfere with other default text messages.
local REPLACE_BLIZZARD_FUNCTION_CALLS = true ---@type boolean --Replaces Display(Timed)TextToForce, ClearTextMessages, and ClearTextMessagesBJ.
local TOOLTIP_ABILITY = 'Amls' ---@type string --For REPLACE_BLIZZARD_FUNCTION_CALLS only. Any unused ability for which the library can change the tooltip to extract the TRIGSTR from.
--=========================================================================================
local isSinglePlayer = nil ---@type boolean
local masterTimer = nil ---@type timer
local numMessagesOnScreen = 0 ---@type integer
local messageCounter = 0 ---@type integer
local frameOfMessage = {} ---@type integer[]
local windowOfMessage = {} ---@type NeatWindow[]
local clearTextTimer = nil ---@type timer
local doNotClear = false ---@type boolean
local TIME_STEP = 0.05 ---@type number
DEFAULT_NEAT_FORMAT = nil ---@type NeatFormat
DEFAULT_NEAT_WINDOW = nil ---@type NeatWindow
local neatWindow = {} ---@type NeatWindow[]
local numNeatWindows = 0 ---@type integer
local ChangeTextFormatting = nil ---@type function
local ChangeText = nil ---@type function
---@class NeatFormat
NeatFormat = {
spacing = SPACING_BETWEEN_MESSAGES, ---@type number
fadeOutTime = FADE_OUT_TIME, ---@type number
fadeInTime = FADE_IN_TIME, ---@type number
fontSize = TEXT_MESSAGE_FONT_SIZE, ---@type number
minDuration = MESSAGE_MINIMUM_DURATION, ---@type number
durationIncrease = MESSAGE_DURATION_INCREASE_PER_CHARACTER, ---@type number
verticalAlignment = VERTICAL_ALIGNMENT, ---@type textaligntype
horizontalAlignment = HORIZONTAL_ALIGNMENT, ---@type textaligntype
isBoxed = BOXED_MESSAGES ---@type boolean
}
local NeatFormatMt = {__index = NeatFormat}
---@return NeatFormat
function NeatFormat.create()
local new = {}
setmetatable(new, NeatFormatMt)
return new
end
---@param copiedFormat NeatFormat
function NeatFormat:copy(copiedFormat)
self.spacing = copiedFormat.spacing
self.fadeOutTime = copiedFormat.fadeOutTime
self.fadeInTime = copiedFormat.fadeInTime
self.fontSize = copiedFormat.fontSize
self.minDuration = copiedFormat.minDuration
self.durationIncrease = copiedFormat.durationIncrease
self.verticalAlignment = copiedFormat.verticalAlignment
self.horizontalAlignment = copiedFormat.horizontalAlignment
self.isBoxed = copiedFormat.isBoxed
end
---@class NeatWindow
NeatWindow = {
xPosition = nil,
yPosition = nil,
maxHeight = nil,
width = nil,
maxTextMessages = nil,
isTopToBottom = nil,
textMessageFrame = nil,
textMessageText = nil,
textMessageBox = nil,
textCarryingFrame = nil,
textMessageIcon = nil,
messageFormat = nil,
messageTimeRemaining = nil,
messageTimeElapsed = nil,
textHeight = nil,
textMessageIconOrientation = nil,
messageOfFrame = 0,
}
local neatWindowMt = {__index = NeatWindow}
---@param xPosition number
---@param yPosition number
---@param width number
---@param maxHeight number
---@param maxTextMessages integer
---@param isTopToBottom boolean
---@return NeatWindow
function NeatWindow.create(xPosition, yPosition, width, maxHeight, maxTextMessages, isTopToBottom)
local new = {}
setmetatable(new, neatWindowMt)
new.xPosition = xPosition
new.yPosition = yPosition
new.maxHeight = maxHeight
new.width = width
new.maxTextMessages = maxTextMessages
new.isTopToBottom = isTopToBottom
if isTopToBottom then
new.yPosition = new.yPosition + maxHeight
end
numNeatWindows = numNeatWindows + 1
neatWindow[numNeatWindows] = new
new.textMessageFrame = {}
new.textMessageText = {}
new.textMessageBox = {}
new.textCarryingFrame = {}
new.textMessageIcon = {}
new.messageFormat = {}
new.textMessageIconOrientation = {}
new.textHeight = {}
new.messageTimeRemaining = {}
new.messageTimeElapsed = {}
new.messageOfFrame = {}
for i = 1, maxTextMessages do
if INCLUDE_FDF then
new.textMessageFrame[i] = BlzCreateFrame("TextMessage", BlzGetOriginFrame(ORIGIN_FRAME_GAME_UI, 0), 0, 0)
new.textMessageText[i] = BlzFrameGetChild( new.textMessageFrame[i],0)
new.textMessageBox[i] = BlzFrameGetChild( new.textMessageFrame[i],1)
BlzFrameSetSize(new.textMessageText[i], width, 0)
BlzFrameSetScale(new.textMessageText[i], TEXT_MESSAGE_FONT_SIZE/10.)
BlzFrameSetAbsPoint(new.textMessageFrame[i], FRAMEPOINT_BOTTOMLEFT, xPosition, yPosition)
BlzFrameSetTextAlignment(new.textMessageText[i] , VERTICAL_ALIGNMENT , HORIZONTAL_ALIGNMENT)
BlzFrameSetVisible( new.textMessageFrame[i] , false )
BlzFrameSetEnable(new.textMessageFrame[i],false)
BlzFrameSetEnable(new.textMessageText[i],false)
BlzFrameSetLevel(new.textMessageText[i],1)
BlzFrameSetLevel(new.textMessageBox[i],0)
new.textCarryingFrame[i] = new.textMessageText[i]
new.textMessageIcon[i] = BlzCreateFrameByType("BACKDROP", "textMessageIcon" .. i , BlzGetOriginFrame(ORIGIN_FRAME_GAME_UI, 0), "", 0)
BlzFrameSetEnable(new.textMessageIcon[i],false)
BlzFrameSetVisible(new.textMessageIcon[i],false)
new.messageFormat[i] = DEFAULT_NEAT_FORMAT
new.messageOfFrame[i] = 0
new.textHeight[i] = 0
new.messageTimeRemaining[i] = 0
new.messageTimeElapsed[i] = 0
new.messageOfFrame[i] = 0
ChangeTextFormatting(new, i, DEFAULT_NEAT_FORMAT)
ChangeText(new, i, "")
else
new.textMessageFrame[i] = BlzCreateFrameByType("TEXT", "textMessageFrame" , BlzGetOriginFrame(ORIGIN_FRAME_GAME_UI, 0), "", 0)
BlzFrameSetScale(new.textMessageFrame[i], TEXT_MESSAGE_FONT_SIZE/10.)
BlzFrameSetTextAlignment(new.textMessageFrame[i] , VERTICAL_ALIGNMENT , HORIZONTAL_ALIGNMENT)
BlzFrameSetAbsPoint(new.textMessageFrame[i], FRAMEPOINT_BOTTOMLEFT, xPosition, yPosition)
BlzFrameSetVisible( new.textMessageFrame[i] , false )
BlzFrameSetEnable(new.textMessageFrame[i],false)
new.textCarryingFrame[i] = new.textMessageFrame[i]
new.textMessageIcon[i] = BlzCreateFrameByType("BACKDROP", "textMessageIcon" .. i , BlzGetOriginFrame(ORIGIN_FRAME_GAME_UI, 0), "", 0)
BlzFrameSetEnable(new.textMessageIcon[i],false)
BlzFrameSetVisible(new.textMessageIcon[i],false)
new.messageFormat[i] = DEFAULT_NEAT_FORMAT
new.messageOfFrame[i] = 0
new.textHeight[i] = 0
new.messageTimeRemaining[i] = 0
new.messageTimeElapsed[i] = 0
new.messageOfFrame[i] = 0
ChangeTextFormatting(new, i, DEFAULT_NEAT_FORMAT)
ChangeText(new, i, "")
end
end
return new
end
--=========================================================================================
function ClearText()
doNotClear = true
ClearTextMessages()
doNotClear = false
end
---@param whichString string
---@return integer
local function GetAdjustedStringLength(whichString)
local rawLength = string.len(whichString) ---@type integer
local adjustedLength = rawLength ---@type integer
local j = 1 ---@type integer
local secondCharacter ---@type string
while j <= rawLength - 10 do
if string.sub(whichString, j, j) == "|" then
secondCharacter = string.lower(string.sub(whichString, j+1, j+1))
if secondCharacter == "c" then
adjustedLength = adjustedLength - 10
j = j + 10
elseif secondCharacter == "r" then
adjustedLength = adjustedLength - 2
j = j + 2
end
else
j = j + 1
end
end
return adjustedLength
end
---@param w NeatWindow
---@param whichFrame integer
---@param whichFormat NeatFormat
ChangeTextFormatting = function(w, whichFrame, whichFormat)
if whichFormat == 0 then
return
end
w.messageFormat[whichFrame] = whichFormat
BlzFrameSetScale(w.textCarryingFrame[whichFrame], whichFormat.fontSize/10.)
BlzFrameSetTextAlignment( w.textCarryingFrame[whichFrame], whichFormat.verticalAlignment, whichFormat.horizontalAlignment )
end
---@param w NeatWindow
---@param whichFrame integer
---@param whichText string
ChangeText = function(w, whichFrame, whichText)
BlzFrameSetText( w.textCarryingFrame[whichFrame] , whichText )
if w.maxTextMessages == 1 then
BlzFrameSetSize( w.textCarryingFrame[whichFrame] , w.width / (w.messageFormat[whichFrame].fontSize/10.) , w.maxHeight / (w.messageFormat[whichFrame].fontSize/10.) )
else
BlzFrameSetSize( w.textCarryingFrame[whichFrame] , w.width / (w.messageFormat[whichFrame].fontSize/10.) , 0 )
end
if INCLUDE_FDF then
BlzFrameSetSize( w.textMessageFrame[whichFrame] , BlzFrameGetWidth(w.textMessageText[whichFrame]) + 0.008 , BlzFrameGetHeight(w.textMessageText[whichFrame]) + 0.009 )
BlzFrameSetPoint( w.textMessageBox[whichFrame] , FRAMEPOINT_BOTTOMLEFT , w.textMessageFrame[whichFrame] , FRAMEPOINT_BOTTOMLEFT , 0 , -0.0007*(w.messageFormat[whichFrame].fontSize-13) )
BlzFrameSetPoint( w.textMessageBox[whichFrame] , FRAMEPOINT_TOPRIGHT , w.textMessageFrame[whichFrame] , FRAMEPOINT_TOPRIGHT , 0 , 0 )
end
if whichText == "" then
BlzFrameSetVisible( w.textMessageFrame[whichFrame] , false )
BlzFrameSetAlpha( w.textMessageFrame[whichFrame] , 255 )
else
BlzFrameSetVisible( w.textMessageFrame[whichFrame] , true )
end
end
---@param w NeatWindow
---@param whichFrame integer
---@param collapseFrame boolean
local function HideTextMessage(w, whichFrame, collapseFrame)
if BlzFrameGetText(w.textCarryingFrame[whichFrame]) ~= "" then
numMessagesOnScreen = numMessagesOnScreen - 1
end
ChangeText(w,whichFrame,"")
w.messageTimeRemaining[whichFrame] = 0
frameOfMessage[w.messageOfFrame[whichFrame]] = nil
w.messageOfFrame[whichFrame] = 0
if collapseFrame then
w.textHeight[whichFrame] = 0
end
if w.textMessageIconOrientation[whichFrame] ~= nil then
BlzFrameSetVisible( w.textMessageIcon[whichFrame] , false )
BlzFrameSetAlpha( w.textMessageIcon[whichFrame] , 255 )
end
end
local function FadeoutLoop()
local w ---@type NeatWindow
if numMessagesOnScreen == 0 then
return
end
for j = 1, numNeatWindows do
w = neatWindow[j]
for i = 1, w.maxTextMessages do
if w.messageTimeRemaining[i] > 0 then
w.messageTimeRemaining[i] = w.messageTimeRemaining[i] - TIME_STEP
w.messageTimeElapsed[i] = w.messageTimeElapsed[i] + TIME_STEP
if w.messageTimeRemaining[i] < w.messageFormat[i].fadeOutTime then
if w.messageTimeRemaining[i] < 0 then
HideTextMessage(w,i,false)
else
BlzFrameSetAlpha( w.textMessageFrame[i] , math.floor(255*w.messageTimeRemaining[i]/w.messageFormat[i].fadeOutTime) )
end
elseif w.messageTimeElapsed[i] < w.messageFormat[i].fadeInTime then
BlzFrameSetAlpha( w.textMessageFrame[i] , math.floor(255*w.messageTimeElapsed[i]/w.messageFormat[i].fadeInTime) )
end
if w.textMessageIconOrientation[i] ~= nil then
BlzFrameSetAlpha( w.textMessageIcon[i] , BlzFrameGetAlpha(w.textMessageFrame[i]) )
end
end
end
end
end
---@param w NeatWindow
local function RepositionAllMessages(w)
local yOffset = {}
--=========================================================================================
--Get message heights
--=========================================================================================
yOffset[1] = 0
for i = 2, w.maxTextMessages do
yOffset[i] = yOffset[i-1] + w.textHeight[i-1]
end
--=========================================================================================
--Reposition messages
--=========================================================================================
for i = 1, w.maxTextMessages do
if yOffset[i] + w.textHeight[i] > w.maxHeight then
HideTextMessage(w,i,true)
elseif w.isTopToBottom then
BlzFrameSetAbsPoint( w.textMessageFrame[i] , FRAMEPOINT_BOTTOMLEFT , w.xPosition , w.yPosition - w.textHeight[i] - yOffset[i] )
else
BlzFrameSetAbsPoint( w.textMessageFrame[i] , FRAMEPOINT_BOTTOMLEFT , w.xPosition , w.yPosition + yOffset[i] )
end
end
end
---@param whichText string
---@param forcedDuration number
---@param whichFormat NeatFormat
---@param w NeatWindow
---@return integer
local function AddTextMessage(whichText, forcedDuration, whichFormat, w)
local tempFrame ---@type framehandle
if whichText == "" then
return 0
end
if COPY_TO_MESSAGE_LOG and isSinglePlayer then
DisplayTextToPlayer( GetLocalPlayer() , 0 , 0 , whichText .. [[
]] )
ClearTextMessages()
end
if BlzFrameGetText(w.textCarryingFrame[w.maxTextMessages]) == "" then
numMessagesOnScreen = numMessagesOnScreen + 1
end
--=========================================================================================
--Transfer messages to next frame
--=========================================================================================
tempFrame = w.textMessageIcon[w.maxTextMessages]
for i = w.maxTextMessages - 1, 1, -1 do
w.messageTimeRemaining[i+1] = w.messageTimeRemaining[i]
w.messageTimeElapsed[i+1] = w.messageTimeElapsed[i]
ChangeTextFormatting(w, i+1, w.messageFormat[i])
ChangeText(w, i+1, BlzFrameGetText(w.textCarryingFrame[i]))
if w.messageOfFrame[i] ~= 0 then
w.messageOfFrame[i+1] = w.messageOfFrame[i]
frameOfMessage[w.messageOfFrame[i+1]] = i + 1
end
if w.messageTimeRemaining[i+1] < w.messageFormat[i+1].fadeOutTime then
BlzFrameSetAlpha( w.textMessageFrame[i+1] , math.floor(255*w.messageTimeRemaining[i+1]/w.messageFormat[i+1].fadeOutTime) )
else
BlzFrameSetAlpha( w.textMessageFrame[i+1] , 255 )
end
BlzFrameSetVisible( w.textMessageFrame[i+1] , true )
if INCLUDE_FDF then
BlzFrameSetVisible( w.textMessageBox[i+1] , BlzFrameIsVisible(w.textMessageBox[i]) )
end
w.textHeight[i+1] = w.textHeight[i]
w.textMessageIcon[i+1] = w.textMessageIcon[i]
w.textMessageIconOrientation[i+1] = w.textMessageIconOrientation[i]
if w.textMessageIconOrientation[i] ~= nil then
if w.textMessageIconOrientation[i+1] == "topleft" then
BlzFrameSetPoint( w.textMessageIcon[i+1] , FRAMEPOINT_TOPRIGHT , w.textMessageFrame[i+1] , FRAMEPOINT_TOPLEFT , 0 , 0 )
elseif w.textMessageIconOrientation[i+1] == "topright" then
BlzFrameSetPoint( w.textMessageIcon[i+1] , FRAMEPOINT_TOPLEFT , w.textMessageFrame[i+1] , FRAMEPOINT_TOPRIGHT , 0 , 0 )
elseif w.textMessageIconOrientation[i+1] == "bottomleft" then
BlzFrameSetPoint( w.textMessageIcon[i+1] , FRAMEPOINT_BOTTOMRIGHT , w.textMessageFrame[i+1] , FRAMEPOINT_BOTTOMLEFT , 0 , 0 )
elseif w.textMessageIconOrientation[i+1] == "bottomright" then
BlzFrameSetPoint( w.textMessageIcon[i+1] , FRAMEPOINT_BOTTOMLEFT , w.textMessageFrame[i+1] , FRAMEPOINT_BOTTOMRIGHT , 0 , 0 )
end
end
end
w.textMessageIcon[1] = tempFrame
--=========================================================================================
--Setup new message
--=========================================================================================
ChangeTextFormatting(w, 1, whichFormat)
ChangeText(w, 1, whichText)
w.textHeight[1] = BlzFrameGetHeight(w.textMessageFrame[1]) + math.max(whichFormat.spacing , w.messageFormat[1].spacing)
if INCLUDE_FDF then
BlzFrameSetVisible( w.textMessageBox[1], whichFormat.isBoxed )
end
if forcedDuration ~= 0 then
w.messageTimeRemaining[1] = forcedDuration + whichFormat.fadeOutTime
else
w.messageTimeRemaining[1] = whichFormat.minDuration + whichFormat.durationIncrease*GetAdjustedStringLength(whichText) + whichFormat.fadeOutTime
end
w.messageTimeElapsed[1] = 0
if whichFormat.fadeInTime > 0 then
BlzFrameSetAlpha(w.textMessageFrame[1] , 0)
else
BlzFrameSetAlpha(w.textMessageFrame[1] , 255)
end
BlzFrameSetVisible( w.textMessageFrame[1] , true )
w.textMessageIconOrientation[1] = nil
messageCounter = messageCounter + 1
w.messageOfFrame[1] = messageCounter
frameOfMessage[messageCounter] = 1
windowOfMessage[messageCounter] = w
if w.maxTextMessages > 1 then
RepositionAllMessages(w)
end
return messageCounter
end
local function Init()
local p ---@type integer
local numPlayers ---@type integer
if INCLUDE_FDF then
BlzLoadTOCFile("NeatMessageTemplates.toc")
end
masterTimer = CreateTimer()
TimerStart( masterTimer , TIME_STEP , true , FadeoutLoop )
DEFAULT_NEAT_FORMAT = NeatFormat.create()
DEFAULT_NEAT_WINDOW = NeatWindow.create(TEXT_MESSAGE_X_POSITION, TEXT_MESSAGE_Y_POSITION, TEXT_MESSAGE_BLOCK_WIDTH, TEXT_MESSAGE_BLOCK_MAX_HEIGHT, MAX_TEXT_MESSAGES, MESSAGE_ORDER_TOP_TO_BOTTOM)
if COPY_TO_MESSAGE_LOG then
p = 0
numPlayers = 1
while p <= 23 do
if GetPlayerSlotState(Player(p)) == PLAYER_SLOT_STATE_PLAYING and GetPlayerController(Player(p)) == MAP_CONTROL_USER then
numPlayers = numPlayers + 1
end
p = p + 1
end
isSinglePlayer = numPlayers == 1
end
if REPLACE_BLIZZARD_FUNCTION_CALLS then
local hook = Require.optionally "Hook"
if hook then
clearTextTimer = CreateTimer()
function Hook:DisplayTextToForce(whichForce, message)
local extractedString
BlzSetAbilityTooltip( FourCC(TOOLTIP_ABILITY), message, 0)
extractedString = BlzGetAbilityTooltip(FourCC(TOOLTIP_ABILITY), 0)
NeatMessageToForce(whichForce, extractedString)
TimerStart(clearTextTimer, 0.0, false, ClearText)
end
function Hook:DisplayTimedTextToForce(whichForce, duration, message)
local extractedString
BlzSetAbilityTooltip( FourCC(TOOLTIP_ABILITY), message, 0)
extractedString = BlzGetAbilityTooltip(FourCC(TOOLTIP_ABILITY), 0)
NeatMessageToForceTimed( whichForce , duration , extractedString )
TimerStart(clearTextTimer, 0.0, false, ClearText)
end
function Hook:ClearTextMessagesBJ(whichForce)
self.old(whichForce)
ClearNeatMessagesForForce(whichForce)
end
function Hook:ClearTextMessages()
self.old()
ClearNeatMessages()
end
else
error("REPLACE_BLIZZARD_FUNCTION_CALLS requires Hook library.")
end
end
end
--===========================================================================================
--API
--===========================================================================================
--Constructors
--===========================================================================================
---@param message string
---@return integer
function NeatMessage(message)
return AddTextMessage(message, 0, DEFAULT_NEAT_FORMAT, DEFAULT_NEAT_WINDOW)
end
---@param whichPlayer player
---@param message string
---@return integer
function NeatMessageToPlayer(whichPlayer, message)
if GetLocalPlayer() == whichPlayer then
return AddTextMessage(message , 0, DEFAULT_NEAT_FORMAT, DEFAULT_NEAT_WINDOW)
end
return 0
end
---@param whichForce force
---@param message string
---@return integer
function NeatMessageToForce(whichForce, message)
if IsPlayerInForce( GetLocalPlayer() , whichForce ) then
return AddTextMessage(message, 0, DEFAULT_NEAT_FORMAT, DEFAULT_NEAT_WINDOW)
end
return 0
end
---@param duration number
---@param message string
---@return integer
function NeatMessageTimed(duration, message)
return AddTextMessage(message, duration, DEFAULT_NEAT_FORMAT, DEFAULT_NEAT_WINDOW)
end
---@param whichPlayer player
---@param duration number
---@param message string
---@return integer
function NeatMessageToPlayerTimed(whichPlayer, duration, message)
if GetLocalPlayer() == whichPlayer then
return AddTextMessage(message, duration, DEFAULT_NEAT_FORMAT, DEFAULT_NEAT_WINDOW)
end
return 0
end
---@param whichForce force
---@param duration number
---@param message string
---@return integer
function NeatMessageToForceTimed(whichForce, duration, message)
if IsPlayerInForce( GetLocalPlayer() , whichForce ) then
return AddTextMessage(message, duration, DEFAULT_NEAT_FORMAT, DEFAULT_NEAT_WINDOW)
end
return 0
end
---@param message string
---@param whichFormat NeatFormat
---@return integer
function NeatMessageFormatted(message, whichFormat)
return AddTextMessage(message, 0, whichFormat, DEFAULT_NEAT_WINDOW)
end
---@param whichPlayer player
---@param message string
---@param whichFormat NeatFormat
---@return integer
function NeatMessageToPlayerFormatted(whichPlayer, message, whichFormat)
if GetLocalPlayer() == whichPlayer then
return AddTextMessage(message , 0, whichFormat, DEFAULT_NEAT_WINDOW)
end
return 0
end
---@param whichForce force
---@param message string
---@param whichFormat NeatFormat
---@return integer
function NeatMessageToForceFormatted(whichForce, message, whichFormat)
if IsPlayerInForce( GetLocalPlayer() , whichForce ) then
return AddTextMessage(message, 0, whichFormat, DEFAULT_NEAT_WINDOW)
end
return 0
end
---@param whichPlayer player
---@param duration number
---@param message string
---@param whichFormat NeatFormat
---@return integer
function NeatMessageToPlayerTimedFormatted(whichPlayer, duration, message, whichFormat)
if GetLocalPlayer() == whichPlayer then
return AddTextMessage(message, duration, whichFormat, DEFAULT_NEAT_WINDOW)
end
return 0
end
---@param whichForce force
---@param duration number
---@param message string
---@param whichFormat NeatFormat
---@return integer
function NeatMessageToForceTimedFormatted(whichForce, duration, message, whichFormat)
if IsPlayerInForce( GetLocalPlayer() , whichForce ) then
return AddTextMessage(message, duration, whichFormat, DEFAULT_NEAT_WINDOW)
end
return 0
end
---@param duration number
---@param message string
---@param whichFormat NeatFormat
---@return integer
function NeatMessageTimedFormatted(duration, message, whichFormat)
return AddTextMessage(message, duration, whichFormat, DEFAULT_NEAT_WINDOW)
end
---@param message string
---@param whichWindow NeatWindow
---@return integer
function NeatMessageInWindow(message, whichWindow)
return AddTextMessage(message, 0, DEFAULT_NEAT_FORMAT, whichWindow)
end
---@param whichPlayer player
---@param message string
---@param whichWindow NeatWindow
---@return integer
function NeatMessageToPlayerInWindow(whichPlayer, message, whichWindow)
if GetLocalPlayer() == whichPlayer then
return AddTextMessage(message , 0, DEFAULT_NEAT_FORMAT, whichWindow)
end
return 0
end
---@param whichForce force
---@param message string
---@param whichWindow NeatWindow
---@return integer
function NeatMessageToForceInWindow(whichForce, message, whichWindow)
if IsPlayerInForce( GetLocalPlayer() , whichForce ) then
return AddTextMessage(message, 0, DEFAULT_NEAT_FORMAT, whichWindow)
end
return 0
end
---@param duration number
---@param message string
---@param whichWindow NeatWindow
---@return integer
function NeatMessageTimedInWindow(duration, message, whichWindow)
return AddTextMessage(message, duration, DEFAULT_NEAT_FORMAT, whichWindow)
end
---@param whichPlayer player
---@param duration number
---@param message string
---@param whichWindow NeatWindow
---@return integer
function NeatMessageToPlayerTimedInWindow(whichPlayer, duration, message, whichWindow)
if GetLocalPlayer() == whichPlayer then
return AddTextMessage(message, duration, DEFAULT_NEAT_FORMAT, whichWindow)
end
return 0
end
---@param whichForce force
---@param duration number
---@param message string
---@param whichWindow NeatWindow
---@return integer
function NeatMessageToForceTimedInWindow(whichForce, duration, message, whichWindow)
if IsPlayerInForce( GetLocalPlayer() , whichForce ) then
return AddTextMessage(message, duration, DEFAULT_NEAT_FORMAT, whichWindow)
end
return 0
end
---@param message string
---@param whichFormat NeatFormat
---@param whichWindow NeatWindow
---@return integer
function NeatMessageFormattedInWindow(message, whichFormat, whichWindow)
return AddTextMessage(message, 0, whichFormat, whichWindow)
end
---@param whichPlayer player
---@param message string
---@param whichFormat NeatFormat
---@param whichWindow NeatWindow
---@return integer
function NeatMessageToPlayerFormattedInWindow(whichPlayer, message, whichFormat, whichWindow)
if GetLocalPlayer() == whichPlayer then
return AddTextMessage(message , 0, whichFormat, whichWindow)
end
return 0
end
---@param whichForce force
---@param message string
---@param whichFormat NeatFormat
---@param whichWindow NeatWindow
---@return integer
function NeatMessageToForceFormattedInWindow(whichForce, message, whichFormat, whichWindow)
if IsPlayerInForce( GetLocalPlayer() , whichForce ) then
return AddTextMessage(message, 0, whichFormat, whichWindow)
end
return 0
end
---@param whichPlayer player
---@param duration number
---@param message string
---@param whichFormat NeatFormat
---@param whichWindow NeatWindow
---@return integer
function NeatMessageToPlayerTimedFormattedInWindow(whichPlayer, duration, message, whichFormat, whichWindow)
if GetLocalPlayer() == whichPlayer then
return AddTextMessage(message, duration, whichFormat, whichWindow)
end
return 0
end
---@param whichForce force
---@param duration number
---@param message string
---@param whichFormat NeatFormat
---@param whichWindow NeatWindow
---@return integer
function NeatMessageToForceTimedFormattedInWindow(whichForce, duration, message, whichFormat, whichWindow)
if IsPlayerInForce( GetLocalPlayer() , whichForce ) then
return AddTextMessage(message, duration, whichFormat, whichWindow)
end
return 0
end
---@param duration number
---@param message string
---@param whichFormat NeatFormat
---@param whichWindow NeatWindow
---@return integer
function NeatMessageTimedFormattedInWindow(duration, message, whichFormat, whichWindow)
return AddTextMessage(message, duration, whichFormat, whichWindow)
end
--Utility
--===========================================================================================
---@param messagePointer integer
---@param newText string
function EditNeatMessage(messagePointer, newText)
local whichFrame = frameOfMessage[messagePointer] ---@type integer
local whichWindow = windowOfMessage[messagePointer] ---@type NeatWindow
if messagePointer == 0 or whichFrame == nil then
return
end
ChangeText(whichWindow, whichFrame, newText)
whichWindow.textHeight[whichFrame] = BlzFrameGetHeight(whichWindow.textMessageFrame[whichFrame]) + math.max(whichWindow.messageFormat[whichFrame].spacing , whichWindow.messageFormat[whichFrame+1].spacing)
RepositionAllMessages(whichWindow)
end
---@param messagePointer integer
---@param additionalTime number
function AddNeatMessageTimeRemaining(messagePointer, additionalTime)
local whichFrame = frameOfMessage[messagePointer] ---@type integer
local whichWindow = windowOfMessage[messagePointer] ---@type NeatWindow
if messagePointer == 0 or whichFrame == nil then
return
end
whichWindow.messageTimeRemaining[whichFrame] = math.max(whichWindow.messageTimeRemaining[whichFrame] + additionalTime, whichWindow.messageFormat[whichFrame].fadeOutTime)
end
---@param messagePointer integer
---@param newTime number
function SetNeatMessageTimeRemaining(messagePointer, newTime)
local whichFrame = frameOfMessage[messagePointer] ---@type integer
local whichWindow = windowOfMessage[messagePointer] ---@type NeatWindow
if messagePointer == 0 or whichFrame == nil then
return
end
whichWindow.messageTimeRemaining[whichFrame] = math.max(newTime, whichWindow.messageFormat[whichFrame].fadeOutTime)
end
---@param messagePointer integer
---@param accountForTimeElapsed boolean
function AutoSetNeatMessageTimeRemaining(messagePointer, accountForTimeElapsed)
local whichFrame = frameOfMessage[messagePointer] ---@type integer
local whichWindow = windowOfMessage[messagePointer] ---@type NeatWindow
local whichFormat = whichWindow.messageFormat[whichFrame] ---@type NeatFormat
if messagePointer == 0 or whichFrame == nil then
return
end
whichWindow.messageTimeRemaining[whichFrame] = whichFormat.minDuration + whichFormat.durationIncrease*GetAdjustedStringLength(BlzFrameGetText(whichWindow.textCarryingFrame[whichFrame])) + whichFormat.fadeOutTime
if accountForTimeElapsed then
whichWindow.messageTimeRemaining[whichFrame] = math.max(whichWindow.messageTimeRemaining[whichFrame] - whichWindow.messageTimeElapsed[whichFrame], whichFormat.fadeOutTime)
end
end
---@param messagePointer integer
function RemoveNeatMessage(messagePointer)
local whichFrame = frameOfMessage[messagePointer] ---@type integer
local whichWindow = windowOfMessage[messagePointer] ---@type NeatWindow
if messagePointer == 0 or whichFrame == nil then
return
end
whichWindow.messageTimeRemaining[whichFrame] = whichWindow.messageFormat[whichFrame].fadeOutTime
end
---@param messagePointer integer
---@return boolean
function IsNeatMessageDisplayed(messagePointer)
return frameOfMessage[messagePointer] ~= nil
end
---@param messagePointer integer
---@param width number
---@param height number
---@param orientation string
---@param texture string
function NeatMessageAddIcon(messagePointer, width, height, orientation, texture)
local whichFrame = frameOfMessage[messagePointer] ---@type integer
local whichWindow = windowOfMessage[messagePointer] ---@type NeatWindow
BlzFrameSetVisible( whichWindow.textMessageIcon[whichFrame] , true )
BlzFrameSetAlpha( whichWindow.textMessageIcon[whichFrame] , 255 )
BlzFrameSetSize( whichWindow.textMessageIcon[whichFrame] , width , height )
if orientation == "topleft" then
BlzFrameSetPoint( whichWindow.textMessageIcon[whichFrame] , FRAMEPOINT_TOPRIGHT , whichWindow.textMessageFrame[whichFrame] , FRAMEPOINT_TOPLEFT , 0 , 0 )
elseif orientation == "topright" then
BlzFrameSetPoint( whichWindow.textMessageIcon[whichFrame] , FRAMEPOINT_TOPLEFT , whichWindow.textMessageFrame[whichFrame] , FRAMEPOINT_TOPRIGHT , 0 , 0 )
elseif orientation == "bottomleft" then
BlzFrameSetPoint( whichWindow.textMessageIcon[whichFrame] , FRAMEPOINT_BOTTOMRIGHT , whichWindow.textMessageFrame[whichFrame] , FRAMEPOINT_BOTTOMLEFT , 0 , 0 )
elseif orientation == "bottomright" then
BlzFrameSetPoint( whichWindow.textMessageIcon[whichFrame] , FRAMEPOINT_BOTTOMLEFT , whichWindow.textMessageFrame[whichFrame] , FRAMEPOINT_BOTTOMRIGHT , 0 , 0 )
else
print("Invalid icon orientation...")
return
end
BlzFrameSetTexture( whichWindow.textMessageIcon[whichFrame] , texture , 0 , true )
whichWindow.textMessageIconOrientation[whichFrame] = orientation
if BlzFrameGetHeight( whichWindow.textMessageFrame[whichFrame] ) < height then
BlzFrameSetSize( whichWindow.textCarryingFrame[whichFrame] , whichWindow.width / (whichWindow.messageFormat[whichFrame].fontSize/10.) , height - 0.018 )
if INCLUDE_FDF then
BlzFrameSetSize( whichWindow.textMessageFrame[whichFrame] , BlzFrameGetWidth(whichWindow.textMessageText[whichFrame]) + 0.008 , BlzFrameGetHeight(whichWindow.textMessageText[whichFrame]) + 0.009 )
BlzFrameSetPoint( whichWindow.textMessageBox[whichFrame] , FRAMEPOINT_BOTTOMLEFT , whichWindow.textMessageFrame[whichFrame] , FRAMEPOINT_BOTTOMLEFT , 0 , -0.0007*(whichWindow.messageFormat[whichFrame].fontSize-13) )
BlzFrameSetPoint( whichWindow.textMessageBox[whichFrame] , FRAMEPOINT_TOPRIGHT , whichWindow.textMessageFrame[whichFrame] , FRAMEPOINT_TOPRIGHT , 0 , 0 )
end
whichWindow.textHeight[whichFrame] = BlzFrameGetHeight(whichWindow.textMessageFrame[whichFrame]) + math.max(whichWindow.messageFormat[whichFrame].spacing , whichWindow.messageFormat[whichFrame+1].spacing)
RepositionAllMessages(whichWindow)
end
end
---@param messagePointer integer
function NeatMessageHideIcon(messagePointer)
local whichFrame = frameOfMessage[messagePointer] ---@type integer
local whichWindow = windowOfMessage[messagePointer] ---@type NeatWindow
BlzFrameSetVisible( whichWindow.textMessageIcon[whichFrame] , false )
whichWindow.textMessageIconOrientation[whichFrame] = nil
end
---@param whichPlayer player
function ClearNeatMessagesForPlayer(whichPlayer)
if GetLocalPlayer() == whichPlayer then
for j = 1, numNeatWindows do
for i = 1, neatWindow[j].maxTextMessages do
HideTextMessage(neatWindow[j], i, true)
end
end
end
end
function ClearNeatMessages()
if doNotClear then
return
end
for j = 1, numNeatWindows do
for i = 1, neatWindow[j].maxTextMessages do
HideTextMessage(neatWindow[j], i, true)
end
end
end
---@param whichForce force
function ClearNeatMessagesForForce(whichForce)
if IsPlayerInForce(GetLocalPlayer() , whichForce) then
for j = 1, numNeatWindows do
for i = 1, neatWindow[j].maxTextMessages do
HideTextMessage(neatWindow[j], i, true)
end
end
end
end
---@param whichPlayer player
---@param whichWindow NeatWindow
function ClearNeatMessagesForPlayerInWindow(whichPlayer, whichWindow)
if GetLocalPlayer() == whichPlayer then
for i = 1, whichWindow.maxTextMessages do
HideTextMessage(whichWindow, i, true)
end
end
end
---@param whichWindow NeatWindow
function ClearNeatMessagesInWindow(whichWindow)
for i = 1, whichWindow.maxTextMessages do
HideTextMessage(whichWindow, i, true)
end
end
---@param whichForce force
---@param whichWindow NeatWindow
function ClearNeatMessagesForForceInWindow(whichForce, whichWindow)
if IsPlayerInForce(GetLocalPlayer() , whichForce) then
for i = 1, whichWindow.maxTextMessages do
HideTextMessage(whichWindow, i, true)
end
end
end
OnInit.main(Init)
end
--[[
Lua-Infused GUI with automatic memory leak resolution: Modernizing the experience for a better future for users of the Trigger Editor.
Credits:
Bribe, Tasyen, Dr Super Good, HerlySQR
Transforming rects, locations, groups, forces and BJ hashtable wrappers into Lua tables, which are automatically garbage collected.
Provides RegisterAnyPlayerUnitEvent to cut down on handle count and simplify syntax for Lua users while benefitting GUI.
Provides GUI.enumUnitsInRect/InRange/Selected/etc. which replaces the first parameter with a function (which takes a unit), for immediate action without needing a separate group variable.
Provides GUI.loopArray for safe iteration over a __jarray
Updated: 7 Nov 2022
Uses optionally:
https://github.com/BribeFromTheHive/Lua-Core/blob/main/Total_Initialization.lua
https://github.com/BribeFromTheHive/Lua-Core/blob/main/Hook.lua
https://github.com/BribeFromTheHive/Lua-Core/blob/main/Global_Variable_Remapper.lua
https://github.com/BribeFromTheHive/Lua-Core/blob/main/UnitEvent.lua
--]]
GUI = {}
do
--Configurables
local _USE_GLOBAL_REMAP = true --set to true if you want GUI to have extended functionality such as "udg_HashTableArray" (which gives GUI an infinite supply of shared hashtables)
local _USE_UNIT_EVENT = true --set to true if you have UnitEvent in your map and want to automatically remove units from their unit groups if they are removed from the game.
--Define common variables to be utilized throughout the script.
local _G = _G
local unpack = table.unpack
do
--[[-----------------------------------------------------------------------------------------
__jarray expander by Bribe
This snippet will ensure that objects used as indices in udg_ arrays will be automatically
cleaned up when the garbage collector runs, and tries to re-use metatables whenever possible.
-------------------------------------------------------------------------------------------]]
local mts = {}
local weakKeys = {__mode="k"} --ensures tables with non-nilled objects as keys will be garbage collected.
---Re-define __jarray.
---@param default? any
---@param tab? table
---@return table
__jarray=function(default, tab)
local mt
if default then
mts[default]=mts[default] or {
__index=function()
return default
end,
__mode="k"
}
mt=mts[default]
else
mt=weakKeys
end
return setmetatable(tab or {}, mt)
end
--have to do a wide search for all arrays in the variable editor. The WarCraft 3 _G table is HUGE,
--and without editing the war3map.lua file manually, it is not possible to rewrite it in advance.
for k,v in pairs(_G) do
if type(v) == "table" and string.sub(k, 1, 4)=="udg_" then
__jarray(v[0], v)
end
end
---Add this safe iterator function for jarrays.
---@param whichTable table
---@param func fun(index:integer, value:any)
function GUI.loopArray(whichTable, func)
for i=rawget(whichTable, 0)~=nil and 0 or 1, #whichTable do
func(i, rawget(whichTable, i))
end
end
end
--[=============[
• HASHTABLES •
--]=============]
do --[[
GUI hashtable converter by Tasyen and Bribe
Converts GUI hashtables API into Lua Tables, overwrites StringHashBJ and GetHandleIdBJ to permit
typecasting, bypasses the 256 hashtable limit by avoiding hashtables, provides the variable
"HashTableArray", which automatically creates hashtables for you as needed (so you don't have to
initialize them each time).
]]
function StringHashBJ(s) return s end
function GetHandleIdBJ(id) return id end
local function load(whichHashTable,parentKey)
local index = whichHashTable[parentKey]
if not index then
index=__jarray()
whichHashTable[parentKey]=index
end
return index
end
if _USE_GLOBAL_REMAP then
OnInit(function(import)
local remap = import "GlobalRemapArray"
local hashes = __jarray()
remap("udg_HashTableArray", function(index)
return load(hashes, index)
end)
end)
end
local last
GetLastCreatedHashtableBJ=function() return last end
function InitHashtableBJ() last=__jarray() ; return last end
local function saveInto(value, childKey, parentKey, whichHashTable)
if childKey and parentKey and whichHashTable then
load(whichHashTable, parentKey)[childKey] = value
end
end
local function loadFrom(childKey, parentKey, whichHashTable, default)
if childKey and parentKey and whichHashTable then
local val = load(whichHashTable, parentKey)[childKey]
return val ~= nil and val or default
end
end
SaveIntegerBJ = saveInto
SaveRealBJ = saveInto
SaveBooleanBJ = saveInto
SaveStringBJ = saveInto
local function createDefault(default)
return function(childKey, parentKey, whichHashTable)
return loadFrom(childKey, parentKey, whichHashTable, default)
end
end
local loadNumber = createDefault(0)
LoadIntegerBJ = loadNumber
LoadRealBJ = loadNumber
LoadBooleanBJ = createDefault(false)
LoadStringBJ = createDefault("")
do
local sub = string.sub
for key in pairs(_G) do
if sub(key, -8)=="HandleBJ" then
local str=sub(key, 1,4)
if str=="Save" then _G[key] = saveInto
elseif str=="Load" then _G[key] = loadFrom end
end
end
end
function HaveSavedValue(childKey, _, parentKey, whichHashTable)
return load(whichHashTable, parentKey)[childKey] ~= nil
end
FlushParentHashtableBJ = function(whichHashTable)
for key in pairs(whichHashTable) do
whichHashTable[key]=nil
end
end
function FlushChildHashtableBJ(whichHashTable, parentKey)
whichHashTable[parentKey]=nil
end
end
--[===========================[
• LOCATIONS (POINTS IN GUI) •
--]===========================]
do
local oldLocation = Location
local location
do
local oldRemove = RemoveLocation
local oldGetX = GetLocationX
local oldGetY = GetLocationY
local oldRally = GetUnitRallyPoint
function GetUnitRallyPoint(unit)
local removeThis = oldRally(unit) --Actually needs to create a location for a brief moment, as there is no GetUnitRallyX/Y
local loc = {oldGetX(removeThis), oldGetY(removeThis)}
oldRemove(removeThis)
return loc
end
end
RemoveLocation = DoNothing
function Location(x,y)
return {x,y}
end
do
local oldMoveLoc = MoveLocation
local oldGetZ=GetLocationZ
function GUI.getCoordZ(x,y)
GUI.getCoordZ = function(x,y)
oldMoveLoc(location, x, y)
return oldGetZ(location)
end
location = oldLocation(x,y)
return oldGetZ(location)
end
end
function GetLocationX(loc) return loc[1] end
function GetLocationY(loc) return loc[2] end
function GetLocationZ(loc)
return GUI.getCoordZ(loc[1], loc[2])
end
function MoveLocation(loc, x, y)
loc[1]=x
loc[2]=y
end
local function fakeCreate(varName, suffix)
local getX=_G[varName.."X"]
local getY=_G[varName.."Y"]
_G[varName..(suffix or "Loc")]=function(obj) return {getX(obj), getY(obj)} end
end
fakeCreate("GetUnit")
fakeCreate("GetOrderPoint")
fakeCreate("GetSpellTarget")
fakeCreate("CameraSetupGetDestPosition")
fakeCreate("GetCameraTargetPosition")
fakeCreate("GetCameraEyePosition")
fakeCreate("BlzGetTriggerPlayerMouse", "Position")
fakeCreate("GetStartLocation")
BlzSetSpecialEffectPositionLoc = function(effect, loc)
local x,y=loc[1],loc[2]
BlzSetSpecialEffectPosition(effect, x, y, GUI.getCoordZ(x,y))
end
---@param oldVarName string
---@param newVarName string
---@param index integer needed to determine which of the parameters calls for a location.
local function hook(oldVarName, newVarName, index)
local new = _G[newVarName]
local func
if index==1 then
func=function(loc, ...)
return new(loc[1], loc[2], ...)
end
elseif index==2 then
func=function(a, loc, ...)
return new(a, loc[1], loc[2], ...)
end
else--index==3
func=function(a, b, loc, ...)
return new(a, b, loc[1], loc[2], ...)
end
end
_G[oldVarName] = func
end
hook("IsLocationInRegion", "IsPointInRegion", 2)
hook("IsUnitInRangeLoc", "IsUnitInRangeXY", 2)
hook("IssuePointOrderLoc", "IssuePointOrder", 3)
IssuePointOrderLocBJ =IssuePointOrderLoc
hook("IssuePointOrderByIdLoc", "IssuePointOrderById", 3)
hook("IsLocationVisibleToPlayer", "IsVisibleToPlayer", 1)
hook("IsLocationFoggedToPlayer", "IsFoggedToPlayer", 1)
hook("IsLocationMaskedToPlayer", "IsMaskedToPlayer", 1)
hook("CreateFogModifierRadiusLoc", "CreateFogModifierRadius", 3)
hook("AddSpecialEffectLoc", "AddSpecialEffect", 2)
hook("AddSpellEffectLoc", "AddSpellEffect", 3)
hook("AddSpellEffectByIdLoc", "AddSpellEffectById", 3)
hook("SetBlightLoc", "SetBlight", 2)
hook("DefineStartLocationLoc", "DefineStartLocation", 2)
hook("GroupEnumUnitsInRangeOfLoc", "GroupEnumUnitsInRange", 2)
hook("GroupEnumUnitsInRangeOfLocCounted", "GroupEnumUnitsInRangeCounted", 2)
hook("GroupPointOrderLoc", "GroupPointOrder", 3)
GroupPointOrderLocBJ =GroupPointOrderLoc
hook("GroupPointOrderByIdLoc", "GroupPointOrderById", 3)
hook("MoveRectToLoc", "MoveRectTo", 2)
hook("RegionAddCellAtLoc", "RegionAddCell", 2)
hook("RegionClearCellAtLoc", "RegionClearCell", 2)
hook("CreateUnitAtLoc", "CreateUnit", 3)
hook("CreateUnitAtLocByName", "CreateUnitByName", 3)
hook("SetUnitPositionLoc", "SetUnitPosition", 2)
hook("ReviveHeroLoc", "ReviveHero", 2)
hook("SetFogStateRadiusLoc", "SetFogStateRadius", 3)
---@param min table location
---@param max table location
---@return rect newRect
RectFromLoc = function(min, max)
return Rect(min[1], min[2], max[1], max[2])
end
---@param whichRect rect
---@param min table location
---@param max table location
SetRectFromLoc = function(whichRect, min, max)
SetRect(whichRect, min[1], min[2], max[1], max[2])
end
end
--[=============================[
• GROUPS (UNIT GROUPS IN GUI) •
--]=============================]
do
local mainGroup = bj_lastCreatedGroup
DestroyGroup(bj_suspendDecayFleshGroup)
DestroyGroup(bj_suspendDecayBoneGroup)
DestroyGroup=DoNothing
CreateGroup=function() return {indexOf={}} end
bj_lastCreatedGroup=CreateGroup()
bj_suspendDecayFleshGroup=CreateGroup()
bj_suspendDecayBoneGroup=CreateGroup()
local groups
if _USE_UNIT_EVENT then
groups = {}
function GroupClear(group)
if group then
local u
for i=1, #group do
u=group[i]
groups[u]=nil
group.indexOf[u]=nil
group[i]=nil
end
end
end
else
function GroupClear(group)
if group then
for i=1, #group do
group.indexOf[group[i]]=nil
group[i]=nil
end
end
end
end
function GroupAddUnit(group, unit)
if group and unit and not group.indexOf[unit] then
local pos = #group+1
group.indexOf[unit]=pos
group[pos]=unit
if groups then
groups[unit] = groups[unit] or __jarray()
groups[unit][group]=true
end
end
end
function GroupRemoveUnit(group, unit)
local indexOf = group and unit and group.indexOf
if indexOf then
local pos = indexOf[unit]
if pos then
local size = #group
if pos ~= size then
indexOf[group[size]] = pos
end
group[size]=nil
indexOf[unit]=nil
if groups then
groups[unit][group]=nil
end
end
end
end
function IsUnitInGroup(unit, group)
return unit and group and group.indexOf[unit]
end
function FirstOfGroup(group)
return group and group[1]
end
local enumUnit
GetEnumUnit=function() return enumUnit end
function GUI.forGroup(group, code)
for i=1, #group do
code(group[i])
end
end
ForGroup = function(group, code)
if group and code then
local old = enumUnit
GUI.forGroup(group, function(unit)
enumUnit=unit
code()
end)
enumUnit=old
end
end
do
local oldUnitAt=BlzGroupUnitAt
function BlzGroupUnitAt(group, index)
return group and group[index+1]
end
local oldGetSize=BlzGroupGetSize
local function groupAction(code)
for i=0, oldGetSize(mainGroup)-1 do
code(oldUnitAt(mainGroup, i))
end
end
for _,name in ipairs({
"OfType",
"OfPlayer",
"OfTypeCounted",
"InRect",
"InRectCounted",
"InRange",
"InRangeOfLoc",
"InRangeCounted",
"InRangeOfLocCounted",
"Selected"
}) do
local varStr = "GroupEnumUnits"..name
local old=_G[varStr]
_G[varStr]=function(group, ...)
if group then
old(mainGroup, ...)
GroupClear(group)
groupAction(function(unit)
GroupAddUnit(group, unit)
end)
end
end
--Provide API for Lua users who just want to efficiently run code, without caring about the group itself.
GUI["enumUnits"..name]=function(code, ...)
old(mainGroup, ...)
groupAction(code)
end
end
end
for _,name in ipairs {
"ImmediateOrder",
"ImmediateOrderById",
"PointOrder",
"PointOrderById",
"TargetOrder",
"TargetOrderById"
} do
local new = _G["Issue"..name]
_G["Group"..name]=function(group, ...)
for i=1, #group do
new(group[i], ...)
end
end
end
GroupTrainOrderByIdBJ = GroupImmediateOrderById
BlzGroupGetSize=function(group) return group and #group or 0 end
function GroupAddGroup(group, add)
if not group or not add then return end
GUI.forGroup(add, function(unit)
GroupAddUnit(group, unit)
end)
end
function GroupRemoveGroup(group, remove)
if not group or not remove then return end
GUI.forGroup(remove, function(unit)
GroupRemoveUnit(group, unit)
end)
end
GroupPickRandomUnit=function(group)
return group and group[1] and group[GetRandomInt(1,#group)] or 0
end
IsUnitGroupEmptyBJ=function(group)
return not group or not group[1]
end
ForGroupBJ=ForGroup
CountUnitsInGroup=BlzGroupGetSize
BlzGroupAddGroupFast=GroupAddGroup
BlzGroupRemoveGroupFast=GroupRemoveGroup
GroupPickRandomUnitEnum=nil
CountUnitsInGroupEnum=nil
GroupAddGroupEnum=nil
GroupRemoveGroupEnum=nil
if groups then
OnInit(function(import)
import "UnitEvent"
UnitEvent.onRemoval(function(data)
local u = data.unit
local g = groups[u]
if g then
for _,group in pairs(g) do
GroupRemoveUnit(group,u)
end
end
end)
end)
end
end
--[========================[
• RECTS (REGIONS IN GUI) •
--]========================]
do
local oldRect, rect = Rect
function Rect(...) return {...} end
local oldSetRect = SetRect
function SetRect(r, mix, miy, max, may)
r[1]=mix
r[2]=miy
r[3]=max
r[4]=may
end
do
local oldWorld = GetWorldBounds
local getMinX=GetRectMinX
local getMinY=GetRectMinY
local getMaxX=GetRectMaxX
local getMaxY=GetRectMaxY
local remover = RemoveRect
RemoveRect=DoNothing
local newWorld
function GetWorldBounds()
if not newWorld then
local w = oldWorld()
newWorld = {getMinX(w),getMinY(w),getMaxX(w),getMaxY(w)}
remover(w)
end
return {unpack(newWorld)}
end
GetEntireMapRect = GetWorldBounds
end
function GetRectMinX(r) return r[1] end
function GetRectMinY(r) return r[2] end
function GetRectMaxX(r) return r[3] end
function GetRectMaxY(r) return r[4] end
function GetRectCenterX(r) return (r[1] + r[3])/2 end
function GetRectCenterY(r) return (r[2] + r[4])/2 end
function MoveRectTo(r, x, y)
x = x - GetRectCenterX(r)
y = y - GetRectCenterY(r)
SetRect(r, r[1]+x, r[2]+y, r[3]+x, r[4]+y)
end
---@param varName string
---@param index integer needed to determine which of the parameters calls for a rect.
local function hook(varName, index)
local old = _G[varName]
local func
if index==1 then
func=function(rct, ...)
oldSetRect(rect, unpack(rct))
return old(rect, ...)
end
elseif index==2 then
func=function(a, rct, ...)
oldSetRect(rect, unpack(rct))
return old(a, rect, ...)
end
else--index==3
func=function(a, b, rct, ...)
oldSetRect(rect, unpack(rct))
return old(a, b, rect, ...)
end
end
_G[varName] = function(...)
if not rect then rect = oldRect(0,0,32,32) end
_G[varName] = func
return func(...)
end
end
hook("EnumDestructablesInRect", 1)
hook("EnumItemsInRect", 1)
hook("AddWeatherEffect", 1)
hook("SetDoodadAnimationRect", 1)
hook("GroupEnumUnitsInRect", 2)
hook("GroupEnumUnitsInRectCounted", 2)
hook("RegionAddRect", 2)
hook("RegionClearRect", 2)
hook("SetBlightRect", 2)
hook("SetFogStateRect", 3)
hook("CreateFogModifierRect", 3)
end
--[===============================[
• FORCES (PLAYER GROUPS IN GUI) •
--]===============================]
do
local oldForce, mainForce, initForce = CreateForce
initForce = function()
initForce = DoNothing
mainForce = oldForce()
end
CreateForce=function() return {indexOf={}} end
DestroyForce=DoNothing
local oldClear=ForceClear
function ForceClear(force)
if force then
for i,val in ipairs(force) do
force.indexOf[val]=nil
force[i]=nil
end
end
end
do
local oldCripple = CripplePlayer
local oldAdd=ForceAddPlayer
CripplePlayer = function(player,force,flag)
if player and force then
initForce()
for _,val in ipairs(force) do
oldAdd(mainForce, val)
end
oldCripple(player, mainForce, flag)
oldClear(mainForce)
end
end
end
function ForceAddPlayer(force, player)
if force and player and not force.indexOf[player] then
local pos = #force+1
force.indexOf[player]=pos
force[pos]=player
end
end
function ForceRemovePlayer(force, player)
local pos = force and player and force.indexOf[player]
if pos then
force.indexOf[player]=nil
local top = #force
if pos ~= top then
force[pos] = force[top]
force.indexOf[force[top]] = pos
end
force[top] = nil
end
end
function BlzForceHasPlayer(force, player)
return force and player and force.indexOf[player]
end
function IsPlayerInForce(player, force)
return player and force and force.indexOf[player]
end
function IsUnitInForce(unit, force)
return unit and force and force.indexOf[GetOwningPlayer(unit)]
end
local enumPlayer
local oldForForce = ForForce
local oldEnumPlayer = GetEnumPlayer
GetEnumPlayer=function() return enumPlayer end
ForForce = function(force, code)
local old = enumPlayer
for _,player in ipairs(force) do
enumPlayer=player
code()
end
enumPlayer=old
end
local function funnelEnum(force)
ForceClear(force)
initForce()
oldForForce(mainForce, function()
ForceAddPlayer(force, oldEnumPlayer())
end)
oldClear(mainForce)
end
local function hookEnum(varStr)
local old=_G[varStr]
_G[varStr]=function(force, ...)
initForce()
old(mainForce, ...)
funnelEnum(force)
end
end
hookEnum("ForceEnumPlayers")
hookEnum("ForceEnumPlayersCounted")
hookEnum("ForceEnumAllies")
hookEnum("ForceEnumEnemies")
CountPlayersInForceBJ=function(force) return #force end
CountPlayersInForceEnum=nil
GetForceOfPlayer=function(player)
--No longer leaks. There was no reason to dynamically create forces to begin with.
return bj_FORCE_PLAYER[GetPlayerId(player)]
end
end
--Blizzard forgot to add this, but still enabled it for GUI. Therefore, I've extracted and simplified the code from DebugIdInteger2IdString
function BlzFourCC2S(value)
local result = ""
for _=1,4 do
result = string.char(value % 256) .. result
value = value // 256
end
return result
end
function TriggerRegisterDestDeathInRegionEvent(trig, r)
--Removes the limit on the number of destructables that can be registered.
EnumDestructablesInRect(r, nil, function() TriggerRegisterDeathEvent(trig, GetEnumDestructable()) end)
end
IsUnitAliveBJ=UnitAlive --use the reliable native instead of the life checks
function IsUnitDeadBJ(u) return not UnitAlive(u) end
function SetUnitPropWindowBJ(whichUnit, propWindow)
--Allows the Prop Window to be set to zero to allow unit movement to be suspended.
SetUnitPropWindow(whichUnit, math.rad(propWindow))
end
if _USE_GLOBAL_REMAP then
OnInit(function(import)
import "GlobalRemap"
GlobalRemap("udg_INFINITE_LOOP", function() return -1 end) --a readonly variable for infinite looping in GUI.
end)
end
do
local cache=__jarray()
function GUI.wrapTrigger(whichTrig)
local func=cache[whichTrig]
if not func then
func=function()if IsTriggerEnabled(whichTrig)and TriggerEvaluate(whichTrig)then TriggerExecute(whichTrig)end end
cache[whichTrig]=func
end
return func
end
end
do
--[[---------------------------------------------------------------------------------------------
RegisterAnyPlayerUnitEvent by Bribe
RegisterAnyPlayerUnitEvent cuts down on handle count for alread-registered events, plus has
the benefit for Lua users to just use function calls.
Adds a third parameter to the RegisterAnyPlayerUnitEvent function: "skip". If true, disables
the specified event, while allowing a single function to run discretely. It also allows (if
Global Variable Remapper is included) GUI to un-register a playerunitevent by setting
udg_RemoveAnyUnitEvent to the trigger they wish to remove.
The "return" value of RegisterAnyPlayerUnitEvent calls the "remove" method. The API, therefore,
has been reduced to just this one function (in addition to the bj override).
-----------------------------------------------------------------------------------------------]]
local fStack,tStack,oldBJ = {},{},TriggerRegisterAnyUnitEventBJ
function RegisterAnyPlayerUnitEvent(event, userFunc, skip)
if skip then
local t = tStack[event]
if t and IsTriggerEnabled(t) then
DisableTrigger(t)
userFunc()
EnableTrigger(t)
else
userFunc()
end
else
local funcs,insertAt=fStack[event],1
if funcs then
insertAt=#funcs+1
if insertAt==1 then EnableTrigger(tStack[event]) end
else
local t=CreateTrigger()
oldBJ(t, event)
tStack[event],funcs = t,{}
fStack[event]=funcs
TriggerAddCondition(t, Filter(function()
for _,func in ipairs(funcs)do func()end
end))
end
funcs[insertAt]=userFunc
return function()
local total=#funcs
for i=1,total do
if funcs[i]==userFunc then
if total==1 then DisableTrigger(tStack[event]) --no more events are registered, disable the event (for now).
elseif total> i then funcs[i]=funcs[total] end --pop just the top index down to this vacant slot so we don't have to down-shift the entire stack.
funcs[total]=nil --remove the top entry.
return true
end
end
end
end
end
local trigFuncs
function TriggerRegisterAnyUnitEventBJ(trig, event)
local removeFunc=RegisterAnyPlayerUnitEvent(event, GUI.wrapTrigger(trig))
if _USE_GLOBAL_REMAP then
if not trigFuncs then
trigFuncs=__jarray()
GlobalRemap("udg_RemoveAnyUnitEvent", nil, function(t)
if trigFuncs[t] then
trigFuncs[t]()
trigFuncs[t]=nil
end
end)
end
trigFuncs[trig]=removeFunc
end
return removeFunc
end
end
---Modify to allow requests for negative hero stats, as per request from Tasyen.
---@param whichHero unit
---@param whichStat integer
---@param value integer
function SetHeroStat(whichHero, whichStat, value)
(whichStat==bj_HEROSTAT_STR and SetHeroStr or whichStat==bj_HEROSTAT_AGI and SetHeroAgi or SetHeroInt)(whichHero, value, true)
end
--The next part of the code is purely optional, as it is intended to optimize rather than add new functionality
CommentString = nil
RegisterDestDeathInRegionEnum = nil
--This next list comes from HerlySQR, and its purpose is to eliminate useless wrapper functions (only where the parameters aligned):
StringIdentity = GetLocalizedString
TriggerRegisterTimerExpireEventBJ = TriggerRegisterTimerExpireEvent
TriggerRegisterDialogEventBJ = TriggerRegisterDialogEvent
TriggerRegisterUpgradeCommandEventBJ = TriggerRegisterUpgradeCommandEvent
RemoveWeatherEffectBJ = RemoveWeatherEffect
DestroyLightningBJ = DestroyLightning
GetLightningColorABJ = GetLightningColorA
GetLightningColorRBJ = GetLightningColorR
GetLightningColorGBJ = GetLightningColorG
GetLightningColorBBJ = GetLightningColorB
SetLightningColorBJ = SetLightningColor
GetAbilityEffectBJ = GetAbilityEffectById
GetAbilitySoundBJ = GetAbilitySoundById
ResetTerrainFogBJ = ResetTerrainFog
SetSoundDistanceCutoffBJ = SetSoundDistanceCutoff
SetSoundPitchBJ = SetSoundPitch
AttachSoundToUnitBJ = AttachSoundToUnit
KillSoundWhenDoneBJ = KillSoundWhenDone
PlayThematicMusicBJ = PlayThematicMusic
EndThematicMusicBJ = EndThematicMusic
StopMusicBJ = StopMusic
ResumeMusicBJ = ResumeMusic
VolumeGroupResetImmediateBJ = VolumeGroupReset
WaitForSoundBJ = TriggerWaitForSound
ClearMapMusicBJ = ClearMapMusic
DestroyEffectBJ = DestroyEffect
GetItemLifeBJ = GetWidgetLife -- This was just to type casting
SetItemLifeBJ = SetWidgetLife -- This was just to type casting
UnitRemoveBuffBJ = UnitRemoveAbility -- The buffs are abilities
GetLearnedSkillBJ = GetLearnedSkill
UnitDropItemPointBJ = UnitDropItemPoint
UnitDropItemTargetBJ = UnitDropItemTarget
UnitUseItemDestructable = UnitUseItemTarget -- This was just to type casting
UnitInventorySizeBJ = UnitInventorySize
SetItemInvulnerableBJ = SetItemInvulnerable
SetItemDropOnDeathBJ = SetItemDropOnDeath
SetItemDroppableBJ = SetItemDroppable
SetItemPlayerBJ = SetItemPlayer
ChooseRandomItemBJ = ChooseRandomItem
ChooseRandomNPBuildingBJ = ChooseRandomNPBuilding
ChooseRandomCreepBJ = ChooseRandomCreep
String2UnitIdBJ = UnitId -- I think they just wanted a better name
GetIssuedOrderIdBJ = GetIssuedOrderId
GetKillingUnitBJ = GetKillingUnit
IsUnitHiddenBJ = IsUnitHidden
IssueTrainOrderByIdBJ = IssueImmediateOrderById -- I think they just wanted a better name
IssueUpgradeOrderByIdBJ = IssueImmediateOrderById -- I think they just wanted a better name
GetAttackedUnitBJ = GetTriggerUnit -- I think they just wanted a better name
SetUnitFlyHeightBJ = SetUnitFlyHeight
SetUnitTurnSpeedBJ = SetUnitTurnSpeed
GetUnitDefaultPropWindowBJ = GetUnitDefaultPropWindow
SetUnitBlendTimeBJ = SetUnitBlendTime
SetUnitAcquireRangeBJ = SetUnitAcquireRange
UnitSetCanSleepBJ = UnitAddSleep
UnitCanSleepBJ = UnitCanSleep
UnitWakeUpBJ = UnitWakeUp
UnitIsSleepingBJ = UnitIsSleeping
IsUnitPausedBJ = IsUnitPaused
SetUnitExplodedBJ = SetUnitExploded
GetTransportUnitBJ = GetTransportUnit
GetLoadedUnitBJ = GetLoadedUnit
IsUnitInTransportBJ = IsUnitInTransport
IsUnitLoadedBJ = IsUnitLoaded
IsUnitIllusionBJ = IsUnitIllusion
SetDestructableInvulnerableBJ = SetDestructableInvulnerable
IsDestructableInvulnerableBJ = IsDestructableInvulnerable
SetDestructableMaxLifeBJ = SetDestructableMaxLife
WaygateIsActiveBJ = WaygateIsActive
QueueUnitAnimationBJ = QueueUnitAnimation
SetDestructableAnimationBJ = SetDestructableAnimation
QueueDestructableAnimationBJ = QueueDestructableAnimation
DialogSetMessageBJ = DialogSetMessage
DialogClearBJ = DialogClear
GetClickedButtonBJ = GetClickedButton
GetClickedDialogBJ = GetClickedDialog
DestroyQuestBJ = DestroyQuest
QuestSetTitleBJ = QuestSetTitle
QuestSetDescriptionBJ = QuestSetDescription
QuestSetCompletedBJ = QuestSetCompleted
QuestSetFailedBJ = QuestSetFailed
QuestSetDiscoveredBJ = QuestSetDiscovered
QuestItemSetDescriptionBJ = QuestItemSetDescription
QuestItemSetCompletedBJ = QuestItemSetCompleted
DestroyDefeatConditionBJ = DestroyDefeatCondition
DefeatConditionSetDescriptionBJ = DefeatConditionSetDescription
FlashQuestDialogButtonBJ = FlashQuestDialogButton
DestroyTimerBJ = DestroyTimer
DestroyTimerDialogBJ = DestroyTimerDialog
TimerDialogSetTitleBJ = TimerDialogSetTitle
TimerDialogSetSpeedBJ = TimerDialogSetSpeed
TimerDialogDisplayBJ = TimerDialogDisplay
LeaderboardSetStyleBJ = LeaderboardSetStyle
LeaderboardGetItemCountBJ = LeaderboardGetItemCount
LeaderboardHasPlayerItemBJ = LeaderboardHasPlayerItem
DestroyLeaderboardBJ = DestroyLeaderboard
LeaderboardDisplayBJ = LeaderboardDisplay
LeaderboardSortItemsByPlayerBJ = LeaderboardSortItemsByPlayer
LeaderboardSortItemsByLabelBJ = LeaderboardSortItemsByLabel
PlayerGetLeaderboardBJ = PlayerGetLeaderboard
DestroyMultiboardBJ = DestroyMultiboard
SetTextTagPosUnitBJ = SetTextTagPosUnit
SetTextTagSuspendedBJ = SetTextTagSuspended
SetTextTagPermanentBJ = SetTextTagPermanent
SetTextTagAgeBJ = SetTextTagAge
SetTextTagLifespanBJ = SetTextTagLifespan
SetTextTagFadepointBJ = SetTextTagFadepoint
DestroyTextTagBJ = DestroyTextTag
ForceCinematicSubtitlesBJ = ForceCinematicSubtitles
DisplayCineFilterBJ = DisplayCineFilter
SaveGameCacheBJ = SaveGameCache
FlushGameCacheBJ = FlushGameCache
SaveGameCheckPointBJ = SaveGameCheckpoint
LoadGameBJ = LoadGame
RenameSaveDirectoryBJ = RenameSaveDirectory
RemoveSaveDirectoryBJ = RemoveSaveDirectory
CopySaveGameBJ = CopySaveGame
IssueTargetOrderBJ = IssueTargetOrder
IssueTargetDestructableOrder = IssueTargetOrder -- This was just to type casting
IssueTargetItemOrder = IssueTargetOrder -- This was just to type casting
IssueImmediateOrderBJ = IssueImmediateOrder
GroupTargetOrderBJ = GroupTargetOrder
GroupImmediateOrderBJ = GroupImmediateOrder
GroupTargetDestructableOrder = GroupTargetOrder -- This was just to type casting
GroupTargetItemOrder = GroupTargetOrder -- This was just to type casting
GetDyingDestructable = GetTriggerDestructable -- I think they just wanted a better name
GetAbilityName = GetObjectName -- I think they just wanted a better name
end
do
--[[
Doubly-Linked List v1.3.0.0 by Wrda, Eikonium and Bribe
------------------------------------------------------------------------------
A script that allows the possibility to create a sequence of any object
linked together.
------------------------------------------------------------------------------
API:
LinkedList.create(head) -> LinkedList
- Creates or resets a table as a LinkedList head.
- Allows a user-specified head or generates a new one.
list:insert([node_or_value, after]) -> listNode
- Inserts *before* the given list/node unless "after" is true.
- If a "node or value" is passed, the system will check if the node is
a table. If the table isn't yet part of a LinkedList structure, it
will be converted into the node that is returned at the end of this
function. If the table is a part of the LinkedList structure, or a
different type of value than a table, then it will be assigned as a
generic "value" (mapped to node.value)
- Returns the inserted node that was added to the list (if addition was successful).
list:remove(node) -> boolean
- Removes a node from whatever list it is a part of and calls self:onRemove().
- Returns true if it was sucessful.
for node in list:loop([backwards]) do [stuff] end
- Iterates over all nodes in "list".
fromList:merge(intoList[, backwardsFrom, backwardsInto])
- Removes all nodes from one list and adds them into another.
list:reset() -> boolean
- Removes all nodes from the given linked list, calling node:onRemove() on each.
- Returns true if sucessful.
- readonly list.n : integer -> the number of nodes in the list.
]]
---@class LinkedList:table
---@field head LinkedList
---@field next listNode|LinkedList
---@field prev listNode|LinkedList
---@field n integer
LinkedList = {}
LinkedList.__index = LinkedList
---@class listNode:LinkedList
---@field remove fun(node:listNode)->boolean
---@field onRemove fun(self:listNode)
---Creates or resets a table as a LinkedList head.
---@param head? LinkedList allows a user-specified head or generates a new one.
---@return LinkedList
function LinkedList.create(head)
if head and type(head) == "table" then
local h = head.head
if h then
if h ~= head then
return --user passed an active ListNode. This is not allowed.
end
if h.n > 0 then --first empty any lists that still have nodes.
for node in head:loop() do node:onRemove() end
end
end
else
head = {}
end
setmetatable(head, LinkedList)
head.next = head
head.prev = head
head.head = head
head.n = 0
return head
end
---Node can be an existing table, or a new table will be created to represent the
---node. "list" can either be the head, or any point where you want the node to be
---inserted. It will insert *before* the given head/node, unless "backward" is true.
---@param list listNode|LinkedList
---@param node_or_value? any
---@param insertAfter? boolean
---@return listNode node that was added to the list (if addition was successful)
function LinkedList.insert(list, node_or_value, insertAfter)
if not list then return end
local head = list.head
if not head then return end
local node, value
if node_or_value then
if type(node_or_value) == "table" then
if node_or_value.head then --table is already part of a linked list. Treat it as a "value"
value = node_or_value
else
node = node_or_value --table will be transmuted into the linked list node itself.
end
else
--User passed a non-table value.
value = node_or_value
end
end
if insertAfter then list = list.next end
node = node or {} ---@type listNode
setmetatable(node, LinkedList)
list.prev.next = node
node.prev = list.prev
list.prev = node
node.next = list
node.head = head
head.n = head.n + 1
node.value = value
node.onRemove = function() node.head = nil end
return node
end
---Removes a node from whatever list it is a part of. A node cannot be a part of
---more than one list at a time, so there is no need to pass the containing list as
---an argument.
---@param node listNode
---@return boolean wasRemoved
function LinkedList:remove(node)
node = node or self
if node then
local head = node.head
if head and head ~= node then
node.prev.next = node.next
node.next.prev = node.prev
head.n = head.n - 1
node:onRemove()
return true
end
end
end
---Enables the generic for-loop for LinkedLists.
---Syntax: "for node in LinkedList.loop(list) do print(node) end"
---Alternative Syntax: "for node in list:loop() do print(node) end"
---@param list LinkedList
---@param backward? boolean
function LinkedList.loop(list, backward)
list = list.head
local loopNode = list ---@type listNode
local direction = backward and "prev" or "next"
return function()
loopNode = loopNode[direction]
return loopNode ~= list and loopNode or nil
end
end
---Merges LinkedList "from" to another LinkedList "into"
---@param from LinkedList|listNode
---@param into LinkedList|listNode
---@param backwardFrom boolean
---@param backwardInto boolean
function LinkedList.merge(from, into, backwardFrom, backwardInto)
if from and from.head and into and into.head then
local directionFrom = backwardFrom and "prev" or "next"
local n, v
local node = from[directionFrom]
from = from.head
while node ~= from do
n, v = node[directionFrom], node.value
node:remove()
into:insert(node, backwardInto).value = v
node = n
end
end
end
---Removes all nodes from the given linked list.
---@param list LinkedList
---@return boolean was_reset
function LinkedList.reset(list)
return list:create() ~= nil
end
end
if LinkedList then --https://www.hiveworkshop.com/threads/definitive-doubly-linked-list.339392/
--[[--------------------------------------------------------------------------------------
Hook v4.1.0.0 by Bribe, with very special thanks to:
Eikonium and Jampion for bug reports, feature improvements, teaching me new things.
MyPad for teaching me new things
Wrda and Eikonium for the better LinkedList approach
----------------------------------------------------------------------------------------]]
Hook = {}
local _LOW_PRIO = -0.1 -- a number to represent what should be the lowest priority for a before-hook (lower values run first).
local _HIGH_PRIO = 9001 -- a number to represent what should be the lowest priority for an after-hook (lower values run first).
local _SKIP_HOOK = "skip hook" --when this is returned from a Hook.addSimple function, the hook will stop.
local hookBefore = {} ---@type Hook[] --stores a list of functions that are called prior to a hooked function.
local hookAfter = {} ---@type Hook[] --stores a list of functions that are called after a hooked function.
local hookedFunc = {} ---@type function[] --stores a list of overriden functions
---@class Hook:LinkedList
---@field add function
---@field addSimple function
---@field flush function
---@field func function
---@class hookNode :listNode
---@field weight number
---@field head Hook
---@field func fun(hook:Hook)
---@class hookInstance:table
---@field args table
---@field call function
---@field skip boolean
---@field returned table
--[[--------------------------------------------------------------------------------------
Internal functions
----------------------------------------------------------------------------------------]]
---@param oldFunc string
---@param parent? table
---@return table
---@return table hookedFuncParent
---@return function? hooked_func_or_nil
---@return function hooked_func
local function parseArgs(oldFunc, parent)
parent = parent or _G
local hfp = hookedFunc[parent]
local hf = hfp and hfp[oldFunc]
return parent, hfp, hf, hf or parent[oldFunc]
end
--[[--------------------------------------------------------------------------------------
Hook.add
Args: string oldFunc, function userFunc[, number weight, table parent, function default]
@ oldFunc is a string that represents the name of a function (e.g. "CreateUnit")
@ userFunc is the function you want to be called when the original function is
called*.
@ weight is an optional parameter that determines whether your hook takes place
"before" the original function is called, or after. Broken down like this:
(a) if "weight" is "nil", "false" or a "negative number", it is treated as a
"before hook". If "nil" or "false", "_LOW_PRIO" will be assigned as the weight.
(b) if "weight" is "true", "0" or a "positive number", it is treated as an
"after hook". If "true",
@ parent is an optional parameter for where the oldFunc is hosted. By default,
it assumes a global (_G table) such as "BJDebugMsg".
@ default is a function that you can inject into the table in case that variable
is not found. If the variable is not found and a function is not passed as a
default, the addition will fail.
Returns two items:
1. The original function you are hooking (if successful) or nil (if failed).
2. A table to represent your hook registry. This is part of a linked list belonging
to the function you hooked and aligned with whether it is a "before" or "after"
hook. Its most relevant use would be to be passed to "Hook.remove(userHookTable)",
as that is the way to remove a single hook in version 4.0.
*The function you specify in Hook.add can take exactly one argument: a table. That
table has the following properties within itself:
args
(table)
Contains the original arguments passed during a hook. Useful for referencing in an
"after hook". Can be modified by a "before hook".
returned
(table or nil)
Contains a table of the return value(s) from "before" hooks and (if applicable) the
original function. This is either "nil", or usually only holds a single index. To
initialize this correctly, use table.pack(returnVal[, returnVal2, returnVal3, ...]).
old
(function)
The original, native function that has been hooked (in case you want to call it).
skip
(boolean)
Note: Set this to "true" from within a before-hook callback function to prevent the
original function from being called. Users can check if this is set to true if
they want to change the behavior of their own hooks accordingly.
----------------------------------------------------------------------------------------]]
---@param oldFunc string
---@param userFunc fun(hook:table)
---@param weight? number
---@param parent? table
---@param default? function
---@return function original_function
---@return hookNode newUserNode
function Hook.add(oldFunc, userFunc, weight, parent, default)
if type(oldFunc) ~= "string" or type(userFunc) ~= "function" then
--print "Hook.add Error: The first argument must be a string, the second must be a function."
return
end
local parent, hfp, hf, old = parseArgs(oldFunc, parent)
if not old or type(old) ~= "function" then
if default then
old = default
parent[oldFunc] = default
else
--print("Hook.add Error: Tried to hook a function that doesn't exist: " .. oldFunc .. ".\nTry calling Hook.add from a Global Initialization function.")
return
end
end
if not hf then
if not hfp then
hfp = {}
hookedFunc[parent] = hfp
end
hfp[oldFunc] = old ---@type function
local hb = LinkedList.create() ---@type Hook
hookBefore[old] = hb
hb.func = old
local ha = LinkedList.create() ---@type Hook
hookAfter[old] = ha
ha.func = old
parent[oldFunc] =
function(...)
local this = {args = table.pack(...), call = old, skip = false } ---@type hookInstance
for userNode in hb:loop() do userNode.func(this) end
local r
if not this.skip then
r = table.pack(old(table.unpack(this.args, 1, this.args.n)))
if r.n > 0 then this.returned = r end
end
r = this.returned
if not (r and type(r) == "table" and r.n and r.n > 0) then
r = nil; this.returned = nil
--else
--print("Hook report: returning " .. r.n .. " values.")
end
for userNode in ha:loop() do userNode.func(this) end
if r then return table.unpack(r, 1, r.n) end
end
end
weight = weight or _LOW_PRIO
if weight == true then weight = _HIGH_PRIO end
--This creates and inserts newUserNode into the corresponding table with taking into consideration the weight of each item.
local tab = weight < 0 and hookBefore[old] or hookAfter[old]
local insertPoint = tab.head
local newUserNode
for node in tab:loop() do
if node.weight > weight then insertPoint = node; break end
end
newUserNode = insertPoint:insert(nil, true) ---@type hookNode
newUserNode.func = userFunc
newUserNode.weight = weight
newUserNode.remove = Hook.remove
--print("indexing")
return old, newUserNode
end
---Remove a registered hook by passing the node returned from the second
---return value of Hook.add.
---@param node hookNode
---@return integer number_of_hooks_remaining
function Hook.remove(node)
local r = 0
local head = node.head
if head then
node:remove()
r = hookBefore[head.func].n + hookAfter[head.func].n
if r == 0 then
Hook.flush(head.func)
end
end
return r
end
--[[--------------------------------------------------------------------------------------
Hook.flush
Args: string oldFunc[, table parent]
Desc: Purges all hooks associated with the given function string and sets the original
function back inside of the parent table.
----------------------------------------------------------------------------------------]]
---Hook.flush
---@param oldFunc string
---@param parent? table
function Hook.flush(oldFunc, parent)
local parent, hfp, hf, old = parseArgs(oldFunc, parent)
if hf then
parent[oldFunc] = old
hookBefore[old] = nil
hookAfter[old] = nil
hfp[oldFunc] = nil
end
end
--[[--------------------------------------------------------------------------------------
The user-function parameters and behavior are different from Hook.add. This uses
the original format I wanted for hook-behavior, but it became clear that there
were scenarios where the user should be able to do more.
"Before hook" parameters are the arguments of the original function call. This is
useful in a situation where you don't want to unpack the args yourself to see them in
an intuitive way, and don't need the additional complexities of the table to determine
what you want to do.
Return: If anything other than "nil" is returned, it will prevent any additional
"before" hooks with a lower priority from running, as well as prevent the
original function from being called. If returning a value other than "nil"
would break the expectations of the original function, return the string
"stop hook" instead.
"After hook"
------------
Args: Takes the return value(s) as parameter(s), if there was any return value.
----------------------------------------------------------------------------------------]]
---@param oldFunc string
---@param userFunc function
---@param weight? number
---@param parent? table
---@param default? function
---@return function original_function
---@return hookNode newUserNode
function Hook.addSimple(oldFunc, userFunc, weight, parent, default)
return Hook.add(oldFunc,
function(hook)
local r = hook.returned
if weight and (weight == true or weight >= 0) then
if r then
userFunc(table.unpack(r, 1, r.n))
else
userFunc()
end
elseif not hook.skip and not r then
r = userFunc(table.unpack(hook.args, 1, hook.args.n))
if r and #r > 0 then
if r[1] ~= _SKIP_HOOK then
hook.returned = table.pack(r)
end
hook.skip = true
end
end
end, weight, parent, default)
end
end
if Hook then --https://www.hiveworkshop.com/threads/hook.339153
-- Global Initialization 2.2.2.0 by Bribe, with special thanks to Tasyen, Forsakn and Troll-Brain
local sFuncs
local function Flush()
if sFuncs then return end
sFuncs = {}
Hook.add("InitBlizzard",
function()
local t = CreateTimer()
TimerStart(t, 0.00, false,
function()
DestroyTimer(t)
for _, f in ipairs(sFuncs) do f() end
sFuncs = nil
OnGlobalInit = nil
OnTrigInit = nil
OnMapInit = nil
OnGameStart = nil
Hook.flush("InitBlizzard")
Hook.flush("InitGlobals")
Hook.flush("InitCustomTriggers")
Hook.flush("RunInitializationTriggers")
end)
end)
end
local function Init(str, backup, func, priority)
if not func or type(func) == "number" then
func, priority = priority, func or true
end
if not Hook.add(str, func, priority) then
backup(priority, func)
end
Flush()
end
---@param priority number | function
---@param func? function
function OnGlobalInit(priority, func) -- Runs once all GUI variables are instantiated.
Init("InitGlobals", function(priority, func) Hook.add("InitBlizzard", func, priority) end, func, priority)
end
---@param priority number | function
---@param func? function
function OnTrigInit(priority, func) -- Runs once all InitTrig_ are called
Init("InitCustomTriggers", OnGlobalInit, func, priority)
end
---@param priority number | function
---@param func? function
function OnMapInit(priority, func) -- Runs once all Map Initialization triggers are run
Init("RunInitializationTriggers", OnTrigInit, func, priority)
end
---@param func function
function OnGameStart(func) -- Runs once the game has actually started
Flush()
sFuncs[#sFuncs + 1] = func
end
end
if Hook then --https://www.hiveworkshop.com/threads/hook.339153
--[[--------------------------------------------------------------------------------------
Global Variable Remapper v1.0.1.1 by Bribe
- Intended to empower the GUI user-base and those who design systems for them.
API:
GlobalRemap(variableStr, getterFunc, setterFunc)
@variableStr is a string such as "udg_MyVariable"
@getterFunc is a function that takes nothing but returns the expected value when
"udg_MyVariable" is referenced.
@setterFunc is a function that takes a single argument (the value that is being
assigned) and allows you to do what you want when someone uses "Set MyVariable = SomeValue".
The function doesn't need to do anything nor return anything. Enables read-only
GUI variables for the first time in WarCraft 3 history.
Systems that use this should call GlobalRemap via Global Initialization or later:
https://www.hiveworkshop.com/threads/global-initialization.317099/
----------------------------------------------------------------------------------------]]
local getters, setters, skip
---GlobalRemap
---@param var string
---@param getFunc? fun() ->value?
---@param setFunc? fun(value)
function GlobalRemap(var, getFunc, setFunc)
if not skip then
getters, setters, skip = {}, {}, DoNothing
local mt = getmetatable(_G)
if not mt then
mt = {}
setmetatable(_G, mt)
end
--hook.args = {1:table, 2:index}
Hook.add("__index",
function(hook)
local func = getters[hook.args[2]]
if func then
hook.skip = true
hook.returned = table.pack(func())
end
end, nil, mt,
function(a, b)
return rawget(a, b)
end)
--hook.args = {1:table, 2:index, 3:value}
Hook.add("__newindex",
function(hook)
local func = setters[hook.args[2]]
if func then
hook.skip = true
func(hook.args[3])
end
end, nil, mt,
function(a, b, c)
rawset(a, b, c)
end)
end
_G[var] = nil --Delete the variable from the global table.
getters[var] = getFunc or skip --Assign a function that returns what should be returned when this variable is referenced.
setters[var] = setFunc or skip --Assign a function that captures the value the variable is attempting to be set to.
end
end
if LinkedList then --https://www.hiveworkshop.com/threads/definitive-doubly-linked-list.339392
--[[--------------------------------------------------------------------------------------
Timed Call and Echo v1.2.1.0, code structure credit to Eikonium and Jesus4Lyf
Timed.call([delay, ]userFunc)
-> Call userFunc after 'delay' seconds. Delay defaults to 0 seconds.
Timed.echo(userFunc[, timeout, userTable])
-> Returns userTable or a new table.
-> calls userFunc every "timeout" seconds until userFunc returns true or you call
userTable:remove()
Node API (for the tables returned by Timed.echo):
node.elapsed -> the number of seconds that 'node' has been iterating for.
----------------------------------------------------------------------------------------]]
local _TIMEOUT = 0.03125 --default echo timeout
Timed = {}
---@class timedNode:listNode
---@field elapsed number
--[[--------------------------------------------------------------------------------------
Internal
----------------------------------------------------------------------------------------]]
local zeroList, _ZERO_TIMER
--[[--------------------------------------------------------------------------------------
Name: Timed.call
Args: [delay, ]userFunc
Desc: After "delay" seconds, call "userFunc".
----------------------------------------------------------------------------------------]]
---Core function by Eikonium; zero-second expiration is a simple list by Bribe
---@param delay number|function
---@param userFunc? function|number
function Timed.call(delay, userFunc)
if not userFunc or delay == 0.00 then
if not zeroList then
zeroList = {}
_ZERO_TIMER = _ZERO_TIMER or CreateTimer()
TimerStart(_ZERO_TIMER, 0.00, false,
function()
local tempList = zeroList
zeroList = nil
for _, func in ipairs(tempList) do func() end
end)
end
zeroList[#zeroList + 1] = userFunc or delay
return
end
local t = CreateTimer()
TimerStart(t, delay, false,
function()
DestroyTimer(t)
userFunc()
end)
end
local lists = {}
--[[--------------------------------------------------------------------------------------
Timed.echo is reminiscent of Jesus4Lyf's Timer32 module. It borrows from it with the
LinkedList syntax and "exitwhen true" nature of the original T32 module.
Desc: Calls userFunc every timeout seconds (by default, every 0.03125 seconds). If
your own node should be specified but you want to use the default timeout, you
can use Timed.echo(yourFunc, nil, myTable).
Warn: This merges all timeouts of the same value together, so large numbers can cause
expirations to occur too early on.
----------------------------------------------------------------------------------------]]
---@param userFunc fun(node:timedNode):boolean -- if true, echo will stop
---@param timeout? number
---@param node? timedNode
---@return timedNode new_node
function Timed.echo(userFunc, timeout, node)
timeout = timeout or _TIMEOUT
local list = lists[timeout]
local t
node = node or {} ---@type timedNode
if list then
t = list.timer
local r = TimerGetRemaining(t)
if r < timeout * 0.50 then --the merge uses rounding to determine if
local q = list.queue --the first expiration should be skipped
if not q then
q = LinkedList.create()
list.queue = q
end
node.elapsed = r --add the remaining timeout to the elapsed time for this node.
node.func = userFunc
return q:insert(node)
end
node.elapsed = r - timeout --the instance will be called on the next tick, despite not being around for the full tick.
else
list = LinkedList.create()
lists[timeout] = list
t = CreateTimer() --one timer per timeout interval
list.timer = t
TimerStart(t, timeout, true,
function()
for tNode in list:loop() do
tNode.elapsed = tNode.elapsed + timeout
if tNode.func(tNode) then --function can return true to remove itself from the list.
tNode:remove()
end
end
-- delayed add to list
if list.queue then
list.queue:merge(list)
list.queue = nil
end
--
if list.n == 0 then --list is empty; delete it.
lists[timeout] = nil
PauseTimer(t)
DestroyTimer(t)
end
end)
node.elapsed = 0.00
end
node.func = userFunc
return list:insert(node)
end
end
if Hook -- https://www.hiveworkshop.com/threads/hook.339153
and Timed then -- https://www.hiveworkshop.com/threads/timed-call-and-echo.339222/
--[[--------------------------------------------------------------------------------------
Lua Damage Engine Version 2.0.0.0
Documentation is found in the code, not in this header.
I'd like to give very special thanks to Eikonium for equipping me with the debugging
tools I needed to get Lua Damage Engine published. I'd also like to thank MindWorX and
Eikonium for getting me started with VSCode, which has changed my (programming) life.
If you want GUI functionality, you also will need the following library:
Global Variable Remapper - https://www.hiveworkshop.com/threads/global-variable-remapper
----------------------------------------------------------------------------------------]]
OnGlobalInit(1, function() Damage = {}
---@class damageEvent:LinkedList
---@class damageEventRegistry:listNode
---@class damageInstance:table
--[[--------------------------------------------------------------------------------------
Configurable variables are listed below
----------------------------------------------------------------------------------------]]
local _USE_GUI = GlobalRemap
local _USE_EXTRA = _USE_GUI --If you don't use DamageEventLevel/DamageEventAOE/SourceDamageEvent, set this to false
local _USE_ARMOR_MOD = true --If you do not modify nor detect armor/defense, set this to false
local _USE_MELEE_RANGE = true --If you do not detect melee nor ranged damage, set this to false
local _LIMBO = 16 --When manually-enabled recursion is enabled via Damage.recurion, the engine will never go deeper than LIMBO.
local _DEATH_VAL = 0.405 --In case M$ or Bliz ever change this, it'll be a quick fix here.
local _TYPE_CODE = 1 --Must be the same as udg_DamageTypeCode, or 0 if you prefer to disable the automatic flag.
local _TYPE_PURE = 2 --Must be the same as udg_DamageTypePure
--These variables coincide with Blizzard's "limitop" type definitions.
local _FILTER_ATTACK = 0 --LESS_THAN
local _FILTER_MELEE = 1 --LESS_THAN_OR_EQUAL
local _FILTER_OTHER = 2 --EQUAL
local _FILTER_RANGED = 3 --GREATER_THAN_OR_EQUAL
local _FILTER_SPELL = 4 --GREATER_THAN
local _FILTER_CODE = 5 --NOT_EQUAL
local CheckUnitType = IsUnitType
local t1, t2, t3 ---@type trigger
local current = nil ---@type damageInstance
local userIndex = nil ---@type damageEventRegistry
local checkConfig
do
local GetUnitItem = UnitItemInSlot
local GetItemType = GetItemTypeId
local GUTI = GetUnitTypeId
local GUAL = GetUnitAbilityLevel
local GRR = GetRandomReal
local function checkItem(u, id)
if CheckUnitType(u, UNIT_TYPE_HERO) then
for i = 0, UnitInventorySize(u) - 1 do
if GetItemType(GetUnitItem(u, i)) == id then return true end
end
end
end
checkConfig = function() if not userIndex.configured then return true
--[[--------------------------------------------------------------------------------------
Mapmakers should comment-out any of the below lines that they will never need to check
for, and move the most common checks to the top of the list.
----------------------------------------------------------------------------------------]]
elseif userIndex.sourceType and GUTI(current.source) ~= userIndex.sourceType then
elseif userIndex.targetType and GUTI(current.target) ~= userIndex.targetType then
elseif userIndex.sourceBuff and GUAL(current.source, userIndex.sourceBuff) == 0 then
elseif userIndex.targetBuff and GUAL(current.target, userIndex.targetBuff) == 0 then
elseif userIndex.failChance and GRR(0.00, 1.00) <= userIndex.failChance then
elseif userIndex.userType and current.userType ~= userIndex.userType then
elseif userIndex.source and userIndex.source ~= current.source then
elseif userIndex.target and userIndex.target ~= current.target then
elseif userIndex.attackType and userIndex.attackType ~= current.attackType then
elseif userIndex.damageType and userIndex.damageType ~= current.damageType then
elseif userIndex.sourceItem and not checkItem(current.source, userIndex.sourceItem) then
elseif userIndex.targetItem and not checkItem(current.target, userIndex.targetItem) then
elseif userIndex.sourceClass and not CheckUnitType(current.source, userIndex.sourceClass) then
elseif userIndex.targetClass and not CheckUnitType(current.target, userIndex.targetClass) then
elseif current.damage >= userIndex.damageMin then
--[[--------------------------------------------------------------------------------------
Configuration section is over. The rest of the library is hard-coded.
----------------------------------------------------------------------------------------]]
--print("Configuration passed")
return true
end
--print("Checking failed")
end
end
--[[--------------------------------------------------------------------------------------
Readonly variables are defined below.
----------------------------------------------------------------------------------------]]
local readonly = {}
readonly.index = function() return current end --Damage.index is the currently-running damage table that contains properties like source/target/damage.
local lastRegistered = nil ---@type damageEventRegistry
readonly.lastRegistered = function() return lastRegistered end --Damage.lastRegistered identifies whatever damage event was most recently added.
readonly.userIndex = function() return userIndex end --Damage.userIndex identifies the registry table for the damage function that's currently running.
local sourceStacks = 1
readonly.sourceStacks = function() return sourceStacks end --Damage.sourceStacks holds how many times a single unit was hit from the same source using the same attack. AKA udg_DamageEventLevel.
local sourceAOE = 1
readonly.sourceAOE = function() return sourceAOE end --Damage.sourceAOE holds how many units were hit by the same source using the same attack. AKA udg_DamageEventAOE.
local originalSource
readonly.originalSource = function() return originalSource end --Damage.originalSource tracks whatever source unit started the current series of damage event(s). AKA udg_AOEDamageSource.
local originalTarget
readonly.originalTarget = function() return originalTarget end --Damage.originalTarget tracks whatever target unit was first hit by the original source. AKA udg_EnhancedDamageTarget.
local _DAMAGING = LinkedList.create() ---@type damageEvent
readonly.damagingEvent = function() return _DAMAGING end
local _ARMOR = LinkedList.create() ---@type damageEvent
readonly.armorEvent = function() return _ARMOR end
local _DAMAGED = LinkedList.create() ---@type damageEvent
readonly.damagedEvent = function() return _DAMAGED end
local _ZERO = LinkedList.create() ---@type damageEvent
readonly.zeroEvent = function() return _ZERO end
local _AFTER = LinkedList.create() ---@type damageEvent
readonly.afterEvent = function() return _AFTER end
local _LETHAL = LinkedList.create() ---@type damageEvent
readonly.lethalEvent = function() return _LETHAL end
local _SOURCE = LinkedList.create() ---@type damageEvent
readonly.sourceEvent = function() return _SOURCE end
local GetUnitLife = GetWidgetLife
local SetUnitLife = SetWidgetLife
local Alive = UnitAlive
local disableT = DisableTrigger
local enableT = EnableTrigger
local hasLethal ---@type boolean
local hasSource ---@type boolean
---@class damageEvent
---@class damageEventRegistry
---@field minAOE integer
---@field filters boolean[]
---@field targetClass unittype
---@field sourceClass unittype
---@field targetItem itemtype
---@field sourceItem itemtype
---@field sourceType unittype
---@field targetType unittype
---@field targetBuff integer
---@field sourceBuff integer
---@field source unit
---@field target unit
---@field attackType attacktype
---@field damageType damagetype
---@field weaponType weapontype
---@field damageMin number
---@field userType integer
---@field trig trigger
---@field eFilter integer
---@field trigFrozen boolean
---@field levelsDeep integer
---@class damageInstance
---@field source unit
---@field target unit
---@field damage real
---@field prevAmt real
---@field isAttack boolean
---@field isRanged boolean
---@field isMelee boolean
---@field attackType attacktype
---@field damageType damagetype
---@field weaponType weapontype
---@field isCode boolean
---@field isSpell boolean
---@field recursiveFunc damageEventRegistry[]
---@field userType integer
---@field armorPierced real
---@field prevArmorT integer
---@field armorType integer
---@field prevDefenseT integer
---@field defenseType integer
local dreaming ---@type boolean
---Turn on (true) or off (false or nil) Damage Engine
---@param on boolean
function Damage.enable(on)
if on then
if dreaming then enableT(t3)
else enableT(t1); enableT(t2) end
else
if dreaming then disableT(t3)
else disableT(t1); disableT(t2) end
end
end
local breakCheck = {} ---@type function[]
local override ---@type boolean
breakCheck[_DAMAGING] = function() return override or current.userType == _TYPE_PURE end
breakCheck[_ARMOR] = function() return current.damage <= 0.00 end
breakCheck[_LETHAL] = function() return hasLethal and Damage.life > _DEATH_VAL end
---@return boolean
local function damageOrAfter() return current.damageType == DAMAGE_TYPE_UNKNOWN end
breakCheck[_DAMAGED] = damageOrAfter
breakCheck[_AFTER] = damageOrAfter
local function defaultCheck() end
---Common function to run any major event in the system.
---@param head damageEventRegistry
---@return boolean ran_yn
local function runEvent(head)
local check = breakCheck[head] or defaultCheck
if dreaming or check() then
return
end
userIndex = head.next
if userIndex ~= head then
Damage.enable(false)
enableT(t3)
dreaming = true
--print("Start of event running")
repeat
if not userIndex.trigFrozen and userIndex.filters[userIndex.eFilter] and checkConfig() and not hasSource or (head ~= _SOURCE or (userIndex.minAOE and sourceAOE > userIndex.minAOE)) then
userIndex.func()
end
userIndex = userIndex.next
until userIndex == head or check()
--print("End of event running")
dreaming = nil
Damage.enable(true)
disableT(t3)
end
return true
end
--[[--------------------------------------------------------------------------------------
Creates a new table for the damage properties for each particular event sequence.
----------------------------------------------------------------------------------------]]
---Create a new damage instance
---@param src unit
---@param tgt unit
---@param amt number
---@param a boolean
---@param r boolean
---@param at attacktype
---@param dt damagetype
---@param wt weapontype
---@param fromCode boolean
---@return damageInstance
local function create(src, tgt, amt, a, r, at, dt, wt, fromCode)
local d = { ---@type damageInstance
source = src,
target = tgt,
damage = amt,
isAttack = a or _USE_GUI and udg_NextDamageIsAttack,
isRanged = r,
attackType = at,
damageType = dt,
weaponType = wt,
prevAmt = amt,
userAmt = amt
}
d.isSpell = at == ATTACK_TYPE_NORMAL and not d.isAttack
if fromCode or Damage.nextType or d.damageType == DAMAGE_TYPE_MIND or (d.damageType == DAMAGE_TYPE_UNKNOWN and d.damage ~= 0.00) or (_USE_GUI and (udg_NextDamageIsAttack or udg_NextDamageIsRanged or udg_NextDamageIsMelee or udg_NextDamageWeaponT)) then
d.isCode = true
d.userType = Damage.nextType or _TYPE_CODE
Damage.nextType = nil
if _USE_MELEE_RANGE and not d.isSpell then
d.isMelee = _USE_GUI and udg_NextDamageIsMelee or (a and not r)
d.isRanged = _USE_GUI and udg_NextDamageIsRanged or (a and r)
end
d.eFilter = _FILTER_CODE
if _USE_GUI then
udg_NextDamageIsAttack = nil
if udg_NextDamageWeaponT then
d.weaponType = ConvertWeaponType(udg_NextDamageWeaponT)
udg_NextDamageWeaponT = nil
end
if _USE_MELEE_RANGE then
udg_NextDamageIsMelee = nil
udg_NextDamageIsRanged = nil
end
end
else
d.userType = 0
end
return d
end
local GetDamage = GetEventDamage
local createFromEvent
do
local GetSource = GetEventDamageSource
local GetTarget = GetTriggerUnit
local GetIsAttack = BlzGetEventIsAttack
local GetAttackType = BlzGetEventAttackType
local GetDamageType = BlzGetEventDamageType
local GetWeaponType = BlzGetEventWeaponType
---Create a damage event from a naturally-occuring event.
---@param isCode? boolean
---@return damageInstance
function createFromEvent(isCode)
local d = create(GetSource(), GetTarget(), GetDamage(), GetIsAttack(), false, GetAttackType(), GetDamageType(), GetWeaponType(), isCode)
if not d.isCode then
if d.damageType == DAMAGE_TYPE_NORMAL and d.isAttack then
if _USE_MELEE_RANGE then
d.isMelee = CheckUnitType(d.source, UNIT_TYPE_MELEE_ATTACKER)
d.isRanged = CheckUnitType(d.source, UNIT_TYPE_RANGED_ATTACKER)
if d.isMelee and d.isRanged then
d.isMelee = d.weaponType -- Melee units play a sound when damaging. In naturally-occuring cases where a
d.isRanged = not d.isMelee -- unit is both ranged and melee, the ranged attack plays no sound.
end
if d.isMelee then
d.eFilter = _FILTER_MELEE
elseif d.isRanged then
d.eFilter = _FILTER_RANGED
else
d.eFilter = _FILTER_ATTACK
end
else
d.eFilter = _FILTER_ATTACK
end
else
if d.isSpell then
d.eFilter = _FILTER_SPELL
else
d.eFilter = _FILTER_OTHER
end
end
end
return d
end
end
local alarmSet
Damage.targets = udg_DamageEventAOEGroup
local function onAOEEnd()
if _USE_EXTRA then
runEvent(_SOURCE)
sourceAOE = 1
sourceStacks = 1
originalTarget = nil
originalSource = nil
GroupClear(Damage.targets)
end
end
---Handle any desired armor modification.
---@param reset? boolean
local function setArmor(reset)
if _USE_ARMOR_MOD then
local pierce ---@type real
local at ---@type integer
local dt ---@type integer
if reset then
pierce = current.armorPierced
at = current.prevArmorT
dt = current.prevDefenseT
else
pierce = -current.armorPierced
at = current.armorType
dt = current.defenseType
end
if pierce ~= 0.00 then --Changed condition thanks to bug reported by BLOKKADE
BlzSetUnitArmor(current.target, BlzGetUnitArmor(current.target) + pierce)
end
if current.prevArmorT ~= current.armorType then
BlzSetUnitIntegerField(current.target, UNIT_IF_ARMOR_TYPE, at)
end
if current.prevDefenseT ~= current.defenseType then
BlzSetUnitIntegerField(current.target, UNIT_IF_DEFENSE_TYPE, dt)
end
end
end
local proclusGlobal = {} ---@type boolean[]
local fischerMorrow = {} ---@type boolean[]
local SetEventDamage = BlzSetEventDamage
local doPreEvents
do
local SetEventAttackType = BlzSetEventAttackType
local SetEventDamageType = BlzSetEventDamageType
local SetEventWeaponType = BlzSetEventWeaponType
---Setup pre-events before running any user-facing damage events.
---@param d damageInstance
---@param natural? boolean
---@return boolean isZeroDamage_yn
doPreEvents = function(d, natural)
if _USE_ARMOR_MOD then
d.armorType = BlzGetUnitIntegerField(d.target, UNIT_IF_ARMOR_TYPE)
d.defenseType = BlzGetUnitIntegerField(d.target, UNIT_IF_DEFENSE_TYPE)
d.prevArmorT = d.armorType
d.prevDefenseT = d.defenseType
d.armorPierced = 0.00
end
current = d
proclusGlobal[d.source] = true
fischerMorrow[d.target] = true
if d.damage == 0.00 then
return true
end
override = d.damageType == DAMAGE_TYPE_UNKNOWN
runEvent(_DAMAGING)
if natural then
SetEventAttackType(d.attackType)
SetEventDamageType(d.damageType)
SetEventWeaponType(d.weaponType)
SetEventDamage(d.damage)
end
setArmor()
end
end
local function afterDamage()
if current then
runEvent(_AFTER)
current = nil
end
override = nil
end
local canKick = true
local sleepLevel = 0
local totem, kicking, eventsRun
local prepped = nil ---@type damageInstance
local recursiveStack = {} ---@type damageInstance[]
local UDT = UnitDamageTarget
local function finish()
if eventsRun then
eventsRun = nil
afterDamage()
end
current = nil
override = nil
if canKick and not kicking then
if #recursiveStack > 0 then
kicking = true
local i = 1
local exit
repeat
sleepLevel = sleepLevel + 1
exit = #recursiveStack
repeat
prepped = recursiveStack[i]
if Alive(prepped.target) then
doPreEvents(prepped) --don't evaluate the pre-event
if prepped.damage > 0.00 then
disableT(t1) --Force only the after armor event to run.
enableT(t2) --in case the user forgot to re-enable this
totem = true
UDT(prepped.source, prepped.target, prepped.damage, prepped.isAttack, prepped.isRanged, prepped.attackType, prepped.damageType, prepped.weaponType)
else
runEvent(_DAMAGED)
if prepped.damage < 0.00 then
--No need for BlzSetEventDamage here
SetUnitLife(prepped.target, GetUnitLife(prepped.target) - prepped.damage)
end
setArmor(true)
end
afterDamage()
end
i = i + 1
until (i >= exit)
until (i >= #recursiveStack)
end
for i = 1, #recursiveStack do
recursiveStack[i].recursiveFunc.trigFrozen = nil
recursiveStack[i].recursiveFunc.levelsDeep = 0
recursiveStack[i] = nil
end
sleepLevel = 0
prepped, kicking, dreaming = nil, nil, nil
Damage.enable(true)
proclusGlobal = {} ---@type boolean[]
fischerMorrow = {} ---@type boolean[]
--print("Cleared up the groups")
end
end
local function failsafeClear()
setArmor(true)
canKick = true
kicking, totem = nil, nil
runEvent(_DAMAGED)
eventsRun = true
finish()
end
local lastInstance ---@type damageInstance
local attacksImmune = {} ---@type boolean[]
local damagesImmune = {} ---@type boolean[]
t1 = CreateTrigger()
TriggerRegisterAnyUnitEventBJ(t1, EVENT_PLAYER_UNIT_DAMAGING)
TriggerAddCondition(t1, Filter(function()
local d = createFromEvent()
--print("Pre-damage event running for " .. GetUnitName(GetTriggerUnit()))
if alarmSet then
if totem then --WarCraft 3 didn't run the DAMAGED event despite running the DAMAGING event.
if d.damageType == DAMAGE_TYPE_SPIRIT_LINK or d.damageType == DAMAGE_TYPE_DEFENSIVE or d.damageType == DAMAGE_TYPE_PLANT then
lastInstance = current
totem = nil
canKick = nil
else
failsafeClear() --Not an overlapping event - just wrap it up
end
else
finish() --wrap up any previous damage index
end
if _USE_EXTRA then
if d.source ~= originalSource then
onAOEEnd()
originalSource = d.source
originalTarget = d.target
elseif d.target == originalTarget then
sourceStacks = sourceStacks + 1
elseif not IsUnitInGroup(d.target, Damage.targets) then
sourceAOE = sourceAOE + 1
end
end
else
alarmSet = true
Timed.call(
function()
alarmSet, dreaming = nil, nil
Damage.enable(true)
if totem then
failsafeClear() --WarCraft 3 didn't run the DAMAGED event despite running the DAMAGING event.
else
canKick = true
kicking = nil
finish()
end
onAOEEnd()
current = nil
--print("Timer wrapped up")
end)
if _USE_EXTRA then
originalSource = d.source
originalTarget = d.target
end
end
if _USE_EXTRA then GroupAddUnit(Damage.targets, d.target) end
if doPreEvents(d, true) then
runEvent(_ZERO)
canKick = true
finish()
end
totem = not lastInstance or attacksImmune[d.attackType] or damagesImmune[d.damageType] or not CheckUnitType(d.target, UNIT_TYPE_MAGIC_IMMUNE)
end))
t2 = CreateTrigger()
TriggerRegisterAnyUnitEventBJ(t2, EVENT_PLAYER_UNIT_DAMAGED)
TriggerAddCondition(t2, Filter(function()
local r = GetDamage()
local d = current
--print("Second damage event running for " .. GetUnitName(GetTriggerUnit()))
if prepped then prepped = nil
elseif dreaming or d.prevAmt == 0.00 then return
elseif totem then totem = nil
else
afterDamage()
d = lastInstance
current = d
lastInstance = nil
canKick = true
end
setArmor(true)
d.userAmt = d.damage
d.damage = r
if r > 0.00 then
runEvent(_ARMOR)
if hasLethal or d.userType < 0 then
Damage.life = GetUnitLife(d.target) - d.damage
if Damage.life <= _DEATH_VAL then
if hasLethal then
runEvent(_LETHAL)
d.damage = GetUnitLife(d.target) - Damage.life
end
if d.userType < 0 and Damage.life <= _DEATH_VAL then
SetUnitExploded(d.target, true)
end
end
end
end
if d.damageType ~= DAMAGE_TYPE_UNKNOWN then runEvent(_DAMAGED) end
SetEventDamage(d.damage)
eventsRun = true
if d.damage == 0.00 then finish() end
end))
--Call to enable recursive damage on your trigger.
function Damage.inception() userIndex.inceptionTrig = true end
---add a recursive damage instance
---@param d damageInstance
local function addRecursive(d)
if d.damage ~= 0.00 then
d.recursiveFunc = userIndex
if kicking and proclusGlobal[d.source] and fischerMorrow[d.target] then
if not userIndex.inceptionTrig then
userIndex.trigFrozen = true
elseif not userIndex.trigFrozen and userIndex.levelsDeep < sleepLevel then
userIndex.levelsDeep = userIndex.levelsDeep + 1
userIndex.trigFrozen = userIndex.levelsDeep >= _LIMBO
end
end
recursiveStack[#recursiveStack + 1] = d
--print("recursiveStack: " .. #recursiveStack .. " levelsDeep: " .. userIndex.levelsDeep .. " sleepLevel: " .. sleepLevel)
end
end
t3 = CreateTrigger()
TriggerRegisterAnyUnitEventBJ(t3, EVENT_PLAYER_UNIT_DAMAGING)
TriggerAddCondition(t3, Filter(function()
addRecursive(createFromEvent(true))
SetEventDamage(0.00)
end))
disableT(t3)
---register a new damage event
---@param head damageEvent
---@param func function
---@param lbs number
---@param filt? integer
---@param trig? trigger
---@return damageEventRegistry
function Damage.register(head, func, lbs, filt, trig)
filt = filt or _FILTER_OTHER
if trig and lastRegistered and lastRegistered.trig and lastRegistered.trig == trig then
lastRegistered.filters[filt]= true
return
end
hasLethal = hasLethal or head == _LETHAL
hasSource = hasSource or head == _SOURCE
local id = {} ---@type damageEventRegistry
lastRegistered = id
id.filters = {}
if filt == _FILTER_OTHER then
id.filters[_FILTER_ATTACK] = true
id.filters[_FILTER_MELEE] = true
id.filters[_FILTER_OTHER] = true
id.filters[_FILTER_RANGED] = true
id.filters[_FILTER_SPELL] = true
id.filters[_FILTER_CODE] = true
elseif filt == _FILTER_ATTACK then
id.filters[_FILTER_ATTACK] = true
id.filters[_FILTER_MELEE] = true
id.filters[_FILTER_RANGED] = true
else
id.filters[filt] = true
end
id.levelsDeep = 0
id.trig = trig
lbs = lbs or 1.00
id.weight = lbs
id.func = func
local insertAt = head
for node in head:loop() do if node.weight > lbs then insertAt = node; break end end
insertAt:insert(id)
--print("Registered new event to " .. var)
return lastRegistered
end
---Remove registered damage event by index
---@param index damageEventRegistry
---@return boolean removed_yn
function Damage.remove(index)
if lastRegistered == index then lastRegistered = nil end
return index:remove()
end
Hook.addSimple("TriggerRegisterVariableEvent",
function(whichTrig, varName, opCode, limitVal)
local index = ((varName == "udg_DamageModifierEvent" and limitVal < 4) or varName == "udg_PreDamageEvent") and _DAMAGING or
(varName == "udg_DamageModifierEvent" or varName == "udg_ArmorDamageEvent") and _ARMOR or
((varName == "udg_DamageEvent" and limitVal == 2 or limitVal == 0) or varName == "udg_ZeroDamageEvent") and _ZERO or
(varName == "udg_DamageEvent" or varName == "udg_OnDamageEvent") and _DAMAGED or
varName == "udg_AfterDamageEvent" and _AFTER or
varName == "udg_LethalDamageEvent" and _LETHAL or
(varName == "udg_AOEDamageEvent" or varName == "udg_SourceDamageEvent") and _SOURCE
if index then
local id = Damage.register(index, function() if IsTriggerEnabled(whichTrig) then ConditionalTriggerExecute(whichTrig) end end, limitVal, GetHandleId(opCode), whichTrig)
if index == _SOURCE then
id.minAOE = (varName == "udg_AOEDamageEvent" and 1) or (varName == "udg_SourceDamageEvent" and 0)
end
return "skip hook"
end
end)
for i = 0, 26 do udg_CONVERTED_DAMAGE_TYPE[i] = ConvertDamageType(i) end
--For filling an array with values from a table.
---@param arr table
---@param tbl table
---@param offset? integer
local function fillArray(arr, tbl, offset)
for i, v in ipairs(tbl) do arr[i + (offset or -1)] = v end
end
--For filling a group of similarly-named variables.
---@param prefix string
---@param tbl table
---@param offset? integer
local function fillVars(prefix, tbl, offset)
for i, v in ipairs(tbl) do _G[prefix .. v] = i + (offset or -1) end
end
local list
if _USE_GUI then
udg_DamageTypeDebugStr[0] = "UNKNOWN"
udg_DamageTypeDebugStr[4] = "NORMAL"
udg_DamageTypeDebugStr[5] = "ENHANCED"
udg_DAMAGE_TYPE_UNKNOWN = 0
udg_DAMAGE_TYPE_NORMAL = 4
udg_DAMAGE_TYPE_ENHANCED = 5
end
damagesImmune[0] = true
damagesImmune[4] = true
damagesImmune[5] = true
fillArray(damagesImmune, {false, false, false, true, true, false, false, false, true, false, false, false, false, false, true, true, false, false, true}, 7)
if _USE_GUI then
list = {"FIRE", "COLD", "LIGHTNING", "POISON", "DISEASE", "DIVINE", "MAGIC", "SONIC", "ACID", "FORCE", "DEATH", "MIND", "PLANT", "DEFENSIVE", "DEMOLITION", "SLOW_POISON", "SPIRIT_LINK", "SHADOW_STRIKE", "UNIVERSAL"}
fillArray(udg_DamageTypeDebugStr, list, 7)
fillVars("udg_DAMAGE_TYPE_", list, 7)
end
fillArray(attacksImmune, { false, true, true, true, false, true, true})
if _USE_GUI then
list = {"SPELLS", "NORMAL", "PIERCE", "SIEGE", "MAGIC", "CHAOS", "HERO"}
fillArray(udg_AttackTypeDebugStr, list)
fillVars("udg_ATTACK_TYPE_", list)
fillArray(udg_WeaponTypeDebugStr, {"NONE", "METAL_LIGHT_CHOP", "METAL_MEDIUM_CHOP", "METAL_HEAVY_CHOP", "METAL_LIGHT_SLICE", "METAL_MEDIUM_SLICE", "METAL_HEAVY_SLICE", "METAL_MEDIUM_BASH", "METAL_HEAVY_BASH", "METAL_MEDIUM_STAB", "METAL_HEAVY_STAB", "WOOD_LIGHT_SLICE", "WOOD_MEDIUM_SLICE", "WOOD_HEAVY_SLICE", "WOOD_LIGHT_BASH", "WOOD_MEDIUM_BASH", "WOOD_HEAVY_BASH", "WOOD_LIGHT_STAB", "WOOD_MEDIUM_STAB", "CLAW_LIGHT_SLICE", "CLAW_MEDIUM_SLICE", "CLAW_HEAVY_SLICE", "AXE_MEDIUM_CHOP", "ROCK_HEAVY_BASH"})
fillVars("udg_WEAPON_TYPE_", {"NONE", "ML_CHOP", "MM_CHOP", "MH_CHOP", "ML_SLICE", "MM_SLICE", "MH_SLICE", "MM_BASH", "MH_BASH", "MM_STAB", "MH_STAB", "WL_SLICE", "WM_SLICE", "WH_SLICE", "WL_BASH", "WM_BASH", "WH_BASH", "WL_STAB", "WM_STAB", "CL_SLICE", "CM_SLICE", "CH_SLICE", "AM_CHOP", "RH_BASH"})
list = {"LIGHT", "MEDIUM", "HEAVY", "FORTIFIED", "NORMAL", "HERO", "DIVINE", "UNARMORED"}
fillArray(udg_DefenseTypeDebugStr, list)
fillVars("udg_DEFENSE_TYPE_", list)
list = {"NONE", "FLESH", "METAL", "WOOD", "ETHEREAL", "STONE"}
fillArray(udg_ArmorTypeDebugStr, list)
fillVars("udg_ARMOR_TYPE_", list)
fillVars("udg_UNIT_CLASS_", {"HERO", "DEAD", "STRUCTURE", "FLYING", "GROUND", "ATTACKS_FLYING", "ATTACKS_GROUND", "MELEE", "RANGED", "GIANT", "SUMMONED", "STUNNED", "PLAGUED", "SNARED", "UNDEAD", "MECHANICAL", "PEON", "SAPPER", "TOWNHALL", "ANCIENT", "TAUREN", "POISONED", "POLYMORPHED", "SLEEPING", "RESISTANT", "ETHEREAL", "MAGIC_IMMUNE"})
for i = 0, 6 do udg_CONVERTED_ATTACK_TYPE[i] = ConvertAttackType(i) end
end
---Apply damage directly via Damage Engine
---@param src unit
---@param tgt unit
---@param amt real
---@param a boolean
---@param r boolean
---@param at attacktype
---@param dt damagetype
---@param wt weapontype
---@return damageInstance
function Damage.apply(src, tgt, amt, a, r, at, dt, wt)
local d ---@type damageInstance
if dreaming then
d = create(src, tgt, amt, a, r, at, dt, wt, true)
addRecursive(d)
else
UDT(src, tgt, amt, a, r, at, dt, wt)
d = current
finish()
end
return d
end
---Deal spell damage using the below simple criteria
---@param src unit
---@param tgt unit
---@param amt real
---@param dt damagetype
---@return damageInstance
function Damage.applySpell(src, tgt, amt, dt)
return Damage.apply(src, tgt, amt, nil, nil, nil, dt, nil)
end
function Damage.applyAttack(src, tgt, amt, ranged, at, wt)
return Damage.apply(src, tgt, amt, true, ranged, at, DAMAGE_TYPE_NORMAL, wt)
end
--[[--------------------------------------------------------------------------------------
The below section defines how GUI interacts with Damage Engine and vice-versa. This is
a breakthrough in coding thanks to the innovation brought forth via Global Variable Remapper.
----------------------------------------------------------------------------------------]]
if _USE_GUI then
---Remap damageInstance types of variables (DamageEventSource/Target/Amount/etc)
---@param oldVarStr string
---@param newVarStr string
---@param get? boolean
---@param set? boolean
local function map(oldVarStr, newVarStr, get, set)
GlobalRemap(oldVarStr, get and function() return current[newVarStr] end, set and function(val) current[newVarStr] = val end)
end
map("udg_DamageEventAmount", "damage", true, true)
map("udg_DamageEventType", "userType", true, true)
if _USE_ARMOR_MOD then
map("udg_DamageEventArmorPierced", "armorPierced", true, true)
map("udg_DamageEventArmorT", "armorType", true, true)
map("udg_DamageEventDefenseT", "defenseType", true, true)
end
map("udg_DamageEventSource", "source", true)
map("udg_DamageEventTarget", "target", true)
map("udg_DamageEventPrevAmt", "prevAmt", true)
map("udg_DamageEventUserAmt", "userAmt", true)
map("udg_IsDamageAttack", "isAttack", true)
map("udg_IsDamageCode", "isCode", true)
map("udg_IsDamageSpell", "isSpell", true)
if _USE_MELEE_RANGE then
map("udg_IsDamageMelee", "isMelee", true)
map("udg_IsDamageRanged", "isRanged", true)
end
GlobalRemap("udg_DamageEventAOE", function() return sourceAOE end)
GlobalRemap("udg_DamageEventLevel", function() return sourceStacks end)
GlobalRemap("udg_AOEDamageSource", function() return originalSource end)
GlobalRemap("udg_EnhancedDamageTarget", function() return originalTarget end)
GlobalRemap("udg_LethalDamageHP", function() return Damage.life end, function(var) Damage.life = var end)
GlobalRemap("udg_DamageEventAttackT", function() return GetHandleId(current.attackType) end, function(var) current.attackType = ConvertAttackType(var) end)
GlobalRemap("udg_DamageEventDamageT", function() return GetHandleId(current.damageType) end, function(var) current.damageType = ConvertDamageType(var) end)
GlobalRemap("udg_DamageEventWeaponT", function() return GetHandleId(current.weaponType) end, function(var) current.weaponType = ConvertWeaponType(var) end)
--New GUI vars unique to version 2.0: boolean DamageEngineEnabled, boolean DamageFilterConfigured, real DamageEventUserAmt
GlobalRemap("udg_DamageEngineEnabled", nil, function(val) Damage.enable(val) end)
GlobalRemap("udg_NextDamageType", nil, function(val) Damage.nextType = val end)
GlobalRemap("udg_RemoveDamageEvent", nil, function() Damage.remove(userIndex) end)
GlobalRemap("udg_DamageFilterSourceC", nil, function(val) current.sourceClass = ConvertUnitType(val) end)
GlobalRemap("udg_DamageFilterTargetC", nil, function(val) current.targetClass = ConvertUnitType(val) end)
---Remap damageEventRegistry type variables (DamageFilterSource/Target/MinAmount/etc)
---@param oldVarStr string
---@param newVarStr string
local function configVar(oldVarStr, newVarStr)
GlobalRemap(oldVarStr, nil,
function(val)
userIndex[newVarStr] = val
end)
end
configVar("udg_DamageFilterSource", "source")
configVar("udg_DamageFilterTarget", "target")
configVar("udg_DamageFilterSourceT", "sourceType")
configVar("udg_DamageFilterTargetT", "targetType")
configVar("udg_DamageFilterType", "userType")
configVar("udg_DamageFilterAttackT", "attackType")
configVar("udg_DamageFilterDamageT", "damageType")
configVar("udg_DamageFilterSourceI", "sourceItem")
configVar("udg_DamageFilterTargetI", "targetItem")
configVar("udg_DamageFilterMinAmount", "damageMin")
configVar("udg_DamageFilterSourceA", "sourceBuff")
configVar("udg_DamageFilterSourceB", "sourceBuff")
configVar("udg_DamageFilterTargetA", "targetBuff")
configVar("udg_DamageFilterTargetB", "targetBuff")
configVar("udg_DamageFilterFailChance", "failChance")
GlobalRemap("udg_DamageFilterRunChance", nil,
function(val)
userIndex.failChance = 1.00 - val
end)
GlobalRemap("udg_DamageFilterConfigured",
function()
local c = userIndex.configured
if not c then
userIndex.configured = 0
return false
elseif c == 0 then
userIndex.configured = 1
return checkConfig()
end
return true
end)
--[[--------------------------------------------------------------------------------------
Set references to readonly variables for public use.
----------------------------------------------------------------------------------------]]
setmetatable(Damage, {
__index =
function(tbl, key)
local index = readonly[key]
if index then return index() end
return rawget(tbl, key)
end,
__newindex =
function(tbl, key, val)
if readonly[key] then return end
rawset(tbl, key, val)
end
})
end
end)
end