repo_id stringlengths 4 98 | size int64 611 5.02M | file_path stringlengths 1 276 | content stringlengths 611 5.02M | shard_id int64 0 109 | quality_score float32 0.5 1 | quality_prediction int8 1 1 | quality_confidence float32 0.5 1 | topic_primary stringclasses 1 value | topic_group stringclasses 1 value | topic_score float32 0.05 1 | topic_all stringclasses 96 values | quality2_score float32 0.5 1 | quality2_prediction int8 1 1 | quality2_confidence float32 0.5 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
VirtueSky/sunflower_2 | 5,083 | Module/Localization/Runtime/Locale.cs | using System;
using System.Linq;
using UnityEngine;
using VirtueSky.DataStorage;
namespace VirtueSky.Localization
{
public sealed class Locale
{
private static Locale instance;
private Language _currentLanguage = Language.English;
/// <summary>
/// Raised when <see cref="CurrentLanguage"/> has been changed.
/// </summary>
private event EventHandler<LocaleChangedEventArgs> OnLocaleChangedEvent;
private static Locale Instance
{
get
{
#if UNITY_EDITOR
if (!Application.isPlaying)
{
Debug.LogError("Locale only avaiable when application playing!");
return null;
}
#endif
if (instance == null)
{
instance = new Locale();
instance.SetDefaultLanguage();
}
return instance;
}
}
public static Language CurrentLanguage
{
get => Instance._currentLanguage;
set
{
if (Instance._currentLanguage != value)
{
Instance._currentLanguage = value;
SetCurrentLanguageCode(value);
var oldValue = Instance._currentLanguage;
Instance._currentLanguage = value;
Instance.OnLanguageChanged(new LocaleChangedEventArgs(oldValue, value));
}
}
}
public static EventHandler<LocaleChangedEventArgs> LocaleChangedEvent
{
get => Instance.OnLocaleChangedEvent;
set => Instance.OnLocaleChangedEvent = value;
}
private void OnLanguageChanged(LocaleChangedEventArgs e)
{
OnLocaleChangedEvent?.Invoke(this, e);
}
/// <summary>
/// Sets the <see cref="CurrentLanguage"/> as <see cref="Application.systemLanguage"/>.
/// </summary>
public void SetSystemLanguage()
{
CurrentLanguage = Application.systemLanguage;
}
/// <summary>
/// Sets the <see cref="CurrentLanguage"/> to default language defined in <see cref="LocaleSettings"/>.
/// </summary>
public void SetDefaultLanguage()
{
CurrentLanguage = LocaleSettings.AvailableLanguages.FirstOrDefault();
}
/// <summary>
/// Finds all localized assets with type given. Finds all assets in the project if in Editor; otherwise,
/// finds only that loaded in memory.
/// </summary>
/// <returns>Array of specified localized assets.</returns>
public static T[] FindAllLocalizedAssets<T>() where T : ScriptableLocaleBase
{
#if UNITY_EDITOR
string[] guids = UnityEditor.AssetDatabase.FindAssets($"t:{typeof(T)}");
var assets = new T[guids.Length];
for (var i = 0; i < guids.Length; ++i)
{
string assetPath = UnityEditor.AssetDatabase.GUIDToAssetPath(guids[i]);
assets[i] = UnityEditor.AssetDatabase.LoadAssetAtPath<T>(assetPath);
Debug.Assert(assets[i]);
}
return assets;
#else
return Resources.FindObjectsOfTypeAll<T>();
#endif
}
/// <summary>
/// Finds all localized assets.
/// </summary>
/// <seealso cref="FindAllLocalizedAssets{T}"/>
/// <returns>Array of localized assets.</returns>
public static ScriptableLocaleBase[] FindAllLocalizedAssets()
{
return FindAllLocalizedAssets<ScriptableLocaleBase>();
}
const string KEY_LANGUAGE = "KEY_LANGUAGE";
public static string GetCurrentLanguageCode() => GameData.Get(KEY_LANGUAGE, "");
public static void SetCurrentLanguageCode(Language language) => GameData.Set(KEY_LANGUAGE, language.Code);
public static void SetCurrentLanguageCode(string languageCode) => GameData.Set(KEY_LANGUAGE, languageCode);
public static void LoadLanguageSetting()
{
var list = LocaleSettings.AvailableLanguages;
string lang = GetCurrentLanguageCode();
// for first time when user not choose lang to display
// use system language, if you don't use detect system language use first language in list available laguages
if (string.IsNullOrEmpty(lang))
{
var index = 0;
if (LocaleSettings.DetectDeviceLanguage)
{
var nameSystemLang = UnityEngine.Application.systemLanguage.ToString();
index = list.FindIndex(x => x.Name == nameSystemLang);
if (index < 0) index = 0;
}
lang = list[index].Code;
SetCurrentLanguageCode(lang);
}
int i = list.FindIndex(x => x.Code == lang);
Locale.CurrentLanguage = list[i];
}
}
} | 412 | 0.895339 | 1 | 0.895339 | game-dev | MEDIA | 0.926388 | game-dev | 0.898745 | 1 | 0.898745 |
RobertSkalko/Age-of-Exile | 1,559 | src/main/java/com/robertx22/age_of_exile/player_skills/items/TieredItem.java | package com.robertx22.age_of_exile.player_skills.items;
import com.robertx22.age_of_exile.aoe_data.datapacks.models.IAutoModel;
import com.robertx22.age_of_exile.aoe_data.datapacks.models.ItemModelManager;
import com.robertx22.age_of_exile.database.base.CreativeTabs;
import com.robertx22.age_of_exile.player_skills.items.foods.SkillItemTier;
import com.robertx22.age_of_exile.uncommon.interfaces.IAutoLocName;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.registry.Registry;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TranslationTextComponent;
public abstract class TieredItem extends Item implements IAutoLocName, IAutoModel {
public SkillItemTier tier;
public TieredItem(SkillItemTier tier) {
super(new Item.Properties().tab(CreativeTabs.Professions));
this.tier = tier;
}
public TieredItem(SkillItemTier tier, Item.Properties settings) {
super(settings.tab(CreativeTabs.Professions));
this.tier = tier;
}
@Override
public ITextComponent getName(ItemStack stack) {
return new TranslationTextComponent(this.getDescriptionId()).withStyle(tier.format);
}
@Override
public void generateModel(ItemModelManager manager) {
manager.generated(this);
}
@Override
public AutoLocGroup locNameGroup() {
return AutoLocGroup.Misc;
}
@Override
public String locNameLangFileGUID() {
return Registry.ITEM.getKey(this)
.toString();
}
}
| 412 | 0.718826 | 1 | 0.718826 | game-dev | MEDIA | 0.986929 | game-dev | 0.745658 | 1 | 0.745658 |
gflze/CSGO-ZE-Configs | 5,705 | vscripts/cosmov6/item/yuffie_shuriken_temp.nut | ::Maker_Shuriken <- Entities.CreateByClassname("env_entity_maker")
Maker_Shuriken.__KeyValueFromString("EntityTemplate", self.GetName());
::Shuriken_Logic <- self;
::TEMP_Shuriken_Owner <- null;
::TEMP_Shuriken_Dir <- Vector();
::TEMP_Shuriken_Materia <- -1;
::TEMP_Shuriken_HitBox <- -1;
::CreateShuriken <- function(hOwner, hHitBox, vecDir = Vector(0, -1, 0), iMateriaStatus = -1)
{
TEMP_Shuriken_Owner = hOwner;
TEMP_Shuriken_Dir = vecDir;
TEMP_Shuriken_Materia = iMateriaStatus;
TEMP_Shuriken_HitBox = hHitBox;
Maker_Shuriken.SetOrigin(hOwner.EyePosition())
Maker_Shuriken.SpawnEntity();
}
function PreSpawnInstance( entityClass, entityName )
{
if (entityClass == "prop_dynamic_glow")
{
if (TEMP_Shuriken_Materia > -1)
{
return {glowcolor = DATA_SHURIKEN[TEMP_Shuriken_Materia].color};
}
}
else if (entityClass == "info_particle_system")
{
if (TEMP_Shuriken_Materia > -1)
{
return {effect_name = DATA_SHURIKEN[TEMP_Shuriken_Materia].particle};
}
}
else if (entityClass == "light_dynamic")
{
if (TEMP_Shuriken_Materia > -1)
{
return {_light = DATA_SHURIKEN[TEMP_Shuriken_Materia].color + " 100"};
}
}
return {};
}
function PostSpawn(entities)
{
foreach (entity in entities)
{
if (entity.GetClassname() == "prop_dynamic_glow")
{
if (TEMP_Shuriken_Materia > -1)
{
EntFireByHandle(entity, "SetGlowEnabled", "", 0, null, null);
}
entity.GetScriptScope().Init(TEMP_Shuriken_Owner, TEMP_Shuriken_HitBox, TEMP_Shuriken_Dir, TEMP_Shuriken_Materia);
}
else if (entity.GetClassname() == "info_particle_system")
{
if (TEMP_Shuriken_Materia > -1)
{
EntFireByHandle(entity, "Start", "", 0, null, null);
}
else
{
EntFireByHandle(entity, "Kill", "", 0, null, null);
}
}
else if (entity.GetClassname() == "light_dynamic")
{
if (TEMP_Shuriken_Materia < 0)
{
EntFireByHandle(entity, "Kill", "", 0, null, null);
}
}
}
TEMP_Shuriken_Owner = null;
TEMP_Shuriken_Dir = Vector();
TEMP_Shuriken_Materia = -1;
TEMP_Shuriken_HitBox = null;
}
::SetShuriken_Effect <- function(aDATA)
{
// printl("DATA: " + aDATA.activator+ " : " +aDATA.materia+ " : " +aDATA.owner+ " : " +aDATA.shuriken);
if (aDATA.materia == 0) //GRAVITY
{
local dir = aDATA.gravity+ Vector(0, 0, 50) - aDATA.activator.GetCenter();
dir.Norm();
aDATA.activator.SetVelocity(Vector(dir.x * 500, dir.y * 500, dir.z * 350));
}
if (aDATA.materia == 1) //Fire
{
EntFireByHandle(MainScript, "RunScriptCode", "DamagePlayer(200,::item)", 0, aDATA.activator, aDATA.activator);
EntFireByHandle(MainScript, "RunScriptCode", "SlowPlayer(0.2,0.1)", 0, aDATA.activator, aDATA.activator);
EntFireByHandle(aDATA.activator,"IgniteLifeTime", "1.0" ,0, null, null);
}
if (aDATA.materia ==2) //WIND
{
local dir = aDATA.activator.GetCenter() - aDATA.owner.GetCenter();
dir.Norm();
aDATA.activator.SetVelocity(Vector(dir.x * 250, dir.y * 250, dir.z * 300));
}
if (aDATA.materia == 3) //poison
{
EntFireByHandle(MainScript, "RunScriptCode", "DamagePlayer(150,::item)", 0, aDATA.activator, aDATA.activator);
EntFireByHandle(MainScript, "RunScriptCode", "SlowPlayer(0.3,0.25)", 0, aDATA.activator, aDATA.activator);
}
if (aDATA.materia == 4) //Ice
{
EntFireByHandle(MainScript, "RunScriptCode", "SlowPlayer(1,1.5)", 0, aDATA.activator, aDATA.activator);
}
if (aDATA.materia == 5) //electro
{
aDATA.activator.SetVelocity(Vector());
EntFireByHandle(MainScript, "RunScriptCode", "DamagePlayer(150,::item)", 0, aDATA.activator, aDATA.activator);
EntFireByHandle(MainScript, "RunScriptCode", "SlowPlayer(0.15,0.25)", 0, aDATA.activator, aDATA.activator);
}
}
::GetItemNameIndexByOwner <- function(owner)
{
local array = MainScript.GetScriptScope().ITEM_OWNER;
foreach (item in array)
{
if (item.owner != owner)
{
continue;
}
if (item.name_right == "gravity")
{
return 0;
}
if (item.name_right == "fire")
{
return 1;
}
if (item.name_right == "wind")
{
return 2;
}
if (item.name_right == "poison")
{
return 3;
}
if (item.name_right == "ice")
{
return 4;
}
if (item.name_right == "electro")
{
return 5;
}
}
return -1;
}
::DATA_SHURIKEN <- [
{
particle = "custom_particle_017",
color = "160 66 255",
}, //Gravity
{
particle = "custom_particle_014",
color = "231 102 24",
}, //fire
{
particle = "custom_particle_001",
color = "72 249 130",
}, //wind
{
particle = "custom_particle_032",
color = "221 251 76",
}, //poison
{
particle = "custom_particle_029",
color = "128 255 255",
}, //ice
{
particle = "custom_particle_011",
color = "7 50 248",
}, //electro
];
function Test()
{
local h;
local count = 0;
local temp = Vector();
while ((h = Entities.FindByClassnameWithin(h, "cs_bot", activator.GetOrigin(), 1024)) != null)
{
DrawAxis(h.GetOrigin(), 16, true, 16);
temp += h.GetOrigin();
count++
}
DrawAxisX(Vector(temp.x / count, temp.y / count, temp.z / count), 64, true, 16);
}
function DrawAxis(pos,s = 16,nocull = true,time = 1)
{
DebugDrawLine(Vector(pos.x-s,pos.y,pos.z), Vector(pos.x+s,pos.y,pos.z), 255, 0, 0, nocull, time);
DebugDrawLine(Vector(pos.x,pos.y-s,pos.z), Vector(pos.x,pos.y+s,pos.z), 0, 255, 0, nocull, time);
DebugDrawLine(Vector(pos.x,pos.y,pos.z-s), Vector(pos.x,pos.y,pos.z+s), 0, 0, 255, nocull, time);
}
function DrawAxisX(pos,s = 16,nocull = true,time = 1)
{
DebugDrawLine(Vector(pos.x-s,pos.y,pos.z), Vector(pos.x+s,pos.y,pos.z), 255, 0, 255, nocull, time);
DebugDrawLine(Vector(pos.x,pos.y-s,pos.z), Vector(pos.x,pos.y+s,pos.z), 255, 0, 255, nocull, time);
DebugDrawLine(Vector(pos.x,pos.y,pos.z-s), Vector(pos.x,pos.y,pos.z+s), 255, 0, 255, nocull, time);
}
| 412 | 0.843159 | 1 | 0.843159 | game-dev | MEDIA | 0.852358 | game-dev | 0.981707 | 1 | 0.981707 |
ColdGrub1384/Pyto | 1,463 | clang_codecompletion/llvm/CodeGen/DIEValue.def | //===- llvm/CodeGen/DIEValue.def - DIEValue types ---------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Macros for running through all types of DIEValue.
//
//===----------------------------------------------------------------------===//
#if !(defined HANDLE_DIEVALUE || defined HANDLE_DIEVALUE_SMALL || \
defined HANDLE_DIEVALUE_LARGE)
#error "Missing macro definition of HANDLE_DIEVALUE"
#endif
// Handler for all values.
#ifndef HANDLE_DIEVALUE
#define HANDLE_DIEVALUE(T)
#endif
// Handler for small values.
#ifndef HANDLE_DIEVALUE_SMALL
#define HANDLE_DIEVALUE_SMALL(T) HANDLE_DIEVALUE(T)
#endif
// Handler for large values.
#ifndef HANDLE_DIEVALUE_LARGE
#define HANDLE_DIEVALUE_LARGE(T) HANDLE_DIEVALUE(T)
#endif
HANDLE_DIEVALUE_SMALL(Integer)
HANDLE_DIEVALUE_SMALL(String)
HANDLE_DIEVALUE_SMALL(Expr)
HANDLE_DIEVALUE_SMALL(Label)
HANDLE_DIEVALUE_LARGE(BaseTypeRef)
HANDLE_DIEVALUE_LARGE(Delta)
HANDLE_DIEVALUE_SMALL(Entry)
HANDLE_DIEVALUE_LARGE(Block)
HANDLE_DIEVALUE_LARGE(Loc)
HANDLE_DIEVALUE_SMALL(LocList)
HANDLE_DIEVALUE_LARGE(InlineString)
HANDLE_DIEVALUE_LARGE(AddrOffset)
#undef HANDLE_DIEVALUE
#undef HANDLE_DIEVALUE_SMALL
#undef HANDLE_DIEVALUE_LARGE
| 412 | 0.832473 | 1 | 0.832473 | game-dev | MEDIA | 0.107135 | game-dev | 0.764484 | 1 | 0.764484 |
Joshua-F/osrs-dumps | 2,933 | script/[proc,dov_census_update].cs2 | // 4870
[proc,dov_census_update](component $component0, component $component1, component $component2, component $component3)
if (%dov_censuspage <= 0) {
if_sethide(true, $component2);
} else {
if_sethide(false, $component2);
}
if (%dov_censuspage >= 5) {
if_sethide(true, $component3);
} else {
if_sethide(false, $component3);
}
def_string $string0 = "";
def_string $string1 = "";
switch_int (%dov_censuspage) {
case 0 :
$string0 = "Gryff Aldock<br>Raminme Altrodor<br>Layte Aubury<br>Ingald Belger<br>Asyff Bymajique<br>Baraek Brigson<br>Brugsen Bursen<br>Jeremy Clerksin<br>Daerig Clod<br>Phillipa DeMarne<br>Trista Donaldson<br>Straven Enroy";
$string1 = "Town Crier<br>Cook<br>Rune Seller<br>Apothecary<br>Clothes Seller<br>Fur Seller<br>Economist<br>Cart Expert<br>Unemployed<br>Minor Noble<br>Banker<br>'Businessman'";
case 1 :
$string0 = "Gertrude Fairweather<br>Shilop Fairweather<br>Walter Fairweather<br>Wilough Fairweather<br>Dimintheis Fitzharmon<br>Eustace Forthwright<br>Romeo Gontamue<br>Everard Grafham<br>Matthew Grey<br>Grimesquit Grime<br>Phingspet Grime<br>Benny Gutenberg";
$string1 = "Housewife<br>Baby<br>Travelling Merchant<br>Baby<br>Former Noble<br>Guard<br>Minor Noble<br>Natural Historian<br>Sailor<br>Profession Withheld<br>Profession Withheld<br>Journalist";
case 2 :
$string0 = "Haig Halen<br>Ritchard Haring<br>Randulf Harlow<br>Tobias Hills<br>Hendry Jamison<br>Louisiana Jones<br>Lawrence Lambare<br>Wimock Landsdown<br>Stuart Lea<br>Draul Leptoc<br>Juliet Leptoc<br>Phearthee Levalsyx";
$string1 = "Museum Curator<br>Dietician<br>Vampyre Hunter<br>Guard<br>Bartender<br>Student<br>Priest<br>Teacher<br>Playwright<br>Lord<br>Noble<br>Mugger";
case 3 :
$string0 = "Charles Lyeman<br>Surok Magis<br>Gaffit Malore<br>Mabel Malore<br>Alfi Marino<br>Aris Maye<br>Iffie Nitter<br>Thessalia Nitter<br>Elsie Parks<br>Fred Parks<br>Ethel Prim<br>Hartwin Prim";
$string1 = "Unemployed<br>Mage<br>Librarian<br>Information Clerk<br>Chef<br>Fortune Teller<br>Retired<br>Clothes Seller<br>Retired<br>Retired<br>Servant<br>Student";
case 4 :
$string0 = "Enhtor Prysin<br>Idonea Ramlock<br>Trevick Ramlock<br>Aeonisig Raispher<br>Katrine Raven<br>Horvik Ravitz<br>Roald Remanis III<br>Milo Rovin<br>Martina Scorsby<br>Stephan Scorsby<br>Sani Semiv<br>Herbert Spiccanspan";
$string1 = "Knight<br>Teacher<br>Banker<br>Royal Advisor<br>Wallet Relocator<br>Apprentice Blacksmith<br>Our Glorious King<br>Captain of the Guard<br>Washerwoman<br>Guard<br>Master Smith<br>Street Cleaner";
case 5 :
$string0 = "Brana Talvoy<br>Launa Talvoy<br>Reldo Trimmly<br>Jack Tylner<br>Romily Weeklax<br>Treznor Withings";
$string1 = "Farmer<br>Farmer<br>Assistant Librarian<br>Rat Exterminator<br>Pie Salesman<br>Kitchen Boy";
}
if_settext($string0, $component0);
if_settext($string1, $component1);
| 412 | 0.867523 | 1 | 0.867523 | game-dev | MEDIA | 0.692844 | game-dev | 0.653311 | 1 | 0.653311 |
KevinDaGame/VoxelSniper-Reimagined | 3,460 | VoxelSniperSpigot/src/main/java/com/github/kevindagame/voxelsniper/entity/player/SpigotPlayer.java | package com.github.kevindagame.voxelsniper.entity.player;
import com.github.kevindagame.snipe.Sniper;
import com.github.kevindagame.voxelsniper.SpigotVoxelSniper;
import com.github.kevindagame.voxelsniper.entity.IEntity;
import com.github.kevindagame.voxelsniper.entity.SpigotEntity;
import com.github.kevindagame.voxelsniper.entity.entitytype.VoxelEntityType;
import com.github.kevindagame.voxelsniper.location.BaseLocation;
import com.github.kevindagame.voxelsniper.location.SpigotLocation;
import com.github.kevindagame.voxelsniper.material.VoxelMaterial;
import com.github.kevindagame.voxelsniper.vector.VoxelVector;
import net.kyori.adventure.text.Component;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.util.Vector;
import org.jetbrains.annotations.NotNull;
import java.util.Locale;
import java.util.Objects;
import java.util.UUID;
public class SpigotPlayer extends SpigotEntity implements IPlayer {
private final Player player;
private final @NotNull Sniper sniper;
public SpigotPlayer(Player player) {
super(player);
this.player = player;
this.sniper = new Sniper(this);
}
@Override
public UUID getUniqueId() {
return player.getUniqueId();
}
@Override
public void sendMessage(String message) {
player.sendMessage(message);
}
@Override
public boolean hasPermission(String permissionNode) {
return player.hasPermission(permissionNode);
}
@Override
public boolean isSneaking() {
return player.isSneaking();
}
@Override
public String getName() {
return player.getName();
}
@Override
public void teleport(BaseLocation location) {
player.teleport(SpigotLocation.toSpigotLocation(location));
}
@Override
public void remove() {
}
@Override
public IEntity launchProjectile(VoxelEntityType type, VoxelVector velocity) {
Class<? extends Entity> clazz = EntityType.valueOf(type.getKey().toUpperCase(Locale.ROOT)).getEntityClass();
if (clazz != null && Projectile.class.isAssignableFrom(clazz)) {
Class<? extends Projectile> projectile = clazz.asSubclass(Projectile.class);
Vector vector = new Vector(velocity.getX(), velocity.getY(), velocity.getZ());
return SpigotEntity.fromSpigotEntity(player.launchProjectile(projectile, vector));
}
return null;
}
@Override
public VoxelMaterial getItemInHand() {
var item = player.getInventory().getItemInMainHand();
VoxelMaterial mat = VoxelMaterial.getMaterial(item.getType().getKey().getKey());
return mat != null ? mat : VoxelMaterial.AIR();
}
@Override
@NotNull
public Sniper getSniper() {
return this.sniper;
}
@Override
public void sendMessage(final @NotNull Component message) {
SpigotVoxelSniper.getAdventure().player(this.player).sendMessage(message);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SpigotPlayer that = (SpigotPlayer) o;
return player.equals(that.player);
}
@Override
public int hashCode() {
return Objects.hash(player);
}
public Player getPlayer() {
return player;
}
}
| 412 | 0.695669 | 1 | 0.695669 | game-dev | MEDIA | 0.932085 | game-dev | 0.620485 | 1 | 0.620485 |
NeoTerrm/NeoTerm | 3,045 | app/src/main/java/io/neoterm/component/session/comp.kt | package io.neoterm.component.session
import android.annotation.SuppressLint
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import io.neoterm.Globals
import io.neoterm.component.NeoComponent
import io.neoterm.component.config.NeoTermPath
import io.neoterm.utils.NLog
class SessionComponent : NeoComponent {
companion object {
private var IS_LIBRARIES_LOADED = false
private fun wrapLibraryName(libName: String): String {
return "lib$libName.so"
}
@SuppressLint("UnsafeDynamicallyLoadedCode")
private fun loadLibraries(): Boolean {
try {
if (Globals.NeedGles3) {
System.loadLibrary("GLESv3")
NLog.e("SessionComponent", "Loaded GLESv3 lib")
} else if (Globals.NeedGles2) {
System.loadLibrary("GLESv2")
NLog.e("SessionComponent", "Loaded GLESv2 lib")
}
} catch (e: UnsatisfiedLinkError) {
NLog.e("SessionComponent", "Cannot load GLESv3 or GLESv2 lib")
}
var result: Boolean
try {
Globals.XLIBS
.plus(Globals.XAPP_LIBS)
.forEach {
val soPath = "${NeoTermPath.LIB_PATH}/xorg-neoterm/${wrapLibraryName(it)}"
NLog.e("SessionComponent", "Loading lib " + soPath)
try {
System.load(soPath)
} catch (error: UnsatisfiedLinkError) {
NLog.e(
"SessionComponent", "Error loading lib " + soPath
+ ", reason: " + error.localizedMessage
)
result = false
}
}
result = true
} catch (ignore: UnsatisfiedLinkError) {
NLog.e("SessionComponent", ignore.localizedMessage)
result = false
}
return result
}
private fun checkLibrariesLoaded(): Boolean {
if (!IS_LIBRARIES_LOADED) {
synchronized(SessionComponent::class.java) {
if (!IS_LIBRARIES_LOADED) {
IS_LIBRARIES_LOADED = loadLibraries()
}
}
}
return IS_LIBRARIES_LOADED
}
}
override fun onServiceInit() {
}
override fun onServiceDestroy() {
}
override fun onServiceObtained() {
}
fun createSession(context: Context, parameter: XParameter): XSession {
if (context is AppCompatActivity) {
if (!checkLibrariesLoaded()) {
throw RuntimeException("Cannot load libraries!")
}
return XSession(context, XSessionData())
}
throw RuntimeException("Creating X sessions requires Activity, but got Context")
}
fun createSession(context: Context, parameter: ShellParameter): ShellTermSession {
return ShellTermSession.Builder()
.executablePath(parameter.executablePath)
.currentWorkingDirectory(parameter.cwd)
.callback(parameter.sessionCallback)
.systemShell(parameter.systemShell)
.envArray(parameter.env)
.argArray(parameter.arguments)
.initialCommand(parameter.initialCommand)
.profile(parameter.shellProfile)
.create(context)
}
}
| 412 | 0.883371 | 1 | 0.883371 | game-dev | MEDIA | 0.596843 | game-dev | 0.792959 | 1 | 0.792959 |
wiremod/wire | 5,632 | lua/entities/gmod_wire_grabber.lua | AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Grabber"
ENT.RenderGroup = RENDERGROUP_BOTH
ENT.WireDebugName = "Grabber"
function ENT:SetupDataTables()
self:NetworkVar( "Float", 0, "BeamLength" )
end
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Inputs = Wire_CreateInputs(self, { "Grab","Strength (The strength of the weld. The weld will break if enough force is applied. Setting to zero makes the weld unbreakable.)","Range" })
self.Outputs = Wire_CreateOutputs(self, {"Holding", "Grabbed Entity [ENTITY]"})
self.WeldStrength = 0
self.Weld = nil
self.WeldEntity = nil
self.EntHadGravity = true
self.ExtraProp = nil
self.ExtraPropWeld = nil
self:GetPhysicsObject():SetMass(10)
self:Setup(100, true)
end
function ENT:OnRemove()
if self.Weld then
self:ResetGrab()
end
Wire_Remove(self)
end
function ENT:Setup(Range, Gravity)
if Range then self:SetBeamLength(Range) end
self.Gravity = Gravity
end
function ENT:LinkEnt( prop )
if not IsValid(prop) then return false, "Not a valid entity!" end
self.ExtraProp = prop
WireLib.SendMarks(self, {prop})
return true
end
function ENT:UnlinkEnt()
if IsValid(self.ExtraPropWeld) then
self.ExtraPropWeld:Remove()
self.ExtraPropWeld = nil
end
self.ExtraProp = nil
WireLib.SendMarks(self, {})
return true
end
function ENT:ResetGrab()
if IsValid(self.Weld) then
self.Weld:Remove()
if self.EntHadGravity and IsValid(self.WeldEntity) and IsValid(self.WeldEntity:GetPhysicsObject()) and self.Gravity then
self.WeldEntity:GetPhysicsObject():EnableGravity(true)
end
end
if IsValid(self.ExtraPropWeld) then
self.ExtraPropWeld:Remove()
end
self.Weld = nil
self.WeldEntity = nil
self.ExtraPropWeld = nil
self:SetColor(Color(255, 255, 255, self:GetColor().a))
Wire_TriggerOutput(self, "Holding", 0)
Wire_TriggerOutput(self, "Grabbed Entity", self.WeldEntity)
end
function ENT:CanGrab(trace)
if not trace.Entity or not isentity(trace.Entity) then return false end
if (not trace.Entity:IsValid() and not trace.Entity:IsWorld()) or trace.Entity:IsPlayer() then return false end
-- If there's no physics object then we can't constraint it!
if not util.IsValidPhysicsObject(trace.Entity, trace.PhysicsBone) then return false end
if not WireLib.CanTool(self:GetPlayer(), trace.Entity, "weld") then return false end
return true
end
function ENT:TriggerInput(iname, value)
if iname == "Grab" then
if value ~= 0 and self.Weld == nil then
local vStart = self:GetPos()
local vForward = self:GetUp()
local filter = ents.FindByClass( "gmod_wire_spawner" ) -- for prop spawning contraptions that grab spawned props
table.insert( filter, self )
local trace = util.TraceLine {
start = vStart,
endpos = vStart + (vForward * self:GetBeamLength()),
filter = filter
}
if not self:CanGrab(trace) then return end
-- Weld them!
local const = constraint.Weld(self, trace.Entity, 0, 0, self.WeldStrength)
if const then
const.Type = "" --prevents the duplicator from making this weld
end
local const2
--Msg("+Weld1\n")
if self.ExtraProp then
if self.ExtraProp:IsValid() then
const2 = constraint.Weld(self.ExtraProp, trace.Entity, 0, 0, self.WeldStrength)
if const2 then
const2.Type = "" --prevents the duplicator from making this weld
end
--Msg("+Weld2\n")
end
end
if self.Gravity then
trace.Entity:GetPhysicsObject():EnableGravity(false)
end
self.WeldEntity = trace.Entity
self.Weld = const
self.ExtraPropWeld = const2
self.EntHadGravity = trace.Entity:GetPhysicsObject():IsGravityEnabled()
self:SetColor(Color(255, 0, 0, self:GetColor().a))
Wire_TriggerOutput(self, "Holding", 1)
Wire_TriggerOutput(self, "Grabbed Entity", self.WeldEntity)
elseif value == 0 then
if self.Weld ~= nil or self.ExtraPropWeld ~= nil then
self:ResetGrab()
end
end
elseif iname == "Strength" then
self.WeldStrength = math.max(value,0)
elseif iname == "Range" then
self:SetBeamLength(math.Clamp(value,0,32000))
end
end
--duplicator support (TAD2020)
function ENT:BuildDupeInfo()
local info = BaseClass.BuildDupeInfo(self) or {}
if self.WeldEntity and self.WeldEntity:IsValid() then
info.WeldEntity = self.WeldEntity:EntIndex()
end
if self.ExtraProp and self.ExtraProp:IsValid() then
info.ExtraProp = self.ExtraProp:EntIndex()
end
return info
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID)
BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID)
self.WeldEntity = GetEntByID(info.WeldEntity)
self.ExtraProp = GetEntByID(info.ExtraProp)
if self.WeldEntity and self.Inputs.Grab.Value ~= 0 then
if not self.Weld and self.trace~=nil then
self.Weld = constraint.Weld(self, self.trace, 0, 0, self.WeldStrength)
self.Weld.Type = "" --prevents the duplicator from making this weld
end
if IsValid(self.ExtraProp) then
self.ExtraPropWeld = constraint.Weld(self.ExtraProp, self.WeldEntity, 0, 0, self.WeldStrength)
self.ExtraPropWeld.Type = "" --prevents the duplicator from making this weld
end
if self.Gravity then
self.WeldEntity:GetPhysicsObject():EnableGravity(false)
end
if self.Weld then
self:SetColor(Color(255, 0, 0, self:GetColor().a))
Wire_TriggerOutput(self, "Holding", 1)
Wire_TriggerOutput(self, "Grabbed Entity", self.WeldEntity)
else
self:ResetGrab()
end
end
end
duplicator.RegisterEntityClass("gmod_wire_grabber", WireLib.MakeWireEnt, "Data", "Range", "Gravity")
| 412 | 0.883178 | 1 | 0.883178 | game-dev | MEDIA | 0.704591 | game-dev | 0.923224 | 1 | 0.923224 |
Potion-Studios/BYG | 3,065 | Common/src/main/java/potionstudios/byg/client/textures/ColorManager.java | package potionstudios.byg.client.textures;
import net.minecraft.client.color.block.BlockColors;
import net.minecraft.client.color.item.ItemColor;
import net.minecraft.client.color.item.ItemColors;
import net.minecraft.client.renderer.BiomeColors;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.level.FoliageColor;
import net.minecraft.world.level.GrassColor;
import net.minecraft.world.level.block.state.BlockState;
import potionstudios.byg.common.block.BYGBlocks;
import potionstudios.byg.common.block.BYGWoodTypes;
import potionstudios.byg.common.item.BYGItems;
public class ColorManager {
public static synchronized void onBlockColorsInit(BlockColors blockColors) {
//registers the colors for blocks that changes colors based on biome
blockColors.register((unknown, lightReader, pos, unknown2) -> lightReader != null && pos != null ? BiomeColors.getAverageGrassColor(lightReader, pos) : GrassColor.get(0.5D, 1.0D), BYGBlocks.FLOWER_PATCH.get(), BYGBlocks.LUSH_GRASS_BLOCK.get(), BYGBlocks.OVERGROWN_STONE.get(), BYGBlocks.OVERGROWN_NETHERRACK.get(), BYGBlocks.TINY_LILYPADS.get(), BYGBlocks.FLOWERING_TINY_LILY_PADS.get(), BYGBlocks.OVERGROWN_DACITE.get(), BYGBlocks.NETHER_BRISTLE.get());
blockColors.register((unknown, lightReader, pos, unknown2) -> lightReader != null && pos != null ? BiomeColors.getAverageFoliageColor(lightReader, pos) : FoliageColor.get(0.5D, 1.0D), BYGBlocks.CLOVER_PATCH.get(), BYGWoodTypes.MAHOGANY.leaves().get(),BYGBlocks.LEAF_PILE.get(), BYGBlocks.POISON_IVY.get(), BYGWoodTypes.WILLOW.leaves().get(), BYGWoodTypes.MAPLE.leaves().get(), BYGBlocks.JOSHUA_LEAVES.get(), BYGBlocks.FLOWERING_JOSHUA_LEAVES.get(), BYGBlocks.RIPE_JOSHUA_LEAVES.get(), BYGWoodTypes.CYPRESS.leaves().get());
blockColors.register((unknown, lightReader, pos, unknown2) -> lightReader != null && pos != null ? BiomeColors.getAverageWaterColor(lightReader, pos) : -1, BYGBlocks.WATER_BARREL_CACTUS.get());
}
public static synchronized void onItemColorsInit(BlockColors blockColors, ItemColors itemColors) {
// Use the Block's colour handler from BlockItem
ItemColor itemBlockColourHandler = (stack, tintIndex) -> {
BlockState state = ((BlockItem) stack.getItem()).getBlock().defaultBlockState();
return blockColors.getColor(state, null, null, tintIndex);
};
itemColors.register(itemBlockColourHandler,
BYGItems.CLOVER_PATCH.get(), BYGItems.LUSH_GRASS_BLOCK.get(), BYGItems.OVERGROWN_NETHERRACK.get(), BYGWoodTypes.MAHOGANY.leaves().get(),
BYGItems.POISON_IVY.get(), BYGItems.OVERGROWN_STONE.get(),
BYGItems.TINY_LILYPADS.get(), BYGItems.FLOWERING_TINY_LILY_PADS.get(), BYGItems.NETHER_BRISTLE.get(), BYGItems.OVERGROWN_DACITE.get(), BYGItems.LEAF_PILE.get(),
BYGWoodTypes.WILLOW.leaves(), BYGWoodTypes.CYPRESS.leaves().get(),
BYGWoodTypes.MAPLE.leaves(), BYGItems.JOSHUA_LEAVES.get(), BYGItems.FLOWERING_JOSHUA_LEAVES.get(), BYGItems.RIPE_JOSHUA_LEAVES.get());
}
} | 412 | 0.880567 | 1 | 0.880567 | game-dev | MEDIA | 0.92387 | game-dev | 0.857216 | 1 | 0.857216 |
Xalalau/Zombie-Survival-v1.11-Fix | 1,263 | entities/weapons/weapon_zs_glock3/shared.lua | if SERVER then
AddCSLuaFile("shared.lua")
SWEP.HoldType = "pistol"
end
if CLIENT then
SWEP.PrintName = "'Crossfire' Glock 3"
SWEP.Author = "JetBoom"
SWEP.Slot = 1
SWEP.SlotPos = 3
SWEP.IconLetter = "c"
killicon.AddFont("weapon_zs_glock3", "CSKillIcons", SWEP.IconLetter, Color(255, 80, 0, 255 ))
end
SWEP.Base = "weapon_zs_base"
SWEP.Spawnable = true
SWEP.AdminSpawnable = true
-- Support replacement weapons, so we don't require CSS - Xala
if file.Exists("models/weapons/2_pist_glock18.mdl", "GAME") then
SWEP.ViewModel = "models/weapons/2_pist_glock18.mdl"
SWEP.WorldModel = "models/weapons/3_pist_glock18.mdl"
else
SWEP.ViewModel = "models/weapons/v_pist_glock18.mdl"
SWEP.WorldModel = "models/weapons/w_pist_glock18.mdl"
end
SWEP.Weight = 5
SWEP.AutoSwitchTo = false
SWEP.AutoSwitchFrom = false
//SWEP.Primary.Sound = Sound("Weapon_Glock.Single")
SWEP.Primary.Sound = Sound("weapons/glock/glock18-1.wav")
SWEP.Primary.Recoil = 2.5
SWEP.Primary.Damage = 11
SWEP.Primary.NumShots = 3
SWEP.Primary.ClipSize = 7
SWEP.Primary.Delay = 0.3
SWEP.Primary.DefaultClip = SWEP.Primary.ClipSize * 3
SWEP.Primary.Automatic = false
SWEP.Primary.Ammo = "pistol"
SWEP.Primary.Cone = 0.13
SWEP.ConeMoving = 0.18
SWEP.ConeCrouching = 0.1
SWEP.WalkSpeed = 200
| 412 | 0.650561 | 1 | 0.650561 | game-dev | MEDIA | 0.516184 | game-dev | 0.589343 | 1 | 0.589343 |
FoxLoveFire/MineBoostV2 | 3,188 | src/gui/guiInventoryList.h | // Luanti
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
#pragma once
#include "inventorymanager.h"
#include "irrlichttypes_extrabloated.h"
#include "util/string.h"
class GUIFormSpecMenu;
class GUIInventoryList : public gui::IGUIElement
{
public:
struct ItemSpec
{
ItemSpec() = default;
ItemSpec(const InventoryLocation &a_inventoryloc,
const std::string &a_listname,
s32 a_i,
const v2s32 slotsize) :
inventoryloc(a_inventoryloc),
listname(a_listname),
i(a_i),
slotsize(slotsize)
{
}
bool operator==(const ItemSpec& other) const
{
return inventoryloc == other.inventoryloc &&
listname == other.listname && i == other.i;
}
bool isValid() const { return i != -1; }
InventoryLocation inventoryloc;
std::string listname;
s32 i = -1;
v2s32 slotsize;
};
// options for inventorylists that are setable with the lua api
struct Options {
// whether a one-pixel border for the slots should be drawn and its color
bool slotborder = false;
video::SColor slotbordercolor = video::SColor(200, 0, 0, 0);
// colors for normal and highlighted slot background
video::SColor slotbg_n = video::SColor(255, 128, 128, 128);
video::SColor slotbg_h = video::SColor(255, 192, 192, 192);
};
GUIInventoryList(gui::IGUIEnvironment *env,
gui::IGUIElement *parent,
s32 id,
const core::rect<s32> &rectangle,
InventoryManager *invmgr,
const InventoryLocation &inventoryloc,
const std::string &listname,
const v2s32 &geom,
const s32 start_item_i,
const v2s32 &slot_size,
const v2f32 &slot_spacing,
GUIFormSpecMenu *fs_menu,
const Options &options,
gui::IGUIFont *font);
virtual void draw() override;
virtual bool OnEvent(const SEvent &event) override;
const InventoryLocation &getInventoryloc() const
{
return m_inventoryloc;
}
const std::string &getListname() const
{
return m_listname;
}
void setSlotBGColors(const video::SColor &slotbg_n, const video::SColor &slotbg_h)
{
m_options.slotbg_n = slotbg_n;
m_options.slotbg_h = slotbg_h;
}
void setSlotBorders(bool slotborder, const video::SColor &slotbordercolor)
{
m_options.slotborder = slotborder;
m_options.slotbordercolor = slotbordercolor;
}
const v2s32 getSlotSize() const noexcept
{
return m_slot_size;
}
// returns -1 if not item is at pos p
s32 getItemIndexAtPos(v2s32 p) const;
private:
InventoryManager *m_invmgr;
const InventoryLocation m_inventoryloc;
const std::string m_listname;
// the specified width and height of the shown inventorylist in itemslots
const v2s32 m_geom;
// the first item's index in inventory
const s32 m_start_item_i;
// specifies how large the slot rects are
const v2s32 m_slot_size;
// specifies how large the space between slots is (space between is spacing-size)
const v2f32 m_slot_spacing;
// the GUIFormSpecMenu can have an item selected and co.
GUIFormSpecMenu *m_fs_menu;
Options m_options;
// the font
gui::IGUIFont *m_font;
// the index of the hovered item; -1 if no item is hovered
s32 m_hovered_i;
// we do not want to write a warning on every draw
bool m_already_warned;
};
| 412 | 0.936698 | 1 | 0.936698 | game-dev | MEDIA | 0.424668 | game-dev,desktop-app | 0.660889 | 1 | 0.660889 |
tukui-org/ElvUI | 3,014 | ElvUI/Core/General/Smoothie.lua | local E, L, V, P, G = unpack(ElvUI)
-- Credit: ls- (lightspark)
local abs, next, Lerp = abs, next, Lerp
local tonumber, assert = tonumber, assert
local activeObjects = {}
local handledObjects = {}
local TARGET_FPS = 60
local AMOUNT = 0.33
local frame = CreateFrame('Frame')
function E:Smoothing_Clamp(v, min, max)
if not min then min = 0 end
if not max then max = 1 end
if v > max then
return max
elseif v < min then
return min
end
return v
end
function E:Smoothing_IsCloseEnough(new, target, range)
if range > 0 then
return abs((new - target) / range) <= 0.001
end
return true
end
function E:Smoothing_OnUpdate(elapsed)
for object, target in next, activeObjects do
local new = Lerp(object._value, target, E:Smoothing_Clamp(AMOUNT * elapsed * TARGET_FPS))
if E:Smoothing_IsCloseEnough(new, target, object._max - object._min) then
new = target
activeObjects[object] = nil
end
object:SetValue_(new)
object._value = new
end
end
function E:Smoothing_SetSmoothedValue(value)
value = tonumber(value)
assert(value, 'bar_SetSmoothedValue requires (value) to be a number.')
self._value = self:GetValue()
activeObjects[self] = E:Smoothing_Clamp(value, self._min, self._max)
end
function E:Smoothing_SetSmoothedMinMaxValues(min, max)
min, max = tonumber(min), tonumber(max)
assert(min and max, 'bar_SetSmoothedMinMaxValues requires (min and max) to be a number.')
self:SetMinMaxValues_(min, max)
if self._max and self._max ~= max then
local ratio = 1
if max ~= 0 and self._max and self._max ~= 0 then
ratio = max / (self._max or max)
end
local target = activeObjects[self]
if target then
activeObjects[self] = target * ratio
end
local cur = self._value
if cur then
self:SetValue_(cur * ratio)
self._value = cur * ratio
end
end
self._min = min
self._max = max
end
function E:Smoothing_Enable(bar)
bar._min, bar._max = bar:GetMinMaxValues()
bar._value = bar:GetValue()
if not bar.SetValue_ then
bar.SetValue_ = bar.SetValue
bar.SetValue = E.Smoothing_SetSmoothedValue
end
if not bar.SetMinMaxValues_ then
bar.SetMinMaxValues_ = bar.SetMinMaxValues
bar.SetMinMaxValues = E.Smoothing_SetSmoothedMinMaxValues
end
if not frame:GetScript('OnUpdate') then
frame:SetScript('OnUpdate', E.Smoothing_OnUpdate)
end
handledObjects[bar] = true
end
function E:Smoothing_Disable(bar)
if activeObjects[bar] then
bar:SetValue_(activeObjects[bar])
activeObjects[bar] = nil
end
if handledObjects[bar] then
handledObjects[bar] = nil
end
if bar.SetValue_ then
bar.SetValue = bar.SetValue_
bar.SetValue_ = nil
end
if bar.SetMinMaxValues_ then
bar.SetMinMaxValues = bar.SetMinMaxValues_
bar.SetMinMaxValues_ = nil
end
if not next(handledObjects) then
frame:SetScript('OnUpdate', nil)
end
end
function E:SetSmoothingAmount(amount)
AMOUNT = E:Smoothing_Clamp(amount, 0.2, 0.8)
end
function E:SetSmoothing(bar, enable)
if enable then
E:Smoothing_Enable(bar)
else
E:Smoothing_Disable(bar)
end
end
| 412 | 0.934172 | 1 | 0.934172 | game-dev | MEDIA | 0.35945 | game-dev | 0.832306 | 1 | 0.832306 |
amethyst/rustrogueliketutorial | 1,600 | chapter-71-logging/src/ai/flee_ai_system.rs | use specs::prelude::*;
use crate::{MyTurn, WantsToFlee, Position, Map, ApplyMove};
pub struct FleeAI {}
impl<'a> System<'a> for FleeAI {
#[allow(clippy::type_complexity)]
type SystemData = (
WriteStorage<'a, MyTurn>,
WriteStorage<'a, WantsToFlee>,
WriteStorage<'a, Position>,
WriteExpect<'a, Map>,
Entities<'a>,
WriteStorage<'a, ApplyMove>
);
fn run(&mut self, data : Self::SystemData) {
let (mut turns, mut want_flee, positions, mut map,
entities, mut apply_move) = data;
let mut turn_done : Vec<Entity> = Vec::new();
for (entity, pos, flee, _myturn) in
(&entities, &positions, &want_flee, &turns).join()
{
turn_done.push(entity);
let my_idx = map.xy_idx(pos.x, pos.y);
map.populate_blocked();
let flee_map = rltk::DijkstraMap::new(map.width as usize, map.height as usize, &flee.indices, &*map, 100.0);
let flee_target = rltk::DijkstraMap::find_highest_exit(&flee_map, my_idx, &*map);
if let Some(flee_target) = flee_target {
if !crate::spatial::is_blocked(flee_target as usize) {
apply_move.insert(entity, ApplyMove{ dest_idx : flee_target }).expect("Unable to insert");
turn_done.push(entity);
}
}
}
want_flee.clear();
// Remove turn marker for those that are done
for done in turn_done.iter() {
turns.remove(*done);
}
}
}
| 412 | 0.787057 | 1 | 0.787057 | game-dev | MEDIA | 0.666562 | game-dev | 0.982986 | 1 | 0.982986 |
babalae/bettergi-scripts-list | 42,136 | repo/js/ArtifactsGroupPurchasing/main.js | const runExtra = settings.runExtra || false;
const leaveTeamRo = RecognitionObject.TemplateMatch(file.ReadImageMatSync("assets/RecognitionObject/leaveTeam.png"));
let targetItems;
let pickupDelay = 100;
let timeMove = 1000;
let timeMoveUp = Math.round(timeMove * 0.45);
let timeMoveDown = Math.round(timeMove * 0.55);
let rollingDelay = 25;
let state;
let gameRegion;
(async function () {
setGameMetrics(1920, 1080, 1);
await genshin.tpToStatueOfTheSeven();
await switchPartyIfNeeded(settings.partyName);
targetItems = await loadTargetItems();
if (settings.groupMode != "按照下列配置自动进入并运行") {
await genshin.clearPartyCache();
await runGroupPurchasing(runExtra);
}
if (settings.groupMode != "手动进入后运行") {
//解析与输出自定义配置
const raw = settings.runningOrder || "1234";
if (!/^[1-4]+$/.test(raw)) {
throw new Error('runningOrder 只能由 1-4 的数字组成,检测到非法字符。');
}
if (new Set(raw).size !== raw.length) {
throw new Error('runningOrder 中出现了重复数字。');
}
const enteringIndex = raw.split('').map(Number);
const msg = '将依次进入' + enteringIndex.map(i => `${i}号`).join(',') + '的世界';
log.info(msg);
const yourIndex = Number(settings.yourIndex);
if (!yourIndex || yourIndex < 1 || yourIndex > 4) {
throw new Error('yourIndex 必须是 1-4 之间的数字。');
}
const pos = enteringIndex.indexOf(yourIndex) + 1; // 第几个执行
log.info(`你的序号是${yourIndex}号,将在第${pos}个执行`);
// 按 runningOrder 依次进入世界并执行联机收尾
for (const idx of enteringIndex) {
await genshin.clearPartyCache();
if (settings.usingCharacter) { await sleep(1000); keyPress(`${settings.usingCharacter}`); }
//构造加入idx号世界的autoEnter的settings
let autoEnterSettings;
if (idx === yourIndex) {
// 1. 先收集真实存在的白名单
const permits = {};
let permitIndex = 1;
for (const otherIdx of [1, 2, 3, 4]) {
if (otherIdx !== yourIndex) {
const pName = settings[`p${otherIdx}Name`];
if (pName) { // 过滤掉空/undefined
permits[`nameToPermit${permitIndex}`] = pName;
permitIndex++;
}
}
}
// 2. 用真正写进去的人数作为 maxEnterCount
autoEnterSettings = {
enterMode: "等待他人进入",
permissionMode: "白名单",
timeout: 5,
maxEnterCount: Object.keys(permits).length
};
Object.assign(autoEnterSettings, permits);
log.info(`等待他人进入自己世界,白名单人数:${autoEnterSettings.maxEnterCount}`);
} else {
// 构造队员配置
autoEnterSettings = {
enterMode: "进入他人世界",
enteringUID: settings[`p${idx}UID`],
timeout: 5
};
log.info(`将要进入序号${idx},uid为${settings[`p${idx}UID`]}的世界`);
}
let attempts = 0;
while (attempts < 5) {
attempts++;
await autoEnter(autoEnterSettings);
//队员加入后要检查房主名称
if (autoEnterSettings.enterMode === "进入他人世界" && attempts != 5) {
if (await checkP1Name(settings[`p${idx}Name`])) {
break;
} else {
//进入了错误的世界,退出世界并重新加入,最后一次不检查
await sleep(1000);
let leaveAttempts = 0;
while (leaveAttempts < 10) {
leaveAttempts++;
if (await getPlayerSign() === 0) {
break;
}
await keyPress("F2");
await sleep(1000);
await findAndClick(leaveTeamRo);
await waitForMainUI(true);
await genshin.returnMainUi();
}
}
} else {
break;
}
}
//执行对应的联机狗粮
await runGroupPurchasing(false);
}
//如果勾选了额外,在结束后再执行一次额外路线
if (settings.runExtra) {
await runGroupPurchasing(runExtra);
}
}
await genshin.tpToStatueOfTheSeven();
}
)();
async function checkP1Name(p1Name) {
await genshin.returnMainUi();
await keyPress("F2");
await sleep(2000);
const gameRegion = captureGameRegion();
const resList = gameRegion.findMulti(RecognitionObject.ocr(400, 170, 300, 55));
gameRegion.dispose();
let hit = null;
let txt;
for (const res of resList) {
txt = res.text.trim();
if (txt === p1Name) { hit = txt; break; }
}
if (hit) {
log.info(`识别到房主为${hit},与预期相符`);
return true;
} else {
log.warn(`识别结果为${txt},与预期的${p1Name}不符,重试`);
return false;
}
}
/**
* 群收尾 / 额外路线统一入口
*
*/
async function runGroupPurchasing(runExtra) {
// ===== 1. 读取配置 =====
const p1EndingRoute = settings.p1EndingRoute || "枫丹高塔";
const p2EndingRoute = settings.p2EndingRoute || "度假村";
const p3EndingRoute = settings.p3EndingRoute || "智障厅";
const p4EndingRoute = settings.p4EndingRoute || "踏鞴砂";
const forceGroupNumber = settings.forceGroupNumber || 0;
// ===== 2. 图标模板 =====
const p2InBigMapRo = RecognitionObject.TemplateMatch(file.ReadImageMatSync("assets/RecognitionObject/2pInBigMap.png"));
const p3InBigMapRo = RecognitionObject.TemplateMatch(file.ReadImageMatSync("assets/RecognitionObject/3pInBigMap.png"));
const p4InBigMapRo = RecognitionObject.TemplateMatch(file.ReadImageMatSync("assets/RecognitionObject/4pInBigMap.png"));
const kickAllRo = RecognitionObject.TemplateMatch(file.ReadImageMatSync("assets/RecognitionObject/kickAll.png"));
const confirmKickRo = RecognitionObject.TemplateMatch(file.ReadImageMatSync("assets/RecognitionObject/confirmKick.png"));
// ===== 3. 初始化变量 =====
let _infoPoints = null;
let running = true;
// ===== 4. 主流程 =====
log.info("开始识别队伍编号");
let groupNumBer = await getPlayerSign();
if (groupNumBer !== 0) log.info(`在队伍中编号为${groupNumBer}`);
else log.info(`不处于联机模式或识别异常`);
if (forceGroupNumber != 0) {
groupNumBer = forceGroupNumber;
log.info(`将自己在队伍中的编号强制指定为${groupNumBer}`);
}
if (groupNumBer === 1) {
log.info("是1p,检测当前总人数");
const totalNumber = await findTotalNumber();
await waitForReady(totalNumber);
for (let i = 1; i <= totalNumber; i++) await runEndingPath(i);
let kickAttempts = 0;
while (kickAttempts < 10) {
kickAttempts++;
await genshin.returnMainUi();
await keyPress("F2");
await sleep(2000);
await findAndClick(kickAllRo);
await sleep(500);
await findAndClick(confirmKickRo);
await waitForMainUI(true);
await genshin.returnMainUi();
if (await getPlayerSign() === 0) {
await genshin.returnMainUi();
break;
}
await genshin.returnMainUi();
await sleep(10000);
}
} else if (groupNumBer > 1) {
await goToTarget(groupNumBer);
let start = new Date();
while (new Date() - start < 2 * 60 * 60 * 1000) {
if (await waitForMainUI(false, 60 * 60 * 1000)) {
await waitForMainUI(true);
await genshin.returnMainUi();
if (await getPlayerSign() === 0) {
break;
}
}
}
if (new Date() - start > 2 * 60 * 60 * 1000) {
log.warn("超时仍未回到主界面,主动退出");
}
let leaveAttempts = 0;
while (leaveAttempts < 10) {
if (await getPlayerSign() === 0) {
break;
}
await keyPress("F2");
await sleep(1000);
await findAndClick(leaveTeamRo);
await waitForMainUI(true);
await genshin.returnMainUi();
}
} else if (runExtra) {
log.info("请确保联机收尾已结束,将开始运行额外路线");
await runExtraPath();
}
running = false;
/**
* 等待所有队友(2P/3P/4P)就位
* @param {number} totalNumber 联机总人数(包含自己)
* @param {number} timeOut 最长等待毫秒
*/
async function waitForReady(totalNumber, timeOut = 300000) {
// 实际需要检测的队友编号:2 ~ totalNumber
const needCheck = totalNumber - 1; // 队友人数
const readyFlags = new Array(needCheck).fill(false); // 下标 0 代表 2P,1 代表 3P …
const startTime = Date.now();
while (Date.now() - startTime < timeOut) {
let allReady = true;
await genshin.returnMainUi();
await keyPress("M"); // 打开多人地图/界面
await sleep(2000); // 给 UI 一点加载时间
for (let i = 0; i < needCheck; i++) {
// 已就绪的队友跳过
if (readyFlags[i]) continue;
const playerIndex = i + 2; // 2P/3P/4P
const ready = await checkReady(playerIndex);
if (ready) {
log.info(`玩家 ${playerIndex}P 已就绪`);
readyFlags[i] = true;
} else {
allReady = false; // 还有没就绪的
}
}
if (allReady) {
log.info("所有队友已就绪");
if (settings.runDebug) await sleep(10000);
return true;
}
// 每轮检测后稍等,防止刷屏
await sleep(500);
}
log.warn("等待队友就绪超时");
return false;
}
async function checkReady(i) {
try {
/* 1. 先把地图移到目标点位(point 来自 info.json) */
const point = await getPointByPlayer(i);
if (!point) return false;
// 把路径封装在函数内部
const map = {
2: "assets/RecognitionObject/2pInBigMap.png",
3: "assets/RecognitionObject/3pInBigMap.png",
4: "assets/RecognitionObject/4pInBigMap.png"
};
const tplPath = map[i];
if (!tplPath) {
log.error(`无效玩家编号: ${i}`);
return null;
}
const template = file.ReadImageMatSync(tplPath);
const recognitionObj = RecognitionObject.TemplateMatch(template, 0, 0, 1920, 1080); // 全屏查找,可自行改区域
if (await findAndClick(recognitionObj, 5)) await sleep(1000);
await genshin.moveMapTo(Math.round(point.x), Math.round(point.y));
/* 2. 取图标屏幕坐标 */
const pos = await getPlayerIconPos(i);
if (!pos || !pos.found) return false;
/* 3. 屏幕坐标 → 地图坐标(图标)*/
const mapZoomLevel = 2.0;
await genshin.setBigMapZoomLevel(mapZoomLevel);
const mapScaleFactor = 2.361;
const center = genshin.getPositionFromBigMap(); // 仅用于坐标系转换
const iconScreenX = pos.x;
const iconScreenY = pos.y;
const iconMapX = (960 - iconScreenX) * mapZoomLevel / mapScaleFactor + center.x;
const iconMapY = (540 - iconScreenY) * mapZoomLevel / mapScaleFactor + center.y;
/* 4. 计算“图标地图坐标”与“目标点位”的距离 */
const dx = iconMapX - point.x;
const dy = iconMapY - point.y;
const dist = Math.sqrt(dx * dx + dy * dy);
/* 5. 打印两种坐标及距离 */
log.info(`玩家 ${i}P`);
log.info(`├─ 屏幕坐标: (${iconScreenX}, ${iconScreenY})`);
log.info(`├─ 图标地图坐标: (${iconMapX.toFixed(2)}, ${iconMapY.toFixed(2)})`);
log.info(`├─ 目标点位坐标: (${point.x}, ${point.y})`);
log.info(`└─ 图标与目标点位距离: ${dist.toFixed(2)} m`);
return dist <= 10; // 10 m 阈值,可按需调整
} catch (error) {
log.error(error.message);
return false;
}
}
/**
* 根据玩家编号返回该路线在 assets/info.json 中记录的点位坐标
* @param {number} playerIndex 1 | 2 | 3 | 4
* @returns {{x:number,y:number}|null}
*/
async function getPointByPlayer(playerIndex) {
// 1. 只读一次:第一次调用时加载并缓存
if (_infoPoints === null) {
try {
const jsonStr = file.ReadTextSync('assets/info.json');
_infoPoints = JSON.parse(jsonStr);
if (!Array.isArray(_infoPoints)) {
log.error('assets/info.json 不是数组格式');
_infoPoints = []; // 防止后续再读
return null;
}
} catch (err) {
log.error(`读取或解析 assets/info.json 失败: ${err.message}`);
_infoPoints = [];
return null;
}
}
// 2. 外部已准备好的路线名称映射
const routeMap = {
1: p1EndingRoute,
2: p2EndingRoute,
3: p3EndingRoute,
4: p4EndingRoute
};
const routeName = routeMap[playerIndex];
if (!routeName) {
log.error(`无效玩家编号: ${playerIndex}`);
return null;
}
// 3. 遍历缓存数组
for (let i = 0; i < _infoPoints.length; i++) {
const p = _infoPoints[i];
if (p && p.name === routeName) {
return { x: p.position.x, y: p.position.y };
}
}
log.warn(`在 info.json 中找不到 name 为 "${routeName}" 的点`);
return null;
}
/**
* 根据玩家编号获取 2/3/4P 图标在屏幕上的坐标
* @param {number} playerIndex 2 | 3 | 4
* @param {number} timeout 最长查找毫秒,默认 2000
* @returns {Promise<{x:number,y:number,width:number,height:number,found:boolean}|null>}
* found=true 时坐标有效;未找到/取消/异常返回 null
*/
async function getPlayerIconPos(playerIndex, timeout = 2000) {
// 把路径封装在函数内部
const map = {
2: "assets/RecognitionObject/2pInBigMap.png",
3: "assets/RecognitionObject/3pInBigMap.png",
4: "assets/RecognitionObject/4pInBigMap.png"
};
const tplPath = map[playerIndex];
if (!tplPath) {
log.error(`无效玩家编号: ${playerIndex}`);
return null;
}
const template = file.ReadImageMatSync(tplPath);
const recognitionObj = RecognitionObject.TemplateMatch(template, 0, 0, 1920, 1080); // 全屏查找,可自行改区域
const start = Date.now();
while (Date.now() - start < timeout) {
let gameRegion = null;
try {
gameRegion = captureGameRegion();
const res = gameRegion.find(recognitionObj);
if (res.isExist()) {
log.info(`${playerIndex}P,在屏幕上的坐标为(${res.x + 10},${res.y + 10})`);//图标大小为20*20
return {
x: res.x + 10,
y: res.y + 10,
found: true
};
}
} catch (e) {
log.error(`模板匹配异常: ${e.message}`);
return null;
} finally {
if (gameRegion) gameRegion.dispose();
}
await sleep(100);
}
return null;
}
/**
* 根据玩家编号执行执行路线的全部 JSON 文件
* @param {number} i 1 | 2 | 3 | 4
*/
async function runEndingPath(i) {
const routeMap = {
1: p1EndingRoute,
2: p2EndingRoute,
3: p3EndingRoute,
4: p4EndingRoute
};
const folderName = routeMap[i];
if (!folderName) {
log.error(`无效玩家编号: ${i}`);
return;
}
const folderPath = `assets/ArtifactsPath/${folderName}/执行`;
const files = await readFolder(folderPath, true);
if (files.length === 0) {
log.warn(`文件夹 ${folderPath} 下未找到任何 JSON 路线文件`);
return;
}
if (!settings.runDebug) {
for (const { fullPath } of files) {
await runPath(fullPath, 1);
}
log.info(`${folderName} 的全部路线已完成`);
} else {
log.info("当前为调试模式,跳过执行路线");
}
}
/**
* 执行额外路线
*/
async function runExtraPath() {
const folderPath = `assets/ArtifactsPath/额外/执行`;
const files = await readFolder(folderPath, true);
if (files.length === 0) {
log.warn(`文件夹 ${folderPath} 下未找到任何 JSON 路线文件`);
return;
}
if (!settings.runDebug) {
for (const { fullPath } of files) {
await runPath(fullPath, 1);
}
log.info(`额外 的全部路线已完成`);
} else {
log.info("当前为调试模式,跳过执行路线");
}
}
/**
* 根据玩家编号执行占位路线的全部 JSON 文件
* @param {number} i 1 | 2 | 3 | 4
*/
async function goToTarget(i) {
const routeMap = {
1: p1EndingRoute,
2: p2EndingRoute,
3: p3EndingRoute,
4: p4EndingRoute
};
const folderName = routeMap[i];
if (!folderName) {
log.error(`无效玩家编号: ${i}`);
return;
}
const folderPath = `assets/ArtifactsPath/${folderName}/占位`;
const files = await readFolder(folderPath, true);
if (files.length === 0) {
log.warn(`文件夹 ${folderPath} 下未找到任何 JSON 路线文件`);
return;
}
for (const { fullPath } of files) {
await runPath(fullPath, 1);
}
log.info(`${folderName} 的全部路线已完成`);
}
}
/**
* 自动联机脚本(整体打包为一个函数)
* @param {Object} autoEnterSettings 配置对象
* enterMode: "进入他人世界" | "等待他人进入"
* enteringUID: string | null
* permissionMode: "无条件通过" | "白名单"
* nameToPermit1/2/3: string | null
* timeout: 分钟
* maxEnterCount: number
*/
async function autoEnter(autoEnterSettings) {
// ===== 配置解析 =====
const enterMode = autoEnterSettings.enterMode || "进入他人世界";
const enteringUID = autoEnterSettings.enteringUID;
const permissionMode = autoEnterSettings.permissionMode || "无条件通过";
const timeout = +autoEnterSettings.timeout || 5;
const maxEnterCount = +autoEnterSettings.maxEnterCount || 3;
// 白名单
const targetList = [];
[autoEnterSettings.nameToPermit1, autoEnterSettings.nameToPermit2, autoEnterSettings.nameToPermit3]
.forEach(v => v && targetList.push(v));
// ===== 模板 / 路径 =====
const enterUIDRo = RecognitionObject.TemplateMatch(file.ReadImageMatSync("assets/RecognitionObject/enterUID.png"));
const searchRo = RecognitionObject.TemplateMatch(file.ReadImageMatSync("assets/RecognitionObject/search.png"));
const requestEnterRo = RecognitionObject.TemplateMatch(file.ReadImageMatSync("assets/RecognitionObject/requestEnter.png"));
const requestEnter2Ro = RecognitionObject.TemplateMatch(file.ReadImageMatSync("assets/RecognitionObject/requestEnter.png"), 1480, 300, 280, 600);
const yUIRo = RecognitionObject.TemplateMatch(file.ReadImageMatSync("assets/RecognitionObject/yUI.png"));
const allowEnterRo = RecognitionObject.TemplateMatch(file.ReadImageMatSync("assets/RecognitionObject/allowEnter.png"), 1250, 300, 150, 130);
const targetsPath = "targets";
// ===== 状态 =====
let enterCount = 0;
let targetsRo = [];
let checkToEnd = false;
let enteredPlayers = [];
// ===== 初始化 =====
setGameMetrics(1920, 1080, 1);
const start = new Date();
log.info(`当前模式为:${enterMode}`);
// 加载目标 PNG
const targetPngs = await readFolder(targetsPath, false);
for (const f of targetPngs) {
if (!f.fullPath.endsWith('.png')) continue;
const mat = file.ReadImageMatSync(f.fullPath);
const ro = RecognitionObject.TemplateMatch(mat, 650, 320, 350, 60);
const baseName = f.fileName.replace(/\.png$/i, '');
targetsRo.push({ ro, baseName });
}
log.info(`加载完成共 ${targetsRo.length} 个目标`);
// ===== 主循环 =====
while (new Date() - start < timeout * 60 * 1000) {
if (enterMode === "进入他人世界") {
const playerSign = await getPlayerSign();
await sleep(500);
if (playerSign !== 0) {
log.info(`加入成功,队伍编号 ${playerSign}`);
break;
}
log.info('不处于多人世界,开始尝试加入');
await genshin.returnMainUi(); await sleep(500);
if (!enteringUID) { log.error('未填写有效 UID'); break; }
await keyPress("F2"); await sleep(2000);
if (!await findAndClick(enterUIDRo)) { await genshin.returnMainUi(); continue; }
await sleep(1000); inputText(enteringUID);
await sleep(1000);
if (!await findAndClick(searchRo)) { await genshin.returnMainUi(); continue; }
await sleep(500);
if (!await confirmSearchResult()) { await genshin.returnMainUi(); log.warn("无搜索结果"); continue; }
await sleep(500);
if (!await findAndClick(requestEnterRo)) { await genshin.returnMainUi(); continue; }
await waitForMainUI(true, 20 * 1000);
} else { // 等待他人进入
const playerSign = await getPlayerSign();
if (playerSign > 1) {
log.warn("处于他人世界,先尝试退出");
let leaveAttempts = 0;
while (leaveAttempts < 10) {
if (await getPlayerSign() === 0) {
break;
}
await keyPress("F2");
await sleep(1000);
await findAndClick(leaveTeamRo);
await waitForMainUI(true);
await genshin.returnMainUi();
}
}
if (enterCount >= maxEnterCount) break;
if (await isYUI()) keyPress("VK_ESCAPE"); await sleep(500);
await genshin.returnMainUi();
keyPress("Y"); await sleep(250);
if (!await isYUI()) continue;
log.info("处于 Y 界面,开始识别");
let attempts = 0;
while (attempts++ < 5) {
if (permissionMode === "无条件通过") {
if (await findAndClick(allowEnterRo)) {
await waitForMainUI(true, 20 * 1000);
enterCount++;
break;
}
} else {
const result = await recognizeRequest();
if (result) {
if (await findAndClick(allowEnterRo)) {
await waitForMainUI(true, 20 * 1000);
enterCount++;
enteredPlayers = [...new Set([...enteredPlayers, result])];
log.info(`允许 ${result} 加入`);
if (await isYUI()) { keyPress("VK_ESCAPE"); await sleep(500); await genshin.returnMainUi(); }
break;
} else {
if (await isYUI()) { keyPress("VK_ESCAPE"); await sleep(500); await genshin.returnMainUi(); }
}
}
}
await sleep(500);
}
if (await isYUI()) { keyPress("VK_ESCAPE"); await genshin.returnMainUi(); }
if (enterCount >= maxEnterCount || checkToEnd) {
checkToEnd = true;
await sleep(20000);
if (await findTotalNumber() === maxEnterCount + 1) break;
else enterCount--;
}
}
}
async function confirmSearchResult() {
for (let i = 0; i < 4; i++) {
const gameRegion = captureGameRegion();
const res = gameRegion.find(requestEnter2Ro);
gameRegion.dispose();
if (res.isExist()) return false;
if (i < 4) await sleep(250);
}
return true;
}
async function isYUI() {
for (let i = 0; i < 5; i++) {
const gameRegion = captureGameRegion();
const res = gameRegion.find(yUIRo);
gameRegion.dispose();
if (res.isExist()) return true;
await sleep(250);
}
return false;
}
async function recognizeRequest() {
try {
const gameRegion = captureGameRegion();
for (const { ro, baseName } of targetsRo) {
if (gameRegion.find(ro).isExist()) { gameRegion.dispose(); return baseName; }
}
gameRegion.dispose();
} catch { }
try {
const gameRegion = captureGameRegion();
const resList = gameRegion.findMulti(RecognitionObject.ocr(650, 320, 350, 60));
gameRegion.dispose();
let hit = null;
for (const res of resList) {
const txt = res.text.trim();
if (targetList.includes(txt)) { hit = txt; break; }
}
if (!hit) resList.forEach(r => log.warn(`识别到"${r.text.trim()}",不在白名单`));
return hit;
} catch { return null; }
}
}
//切换队伍
async function switchPartyIfNeeded(partyName) {
if (!partyName) {
await genshin.returnMainUi();
return;
}
try {
log.info("正在尝试切换至" + partyName);
if (!await genshin.switchParty(partyName)) {
log.info("切换队伍失败,前往七天神像重试");
await genshin.tpToStatueOfTheSeven();
await genshin.switchParty(partyName);
}
} catch {
log.error("队伍切换失败,可能处于联机模式或其他不可切换状态");
notification.error(`队伍切换失败,可能处于联机模式或其他不可切换状态`);
await genshin.returnMainUi();
}
}
async function findAndClick(target, maxAttempts = 20) {
for (let attempts = 0; attempts < maxAttempts; attempts++) {
const gameRegion = captureGameRegion();
try {
const result = gameRegion.find(target);
if (result.isExist()) {
result.click();
return true; // 成功立刻返回
}
} catch (err) {
} finally {
gameRegion.dispose();
}
if (attempts < maxAttempts - 1) { // 最后一次不再 sleep
await sleep(250);
}
}
//log.error("已达到重试次数上限,仍未找到目标");
return false;
}
//等待主界面状态
async function waitForMainUI(requirement, timeOut = 60 * 1000) {
log.info(`等待至多${timeOut}毫秒`)
const startTime = Date.now();
while (Date.now() - startTime < timeOut) {
const mainUIState = await isMainUI();
if (mainUIState === requirement) return true;
const elapsed = Date.now() - startTime;
const min = Math.floor(elapsed / 60000);
const sec = Math.floor((elapsed % 60000) / 1000);
const ms = elapsed % 1000;
log.info(`已等待 ${min}分 ${sec}秒 ${ms}毫秒`);
await sleep(1000);
}
log.error("超时仍未到达指定状态");
return false;
}
//检查是否在主界面
async function isMainUI() {
// 修改后的图像路径
const imagePath = "assets/RecognitionObject/MainUI.png";
// 修改后的识别区域(左上角区域)
const xMin = 0;
const yMin = 0;
const width = 150; // 识别区域宽度
const height = 150; // 识别区域高度
let template = file.ReadImageMatSync(imagePath);
let recognitionObject = RecognitionObject.TemplateMatch(template, xMin, yMin, width, height);
// 尝试次数设置为 5 次
const maxAttempts = 5;
let attempts = 0;
while (attempts < maxAttempts) {
try {
let gameRegion = captureGameRegion();
let result = gameRegion.find(recognitionObject);
gameRegion.dispose();
if (result.isExist()) {
//log.info("处于主界面");
return true; // 如果找到图标,返回 true
}
} catch (error) {
log.error(`识别图像时发生异常: ${error.message}`);
return false; // 发生异常时返回 false
}
attempts++; // 增加尝试次数
await sleep(250); // 每次检测间隔 250 毫秒
}
return false; // 如果尝试次数达到上限或取消,返回 false
}
//获取联机世界的当前玩家标识
async function getPlayerSign() {
let attempts = 0;
let result = 0;
while (attempts < 5) {
attempts++;
const picDic = {
"0P": "assets/RecognitionObject/0P.png",
"1P": "assets/RecognitionObject/1P.png",
"2P": "assets/RecognitionObject/2P.png",
"3P": "assets/RecognitionObject/3P.png",
"4P": "assets/RecognitionObject/4P.png"
}
await genshin.returnMainUi();
await sleep(500);
const p0Ro = RecognitionObject.TemplateMatch(file.ReadImageMatSync(picDic["0P"]), 344, 22, 45, 45);
const p1Ro = RecognitionObject.TemplateMatch(file.ReadImageMatSync(picDic["1P"]), 344, 22, 45, 45);
const p2Ro = RecognitionObject.TemplateMatch(file.ReadImageMatSync(picDic["2P"]), 344, 22, 45, 45);
const p3Ro = RecognitionObject.TemplateMatch(file.ReadImageMatSync(picDic["3P"]), 344, 22, 45, 45);
const p4Ro = RecognitionObject.TemplateMatch(file.ReadImageMatSync(picDic["4P"]), 344, 22, 45, 45);
moveMouseTo(1555, 860); // 移走鼠标,防止干扰识别
const gameRegion = captureGameRegion();
// 当前页面模板匹配
let p0 = gameRegion.Find(p0Ro);
let p1 = gameRegion.Find(p1Ro);
let p2 = gameRegion.Find(p2Ro);
let p3 = gameRegion.Find(p3Ro);
let p4 = gameRegion.Find(p4Ro);
gameRegion.dispose();
if (p0.isExist()) { result = 0; break; }
if (p1.isExist()) { result = 1; break; }
if (p2.isExist()) { result = 2; break; }
if (p3.isExist()) { result = 3; break; }
if (p4.isExist()) { result = 4; break; }
}
return result;
}
async function findTotalNumber() {
await genshin.returnMainUi();
await keyPress("F2");
await sleep(2000);
// 定义模板
const kick2pRo = RecognitionObject.TemplateMatch(file.ReadImageMatSync("assets/RecognitionObject/kickButton.png"), 1520, 277, 230, 120);
const kick3pRo = RecognitionObject.TemplateMatch(file.ReadImageMatSync("assets/RecognitionObject/kickButton.png"), 1520, 400, 230, 120);
const kick4pRo = RecognitionObject.TemplateMatch(file.ReadImageMatSync("assets/RecognitionObject/kickButton.png"), 1520, 527, 230, 120);
moveMouseTo(1555, 860); // 防止鼠标干扰
const gameRegion = captureGameRegion();
await sleep(200);
let count = 1; // 先算上自己
// 依次匹配 2P
if (gameRegion.Find(kick2pRo).isExist()) {
log.info("发现 2P");
count++;
}
// 依次匹配 3P
if (gameRegion.Find(kick3pRo).isExist()) {
log.info("发现 3P");
count++;
}
// 依次匹配 4P
if (gameRegion.Find(kick4pRo).isExist()) {
log.info("发现 4P");
count++;
}
gameRegion.dispose();
log.info(`当前联机世界玩家总数(含自己):${count}`);
return count;
}
// fakeLog 函数,使用方法:将本函数放在主函数前,调用时请务必使用await,否则可能出现v8白框报错
//在js开头处伪造该js结束运行的日志信息,如 await fakeLog("js脚本", true, true, 0);
//在js结尾处伪造该js开始运行的日志信息,如 await fakeLog("js脚本", true, false, 2333);
//duration项目仅在伪造结束信息时有效,且无实际作用,可以任意填写,当你需要在日志中输出特定值时才需要,单位为毫秒
//在调用地图追踪前伪造该地图追踪开始运行的日志信息,如 await fakeLog(`地图追踪.json`, false, true, 0);
//在调用地图追踪后伪造该地图追踪结束运行的日志信息,如 await fakeLog(`地图追踪.json`, false, false, 0);
//如此便可以在js运行过程中伪造地图追踪的日志信息,可以在日志分析等中查看
async function fakeLog(name, isJs, isStart, duration) {
await sleep(10);
const currentTime = Date.now();
// 参数检查
if (typeof name !== 'string') {
log.error("参数 'name' 必须是字符串类型!");
return;
}
if (typeof isJs !== 'boolean') {
log.error("参数 'isJs' 必须是布尔型!");
return;
}
if (typeof isStart !== 'boolean') {
log.error("参数 'isStart' 必须是布尔型!");
return;
}
if (typeof currentTime !== 'number' || !Number.isInteger(currentTime)) {
log.error("参数 'currentTime' 必须是整数!");
return;
}
if (typeof duration !== 'number' || !Number.isInteger(duration)) {
log.error("参数 'duration' 必须是整数!");
return;
}
// 将 currentTime 转换为 Date 对象并格式化为 HH:mm:ss.sss
const date = new Date(currentTime);
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
const milliseconds = String(date.getMilliseconds()).padStart(3, '0');
const formattedTime = `${hours}:${minutes}:${seconds}.${milliseconds}`;
// 将 duration 转换为分钟和秒,并保留三位小数
const durationInSeconds = duration / 1000; // 转换为秒
const durationMinutes = Math.floor(durationInSeconds / 60);
const durationSeconds = (durationInSeconds % 60).toFixed(3); // 保留三位小数
// 使用四个独立的 if 语句处理四种情况
if (isJs && isStart) {
// 处理 isJs = true 且 isStart = true 的情况
const logMessage = `正在伪造js开始的日志记录\n\n` +
`[${formattedTime}] [INF] BetterGenshinImpact.Service.ScriptService\n` +
`------------------------------\n\n` +
`[${formattedTime}] [INF] BetterGenshinImpact.Service.ScriptService\n` +
`→ 开始执行JS脚本: "${name}"`;
log.debug(logMessage);
}
if (isJs && !isStart) {
// 处理 isJs = true 且 isStart = false 的情况
const logMessage = `正在伪造js结束的日志记录\n\n` +
`[${formattedTime}] [INF] BetterGenshinImpact.Service.ScriptService\n` +
`→ 脚本执行结束: "${name}", 耗时: ${durationMinutes}分${durationSeconds}秒\n\n` +
`[${formattedTime}] [INF] BetterGenshinImpact.Service.ScriptService\n` +
`------------------------------`;
log.debug(logMessage);
}
if (!isJs && isStart) {
// 处理 isJs = false 且 isStart = true 的情况
const logMessage = `正在伪造地图追踪开始的日志记录\n\n` +
`[${formattedTime}] [INF] BetterGenshinImpact.Service.ScriptService\n` +
`------------------------------\n\n` +
`[${formattedTime}] [INF] BetterGenshinImpact.Service.ScriptService\n` +
`→ 开始执行地图追踪任务: "${name}"`;
log.debug(logMessage);
}
if (!isJs && !isStart) {
// 处理 isJs = false 且 isStart = false 的情况
const logMessage = `正在伪造地图追踪结束的日志记录\n\n` +
`[${formattedTime}] [INF] BetterGenshinImpact.Service.ScriptService\n` +
`→ 脚本执行结束: "${name}", 耗时: ${durationMinutes}分${durationSeconds}秒\n\n` +
`[${formattedTime}] [INF] BetterGenshinImpact.Service.ScriptService\n` +
`------------------------------`;
log.debug(logMessage);
}
}
// 定义 readFolder 函数
async function readFolder(folderPath, onlyJson) {
// 新增一个堆栈,初始时包含 folderPath
const folderStack = [folderPath];
// 新增一个数组,用于存储文件信息对象
const files = [];
// 当堆栈不为空时,继续处理
while (folderStack.length > 0) {
// 从堆栈中弹出一个路径
const currentPath = folderStack.pop();
// 读取当前路径下的所有文件和子文件夹路径
const filesInSubFolder = file.ReadPathSync(currentPath);
// 临时数组,用于存储子文件夹路径
const subFolders = [];
for (const filePath of filesInSubFolder) {
if (file.IsFolder(filePath)) {
// 如果是文件夹,先存储到临时数组中
subFolders.push(filePath);
} else {
// 如果是文件,根据 onlyJson 判断是否存储
if (onlyJson) {
if (filePath.endsWith(".json")) {
const fileName = filePath.split('\\').pop(); // 提取文件名
const folderPathArray = filePath.split('\\').slice(0, -1); // 提取文件夹路径数组
files.push({
fullPath: filePath,
fileName: fileName,
folderPathArray: folderPathArray
});
//log.info(`找到 JSON 文件:${filePath}`);
}
} else {
const fileName = filePath.split('\\').pop(); // 提取文件名
const folderPathArray = filePath.split('\\').slice(0, -1); // 提取文件夹路径数组
files.push({
fullPath: filePath,
fileName: fileName,
folderPathArray: folderPathArray
});
//log.info(`找到文件:${filePath}`);
}
}
}
// 将临时数组中的子文件夹路径按原顺序压入堆栈
folderStack.push(...subFolders.reverse()); // 反转子文件夹路径
}
return files;
}
async function runPath(fullPath, targetItemPath) {
state = { running: true };
/* ---------- 主任务 ---------- */
const pathingTask = (async () => {
log.info(`开始执行路线: ${fullPath}`);
await fakeLog(fullPath, false, true, 0);
await pathingScript.runFile(fullPath);
await fakeLog(fullPath, false, false, 0);
state.running = false;
})();
/* ---------- 伴随任务 ---------- */
const pickupTask = (async () => {
await recognizeAndInteract();
})();
const errorProcessTask = (async () => {
const revivalRo1 = RecognitionObject.TemplateMatch(file.ReadImageMatSync("assets/RecognitionObject/revival1.png"));
let errorCheckCount = 9;
while (state.running) {
await sleep(100);
errorCheckCount++;
if (errorCheckCount > 50) {
errorCheckCount = 0;
//log.info("尝试识别并点击复苏按钮");
if (await findAndClick(revivalRo1, 2)) {
//log.info("识别到复苏按钮,点击复苏");
}
}
}
})();
/* ---------- 并发等待 ---------- */
await Promise.allSettled([pathingTask, pickupTask, errorProcessTask]);
}
//加载拾取物图片
async function loadTargetItems() {
const targetItemPath = 'assets/targetItems'; // 固定目录
const items = await readFolder(targetItemPath, false);
// 统一预加载模板
for (const it of items) {
it.template = file.ReadImageMatSync(it.fullPath);
it.itemName = it.fileName.replace(/\.png$/i, '');
}
return items;
}
// 定义一个函数用于拾取
async function recognizeAndInteract() {
//log.info("调试-开始执行图像识别与拾取任务");
let lastcenterYF = 0;
let lastItemName = "";
let fIcontemplate = file.ReadImageMatSync('assets/F_Dialogue.png');
let mainUITemplate = file.ReadImageMatSync("assets/MainUI.png");
let thisMoveUpTime = 0;
let lastMoveDown = 0;
gameRegion = captureGameRegion();
//主循环
while (state.running) {
gameRegion.dispose();
gameRegion = captureGameRegion();
let centerYF = await findFIcon();
if (!centerYF) {
if (await isMainUI()) await keyMouseScript.runFile(`assets/滚轮下翻.json`);
continue;
}
//log.info(`调试-成功找到f图标,centerYF为${centerYF}`);
let foundTarget = false;
let itemName = await performTemplateMatch(centerYF);
if (itemName) {
//log.info(`调试-识别到物品${itemName}`);
if (Math.abs(lastcenterYF - centerYF) <= 20 && lastItemName === itemName) {
//log.info("调试-相同物品名和相近y坐标,本次不拾取");
await sleep(2 * pickupDelay);
lastcenterYF = -20;
lastItemName = null;
} else {
keyPress("F");
log.info(`交互或拾取:"${itemName}"`);
lastcenterYF = centerYF;
lastItemName = itemName;
await sleep(pickupDelay);
}
} else {
/*
log.info("识别失败,尝试截图");
await refreshTargetItems(centerYF);
lastItemName = "";
*/
}
if (!foundTarget) {
//log.info(`调试-执行滚轮动作`);
const currentTime = new Date().getTime();
if (currentTime - lastMoveDown > timeMoveUp) {
await keyMouseScript.runFile(`assets/滚轮下翻.json`);
if (thisMoveUpTime === 0) thisMoveUpTime = currentTime;
if (currentTime - thisMoveUpTime >= timeMoveDown) {
lastMoveDown = currentTime;
thisMoveUpTime = 0;
}
} else {
await keyMouseScript.runFile(`assets/滚轮上翻.json`);
}
await sleep(rollingDelay);
}
}
async function performTemplateMatch(centerYF) {
try {
let result;
let itemName = null;
for (const targetItem of targetItems) {
let recognitionObject = RecognitionObject.TemplateMatch(targetItem.template, 1219, centerYF - 15, 32 + 30 * (targetItem.itemName.length) + 2, 30);
recognitionObject.Threshold = 0.9;
recognitionObject.InitTemplate();
result = gameRegion.find(recognitionObject);
if (result.isExist()) {
itemName = targetItem.itemName;
break;
}
}
return itemName;
} catch (error) {
log.error(`模板匹配时发生异常: ${error.message}`);
return null;
}
}
async function findFIcon() {
let recognitionObject = RecognitionObject.TemplateMatch(fIcontemplate, 1102, 335, 34, 400);
recognitionObject.Threshold = 0.95;
recognitionObject.InitTemplate();
try {
let result = gameRegion.find(recognitionObject);
if (result.isExist()) {
return Math.round(result.y + result.height / 2);
}
} catch (error) {
log.error(`识别图像时发生异常: ${error.message}`);
if (!state.running)
return null;
}
await sleep(100);
return null;
}
async function isMainUI() {
const recognitionObject = RecognitionObject.TemplateMatch(mainUITemplate, 0, 0, 150, 150);
const maxAttempts = 1;
let attempts = 0;
while (attempts < maxAttempts && state.running) {
try {
const result = gameRegion.find(recognitionObject);
if (result.isExist()) return true;
} catch (error) {
log.error(`识别图像时发生异常: ${error.message}`);
if (!state.running) break;
return false;
}
attempts++;
await sleep(50);
}
return false;
}
} | 412 | 0.812083 | 1 | 0.812083 | game-dev | MEDIA | 0.4758 | game-dev | 0.884914 | 1 | 0.884914 |
0x0ade/CelesteNet | 1,972 | CelesteNet.Server.FrontendModule/WSCMDs/WSCMDChatX.cs | using System;
using System.Linq;
using Celeste.Mod.CelesteNet.DataTypes;
using Celeste.Mod.CelesteNet.Server.Chat;
using Newtonsoft.Json.Linq;
namespace Celeste.Mod.CelesteNet.Server.Control {
public class WSCMDChatX : WSCMD {
public override bool MustAuth => true;
public override object? Run(dynamic? input) {
if (input == null)
return null;
string? text = input.Text;
string? tag = input.Tag;
string? color = input.Color;
JArray? targets = input.Targets;
ChatModule chat = Frontend.Server.Get<ChatModule>();
DataChat msg = new()
{
Text = text ?? "",
Tag = tag ?? "",
Color = chat.Settings.ColorBroadcast
};
if (!string.IsNullOrEmpty(color))
msg.Color = ColorHelpers.HexToColor(color!);
if (targets != null && targets.Count > 0)
{
uint[] targetIDs = targets
.Where(el => el.Type == JTokenType.Integer)
.Select(el => {
try {
return el.Value<uint>();
} catch (OverflowException) {
return 0u;
}
})
.Where(id => id != 0u)
.ToArray();
DataPlayerInfo[] targetSessions = Frontend.Server.Sessions
.Where(s => targetIDs.Contains(s.SessionID) && s.PlayerInfo != null)
.Select(s => s.PlayerInfo!)
.ToArray();
if (targetSessions.Length == 0)
// the message would reach 0 players
return null;
msg.Targets = targetSessions;
}
chat.Broadcast(msg);
return msg.ToDetailedFrontendChat();
}
}
}
| 412 | 0.878603 | 1 | 0.878603 | game-dev | MEDIA | 0.601443 | game-dev | 0.893801 | 1 | 0.893801 |
EphemeralSpace/ephemeral-space | 2,686 | Content.Server/NPC/Systems/NPCRetaliationSystem.cs | using Content.Server.NPC.Components;
using Content.Shared.CombatMode;
using Content.Shared.Damage;
using Content.Shared.Mobs.Components;
using Content.Shared.NPC.Components;
using Content.Shared.NPC.Systems;
using Robust.Shared.Collections;
using Robust.Shared.Timing;
namespace Content.Server.NPC.Systems;
/// <summary>
/// Handles NPC which become aggressive after being attacked.
/// </summary>
public sealed class NPCRetaliationSystem : EntitySystem
{
[Dependency] private readonly NpcFactionSystem _npcFaction = default!;
[Dependency] private readonly IGameTiming _timing = default!;
/// <inheritdoc />
public override void Initialize()
{
SubscribeLocalEvent<NPCRetaliationComponent, DamageChangedEvent>(OnDamageChanged);
SubscribeLocalEvent<NPCRetaliationComponent, DisarmedEvent>(OnDisarmed);
}
private void OnDamageChanged(Entity<NPCRetaliationComponent> ent, ref DamageChangedEvent args)
{
if (!args.DamageIncreased)
return;
if (args.Origin is not {} origin)
return;
TryRetaliate(ent, origin);
}
private void OnDisarmed(Entity<NPCRetaliationComponent> ent, ref DisarmedEvent args)
{
TryRetaliate(ent, args.Source);
}
public bool TryRetaliate(Entity<NPCRetaliationComponent> ent, EntityUid target)
{
// don't retaliate against inanimate objects.
if (!HasComp<MobStateComponent>(target))
return false;
// don't retaliate against the same faction
if (_npcFaction.IsEntityFriendly(ent.Owner, target))
return false;
_npcFaction.AggroEntity(ent.Owner, target);
if (ent.Comp.AttackMemoryLength is {} memoryLength)
ent.Comp.AttackMemories[target] = _timing.CurTime + memoryLength;
return true;
}
public override void Update(float frameTime)
{
base.Update(frameTime);
var query = EntityQueryEnumerator<NPCRetaliationComponent, FactionExceptionComponent>();
while (query.MoveNext(out var uid, out var retaliationComponent, out var factionException))
{
// TODO: can probably reuse this allocation and clear it
foreach (var entity in new ValueList<EntityUid>(retaliationComponent.AttackMemories.Keys))
{
if (!TerminatingOrDeleted(entity) && _timing.CurTime < retaliationComponent.AttackMemories[entity])
continue;
_npcFaction.DeAggroEntity((uid, factionException), entity);
// TODO: should probably remove the AttackMemory, thats the whole point of the ValueList right??
}
}
}
}
| 412 | 0.897278 | 1 | 0.897278 | game-dev | MEDIA | 0.992495 | game-dev | 0.860326 | 1 | 0.860326 |
Anuken/Arc | 12,801 | arc-core/src/arc/struct/BoolSeq.java | package arc.struct;
import arc.math.Mathf;
import java.util.BitSet;
/**
* A resizable, ordered or unordered boolean array. Avoids the boxing that occurs with ArrayList<Boolean>. It is less memory
* efficient than {@link BitSet}, except for very small sizes. It more CPU efficient than {@link BitSet}, except for very large
* sizes or if BitSet functionality such as and, or, xor, etc are needed. If unordered, this class avoids a memory copy when
* removing elements (the last element is moved to the removed element's position).
* @author Nathan Sweet
*/
public class BoolSeq{
public boolean[] items;
public int size;
public boolean ordered;
/** Creates an ordered array with a capacity of 16. */
public BoolSeq(){
this(true, 16);
}
/** Creates an ordered array with the specified capacity. */
public BoolSeq(int capacity){
this(true, capacity);
}
/**
* @param ordered If false, methods that remove elements may change the order of other elements in the array, which avoids a
* memory copy.
* @param capacity Any elements added beyond this will cause the backing array to be grown.
*/
public BoolSeq(boolean ordered, int capacity){
this.ordered = ordered;
items = new boolean[capacity];
}
/**
* Creates a new array containing the elements in the specific array. The new array will be ordered if the specific array is
* ordered. The capacity is set to the number of elements, so any subsequent elements added will cause the backing array to be
* grown.
*/
public BoolSeq(BoolSeq array){
this.ordered = array.ordered;
size = array.size;
items = new boolean[size];
System.arraycopy(array.items, 0, items, 0, size);
}
/**
* Creates a new ordered array containing the elements in the specified array. The capacity is set to the number of elements,
* so any subsequent elements added will cause the backing array to be grown.
*/
public BoolSeq(boolean[] array){
this(true, array, 0, array.length);
}
/**
* Creates a new array containing the elements in the specified array. The capacity is set to the number of elements, so any
* subsequent elements added will cause the backing array to be grown.
* @param ordered If false, methods that remove elements may change the order of other elements in the array, which avoids a
* memory copy.
*/
public BoolSeq(boolean ordered, boolean[] array, int startIndex, int count){
this(ordered, count);
size = count;
System.arraycopy(array, startIndex, items, 0, count);
}
/** @see #BoolSeq(boolean[]) */
public static BoolSeq with(boolean... array){
return new BoolSeq(array);
}
public void add(boolean value){
boolean[] items = this.items;
if(size == items.length) items = resize(Math.max(8, (int)(size * 1.75f)));
items[size++] = value;
}
public void add(boolean value1, boolean value2){
boolean[] items = this.items;
if(size + 1 >= items.length) items = resize(Math.max(8, (int)(size * 1.75f)));
items[size] = value1;
items[size + 1] = value2;
size += 2;
}
public void add(boolean value1, boolean value2, boolean value3){
boolean[] items = this.items;
if(size + 2 >= items.length) items = resize(Math.max(8, (int)(size * 1.75f)));
items[size] = value1;
items[size + 1] = value2;
items[size + 2] = value3;
size += 3;
}
public void add(boolean value1, boolean value2, boolean value3, boolean value4){
boolean[] items = this.items;
if(size + 3 >= items.length) items = resize(Math.max(8, (int)(size * 1.8f))); // 1.75 isn't enough when size=5.
items[size] = value1;
items[size + 1] = value2;
items[size + 2] = value3;
items[size + 3] = value4;
size += 4;
}
public void addAll(BoolSeq array){
addAll(array.items, 0, array.size);
}
public void addAll(BoolSeq array, int offset, int length){
if(offset + length > array.size)
throw new IllegalArgumentException("offset + length must be <= size: " + offset + " + " + length + " <= " + array.size);
addAll(array.items, offset, length);
}
public void addAll(boolean... array){
addAll(array, 0, array.length);
}
public void addAll(boolean[] array, int offset, int length){
boolean[] items = this.items;
int sizeNeeded = size + length;
if(sizeNeeded > items.length) items = resize(Math.max(8, (int)(sizeNeeded * 1.75f)));
System.arraycopy(array, offset, items, size, length);
size += length;
}
public boolean get(int index){
if(index >= size) throw new IndexOutOfBoundsException("index can't be >= size: " + index + " >= " + size);
return items[index];
}
public void set(int index, boolean value){
if(index >= size) throw new IndexOutOfBoundsException("index can't be >= size: " + index + " >= " + size);
items[index] = value;
}
public void insert(int index, boolean value){
if(index > size) throw new IndexOutOfBoundsException("index can't be > size: " + index + " > " + size);
boolean[] items = this.items;
if(size == items.length) items = resize(Math.max(8, (int)(size * 1.75f)));
if(ordered)
System.arraycopy(items, index, items, index + 1, size - index);
else
items[size] = items[index];
size++;
items[index] = value;
}
public void swap(int first, int second){
if(first >= size) throw new IndexOutOfBoundsException("first can't be >= size: " + first + " >= " + size);
if(second >= size) throw new IndexOutOfBoundsException("second can't be >= size: " + second + " >= " + size);
boolean[] items = this.items;
boolean firstValue = items[first];
items[first] = items[second];
items[second] = firstValue;
}
/** Removes and returns the item at the specified index. */
public boolean removeIndex(int index){
if(index >= size) throw new IndexOutOfBoundsException("index can't be >= size: " + index + " >= " + size);
boolean[] items = this.items;
boolean value = items[index];
size--;
if(ordered)
System.arraycopy(items, index + 1, items, index, size - index);
else
items[index] = items[size];
return value;
}
/** Removes the items between the specified indices, inclusive. */
public void removeRange(int start, int end){
if(end >= size) throw new IndexOutOfBoundsException("end can't be >= size: " + end + " >= " + size);
if(start > end) throw new IndexOutOfBoundsException("start can't be > end: " + start + " > " + end);
boolean[] items = this.items;
int count = end - start + 1;
if(ordered)
System.arraycopy(items, start + count, items, start, size - (start + count));
else{
int lastIndex = this.size - 1;
for(int i = 0; i < count; i++)
items[start + i] = items[lastIndex - i];
}
size -= count;
}
/**
* Removes from this array all of elements contained in the specified array.
* @return true if this array was modified.
*/
public boolean removeAll(BoolSeq array){
int size = this.size;
int startSize = size;
boolean[] items = this.items;
for(int i = 0, n = array.size; i < n; i++){
boolean item = array.get(i);
for(int ii = 0; ii < size; ii++){
if(item == items[ii]){
removeIndex(ii);
size--;
break;
}
}
}
return size != startSize;
}
/** Removes and returns the last item. */
public boolean pop(){
return items[--size];
}
/** Returns the last item. */
public boolean peek(){
return items[size - 1];
}
/** Returns the first item. */
public boolean first(){
if(size == 0) throw new IllegalStateException("Array is empty.");
return items[0];
}
/** Returns true if the array is empty. */
public boolean isEmpty(){
return size == 0;
}
public void clear(){
size = 0;
}
/**
* Reduces the size of the backing array to the size of the actual items. This is useful to release memory when many items
* have been removed, or if it is known that more items will not be added.
* @return {@link #items}
*/
public boolean[] shrink(){
if(items.length != size) resize(size);
return items;
}
/**
* Increases the size of the backing array to accommodate the specified number of additional items. Useful before adding many
* items to avoid multiple backing array resizes.
* @return {@link #items}
*/
public boolean[] ensureCapacity(int additionalCapacity){
if(additionalCapacity < 0)
throw new IllegalArgumentException("additionalCapacity must be >= 0: " + additionalCapacity);
int sizeNeeded = size + additionalCapacity;
if(sizeNeeded > items.length) resize(Math.max(8, sizeNeeded));
return items;
}
/**
* Sets the array size, leaving any values beyond the current size undefined.
* @return {@link #items}
*/
public boolean[] setSize(int newSize){
if(newSize < 0) throw new IllegalArgumentException("newSize must be >= 0: " + newSize);
if(newSize > items.length) resize(Math.max(8, newSize));
size = newSize;
return items;
}
protected boolean[] resize(int newSize){
boolean[] newItems = new boolean[newSize];
boolean[] items = this.items;
System.arraycopy(items, 0, newItems, 0, Math.min(size, newItems.length));
this.items = newItems;
return newItems;
}
public void reverse(){
boolean[] items = this.items;
for(int i = 0, lastIndex = size - 1, n = size / 2; i < n; i++){
int ii = lastIndex - i;
boolean temp = items[i];
items[i] = items[ii];
items[ii] = temp;
}
}
public void shuffle(){
boolean[] items = this.items;
for(int i = size - 1; i >= 0; i--){
int ii = Mathf.random(i);
boolean temp = items[i];
items[i] = items[ii];
items[ii] = temp;
}
}
/**
* Reduces the size of the array to the specified size. If the array is already smaller than the specified size, no action is
* taken.
*/
public void truncate(int newSize){
if(size > newSize) size = newSize;
}
/** Returns a random item from the array, or false if the array is empty. */
public boolean random(){
if(size == 0) return false;
return items[Mathf.random(0, size - 1)];
}
public boolean[] toArray(){
boolean[] array = new boolean[size];
System.arraycopy(items, 0, array, 0, size);
return array;
}
public int hashCode(){
if(!ordered) return super.hashCode();
boolean[] items = this.items;
int h = 1;
for(int i = 0, n = size; i < n; i++)
h = h * 31 + (items[i] ? 1231 : 1237);
return h;
}
public boolean equals(Object object){
if(object == this) return true;
if(!ordered) return false;
if(!(object instanceof BoolSeq)) return false;
BoolSeq array = (BoolSeq)object;
if(!array.ordered) return false;
int n = size;
if(n != array.size) return false;
boolean[] items1 = this.items;
boolean[] items2 = array.items;
for(int i = 0; i < n; i++)
if(items1[i] != items2[i]) return false;
return true;
}
public String toString(){
if(size == 0) return "[]";
boolean[] items = this.items;
StringBuilder buffer = new StringBuilder(32);
buffer.append('[');
buffer.append(items[0]);
for(int i = 1; i < size; i++){
buffer.append(", ");
buffer.append(items[i]);
}
buffer.append(']');
return buffer.toString();
}
public String toString(String separator){
if(size == 0) return "";
boolean[] items = this.items;
StringBuilder buffer = new StringBuilder(32);
buffer.append(items[0]);
for(int i = 1; i < size; i++){
buffer.append(separator);
buffer.append(items[i]);
}
return buffer.toString();
}
}
| 412 | 0.8032 | 1 | 0.8032 | game-dev | MEDIA | 0.39724 | game-dev | 0.957301 | 1 | 0.957301 |
mgschwan/blensor | 8,793 | release/scripts/addons/rigify/rigs/limbs/super_limb.py | import bpy
from .arm import Rig as armRig
from .leg import Rig as legRig
from .paw import Rig as pawRig
class Rig:
def __init__(self, obj, bone_name, params):
""" Initialize super_limb rig wrapper class """
self.obj = obj
self.params = params
if params.limb_type == 'arm':
self.limb = armRig(obj, bone_name, params)
elif params.limb_type == 'leg':
self.limb = legRig(obj, bone_name, params)
elif params.limb_type == 'paw':
self.limb = pawRig(obj, bone_name, params)
def generate(self):
return self.limb.generate()
@staticmethod
def get_future_names(bones):
if bones[0].rigify_parameters.limb_type == 'arm':
return armRig.get_future_names(bones)
elif bones[0].rigify_parameters.limb_type == 'leg':
return legRig.get_future_names(bones)
elif bones[0].rigify_parameters.limb_type == 'paw':
return pawRig.get_future_names(bones)
def add_parameters(params):
""" Add the parameters of this rig type to the
RigifyParameters PropertyGroup
"""
items = [
('arm', 'Arm', ''),
('leg', 'Leg', ''),
('paw', 'Paw', '')
]
params.limb_type = bpy.props.EnumProperty(
items = items,
name = "Limb Type",
default = 'arm'
)
items = [
('x', 'X manual', ''),
('z', 'Z manual', ''),
('automatic', 'Automatic', '')
]
params.rotation_axis = bpy.props.EnumProperty(
items = items,
name = "Rotation Axis",
default = 'automatic'
)
params.auto_align_extremity = bpy.props.BoolProperty(
name='auto_align_extremity',
default=False,
description="Auto Align Extremity Bone"
)
params.segments = bpy.props.IntProperty(
name = 'limb segments',
default = 2,
min = 1,
description = 'Number of segments'
)
params.bbones = bpy.props.IntProperty(
name = 'bbone segments',
default = 10,
min = 1,
description = 'Number of segments'
)
# Setting up extra layers for the FK and tweak
params.tweak_extra_layers = bpy.props.BoolProperty(
name = "tweak_extra_layers",
default = True,
description = ""
)
params.tweak_layers = bpy.props.BoolVectorProperty(
size = 32,
description = "Layers for the tweak controls to be on",
default = tuple( [ i == 1 for i in range(0, 32) ] )
)
# Setting up extra layers for the FK and tweak
params.fk_extra_layers = bpy.props.BoolProperty(
name = "fk_extra_layers",
default = True,
description = ""
)
params.fk_layers = bpy.props.BoolVectorProperty(
size = 32,
description = "Layers for the FK controls to be on",
default = tuple( [ i == 1 for i in range(0, 32) ] )
)
def parameters_ui(layout, params):
""" Create the ui for the rig parameters."""
r = layout.row()
r.prop(params, "limb_type")
r = layout.row()
r.prop(params, "rotation_axis")
if 'auto' not in params.rotation_axis.lower():
r = layout.row()
etremities = {'arm': 'Hand', 'leg': 'Foot', 'paw': 'Claw'}
text = "Auto align " + etremities[params.limb_type]
r.prop(params, "auto_align_extremity", text=text)
r = layout.row()
r.prop(params, "segments")
r = layout.row()
r.prop(params, "bbones")
bone_layers = bpy.context.active_pose_bone.bone.layers[:]
for layer in ['fk', 'tweak']:
r = layout.row()
r.prop(params, layer + "_extra_layers")
r.active = params.tweak_extra_layers
col = r.column(align=True)
row = col.row(align=True)
for i in range(8):
icon = "NONE"
if bone_layers[i]:
icon = "LAYER_ACTIVE"
row.prop(params, layer + "_layers", index=i, toggle=True, text="", icon=icon)
row = col.row(align=True)
for i in range(16,24):
icon = "NONE"
if bone_layers[i]:
icon = "LAYER_ACTIVE"
row.prop(params, layer + "_layers", index=i, toggle=True, text="", icon=icon)
col = r.column(align=True)
row = col.row(align=True)
for i in range(8,16):
icon = "NONE"
if bone_layers[i]:
icon = "LAYER_ACTIVE"
row.prop(params, layer + "_layers", index=i, toggle=True, text="", icon=icon)
row = col.row(align=True)
for i in range(24,32):
icon = "NONE"
if bone_layers[i]:
icon = "LAYER_ACTIVE"
row.prop(params, layer + "_layers", index=i, toggle=True, text="", icon=icon)
def create_sample(obj):
# generated by rigify.utils.write_metarig
bpy.ops.object.mode_set(mode='EDIT')
arm = obj.data
bones = {}
bone = arm.edit_bones.new('upper_arm.L')
bone.head[:] = -0.0016, 0.0060, -0.0012
bone.tail[:] = 0.2455, 0.0678, -0.1367
bone.roll = 2.0724
bone.use_connect = False
bones['upper_arm.L'] = bone.name
bone = arm.edit_bones.new('forearm.L')
bone.head[:] = 0.2455, 0.0678, -0.1367
bone.tail[:] = 0.4625, 0.0285, -0.2797
bone.roll = 2.1535
bone.use_connect = True
bone.parent = arm.edit_bones[bones['upper_arm.L']]
bones['forearm.L'] = bone.name
bone = arm.edit_bones.new('hand.L')
bone.head[:] = 0.4625, 0.0285, -0.2797
bone.tail[:] = 0.5265, 0.0205, -0.3273
bone.roll = 2.2103
bone.use_connect = True
bone.parent = arm.edit_bones[bones['forearm.L']]
bones['hand.L'] = bone.name
bpy.ops.object.mode_set(mode='OBJECT')
pbone = obj.pose.bones[bones['upper_arm.L']]
pbone.rigify_type = 'limbs.super_limb'
pbone.lock_location = (False, False, False)
pbone.lock_rotation = (False, False, False)
pbone.lock_rotation_w = False
pbone.lock_scale = (False, False, False)
pbone.rotation_mode = 'QUATERNION'
try:
pbone.rigify_parameters.separate_ik_layers = True
except AttributeError:
pass
try:
pbone.rigify_parameters.ik_layers = [
False, False, False, False, False, False, False, False, True, False,
False, False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False, False,
False, False
]
except AttributeError:
pass
try:
pbone.rigify_parameters.separate_hose_layers = True
except AttributeError:
pass
try:
pbone.rigify_parameters.hose_layers = [
False, False, False, False, False, False, False, False, False, True,
False, False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False, False,
False, False
]
except AttributeError:
pass
try:
pbone.rigify_parameters.tweak_layers = [
False, False, False, False, False, False, False, False, False, True,
False, False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False, False,
False, False
]
except AttributeError:
pass
try:
pbone.rigify_parameters.fk_layers = [
False, False, False, False, False, False, False, False, True, False,
False, False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False, False,
False, False
]
except AttributeError:
pass
pbone = obj.pose.bones[bones['forearm.L']]
pbone.rigify_type = ''
pbone.lock_location = (False, False, False)
pbone.lock_rotation = (False, False, False)
pbone.lock_rotation_w = False
pbone.lock_scale = (False, False, False)
pbone.rotation_mode = 'QUATERNION'
pbone = obj.pose.bones[bones['hand.L']]
pbone.rigify_type = ''
pbone.lock_location = (False, False, False)
pbone.lock_rotation = (False, False, False)
pbone.lock_rotation_w = False
pbone.lock_scale = (False, False, False)
pbone.rotation_mode = 'QUATERNION'
bpy.ops.object.mode_set(mode='EDIT')
for bone in arm.edit_bones:
bone.select = False
bone.select_head = False
bone.select_tail = False
for b in bones:
bone = arm.edit_bones[bones[b]]
bone.select = True
bone.select_head = True
bone.select_tail = True
arm.edit_bones.active = bone
| 412 | 0.702609 | 1 | 0.702609 | game-dev | MEDIA | 0.363244 | game-dev | 0.846376 | 1 | 0.846376 |
ellermister/MapleStory | 1,754 | scripts/event/KyrinTrainingGroundC.js | /**
Kyrin's Training Ground, 4th job Quest [Captain]
**/
function init() {}
function monsterValue(eim, mobId) {
return 1;
}
function setup() {
em.setProperty("started", "true");
var eim = em.newInstance("KyrinTrainingGroundC");
var map = eim.setInstanceMap(912010100);
map.resetFully();
map.respawn(true);
eim.startEventTimer(240000);
return eim;
}
function playerEntry(eim, player) {
var map = eim.getMapFactory().getMap(912010100);
player.changeMap(map, map.getPortal(0));
player.dropMessage(6, "You must endure Kyrin's attacks for more than 2 minuets!");
}
function playerDead(eim, player) {}
function playerRevive(eim, player) {}
function scheduledTimeout(eim) {
eim.disposeIfPlayerBelow(100, 120000101);
em.setProperty("started", "false");
}
function changedMap(eim, player, mapid) {
if (mapid != 912010100) {
eim.unregisterPlayer(player);
if (eim.disposeIfPlayerBelow(0, 0)) {
em.setProperty("started", "false");
}
}
}
function playerDisconnected(eim, player) {
return 0;
}
function leftParty(eim, player) {
// If only 2 players are left, uncompletable:
playerExit(eim, player);
}
function disbandParty(eim) {
//boot whole party and end
eim.disposeIfPlayerBelow(100, 120000101);
em.setProperty("started", "false");
}
function playerExit(eim, player) {
eim.unregisterPlayer(player);
var map = eim.getMapFactory().getMap(120000101);
player.changeMap(map, map.getPortal(0));
}
function clearPQ(eim) {
eim.disposeIfPlayerBelow(100, 120000101);
em.setProperty("started", "false");
}
function allMonstersDead(eim) {
//has nothing to do with monster killing
}
function cancelSchedule() {} | 412 | 0.742156 | 1 | 0.742156 | game-dev | MEDIA | 0.885684 | game-dev | 0.950678 | 1 | 0.950678 |
mc-zhonghuang/Urticaria-Public | 8,837 | src/main/java/net/minecraft/client/entity/AbstractClientPlayer.java | package net.minecraft.client.entity;
import cn.hackedmc.urticaria.Client;
import cn.hackedmc.urticaria.module.impl.render.NoFOV;
import cn.hackedmc.urticaria.newevent.impl.render.LookEvent;
import cn.hackedmc.urticaria.util.vector.Vector2f;
import com.mojang.authlib.GameProfile;
import net.minecraft.client.Minecraft;
import net.minecraft.client.network.NetworkPlayerInfo;
import net.minecraft.client.renderer.ImageBufferDownload;
import net.minecraft.client.renderer.ThreadDownloadImageData;
import net.minecraft.client.renderer.texture.ITextureObject;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.resources.DefaultPlayerSkin;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.attributes.IAttributeInstance;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.potion.Potion;
import net.minecraft.src.Config;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StringUtils;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import net.minecraft.world.WorldSettings;
import net.optifine.player.CapeUtils;
import net.optifine.player.PlayerConfigurations;
import net.optifine.reflect.Reflector;
public abstract class AbstractClientPlayer extends EntityPlayer {
private NetworkPlayerInfo playerInfo;
private ResourceLocation locationOfCape = null;
private long reloadCapeTimeMs = 0L;
private boolean elytraOfCape = false;
private String nameClear = null;
private static final ResourceLocation TEXTURE_ELYTRA = new ResourceLocation("textures/entity/elytra.png");
public AbstractClientPlayer(final World worldIn, final GameProfile playerProfile) {
super(worldIn, playerProfile);
this.nameClear = playerProfile.getName();
if (this.nameClear != null && !this.nameClear.isEmpty()) {
this.nameClear = StringUtils.stripControlCodes(this.nameClear);
}
CapeUtils.downloadCape(this);
PlayerConfigurations.getPlayerConfiguration(this);
}
/**
* Returns true if the player is in spectator mode.
*/
public boolean isSpectator() {
final NetworkPlayerInfo networkplayerinfo = Minecraft.getMinecraft().getNetHandler().getPlayerInfo(this.getGameProfile().getId());
return networkplayerinfo != null && networkplayerinfo.getGameType() == WorldSettings.GameType.SPECTATOR;
}
/**
* Checks if this instance of AbstractClientPlayer has any associated player data.
*/
public boolean hasPlayerInfo() {
return this.getPlayerInfo() != null;
}
protected NetworkPlayerInfo getPlayerInfo() {
if (this.playerInfo == null) {
this.playerInfo = Minecraft.getMinecraft().getNetHandler().getPlayerInfo(this.getUniqueID());
}
return this.playerInfo;
}
/**
* Returns true if the player has an associated skin.
*/
public boolean hasSkin() {
final NetworkPlayerInfo networkplayerinfo = this.getPlayerInfo();
return networkplayerinfo != null && networkplayerinfo.hasLocationSkin();
}
/**
* Returns true if the player instance has an associated skin.
*/
public ResourceLocation getLocationSkin() {
final NetworkPlayerInfo networkplayerinfo = this.getPlayerInfo();
return networkplayerinfo == null ? DefaultPlayerSkin.getDefaultSkin(this.getUniqueID()) : networkplayerinfo.getLocationSkin();
}
public ResourceLocation getLocationCape() {
if (!Config.isShowCapes()) {
return null;
} else {
if (this.reloadCapeTimeMs != 0L && System.currentTimeMillis() > this.reloadCapeTimeMs) {
CapeUtils.reloadCape(this);
this.reloadCapeTimeMs = 0L;
}
if (this.locationOfCape != null) {
return this.locationOfCape;
} else {
final NetworkPlayerInfo networkplayerinfo = this.getPlayerInfo();
return networkplayerinfo == null ? null : networkplayerinfo.getLocationCape();
}
}
}
public static ThreadDownloadImageData getDownloadImageSkin(final ResourceLocation resourceLocationIn, final String username) {
final TextureManager texturemanager = Minecraft.getMinecraft().getTextureManager();
ITextureObject itextureobject = texturemanager.getTexture(resourceLocationIn);
if (itextureobject == null) {
itextureobject = new ThreadDownloadImageData(null, String.format("http://skins.minecraft.net/MinecraftSkins/%s.png", StringUtils.stripControlCodes(username)), DefaultPlayerSkin.getDefaultSkin(getOfflineUUID(username)), new ImageBufferDownload());
texturemanager.loadTexture(resourceLocationIn, itextureobject);
}
return (ThreadDownloadImageData) itextureobject;
}
/**
* Returns true if the username has an associated skin.
*
* @param username The username of the player being checked.
*/
public static ResourceLocation getLocationSkin(final String username) {
return new ResourceLocation("skins/" + StringUtils.stripControlCodes(username));
}
public String getSkinType() {
final NetworkPlayerInfo networkplayerinfo = this.getPlayerInfo();
return networkplayerinfo == null ? DefaultPlayerSkin.getSkinType(this.getUniqueID()) : networkplayerinfo.getSkinType();
}
public float getFovModifier() {
if (NoFOV.INSTANCE.isEnabled()) {
float newFOV = NoFOV.INSTANCE.fov.getValue().floatValue();
if (!this.isUsingItem()) {
return newFOV;
}
if (this.getItemInUse().getItem() != Items.bow) {
return newFOV;
}
int i = this.getItemInUseCount();
float f1 = (float) i / 20.0f;
f1 = f1 > 1.0f ? 1.0f : f1 * f1;
newFOV *= 1.0f - f1 * 0.15f;
return newFOV;
} else {
float f = 1.0F;
if (this.capabilities.isFlying) {
f *= 1.1F;
}
final IAttributeInstance iattributeinstance = this.getEntityAttribute(SharedMonsterAttributes.movementSpeed);
double attributeValue = iattributeinstance.getAttributeValue();
if (isPotionActive(Potion.moveSpeed)) {
final int modifier = getActivePotionEffect(Potion.moveSpeed).getAmplifier() + 1;
attributeValue /= 1.0D + (modifier * 0.20000000298023224D);
}
f = (float) ((double) f * ((attributeValue / (double) this.capabilities.getWalkSpeed() + 1.0D) / 2.0D));
if (this.capabilities.getWalkSpeed() == 0.0F || Float.isNaN(f) || Float.isInfinite(f)) {
f = 1.0F;
}
if (this.isUsingItem() && this.getItemInUse().getItem() == Items.bow) {
final int i = this.getItemInUseDuration();
float f1 = (float) i / 20.0F;
if (f1 > 1.0F) {
f1 = 1.0F;
} else {
f1 = f1 * f1;
}
f *= 1.0F - f1 * 0.15F;
}
return Reflector.ForgeHooksClient_getOffsetFOV.exists() ? Reflector.callFloat(Reflector.ForgeHooksClient_getOffsetFOV, this, Float.valueOf(f)) : f;
}
}
public String getNameClear() {
return this.nameClear;
}
public ResourceLocation getLocationOfCape() {
return this.locationOfCape;
}
public void setLocationOfCape(final ResourceLocation p_setLocationOfCape_1_) {
this.locationOfCape = p_setLocationOfCape_1_;
}
public boolean hasElytraCape() {
final ResourceLocation resourcelocation = this.getLocationCape();
return resourcelocation != null && (resourcelocation != this.locationOfCape || this.elytraOfCape);
}
public void setElytraOfCape(final boolean p_setElytraOfCape_1_) {
this.elytraOfCape = p_setElytraOfCape_1_;
}
public boolean isElytraOfCape() {
return this.elytraOfCape;
}
public long getReloadCapeTimeMs() {
return this.reloadCapeTimeMs;
}
public void setReloadCapeTimeMs(final long p_setReloadCapeTimeMs_1_) {
this.reloadCapeTimeMs = p_setReloadCapeTimeMs_1_;
}
/**
* interpolated look vector
*/
public Vec3 getLook(final float partialTicks) {
float yaw = this.rotationYaw;
float pitch = this.rotationPitch;
LookEvent lookEvent = new LookEvent(new Vector2f(yaw, pitch));
Client.INSTANCE.getEventBus().handle(lookEvent);
yaw = lookEvent.getRotation().x;
pitch = lookEvent.getRotation().y;
return this.getVectorForRotation(pitch, yaw);
}
}
| 412 | 0.949721 | 1 | 0.949721 | game-dev | MEDIA | 0.864966 | game-dev | 0.973242 | 1 | 0.973242 |
motorsep/StormEngine2 | 8,809 | neo/libs/SDL2/include/SDL_main.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2022 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef SDL_main_h_
#define SDL_main_h_
#include "SDL_stdinc.h"
/**
* \file SDL_main.h
*
* Redefine main() on some platforms so that it is called by SDL.
*/
#ifndef SDL_MAIN_HANDLED
#if defined(__WIN32__)
/* On Windows SDL provides WinMain(), which parses the command line and passes
the arguments to your main function.
If you provide your own WinMain(), you may define SDL_MAIN_HANDLED
*/
#define SDL_MAIN_AVAILABLE
#elif defined(__WINRT__)
/* On WinRT, SDL provides a main function that initializes CoreApplication,
creating an instance of IFrameworkView in the process.
Please note that #include'ing SDL_main.h is not enough to get a main()
function working. In non-XAML apps, the file,
src/main/winrt/SDL_WinRT_main_NonXAML.cpp, or a copy of it, must be compiled
into the app itself. In XAML apps, the function, SDL_WinRTRunApp must be
called, with a pointer to the Direct3D-hosted XAML control passed in.
*/
#define SDL_MAIN_NEEDED
#elif defined(__GDK__)
/* On GDK, SDL provides a main function that initializes the game runtime.
Please note that #include'ing SDL_main.h is not enough to get a main()
function working. You must either link against SDL2main or, if not possible,
call the SDL_GDKRunApp function from your entry point.
*/
#define SDL_MAIN_NEEDED
#elif defined(__IPHONEOS__)
/* On iOS SDL provides a main function that creates an application delegate
and starts the iOS application run loop.
If you link with SDL dynamically on iOS, the main function can't be in a
shared library, so you need to link with libSDLmain.a, which includes a
stub main function that calls into the shared library to start execution.
See src/video/uikit/SDL_uikitappdelegate.m for more details.
*/
#define SDL_MAIN_NEEDED
#elif defined(__ANDROID__)
/* On Android SDL provides a Java class in SDLActivity.java that is the
main activity entry point.
See docs/README-android.md for more details on extending that class.
*/
#define SDL_MAIN_NEEDED
/* We need to export SDL_main so it can be launched from Java */
#define SDLMAIN_DECLSPEC DECLSPEC
#elif defined(__NACL__)
/* On NACL we use ppapi_simple to set up the application helper code,
then wait for the first PSE_INSTANCE_DIDCHANGEVIEW event before
starting the user main function.
All user code is run in a separate thread by ppapi_simple, thus
allowing for blocking io to take place via nacl_io
*/
#define SDL_MAIN_NEEDED
#elif defined(__PSP__)
/* On PSP SDL provides a main function that sets the module info,
activates the GPU and starts the thread required to be able to exit
the software.
If you provide this yourself, you may define SDL_MAIN_HANDLED
*/
#define SDL_MAIN_AVAILABLE
#elif defined(__PS2__)
#define SDL_MAIN_AVAILABLE
#define SDL_PS2_SKIP_IOP_RESET() \
void reset_IOP(); \
void reset_IOP() {}
#elif defined(__3DS__)
/*
On N3DS, SDL provides a main function that sets up the screens
and storage.
If you provide this yourself, you may define SDL_MAIN_HANDLED
*/
#define SDL_MAIN_AVAILABLE
#endif
#endif /* SDL_MAIN_HANDLED */
#ifndef SDLMAIN_DECLSPEC
#define SDLMAIN_DECLSPEC
#endif
/**
* \file SDL_main.h
*
* The application's main() function must be called with C linkage,
* and should be declared like this:
* \code
* #ifdef __cplusplus
* extern "C"
* #endif
* int main(int argc, char *argv[])
* {
* }
* \endcode
*/
#if defined(SDL_MAIN_NEEDED) || defined(SDL_MAIN_AVAILABLE)
#define main SDL_main
#endif
#include "begin_code.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* The prototype for the application's main() function
*/
typedef int (*SDL_main_func)(int argc, char *argv[]);
extern SDLMAIN_DECLSPEC int SDL_main(int argc, char *argv[]);
/**
* Circumvent failure of SDL_Init() when not using SDL_main() as an entry
* point.
*
* This function is defined in SDL_main.h, along with the preprocessor rule to
* redefine main() as SDL_main(). Thus to ensure that your main() function
* will not be changed it is necessary to define SDL_MAIN_HANDLED before
* including SDL.h.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_Init
*/
extern DECLSPEC void SDLCALL SDL_SetMainReady(void);
#if defined(__WIN32__) || defined(__GDK__)
/**
* Register a win32 window class for SDL's use.
*
* This can be called to set the application window class at startup. It is
* safe to call this multiple times, as long as every call is eventually
* paired with a call to SDL_UnregisterApp, but a second registration attempt
* while a previous registration is still active will be ignored, other than
* to increment a counter.
*
* Most applications do not need to, and should not, call this directly; SDL
* will call it when initializing the video subsystem.
*
* \param name the window class name, in UTF-8 encoding. If NULL, SDL
* currently uses "SDL_app" but this isn't guaranteed.
* \param style the value to use in WNDCLASSEX::style. If `name` is NULL, SDL
* currently uses `(CS_BYTEALIGNCLIENT | CS_OWNDC)` regardless of
* what is specified here.
* \param hInst the HINSTANCE to use in WNDCLASSEX::hInstance. If zero, SDL
* will use `GetModuleHandle(NULL)` instead.
* \returns 0 on success, -1 on error. SDL_GetError() may have details.
*
* \since This function is available since SDL 2.0.2.
*/
extern DECLSPEC int SDLCALL SDL_RegisterApp(const char *name, Uint32 style, void *hInst);
/**
* Deregister the win32 window class from an SDL_RegisterApp call.
*
* This can be called to undo the effects of SDL_RegisterApp.
*
* Most applications do not need to, and should not, call this directly; SDL
* will call it when deinitializing the video subsystem.
*
* It is safe to call this multiple times, as long as every call is eventually
* paired with a prior call to SDL_RegisterApp. The window class will only be
* deregistered when the registration counter in SDL_RegisterApp decrements to
* zero through calls to this function.
*
* \since This function is available since SDL 2.0.2.
*/
extern DECLSPEC void SDLCALL SDL_UnregisterApp(void);
#endif /* defined(__WIN32__) || defined(__GDK__) */
#ifdef __WINRT__
/**
* Initialize and launch an SDL/WinRT application.
*
* \param mainFunction the SDL app's C-style main(), an SDL_main_func
* \param reserved reserved for future use; should be NULL
* \returns 0 on success or -1 on failure; call SDL_GetError() to retrieve
* more information on the failure.
*
* \since This function is available since SDL 2.0.3.
*/
extern DECLSPEC int SDLCALL SDL_WinRTRunApp(SDL_main_func mainFunction, void * reserved);
#endif /* __WINRT__ */
#if defined(__IPHONEOS__)
/**
* Initializes and launches an SDL application.
*
* \param argc The argc parameter from the application's main() function
* \param argv The argv parameter from the application's main() function
* \param mainFunction The SDL app's C-style main(), an SDL_main_func
* \return the return value from mainFunction
*
* \since This function is available since SDL 2.0.10.
*/
extern DECLSPEC int SDLCALL SDL_UIKitRunApp(int argc, char *argv[], SDL_main_func mainFunction);
#endif /* __IPHONEOS__ */
#ifdef __GDK__
/**
* Initialize and launch an SDL GDK application.
*
* \param mainFunction the SDL app's C-style main(), an SDL_main_func
* \param reserved reserved for future use; should be NULL
* \returns 0 on success or -1 on failure; call SDL_GetError() to retrieve
* more information on the failure.
*
* \since This function is available since SDL 2.24.0.
*/
extern DECLSPEC int SDLCALL SDL_GDKRunApp(SDL_main_func mainFunction, void *reserved);
#endif /* __GDK__ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_main_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 412 | 0.839046 | 1 | 0.839046 | game-dev | MEDIA | 0.600025 | game-dev | 0.527364 | 1 | 0.527364 |
AmbientRun/Ambient | 7,504 | crates/timings/src/lib.rs | use std::{collections::VecDeque, time::Duration};
use ambient_core::timing::{reporter, TimingEvent, TimingEventType};
use ambient_ecs::{components, Debuggable, FrameEvent, Resource, System, World, WorldContext};
use ambient_sys::time::Instant;
use winit::event::{DeviceEvent, Event, WindowEvent};
const MAX_SAMPLES: usize = 128;
#[derive(Clone, Copy, Debug)]
pub struct FrameTimings {
event_times: [Option<Instant>; TimingEventType::COUNT],
}
impl FrameTimings {
pub fn input_to_rendered(&self) -> Option<Duration> {
self.event_times[TimingEventType::Input as usize]
.zip(self.event_times[TimingEventType::RenderingFinished as usize])
.map(|(input, rendered)| rendered - input)
}
}
impl std::fmt::Display for FrameTimings {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut last = None;
for (time, idx) in self
.event_times
.iter()
.enumerate()
.filter_map(|(idx, t)| t.zip(Some(idx)))
{
let event_type = TimingEventType::from_usize(idx).unwrap();
if let Some(last) = last {
write!(f, " <- {:?} -> ", time - last)?;
}
write!(f, "{:?}", event_type)?;
last = Some(time);
}
Ok(())
}
}
const fn is_next_event(last: TimingEventType, event: TimingEventType) -> bool {
last.idx() + 1 == event.idx()
}
fn can_be_repeated(event: TimingEventType) -> bool {
event == TimingEventType::Input
}
#[derive(Clone, Copy, Debug)]
struct Frame {
last_event_type: TimingEventType,
event_times: [Option<Instant>; TimingEventType::COUNT],
}
impl Frame {
fn timings(&self) -> FrameTimings {
FrameTimings {
event_times: self.event_times,
}
}
fn should_accept_event(&self, event_type: TimingEventType) -> bool {
// if it simply is the next event
is_next_event(self.last_event_type, event_type) ||
// or if it is repeated input event (there can be multiple input events)
(self.last_event_type == event_type && can_be_repeated(event_type))
}
fn is_accepting_input(&self) -> bool {
self.last_event_type == TimingEventType::Input
}
fn is_finished(&self) -> bool {
self.last_event_type == TimingEventType::last()
}
fn process_event(&mut self, event: TimingEvent) {
if self.should_accept_event(event.event_type) {
self.event_times[event.event_type.idx()] =
self.event_times[event.event_type.idx()].or(Some(event.time));
self.last_event_type = event.event_type;
}
}
}
impl Default for Frame {
fn default() -> Self {
Self {
last_event_type: TimingEventType::Input,
event_times: Default::default(),
}
}
}
#[derive(Debug)]
pub struct ProcessTimingEventsSystem {
frames: VecDeque<Frame>,
}
impl Default for ProcessTimingEventsSystem {
fn default() -> Self {
// we normally have at most 2 frames in flight
let mut frames = VecDeque::with_capacity(2);
frames.push_back(Default::default());
Self { frames }
}
}
impl System for ProcessTimingEventsSystem {
fn run(&mut self, world: &mut World, _event: &FrameEvent) {
// only process timing events in the app world so that they are available for the debugger
if world.context() != WorldContext::App {
return;
}
// timings of finished frames, to be added to the samples resource
let mut pending_samples = Vec::new();
let reporter = world.resource(reporter());
for event in reporter.try_iter() {
for f in self.frames.iter_mut() {
f.process_event(event);
}
// the newest frame should always be accepting input
if !self
.frames
.front()
.map(Frame::is_accepting_input)
.unwrap_or_default()
{
// the currently newest one is missing or not accepting input, so we need to add a new one
self.frames.push_front(Default::default());
}
// pop finished frames
while let Some(f) = self.frames.back() {
if f.is_finished() {
let timings = self.frames.pop_back().unwrap().timings();
pending_samples.push(timings);
} else {
break;
}
}
}
// add pending samples to the samples resource
if !pending_samples.is_empty() {
let samples = world.resource_mut(samples());
for sample in pending_samples {
while samples.len() + 1 >= MAX_SAMPLES {
samples.pop_front();
}
samples.push_back(sample);
}
}
}
}
components!("timings", {
@[Debuggable, Resource]
samples: VecDeque<FrameTimings>,
});
#[derive(Debug)]
struct ClientWorldTimingSystem<const EVENT_TYPE: usize>;
impl<const EVENT_TYPE: usize> System for ClientWorldTimingSystem<EVENT_TYPE> {
fn run(&mut self, world: &mut World, _event: &FrameEvent) {
if world.context() != WorldContext::Client {
return;
}
// emit timing events in the client world
let time = Instant::now();
let event_type = TimingEventType::from_usize(EVENT_TYPE).unwrap();
world
.resource(reporter())
.report_event(TimingEvent { time, event_type });
}
}
pub const fn on_started_timing_system() -> impl System {
const EVENT_TYPE: usize = TimingEventType::ClientSystemsStarted as usize;
ClientWorldTimingSystem::<EVENT_TYPE> {}
}
pub const fn on_finished_timing_system() -> impl System {
const EVENT_TYPE: usize = TimingEventType::ClientSystemsFinished as usize;
ClientWorldTimingSystem::<EVENT_TYPE> {}
}
#[derive(Debug)]
struct SystemWrapper<S> {
system: S,
on_started: TimingEventType,
on_finished: TimingEventType,
}
impl<S, E> System<E> for SystemWrapper<S>
where
S: System<E>,
{
fn run(&mut self, world: &mut World, event: &E) {
let r = world.resource(reporter()).reporter();
r.report_event(TimingEvent::from(self.on_started));
self.system.run(world, event);
r.report_event(TimingEvent::from(self.on_finished));
}
}
pub fn wrap_system<E>(
system: impl System<E>,
on_started: TimingEventType,
on_finished: TimingEventType,
) -> impl System<E> {
SystemWrapper {
system,
on_started,
on_finished,
}
}
#[derive(Debug)]
pub struct InputTimingSystem;
impl System<Event<'static, ()>> for InputTimingSystem {
fn run(&mut self, world: &mut World, event: &Event<'static, ()>) {
if is_user_input_event(event) {
world
.resource(reporter())
.report_event(TimingEventType::Input);
}
}
}
fn is_user_input_event(event: &Event<'static, ()>) -> bool {
matches!(
event,
Event::WindowEvent {
event: WindowEvent::ModifiersChanged(_)
| WindowEvent::KeyboardInput { .. }
| WindowEvent::MouseInput { .. }
| WindowEvent::MouseWheel { .. },
..
} | Event::DeviceEvent {
event: DeviceEvent::MouseMotion { .. },
..
}
)
}
| 412 | 0.868937 | 1 | 0.868937 | game-dev | MEDIA | 0.264078 | game-dev | 0.959292 | 1 | 0.959292 |
ImLegiitXD/Dream-Advanced | 8,624 | dll/back/1.12/net/minecraft/realms/RealmsScreen.java | package net.minecraft.realms;
import com.mojang.util.UUIDTypeAdapter;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.AbstractClientPlayer;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiScreenRealmsProxy;
import net.minecraft.client.resources.DefaultPlayerSkin;
import net.minecraft.client.resources.I18n;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
public class RealmsScreen
{
public static final int SKIN_HEAD_U = 8;
public static final int SKIN_HEAD_V = 8;
public static final int SKIN_HEAD_WIDTH = 8;
public static final int SKIN_HEAD_HEIGHT = 8;
public static final int SKIN_HAT_U = 40;
public static final int SKIN_HAT_V = 8;
public static final int SKIN_HAT_WIDTH = 8;
public static final int SKIN_HAT_HEIGHT = 8;
public static final int SKIN_TEX_WIDTH = 64;
public static final int SKIN_TEX_HEIGHT = 64;
protected Minecraft minecraft;
public int width;
public int height;
private final GuiScreenRealmsProxy proxy = new GuiScreenRealmsProxy(this);
public GuiScreenRealmsProxy getProxy()
{
return this.proxy;
}
public void init()
{
}
public void init(Minecraft p_init_1_, int p_init_2_, int p_init_3_)
{
}
public void drawCenteredString(String p_drawCenteredString_1_, int p_drawCenteredString_2_, int p_drawCenteredString_3_, int p_drawCenteredString_4_)
{
this.proxy.drawCenteredString(p_drawCenteredString_1_, p_drawCenteredString_2_, p_drawCenteredString_3_, p_drawCenteredString_4_);
}
public void drawString(String p_drawString_1_, int p_drawString_2_, int p_drawString_3_, int p_drawString_4_)
{
this.drawString(p_drawString_1_, p_drawString_2_, p_drawString_3_, p_drawString_4_, true);
}
public void drawString(String p_drawString_1_, int p_drawString_2_, int p_drawString_3_, int p_drawString_4_, boolean p_drawString_5_)
{
this.proxy.drawString(p_drawString_1_, p_drawString_2_, p_drawString_3_, p_drawString_4_, false);
}
public void blit(int p_blit_1_, int p_blit_2_, int p_blit_3_, int p_blit_4_, int p_blit_5_, int p_blit_6_)
{
this.proxy.drawTexturedModalRect(p_blit_1_, p_blit_2_, p_blit_3_, p_blit_4_, p_blit_5_, p_blit_6_);
}
public static void blit(int p_blit_0_, int p_blit_1_, float p_blit_2_, float p_blit_3_, int p_blit_4_, int p_blit_5_, int p_blit_6_, int p_blit_7_, float p_blit_8_, float p_blit_9_)
{
Gui.drawScaledCustomSizeModalRect(p_blit_0_, p_blit_1_, p_blit_2_, p_blit_3_, p_blit_4_, p_blit_5_, p_blit_6_, p_blit_7_, p_blit_8_, p_blit_9_);
}
public static void blit(int p_blit_0_, int p_blit_1_, float p_blit_2_, float p_blit_3_, int p_blit_4_, int p_blit_5_, float p_blit_6_, float p_blit_7_)
{
Gui.drawModalRectWithCustomSizedTexture(p_blit_0_, p_blit_1_, p_blit_2_, p_blit_3_, p_blit_4_, p_blit_5_, p_blit_6_, p_blit_7_);
}
public void fillGradient(int p_fillGradient_1_, int p_fillGradient_2_, int p_fillGradient_3_, int p_fillGradient_4_, int p_fillGradient_5_, int p_fillGradient_6_)
{
this.proxy.drawGradientRect(p_fillGradient_1_, p_fillGradient_2_, p_fillGradient_3_, p_fillGradient_4_, p_fillGradient_5_, p_fillGradient_6_);
}
public void renderBackground()
{
this.proxy.drawDefaultBackground();
}
public boolean isPauseScreen()
{
return this.proxy.doesGuiPauseGame();
}
public void renderBackground(int p_renderBackground_1_)
{
this.proxy.drawWorldBackground(p_renderBackground_1_);
}
public void render(int p_render_1_, int p_render_2_, float p_render_3_)
{
for (int i = 0; i < this.proxy.buttons().size(); ++i)
{
((RealmsButton)this.proxy.buttons().get(i)).render(p_render_1_, p_render_2_, p_render_3_);
}
}
public void renderTooltip(ItemStack p_renderTooltip_1_, int p_renderTooltip_2_, int p_renderTooltip_3_)
{
this.proxy.renderToolTip(p_renderTooltip_1_, p_renderTooltip_2_, p_renderTooltip_3_);
}
public void renderTooltip(String p_renderTooltip_1_, int p_renderTooltip_2_, int p_renderTooltip_3_)
{
this.proxy.drawHoveringText(p_renderTooltip_1_, p_renderTooltip_2_, p_renderTooltip_3_);
}
public void renderTooltip(List<String> p_renderTooltip_1_, int p_renderTooltip_2_, int p_renderTooltip_3_)
{
this.proxy.drawHoveringText(p_renderTooltip_1_, p_renderTooltip_2_, p_renderTooltip_3_);
}
public static void bindFace(String p_bindFace_0_, String p_bindFace_1_)
{
ResourceLocation resourcelocation = AbstractClientPlayer.getLocationSkin(p_bindFace_1_);
if (resourcelocation == null)
{
resourcelocation = DefaultPlayerSkin.getDefaultSkin(UUIDTypeAdapter.fromString(p_bindFace_0_));
}
AbstractClientPlayer.getDownloadImageSkin(resourcelocation, p_bindFace_1_);
Minecraft.getMinecraft().getTextureManager().bindTexture(resourcelocation);
}
public static void bind(String p_bind_0_)
{
ResourceLocation resourcelocation = new ResourceLocation(p_bind_0_);
Minecraft.getMinecraft().getTextureManager().bindTexture(resourcelocation);
}
public void tick()
{
}
public int width()
{
return this.proxy.width;
}
public int height()
{
return this.proxy.height;
}
public int fontLineHeight()
{
return this.proxy.getFontHeight();
}
public int fontWidth(String p_fontWidth_1_)
{
return this.proxy.getStringWidth(p_fontWidth_1_);
}
public void fontDrawShadow(String p_fontDrawShadow_1_, int p_fontDrawShadow_2_, int p_fontDrawShadow_3_, int p_fontDrawShadow_4_)
{
this.proxy.fontDrawShadow(p_fontDrawShadow_1_, p_fontDrawShadow_2_, p_fontDrawShadow_3_, p_fontDrawShadow_4_);
}
public List<String> fontSplit(String p_fontSplit_1_, int p_fontSplit_2_)
{
return this.proxy.fontSplit(p_fontSplit_1_, p_fontSplit_2_);
}
public void buttonClicked(RealmsButton p_buttonClicked_1_)
{
}
public static RealmsButton newButton(int p_newButton_0_, int p_newButton_1_, int p_newButton_2_, String p_newButton_3_)
{
return new RealmsButton(p_newButton_0_, p_newButton_1_, p_newButton_2_, p_newButton_3_);
}
public static RealmsButton newButton(int p_newButton_0_, int p_newButton_1_, int p_newButton_2_, int p_newButton_3_, int p_newButton_4_, String p_newButton_5_)
{
return new RealmsButton(p_newButton_0_, p_newButton_1_, p_newButton_2_, p_newButton_3_, p_newButton_4_, p_newButton_5_);
}
public void buttonsClear()
{
this.proxy.buttonsClear();
}
public void buttonsAdd(RealmsButton p_buttonsAdd_1_)
{
this.proxy.buttonsAdd(p_buttonsAdd_1_);
}
public List<RealmsButton> buttons()
{
return this.proxy.buttons();
}
public void buttonsRemove(RealmsButton p_buttonsRemove_1_)
{
this.proxy.buttonsRemove(p_buttonsRemove_1_);
}
public RealmsEditBox newEditBox(int p_newEditBox_1_, int p_newEditBox_2_, int p_newEditBox_3_, int p_newEditBox_4_, int p_newEditBox_5_)
{
return new RealmsEditBox(p_newEditBox_1_, p_newEditBox_2_, p_newEditBox_3_, p_newEditBox_4_, p_newEditBox_5_);
}
public void mouseClicked(int p_mouseClicked_1_, int p_mouseClicked_2_, int p_mouseClicked_3_)
{
}
public void mouseEvent()
{
}
public void keyboardEvent()
{
}
public void mouseReleased(int p_mouseReleased_1_, int p_mouseReleased_2_, int p_mouseReleased_3_)
{
}
public void mouseDragged(int p_mouseDragged_1_, int p_mouseDragged_2_, int p_mouseDragged_3_, long p_mouseDragged_4_)
{
}
public void keyPressed(char p_keyPressed_1_, int p_keyPressed_2_)
{
}
public void confirmResult(boolean p_confirmResult_1_, int p_confirmResult_2_)
{
}
public static String getLocalizedString(String p_getLocalizedString_0_)
{
return I18n.format(p_getLocalizedString_0_);
}
public static String getLocalizedString(String p_getLocalizedString_0_, Object... p_getLocalizedString_1_)
{
return I18n.format(p_getLocalizedString_0_, p_getLocalizedString_1_);
}
public RealmsAnvilLevelStorageSource getLevelStorageSource()
{
return new RealmsAnvilLevelStorageSource(Minecraft.getMinecraft().getSaveLoader());
}
public void removed()
{
}
}
| 412 | 0.548724 | 1 | 0.548724 | game-dev | MEDIA | 0.612168 | game-dev | 0.576124 | 1 | 0.576124 |
keybase/client | 22,511 | go/libkb/chain_link_v2.go | package libkb
import (
"encoding/base64"
"errors"
"fmt"
"github.com/keybase/client/go/msgpack"
keybase1 "github.com/keybase/client/go/protocol/keybase1"
"github.com/keybase/go-codec/codec"
)
// See comment at top of sig_chain.go for a description of V1, V2 and
// V2 stubbed sigchain links.
type SigchainV2Type int
// These values must match constants.iced in the proofs library.
const (
SigchainV2TypeNone SigchainV2Type = 0
SigchainV2TypeEldest SigchainV2Type = 1
SigchainV2TypeWebServiceBinding SigchainV2Type = 2
SigchainV2TypeTrack SigchainV2Type = 3
SigchainV2TypeUntrack SigchainV2Type = 4
SigchainV2TypeRevoke SigchainV2Type = 5
SigchainV2TypeCryptocurrency SigchainV2Type = 6
SigchainV2TypeAnnouncement SigchainV2Type = 7
SigchainV2TypeDevice SigchainV2Type = 8
SigchainV2TypeWebServiceBindingWithRevoke SigchainV2Type = 9
SigchainV2TypeCryptocurrencyWithRevoke SigchainV2Type = 10
SigchainV2TypeSibkey SigchainV2Type = 11
SigchainV2TypeSubkey SigchainV2Type = 12
SigchainV2TypePGPUpdate SigchainV2Type = 13
SigchainV2TypePerUserKey SigchainV2Type = 14
SigchainV2TypeWalletStellar SigchainV2Type = 15
SigchainV2TypeWotVouch SigchainV2Type = 16
SigchainV2TypeWotVouchWithRevoke SigchainV2Type = 17
SigchainV2TypeWotReact SigchainV2Type = 18
// Team link types
// If you add a new one be sure to get all of these too:
// - A corresponding libkb.LinkType in constants.go
// - SigchainV2TypeFromV1TypeTeams
// - SigChainV2Type.IsSupportedTeamType
// - SigChainV2Type.TeamAllowStubWithAdminFlag
// - TeamSigChainPlayer.addInnerLink (add a case)
SigchainV2TypeTeamRoot SigchainV2Type = 33
SigchainV2TypeTeamNewSubteam SigchainV2Type = 34
SigchainV2TypeTeamChangeMembership SigchainV2Type = 35
SigchainV2TypeTeamRotateKey SigchainV2Type = 36
SigchainV2TypeTeamLeave SigchainV2Type = 37
SigchainV2TypeTeamSubteamHead SigchainV2Type = 38
SigchainV2TypeTeamRenameSubteam SigchainV2Type = 39
SigchainV2TypeTeamInvite SigchainV2Type = 40
SigchainV2TypeTeamRenameUpPointer SigchainV2Type = 41
SigchainV2TypeTeamDeleteRoot SigchainV2Type = 42
SigchainV2TypeTeamDeleteSubteam SigchainV2Type = 43
SigchainV2TypeTeamDeleteUpPointer SigchainV2Type = 44
// Note that 45 is skipped, since it's retired; used to be LegacyTLFUpgrade
SigchainV2TypeTeamSettings SigchainV2Type = 46
SigchainV2TypeTeamKBFSSettings SigchainV2Type = 47
SigchainV2TypeTeamBotSettings SigchainV2Type = 48
)
// NeedsSignature is untrue of most supported link types. If a link can
// be stubbed, that means we potentially won't get to verify its signature,
// since we need the full link to verify signatures. However, in some cases,
// signature verification is required, and hence stubbing is disallowed.
// NOTE when modifying this function ensure that web/sig.iced#_allow_stubbing
// is updated as well.
func (t SigchainV2Type) AllowStubbing() bool {
// Unsupported types don't need signatures. Otherwise we can't
// make code forwards-compatible.
if !t.IsSupportedUserType() {
return true
}
// Of known types, Track, Untrack and Announcement can be stubbed, but
// nothing else, for now....
switch t {
case SigchainV2TypeTrack, SigchainV2TypeUntrack, SigchainV2TypeAnnouncement:
return true
default:
return false
}
}
// NOTE when modifying this function ensure that web/sig.iced#_is_supported_user_type
// is updated as well.
func (t SigchainV2Type) IsSupportedUserType() bool {
switch t {
case SigchainV2TypeNone,
SigchainV2TypeEldest,
SigchainV2TypeWebServiceBinding,
SigchainV2TypeTrack,
SigchainV2TypeUntrack,
SigchainV2TypeRevoke,
SigchainV2TypeCryptocurrency,
SigchainV2TypeAnnouncement,
SigchainV2TypeDevice,
SigchainV2TypeWebServiceBindingWithRevoke,
SigchainV2TypeCryptocurrencyWithRevoke,
SigchainV2TypeSibkey,
SigchainV2TypeSubkey,
SigchainV2TypePGPUpdate,
SigchainV2TypePerUserKey,
SigchainV2TypeWotVouchWithRevoke,
SigchainV2TypeWalletStellar:
return true
default:
return false
}
}
func (t SigchainV2Type) IsSupportedType() bool {
return t.IsSupportedTeamType() || t.IsSupportedUserType()
}
// Whether a type is for team sigchains.
// Also the list of which types are supported by this client.
func (t SigchainV2Type) IsSupportedTeamType() bool {
switch t {
case SigchainV2TypeTeamRoot,
SigchainV2TypeTeamNewSubteam,
SigchainV2TypeTeamChangeMembership,
SigchainV2TypeTeamRotateKey,
SigchainV2TypeTeamLeave,
SigchainV2TypeTeamSubteamHead,
SigchainV2TypeTeamRenameSubteam,
SigchainV2TypeTeamInvite,
SigchainV2TypeTeamRenameUpPointer,
SigchainV2TypeTeamDeleteRoot,
SigchainV2TypeTeamDeleteSubteam,
SigchainV2TypeTeamDeleteUpPointer,
SigchainV2TypeTeamKBFSSettings,
SigchainV2TypeTeamSettings,
SigchainV2TypeTeamBotSettings:
return true
default:
return false
}
}
func (t SigchainV2Type) RequiresAtLeastRole() keybase1.TeamRole {
if !t.IsSupportedTeamType() {
// Links from the future require a bare minimum.
// They should be checked later by a code update that busts the cache.
return keybase1.TeamRole_RESTRICTEDBOT
}
switch t {
case SigchainV2TypeTeamLeave:
return keybase1.TeamRole_RESTRICTEDBOT
case SigchainV2TypeTeamRoot:
return keybase1.TeamRole_BOT
case SigchainV2TypeTeamRotateKey,
SigchainV2TypeTeamKBFSSettings:
return keybase1.TeamRole_WRITER
default:
return keybase1.TeamRole_ADMIN
}
}
func (t SigchainV2Type) TeamAllowStubWithAdminFlag(isAdmin bool) bool {
if isAdmin {
// Links cannot be stubbed for owners and admins
return false
}
switch t {
case SigchainV2TypeTeamNewSubteam,
SigchainV2TypeTeamRenameSubteam,
SigchainV2TypeTeamDeleteSubteam,
SigchainV2TypeTeamInvite,
SigchainV2TypeTeamSettings,
SigchainV2TypeTeamKBFSSettings,
SigchainV2TypeTeamBotSettings:
return true
default:
// Disallow stubbing of other known links.
// Allow stubbing of unknown link types for forward compatibility.
return !t.IsSupportedTeamType()
}
}
type OuterLinkV2Partial0 struct {
_struct bool `codec:",toarray"` //nolint
Version SigVersion `codec:"version"`
Seqno keybase1.Seqno `codec:"seqno"`
Prev LinkID `codec:"prev"`
Curr LinkID `codec:"curr"`
LinkType SigchainV2Type `codec:"type"`
}
type OuterLinkV2Partial1 struct {
_struct bool `codec:",toarray"` //nolint
Version SigVersion `codec:"version"`
Seqno keybase1.Seqno `codec:"seqno"`
Prev LinkID `codec:"prev"`
Curr LinkID `codec:"curr"`
LinkType SigchainV2Type `codec:"type"`
SeqType keybase1.SeqType `codec:"seqtype"`
}
type OuterLinkV2Partial2 struct {
_struct bool `codec:",toarray"` //nolint
Version SigVersion `codec:"version"`
Seqno keybase1.Seqno `codec:"seqno"`
Prev LinkID `codec:"prev"`
Curr LinkID `codec:"curr"`
LinkType SigchainV2Type `codec:"type"`
SeqType keybase1.SeqType `codec:"seqtype"`
IgnoreIfUnsupported SigIgnoreIfUnsupported `codec:"ignore_if_unsupported"`
}
// OuterLinkV2 is the second version of Keybase sigchain signatures.
type OuterLinkV2 struct {
_struct bool `codec:",toarray"` //nolint
Version SigVersion `codec:"version"`
Seqno keybase1.Seqno `codec:"seqno"`
Prev LinkID `codec:"prev"`
Curr LinkID `codec:"curr"`
LinkType SigchainV2Type `codec:"type"`
// -- Links exist in the wild that are missing fields below this line (see Partial0)
SeqType keybase1.SeqType `codec:"seqtype"`
// -- Links exist in the wild that are missing fields below this line too (see Partial1)
// Whether the link can be ignored by clients that do not support its link type.
// This does _not_ mean the link can be ignored if the client supports the link type.
// When it comes to stubbing, if the link is unsupported and this bit is set then
// - it can be stubbed for non-admins
// - it cannot be stubbed for admins
IgnoreIfUnsupported SigIgnoreIfUnsupported `codec:"ignore_if_unsupported"`
// -- Links exist in the wild that are missing fields below this line too (see Partial2)
// If not provided, both of these are nil, and highSkip in the inner link is set to nil.
// Note that a link providing HighSkipSeqno == 0 and HighSkipHash == nil is valid
// (and mandatory) for an initial link.
HighSkipSeqno *keybase1.Seqno `codec:"high_skip_seqno"`
HighSkipHash *LinkID `codec:"high_skip_hash"`
}
func (o OuterLinkV2) Encode() ([]byte, error) {
return msgpack.Encode(o)
}
type OuterLinkV2WithMetadata struct {
OuterLinkV2
raw []byte
sigID keybase1.SigID
sig string
kid keybase1.KID
}
// An OuterLinkV2WithMetadata should never be encoded/decoded
// directly. This is to avoid problems like
// https://github.com/keybase/saltpack/pull/43 .
var _ codec.Selfer = (*OuterLinkV2WithMetadata)(nil)
var errCodecEncodeSelf = errors.New("Unexpected call to OuterLinkV2WithMetadata.CodecEncodeSelf")
var errCodecDecodeSelf = errors.New("Unexpected call to OuterLinkV2WithMetadata.CodecDecodeSelf")
func (o *OuterLinkV2WithMetadata) CodecEncodeSelf(e *codec.Encoder) {
panic(errCodecEncodeSelf)
}
func (o *OuterLinkV2WithMetadata) CodecDecodeSelf(d *codec.Decoder) {
panic(errCodecDecodeSelf)
}
type SigIgnoreIfUnsupported bool
type SigHasRevokes bool
func (b SigIgnoreIfUnsupported) Bool() bool { return bool(b) }
func encodeOuterLink(
m MetaContext,
v1LinkType LinkType,
seqno keybase1.Seqno,
innerLinkJSON []byte,
prevLinkID LinkID,
hasRevokes SigHasRevokes,
seqType keybase1.SeqType,
ignoreIfUnsupported SigIgnoreIfUnsupported,
highSkip *HighSkip,
) ([]byte, error) {
var encodedOuterLink []byte
currLinkID := ComputeLinkID(innerLinkJSON)
v2LinkType, err := SigchainV2TypeFromV1TypeAndRevocations(string(v1LinkType), hasRevokes, ignoreIfUnsupported)
if err != nil {
return encodedOuterLink, err
}
// When 2.3 links are mandatory, it will be invalid for highSkip == nil,
// so the featureflag check will be removed and the nil check will result
// in an error.
allowHighSkips := m.G().Env.GetFeatureFlags().HasFeature(EnvironmentFeatureAllowHighSkips)
var highSkipSeqno *keybase1.Seqno
var highSkipHash *LinkID
if highSkip != nil && allowHighSkips {
highSkipSeqno = &highSkip.Seqno
highSkipHash = &highSkip.Hash
}
return encodeOuterLinkWithLinkID(v2LinkType, seqno, currLinkID, prevLinkID, seqType, ignoreIfUnsupported, highSkipSeqno, highSkipHash)
}
func encodeOuterLinkWithLinkID(
v2LinkType SigchainV2Type,
seqno keybase1.Seqno,
currLinkID LinkID,
prevLinkID LinkID,
seqType keybase1.SeqType,
ignoreIfUnsupported SigIgnoreIfUnsupported,
highSkipSeqno *keybase1.Seqno,
highSkipHash *LinkID,
) ([]byte, error) {
var encodedOuterLink []byte
var err error
if highSkipSeqno != nil && highSkipHash != nil {
outerLink := OuterLinkV2{
Version: 2,
Seqno: seqno,
Prev: prevLinkID,
Curr: currLinkID,
LinkType: v2LinkType,
SeqType: seqType,
IgnoreIfUnsupported: ignoreIfUnsupported,
HighSkipSeqno: highSkipSeqno,
HighSkipHash: highSkipHash,
}
encodedOuterLink, err = outerLink.Encode()
} else {
// This is a helper struct. When the code for Sigchain 2.3
// is released, it is possible some clients will still post 2.2
// links, i.e., without high_skip information. Due to a bug
// in Keybase's fork of go-codec, omitempty does not work
// for arrays. So, we send up the serialization of the
// appropriate struct depending on whether we are making a 2.3 link.
// When 2.3 links are mandatory, this struct can be deleted.
encodedOuterLink, err = msgpack.Encode(OuterLinkV2Partial2{
Version: 2,
Seqno: seqno,
Prev: prevLinkID,
Curr: currLinkID,
LinkType: v2LinkType,
SeqType: seqType,
IgnoreIfUnsupported: ignoreIfUnsupported,
})
}
if err != nil {
return encodedOuterLink, err
}
return encodedOuterLink, err
}
func MakeSigchainV2OuterSig(
m MetaContext,
signingKey GenericKey,
v1LinkType LinkType,
seqno keybase1.Seqno,
innerLinkJSON []byte,
prevLinkID LinkID,
hasRevokes SigHasRevokes,
seqType keybase1.SeqType,
ignoreIfUnsupported SigIgnoreIfUnsupported,
highSkip *HighSkip,
) (sig string, sigid keybase1.SigID, linkID LinkID, err error) {
encodedOuterLink, err := encodeOuterLink(m, v1LinkType, seqno, innerLinkJSON, prevLinkID, hasRevokes, seqType, ignoreIfUnsupported, highSkip)
if err != nil {
return sig, sigid, linkID, err
}
var sigIDBase keybase1.SigIDBase
sig, sigIDBase, err = signingKey.SignToString(encodedOuterLink)
if err != nil {
return sig, sigid, linkID, err
}
params := keybase1.SigIDSuffixParametersFromTypeAndVersion(string(v1LinkType), keybase1.SigVersion(2))
sigid = sigIDBase.ToSigID(params)
linkID = ComputeLinkID(encodedOuterLink)
return sig, sigid, linkID, nil
}
func (o OuterLinkV2) EncodeTruncateHighSkips() ([]byte, error) {
return encodeOuterLinkWithLinkID(o.LinkType, o.Seqno, o.Curr, o.Prev, o.SeqType, o.IgnoreIfUnsupported, o.HighSkipSeqno, o.HighSkipHash)
}
func (o OuterLinkV2) EncodePartial(numFields int) ([]byte, error) {
switch numFields {
case 5:
return msgpack.Encode(OuterLinkV2Partial0{
Version: 2,
Seqno: o.Seqno,
Prev: o.Prev,
Curr: o.Curr,
LinkType: o.LinkType,
})
case 6:
return msgpack.Encode(OuterLinkV2Partial1{
Version: 2,
Seqno: o.Seqno,
Prev: o.Prev,
Curr: o.Curr,
LinkType: o.LinkType,
SeqType: o.SeqType,
})
case 7:
return msgpack.Encode(OuterLinkV2Partial2{
Version: 2,
Seqno: o.Seqno,
Prev: o.Prev,
Curr: o.Curr,
LinkType: o.LinkType,
SeqType: o.SeqType,
IgnoreIfUnsupported: o.IgnoreIfUnsupported,
})
case 9:
return msgpack.Encode(OuterLinkV2{
Version: 2,
Seqno: o.Seqno,
Prev: o.Prev,
Curr: o.Curr,
LinkType: o.LinkType,
SeqType: o.SeqType,
IgnoreIfUnsupported: o.IgnoreIfUnsupported,
HighSkipHash: o.HighSkipHash,
HighSkipSeqno: o.HighSkipSeqno,
})
default:
return nil, fmt.Errorf("Cannot encode sig2 partial with %d fields", numFields)
}
}
func DecodeStubbedOuterLinkV2(b64encoded string) (*OuterLinkV2WithMetadata, error) {
payload, err := base64.StdEncoding.DecodeString(b64encoded)
if err != nil {
return nil, err
}
if !msgpack.IsEncodedMsgpackArray(payload) {
return nil, ChainLinkError{"expected a msgpack array but got leading junk"}
}
var ol OuterLinkV2
if err = msgpack.Decode(&ol, payload); err != nil {
return nil, err
}
return &OuterLinkV2WithMetadata{OuterLinkV2: ol, raw: payload}, nil
}
func (o OuterLinkV2WithMetadata) EncodeStubbed() string {
return base64.StdEncoding.EncodeToString(o.raw)
}
func (o OuterLinkV2WithMetadata) LinkID() LinkID {
return ComputeLinkID(o.raw)
}
func (o OuterLinkV2WithMetadata) SigID() keybase1.SigID {
return o.sigID
}
func (o OuterLinkV2WithMetadata) Raw() []byte {
return o.raw
}
func (o OuterLinkV2WithMetadata) Verify(ctx VerifyContext) (kid keybase1.KID, err error) {
key, err := ImportKeypairFromKID(o.kid)
if err != nil {
return kid, err
}
_, err = key.VerifyString(ctx, o.sig, o.raw)
if err != nil {
return kid, err
}
return o.kid, nil
}
func (t SigchainV2Type) SigIDSuffixParams(v keybase1.SigVersion) keybase1.SigIDSuffixParameters {
return keybase1.SigIDSuffixParameters{
IsUserSig: t.IsSupportedUserType(),
IsWalletStellar: (t == SigchainV2TypeWalletStellar),
SigVersion: v,
}
}
func DecodeOuterLinkV2(armored string) (*OuterLinkV2WithMetadata, error) {
payload, kid, sigIDBase, err := SigExtractPayloadAndKID(armored)
if err != nil {
return nil, err
}
if !msgpack.IsEncodedMsgpackArray(payload) {
return nil, ChainLinkError{"expected a msgpack array but got leading junk"}
}
var ol OuterLinkV2
if err := msgpack.Decode(&ol, payload); err != nil {
return nil, err
}
params := ol.LinkType.SigIDSuffixParams(keybase1.SigVersion(2))
ret := OuterLinkV2WithMetadata{
OuterLinkV2: ol,
sigID: sigIDBase.ToSigID(params),
raw: payload,
kid: kid,
sig: armored,
}
return &ret, nil
}
func SigchainV2TypeFromV1TypeAndRevocations(s string, hasRevocations SigHasRevokes, ignoreIfUnsupported SigIgnoreIfUnsupported) (ret SigchainV2Type, err error) {
switch s {
case "eldest":
ret = SigchainV2TypeEldest
case "web_service_binding":
if hasRevocations {
ret = SigchainV2TypeWebServiceBindingWithRevoke
} else {
ret = SigchainV2TypeWebServiceBinding
}
case "track":
ret = SigchainV2TypeTrack
case "untrack":
ret = SigchainV2TypeUntrack
case "revoke":
ret = SigchainV2TypeRevoke
case "cryptocurrency":
if hasRevocations {
ret = SigchainV2TypeCryptocurrencyWithRevoke
} else {
ret = SigchainV2TypeCryptocurrency
}
case "announcement":
ret = SigchainV2TypeAnnouncement
case "device":
ret = SigchainV2TypeDevice
case "sibkey":
ret = SigchainV2TypeSibkey
case "subkey":
ret = SigchainV2TypeSubkey
case "pgp_update":
ret = SigchainV2TypePGPUpdate
case "per_user_key":
ret = SigchainV2TypePerUserKey
case string(LinkTypeWalletStellar):
ret = SigchainV2TypeWalletStellar
case string(LinkTypeWotVouch):
if hasRevocations {
ret = SigchainV2TypeWotVouchWithRevoke
} else {
ret = SigchainV2TypeWotVouch
}
case string(LinkTypeWotReact):
ret = SigchainV2TypeWotReact
default:
teamRes, teamErr := SigchainV2TypeFromV1TypeTeams(s)
if teamErr == nil {
ret = teamRes
} else {
ret = SigchainV2TypeNone
if !ignoreIfUnsupported {
err = ChainLinkError{fmt.Sprintf("Unknown sig v1 type: %s", s)}
}
}
}
if ret.AllowStubbing() && bool(hasRevocations) {
err = ChainLinkError{fmt.Sprintf("invalid chain link of type %d with a revocation", ret)}
}
return ret, err
}
func SigchainV2TypeFromV1TypeTeams(s string) (ret SigchainV2Type, err error) {
switch LinkType(s) {
case LinkTypeTeamRoot:
ret = SigchainV2TypeTeamRoot
case LinkTypeNewSubteam:
ret = SigchainV2TypeTeamNewSubteam
case LinkTypeChangeMembership:
ret = SigchainV2TypeTeamChangeMembership
case LinkTypeRotateKey:
ret = SigchainV2TypeTeamRotateKey
case LinkTypeLeave:
ret = SigchainV2TypeTeamLeave
case LinkTypeSubteamHead:
ret = SigchainV2TypeTeamSubteamHead
case LinkTypeRenameSubteam:
ret = SigchainV2TypeTeamRenameSubteam
case LinkTypeInvite:
ret = SigchainV2TypeTeamInvite
case LinkTypeRenameUpPointer:
ret = SigchainV2TypeTeamRenameUpPointer
case LinkTypeDeleteRoot:
ret = SigchainV2TypeTeamDeleteRoot
case LinkTypeDeleteSubteam:
ret = SigchainV2TypeTeamDeleteSubteam
case LinkTypeDeleteUpPointer:
ret = SigchainV2TypeTeamDeleteUpPointer
case LinkTypeKBFSSettings:
ret = SigchainV2TypeTeamKBFSSettings
case LinkTypeSettings:
ret = SigchainV2TypeTeamSettings
case LinkTypeTeamBotSettings:
ret = SigchainV2TypeTeamBotSettings
default:
return SigchainV2TypeNone, ChainLinkError{fmt.Sprintf("Unknown team sig v1 type: %s", s)}
}
return ret, err
}
func mismatchError(format string, arg ...interface{}) error {
return SigchainV2MismatchedFieldError{fmt.Sprintf(format, arg...)}
}
func (o OuterLinkV2) AssertFields(
version SigVersion,
seqno keybase1.Seqno,
prev LinkID,
curr LinkID,
linkType SigchainV2Type,
seqType keybase1.SeqType,
ignoreIfUnsupported SigIgnoreIfUnsupported,
highSkip *HighSkip,
) (err error) {
if o.Version != version {
return mismatchError("version field (%d != %d)", o.Version, version)
}
if o.Seqno != seqno {
return mismatchError("seqno field: (%d != %d)", o.Seqno, seqno)
}
if !o.Prev.Eq(prev) {
return mismatchError("prev pointer: (%s != !%s)", o.Prev, prev)
}
if !o.Curr.Eq(curr) {
return mismatchError("curr pointer: (%s != %s)", o.Curr, curr)
}
if !(linkType == SigchainV2TypeNone && ignoreIfUnsupported) && o.LinkType != linkType {
return mismatchError("link type: (%d != %d)", o.LinkType, linkType)
}
if o.SeqType != seqType {
return mismatchError("seq type: (%d != %d)", o.SeqType, seqType)
}
if o.IgnoreIfUnsupported != ignoreIfUnsupported {
return mismatchError("ignore_if_unsupported: (%v != %v)", o.IgnoreIfUnsupported, ignoreIfUnsupported)
}
err = o.assertHighSkip(highSkip)
if err != nil {
return err
}
return nil
}
func (o OuterLinkV2) assertHighSkip(highSkip *HighSkip) error {
if highSkip == nil && o.HighSkipSeqno != nil {
return mismatchError("provided HighSkipSeqno (%d) in outer link but not in inner link", o.HighSkipSeqno)
}
if highSkip == nil && o.HighSkipHash != nil {
return mismatchError("provided HighSkipHash (%v) in outer link but not in inner link", o.HighSkipHash)
}
// o.HighSkipHash may be nil even if highSkip is not, so we don't check it
if highSkip != nil && o.HighSkipSeqno == nil {
return mismatchError("provided HighSkip in inner link but not HighSkipSeqno in outer link")
}
if highSkip == nil {
return nil
}
if *o.HighSkipSeqno != highSkip.Seqno {
return mismatchError("highSkip.Seqno field outer (%d)/inner (%d) mismatch", *o.HighSkipSeqno, highSkip.Seqno)
}
if o.HighSkipHash == nil && highSkip.Hash != nil {
return mismatchError("Provided HighSkip.Hash in outer link but not inner.")
}
if o.HighSkipHash != nil && highSkip.Hash == nil {
return mismatchError("Provided HighSkip.Hash in inner link but not outer.")
}
if o.HighSkipHash != nil && !o.HighSkipHash.Eq(highSkip.Hash) {
return mismatchError("highSkip.Hash field outer (%v)/inner (%v) mismatch", o.HighSkipHash, highSkip.Hash)
}
return nil
}
func (o OuterLinkV2) AssertSomeFields(
version SigVersion,
seqno keybase1.Seqno,
) (err error) {
if o.Version != version {
return mismatchError("version field (%d != %d)", o.Version, version)
}
if o.Seqno != seqno {
return mismatchError("seqno field: (%d != %d)", o.Seqno, seqno)
}
return nil
}
| 412 | 0.864719 | 1 | 0.864719 | game-dev | MEDIA | 0.295274 | game-dev | 0.612856 | 1 | 0.612856 |
Naton1/osrs-pvp-reinforcement-learning | 12,212 | simulation-rsps/ElvargServer/src/main/java/com/elvarg/game/content/combat/magic/EffectSpells.java | package com.elvarg.game.content.combat.magic;
import com.elvarg.game.entity.impl.Mobile;
import com.elvarg.game.entity.impl.player.Player;
import com.elvarg.game.model.*;
import com.elvarg.util.Misc;
import com.elvarg.util.timers.TimerKey;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
/**
* Handles spells with special effects.
*/
public class EffectSpells {
public static boolean handleSpell(Player player, int button) {
Optional<EffectSpell> spell = EffectSpell.forSpellId(button);
if (!spell.isPresent()) {
return false;
}
if (!spell.get().getSpell().canCast(player, false)) {
return true;
}
switch (spell.get()) {
case BONES_TO_PEACHES:
case BONES_TO_BANANAS:
if (!player.getClickDelay().elapsed(500)) {
return true;
}
if (!player.getInventory().contains(526)) {
player.getPacketSender().sendMessage("You do not have any bones in your inventory.");
return true;
}
player.getInventory().deleteItemSet(spell.get().getSpell().itemsRequired(player));
int i = 0;
for (Item invItem : player.getInventory().getValidItems()) {
if (invItem.getId() == 526) {
player.getInventory().delete(526, 1).add(spell.get() == EffectSpell.BONES_TO_PEACHES ? 6883 : 1963, 1);
i++;
}
}
player.performGraphic(new Graphic(141, GraphicHeight.MIDDLE));
player.performAnimation(new Animation(722));
player.getSkillManager().addExperience(Skill.MAGIC, spell.get().getSpell().baseExperience() * i);
player.getClickDelay().reset();
break;
case VENGEANCE:
if (player.getDueling().inDuel()) {
player.getPacketSender().sendMessage("You cannot cast Vengeance during a duel!");
return true;
}
if (player.getSkillManager().getMaxLevel(Skill.DEFENCE) < 40) {
player.getPacketSender().sendMessage("You need at least level 40 Defence to cast this spell.");
return true;
}
if (player.hasVengeance()) {
player.getPacketSender().sendMessage("You already have Vengeance's effect.");
return true;
}
if (player.getTimers().has(TimerKey.VENGEANCE_COOLDOWN)) {
final int remainingSeconds = Misc.getSeconds(player.getTimers().getTicks(TimerKey.VENGEANCE_COOLDOWN));
player.getPacketSender().sendMessage("You must wait another " + remainingSeconds + " seconds before you can cast that again.");
return true;
}
//Send message and effect timer to client
player.setHasVengeance(true);
player.getTimers().register(TimerKey.VENGEANCE_COOLDOWN, 50);
final int remainingSeconds = Misc.getSeconds(player.getTimers().getTicks(TimerKey.VENGEANCE_COOLDOWN));
player.getPacketSender().sendEffectTimer(remainingSeconds, EffectTimer.VENGEANCE)
.sendMessage("You now have Vengeance's effect.");
player.getInventory().deleteItemSet(EffectSpell.VENGEANCE.getSpell().itemsRequired(player));
player.performAnimation(new Animation(4410));
player.performGraphic(new Graphic(726, GraphicHeight.HIGH));
break;
}
return true;
}
public static enum EffectSpell {
BONES_TO_BANANAS(new Spell() {
@Override
public int spellId() {
return 1159;
}
@Override
public int levelRequired() {
return 15;
}
@Override
public int baseExperience() {
return 650;
}
@Override
public Optional<Item[]> itemsRequired(Player player) {
return Optional.of(new Item[]{new Item(561), new Item(555, 2), new Item(557, 2)});
}
@Override
public Optional<Item[]> equipmentRequired(Player player) {
return Optional.empty();
}
@Override
public void startCast(Mobile cast, Mobile castOn) {
}
}),
LOW_ALCHEMY(new Spell() {
@Override
public int spellId() {
return 1162;
}
@Override
public int levelRequired() {
return 21;
}
@Override
public int baseExperience() {
return 4000;
}
@Override
public Optional<Item[]> itemsRequired(Player player) {
return Optional.of(new Item[]{new Item(554, 3), new Item(561)});
}
@Override
public Optional<Item[]> equipmentRequired(Player player) {
return Optional.empty();
}
@Override
public void startCast(Mobile cast, Mobile castOn) {
}
}),
TELEKINETIC_GRAB(new Spell() {
@Override
public int spellId() {
return 1168;
}
@Override
public int levelRequired() {
return 33;
}
@Override
public int baseExperience() {
return 3988;
}
@Override
public Optional<Item[]> itemsRequired(Player player) {
return Optional.of(new Item[]{new Item(563), new Item(556)});
}
@Override
public Optional<Item[]> equipmentRequired(Player player) {
return Optional.empty();
}
@Override
public void startCast(Mobile cast, Mobile castOn) {
}
}),
SUPERHEAT_ITEM(new Spell() {
@Override
public int spellId() {
return 1173;
}
@Override
public int levelRequired() {
return 43;
}
@Override
public int baseExperience() {
return 6544;
}
@Override
public Optional<Item[]> itemsRequired(Player player) {
return Optional.of(new Item[]{new Item(554, 4), new Item(561)});
}
@Override
public Optional<Item[]> equipmentRequired(Player player) {
return Optional.empty();
}
@Override
public void startCast(Mobile cast, Mobile castOn) {
}
}),
HIGH_ALCHEMY(new Spell() {
@Override
public int spellId() {
return 1178;
}
@Override
public int levelRequired() {
return 55;
}
@Override
public int baseExperience() {
return 20000;
}
@Override
public Optional<Item[]> itemsRequired(Player player) {
return Optional.of(new Item[]{new Item(554, 5), new Item(561)});
}
@Override
public Optional<Item[]> equipmentRequired(Player player) {
return Optional.empty();
}
@Override
public void startCast(Mobile cast, Mobile castOn) {
}
}),
BONES_TO_PEACHES(new Spell() {
@Override
public int spellId() {
return 15877;
}
@Override
public int levelRequired() {
return 60;
}
@Override
public int baseExperience() {
return 4121;
}
@Override
public Optional<Item[]> itemsRequired(Player player) {
return Optional.of(new Item[]{new Item(561, 2), new Item(555, 4), new Item(557, 4)});
}
@Override
public Optional<Item[]> equipmentRequired(Player player) {
return Optional.empty();
}
@Override
public void startCast(Mobile cast, Mobile castOn) {
}
}),
BAKE_PIE(new Spell() {
@Override
public int spellId() {
return 30017;
}
@Override
public int levelRequired() {
return 65;
}
@Override
public int baseExperience() {
return 5121;
}
@Override
public Optional<Item[]> itemsRequired(Player player) {
return Optional.of(new Item[]{new Item(9075, 1), new Item(554, 5), new Item(555, 4)});
}
@Override
public Optional<Item[]> equipmentRequired(Player player) {
return Optional.empty();
}
@Override
public void startCast(Mobile cast, Mobile castOn) {
}
@Override
public MagicSpellbook getSpellbook() {
return MagicSpellbook.LUNAR;
}
}),
VENGEANCE_OTHER(new Spell() {
@Override
public int spellId() {
return 30298;
}
@Override
public int levelRequired() {
return 93;
}
@Override
public int baseExperience() {
return 10000;
}
@Override
public Optional<Item[]> itemsRequired(Player player) {
return Optional.of(new Item[]{new Item(9075, 3), new Item(557, 10), new Item(560, 2)});
}
@Override
public Optional<Item[]> equipmentRequired(Player player) {
return Optional.empty();
}
@Override
public void startCast(Mobile cast, Mobile castOn) {
}
@Override
public MagicSpellbook getSpellbook() {
return MagicSpellbook.LUNAR;
}
}),
VENGEANCE(new Spell() {
@Override
public int spellId() {
return 30306;
}
@Override
public int levelRequired() {
return 94;
}
@Override
public int baseExperience() {
return 14000;
}
@Override
public Optional<Item[]> itemsRequired(Player player) {
return Optional.of(new Item[]{new Item(9075, 4), new Item(557, 10), new Item(560, 2)});
}
@Override
public Optional<Item[]> equipmentRequired(Player player) {
return Optional.empty();
}
@Override
public void startCast(Mobile cast, Mobile castOn) {
}
@Override
public MagicSpellbook getSpellbook() {
return MagicSpellbook.LUNAR;
}
});
private static final Map<Integer, EffectSpell> map = new HashMap<Integer, EffectSpell>();
static {
for (EffectSpell spell : EffectSpell.values()) {
map.put(spell.getSpell().spellId(), spell);
}
}
private Spell spell;
EffectSpell(Spell spell) {
this.spell = spell;
}
public static Optional<EffectSpell> forSpellId(int spellId) {
EffectSpell spell = map.get(spellId);
if (spell != null) {
return Optional.of(spell);
}
return Optional.empty();
}
public Spell getSpell() {
return spell;
}
}
}
| 412 | 0.948102 | 1 | 0.948102 | game-dev | MEDIA | 0.981265 | game-dev | 0.9696 | 1 | 0.9696 |
FMXExpress/Firemonkey | 3,581 | Embarcadero/Berlin/CPP/TestBed/Tests/BulletTest.h | /*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BULLET_TEST_H
#define BULLET_TEST_H
class BulletTest : public Test
{
public:
BulletTest()
{
{
b2BodyDef bd;
bd.position.Set(0.0f, 0.0f);
b2Body* body = m_world->CreateBody(&bd);
b2EdgeShape edge;
edge.Set(b2Vec2(-10.0f, 0.0f), b2Vec2(10.0f, 0.0f));
body->CreateFixture(&edge, 0.0f);
b2PolygonShape shape;
shape.SetAsBox(0.2f, 1.0f, b2Vec2(0.5f, 1.0f), 0.0f);
body->CreateFixture(&shape, 0.0f);
}
{
b2BodyDef bd;
bd.type = b2_dynamicBody;
bd.position.Set(0.0f, 4.0f);
b2PolygonShape box;
box.SetAsBox(2.0f, 0.1f);
m_body = m_world->CreateBody(&bd);
m_body->CreateFixture(&box, 1.0f);
box.SetAsBox(0.25f, 0.25f);
//m_x = RandomFloat(-1.0f, 1.0f);
m_x = 0.20352793f;
bd.position.Set(m_x, 10.0f);
bd.bullet = true;
m_bullet = m_world->CreateBody(&bd);
m_bullet->CreateFixture(&box, 100.0f);
m_bullet->SetLinearVelocity(b2Vec2(0.0f, -50.0f));
}
}
void Launch()
{
m_body->SetTransform(b2Vec2(0.0f, 4.0f), 0.0f);
m_body->SetLinearVelocity(b2Vec2_zero);
m_body->SetAngularVelocity(0.0f);
m_x = RandomFloat(-1.0f, 1.0f);
m_bullet->SetTransform(b2Vec2(m_x, 10.0f), 0.0f);
m_bullet->SetLinearVelocity(b2Vec2(0.0f, -50.0f));
m_bullet->SetAngularVelocity(0.0f);
extern int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters;
extern int32 b2_toiCalls, b2_toiIters, b2_toiMaxIters;
extern int32 b2_toiRootIters, b2_toiMaxRootIters;
b2_gjkCalls = 0;
b2_gjkIters = 0;
b2_gjkMaxIters = 0;
b2_toiCalls = 0;
b2_toiIters = 0;
b2_toiMaxIters = 0;
b2_toiRootIters = 0;
b2_toiMaxRootIters = 0;
}
void Step(Settings* settings)
{
Test::Step(settings);
extern int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters;
extern int32 b2_toiCalls, b2_toiIters;
extern int32 b2_toiRootIters, b2_toiMaxRootIters;
if (b2_gjkCalls > 0)
{
g_debugDraw.DrawString(5, m_textLine, "gjk calls = %d, ave gjk iters = %3.1f, max gjk iters = %d",
b2_gjkCalls, b2_gjkIters / float32(b2_gjkCalls), b2_gjkMaxIters);
m_textLine += DRAW_STRING_NEW_LINE;
}
if (b2_toiCalls > 0)
{
g_debugDraw.DrawString(5, m_textLine, "toi calls = %d, ave toi iters = %3.1f, max toi iters = %d",
b2_toiCalls, b2_toiIters / float32(b2_toiCalls), b2_toiMaxRootIters);
m_textLine += DRAW_STRING_NEW_LINE;
g_debugDraw.DrawString(5, m_textLine, "ave toi root iters = %3.1f, max toi root iters = %d",
b2_toiRootIters / float32(b2_toiCalls), b2_toiMaxRootIters);
m_textLine += DRAW_STRING_NEW_LINE;
}
if (m_stepCount % 60 == 0)
{
Launch();
}
}
static Test* Create()
{
return new BulletTest;
}
b2Body* m_body;
b2Body* m_bullet;
float32 m_x;
};
#endif
| 412 | 0.907364 | 1 | 0.907364 | game-dev | MEDIA | 0.946782 | game-dev,testing-qa | 0.885981 | 1 | 0.885981 |
glKarin/com.n0n3m4.diii4a | 22,364 | Q3E/src/main/jni/quake2/zaero/src/savegame/savegame.c | /*
* =======================================================================
*
* The savegame system.
*
* =======================================================================
*/
/*
* This is the Quake 2 savegame system, fixed by Yamagi
* based on an idea by Knightmare of kmquake2. This major
* rewrite of the original g_save.c is much more robust
* and portable since it doesn't use any function pointers.
*
* Inner workings:
* When the game is saved all function pointers are
* translated into human readable function definition strings.
* The same way all mmove_t pointers are translated. This
* human readable strings are then written into the file.
* At game load the human readable strings are retranslated
* into the actual function pointers and struct pointers. The
* pointers are generated at each compilation / start of the
* client, thus the pointers are always correct.
*
* Limitations:
* While savegames survive recompilations of the game source
* and bigger changes in the source, there are some limitation
* which a nearly impossible to fix without a object orientated
* rewrite of the game.
* - If functions or mmove_t structs that a referencenced
* inside savegames are added or removed (e.g. the files
* in tables/ are altered) the load functions cannot
* reconnect all pointers and thus not restore the game.
* - If the operating system is changed internal structures
* may change in an unrepairable way.
* - If the architecture is changed pointer length and
* other internal datastructures change in an
* incompatible way.
* - If the edict_t struct is changed, savegames
* will break.
* This is not so bad as it looks since functions and
* struct won't be added and edict_t won't be changed
* if no big, sweeping changes are done. The operating
* system and architecture are in the hands of the user.
*/
#include "../header/local.h"
/*
* When ever the savegame version
* is changed, q2 will refuse to
* load older savegames. This
* should be bumped if the files
* in tables/ are changed, otherwise
* strange things may happen.
*/
#define SAVEGAMEVER "YQ2-4"
/*
* This macros are used to prohibit loading of savegames
* created on other systems or architectures. This will
* crash q2 in spectacular ways
*/
#ifndef YQ2OSTYPE
#error YQ2OSTYPE should be defined by the build system
#endif
#ifndef YQ2ARCH
#error YQ2ARCH should be defined by the build system
#endif
/*
* Older operating system and architecture detection
* macros, implemented by savegame version YQ2-1.
*/
#if defined(__APPLE__)
#define YQ2OSTYPE_1 "MacOS X"
#elif defined(__FreeBSD__)
#define YQ2OSTYPE_1 "FreeBSD"
#elif defined(__OpenBSD__)
#define YQ2OSTYPE_1 "OpenBSD"
#elif defined(__linux__)
#define YQ2OSTYPE_1 "Linux"
#elif defined(_WIN32)
#define YQ2OSTYPE_1 "Windows"
#else
#define YQ2OSTYPE_1 "Unknown"
#endif
#if defined(__i386__)
#define YQ2ARCH_1 "i386"
#elif defined(__x86_64__)
#define YQ2ARCH_1 "amd64"
#elif defined(__sparc__)
#define YQ2ARCH_1 "sparc64"
#elif defined(__ia64__)
#define YQ2ARCH_1 "ia64"
#else
#define YQ2ARCH_1 "unknown"
#endif
/*
* Connects a human readable
* function signature with
* the corresponding pointer
*/
typedef struct
{
char *funcStr;
byte *funcPtr;
} functionList_t;
/*
* Connects a human readable
* mmove_t string with the
* correspondig pointer
* */
typedef struct
{
char *mmoveStr;
mmove_t *mmovePtr;
} mmoveList_t;
typedef struct
{
char ver[32];
char game[32];
char os[32];
char arch[32];
} savegameHeader_t;
/* ========================================================= */
/*
* Prototypes for forward
* declaration for all game
* functions.
*/
#include "tables/gamefunc_decs.h"
/*
* List with function pointer
* to each of the functions
* prototyped above.
*/
functionList_t functionList[] = {
#include "tables/gamefunc_list.h"
};
/*
* Prtotypes for forward
* declaration for all game
* mmove_t functions.
*/
#include "tables/gamemmove_decs.h"
/*
* List with pointers to
* each of the mmove_t
* functions prototyped
* above.
*/
mmoveList_t mmoveList[] = {
#include "tables/gamemmove_list.h"
};
/*
* Fields to be saved
*/
field_t fields[] = {
#include "tables/fields.h"
};
/*
* Level fields to
* be saved
*/
field_t levelfields[] = {
#include "tables/levelfields.h"
};
/*
* Client fields to
* be saved
*/
field_t clientfields[] = {
#include "tables/clientfields.h"
};
/* ========================================================= */
/*
* This will be called when the dll is first loaded,
* which only happens when a new game is started or
* a save game is loaded.
*/
void
InitGame(void)
{
gi.dprintf("Game is starting up.\n");
gi.dprintf("Game is %s built on %s.\n", GAMEVERSION, __DATE__);
gun_x = gi.cvar ("gun_x", "0", 0);
gun_y = gi.cvar ("gun_y", "0", 0);
gun_z = gi.cvar ("gun_z", "0", 0);
sv_rollspeed = gi.cvar ("sv_rollspeed", "200", 0);
sv_rollangle = gi.cvar ("sv_rollangle", "2", 0);
sv_maxvelocity = gi.cvar ("sv_maxvelocity", "2000", 0);
sv_gravity = gi.cvar ("sv_gravity", "800", 0);
/* noset vars */
dedicated = gi.cvar ("dedicated", "0", CVAR_NOSET);
/* latched vars */
sv_cheats = gi.cvar ("cheats", "0", CVAR_SERVERINFO|CVAR_LATCH);
gi.cvar ("gamename", GAMEVERSION , CVAR_SERVERINFO | CVAR_LATCH);
gi.cvar ("gamedate", __DATE__ , CVAR_SERVERINFO | CVAR_LATCH);
maxclients = gi.cvar ("maxclients", "4", CVAR_SERVERINFO | CVAR_LATCH);
deathmatch = gi.cvar ("deathmatch", "0", CVAR_LATCH);
coop = gi.cvar ("coop", "0", CVAR_LATCH);
skill = gi.cvar ("skill", "1", CVAR_LATCH);
maxentities = gi.cvar ("maxentities", va("%i",MAX_EDICTS), CVAR_LATCH);
/* change anytime vars */
dmflags = gi.cvar ("dmflags", "0", CVAR_SERVERINFO);
fraglimit = gi.cvar ("fraglimit", "0", CVAR_SERVERINFO);
timelimit = gi.cvar ("timelimit", "0", CVAR_SERVERINFO);
password = gi.cvar ("password", "", CVAR_USERINFO);
g_select_empty = gi.cvar ("g_select_empty", "0", CVAR_ARCHIVE);
run_pitch = gi.cvar ("run_pitch", "0.002", 0);
run_roll = gi.cvar ("run_roll", "0.005", 0);
bob_up = gi.cvar ("bob_up", "0.005", 0);
bob_pitch = gi.cvar ("bob_pitch", "0.002", 0);
bob_roll = gi.cvar ("bob_roll", "0.002", 0);
/* others */
aimfix = gi.cvar("aimfix", "0", CVAR_ARCHIVE);
g_machinegun_norecoil = gi.cvar("g_machinegun_norecoil", "0", CVAR_ARCHIVE);
g_quick_weap = gi.cvar("g_quick_weap", "1", CVAR_ARCHIVE);
g_swap_speed = gi.cvar("g_swap_speed", "1", CVAR_ARCHIVE);
/* items */
InitItems ();
Com_sprintf (game.helpmessage1, sizeof(game.helpmessage1), "");
Com_sprintf (game.helpmessage2, sizeof(game.helpmessage2), "");
/* initialize all entities for this game */
game.maxentities = maxentities->value;
g_edicts = gi.TagMalloc (game.maxentities * sizeof(g_edicts[0]), TAG_GAME);
globals.edicts = g_edicts;
globals.max_edicts = game.maxentities;
/* initialize all clients for this game */
game.maxclients = maxclients->value;
game.clients = gi.TagMalloc (game.maxclients * sizeof(game.clients[0]), TAG_GAME);
globals.num_edicts = game.maxclients+1;
}
/* ========================================================= */
/*
* Helper function to get
* the human readable function
* definition by an address.
* Called by WriteField1 and
* WriteField2.
*/
functionList_t *
GetFunctionByAddress(byte *adr)
{
int i;
for (i = 0; functionList[i].funcStr; i++)
{
if (functionList[i].funcPtr == adr)
{
return &functionList[i];
}
}
return NULL;
}
/*
* Helper function to get the
* pointer to a function by
* it's human readable name.
* Called by WriteField1 and
* WriteField2.
*/
byte *
FindFunctionByName(char *name)
{
int i;
for (i = 0; functionList[i].funcStr; i++)
{
if (!strcmp(name, functionList[i].funcStr))
{
return functionList[i].funcPtr;
}
}
return NULL;
}
/*
* Helper function to get the
* human readable definition of
* a mmove_t struct by a pointer.
*/
mmoveList_t *
GetMmoveByAddress(mmove_t *adr)
{
int i;
for (i = 0; mmoveList[i].mmoveStr; i++)
{
if (mmoveList[i].mmovePtr == adr)
{
return &mmoveList[i];
}
}
return NULL;
}
/*
* Helper function to get the
* pointer to a mmove_t struct
* by a human readable definition.
*/
mmove_t *
FindMmoveByName(char *name)
{
int i;
for (i = 0; mmoveList[i].mmoveStr; i++)
{
if (!strcmp(name, mmoveList[i].mmoveStr))
{
return mmoveList[i].mmovePtr;
}
}
return NULL;
}
/* ========================================================= */
/*
* The following two functions are
* doing the dirty work to write the
* data generated by the functions
* below this block into files.
*/
void
WriteField1(FILE *f, field_t *field, byte *base)
{
void *p;
int len;
int index;
functionList_t *func;
mmoveList_t *mmove;
if (field->flags & FFL_SPAWNTEMP)
{
return;
}
p = (void *)(base + field->ofs);
switch (field->type)
{
case F_INT:
case F_FLOAT:
case F_ANGLEHACK:
case F_VECTOR:
case F_IGNORE:
break;
case F_LSTRING:
case F_GSTRING:
if (*(char **)p)
{
len = strlen(*(char **)p) + 1;
}
else
{
len = 0;
}
*(int *)p = len;
break;
case F_EDICT:
if (*(edict_t **)p == NULL)
{
index = -1;
}
else
{
index = *(edict_t **)p - g_edicts;
}
*(int *)p = index;
break;
case F_CLIENT:
if (*(gclient_t **)p == NULL)
{
index = -1;
}
else
{
index = *(gclient_t **)p - game.clients;
}
*(int *)p = index;
break;
case F_ITEM:
if (*(edict_t **)p == NULL)
{
index = -1;
}
else
{
index = *(gitem_t **)p - itemlist;
}
*(int *)p = index;
break;
case F_FUNCTION:
if (*(byte **)p == NULL)
{
len = 0;
}
else
{
func = GetFunctionByAddress (*(byte **)p);
if (!func)
{
gi.error ("WriteField1: function not in list, can't save game");
}
len = strlen(func->funcStr)+1;
}
*(int *)p = len;
break;
case F_MMOVE:
if (*(byte **)p == NULL)
{
len = 0;
}
else
{
mmove = GetMmoveByAddress (*(mmove_t **)p);
if (!mmove)
{
gi.error ("WriteField1: mmove not in list, can't save game");
}
len = strlen(mmove->mmoveStr)+1;
}
*(int *)p = len;
break;
default:
gi.error("WriteEdict: unknown field type");
}
}
void
WriteField2(FILE *f, field_t *field, byte *base)
{
int len;
void *p;
functionList_t *func;
mmoveList_t *mmove;
if (field->flags & FFL_SPAWNTEMP)
{
return;
}
p = (void *)(base + field->ofs);
switch (field->type)
{
case F_LSTRING:
if (*(char **)p)
{
len = strlen(*(char **)p) + 1;
fwrite(*(char **)p, len, 1, f);
}
break;
case F_FUNCTION:
if (*(byte **)p)
{
func = GetFunctionByAddress (*(byte **)p);
if (!func)
{
gi.error ("WriteField2: function not in list, can't save game");
}
len = strlen(func->funcStr)+1;
fwrite (func->funcStr, len, 1, f);
}
break;
case F_MMOVE:
if (*(byte **)p)
{
mmove = GetMmoveByAddress (*(mmove_t **)p);
if (!mmove)
{
gi.error ("WriteField2: mmove not in list, can't save game");
}
len = strlen(mmove->mmoveStr)+1;
fwrite (mmove->mmoveStr, len, 1, f);
}
break;
default:
break;
}
}
/* ========================================================= */
/*
* This function does the dirty
* work to read the data from a
* file. The processing of the
* data is done in the functions
* below
*/
void
ReadField(FILE *f, field_t *field, byte *base)
{
void *p;
int len;
int index;
char funcStr[2048];
if (field->flags & FFL_SPAWNTEMP)
{
return;
}
p = (void *)(base + field->ofs);
switch (field->type)
{
case F_INT:
case F_FLOAT:
case F_ANGLEHACK:
case F_VECTOR:
case F_IGNORE:
break;
case F_LSTRING:
len = *(int *)p;
if (!len)
{
*(char **)p = NULL;
}
else
{
*(char **)p = gi.TagMalloc(32 + len, TAG_LEVEL);
fread(*(char **)p, len, 1, f);
}
break;
case F_EDICT:
index = *(int *)p;
if (index == -1)
{
*(edict_t **)p = NULL;
}
else
{
*(edict_t **)p = &g_edicts[index];
}
break;
case F_CLIENT:
index = *(int *)p;
if (index == -1)
{
*(gclient_t **)p = NULL;
}
else
{
*(gclient_t **)p = &game.clients[index];
}
break;
case F_ITEM:
index = *(int *)p;
if (index == -1)
{
*(gitem_t **)p = NULL;
}
else
{
*(gitem_t **)p = &itemlist[index];
}
break;
case F_FUNCTION:
len = *(int *)p;
if (!len)
{
*(byte **)p = NULL;
}
else
{
if (len > sizeof(funcStr))
{
gi.error ("ReadField: function name is longer than buffer (%i chars)",
sizeof(funcStr));
}
fread (funcStr, len, 1, f);
if ( !(*(byte **)p = FindFunctionByName (funcStr)) )
{
gi.error ("ReadField: function %s not found in table, can't load game", funcStr);
}
}
break;
case F_MMOVE:
len = *(int *)p;
if (!len)
{
*(byte **)p = NULL;
}
else
{
if (len > sizeof(funcStr))
{
gi.error ("ReadField: mmove name is longer than buffer (%i chars)",
sizeof(funcStr));
}
fread (funcStr, len, 1, f);
if ( !(*(mmove_t **)p = FindMmoveByName (funcStr)) )
{
gi.error ("ReadField: mmove %s not found in table, can't load game", funcStr);
}
}
break;
default:
gi.error("ReadEdict: unknown field type");
}
}
/* ========================================================= */
/*
* Write the client struct into a file.
*/
void
WriteClient(FILE *f, gclient_t *client)
{
field_t *field;
gclient_t temp;
/* all of the ints, floats, and vectors stay as they are */
temp = *client;
/* change the pointers to indexes */
for (field = clientfields; field->name; field++)
{
WriteField1(f, field, (byte *)&temp);
}
/* write the block */
fwrite(&temp, sizeof(temp), 1, f);
/* now write any allocated data following the edict */
for (field = clientfields; field->name; field++)
{
WriteField2(f, field, (byte *)client);
}
}
/*
* Read the client struct from a file
*/
void
ReadClient(FILE *f, gclient_t *client, short save_ver)
{
field_t *field;
fread(client, sizeof(*client), 1, f);
for (field = clientfields; field->name; field++)
{
if (field->save_ver <= save_ver)
{
ReadField(f, field, (byte *)client);
}
}
if (save_ver < 3)
{
InitClientResp(client);
}
}
/* ========================================================= */
/*
* Writes the game struct into
* a file. This is called when
* ever the games goes to e new
* level or the user saves the
* game. Saved informations are:
* - cross level data
* - client states
* - help computer info
*/
void
WriteGame(const char *filename, qboolean autosave)
{
savegameHeader_t sv;
FILE *f;
int i;
if (!autosave)
{
SaveClientData();
}
f = fopen(filename, "wb");
if (!f)
{
gi.error("Couldn't open %s", filename);
}
/* Savegame identification */
memset(&sv, 0, sizeof(sv));
Q_strlcpy(sv.ver, SAVEGAMEVER, sizeof(sv.ver));
Q_strlcpy(sv.game, GAMEVERSION, sizeof(sv.game));
Q_strlcpy(sv.os, YQ2OSTYPE, sizeof(sv.os) - 1);
Q_strlcpy(sv.arch, YQ2ARCH, sizeof(sv.arch));
fwrite(&sv, sizeof(sv), 1, f);
game.autosaved = autosave;
fwrite(&game, sizeof(game), 1, f);
game.autosaved = false;
for (i = 0; i < game.maxclients; i++)
{
WriteClient(f, &game.clients[i]);
}
fclose(f);
}
/*
* Read the game structs from
* a file. Called when ever a
* savegames is loaded.
*/
void
ReadGame(const char *filename)
{
savegameHeader_t sv;
FILE *f;
int i;
short save_ver = 0;
gi.FreeTags(TAG_GAME);
f = fopen(filename, "rb");
if (!f)
{
gi.error("Couldn't open %s", filename);
}
/* Sanity checks */
fread(&sv, sizeof(sv), 1, f);
static const struct {
const char* verstr;
int vernum;
} version_mappings[] = {
{"YQ2-1", 1},
{"YQ2-2", 2},
{"YQ2-3", 3},
{"YQ2-4", 4},
};
for (i=0; i < sizeof(version_mappings)/sizeof(version_mappings[0]); ++i)
{
if (strcmp(version_mappings[i].verstr, sv.ver) == 0)
{
save_ver = version_mappings[i].vernum;
break;
}
}
if (save_ver == 0) // not found in mappings table
{
fclose(f);
gi.error("Savegame from an incompatible version.\n");
}
if (save_ver == 1)
{
if (strcmp(sv.game, GAMEVERSION) != 0)
{
fclose(f);
gi.error("Savegame from another game.so.\n");
}
else if (strcmp(sv.os, YQ2OSTYPE_1) != 0)
{
fclose(f);
gi.error("Savegame from another os.\n");
}
#ifdef _WIN32
/* Windows was forced to i386 */
if (strcmp(sv.arch, "i386") != 0)
{
fclose(f);
gi.error("Savegame from another architecture.\n");
}
#else
if (strcmp(sv.arch, YQ2ARCH_1) != 0)
{
fclose(f);
gi.error("Savegame from another architecture.\n");
}
#endif
}
else // all newer savegame versions
{
if (strcmp(sv.game, GAMEVERSION) != 0)
{
fclose(f);
gi.error("Savegame from another game.so.\n");
}
else if (strcmp(sv.os, YQ2OSTYPE) != 0)
{
fclose(f);
gi.error("Savegame from another os.\n");
}
else if (strcmp(sv.arch, YQ2ARCH) != 0)
{
#if defined(_WIN32) && (defined(__i386__) || defined(_M_IX86))
// before savegame version "YQ2-4" (and after version 1),
// the official Win32 binaries accidentally had the YQ2ARCH "AMD64"
// instead of "i386" set due to a bug in the Makefile.
// This quirk allows loading those savegames anyway
if (save_ver >= 4 || strcmp(sv.arch, "AMD64") != 0)
#endif
{
fclose(f);
gi.error("Savegame from another architecture.\n");
}
}
}
g_edicts = gi.TagMalloc(game.maxentities * sizeof(g_edicts[0]), TAG_GAME);
globals.edicts = g_edicts;
fread(&game, sizeof(game), 1, f);
game.clients = gi.TagMalloc(game.maxclients * sizeof(game.clients[0]),
TAG_GAME);
for (i = 0; i < game.maxclients; i++)
{
ReadClient(f, &game.clients[i], save_ver);
}
fclose(f);
}
/* ========================================================== */
/*
* Helper function to write the
* edict into a file. Called by
* WriteLevel.
*/
void
WriteEdict(FILE *f, edict_t *ent)
{
field_t *field;
edict_t temp;
/* all of the ints, floats, and vectors stay as they are */
temp = *ent;
/* change the pointers to lengths or indexes */
for (field = fields; field->name; field++)
{
WriteField1(f, field, (byte *)&temp);
}
/* write the block */
fwrite(&temp, sizeof(temp), 1, f);
/* now write any allocated data following the edict */
for (field = fields; field->name; field++)
{
WriteField2(f, field, (byte *)ent);
}
}
/*
* Helper fcuntion to write the
* level local data into a file.
* Called by WriteLevel.
*/
void
WriteLevelLocals(FILE *f)
{
field_t *field;
level_locals_t temp;
/* all of the ints, floats, and vectors stay as they are */
temp = level;
/* change the pointers to lengths or indexes */
for (field = levelfields; field->name; field++)
{
WriteField1(f, field, (byte *)&temp);
}
/* write the block */
fwrite(&temp, sizeof(temp), 1, f);
/* now write any allocated data following the edict */
for (field = levelfields; field->name; field++)
{
WriteField2(f, field, (byte *)&level);
}
}
/*
* Writes the current level
* into a file.
*/
void
WriteLevel(const char *filename)
{
int i;
edict_t *ent;
FILE *f;
f = fopen(filename, "wb");
if (!f)
{
gi.error("Couldn't open %s", filename);
}
/* write out edict size for checking */
i = sizeof(edict_t);
fwrite(&i, sizeof(i), 1, f);
/* write out level_locals_t */
WriteLevelLocals(f);
/* write out all the entities */
for (i = 0; i < globals.num_edicts; i++)
{
ent = &g_edicts[i];
if (!ent->inuse)
{
continue;
}
fwrite(&i, sizeof(i), 1, f);
WriteEdict(f, ent);
}
i = -1;
fwrite(&i, sizeof(i), 1, f);
fclose(f);
}
/* ========================================================== */
/*
* A helper function to
* read the edict back
* into the memory. Called
* by ReadLevel.
*/
void
ReadEdict(FILE *f, edict_t *ent)
{
field_t *field;
fread(ent, sizeof(*ent), 1, f);
for (field = fields; field->name; field++)
{
ReadField(f, field, (byte *)ent);
}
}
/*
* A helper function to
* read the level local
* data from a file.
* Called by ReadLevel.
*/
void
ReadLevelLocals(FILE *f)
{
field_t *field;
fread(&level, sizeof(level), 1, f);
for (field = levelfields; field->name; field++)
{
ReadField(f, field, (byte *)&level);
}
}
/*
* Reads a level back into the memory.
* SpawnEntities were allready called
* in the same way when the level was
* saved. All world links were cleared
* befor this function was called. When
* this function is called, no clients
* are connected to the server.
*/
void
ReadLevel(const char *filename)
{
int entnum;
FILE *f;
int i;
edict_t *ent;
f = fopen(filename, "rb");
if (!f)
{
gi.error("Couldn't open %s", filename);
}
/* free any dynamic memory allocated by
loading the level base state */
gi.FreeTags(TAG_LEVEL);
/* wipe all the entities */
memset(g_edicts, 0, game.maxentities * sizeof(g_edicts[0]));
globals.num_edicts = maxclients->value + 1;
/* check edict size */
fread(&i, sizeof(i), 1, f);
if (i != sizeof(edict_t))
{
fclose(f);
gi.error("ReadLevel: mismatched edict size");
}
/* load the level locals */
ReadLevelLocals(f);
/* load all the entities */
while (1)
{
if (fread(&entnum, sizeof(entnum), 1, f) != 1)
{
fclose(f);
gi.error("ReadLevel: failed to read entnum");
}
if (entnum == -1)
{
break;
}
if (entnum >= globals.num_edicts)
{
globals.num_edicts = entnum + 1;
}
ent = &g_edicts[entnum];
ReadEdict(f, ent);
/* let the server rebuild world links for this ent */
memset(&ent->area, 0, sizeof(ent->area));
gi.linkentity(ent);
}
fclose(f);
/* mark all clients as unconnected */
for (i = 0; i < maxclients->value; i++)
{
ent = &g_edicts[i + 1];
ent->client = game.clients + i;
ent->client->pers.connected = false;
}
/* do any load time things at this point */
for (i = 0; i < globals.num_edicts; i++)
{
ent = &g_edicts[i];
if (!ent->inuse)
{
continue;
}
/* fire any cross-level triggers */
if (ent->classname)
{
if (strcmp(ent->classname, "target_crosslevel_target") == 0)
{
ent->nextthink = level.time + ent->delay;
}
}
}
}
| 412 | 0.844511 | 1 | 0.844511 | game-dev | MEDIA | 0.902602 | game-dev | 0.837436 | 1 | 0.837436 |
manisha-v/Number-Cruncher | 5,250 | Codes/Minor2d/Library/PackageCache/com.unity.timeline@1.2.18/Runtime/Utilities/AnimatorBindingCache.cs | #if UNITY_EDITOR
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Playables;
using UnityEngine.Timeline;
using UnityEditor;
namespace UnityEngine.Timeline
{
/// <summary>
/// Animator to Editor Curve Binding cache. Used to prevent frequent calls to GetAnimatorBindings which can be costly
/// </summary>
class AnimatorBindingCache
{
public const string TRPlaceHolder = "TransformTR";
public const string ScalePlaceholder = "TransformScale";
struct AnimatorEntry
{
public int animatorID;
public bool applyRootMotion;
public bool humanoid;
}
class AnimatorEntryComparer : IEqualityComparer<AnimatorEntry>
{
public bool Equals(AnimatorEntry x, AnimatorEntry y) { return x.animatorID == y.animatorID && x.applyRootMotion == y.applyRootMotion && x.humanoid == y.humanoid; }
public int GetHashCode(AnimatorEntry obj) { return HashUtility.CombineHash(obj.animatorID, obj.applyRootMotion.GetHashCode(), obj.humanoid.GetHashCode()); }
public static readonly AnimatorEntryComparer Instance = new AnimatorEntryComparer();
}
readonly Dictionary<AnimatorEntry, EditorCurveBinding[]> m_AnimatorCache = new Dictionary<AnimatorEntry, EditorCurveBinding[]>(AnimatorEntryComparer.Instance);
readonly Dictionary<AnimationClip, EditorCurveBinding[]> m_ClipCache = new Dictionary<AnimationClip, EditorCurveBinding[]>();
private static readonly EditorCurveBinding[] kEmptyArray = new EditorCurveBinding[0];
private static readonly List<EditorCurveBinding> s_BindingScratchPad = new List<EditorCurveBinding>(1000);
public AnimatorBindingCache()
{
AnimationUtility.onCurveWasModified += OnCurveWasModified;
}
public EditorCurveBinding[] GetAnimatorBindings(GameObject gameObject)
{
if (gameObject == null)
return kEmptyArray;
Animator animator = gameObject.GetComponent<Animator>();
if (animator == null)
return kEmptyArray;
AnimatorEntry entry = new AnimatorEntry()
{
animatorID = animator.GetInstanceID(),
applyRootMotion = animator.applyRootMotion,
humanoid = animator.isHuman
};
EditorCurveBinding[] result = null;
if (m_AnimatorCache.TryGetValue(entry, out result))
return result;
s_BindingScratchPad.Clear();
// Replacement for AnimationMode.GetAnimatorBinding - this is faster and allocates kB instead of MB
var transforms = animator.GetComponentsInChildren<Transform>();
foreach (var t in transforms)
{
if (animator.IsBoneTransform(t))
s_BindingScratchPad.Add(EditorCurveBinding.FloatCurve(AnimationUtility.CalculateTransformPath(t, animator.transform), typeof(Transform), TRPlaceHolder));
}
var streamBindings = AnimationUtility.GetAnimationStreamBindings(animator.gameObject);
UpdateTransformBindings(streamBindings);
s_BindingScratchPad.AddRange(streamBindings);
result = new EditorCurveBinding[s_BindingScratchPad.Count];
s_BindingScratchPad.CopyTo(result);
m_AnimatorCache[entry] = result;
return result;
}
public EditorCurveBinding[] GetCurveBindings(AnimationClip clip)
{
if (clip == null)
return kEmptyArray;
EditorCurveBinding[] result;
if (!m_ClipCache.TryGetValue(clip, out result))
{
result = AnimationMode.GetCurveBindings(clip);
UpdateTransformBindings(result);
m_ClipCache[clip] = result;
}
return result;
}
private static void UpdateTransformBindings(EditorCurveBinding[] bindings)
{
for (int i = 0; i < bindings.Length; i++)
{
var binding = bindings[i];
if (AnimationPreviewUtilities.IsRootMotion(binding))
{
binding.type = typeof(Transform);
binding.propertyName = TRPlaceHolder;
}
else if (typeof(Transform).IsAssignableFrom(binding.type) && (binding.propertyName.StartsWith("m_LocalRotation.") || binding.propertyName.StartsWith("m_LocalPosition.")))
{
binding.propertyName = TRPlaceHolder;
}
else if (typeof(Transform).IsAssignableFrom(binding.type) && binding.propertyName.StartsWith("m_LocalScale."))
{
binding.propertyName = ScalePlaceholder;
}
bindings[i] = binding;
}
}
public void Clear()
{
m_AnimatorCache.Clear();
m_ClipCache.Clear();
}
void OnCurveWasModified(AnimationClip clip, EditorCurveBinding binding, AnimationUtility.CurveModifiedType modification)
{
m_ClipCache.Remove(clip);
}
}
}
#endif
| 412 | 0.845636 | 1 | 0.845636 | game-dev | MEDIA | 0.560312 | game-dev | 0.96986 | 1 | 0.96986 |
space-wizards/space-station-14 | 4,335 | Content.Shared/PowerCell/SharedPowerCellSystem.cs | using Content.Shared.Containers.ItemSlots;
using Content.Shared.Emp;
using Content.Shared.PowerCell.Components;
using Content.Shared.Rejuvenate;
using Robust.Shared.Containers;
using Robust.Shared.Timing;
namespace Content.Shared.PowerCell;
public abstract class SharedPowerCellSystem : EntitySystem
{
[Dependency] protected readonly IGameTiming Timing = default!;
[Dependency] private readonly ItemSlotsSystem _itemSlots = default!;
[Dependency] private readonly SharedAppearanceSystem _appearance = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<PowerCellDrawComponent, MapInitEvent>(OnMapInit);
SubscribeLocalEvent<PowerCellSlotComponent, RejuvenateEvent>(OnRejuvenate);
SubscribeLocalEvent<PowerCellSlotComponent, EntInsertedIntoContainerMessage>(OnCellInserted);
SubscribeLocalEvent<PowerCellSlotComponent, EntRemovedFromContainerMessage>(OnCellRemoved);
SubscribeLocalEvent<PowerCellSlotComponent, ContainerIsInsertingAttemptEvent>(OnCellInsertAttempt);
SubscribeLocalEvent<PowerCellComponent, EmpAttemptEvent>(OnCellEmpAttempt);
}
private void OnMapInit(Entity<PowerCellDrawComponent> ent, ref MapInitEvent args)
{
ent.Comp.NextUpdateTime = Timing.CurTime + ent.Comp.Delay;
}
private void OnRejuvenate(EntityUid uid, PowerCellSlotComponent component, RejuvenateEvent args)
{
if (!_itemSlots.TryGetSlot(uid, component.CellSlotId, out var itemSlot) || !itemSlot.Item.HasValue)
return;
// charge entity batteries and remove booby traps.
RaiseLocalEvent(itemSlot.Item.Value, args);
}
private void OnCellInsertAttempt(EntityUid uid, PowerCellSlotComponent component, ContainerIsInsertingAttemptEvent args)
{
if (!component.Initialized)
return;
if (args.Container.ID != component.CellSlotId)
return;
if (!HasComp<PowerCellComponent>(args.EntityUid))
{
args.Cancel();
}
}
private void OnCellInserted(EntityUid uid, PowerCellSlotComponent component, EntInsertedIntoContainerMessage args)
{
if (!component.Initialized)
return;
if (args.Container.ID != component.CellSlotId)
return;
_appearance.SetData(uid, PowerCellSlotVisuals.Enabled, true);
RaiseLocalEvent(uid, new PowerCellChangedEvent(false), false);
}
protected virtual void OnCellRemoved(EntityUid uid, PowerCellSlotComponent component, EntRemovedFromContainerMessage args)
{
if (args.Container.ID != component.CellSlotId)
return;
_appearance.SetData(uid, PowerCellSlotVisuals.Enabled, false);
RaiseLocalEvent(uid, new PowerCellChangedEvent(true), false);
}
private void OnCellEmpAttempt(EntityUid uid, PowerCellComponent component, EmpAttemptEvent args)
{
var parent = Transform(uid).ParentUid;
// relay the attempt event to the slot so it can cancel it
if (HasComp<PowerCellSlotComponent>(parent))
RaiseLocalEvent(parent, ref args);
}
public void SetDrawEnabled(Entity<PowerCellDrawComponent?> ent, bool enabled)
{
if (!Resolve(ent, ref ent.Comp, false) || ent.Comp.Enabled == enabled)
return;
if (enabled)
ent.Comp.NextUpdateTime = Timing.CurTime;
ent.Comp.Enabled = enabled;
Dirty(ent, ent.Comp);
}
/// <summary>
/// Returns whether the entity has a slotted battery and <see cref="PowerCellDrawComponent.UseRate"/> charge.
/// </summary>
/// <param name="uid"></param>
/// <param name="battery"></param>
/// <param name="cell"></param>
/// <param name="user">Popup to this user with the relevant detail if specified.</param>
public abstract bool HasActivatableCharge(
EntityUid uid,
PowerCellDrawComponent? battery = null,
PowerCellSlotComponent? cell = null,
EntityUid? user = null);
/// <summary>
/// Whether the power cell has any power at all for the draw rate.
/// </summary>
public abstract bool HasDrawCharge(
EntityUid uid,
PowerCellDrawComponent? battery = null,
PowerCellSlotComponent? cell = null,
EntityUid? user = null);
}
| 412 | 0.972024 | 1 | 0.972024 | game-dev | MEDIA | 0.963208 | game-dev | 0.934475 | 1 | 0.934475 |
Dimbreath/AzurLaneData | 4,112 | ko-KR/view/battle/battledodgemresultlayer.lua | slot0 = class("BattleDodgemResultLayer", import(".BattleResultLayer"))
function slot0.didEnter(slot0)
setText(slot0._levelText, pg.expedition_data_template[slot0.contextData.stageId].name)
slot3 = rtf(slot0._grade)
slot0._gradeUpperLeftPos = slot3.localPosition
slot3.localPosition = Vector3(0, 25, 0)
pg.UIMgr.GetInstance():BlurPanel(slot0._tf)
slot0._grade.transform.localScale = Vector3(1.5, 1.5, 0)
LeanTween.scale(slot0._grade, Vector3(0.88, 0.88, 1), uv0.DURATION_WIN_SCALE):setOnComplete(System.Action(function ()
SetActive(uv0._levelText, true)
uv0:rankAnimaFinish()
end))
slot0._tf:GetComponent(typeof(Image)).color = Color.New(0, 0, 0, 0.5)
slot0._stateFlag = BattleResultLayer.STATE_RANK_ANIMA
onButton(slot0, slot0._skipBtn, function ()
uv0:skip()
end, SFX_CONFIRM)
end
function slot0.rankAnimaFinish(slot0)
SetActive(slot0:findTF("main/conditions"), true)
SetActive(slot0._conditionBGNormal, false)
SetActive(slot0._conditionBGContribute, true)
slot2 = slot0.contextData.statistics.dodgemResult
slot0:setCondition(i18n("battle_result_total_score"), slot2.score, COLOR_BLUE)
slot0:setCondition(i18n("battle_result_max_combo"), slot2.maxCombo, COLOR_YELLOW)
table.insert(slot0._delayLeanList, LeanTween.delayedCall(1, System.Action(function ()
uv0._stateFlag = uv1.STATE_REPORTED
SetActive(uv0:findTF("jieuan01/tips", uv0._bg), true)
end)).id)
slot0._stateFlag = uv0.STATE_REPORT
end
function slot0.displayBG(slot0)
LeanTween.moveX(rtf(slot0._conditions), 1300, uv0.DURATION_MOVE)
LeanTween.scale(slot0._grade, Vector3(0.6, 0.6, 0), uv0.DURATION_MOVE)
LeanTween.moveLocal(go(rtf(slot0._grade)), slot0._gradeUpperLeftPos, uv0.DURATION_MOVE):setOnComplete(System.Action(function ()
uv0:showPainting()
end))
setActive(slot0:findTF("jieuan01/Bomb", slot0._bg), false)
end
function slot0.setCondition(slot0, slot1, slot2, slot3)
slot4 = cloneTplTo(slot0._conditionContributeTpl, slot0._conditionContainer)
setActive(slot4, false)
slot5 = nil
slot4:Find("text"):GetComponent(typeof(Text)).text = setColorStr(slot1, "#FFFFFFFF")
slot4:Find("value"):GetComponent(typeof(Text)).text = setColorStr(slot2, slot3)
if slot0._conditionContainer.childCount - 1 > 0 then
table.insert(slot0._delayLeanList, LeanTween.delayedCall(uv0.CONDITIONS_FREQUENCE * slot8, System.Action(function ()
setActive(uv0, true)
end)).id)
else
setActive(slot4, true)
end
end
function slot0.showPainting(slot0)
slot1, slot2, slot3 = nil
SetActive(slot0._painting, true)
slot0.paintingName = "yanzhan"
setPaintingPrefabAsync(slot0._painting, slot0.paintingName, "jiesuan", function ()
if findTF(uv0._painting, "fitter").childCount > 0 then
ShipExpressionHelper.SetExpression(findTF(uv0._painting, "fitter"):GetChild(0), uv0.paintingName, "win_mvp")
end
end)
SetActive(slot0._failPainting, false)
if slot0.contextData.score > 1 then
slot1, slot3, slot2 = ShipWordHelper.GetWordAndCV(205020, ShipWordHelper.WORD_TYPE_MVP)
else
slot1, slot3, slot2 = ShipWordHelper.GetWordAndCV(205020, ShipWordHelper.WORD_TYPE_LOSE)
end
setText(slot0._chat:Find("Text"), slot2)
if CHAT_POP_STR_LEN < #slot0._chat:Find("Text"):GetComponent(typeof(Text)).text then
slot4.alignment = TextAnchor.MiddleLeft
else
slot4.alignment = TextAnchor.MiddleCenter
end
SetActive(slot0._chat, true)
slot0._chat.transform.localScale = Vector3.New(0, 0, 0)
LeanTween.moveX(rtf(slot0._painting), 50, 0.1):setOnComplete(System.Action(function ()
LeanTween.scale(rtf(uv0._chat.gameObject), Vector3.New(1, 1, 1), 0.1):setEase(LeanTweenType.easeOutBack)
end))
slot0._stateFlag = BattleResultLayer.STATE_DISPLAYED
end
function slot0.skip(slot0)
if slot0._stateFlag == BattleResultLayer.STATE_REPORTED then
slot0:displayBG()
elseif slot0._stateFlag == BattleResultLayer.STATE_DISPLAYED then
slot0:emit(BattleResultMediator.ON_BACK_TO_LEVEL_SCENE)
end
end
function slot0.onBackPressed(slot0)
triggerButton(slot0._skipBtn)
end
function slot0.willExit(slot0)
LeanTween.cancel(go(slot0._tf))
pg.UIMgr.GetInstance():UnblurPanel(slot0._tf)
end
return slot0
| 412 | 0.847864 | 1 | 0.847864 | game-dev | MEDIA | 0.951895 | game-dev | 0.942039 | 1 | 0.942039 |
FallingColors/HexMod | 1,970 | Fabric/src/main/java/at/petrak/hexcasting/fabric/interop/emi/EmiBrainsweepRecipe.java | package at.petrak.hexcasting.fabric.interop.emi;
import dev.emi.emi.api.recipe.EmiRecipe;
import dev.emi.emi.api.recipe.EmiRecipeCategory;
import dev.emi.emi.api.stack.EmiIngredient;
import dev.emi.emi.api.stack.EmiStack;
import dev.emi.emi.api.widget.WidgetHolder;
import net.minecraft.resources.ResourceLocation;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import static at.petrak.hexcasting.api.HexAPI.modLoc;
public record EmiBrainsweepRecipe(EmiIngredient blockInput,
EmiIngredient villagerInput,
EmiStack output,
ResourceLocation id) implements EmiRecipe {
private static final ResourceLocation OVERLAY = modLoc("textures/gui/brainsweep_jei.png");
@Override
public EmiRecipeCategory getCategory() {
return HexEMIPlugin.BRAINSWEEP;
}
@Override
public @Nullable ResourceLocation getId() {
return id;
}
@Override
public List<EmiIngredient> getInputs() {
return List.of(blockInput, villagerInput);
}
@Override
public List<EmiStack> getOutputs() {
return List.of(output);
}
@Override
public int getDisplayWidth() {
return 118;
}
@Override
public int getDisplayHeight() {
return 85;
}
@Override
public void addWidgets(WidgetHolder widgets) {
widgets.addTexture(OVERLAY, 0, 0, getDisplayWidth(), getDisplayHeight(), 0, 0, getDisplayWidth(), getDisplayHeight(), 128, 128);
widgets.addSlot(blockInput, 11, 34).drawBack(false).customBackground(null, 0, 0, 19, 19);
widgets.add(new TheCoolerSlotWidget(villagerInput, 37, 19, 2.75f).useOffset(false).customShift(-8.5f, 2.485f))
.drawBack(false).customBackground(null, 0, 0, 27, 49);
widgets.addSlot(output, 86, 34).drawBack(false).large(true).recipeContext(this).customBackground(null, 0, 0, 19, 19);
}
}
| 412 | 0.730531 | 1 | 0.730531 | game-dev | MEDIA | 0.313465 | game-dev | 0.830919 | 1 | 0.830919 |
Kitware/VTK | 9,083 | Filters/ParallelDIY2/vtkGhostCellsGenerator.h | // SPDX-FileCopyrightText: Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
// SPDX-License-Identifier: BSD-3-Clause
/**
* @class vtkGhostCellsGenerator
* @brief Computes ghost cells on vtkCompositeDataSet inputs
*
* This filter computes ghost cells between data sets of same types in a `vtkCompositeDataSet`.
* For example, a `vtkImageData` inside a `vtkCompositeDataSet` will send and receive ghosts only to
* and from other `vtkImageData`.
* The backend used to generate the ghosts is `vtkDIYGhostUtilities::GenerateGhosts`.
*
* If the input is a `vtkPartitionedDataSetCollection`, then ghosts are computed per partitioned
* data set. In other words, ghost are not computed between 2 `vtkDataSet` belonging to 2 different
* `vtkPartitionedDataSet`, even if they are adjacent.
*
* If `BuildIfRequired` is set to true (which is by default), then the filter will compute ghost
* based on the value being returned by
* `vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_GHOST_LEVELS()` in the downstream streaming
* pipeline. If not (i.e. `BuildIfRequired` is off), then the max between this latter value and
* `NumberOfGhostLayers` is being used.
*
* Ghosts points are generated in addition to ghost cells. The same point exists across multiple
* partitions at the interface between them. One version of those points is not tagged as ghost,
* while the others are. As a consequence, there are as many non ghost points as there would be
* points if the input partitions were all merged into one partition.
*
* If the input is composed of some data sets already owning ghosts, those ghosts are removed from
* the output and are recomputed. Ghosts in the input are as if they didn't exist.
* A ghost cell is to be peeled off if it holds the `CELLDUPLICATE` flag in its ghost bit mask.
* Similarly, each generated ghost cells from this filter is tagged with `CELLDUPLICATE`, in
* addition of other tags that could be set (`HIDDENCELL` for instance).
*
* However, if `SynchronizeOnly` is On, ghost data will be synchronized between processes and ghost
* array won't be recomputed. This parameter assumes that the ghost layer remains unchanged. For
* this feature to work, the input must already have GlobalIds and ProcessIds arrays. Otherwise,
* the filter will fallback on its default behavior.
*
* To ease the subsequent use of the synchronization mechanism, two other options can be enabled
* to generate GlobalIds and ProcessIds on points/cells, via `GenerateGlobalIds` and
* `GenerateProcessIds`.
*
* If the input is a `vtkUnstructuredGrid`, if the input `vtkPointData` has global ids, then the
* values of those global ids are used instead of point position in 3D to connect 2 partitions.
* If not, point position of the outer surface are used to connect them. The precision of such
* connection is done using numeric precision of the input coordinates. Points and cells tagged as
* hidden ghosts are removed from the output.
*
* When requesting zero layers of ghost cells, ghost points are still generated. In this instance,
* the filter will produce a ghost cell array in the output if and only if the input is a structured
* data set (`vtkImageData`, `vtkRectilinearGrid`, or `vtkStructuredGrid`), and has hidden ghosts
* within its valid extent (extent when duplicate ghosts are peeled off).
*
* Points at the interface between 2 partitions are edited depending on the ownership of the point
* after the ghost points are generated. One can keep track of which process owns a non-ghost copy
* of the point if an array associating each point with its process id is available in the input.
*
* @warning If an input already holds ghosts, the input ghost cells should be tagged as
* `CELLDUPLICATE` in order for this filter to work properly.
*
* @note Currently,`vtkImageData`, `vtkRectilinearGrid`, `vtkStructuredGrid`,
* `vtkUnstructuredGrid` and `vtkPolyData` are implemented.
*
* @warning This warning only applies for `vtkUnstructuredGrid` and `vtkPolyData` inputs. If
* there are duplicate points in the outer shell of an input partition, then this filter cannot
* decide on how to connect the cells properly when generating ghosts. The same phenomenon occurs
* when the outer shell of the partition has 2 points with the same global id. In such
* circumstances, use the `vtkStaticCleanUnstructuredGrid`
* or `vtkStaticCleanPolyData` filter first in order to have a clean input.
*
* @sa vtkDIYGhostUtilities
*/
#ifndef vtkGhostCellsGenerator_h
#define vtkGhostCellsGenerator_h
#include "vtkPassInputTypeAlgorithm.h"
#include "vtkFiltersParallelDIY2Module.h" // for export macros
#include "vtkWeakPointer.h" // for vtkWeakPointer
VTK_ABI_NAMESPACE_BEGIN
class vtkDataObject;
class vtkMultiProcessController;
class vtkDataObjectMeshCache;
class VTKFILTERSPARALLELDIY2_EXPORT vtkGhostCellsGenerator : public vtkPassInputTypeAlgorithm
{
public:
static vtkGhostCellsGenerator* New();
vtkTypeMacro(vtkGhostCellsGenerator, vtkPassInputTypeAlgorithm);
void PrintSelf(ostream& os, vtkIndent indent) override;
///@{
/**
* Get/Set the controller to use. By default
* vtkMultiProcessController::GlobalController will be used.
*/
virtual void SetController(vtkMultiProcessController*);
vtkMultiProcessController* GetController();
///@}
///@{
/**
* Resets parameter.
*/
///@}
virtual void Initialize();
///@{
/**
* Specify if the filter must generate the ghost cells only if required by
* the pipeline.
* If false, ghost cells are computed even if they are not required.
* Default is TRUE.
*/
vtkSetMacro(BuildIfRequired, bool);
vtkGetMacro(BuildIfRequired, bool);
vtkBooleanMacro(BuildIfRequired, bool);
///@}
///@{
/**
* When BuildIfRequired is `false`, this can be used to set the number
* of ghost layers to generate. Note, if the downstream pipeline requests more
* ghost levels than the number specified here, then the filter will generate
* those extra ghost levels as needed. Accepted values are in the interval
* [1, VTK_INT_MAX].
*/
vtkGetMacro(NumberOfGhostLayers, int);
vtkSetClampMacro(NumberOfGhostLayers, int, 0, VTK_INT_MAX);
///@}
///@{
/**
* Specify if the filter should generate GlobalsIds.
* Default is FALSE.
*/
vtkSetMacro(GenerateGlobalIds, bool);
vtkGetMacro(GenerateGlobalIds, bool);
vtkBooleanMacro(GenerateGlobalIds, bool);
///@}
///@{
/**
* Specify if the filter should generate ProcessIds.
* Default is FALSE.
*/
vtkSetMacro(GenerateProcessIds, bool);
vtkGetMacro(GenerateProcessIds, bool);
vtkBooleanMacro(GenerateProcessIds, bool);
///@}
///@{
/**
* Specify if the filter should try to synchronize ghost
* instead of regenerating ghosts if it can. If it can't,
* ghost cells and points will be generated instead.
* This assumes that the ghost layer stays the same.
* Default is FALSE.
*/
vtkSetMacro(SynchronizeOnly, bool);
vtkGetMacro(SynchronizeOnly, bool);
vtkBooleanMacro(SynchronizeOnly, bool);
///@}
///@{
/**
* Specify if the filter should keep a cache of the output geometry.
* Ghost cells will be generated once on the first update, and following updates
* will only regenerate them if the input mesh has changed.
* This should allow faster execution in cases where the mesh is the same.
* Default is TRUE.
*/
vtkSetMacro(UseStaticMeshCache, bool);
vtkGetMacro(UseStaticMeshCache, bool);
vtkBooleanMacro(UseStaticMeshCache, bool);
///@}
protected:
vtkGhostCellsGenerator();
~vtkGhostCellsGenerator() override;
int FillInputPortInformation(int port, vtkInformation* info) override;
int RequestData(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override;
int RequestUpdateExtent(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override;
/**
* Runs the filter using custom inputs.
*/
virtual int Execute(vtkDataObject* inputDO, vtkInformationVector* outputVector);
/**
* Local controller.
*/
vtkWeakPointer<vtkMultiProcessController> Controller;
int NumberOfGhostLayers = 1;
bool BuildIfRequired = true;
private:
vtkGhostCellsGenerator(const vtkGhostCellsGenerator&) = delete;
void operator=(const vtkGhostCellsGenerator&) = delete;
/**
* Check if this filter can synchronize only,
* which can only be true if ghost array,
* process ids and global ids and available.
* Return true if cells AND points can be synchronized.
*/
bool CanSynchronize(vtkDataObject* input, bool& canSyncCell, bool& canSyncPoint);
int GenerateGhostCells(
vtkDataObject* input, vtkDataObject* output, int reqGhostLayers, bool syncOnly);
void UpdateCache(vtkDataObject* updatedOutput);
bool UseCacheIfPossible(vtkDataObject* input, vtkDataObject* output);
bool GenerateGlobalIds = false;
bool GenerateProcessIds = false;
bool SynchronizeOnly = false;
bool UseStaticMeshCache = true;
vtkNew<vtkDataObjectMeshCache> MeshCache;
};
VTK_ABI_NAMESPACE_END
#endif
| 412 | 0.980694 | 1 | 0.980694 | game-dev | MEDIA | 0.595699 | game-dev,graphics-rendering | 0.770651 | 1 | 0.770651 |
ProjectIgnis/CardScripts | 3,494 | official/c71521025.lua | --カクリヨノチザクラ
--Red Blossoms from Underroot
--scripted by andré
local s,id=GetID()
function s.initial_effect(c)
--Special Summon itself from the hand
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetCategory(CATEGORY_REMOVE+CATEGORY_SPECIAL_SUMMON)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_HAND)
e1:SetCountLimit(1,id)
e1:SetTarget(s.target1)
e1:SetOperation(s.operation1)
c:RegisterEffect(e1)
--Special Summon 1 monster from the GY
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(id,1))
e2:SetCategory(CATEGORY_REMOVE+CATEGORY_SPECIAL_SUMMON)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1,{id,1})
e2:SetCost(Cost.SelfTribute)
e2:SetTarget(s.target2)
e2:SetOperation(s.operation2)
c:RegisterEffect(e2)
end
function s.filter(c,e)
return c:IsSpellTrap() and c:IsAbleToRemove() and c:IsCanBeEffectTarget(e)
end
function s.rescon(sg,e,tp,mg)
return sg:IsExists(Card.IsControler,1,nil,tp) and sg:IsExists(Card.IsControler,1,nil,1-tp)
end
function s.target1(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
local c=e:GetHandler()
local g = Duel.GetMatchingGroup(s.filter,tp,LOCATION_GRAVE,LOCATION_GRAVE,nil,e)
if chkc then return false end
if chk==0 then return aux.SelectUnselectGroup(g,e,tp,2,2,s.rescon,0) and Duel.GetLocationCount(tp,LOCATION_MZONE) > 0
and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end
local sg=aux.SelectUnselectGroup(g,e,tp,2,2,s.rescon,1,tp,HINTMSG_REMOVE)
Duel.SetTargetCard(sg)
Duel.SetOperationInfo(0,CATEGORY_REMOVE,sg,2,tp,0)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,c,1,tp,LOCATION_HAND)
end
function s.operation1(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local sg=Duel.GetTargetCards(e)
if #sg>0 and Duel.Remove(sg,POS_FACEUP,REASON_EFFECT)>0 and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and c:IsRelateToEffect(e) then
Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)
end
end
function s.filter1(c,e,tp)
return c:IsType(TYPE_FUSION|TYPE_SYNCHRO|TYPE_XYZ|TYPE_LINK) and c:IsAbleToRemove()
and Duel.IsExistingMatchingCard(s.filter2,tp,LOCATION_GRAVE,0,1,c,e,tp,c:GetType()&(TYPE_FUSION|TYPE_SYNCHRO|TYPE_XYZ|TYPE_LINK))
end
function s.filter2(c,e,tp,type)
return c:IsType(TYPE_FUSION|TYPE_SYNCHRO|TYPE_XYZ|TYPE_LINK) and not c:IsType(type) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function s.target2(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and s.filter1(chkc,e,tp) end
if chk==0 then return Duel.IsExistingTarget(s.filter1,tp,LOCATION_GRAVE,LOCATION_GRAVE,1,nil,e,tp)
and Duel.GetLocationCount(tp,LOCATION_MZONE)>-1 end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local sg=Duel.SelectTarget(tp,s.filter1,tp,LOCATION_GRAVE,LOCATION_GRAVE,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_REMOVE,sg,1,tp,0)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,0,1,tp,LOCATION_GRAVE)
end
function s.operation2(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
local type=tc:GetType()&(TYPE_FUSION|TYPE_SYNCHRO|TYPE_XYZ|TYPE_LINK)
if Duel.Remove(tc,POS_FACEUP,REASON_EFFECT)>0 and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local sg=Duel.SelectMatchingCard(tp,s.filter2,tp,LOCATION_GRAVE,0,1,1,nil,e,tp,type)
if #sg>0 then
Duel.SpecialSummon(sg,0,tp,tp,false,false,POS_FACEUP)
end
end
end
end | 412 | 0.95836 | 1 | 0.95836 | game-dev | MEDIA | 0.976013 | game-dev | 0.964871 | 1 | 0.964871 |
scottschiller/ArmorAlley | 2,393 | src/js/levels/convoys.js | import { game } from '../core/Game.js';
import { COSTS, TYPES } from '../core/global.js';
import { levelConfig } from './default.js';
/**
* CPU convoy ordering patterns from original, somewhat reduced.
* First character = "inventory level", followed by a series of items.
* Inventory level ranges from 5-10 per level (battle) config.
*/
let convoyData = [
'0 V',
'0 M',
'0 T',
'0 I',
'0 I',
'0 I',
'0 E',
'3 TI',
'3 TT',
'3 IV',
'4 V',
'4 IE',
'4 MI',
'4 MM',
'4 I',
'5 V',
'5 MIIM',
'5 TTMI',
'5 TEV',
'5 IMEV',
'5 MIVV',
'5 TMV',
'6 TEVIM',
'6 TVTV',
'6 MTVVIM',
'6 TTMTVI',
'6 TTMMIE',
'7 TMIVIM',
'7 TTVEVEMM',
'7 MIVVTMMI',
'8 TTIMMMEV',
'8 IVIVEMMIV',
'9 TVVV',
'9 TMMMMM',
'9 TTTTEEEM',
'9 TVEMIVTV',
'9 TTMTVIVITMEVVTEVIMM',
// `:` is hex 3A / decimal 48 - when subtracting '0' (38), leaves 10. ;)
': MTIMTMIME',
': TMIMTMTV',
': TEEMIVVTMM',
': IIIMMIMMMTTTEET',
': TTTMMMIIETM',
': TMTMIMTMIEV',
': TTMMTTMTMTMIIEVIVVV'
];
let costs = {
M: COSTS[TYPES.missileLauncher],
I: COSTS[TYPES.infantry],
E: COSTS[TYPES.engineer],
T: COSTS[TYPES.tank],
V: COSTS[TYPES.van]
};
function parseConvoyData(convoyLevel) {
let parsed = [];
convoyData.forEach((convoy) => {
let l = convoy.charAt(0);
// "inventory level" offset: 0-9, and `:` (10) as per original formatting.
let level = l.charCodeAt(0) - '0'.charCodeAt(0);
// skip convoy bits which don't apply to the current battle.
if (convoyLevel < level) return;
// MTVIE pattern
let items = convoy.substring(2);
let cost = 0;
// iterate through inventory items, handle possible substitutions.
// if missile launchers can't be ordered, swap with infantry.
if (!levelConfig.buildTruckB) {
items = items.replace(/M/g, 'I');
}
// if engineers can't be ordered OR there are no turrets for this battle, swap with infantry.
if (
!levelConfig.buildEngineersB ||
(game.objects.turret && !game.objects.turret.length)
) {
items = items.replace(/E/g, 'I');
}
// character -> type, e.g., MTVIE
let key;
for (var i = 0; i < items.length; i++) {
key = items.charAt(i);
cost += costs[key]?.funds || 0;
}
parsed.push({
level,
items,
cost
});
});
return parsed;
}
export { parseConvoyData };
| 412 | 0.715469 | 1 | 0.715469 | game-dev | MEDIA | 0.486737 | game-dev | 0.922342 | 1 | 0.922342 |
DeltaV-Station/Delta-v | 37,151 | Content.Shared/Actions/SharedActionsSystem.cs | using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Content.Shared.ActionBlocker;
using Content.Shared.Actions.Components;
using Content.Shared.Actions.Events;
using Content.Shared.Administration.Logs;
using Content.Shared.Database;
using Content.Shared.Hands;
using Content.Shared.Interaction;
using Content.Shared.Inventory.Events;
using Content.Shared.Mind;
using Content.Shared.Rejuvenate;
using Content.Shared.Whitelist;
using Robust.Shared.Audio.Systems;
using Robust.Shared.GameStates;
using Robust.Shared.Map;
using Robust.Shared.Timing;
using Robust.Shared.Utility;
namespace Content.Shared.Actions;
public abstract class SharedActionsSystem : EntitySystem
{
[Dependency] protected readonly IGameTiming GameTiming = default!;
[Dependency] private readonly ISharedAdminLogManager _adminLogger = default!;
[Dependency] private readonly ActionBlockerSystem _actionBlocker = default!;
[Dependency] private readonly ActionContainerSystem _actionContainer = default!;
[Dependency] private readonly EntityWhitelistSystem _whitelist = default!;
[Dependency] private readonly RotateToFaceSystem _rotateToFace = default!;
[Dependency] private readonly SharedAudioSystem _audio = default!;
[Dependency] private readonly SharedInteractionSystem _interaction = default!;
[Dependency] private readonly SharedTransformSystem _transform = default!;
private EntityQuery<ActionComponent> _actionQuery;
private EntityQuery<ActionsComponent> _actionsQuery;
private EntityQuery<MindComponent> _mindQuery;
public override void Initialize()
{
base.Initialize();
_actionQuery = GetEntityQuery<ActionComponent>();
_actionsQuery = GetEntityQuery<ActionsComponent>();
_mindQuery = GetEntityQuery<MindComponent>();
SubscribeLocalEvent<ActionComponent, MapInitEvent>(OnActionMapInit);
SubscribeLocalEvent<ActionComponent, ComponentShutdown>(OnActionShutdown);
SubscribeLocalEvent<ActionsComponent, ActionComponentChangeEvent>(OnActionCompChange);
SubscribeLocalEvent<ActionsComponent, RelayedActionComponentChangeEvent>(OnRelayActionCompChange);
SubscribeLocalEvent<ActionsComponent, DidEquipEvent>(OnDidEquip);
SubscribeLocalEvent<ActionsComponent, DidEquipHandEvent>(OnHandEquipped);
SubscribeLocalEvent<ActionsComponent, DidUnequipEvent>(OnDidUnequip);
SubscribeLocalEvent<ActionsComponent, DidUnequipHandEvent>(OnHandUnequipped);
SubscribeLocalEvent<ActionsComponent, RejuvenateEvent>(OnRejuventate);
SubscribeLocalEvent<ActionsComponent, ComponentShutdown>(OnShutdown);
SubscribeLocalEvent<ActionsComponent, ComponentGetState>(OnGetState);
SubscribeLocalEvent<ActionComponent, ActionValidateEvent>(OnValidate);
SubscribeLocalEvent<InstantActionComponent, ActionValidateEvent>(OnInstantValidate);
SubscribeLocalEvent<EntityTargetActionComponent, ActionValidateEvent>(OnEntityValidate);
SubscribeLocalEvent<WorldTargetActionComponent, ActionValidateEvent>(OnWorldValidate);
SubscribeLocalEvent<InstantActionComponent, ActionGetEventEvent>(OnInstantGetEvent);
SubscribeLocalEvent<EntityTargetActionComponent, ActionGetEventEvent>(OnEntityGetEvent);
SubscribeLocalEvent<WorldTargetActionComponent, ActionGetEventEvent>(OnWorldGetEvent);
SubscribeLocalEvent<InstantActionComponent, ActionSetEventEvent>(OnInstantSetEvent);
SubscribeLocalEvent<EntityTargetActionComponent, ActionSetEventEvent>(OnEntitySetEvent);
SubscribeLocalEvent<WorldTargetActionComponent, ActionSetEventEvent>(OnWorldSetEvent);
SubscribeLocalEvent<EntityTargetActionComponent, ActionSetTargetEvent>(OnEntitySetTarget);
SubscribeLocalEvent<WorldTargetActionComponent, ActionSetTargetEvent>(OnWorldSetTarget);
SubscribeAllEvent<RequestPerformActionEvent>(OnActionRequest);
}
private void OnActionMapInit(Entity<ActionComponent> ent, ref MapInitEvent args)
{
var comp = ent.Comp;
comp.OriginalIconColor = comp.IconColor;
DirtyField(ent, ent.Comp, nameof(ActionComponent.OriginalIconColor));
}
private void OnActionShutdown(Entity<ActionComponent> ent, ref ComponentShutdown args)
{
if (ent.Comp.AttachedEntity is {} user && !TerminatingOrDeleted(user))
RemoveAction(user, (ent, ent));
}
private void OnShutdown(Entity<ActionsComponent> ent, ref ComponentShutdown args)
{
foreach (var actionId in ent.Comp.Actions)
{
RemoveAction((ent, ent), actionId);
}
}
private void OnGetState(Entity<ActionsComponent> ent, ref ComponentGetState args)
{
args.State = new ActionsComponentState(GetNetEntitySet(ent.Comp.Actions));
}
/// <summary>
/// Resolving an action's <see cref="ActionComponent"/>, only returning a value if it exists and has it.
/// </summary>
public Entity<ActionComponent>? GetAction(Entity<ActionComponent?>? action, bool logError = true)
{
if (action is not {} ent || Deleted(ent))
return null;
if (!_actionQuery.Resolve(ent, ref ent.Comp, logError))
return null;
return (ent, ent.Comp);
}
public void SetCooldown(Entity<ActionComponent?>? action, TimeSpan start, TimeSpan end)
{
if (GetAction(action) is not {} ent)
return;
ent.Comp.Cooldown = new ActionCooldown
{
Start = start,
End = end
};
DirtyField(ent, ent.Comp, nameof(ActionComponent.Cooldown));
}
public void RemoveCooldown(Entity<ActionComponent?>? action)
{
if (GetAction(action) is not {} ent)
return;
ent.Comp.Cooldown = null;
DirtyField(ent, ent.Comp, nameof(ActionComponent.Cooldown));
}
/// <summary>
/// Starts a cooldown starting now, lasting for <c>cooldown</c> seconds.
/// </summary>
public void SetCooldown(Entity<ActionComponent?>? action, TimeSpan cooldown)
{
var start = GameTiming.CurTime;
SetCooldown(action, start, start + cooldown);
}
public void ClearCooldown(Entity<ActionComponent?>? action)
{
if (GetAction(action) is not {} ent)
return;
if (ent.Comp.Cooldown is not {} cooldown)
return;
ent.Comp.Cooldown = new ActionCooldown
{
Start = cooldown.Start,
End = GameTiming.CurTime
};
DirtyField(ent, ent.Comp, nameof(ActionComponent.Cooldown));
}
/// <summary>
/// Sets the cooldown for this action only if it is bigger than the one it already has.
/// </summary>
public void SetIfBiggerCooldown(Entity<ActionComponent?>? action, TimeSpan cooldown)
{
if (GetAction(action) is not {} ent || cooldown < TimeSpan.Zero)
return;
var start = GameTiming.CurTime;
var end = start + cooldown;
if (ent.Comp.Cooldown?.End > end)
return;
SetCooldown((ent, ent), start, end);
}
/// <summary>
/// Set an action's cooldown to its use delay, if it has one.
/// If there is no set use delay this does nothing.
/// </summary>
public void StartUseDelay(Entity<ActionComponent?>? action)
{
if (GetAction(action) is not {} ent || ent.Comp.UseDelay is not {} delay)
return;
SetCooldown((ent, ent), delay);
}
public void SetUseDelay(Entity<ActionComponent?>? action, TimeSpan? delay)
{
if (GetAction(action) is not {} ent || ent.Comp.UseDelay == delay)
return;
ent.Comp.UseDelay = delay;
UpdateAction(ent);
DirtyField(ent, ent.Comp, nameof(ActionComponent.UseDelay));
}
public void ReduceUseDelay(Entity<ActionComponent?>? action, TimeSpan? lowerDelay)
{
if (GetAction(action) is not {} ent)
return;
if (ent.Comp.UseDelay != null && lowerDelay != null)
ent.Comp.UseDelay -= lowerDelay;
if (ent.Comp.UseDelay < TimeSpan.Zero)
ent.Comp.UseDelay = null;
UpdateAction(ent);
DirtyField(ent, ent.Comp, nameof(ActionComponent.UseDelay));
}
private void OnRejuventate(Entity<ActionsComponent> ent, ref RejuvenateEvent args)
{
foreach (var act in ent.Comp.Actions)
{
ClearCooldown(act);
}
}
#region ComponentStateManagement
public virtual void UpdateAction(Entity<ActionComponent> ent)
{
// See client-side code.
}
public void SetToggled(Entity<ActionComponent?>? action, bool toggled)
{
if (GetAction(action) is not {} ent || ent.Comp.Toggled == toggled)
return;
ent.Comp.Toggled = toggled;
UpdateAction(ent);
DirtyField(ent, ent.Comp, nameof(ActionComponent.Toggled));
}
public void SetEnabled(Entity<ActionComponent?>? action, bool enabled)
{
if (GetAction(action) is not {} ent || ent.Comp.Enabled == enabled)
return;
ent.Comp.Enabled = enabled;
UpdateAction(ent);
DirtyField(ent, ent.Comp, nameof(ActionComponent.Enabled));
}
#endregion
#region Execution
/// <summary>
/// When receiving a request to perform an action, this validates whether the action is allowed. If it is, it
/// will raise the relevant <see cref="InstantActionEvent"/>
/// </summary>
private void OnActionRequest(RequestPerformActionEvent ev, EntitySessionEventArgs args)
{
if (args.SenderSession.AttachedEntity is not { } user)
return;
if (!_actionsQuery.TryComp(user, out var component))
return;
var actionEnt = GetEntity(ev.Action);
if (!TryComp(actionEnt, out MetaDataComponent? metaData))
return;
var name = Name(actionEnt, metaData);
// Does the user actually have the requested action?
if (!component.Actions.Contains(actionEnt))
{
_adminLogger.Add(LogType.Action,
$"{ToPrettyString(user):user} attempted to perform an action that they do not have: {name}.");
return;
}
if (GetAction(actionEnt) is not {} action)
return;
DebugTools.Assert(action.Comp.AttachedEntity == user);
if (!action.Comp.Enabled)
return;
var curTime = GameTiming.CurTime;
if (IsCooldownActive(action, curTime))
return;
// check for action use prevention
// TODO: make code below use this event with a dedicated component
var attemptEv = new ActionAttemptEvent(user);
RaiseLocalEvent(action, ref attemptEv);
if (attemptEv.Cancelled)
return;
// Validate request by checking action blockers and the like
var provider = action.Comp.Container ?? user;
var validateEv = new ActionValidateEvent()
{
Input = ev,
User = user,
Provider = provider
};
RaiseLocalEvent(action, ref validateEv);
if (validateEv.Invalid)
return;
// All checks passed. Perform the action!
PerformAction((user, component), action);
}
private void OnValidate(Entity<ActionComponent> ent, ref ActionValidateEvent args)
{
if ((ent.Comp.CheckConsciousness && !_actionBlocker.CanConsciouslyPerformAction(args.User))
|| (ent.Comp.CheckCanInteract && !_actionBlocker.CanInteract(args.User, null)))
args.Invalid = true;
}
private void OnInstantValidate(Entity<InstantActionComponent> ent, ref ActionValidateEvent args)
{
_adminLogger.Add(LogType.Action,
$"{ToPrettyString(args.User):user} is performing the {Name(ent):action} action provided by {ToPrettyString(args.Provider):provider}.");
}
private void OnEntityValidate(Entity<EntityTargetActionComponent> ent, ref ActionValidateEvent args)
{
// let WorldTargetAction handle it
if (ent.Comp.Event is not {} ev)
{
DebugTools.Assert(HasComp<WorldTargetActionComponent>(ent), $"Entity-world targeting action {ToPrettyString(ent)} requires WorldTargetActionComponent");
return;
}
if (args.Input.EntityTarget is not {} netTarget)
{
args.Invalid = true;
return;
}
var user = args.User;
var target = GetEntity(netTarget);
var targetWorldPos = _transform.GetWorldPosition(target);
if (ent.Comp.RotateOnUse)
_rotateToFace.TryFaceCoordinates(user, targetWorldPos);
if (!ValidateEntityTarget(user, target, ent))
return;
_adminLogger.Add(LogType.Action,
$"{ToPrettyString(user):user} is performing the {Name(ent):action} action (provided by {ToPrettyString(args.Provider):provider}) targeted at {ToPrettyString(target):target}.");
ev.Target = target;
}
private void OnWorldValidate(Entity<WorldTargetActionComponent> ent, ref ActionValidateEvent args)
{
if (args.Input.EntityCoordinatesTarget is not { } netTarget)
{
args.Invalid = true;
return;
}
var user = args.User;
var target = GetCoordinates(netTarget);
if (ent.Comp.RotateOnUse)
_rotateToFace.TryFaceCoordinates(user, _transform.ToMapCoordinates(target).Position);
if (!ValidateWorldTarget(user, target, ent))
return;
// if the client specified an entity it needs to be valid
var targetEntity = GetEntity(args.Input.EntityTarget);
if (targetEntity != null && (
!TryComp<EntityTargetActionComponent>(ent, out var entTarget) ||
!ValidateEntityTarget(user, targetEntity.Value, (ent, entTarget))))
{
args.Invalid = true;
return;
}
_adminLogger.Add(LogType.Action,
$"{ToPrettyString(user):user} is performing the {Name(ent):action} action (provided by {args.Provider}) targeting {targetEntity} at {target:target}.");
if (ent.Comp.Event is {} ev)
{
ev.Target = target;
ev.Entity = targetEntity;
}
}
public bool ValidateEntityTarget(EntityUid user, EntityUid target, Entity<EntityTargetActionComponent> ent)
{
var (uid, comp) = ent;
if (!target.IsValid() || Deleted(target))
return false;
if (_whitelist.IsWhitelistFail(comp.Whitelist, target))
return false;
if (_whitelist.IsBlacklistPass(comp.Blacklist, target))
return false;
if (_actionQuery.Comp(uid).CheckCanInteract && !_actionBlocker.CanInteract(user, target))
return false;
if (user == target)
return comp.CanTargetSelf;
var targetAction = Comp<TargetActionComponent>(uid);
// not using the ValidateBaseTarget logic since its raycast fails if the target is e.g. a wall
if (targetAction.CheckCanAccess)
return _interaction.InRangeAndAccessible(user, target, targetAction.Range, targetAction.AccessMask);
// Just check normal in range, allowing <= 0 range to mean infinite range.
if (targetAction.Range > 0
&& !_transform.InRange(user, target, targetAction.Range))
return false;
// If checkCanAccess isn't set, we allow targeting things in containers
return _interaction.IsAccessible(user, target);
}
public bool ValidateWorldTarget(EntityUid user, EntityCoordinates target, Entity<WorldTargetActionComponent> ent)
{
var targetAction = Comp<TargetActionComponent>(ent);
return ValidateBaseTarget(user, target, (ent, targetAction));
}
private bool ValidateBaseTarget(EntityUid user, EntityCoordinates coords, Entity<TargetActionComponent> ent)
{
var comp = ent.Comp;
if (comp.CheckCanAccess)
return _interaction.InRangeUnobstructed(user, coords, range: comp.Range);
// even if we don't check for obstructions, we may still need to check the range.
var xform = Transform(user);
if (xform.MapID != _transform.GetMapId(coords))
return false;
if (comp.Range <= 0)
return true;
return _transform.InRange(coords, xform.Coordinates, comp.Range);
}
private void OnInstantGetEvent(Entity<InstantActionComponent> ent, ref ActionGetEventEvent args)
{
if (ent.Comp.Event is {} ev)
args.Event = ev;
}
private void OnEntityGetEvent(Entity<EntityTargetActionComponent> ent, ref ActionGetEventEvent args)
{
if (ent.Comp.Event is {} ev)
args.Event = ev;
}
private void OnWorldGetEvent(Entity<WorldTargetActionComponent> ent, ref ActionGetEventEvent args)
{
if (ent.Comp.Event is {} ev)
args.Event = ev;
}
private void OnInstantSetEvent(Entity<InstantActionComponent> ent, ref ActionSetEventEvent args)
{
if (args.Event is InstantActionEvent ev)
{
ent.Comp.Event = ev;
args.Handled = true;
}
}
private void OnEntitySetEvent(Entity<EntityTargetActionComponent> ent, ref ActionSetEventEvent args)
{
if (args.Event is EntityTargetActionEvent ev)
{
ent.Comp.Event = ev;
args.Handled = true;
}
}
private void OnWorldSetEvent(Entity<WorldTargetActionComponent> ent, ref ActionSetEventEvent args)
{
if (args.Event is WorldTargetActionEvent ev)
{
ent.Comp.Event = ev;
args.Handled = true;
}
}
private void OnEntitySetTarget(Entity<EntityTargetActionComponent> ent, ref ActionSetTargetEvent args)
{
if (ent.Comp.Event is {} ev)
{
ev.Target = args.Target;
args.Handled = true;
}
}
private void OnWorldSetTarget(Entity<WorldTargetActionComponent> ent, ref ActionSetTargetEvent args)
{
if (ent.Comp.Event is {} ev)
{
ev.Target = Transform(args.Target).Coordinates;
// only set Entity if the action also has EntityTargetAction
ev.Entity = HasComp<EntityTargetActionComponent>(ent) ? args.Target : null;
args.Handled = true;
}
}
/// <summary>
/// Perform an action, bypassing validation checks.
/// </summary>
/// <param name="performer">The entity performing the action</param>
/// <param name="action">The action being performed</param>
/// <param name="actionEvent">An event override to perform. If null, uses <see cref="GetEvent"/></param>
/// <param name="predicted">If false, prevents playing the action's sound on the client</param>
public void PerformAction(Entity<ActionsComponent?> performer, Entity<ActionComponent> action, BaseActionEvent? actionEvent = null, bool predicted = true)
{
var handled = false;
var toggledBefore = action.Comp.Toggled;
// Note that attached entity and attached container are allowed to be null here.
if (action.Comp.AttachedEntity != null && action.Comp.AttachedEntity != performer)
{
Log.Error($"{ToPrettyString(performer)} is attempting to perform an action {ToPrettyString(action)} that is attached to another entity {ToPrettyString(action.Comp.AttachedEntity)}");
return;
}
actionEvent ??= GetEvent(action);
if (actionEvent is not {} ev)
return;
ev.Performer = performer;
// This here is required because of client-side prediction (RaisePredictiveEvent results in event re-use).
ev.Handled = false;
var target = performer.Owner;
ev.Performer = performer;
ev.Action = action;
if (!action.Comp.RaiseOnUser && action.Comp.Container is {} container && !_mindQuery.HasComp(container))
target = container;
if (action.Comp.RaiseOnAction)
target = action;
RaiseLocalEvent(target, (object) ev, broadcast: true);
handled = ev.Handled;
if (!handled)
return; // no interaction occurred.
// play sound, reduce charges, start cooldown
if (ev?.Toggle == true)
SetToggled((action, action), !action.Comp.Toggled);
_audio.PlayPredicted(action.Comp.Sound, performer, predicted ? performer : null);
// TODO: move to ActionCooldown ActionPerformedEvent?
RemoveCooldown((action, action));
StartUseDelay((action, action));
UpdateAction(action);
var performed = new ActionPerformedEvent(performer);
RaiseLocalEvent(action, ref performed);
}
#endregion
#region AddRemoveActions
public EntityUid? AddAction(EntityUid performer,
string? actionPrototypeId,
EntityUid container = default,
ActionsComponent? component = null)
{
EntityUid? actionId = null;
AddAction(performer, ref actionId, out _, actionPrototypeId, container, component);
return actionId;
}
/// <summary>
/// Adds an action to an action holder. If the given entity does not exist, it will attempt to spawn one.
/// If the holder has no actions component, this will give them one.
/// </summary>
/// <param name="performer">Entity to receive the actions</param>
/// <param name="actionId">Action entity to add</param>
/// <param name="component">The <see cref="performer"/>'s action component of </param>
/// <param name="actionPrototypeId">The action entity prototype id to use if <see cref="actionId"/> is invalid.</param>
/// <param name="container">The entity that contains/enables this action (e.g., flashlight).</param>
public bool AddAction(EntityUid performer,
[NotNullWhen(true)] ref EntityUid? actionId,
string? actionPrototypeId,
EntityUid container = default,
ActionsComponent? component = null)
{
return AddAction(performer, ref actionId, out _, actionPrototypeId, container, component);
}
/// <inheritdoc cref="AddAction(Robust.Shared.GameObjects.EntityUid,ref System.Nullable{Robust.Shared.GameObjects.EntityUid},string?,Robust.Shared.GameObjects.EntityUid,ActionsComponent?)"/>
public bool AddAction(EntityUid performer,
[NotNullWhen(true)] ref EntityUid? actionId,
[NotNullWhen(true)] out ActionComponent? action,
string? actionPrototypeId,
EntityUid container = default,
ActionsComponent? component = null)
{
if (!container.IsValid())
container = performer;
if (!_actionContainer.EnsureAction(container, ref actionId, out action, actionPrototypeId))
return false;
return AddActionDirect((performer, component), (actionId.Value, action));
}
/// <summary>
/// Adds a pre-existing action.
/// </summary>
public bool AddAction(Entity<ActionsComponent?> performer,
Entity<ActionComponent?> action,
Entity<ActionsContainerComponent?> container)
{
if (GetAction(action) is not {} ent)
return false;
if (ent.Comp.Container != container.Owner
|| !Resolve(container, ref container.Comp)
|| !container.Comp.Container.Contains(ent))
{
Log.Error($"Attempted to add an action with an invalid container: {ToPrettyString(ent)}");
return false;
}
return AddActionDirect(performer, (ent, ent));
}
/// <summary>
/// Adds a pre-existing action. This also bypasses the requirement that the given action must be stored in a
/// valid action container.
/// </summary>
public bool AddActionDirect(Entity<ActionsComponent?> performer,
Entity<ActionComponent?>? action)
{
if (GetAction(action) is not {} ent)
return false;
DebugTools.Assert(ent.Comp.Container == null ||
(TryComp(ent.Comp.Container, out ActionsContainerComponent? containerComp)
&& containerComp.Container.Contains(ent)));
if (ent.Comp.AttachedEntity is {} user)
RemoveAction(user, (ent, ent));
// TODO: make this an event bruh
if (ent.Comp.StartDelay && ent.Comp.UseDelay != null)
SetCooldown((ent, ent), ent.Comp.UseDelay.Value);
DebugTools.AssertOwner(performer, performer.Comp);
performer.Comp ??= EnsureComp<ActionsComponent>(performer);
ent.Comp.AttachedEntity = performer;
DirtyField(ent, ent.Comp, nameof(ActionComponent.AttachedEntity));
performer.Comp.Actions.Add(ent);
Dirty(performer, performer.Comp);
ActionAdded((performer, performer.Comp), (ent, ent.Comp));
return true;
}
/// <summary>
/// This method gets called after a new action got added.
/// </summary>
protected virtual void ActionAdded(Entity<ActionsComponent> performer, Entity<ActionComponent> action)
{
// See client-side system for UI code.
}
/// <summary>
/// Grant pre-existing actions. If the entity has no action component, this will give them one.
/// </summary>
/// <param name="performer">Entity to receive the actions</param>
/// <param name="actions">The actions to add</param>
/// <param name="container">The entity that enables these actions (e.g., flashlight). May be null (innate actions).</param>
public void GrantActions(Entity<ActionsComponent?> performer,
IEnumerable<EntityUid> actions,
Entity<ActionsContainerComponent?> container)
{
if (!Resolve(container, ref container.Comp))
return;
DebugTools.AssertOwner(performer, performer.Comp);
performer.Comp ??= EnsureComp<ActionsComponent>(performer);
foreach (var actionId in actions)
{
AddAction(performer, actionId, container);
}
}
/// <summary>
/// Grants all actions currently contained in some action-container. If the target entity has no action
/// component, this will give them one.
/// </summary>
/// <param name="performer">Entity to receive the actions</param>
/// <param name="container">The entity that contains thee actions.</param>
public void GrantContainedActions(Entity<ActionsComponent?> performer, Entity<ActionsContainerComponent?> container)
{
if (!Resolve(container, ref container.Comp))
return;
performer.Comp ??= EnsureComp<ActionsComponent>(performer);
foreach (var actionId in container.Comp.Container.ContainedEntities)
{
if (GetAction(actionId) is {} action)
AddActionDirect(performer, (action, action));
}
}
/// <summary>
/// Grants the provided action from the container to the target entity. If the target entity has no action
/// component, this will give them one.
/// </summary>
/// <param name="performer"></param>
/// <param name="container"></param>
/// <param name="actionId"></param>
public void GrantContainedAction(Entity<ActionsComponent?> performer, Entity<ActionsContainerComponent?> container, EntityUid actionId)
{
if (!Resolve(container, ref container.Comp))
return;
performer.Comp ??= EnsureComp<ActionsComponent>(performer);
AddActionDirect(performer, actionId);
}
public IEnumerable<Entity<ActionComponent>> GetActions(EntityUid holderId, ActionsComponent? actions = null)
{
if (!Resolve(holderId, ref actions, false))
yield break;
foreach (var actionId in actions.Actions)
{
if (GetAction(actionId) is not {} ent)
continue;
yield return ent;
}
}
/// <summary>
/// Remove any actions that were enabled by some other entity. Useful when unequiping items that grant actions.
/// </summary>
public void RemoveProvidedActions(EntityUid performer, EntityUid container, ActionsComponent? comp = null)
{
if (!Resolve(performer, ref comp, false))
return;
foreach (var actionId in comp.Actions.ToArray())
{
if (GetAction(actionId) is not {} ent)
return;
if (ent.Comp.Container == container)
RemoveAction((performer, comp), (ent, ent));
}
}
/// <summary>
/// Removes a single provided action provided by another entity.
/// </summary>
public void RemoveProvidedAction(EntityUid performer, EntityUid container, EntityUid actionId, ActionsComponent? comp = null)
{
if (!_actionsQuery.Resolve(performer, ref comp, false) || GetAction(actionId) is not {} ent)
return;
if (ent.Comp.Container == container)
RemoveAction((performer, comp), (ent, ent));
}
/// <summary>
/// Removes an action from its container, if it still exists.
/// </summary>
public void RemoveAction(Entity<ActionComponent?>? action)
{
if (GetAction(action) is not {} ent || ent.Comp.AttachedEntity is not {} actions)
return;
if (!_actionsQuery.TryComp(actions, out var comp))
return;
RemoveAction((actions, comp), (ent, ent));
}
public void RemoveAction(Entity<ActionsComponent?> performer, Entity<ActionComponent?>? action)
{
if (GetAction(action) is not {} ent)
return;
if (ent.Comp.AttachedEntity != performer.Owner)
{
DebugTools.Assert(!Resolve(performer, ref performer.Comp, false)
|| performer.Comp.LifeStage >= ComponentLifeStage.Stopping
|| !performer.Comp.Actions.Contains(ent.Owner));
if (!GameTiming.ApplyingState)
Log.Error($"Attempted to remove an action {ToPrettyString(ent)} from an entity that it was never attached to: {ToPrettyString(performer)}. Trace: {Environment.StackTrace}");
return;
}
if (!_actionsQuery.Resolve(performer, ref performer.Comp, false))
{
DebugTools.Assert(performer == null || TerminatingOrDeleted(performer));
ent.Comp.AttachedEntity = null;
// TODO: should this delete the action since it's now orphaned?
return;
}
performer.Comp.Actions.Remove(ent.Owner);
Dirty(performer, performer.Comp);
ent.Comp.AttachedEntity = null;
DirtyField(ent, ent.Comp, nameof(ActionComponent.AttachedEntity));
ActionRemoved((performer, performer.Comp), ent);
if (ent.Comp.Temporary)
QueueDel(ent);
}
/// <summary>
/// This method gets called after an action got removed.
/// </summary>
protected virtual void ActionRemoved(Entity<ActionsComponent> performer, Entity<ActionComponent> action)
{
// See client-side system for UI code.
}
public bool ValidAction(Entity<ActionComponent> ent, bool canReach = true)
{
var (uid, comp) = ent;
if (!comp.Enabled)
return false;
var curTime = GameTiming.CurTime;
if (comp.Cooldown.HasValue && comp.Cooldown.Value.End > curTime)
return false;
// TODO: use event for this
return canReach || Comp<TargetActionComponent>(ent)?.CheckCanAccess == false;
}
#endregion
private void OnRelayActionCompChange(Entity<ActionsComponent> ent, ref RelayedActionComponentChangeEvent args)
{
if (args.Handled)
return;
var ev = new AttemptRelayActionComponentChangeEvent();
RaiseLocalEvent(ent.Owner, ref ev);
var target = ev.Target ?? ent.Owner;
args.Handled = true;
args.Toggle = true;
if (!args.Action.Comp.Toggled)
{
EntityManager.AddComponents(target, args.Components);
}
else
{
EntityManager.RemoveComponents(target, args.Components);
}
}
private void OnActionCompChange(Entity<ActionsComponent> ent, ref ActionComponentChangeEvent args)
{
if (args.Handled)
return;
args.Handled = true;
args.Toggle = true;
var target = ent.Owner;
if (!args.Action.Comp.Toggled)
{
EntityManager.AddComponents(target, args.Components);
}
else
{
EntityManager.RemoveComponents(target, args.Components);
}
}
#region EquipHandlers
private void OnDidEquip(Entity<ActionsComponent> ent, ref DidEquipEvent args)
{
if (GameTiming.ApplyingState)
return;
var ev = new GetItemActionsEvent(_actionContainer, args.Equipee, args.Equipment, args.SlotFlags);
RaiseLocalEvent(args.Equipment, ev);
if (ev.Actions.Count == 0)
return;
GrantActions((ent, ent), ev.Actions, args.Equipment);
}
private void OnHandEquipped(Entity<ActionsComponent> ent, ref DidEquipHandEvent args)
{
if (GameTiming.ApplyingState)
return;
var ev = new GetItemActionsEvent(_actionContainer, args.User, args.Equipped);
RaiseLocalEvent(args.Equipped, ev);
if (ev.Actions.Count == 0)
return;
GrantActions((ent, ent), ev.Actions, args.Equipped);
}
private void OnDidUnequip(EntityUid uid, ActionsComponent component, DidUnequipEvent args)
{
if (GameTiming.ApplyingState)
return;
RemoveProvidedActions(uid, args.Equipment, component);
}
private void OnHandUnequipped(EntityUid uid, ActionsComponent component, DidUnequipHandEvent args)
{
if (GameTiming.ApplyingState)
return;
RemoveProvidedActions(uid, args.Unequipped, component);
}
#endregion
public void SetEntityIcon(Entity<ActionComponent?> ent, EntityUid? icon)
{
if (!_actionQuery.Resolve(ent, ref ent.Comp) || ent.Comp.EntityIcon == icon)
return;
ent.Comp.EntityIcon = icon;
DirtyField(ent, ent.Comp, nameof(ActionComponent.EntIcon));
}
public void SetIcon(Entity<ActionComponent?> ent, SpriteSpecifier? icon)
{
if (!_actionQuery.Resolve(ent, ref ent.Comp) || ent.Comp.Icon == icon)
return;
ent.Comp.Icon = icon;
DirtyField(ent, ent.Comp, nameof(ActionComponent.Icon));
}
public void SetIconOn(Entity<ActionComponent?> ent, SpriteSpecifier? iconOn)
{
if (!_actionQuery.Resolve(ent, ref ent.Comp) || ent.Comp.IconOn == iconOn)
return;
ent.Comp.IconOn = iconOn;
DirtyField(ent, ent.Comp, nameof(ActionComponent.IconOn));
}
public void SetIconColor(Entity<ActionComponent?> ent, Color color)
{
if (!_actionQuery.Resolve(ent, ref ent.Comp) || ent.Comp.IconColor == color)
return;
ent.Comp.IconColor = color;
DirtyField(ent, ent.Comp, nameof(ActionComponent.IconColor));
}
/// <summary>
/// Set the event of an action.
/// Since the event isn't required to be serializable this is not networked.
/// Only use this if it's predicted or for a clientside action.
/// </summary>
public void SetEvent(EntityUid uid, BaseActionEvent ev)
{
// now this is meta
var setEv = new ActionSetEventEvent(ev);
RaiseLocalEvent(uid, ref setEv);
if (!setEv.Handled)
Log.Error($"Tried to set event of {ToPrettyString(uid):action} but nothing handled it!");
}
public BaseActionEvent? GetEvent(EntityUid uid)
{
DebugTools.Assert(_actionQuery.HasComp(uid), $"Entity {ToPrettyString(uid)} is missing ActionComponent");
var ev = new ActionGetEventEvent();
RaiseLocalEvent(uid, ref ev);
return ev.Event;
}
public bool SetEventTarget(EntityUid uid, EntityUid target)
{
DebugTools.Assert(_actionQuery.HasComp(uid), $"Entity {ToPrettyString(uid)} is missing ActionComponent");
var ev = new ActionSetTargetEvent(target);
RaiseLocalEvent(uid, ref ev);
return ev.Handled;
}
/// <summary>
/// Checks if the action has a cooldown and if it's still active
/// </summary>
public bool IsCooldownActive(ActionComponent action, TimeSpan? curTime = null)
{
// TODO: Check for charge recovery timer
return action.Cooldown.HasValue && action.Cooldown.Value.End > curTime;
}
/// <summary>
/// Marks the action as temporary.
/// Temporary actions get deleted upon being removed from an entity.
/// </summary>
public void SetTemporary(Entity<ActionComponent?> ent, bool temporary)
{
if (!Resolve(ent.Owner, ref ent.Comp, false))
return;
ent.Comp.Temporary = temporary;
Dirty(ent);
}
}
| 412 | 0.939442 | 1 | 0.939442 | game-dev | MEDIA | 0.979839 | game-dev | 0.92706 | 1 | 0.92706 |
projectPiki/pikmin | 11,009 | src/plugPikiKando/searchSystem.cpp | #include "SearchSystem.h"
#include "AIPerf.h"
#include "Boss.h"
#include "DebugLog.h"
#include "ItemMgr.h"
#include "NaviMgr.h"
#include "Pellet.h"
#include "PikiMgr.h"
#include "PlantMgr.h"
#include "teki.h"
/*
* --INFO--
* Address: ........
* Size: 00009C
*/
DEFINE_ERROR(__LINE__) // Never used in the DLL
/*
* --INFO--
* Address: ........
* Size: 0000F4
*/
DEFINE_PRINT("searchSys")
/*
* --INFO--
* Address: 800E2FB4
* Size: 000004
*/
SearchSystem::SearchSystem()
{
}
/*
* --INFO--
* Address: 800E2FB8
* Size: 00046C
*/
void SearchSystem::update()
{
if (AIPerf::loopOptimise) {
updateLoopOptimised();
naviMgr->search(itemMgr);
if (tekiMgr) {
naviMgr->search(tekiMgr);
}
naviMgr->search(naviMgr);
if (bossMgr) {
naviMgr->search(bossMgr);
}
naviMgr->search(plantMgr);
pikiMgr->search(plantMgr);
itemMgr->search(itemMgr);
if (bossMgr) {
bossMgr->search(bossMgr);
}
if (tekiMgr) {
tekiMgr->search(tekiMgr);
tekiMgr->search(itemMgr);
}
if (bossMgr) {
bossMgr->search(itemMgr);
}
} else {
pikiMgr->search(itemMgr);
pikiMgr->search(itemMgr->mMeltingPotMgr);
if (tekiMgr) {
pikiMgr->search(tekiMgr);
}
if (bossMgr) {
pikiMgr->search(bossMgr);
}
pikiMgr->search(pikiMgr);
pikiMgr->search(pelletMgr);
naviMgr->search(itemMgr);
naviMgr->search(itemMgr->mMeltingPotMgr);
if (tekiMgr) {
naviMgr->search(tekiMgr);
}
if (bossMgr) {
naviMgr->search(bossMgr);
}
naviMgr->search(naviMgr);
naviMgr->search(pelletMgr);
naviMgr->search(plantMgr);
pikiMgr->search(plantMgr);
if (tekiMgr) {
tekiMgr->search(plantMgr);
}
pikiMgr->search(naviMgr);
itemMgr->search(itemMgr);
itemMgr->search(itemMgr->mMeltingPotMgr);
pelletMgr->search(itemMgr);
pelletMgr->search(itemMgr->mMeltingPotMgr);
if (bossMgr) {
bossMgr->search(bossMgr);
bossMgr->search(pelletMgr);
}
if (tekiMgr) {
tekiMgr->search(tekiMgr);
tekiMgr->search(itemMgr);
tekiMgr->search(itemMgr->mMeltingPotMgr);
tekiMgr->search(pelletMgr);
}
pelletMgr->search(pelletMgr);
if (bossMgr) {
bossMgr->search(itemMgr);
bossMgr->search(itemMgr->mMeltingPotMgr);
}
}
}
/*
* --INFO--
* Address: 800E3424
* Size: 0007EC
*/
void SearchSystem::updateLoopOptimised()
{
for (int i = 0; i < pikiMgr->mMaxElements; i++) {
if (pikiMgr->mEntryStatus[i]) {
continue;
}
Piki* piki = (Piki*)pikiMgr->mObjectList[i];
Iterator it(naviMgr);
CI_LOOP(it)
{
Creature* obj = *it;
if (AIPerf::useGrid) {
f32 sizeA = obj->getCentreSize();
f32 sizeB = piki->getCentreSize();
if (piki->mGrid.doCulling(obj->mGrid, sizeB + sizeA)) {
continue;
}
}
f32 dist = sphereDist(piki, obj);
if (dist <= 300.0f && piki->mSearchBuffer.available()) {
piki->mSearchBuffer.insert(obj, dist);
}
if (dist <= 300.0f && obj->mSearchBuffer.available()) {
obj->mSearchBuffer.insert(piki, dist);
}
}
Iterator it2(tekiMgr);
CI_LOOP(it2)
{
Creature* obj = *it2;
if (!obj->mGrid.aiCulling()) {
if (AIPerf::useGrid) {
f32 sizeA = obj->getCentreSize();
f32 sizeB = piki->getCentreSize();
if (piki->mGrid.doCulling(obj->mGrid, sizeB + sizeA)) {
continue;
}
}
f32 dist = sphereDist(piki, obj);
if (dist <= 300.0f && piki->mSearchBuffer.available()) {
piki->mSearchBuffer.insert(obj, dist);
}
if (dist <= 300.0f && obj->mSearchBuffer.available()) {
obj->mSearchBuffer.insert(piki, dist);
}
}
}
Iterator it3(bossMgr);
CI_LOOP(it3)
{
Creature* obj = *it3;
if (!obj->mGrid.aiCulling()) {
if (AIPerf::useGrid) {
f32 sizeA = obj->getCentreSize();
f32 sizeB = piki->getCentreSize();
if (piki->mGrid.doCulling(obj->mGrid, sizeB + sizeA)) {
continue;
}
}
f32 dist = sphereDist(piki, obj);
if (dist <= 300.0f && piki->mSearchBuffer.available()) {
piki->mSearchBuffer.insert(obj, dist);
}
if (dist <= 300.0f && obj->mSearchBuffer.available()) {
obj->mSearchBuffer.insert(piki, dist);
}
}
}
Iterator it4(itemMgr);
CI_LOOP(it4)
{
Creature* obj = *it4;
if (!obj->mGrid.aiCulling()) {
if (AIPerf::useGrid) {
f32 sizeA = obj->getCentreSize();
f32 sizeB = piki->getCentreSize();
if (piki->mGrid.doCulling(obj->mGrid, sizeB + sizeA)) {
continue;
}
}
f32 dist = sphereDist(piki, obj);
if (dist <= 300.0f && piki->mSearchBuffer.available()) {
piki->mSearchBuffer.insert(obj, dist);
}
if (dist <= 300.0f && obj->mSearchBuffer.available()) {
obj->mSearchBuffer.insert(piki, dist);
}
}
}
for (int j = i + 1; j < pikiMgr->mMaxElements; j++) {
if (!pikiMgr->mEntryStatus[j]) {
Piki* piki2 = (Piki*)pikiMgr->mObjectList[j];
if ((AIPerf::pikiMabiki || AIPerf::useUpdateMgr) && !piki->mSearchContext.updatable()
&& !piki2->mSearchContext.updatable()) {
continue;
}
if (AIPerf::useGrid) {
f32 sizeA = piki2->getCentreSize();
f32 sizeB = piki->getCentreSize();
if (piki->mGrid.doCulling(piki2->mGrid, sizeB + sizeA)) {
continue;
}
}
f32 dist = sphereDist(piki, piki2);
if (dist <= 300.0f) {
if (piki->mSearchBuffer.available()) {
piki->mSearchBuffer.insert(piki2, dist);
}
if (piki2->mSearchBuffer.available()) {
piki2->mSearchBuffer.insert(piki, dist);
}
}
}
}
}
}
/*
* --INFO--
* Address: 800E3C10
* Size: 000070
*/
SearchBuffer::SearchBuffer()
{
mMaxEntries = 0;
_20 = 0;
mCurrentEntries = 0;
mDataList = nullptr;
invalidate();
_24 = 0;
}
/*
* --INFO--
* Address: 800E3C80
* Size: 0001D8
*/
void SearchBuffer::init(SearchData* data, int p2)
{
mMaxEntries = p2;
mDataList = data;
for (int i = 0; i < p2; i++) {
mDataList[i].mSearchIteration = 0;
if (!mDataList[i].mTargetCreature.isNull()) {
PRINT(" %x(%d) : [%d] = %x\n", data, p2, i, mDataList[i].mTargetCreature.getPtr());
}
mDataList[i].mTargetCreature.clear();
mDataList[i].mDistance = 12800.0f;
}
mCurrentEntries = 0;
_10 = 0;
invalidate();
}
/*
* --INFO--
* Address: ........
* Size: 0000E4
*/
void SearchBuffer::operator=(SearchBuffer& other)
{
mMaxEntries = other.mMaxEntries;
_20 = other._20;
mCurrentEntries = other.mCurrentEntries;
_10 = other._10;
for (int i = 0; i < mMaxEntries; i++) {
mDataList[i].mSearchIteration = other.mDataList[i].mSearchIteration;
mDataList[i].mTargetCreature = other.mDataList[i].mTargetCreature;
mDataList[i].mDistance = other.mDataList[i].mDistance;
}
invalidate();
// UNUSED FUNCTION
}
/*
* --INFO--
* Address: ........
* Size: 000044
*/
int SearchBuffer::getIndex(Creature* obj)
{
for (int i = 0; i < mCurrentEntries; i++) {
if (mDataList[i].mTargetCreature.getPtr() == obj) {
return i;
}
}
return -1;
}
/*
* --INFO--
* Address: 800E3E58
* Size: 00003C
*/
void SearchBuffer::clear()
{
for (int i = 0; i < mCurrentEntries; i++) {
mDataList[i].mTargetCreature.clear();
}
mCurrentEntries = 0;
_1C = 0;
}
/*
* --INFO--
* Address: ........
* Size: 000024
*/
void SearchBuffer::reset()
{
if (mMaxEntries > 0) {
mDataList[mMaxEntries - 1].mDistance = 0.0f;
}
}
/*
* --INFO--
* Address: 800E3E94
* Size: 000060
*/
void SearchBuffer::invalidate()
{
if (!AIPerf::insQuick) {
return;
}
clear();
mMaxDistance = -100.0f;
mLastEntry = -1;
mCurrentEntries = 0;
_1C = 0;
}
/*
* --INFO--
* Address: 800E3EF4
* Size: 0001E8
*/
void SearchBuffer::insertQuick(Creature* obj, f32 dist)
{
if (!obj->isVisible() || !obj->isAlive()) {
return;
}
if ((mCurrentEntries < mMaxEntries || !(mMaxDistance < dist)) && getIndex(obj) == -1) {
if (mCurrentEntries >= mMaxEntries) {
if (mLastEntry == -1) {
return;
}
mDataList[mLastEntry].mTargetCreature.getPtr();
mDataList[mLastEntry].mTargetCreature.reset();
mDataList[mLastEntry].mTargetCreature.set(obj);
mMaxDistance = dist;
return;
}
mDataList[mCurrentEntries].mTargetCreature.getPtr();
mDataList[mCurrentEntries].mTargetCreature.reset();
mDataList[mCurrentEntries].mTargetCreature.set(obj);
if (mMaxDistance < dist) {
mMaxDistance = dist;
mLastEntry = mCurrentEntries;
}
mCurrentEntries++;
}
STACK_PAD_VAR(8);
}
/*
* --INFO--
* Address: 800E40DC
* Size: 000204
*/
void SearchBuffer::insert(Creature* creature, f32 distance)
{
if (AIPerf::insQuick) {
insertQuick(creature, distance);
return;
}
if (!creature->isVisible()) {
return;
}
int index = getIndex(creature);
if (index == -1) {
int i = mCurrentEntries - 1;
for (i; i >= 0; i--) {
if (mDataList[i].mDistance > distance) {
if (i + 1 < mMaxEntries) {
mDataList[i + 1].mTargetCreature = mDataList[i].mTargetCreature;
mDataList[i + 1].mDistance = mDataList[i].mDistance;
mDataList[i + 1].mSearchIteration = mDataList[i].mSearchIteration;
} else {
mDataList[mMaxEntries - 1].mTargetCreature.reset();
}
} else {
break;
}
}
if (i + 1 < mMaxEntries) {
mDataList[i + 1].mTargetCreature.set(creature);
mDataList[i + 1].mSearchIteration = -1;
mDataList[i + 1].mDistance = distance;
mCurrentEntries++;
if (mCurrentEntries >= mMaxEntries) {
mCurrentEntries = mMaxEntries;
}
}
} else {
if (mDataList[index].mSearchIteration > 0) {
mDataList[index].mSearchIteration = 0;
}
mDataList[index].mDistance = distance;
}
}
/*
* --INFO--
* Address: ........
* Size: 000114
* Note: Size isnt exact, but close enough for a stripped function
*/
void SearchBuffer::update()
{
for (int i = 0; i < mCurrentEntries; i++) {
int frameSinceLastSeen = mDataList[i].mSearchIteration;
mDataList[i].mSearchIteration++;
if (frameSinceLastSeen < 6) {
if (mDataList[i].mTargetCreature.getPtr()->isAlive()) {
continue;
}
continue;
}
// Timeout after 6 frames of not seeing the creature
mDataList[i].mTargetCreature.getPtr();
mDataList[i].mTargetCreature.reset();
int offs = i;
for (int j = offs + 1; j < mCurrentEntries; j++) {
mDataList[offs].mDistance = mDataList[j].mDistance;
mDataList[offs].mTargetCreature = mDataList[j].mTargetCreature;
mDataList[offs].mSearchIteration = mDataList[j].mSearchIteration;
offs = j;
}
mCurrentEntries--;
}
}
/*
* --INFO--
* Address: 800E42E0
* Size: 00002C
*/
Creature* SearchBuffer::getCreature(int id)
{
if (id < 0 || id >= mCurrentEntries) {
return nullptr;
}
return mDataList[id].mTargetCreature.getPtr();
}
/*
* --INFO--
* Address: 800E430C
* Size: 000008
*/
int SearchBuffer::getFirst()
{
return 0;
}
/*
* --INFO--
* Address: 800E4314
* Size: 000008
*/
int SearchBuffer::getNext(int i)
{
return i + 1;
}
/*
* --INFO--
* Address: 800E431C
* Size: 00001C
*/
bool SearchBuffer::isDone(int i)
{
if (i >= mCurrentEntries) {
return true;
}
return false;
}
| 412 | 0.815702 | 1 | 0.815702 | game-dev | MEDIA | 0.693799 | game-dev | 0.996006 | 1 | 0.996006 |
lynx-family/lynx | 5,959 | platform/darwin/ios/lynx/public/ui/LynxUIContext.h | // Copyright 2019 The Lynx Authors. All rights reserved.
// Licensed under the Apache License Version 2.0 that can be found in the
// LICENSE file in the root directory of this source tree.
#import <Foundation/Foundation.h>
#import <Lynx/ListNodeInfoFetcherProtocol.h>
#import <Lynx/LynxEventEmitter.h>
#import <Lynx/LynxGenericResourceFetcher.h>
#import <Lynx/LynxLifecycleDispatcher.h>
#import <Lynx/LynxMediaResourceFetcher.h>
#import <Lynx/LynxScreenMetrics.h>
#import <Lynx/LynxScrollListener.h>
#import <Lynx/LynxTemplateResourceFetcher.h>
#import <Lynx/LynxUIListProtocol.h>
#import "LynxImageFetcher.h"
NS_ASSUME_NONNULL_BEGIN
@class LynxRootUI;
@class LynxFontFaceContext;
@class LynxEventHandler;
@class LynxLifecycleDispatcher;
@class LynxShadowNodeOwner;
@class LynxUIOwner;
@class LynxUIExposure;
@class LynxUIIntersectionObserverManager;
@class LynxGlobalObserver;
@class LynxContext;
@class LynxShadowNode;
@protocol LUIErrorHandling;
@interface LynxUIContext : NSObject
@property(nonatomic, weak, nullable, readwrite) LynxContext* lynxContext;
@property(nonatomic, weak, nullable, readwrite) id<LynxImageFetcher> imageFetcher;
@property(nonatomic, weak, nullable, readwrite) id<LynxResourceFetcher> resourceFetcher;
@property(nonatomic, strong, nullable, readwrite) id<LynxResourceFetcher> resourceServiceFetcher;
@property(nonatomic, weak, nullable) id<LynxListLayoutProtocol> customizedListLayout;
@property(nonatomic, weak, nullable) id<LUIErrorHandling> errorHandler;
@property(nonatomic, weak, nullable, readwrite) id<LynxScrollListener> scrollListener;
@property(nonatomic, weak, nullable, readonly) LynxEventHandler* eventHandler;
@property(nonatomic, weak, nullable, readonly) LynxEventEmitter* eventEmitter;
@property(nonatomic, weak, nullable, readonly) UIView<LUIBodyView>* rootView;
@property(nonatomic, weak, nullable, readwrite) LynxRootUI* rootUI;
@property(nonatomic, weak, nullable, readwrite) LynxFontFaceContext* fontFaceContext;
@property(nonatomic, weak, nullable, readwrite) LynxShadowNodeOwner* nodeOwner;
@property(nonatomic, weak, nullable, readwrite) LynxUIOwner* uiOwner;
@property(nonatomic, weak) id lynxModuleExtraData;
@property(nonatomic, assign, readwrite) int64_t shellPtr;
@property(nonatomic, strong) id<ListNodeInfoFetcherProtocol> fetcher;
@property(nonatomic, readwrite) LynxScreenMetrics* screenMetrics;
@property(nonatomic, readonly) LynxUIIntersectionObserverManager* intersectionManager;
@property(nonatomic) LynxUIExposure* uiExposure;
@property(nonatomic, strong, nullable, readonly) NSDictionary* keyframesDict;
@property(nonatomic, nullable) NSDictionary* contextDict;
@property(nonatomic) LynxGlobalObserver* observer;
@property(nonatomic, readonly) BOOL enableTextGradientOpt;
// generic resource fetcher
@property(nonatomic, strong, nullable) id<LynxGenericResourceFetcher> genericResourceFetcher;
@property(nonatomic, strong, nullable) id<LynxMediaResourceFetcher> mediaResourceFetcher;
@property(nonatomic, strong, nullable) id<LynxTemplateResourceFetcher> templateResourceFetcher;
// settings
@property(nonatomic, readonly) BOOL defaultOverflowVisible;
@property(nonatomic, readonly) BOOL defaultImplicitAnimation;
@property(nonatomic, readonly) BOOL enableTextRefactor;
@property(nonatomic, readonly) BOOL defaultAutoResumeAnimation;
@property(nonatomic, readonly) BOOL defaultEnableNewTransformOrigin;
@property(nonatomic, readonly) BOOL enableEventRefactor;
@property(nonatomic, readonly) BOOL enableA11yIDMutationObserver;
@property(nonatomic, readonly) BOOL enableTextOverflow;
@property(nonatomic, readonly) BOOL enableNewClipMode;
@property(nonatomic, readonly) BOOL enableEventThrough;
@property(nonatomic, readonly) BOOL enableBackgroundShapeLayer;
@property(nonatomic, readonly) BOOL enableFiberArch;
@property(nonatomic, readonly) BOOL enableExposureUIMargin;
@property(nonatomic, readonly) BOOL enableTextLayerRender;
@property(nonatomic, readonly) BOOL enableTextLanguageAlignment;
@property(nonatomic, readonly) BOOL enableXTextLayoutReused;
@property(nonatomic, readonly) BOOL enableNewGesture;
@property(nonatomic, readonly) BOOL cssAlignWithLegacyW3c;
@property(nonatomic, readonly) NSString* targetSdkVersion;
@property(nonatomic, readonly) BOOL enableTextNonContiguousLayout;
@property(nonatomic, readonly) BOOL enableImageDownsampling;
@property(nonatomic, readonly) BOOL enableNewImage;
@property(nonatomic, readonly) BOOL trailUseNewImage;
@property(nonatomic, readonly) NSInteger logBoxImageSizeWarningThreshold;
@property(nonatomic, readonly) BOOL enableTextLayoutCache;
@property(nonatomic, readonly) BOOL enableExposureWhenReload;
- (instancetype)initWithScreenMetrics:(LynxScreenMetrics*)screenMetrics;
- (void)updateScreenSize:(CGSize)screenSize;
- (void)onGestureRecognized;
- (void)onGestureRecognizedByUI:(LynxUI*)ui;
- (void)onPlatformGestureStatusChanged:(int)status;
- (void)onPropsChangedByUI:(LynxUI*)ui;
- (BOOL)isTouchMoving;
- (NSNumber*)getLynxRuntimeId;
/// Deprecated: use didReceiveResourceError:withSource:type: instead
- (void)didReceiveResourceError:(NSError*)error;
- (void)reportError:(nonnull NSError*)error;
- (void)didReceiveException:(NSException*)exception
withMessage:(NSString*)message
forUI:(LynxUI*)ui;
- (BOOL)isDev;
- (void)addUIToExposedMap:(LynxUI*)ui;
- (void)addUIToExposedMap:(LynxUI*)ui
withUniqueIdentifier:(NSString* _Nullable)uniqueID
extraData:(NSDictionary* _Nullable)data
useOptions:(NSDictionary* _Nullable)options;
- (void)removeUIFromExposedMap:(LynxUI*)ui;
- (void)removeUIFromExposedMap:(LynxUI*)ui withUniqueIdentifier:(NSString* _Nullable)uniqueID;
- (void)removeUIFromIntersectionManager:(LynxUI*)ui;
- (void)stopExposure;
- (void)resumeExposure;
- (void)findShadowNodeAndRunTask:(NSInteger)sign task:(void (^)(LynxShadowNode*))task;
- (nullable id<LynxResourceFetcher>)getGenericResourceFetcher;
@end
NS_ASSUME_NONNULL_END
| 412 | 0.582482 | 1 | 0.582482 | game-dev | MEDIA | 0.513896 | game-dev | 0.634045 | 1 | 0.634045 |
AppliedEnergistics/Applied-Energistics-2 | 2,767 | src/main/java/appeng/api/upgrades/EmptyUpgradeInventory.java | /*
* This file is part of Applied Energistics 2.
* Copyright (c) 2021, TeamAppliedEnergistics, All rights reserved.
*
* Applied Energistics 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Applied Energistics 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.api.upgrades;
import java.util.Collections;
import java.util.Iterator;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.level.ItemLike;
import net.neoforged.neoforge.items.IItemHandler;
import net.neoforged.neoforge.items.wrapper.EmptyItemHandler;
final class EmptyUpgradeInventory implements IUpgradeInventory {
public static final EmptyUpgradeInventory INSTANCE = new EmptyUpgradeInventory();
@Override
public ItemLike getUpgradableItem() {
return Items.AIR;
}
@Override
public boolean isInstalled(ItemLike upgradeCard) {
return false;
}
@Override
public int getInstalledUpgrades(ItemLike u) {
return 0;
}
@Override
public int getMaxInstalled(ItemLike u) {
return 0;
}
@Override
public boolean isEmpty() {
return true;
}
@Override
public IItemHandler toItemHandler() {
return EmptyItemHandler.INSTANCE;
}
@Override
public int size() {
return 0;
}
@Override
public ItemStack getStackInSlot(int slotIndex) {
return ItemStack.EMPTY;
}
@Override
public void setItemDirect(int slotIndex, ItemStack stack) {
}
@Override
public Iterator<ItemStack> iterator() {
return Collections.emptyIterator();
}
@Override
public ItemStack insertItem(int slot, ItemStack stack, boolean simulate) {
return stack;
}
@Override
public ItemStack extractItem(int slot, int amount, boolean simulate) {
return ItemStack.EMPTY;
}
@Override
public void readFromNBT(CompoundTag data, String subtag, HolderLookup.Provider registries) {
}
@Override
public void writeToNBT(CompoundTag data, String subtag, HolderLookup.Provider registries) {
}
}
| 412 | 0.588741 | 1 | 0.588741 | game-dev | MEDIA | 0.995997 | game-dev | 0.745886 | 1 | 0.745886 |
SpartanJ/eepp | 6,299 | src/thirdparty/SDL2/src/filesystem/winrt/SDL_sysfilesystem.cpp | /*
Simple DirectMedia Layer
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "../../SDL_internal.h"
/* TODO, WinRT: remove the need to compile this with C++/CX (/ZW) extensions, and if possible, without C++ at all
*/
#ifdef __WINRT__
extern "C" {
#include "SDL_filesystem.h"
#include "SDL_error.h"
#include "SDL_hints.h"
#include "SDL_stdinc.h"
#include "SDL_system.h"
#include "../../core/windows/SDL_windows.h"
}
#include <string>
#include <unordered_map>
using namespace std;
using namespace Windows::Storage;
extern "C" const wchar_t *
SDL_WinRTGetFSPathUNICODE(SDL_WinRT_Path pathType)
{
switch (pathType) {
case SDL_WINRT_PATH_INSTALLED_LOCATION:
{
static wstring path;
if (path.empty()) {
path = Windows::ApplicationModel::Package::Current->InstalledLocation->Path->Data();
}
return path.c_str();
}
case SDL_WINRT_PATH_LOCAL_FOLDER:
{
static wstring path;
if (path.empty()) {
path = ApplicationData::Current->LocalFolder->Path->Data();
}
return path.c_str();
}
#if (WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP) || (NTDDI_VERSION > NTDDI_WIN8)
case SDL_WINRT_PATH_ROAMING_FOLDER:
{
static wstring path;
if (path.empty()) {
path = ApplicationData::Current->RoamingFolder->Path->Data();
}
return path.c_str();
}
case SDL_WINRT_PATH_TEMP_FOLDER:
{
static wstring path;
if (path.empty()) {
path = ApplicationData::Current->TemporaryFolder->Path->Data();
}
return path.c_str();
}
#endif
default:
break;
}
SDL_Unsupported();
return NULL;
}
extern "C" const char *
SDL_WinRTGetFSPathUTF8(SDL_WinRT_Path pathType)
{
typedef unordered_map<SDL_WinRT_Path, string> UTF8PathMap;
static UTF8PathMap utf8Paths;
UTF8PathMap::iterator searchResult = utf8Paths.find(pathType);
if (searchResult != utf8Paths.end()) {
return searchResult->second.c_str();
}
const wchar_t * ucs2Path = SDL_WinRTGetFSPathUNICODE(pathType);
if (!ucs2Path) {
return NULL;
}
char * utf8Path = WIN_StringToUTF8(ucs2Path);
utf8Paths[pathType] = utf8Path;
SDL_free(utf8Path);
return utf8Paths[pathType].c_str();
}
extern "C" char *
SDL_GetBasePath(void)
{
const char * srcPath = SDL_WinRTGetFSPathUTF8(SDL_WINRT_PATH_INSTALLED_LOCATION);
size_t destPathLen;
char * destPath = NULL;
if (!srcPath) {
SDL_SetError("Couldn't locate our basepath: %s", SDL_GetError());
return NULL;
}
destPathLen = SDL_strlen(srcPath) + 2;
destPath = (char *) SDL_malloc(destPathLen);
if (!destPath) {
SDL_OutOfMemory();
return NULL;
}
SDL_snprintf(destPath, destPathLen, "%s\\", srcPath);
return destPath;
}
extern "C" char *
SDL_GetPrefPath(const char *org, const char *app)
{
/* WinRT note: The 'SHGetFolderPath' API that is used in Windows 7 and
* earlier is not available on WinRT or Windows Phone. WinRT provides
* a similar API, but SHGetFolderPath can't be called, at least not
* without violating Microsoft's app-store requirements.
*/
const WCHAR * srcPath = NULL;
WCHAR path[MAX_PATH];
char *retval = NULL;
WCHAR* worg = NULL;
WCHAR* wapp = NULL;
size_t new_wpath_len = 0;
BOOL api_result = FALSE;
if (!app) {
SDL_InvalidParamError("app");
return NULL;
}
if (!org) {
org = "";
}
srcPath = SDL_WinRTGetFSPathUNICODE(SDL_WINRT_PATH_LOCAL_FOLDER);
if ( ! srcPath) {
SDL_SetError("Unable to find a source path");
return NULL;
}
if (SDL_wcslen(srcPath) >= MAX_PATH) {
SDL_SetError("Path too long.");
return NULL;
}
SDL_wcslcpy(path, srcPath, SDL_arraysize(path));
worg = WIN_UTF8ToString(org);
if (worg == NULL) {
SDL_OutOfMemory();
return NULL;
}
wapp = WIN_UTF8ToString(app);
if (wapp == NULL) {
SDL_free(worg);
SDL_OutOfMemory();
return NULL;
}
new_wpath_len = SDL_wcslen(worg) + SDL_wcslen(wapp) + SDL_wcslen(path) + 3;
if ((new_wpath_len + 1) > MAX_PATH) {
SDL_free(worg);
SDL_free(wapp);
SDL_SetError("Path too long.");
return NULL;
}
if (*worg) {
SDL_wcslcat(path, L"\\", new_wpath_len + 1);
SDL_wcslcat(path, worg, new_wpath_len + 1);
SDL_free(worg);
}
api_result = CreateDirectoryW(path, NULL);
if (api_result == FALSE) {
if (GetLastError() != ERROR_ALREADY_EXISTS) {
SDL_free(wapp);
WIN_SetError("Couldn't create a prefpath.");
return NULL;
}
}
SDL_wcslcat(path, L"\\", new_wpath_len + 1);
SDL_wcslcat(path, wapp, new_wpath_len + 1);
SDL_free(wapp);
api_result = CreateDirectoryW(path, NULL);
if (api_result == FALSE) {
if (GetLastError() != ERROR_ALREADY_EXISTS) {
WIN_SetError("Couldn't create a prefpath.");
return NULL;
}
}
SDL_wcslcat(path, L"\\", new_wpath_len + 1);
retval = WIN_StringToUTF8(path);
return retval;
}
#endif /* __WINRT__ */
/* vi: set ts=4 sw=4 expandtab: */
| 412 | 0.904708 | 1 | 0.904708 | game-dev | MEDIA | 0.444246 | game-dev,os-kernel | 0.837954 | 1 | 0.837954 |
EFanZh/LeetCode | 1,573 | src/problem_1547_minimum_cost_to_cut_a_stick/dynamic_programming.rs | pub struct Solution;
// ------------------------------------------------------ snip ------------------------------------------------------ //
impl Solution {
pub fn min_cost(n: i32, cuts: Vec<i32>) -> i32 {
let mut cuts = cuts;
let cuts = cuts.as_mut_slice();
cuts.sort_unstable();
let total_sticks = cuts.len() + 1;
let mut cache = vec![0; total_sticks * total_sticks].into_boxed_slice();
for sticks in 2..=total_sticks {
for start in 0..=total_sticks - sticks {
let end = start + sticks;
let mut cost = i32::MAX;
for cut in start + 1..end {
cost = cost.min(
cache[total_sticks * (cut - start - 1) + start] + cache[total_sticks * (end - cut - 1) + cut],
);
}
let left = cuts.get(start.wrapping_sub(1)).copied().unwrap_or(0);
let right = cuts.get(end - 1).copied().unwrap_or(n);
cost += right - left;
cache[total_sticks * (sticks - 1) + start] = cost;
}
}
cache[total_sticks * (total_sticks - 1)]
}
}
// ------------------------------------------------------ snip ------------------------------------------------------ //
impl super::Solution for Solution {
fn min_cost(n: i32, cuts: Vec<i32>) -> i32 {
Self::min_cost(n, cuts)
}
}
#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
| 412 | 0.694483 | 1 | 0.694483 | game-dev | MEDIA | 0.543738 | game-dev | 0.73053 | 1 | 0.73053 |
glKarin/com.n0n3m4.diii4a | 12,473 | Q3E/src/main/jni/fteqw/quakec/csqctest/src/ss/shambler.qc | /*
==============================================================================
SHAMBLER
==============================================================================
*/
$cd id1/models/shams
$origin 0 0 24
$base base
$skin base
$frame stand1 stand2 stand3 stand4 stand5 stand6 stand7 stand8 stand9
$frame stand10 stand11 stand12 stand13 stand14 stand15 stand16 stand17
$frame walk1 walk2 walk3 walk4 walk5 walk6 walk7
$frame walk8 walk9 walk10 walk11 walk12
$frame run1 run2 run3 run4 run5 run6
$frame smash1 smash2 smash3 smash4 smash5 smash6 smash7
$frame smash8 smash9 smash10 smash11 smash12
$frame swingr1 swingr2 swingr3 swingr4 swingr5
$frame swingr6 swingr7 swingr8 swingr9
$frame swingl1 swingl2 swingl3 swingl4 swingl5
$frame swingl6 swingl7 swingl8 swingl9
$frame magic1 magic2 magic3 magic4 magic5
$frame magic6 magic7 magic8 magic9 magic10 magic11 magic12
$frame pain1 pain2 pain3 pain4 pain5 pain6
$frame death1 death2 death3 death4 death5 death6
$frame death7 death8 death9 death10 death11
void() sham_stand1 =[ $stand1, sham_stand2 ] {ai_stand();};
void() sham_stand2 =[ $stand2, sham_stand3 ] {ai_stand();};
void() sham_stand3 =[ $stand3, sham_stand4 ] {ai_stand();};
void() sham_stand4 =[ $stand4, sham_stand5 ] {ai_stand();};
void() sham_stand5 =[ $stand5, sham_stand6 ] {ai_stand();};
void() sham_stand6 =[ $stand6, sham_stand7 ] {ai_stand();};
void() sham_stand7 =[ $stand7, sham_stand8 ] {ai_stand();};
void() sham_stand8 =[ $stand8, sham_stand9 ] {ai_stand();};
void() sham_stand9 =[ $stand9, sham_stand10] {ai_stand();};
void() sham_stand10 =[ $stand10, sham_stand11] {ai_stand();};
void() sham_stand11 =[ $stand11, sham_stand12] {ai_stand();};
void() sham_stand12 =[ $stand12, sham_stand13] {ai_stand();};
void() sham_stand13 =[ $stand13, sham_stand14] {ai_stand();};
void() sham_stand14 =[ $stand14, sham_stand15] {ai_stand();};
void() sham_stand15 =[ $stand15, sham_stand16] {ai_stand();};
void() sham_stand16 =[ $stand16, sham_stand17] {ai_stand();};
void() sham_stand17 =[ $stand17, sham_stand1 ] {ai_stand();};
void() sham_walk1 =[ $walk1, sham_walk2 ] {ai_walk(10);};
void() sham_walk2 =[ $walk2, sham_walk3 ] {ai_walk(9);};
void() sham_walk3 =[ $walk3, sham_walk4 ] {ai_walk(9);};
void() sham_walk4 =[ $walk4, sham_walk5 ] {ai_walk(5);};
void() sham_walk5 =[ $walk5, sham_walk6 ] {ai_walk(6);};
void() sham_walk6 =[ $walk6, sham_walk7 ] {ai_walk(12);};
void() sham_walk7 =[ $walk7, sham_walk8 ] {ai_walk(8);};
void() sham_walk8 =[ $walk8, sham_walk9 ] {ai_walk(3);};
void() sham_walk9 =[ $walk9, sham_walk10] {ai_walk(13);};
void() sham_walk10 =[ $walk10, sham_walk11] {ai_walk(9);};
void() sham_walk11 =[ $walk11, sham_walk12] {ai_walk(7);};
void() sham_walk12 =[ $walk12, sham_walk1 ] {ai_walk(7);
if (random() > 0.8)
sound (self, CHAN_VOICE, "shambler/sidle.wav", 1, ATTN_IDLE);};
void() sham_run1 =[ $run1, sham_run2 ] {ai_run(20);};
void() sham_run2 =[ $run2, sham_run3 ] {ai_run(24);};
void() sham_run3 =[ $run3, sham_run4 ] {ai_run(20);};
void() sham_run4 =[ $run4, sham_run5 ] {ai_run(20);};
void() sham_run5 =[ $run5, sham_run6 ] {ai_run(24);};
void() sham_run6 =[ $run6, sham_run1 ] {ai_run(20);
if (random() > 0.8)
sound (self, CHAN_VOICE, "shambler/sidle.wav", 1, ATTN_IDLE);
};
void() sham_smash1 =[ $smash1, sham_smash2 ] {
sound (self, CHAN_VOICE, "shambler/melee1.wav", 1, ATTN_NORM);
ai_charge(2);};
void() sham_smash2 =[ $smash2, sham_smash3 ] {ai_charge(6);};
void() sham_smash3 =[ $smash3, sham_smash4 ] {ai_charge(6);};
void() sham_smash4 =[ $smash4, sham_smash5 ] {ai_charge(5);};
void() sham_smash5 =[ $smash5, sham_smash6 ] {ai_charge(4);};
void() sham_smash6 =[ $smash6, sham_smash7 ] {ai_charge(1);};
void() sham_smash7 =[ $smash7, sham_smash8 ] {ai_charge(0);};
void() sham_smash8 =[ $smash8, sham_smash9 ] {ai_charge(0);};
void() sham_smash9 =[ $smash9, sham_smash10 ] {ai_charge(0);};
void() sham_smash10 =[ $smash10, sham_smash11 ] {
local vector delta;
local float ldmg;
if (!self.enemy)
return;
ai_charge(0);
delta = self.enemy.origin - self.origin;
if (vlen(delta) > 100)
return;
if (!CanDamage (self.enemy, self))
return;
ldmg = (random()*3) * 40;
T_Damage (self.enemy, self, self, ldmg);
sound (self, CHAN_VOICE, "shambler/smack.wav", 1, ATTN_NORM);
SpawnMeatSpray (self.origin + v_forward*16, crandom() * 100 * v_right);
SpawnMeatSpray (self.origin + v_forward*16, crandom() * 100 * v_right);
};
void() sham_smash11 =[ $smash11, sham_smash12 ] {ai_charge(5);};
void() sham_smash12 =[ $smash12, sham_run1 ] {ai_charge(4);};
void() sham_swingr1;
void(float side) ShamClaw =
{
local vector delta;
local float ldmg;
if (!self.enemy)
return;
ai_charge(10);
delta = self.enemy.origin - self.origin;
if (vlen(delta) > 100)
return;
ldmg = (random()*3) * 20;
T_Damage (self.enemy, self, self, ldmg);
sound (self, CHAN_VOICE, "shambler/smack.wav", 1, ATTN_NORM);
if (side)
{
makevectors (self.angles);
SpawnMeatSpray (self.origin + v_forward*16, side * v_right);
}
};
void() sham_swingl1 =[ $swingl1, sham_swingl2 ] {
sound (self, CHAN_VOICE, "shambler/melee2.wav", 1, ATTN_NORM);
ai_charge(5);};
void() sham_swingl2 =[ $swingl2, sham_swingl3 ] {ai_charge(3);};
void() sham_swingl3 =[ $swingl3, sham_swingl4 ] {ai_charge(7);};
void() sham_swingl4 =[ $swingl4, sham_swingl5 ] {ai_charge(3);};
void() sham_swingl5 =[ $swingl5, sham_swingl6 ] {ai_charge(7);};
void() sham_swingl6 =[ $swingl6, sham_swingl7 ] {ai_charge(9);};
void() sham_swingl7 =[ $swingl7, sham_swingl8 ] {ai_charge(5); ShamClaw(250);};
void() sham_swingl8 =[ $swingl8, sham_swingl9 ] {ai_charge(4);};
void() sham_swingl9 =[ $swingl9, sham_run1 ] {
ai_charge(8);
if (random()<0.5)
self.think = sham_swingr1;
};
void() sham_swingr1 =[ $swingr1, sham_swingr2 ] {
sound (self, CHAN_VOICE, "shambler/melee1.wav", 1, ATTN_NORM);
ai_charge(1);};
void() sham_swingr2 =[ $swingr2, sham_swingr3 ] {ai_charge(8);};
void() sham_swingr3 =[ $swingr3, sham_swingr4 ] {ai_charge(14);};
void() sham_swingr4 =[ $swingr4, sham_swingr5 ] {ai_charge(7);};
void() sham_swingr5 =[ $swingr5, sham_swingr6 ] {ai_charge(3);};
void() sham_swingr6 =[ $swingr6, sham_swingr7 ] {ai_charge(6);};
void() sham_swingr7 =[ $swingr7, sham_swingr8 ] {ai_charge(6); ShamClaw(-250);};
void() sham_swingr8 =[ $swingr8, sham_swingr9 ] {ai_charge(3);};
void() sham_swingr9 =[ $swingr9, sham_run1 ] {ai_charge(1);
ai_charge(10);
if (random()<0.5)
self.think = sham_swingl1;
};
void() sham_melee =
{
local float chance;
chance = random();
if (chance > 0.6 || self.health == 600)
sham_smash1 ();
else if (chance > 0.3)
sham_swingr1 ();
else
sham_swingl1 ();
};
//============================================================================
void() CastLightning =
{
local vector org, dir;
self.effects = self.effects | EF_MUZZLEFLASH;
ai_face ();
org = self.origin + '0 0 40';
dir = self.enemy.origin + '0 0 16' - org;
dir = normalize (dir);
traceline (org, self.origin + dir*600, TRUE, self);
WriteByte (MSG_BROADCAST, SVC_TEMPENTITY);
WriteByte (MSG_BROADCAST, TE_LIGHTNING1);
WriteEntity (MSG_BROADCAST, self);
WriteCoord (MSG_BROADCAST, org_x);
WriteCoord (MSG_BROADCAST, org_y);
WriteCoord (MSG_BROADCAST, org_z);
WriteCoord (MSG_BROADCAST, trace_endpos_x);
WriteCoord (MSG_BROADCAST, trace_endpos_y);
WriteCoord (MSG_BROADCAST, trace_endpos_z);
LightningDamage (org, trace_endpos, self, 10);
};
void() sham_magic1 =[ $magic1, sham_magic2 ] {ai_face();
sound (self, CHAN_WEAPON, "shambler/sattck1.wav", 1, ATTN_NORM);
};
void() sham_magic2 =[ $magic2, sham_magic3 ] {ai_face();};
void() sham_magic3 =[ $magic3, sham_magic4 ] {ai_face();self.nextthink = self.nextthink + 0.2;
local entity o;
self.effects = self.effects | EF_MUZZLEFLASH;
ai_face();
self.owner = spawn();
o = self.owner;
setmodel (o, "progs/s_light.mdl");
setorigin (o, self.origin);
o.angles = self.angles;
o.nextthink = time + 0.7;
o.think = SUB_Remove;
};
void() sham_magic4 =[ $magic4, sham_magic5 ]
{
self.effects = self.effects | EF_MUZZLEFLASH;
self.owner.frame = 1;
};
void() sham_magic5 =[ $magic5, sham_magic6 ]
{
self.effects = self.effects | EF_MUZZLEFLASH;
self.owner.frame = 2;
};
void() sham_magic6 =[ $magic6, sham_magic9 ]
{
remove (self.owner);
CastLightning();
sound (self, CHAN_WEAPON, "shambler/sboom.wav", 1, ATTN_NORM);
};
void() sham_magic9 =[ $magic9, sham_magic10 ]
{CastLightning();};
void() sham_magic10 =[ $magic10, sham_magic11 ]
{CastLightning();};
void() sham_magic11 =[ $magic11, sham_magic12 ]
{
if (skill == 3)
CastLightning();
};
void() sham_magic12 =[ $magic12, sham_run1 ] {};
void() sham_pain1 =[ $pain1, sham_pain2 ] {};
void() sham_pain2 =[ $pain2, sham_pain3 ] {};
void() sham_pain3 =[ $pain3, sham_pain4 ] {};
void() sham_pain4 =[ $pain4, sham_pain5 ] {};
void() sham_pain5 =[ $pain5, sham_pain6 ] {};
void() sham_pain6 =[ $pain6, sham_run1 ] {};
void(entity attacker, float damage) sham_pain =
{
sound (self, CHAN_VOICE, "shambler/shurt2.wav", 1, ATTN_NORM);
if (self.health <= 0)
return; // allready dying, don't go into pain frame
if (random()*400 > damage)
return; // didn't flinch
if (self.pain_finished > time)
return;
self.pain_finished = time + 2;
sham_pain1 ();
};
//============================================================================
void() sham_death1 =[ $death1, sham_death2 ] {};
void() sham_death2 =[ $death2, sham_death3 ] {};
void() sham_death3 =[ $death3, sham_death4 ] {self.solid = SOLID_NOT;};
void() sham_death4 =[ $death4, sham_death5 ] {};
void() sham_death5 =[ $death5, sham_death6 ] {};
void() sham_death6 =[ $death6, sham_death7 ] {};
void() sham_death7 =[ $death7, sham_death8 ] {};
void() sham_death8 =[ $death8, sham_death9 ] {};
void() sham_death9 =[ $death9, sham_death10 ] {};
void() sham_death10 =[ $death10, sham_death11 ] {};
void() sham_death11 =[ $death11, sham_death11 ] {};
void() sham_die =
{
// check for gib
if (self.health < -60)
{
ThrowCSQCGibs(GIB_SHAMBLER);
return;
}
// regular death
sound (self, CHAN_VOICE, "shambler/sdeath.wav", 1, ATTN_NORM);
sham_death1 ();
};
//============================================================================
/*QUAKED monster_shambler (1 0 0) (-32 -32 -24) (32 32 64) Ambush
*/
void() monster_shambler =
{
if (deathmatch)
{
remove(self);
return;
}
precache_model ("progs/shambler.mdl");
precache_model ("progs/s_light.mdl");
precache_model ("progs/h_shams.mdl");
precache_model ("progs/bolt.mdl");
precache_sound ("shambler/sattck1.wav");
precache_sound ("shambler/sboom.wav");
precache_sound ("shambler/sdeath.wav");
precache_sound ("shambler/shurt2.wav");
precache_sound ("shambler/sidle.wav");
precache_sound ("shambler/ssight.wav");
precache_sound ("shambler/melee1.wav");
precache_sound ("shambler/melee2.wav");
precache_sound ("shambler/smack.wav");
self.solid = SOLID_SLIDEBOX;
self.movetype = MOVETYPE_STEP;
setmodel (self, "progs/shambler.mdl");
setsize (self, VEC_HULL2_MIN, VEC_HULL2_MAX);
self.health = 600;
self.th_stand = sham_stand1;
self.th_walk = sham_walk1;
self.th_run = sham_run1;
self.th_die = sham_die;
self.th_melee = sham_melee;
self.th_missile = sham_magic1;
self.th_pain = sham_pain;
walkmonster_start();
};
| 412 | 0.903567 | 1 | 0.903567 | game-dev | MEDIA | 0.98491 | game-dev | 0.789048 | 1 | 0.789048 |
CraftTweaker/CraftTweaker-Documentation | 1,548 | docs_exported/1.19.4/crafttweaker/docs/vanilla/api/loot/condition/builder/LootConditionBuilder.md | # LootConditionBuilder
## Importing the class
It might be required for you to import the package if you encounter any issues (like casting an Array), so better be safe than sorry and add the import at the very top of the file.
```zenscript
import crafttweaker.api.loot.condition.builder.LootConditionBuilder;
```
## Casters
| Result Type | Is Implicit |
|------------------------------------------------------------|-------------|
| [LootCondition](/vanilla/api/loot/condition/LootCondition) | true |
## Methods
:::group{name=build}
Return Type: [LootCondition](/vanilla/api/loot/condition/LootCondition)
```zenscript
// LootConditionBuilder.build() as LootCondition
myLootConditionBuilder.build();
```
:::
:::group{name=invert}
Return Type: [LootConditionBuilder](/vanilla/api/loot/condition/builder/LootConditionBuilder)
```zenscript
// LootConditionBuilder.invert() as LootConditionBuilder
myLootConditionBuilder.invert();
```
:::
:::group{name=or}
Return Type: [AlternativeLootConditionBuilder](/vanilla/api/loot/condition/builder/AlternativeLootConditionBuilder)
```zenscript
LootConditionBuilder.or(other as LootConditionBuilder) as AlternativeLootConditionBuilder
```
| Parameter | Type |
|-----------|----------------------------------------------------------------------------------|
| other | [LootConditionBuilder](/vanilla/api/loot/condition/builder/LootConditionBuilder) |
:::
| 412 | 0.81683 | 1 | 0.81683 | game-dev | MEDIA | 0.984304 | game-dev | 0.595479 | 1 | 0.595479 |
Ravaelles/Atlantis | 2,921 | src/atlantis/production/constructions/position/conditions/TooCloseToBaseLocation.java | package atlantis.production.constructions.position.conditions;
import atlantis.config.AtlantisRaceConfig;
import atlantis.map.base.ABaseLocation;
import atlantis.map.base.BaseLocations;
import atlantis.map.position.APosition;
import atlantis.production.constructions.ConstructionRequests;
import atlantis.production.constructions.position.AbstractPositionFinder;
import atlantis.units.AUnitType;
import atlantis.units.select.Select;
import atlantis.util.We;
public class TooCloseToBaseLocation {
public static boolean TooCloseAndOverlapsBaseLocation(AUnitType building, APosition position) {
if (building.isGasBuilding()) return false;
if (building.isBase()) return forBase(position);
return forNonBaseBuilding(position, building);
}
private static boolean forBase(APosition position) {
if (
checkExistingBasesIncludingUnfinished(position)
|| checkExistingConstructionsOfOtherBase(position)
) {
AbstractPositionFinder._STATUS = "Base to close to anotha base";
return failed("Base to close to anotha base");
}
return false;
}
private static boolean failed(String reason) {
AbstractPositionFinder._STATUS = reason;
return true;
}
private static boolean checkExistingConstructionsOfOtherBase(APosition position) {
return ConstructionRequests.hasNotStartedNear(AtlantisRaceConfig.BASE, position, 8);
}
private static boolean forNonBaseBuilding(APosition position, AUnitType building) {
double minDist = 6;
if (We.protoss()) {
if (building.isPylon()) minDist = 4.5;
if (building.isGateway()) minDist = 5;
if (building.isForge()) minDist = 2.9;
}
if (We.terran()) {
if (building.isBunker()) minDist = 3.5;
}
// if (building.isBunker()) System.err.println("@ " + A.now() + " - bunker ");
for (ABaseLocation base : BaseLocations.baseLocations()) {
if (
base.translateByTiles(We.terran() ? 4 : 2, 1).distTo(position) <= minDist
) {
if (Select.ourBasesWithUnfinished().inRadius(6, position).notEmpty()) return false;
// System.err.println(" --- BASE " + base.position() + " Out with dist: " + base.translateByTiles(4,
// 1).distTo(position) + " / " + position);
// APosition natural = Bases.natural();
return failed("Overlaps base location");
}
}
return false;
}
private static boolean checkExistingBasesIncludingUnfinished(APosition position) {
int minDist = We.terran() ? 10 : 0;
if (Select.ourBuildingsWithUnfinished().bases().inRadius(minDist, position).isNotEmpty()) {
return failed("Base already exists here");
}
return false;
}
}
| 412 | 0.780838 | 1 | 0.780838 | game-dev | MEDIA | 0.571716 | game-dev | 0.92856 | 1 | 0.92856 |
LostCityRS/Content | 7,943 | scripts/quests/quest_legends/scripts/jungle_tree.rs2 | [oploc1,_jungle_tree] @start_chop_jungle;
[oploc1,_jungle_bush] @start_chop_jungle;
[oploc3,_jungle_tree] @chop_jungle;
[oploc3,_jungle_bush] @chop_jungle;
// the success rates in here don't feel quite right, probably need tweaking
[label,start_chop_jungle]
if (inv_total(inv, thkaramjamap) = 0 & inv_total(inv, thkaramjamapcomp) = 0 & %legendsquest < ^legends_complete) {
~mesbox("You'll get lost in this jungle without a map. You decide not to go any further.");
return;
}
def_namedobj $axe = ~woodcutting_axe_checker(false);
if ($axe = null) {
// OSRS message
~mesbox("You'll need an axe to get through this rough jungle. You don't think it would be a good idea to continue without one you've got the level to use.");
if (~inzone_coord_pair_table(kharazi_dense_jungle, coord) = true) {
@dense_jungle_escape;
}
return;
}
if (inv_total(inv, machette) = 0 & inv_total(worn, machette) = 0) {
// Says bush even for tree
~mesbox("You need a machete to cut your way through this dense jungle bush.");
if (~inzone_coord_pair_table(kharazi_dense_jungle, coord) = true) {
@dense_jungle_escape;
}
return;
}
def_int $bowl_water_count = inv_total(inv, goldbowl_water);
def_int $bowl_pure_water_count = inv_total(inv, goldbowl_pure);
def_int $blessed_bowl_water_count = inv_total(inv, goldbowlbless_water);
def_int $blessed_bowl_pure_water_count = inv_total(inv, goldbowlbless_pure);
if (calc($bowl_water_count + $bowl_pure_water_count + $blessed_bowl_water_count + $blessed_bowl_pure_water_count) > 0) {
mes("The heat in this jungle is terrific.");
mes("The water from your golden bowl evaporates.");
if ($bowl_water_count > 0) {
inv_del(inv, goldbowl_water, $bowl_water_count);
inv_add(inv, goldbowl_empty, $bowl_water_count);
}
if ($bowl_pure_water_count > 0) {
inv_del(inv, goldbowl_pure, $bowl_pure_water_count);
inv_add(inv, goldbowl_empty, $bowl_pure_water_count);
}
if ($blessed_bowl_water_count > 0) {
inv_del(inv, goldbowlbless_water, $blessed_bowl_water_count);
inv_add(inv, goldbowlbless_empty, $blessed_bowl_water_count);
}
if ($blessed_bowl_pure_water_count > 0) {
inv_del(inv, goldbowlbless_pure, $blessed_bowl_pure_water_count);
inv_add(inv, goldbowlbless_empty, $blessed_bowl_pure_water_count);
}
}
db_find(woodcutting_trees:tree, loc_type);
def_dbrow $data = db_findnext;
if ($data = null) {
~displaymessage(^dm_default);
return;
}
if (%action_delay < map_clock) {
if (loc_category = jungle_bush) {
%action_delay = calc(map_clock + 3);
%skill_anim = calc(map_clock + 1);
} else {
%action_delay = calc(map_clock + 5);
%skill_anim = calc(map_clock + 5);
}
p_oploc(1);
} else {
if (loc_category = jungle_bush) {
mes("You swing your machete at the jungle plant.");
}
else {
anim(struct_param(oc_param($axe, woodcutting_struct), skill_anim), 0);
mes("You swing your axe at the tree.");
}
@chop_jungle;
}
[label,chop_jungle]
// check if player has axe and level, ifso return best axe
def_namedobj $axe = ~woodcutting_axe_checker(true);
if ($axe = null) {
return;
}
// find tree in db
db_find(woodcutting_trees:tree, loc_type);
def_dbrow $data = db_findnext;
if ($data = null) {
~displaymessage(^dm_default);
return;
}
def_namedobj $product = db_getfield($data, woodcutting_trees:product, 0);
// play animation every 4 ticks, 2t for jungle bush
// make sure this is before the skill clock check, else theres a few cases where the skill anim
// gets redefined after skill(anim, null)
if (%skill_anim <= map_clock) {
if (loc_category = jungle_bush) {
%skill_anim = calc(map_clock + 2);
anim(human_machette_chop, 0);
}
else {
%skill_anim = calc(map_clock + 4);
anim(struct_param(oc_param($axe, woodcutting_struct), skill_anim), 0);
}
}
// sounds plays every tick for jungle bush, not at all for the tree
if(loc_category = jungle_bush) {
sound_synth(woodchop_4, 0, 10);
}
// this is here because theres always a tick where no mes("You swing your axe at the tree.") when spam clicking on tree
// this tick is when you get you get a roll. so that means that skill clock is set next tick after roll is given
if (%action_delay < map_clock) {
%action_delay = calc(map_clock + 4);
}
if (%action_delay = map_clock) {
// get lows and highs
if(loc_category = jungle_bush) sound_synth(woodchop_4, 0, 10); // double sound
def_int $respawnrate = db_getfield($data, woodcutting_trees:respawnrate, 0);
def_int $deplete_chance = 4; // 3/4 chance to deplete - this is a guess
// axe does not seem to have any effect, wc level does? (need more data)
if (stat_random(woodcutting, 70, 233) = true) {
// Jungle trees/bushes just silently fail to give logs/xp if no space
// There's also a chance to receive no logs. This seems to be about a 50% chance (tested w/100 rolls on OSRS)
if (inv_freespace(inv) > 0 & random(2) = 0) {
mes("You get some <lowercase(oc_name($product))>.");
stat_advance(woodcutting, db_getfield($data, woodcutting_trees:productexp, 0));
inv_add(inv, $product, 1);
}
if (random($deplete_chance) <= 2) {
$respawnrate = ~scale_by_playercount($respawnrate);
loc_change(loc_param(next_loc_stage), $respawnrate);
// set skill anim so it doesnt continue after depletion
anim(null, 0);
def_coord $dest = coord;
// If you chop jungle that you're standing on, you don't move forward
if (coord ! loc_coord) {
$dest = ~movecoord_indirection(coord, ~coord_direction(coord, loc_coord), 2);
}
else {
mes("This way is blocked off, no chance to get through here!");
return;
}
// todo: test on OSRS
if (map_blocked($dest) = true & ~jungle_at_dest($dest) = false) {
mes("This way is blocked off, no chance to get through here!");
}
else {
if (loc_category = jungle_tree) {
mes("You hack your way through the tree.");
}
else {
mes("You hack your way through the jungle bush.");
}
// Same message even when leaving the jungle
mes("You move deeper into the jungle.");
p_teleport($dest);
p_delay(0);
}
return;
}
}
}
p_oploc(3);
[proc,jungle_at_dest](coord $dest)(boolean)
if (.loc_find($dest, kharazi_jungle_plant1) = true | .loc_find($dest, kharazi_jungle_plant2) = true |
.loc_find($dest, kharazi_jungle_tree_logs) = true | .loc_find($dest, kharazi_jungle_tree1) = true |
.loc_find($dest, kharazi_jungle_tree2) = true) {
return (true);
}
return (false);
[label,dense_jungle_escape]
~mesbox("It looks like you're lost in the jungle!|Would you like to try and scrabble out?");
def_int $op = ~p_choice2_header("Yes, I'll scrabble out of this jungle.", 1, "No, I think I can find my own way out.", 2, "Scrabble out of jungle?");
if($op = 2) {
mes("You decide to stay where you are.");
return;
}
if(inzone(0_45_45_50_57,0_45_45_61_61,coord) = true) p_teleport(0_45_45_57_63);
else if(inzone(0_44_45_42_54,0_44_45_57_59,coord) = true) p_teleport(0_44_45_50_61);
else if(inzone(0_43_45_37_55,0_43_45_50_61,coord) = true) p_teleport(0_43_45_43_62);
else p_teleport(0_44_45_4_61); // other 2 zones tele to same pos
mes("You scrabble out of the jungle.");
mes("You're scratched to pieces by the dense jungle trees,");
mes("but at least you're alive and out of the jungle.");
~damage_self(1);
| 412 | 0.687012 | 1 | 0.687012 | game-dev | MEDIA | 0.964276 | game-dev | 0.889035 | 1 | 0.889035 |
Oxen-AI/oxen-archive | 2,298 | src/lib/src/model/merkle_tree/node.rs | // use std::fmt::{Display, Formatter, Result};
pub mod commit_node;
pub mod dir_node;
pub mod dir_node_with_path;
pub mod file_chunk_node;
pub mod file_node;
pub mod file_node_types;
pub mod file_node_with_dir;
pub mod merkle_tree_node;
pub mod merkle_tree_node_cache;
pub mod staged_merkle_tree_node;
pub mod vnode;
pub use commit_node::CommitNode;
pub use dir_node::DirNode;
pub use dir_node_with_path::DirNodeWithPath;
pub use file_chunk_node::FileChunkNode;
pub use file_node::FileNode;
pub use file_node_types::{FileChunkType, FileStorageType};
pub use file_node_with_dir::FileNodeWithDir;
pub use merkle_tree_node::MerkleTreeNode;
pub use staged_merkle_tree_node::StagedMerkleTreeNode;
pub use vnode::VNode;
use crate::model::metadata::generic_metadata::GenericMetadata;
pub use crate::model::{MerkleTreeNodeType, TMerkleTreeNode};
use serde::{Deserialize, Serialize};
use super::MerkleHash;
#[derive(Clone, Eq, PartialEq, Debug, Deserialize, Serialize)]
pub enum EMerkleTreeNode {
File(FileNode),
Directory(DirNode),
VNode(VNode),
FileChunk(FileChunkNode),
Commit(CommitNode),
}
impl EMerkleTreeNode {
pub fn node_type(&self) -> MerkleTreeNodeType {
match self {
EMerkleTreeNode::File(_) => MerkleTreeNodeType::File,
EMerkleTreeNode::Directory(_) => MerkleTreeNodeType::Dir,
EMerkleTreeNode::VNode(_) => MerkleTreeNodeType::VNode,
EMerkleTreeNode::FileChunk(_) => MerkleTreeNodeType::FileChunk,
EMerkleTreeNode::Commit(_) => MerkleTreeNodeType::Commit,
}
}
pub fn hash(&self) -> &MerkleHash {
match self {
EMerkleTreeNode::File(file) => file.hash(),
EMerkleTreeNode::Directory(dir) => dir.hash(),
EMerkleTreeNode::VNode(vnode) => vnode.hash(),
EMerkleTreeNode::FileChunk(file_chunk) => &file_chunk.hash,
EMerkleTreeNode::Commit(commit) => commit.hash(),
}
}
pub fn metadata(&self) -> Option<GenericMetadata> {
match self {
EMerkleTreeNode::File(file) => file.metadata(),
_ => None,
}
}
pub fn is_leaf(&self) -> bool {
matches!(
&self,
EMerkleTreeNode::File(_) | EMerkleTreeNode::FileChunk(_)
)
}
}
| 412 | 0.909123 | 1 | 0.909123 | game-dev | MEDIA | 0.662696 | game-dev | 0.653515 | 1 | 0.653515 |
shiptest-ss13/Shiptest | 12,025 | code/modules/research/nanites/nanite_programs/suppression.dm | //Programs that are generally useful for population control and non-harmful suppression.
/datum/nanite_program/sleepy
name = "Sleep Induction"
desc = "The nanites cause rapid narcolepsy when triggered."
can_trigger = TRUE
trigger_cost = 15
trigger_cooldown = 1200
rogue_types = list(/datum/nanite_program/brain_misfire, /datum/nanite_program/brain_decay)
/datum/nanite_program/sleepy/on_trigger(comm_message)
to_chat(host_mob, span_warning("You start to feel very sleepy..."))
host_mob.drowsyness += 20
addtimer(CALLBACK(host_mob, TYPE_PROC_REF(/mob/living, Sleeping), 200), rand(60,200))
/datum/nanite_program/paralyzing
name = "Paralysis"
desc = "The nanites force muscle contraction, effectively paralyzing the host."
use_rate = 3
rogue_types = list(/datum/nanite_program/nerve_decay)
/datum/nanite_program/paralyzing/active_effect()
host_mob.Stun(40)
/datum/nanite_program/paralyzing/enable_passive_effect()
. = ..()
to_chat(host_mob, span_warning("Your muscles seize! You can't move!"))
/datum/nanite_program/paralyzing/disable_passive_effect()
. = ..()
to_chat(host_mob, span_notice("Your muscles relax, and you can move again."))
/datum/nanite_program/shocking
name = "Electric Shock"
desc = "The nanites shock the host when triggered. Destroys a large amount of nanites!"
can_trigger = TRUE
trigger_cost = 10
trigger_cooldown = 300
program_flags = NANITE_SHOCK_IMMUNE
rogue_types = list(/datum/nanite_program/toxic)
/datum/nanite_program/shocking/on_trigger(comm_message)
host_mob.electrocute_act(rand(5,10), "shock nanites", 1, SHOCK_NOGLOVES)
/datum/nanite_program/stun
name = "Neural Shock"
desc = "The nanites pulse the host's nerves when triggered, inapacitating them for a short period."
can_trigger = TRUE
trigger_cost = 4
trigger_cooldown = 300
rogue_types = list(/datum/nanite_program/shocking, /datum/nanite_program/nerve_decay)
/datum/nanite_program/stun/on_trigger(comm_message)
playsound(host_mob, "sparks", 75, TRUE, -1, SHORT_RANGE_SOUND_EXTRARANGE)
host_mob.Paralyze(80)
/datum/nanite_program/pacifying
name = "Pacification"
desc = "The nanites suppress the aggression center of the brain, preventing the host from causing direct harm to others."
use_rate = 1
rogue_types = list(/datum/nanite_program/brain_misfire, /datum/nanite_program/brain_decay)
/datum/nanite_program/pacifying/enable_passive_effect()
. = ..()
ADD_TRAIT(host_mob, TRAIT_PACIFISM, "nanites")
/datum/nanite_program/pacifying/disable_passive_effect()
. = ..()
REMOVE_TRAIT(host_mob, TRAIT_PACIFISM, "nanites")
/datum/nanite_program/blinding
name = "Blindness"
desc = "The nanites suppress the host's ocular nerves, blinding them while they're active."
use_rate = 1.5
rogue_types = list(/datum/nanite_program/nerve_decay)
/datum/nanite_program/blinding/enable_passive_effect()
. = ..()
host_mob.become_blind("nanites")
/datum/nanite_program/blinding/disable_passive_effect()
. = ..()
host_mob.cure_blind("nanites")
/datum/nanite_program/mute
name = "Mute"
desc = "The nanites suppress the host's speech, making them mute while they're active."
use_rate = 0.75
rogue_types = list(/datum/nanite_program/brain_decay, /datum/nanite_program/brain_misfire)
/datum/nanite_program/mute/enable_passive_effect()
. = ..()
ADD_TRAIT(host_mob, TRAIT_MUTE, "nanites")
/datum/nanite_program/mute/disable_passive_effect()
. = ..()
REMOVE_TRAIT(host_mob, TRAIT_MUTE, "nanites")
/datum/nanite_program/fake_death
name = "Death Simulation"
desc = "The nanites induce a death-like coma into the host, able to fool most medical scans."
use_rate = 3.5
rogue_types = list(/datum/nanite_program/nerve_decay, /datum/nanite_program/necrotic, /datum/nanite_program/brain_decay)
/datum/nanite_program/fake_death/enable_passive_effect()
. = ..()
host_mob.emote("deathgasp")
host_mob.fakedeath("nanites")
/datum/nanite_program/fake_death/disable_passive_effect()
. = ..()
host_mob.cure_fakedeath("nanites")
//Can receive transmissions from a nanite communication remote for customized messages
/datum/nanite_program/comm
can_trigger = TRUE
var/comm_message = ""
/datum/nanite_program/comm/register_extra_settings()
extra_settings[NES_COMM_CODE] = new /datum/nanite_extra_setting/number(0, 0, 9999)
/datum/nanite_program/comm/proc/receive_comm_signal(signal_comm_code, comm_message, comm_source)
var/datum/nanite_extra_setting/comm_code = extra_settings[NES_COMM_CODE]
if(!activated || !comm_code)
return
if(signal_comm_code == comm_code)
host_mob.investigate_log("'s [name] nanite program was messaged by [comm_source] with comm code [signal_comm_code] and message '[comm_message]'.", INVESTIGATE_NANITES)
trigger(comm_message)
/datum/nanite_program/comm/speech
name = "Forced Speech"
desc = "The nanites force the host to say a pre-programmed sentence when triggered."
unique = FALSE
trigger_cost = 3
trigger_cooldown = 20
rogue_types = list(/datum/nanite_program/brain_misfire, /datum/nanite_program/brain_decay)
var/static/list/blacklist = list(
"*surrender",
"*collapse"
)
/datum/nanite_program/comm/speech/register_extra_settings()
. = ..()
extra_settings[NES_SENTENCE] = new /datum/nanite_extra_setting/text("")
/datum/nanite_program/comm/speech/on_trigger(comm_message)
var/sent_message = comm_message
if(!comm_message)
var/datum/nanite_extra_setting/sentence = extra_settings[NES_SENTENCE]
sent_message = sentence.get_value()
if(sent_message in blacklist)
return
if(host_mob.stat == DEAD)
return
to_chat(host_mob, span_warning("You feel compelled to speak..."))
host_mob.say(sent_message, forced = "nanite speech")
/datum/nanite_program/comm/voice
name = "Skull Echo"
desc = "The nanites echo a synthesized message inside the host's skull."
unique = FALSE
trigger_cost = 1
trigger_cooldown = 20
rogue_types = list(/datum/nanite_program/brain_misfire, /datum/nanite_program/brain_decay)
/datum/nanite_program/comm/voice/register_extra_settings()
. = ..()
extra_settings[NES_MESSAGE] = new /datum/nanite_extra_setting/text("")
/datum/nanite_program/comm/voice/on_trigger(comm_message)
var/sent_message = comm_message
if(!comm_message)
var/datum/nanite_extra_setting/message_setting = extra_settings[NES_MESSAGE]
sent_message = message_setting.get_value()
if(host_mob.stat == DEAD)
return
to_chat(host_mob, "<i>You hear a strange, robotic voice in your head...</i> \"[span_robot("[sent_message]")]\"")
/datum/nanite_program/comm/hallucination
name = "Hallucination"
desc = "The nanites make the host hallucinate something when triggered."
trigger_cost = 4
trigger_cooldown = 80
unique = FALSE
rogue_types = list(/datum/nanite_program/brain_misfire)
/datum/nanite_program/comm/hallucination/register_extra_settings()
. = ..()
var/list/options = list(
"Message",
"Battle",
"Sound",
"Weird Sound",
"Station Message",
"Health",
"Alert",
"Fire",
"Shock",
"Plasma Flood",
"Random"
)
extra_settings[NES_HALLUCINATION_TYPE] = new /datum/nanite_extra_setting/type("Message", options)
extra_settings[NES_HALLUCINATION_DETAIL] = new /datum/nanite_extra_setting/text("")
/datum/nanite_program/comm/hallucination/on_trigger(comm_message)
var/datum/nanite_extra_setting/hal_setting = extra_settings[NES_HALLUCINATION_TYPE]
var/hal_type = hal_setting.get_value()
var/datum/nanite_extra_setting/hal_detail_setting = extra_settings[NES_HALLUCINATION_DETAIL]
var/hal_details = hal_detail_setting.get_value()
if(comm_message && (hal_type != "Message")) //Triggered via comm remote, but not set to a message hallucination
return
var/sent_message = comm_message //Comm remotes can send custom hallucination messages for the chat hallucination
if(!sent_message)
sent_message = hal_details
if(!iscarbon(host_mob))
return
var/mob/living/carbon/C = host_mob
if(hal_details == "random")
hal_details = null
if(hal_type == "Random")
C.hallucination += 15
else
switch(hal_type)
if("Message")
new /datum/hallucination/chat(C, TRUE, null, sent_message)
if("Battle")
new /datum/hallucination/battle(C, TRUE, hal_details)
if("Sound")
new /datum/hallucination/sounds(C, TRUE, hal_details)
if("Weird Sound")
new /datum/hallucination/weird_sounds(C, TRUE, hal_details)
if("Station Message")
new /datum/hallucination/stationmessage(C, TRUE, hal_details)
if("Health")
switch(hal_details)
if("critical")
hal_details = SCREWYHUD_CRIT
if("dead")
hal_details = SCREWYHUD_DEAD
if("healthy")
hal_details = SCREWYHUD_HEALTHY
new /datum/hallucination/hudscrew(C, TRUE, hal_details)
if("Alert")
new /datum/hallucination/fake_alert(C, TRUE, hal_details)
if("Fire")
new /datum/hallucination/fire(C, TRUE)
if("Shock")
new /datum/hallucination/shock(C, TRUE)
if("Plasma Flood")
new /datum/hallucination/fake_flood(C, TRUE)
/datum/nanite_program/comm/hallucination/set_extra_setting(setting, value)
. = ..()
if(setting == NES_HALLUCINATION_TYPE)
switch(value)
if("Message")
extra_settings[NES_HALLUCINATION_DETAIL] = new /datum/nanite_extra_setting/text("")
if("Battle")
extra_settings[NES_HALLUCINATION_DETAIL] = new /datum/nanite_extra_setting/type("random", list("random","laser","disabler","esword","gun","stunprod","harmbaton","bomb"))
if("Sound")
extra_settings[NES_HALLUCINATION_DETAIL] = new /datum/nanite_extra_setting/type("random", list("random","airlock","airlock pry","console","explosion","far explosion","mech","glass","alarm","beepsky","mech","wall decon","door hack"))
if("Weird Sound")
extra_settings[NES_HALLUCINATION_DETAIL] = new /datum/nanite_extra_setting/type("random", list("random","phone","hallelujah","highlander","laughter","hyperspace","game over","creepy","tesla"))
if("Station Message")
extra_settings[NES_HALLUCINATION_DETAIL] = new /datum/nanite_extra_setting/type("random", list("random","ratvar","shuttle dock","blob alert","malf ai","meteors","supermatter"))
if("Health")
extra_settings[NES_HALLUCINATION_DETAIL] = new /datum/nanite_extra_setting/type("random", list("random","critical","dead","healthy"))
if("Alert")
extra_settings[NES_HALLUCINATION_DETAIL] = new /datum/nanite_extra_setting/type("random", list("random","not_enough_oxy","not_enough_tox","not_enough_co2","too_much_oxy","too_much_co2","too_much_tox","newlaw","nutrition","charge","gravity","fire","locked","hacked","temphot","tempcold","pressure"))
else
extra_settings.Remove(NES_HALLUCINATION_DETAIL)
/datum/nanite_program/good_mood
name = "Happiness Enhancer"
desc = "The nanites synthesize serotonin inside the host's brain, creating an artificial sense of happiness."
use_rate = 0.1
rogue_types = list(/datum/nanite_program/brain_decay)
/datum/nanite_program/good_mood/register_extra_settings()
. = ..()
extra_settings[NES_MOOD_MESSAGE] = new /datum/nanite_extra_setting/text("HAPPINESS ENHANCEMENT")
/datum/nanite_program/good_mood/enable_passive_effect()
. = ..()
SEND_SIGNAL(host_mob, COMSIG_ADD_MOOD_EVENT, "nanite_happy", /datum/mood_event/nanite_happiness, get_extra_setting_value(NES_MOOD_MESSAGE))
/datum/nanite_program/good_mood/disable_passive_effect()
. = ..()
SEND_SIGNAL(host_mob, COMSIG_CLEAR_MOOD_EVENT, "nanite_happy")
/datum/nanite_program/bad_mood
name = "Happiness Suppressor"
desc = "The nanites suppress the production of serotonin inside the host's brain, creating an artificial state of depression."
use_rate = 0.1
rogue_types = list(/datum/nanite_program/brain_decay)
/datum/nanite_program/bad_mood/register_extra_settings()
. = ..()
extra_settings[NES_MOOD_MESSAGE] = new /datum/nanite_extra_setting/text("HAPPINESS SUPPRESSION")
/datum/nanite_program/bad_mood/enable_passive_effect()
. = ..()
SEND_SIGNAL(host_mob, COMSIG_ADD_MOOD_EVENT, "nanite_sadness", /datum/mood_event/nanite_sadness, get_extra_setting_value(NES_MOOD_MESSAGE))
/datum/nanite_program/bad_mood/disable_passive_effect()
. = ..()
SEND_SIGNAL(host_mob, COMSIG_CLEAR_MOOD_EVENT, "nanite_sadness")
| 412 | 0.832155 | 1 | 0.832155 | game-dev | MEDIA | 0.995851 | game-dev | 0.84357 | 1 | 0.84357 |
PiratesOnlineRewritten/Pirates-Online-Rewritten | 3,942 | pirates/effects/VoodooSmoke.py | from pandac.PandaModules import *
from direct.interval.IntervalGlobal import *
from direct.particles import ParticleEffect
from direct.particles import Particles
from direct.particles import ForceGroup
import random
from PooledEffect import PooledEffect
from EffectController import EffectController
class VoodooSmoke(PooledEffect, EffectController):
cardScale = 64.0
def __init__(self):
PooledEffect.__init__(self)
EffectController.__init__(self)
model = loader.loadModel('models/effects/candleHalo')
self.card = model.find('**/effectCandleHalo')
if not VoodooSmoke.particleDummy:
VoodooSmoke.particleDummy = render.attachNewNode(ModelNode('VoodooSmokeParticleDummy'))
VoodooSmoke.particleDummy.setDepthWrite(0)
VoodooSmoke.particleDummy.setLightOff()
VoodooSmoke.particleDummy.setColorScaleOff()
VoodooSmoke.particleDummy.setFogOff()
self.f = ParticleEffect.ParticleEffect('VoodooSmoke')
self.f.reparentTo(self)
self.p0 = Particles.Particles('particles-1')
self.p0.setFactory('PointParticleFactory')
self.p0.setRenderer('SpriteParticleRenderer')
self.p0.setEmitter('DiscEmitter')
self.f.addParticles(self.p0)
f0 = ForceGroup.ForceGroup('Vortex')
self.f.addForceGroup(f0)
def createTrack(self):
self.p0.setPoolSize(128)
self.p0.setBirthRate(0.02)
self.p0.setLitterSize(1)
self.p0.setLitterSpread(0)
self.p0.setSystemLifespan(0.0)
self.p0.setLocalVelocityFlag(1)
self.p0.setSystemGrowsOlderFlag(0)
self.p0.factory.setLifespanBase(2.0)
self.p0.factory.setLifespanSpread(0.0)
self.p0.factory.setMassBase(1.0)
self.p0.factory.setMassSpread(0.0)
self.p0.factory.setTerminalVelocityBase(400.0)
self.p0.factory.setTerminalVelocitySpread(0.0)
self.p0.renderer.setAlphaMode(BaseParticleRenderer.PRALPHAINOUT)
self.p0.renderer.setUserAlpha(1.0)
self.p0.renderer.setFromNode(self.card)
self.p0.renderer.setColor(Vec4(1.0, 1.0, 1.0, 1.0))
self.p0.renderer.setXScaleFlag(1)
self.p0.renderer.setYScaleFlag(1)
self.p0.renderer.setAnimAngleFlag(0)
self.p0.renderer.setInitialXScale(0.01 * self.cardScale)
self.p0.renderer.setFinalXScale(0.02 * self.cardScale)
self.p0.renderer.setInitialYScale(0.04 * self.cardScale)
self.p0.renderer.setFinalYScale(0.04 * self.cardScale)
self.p0.renderer.setNonanimatedTheta(0.0)
self.p0.renderer.setAlphaBlendMethod(BaseParticleRenderer.PPBLENDLINEAR)
self.p0.renderer.setAlphaDisable(0)
self.p0.renderer.setColorBlendMode(ColorBlendAttrib.MAdd, ColorBlendAttrib.OIncomingColor, ColorBlendAttrib.OOneMinusIncomingAlpha)
self.p0.renderer.getColorInterpolationManager().addLinear(0.0, 1.0, Vec4(1.0, 0.5882353186607361, 1.0, 1.0), Vec4(0.0, 1.0, 1.0, 0.19607843458652496), 1)
self.p0.emitter.setEmissionType(BaseParticleEmitter.ETRADIATE)
self.p0.emitter.setAmplitude(1.0)
self.p0.emitter.setAmplitudeSpread(0.0)
self.p0.emitter.setOffsetForce(Vec3(0.0, 0.0, 6.0))
self.p0.emitter.setExplicitLaunchVector(Vec3(1.0, 0.0, 0.0))
self.p0.emitter.setRadiateOrigin(Point3(0.0, 0.0, 0.0))
self.p0.emitter.setRadius(0.6)
self.startEffect = Sequence(Func(self.p0.setBirthRate, 0.02), Func(self.p0.clearToInitial), Func(self.f.start, self, self.particleDummy))
self.endEffect = Sequence(Func(self.p0.setBirthRate, 100), Wait(7.0), Func(self.cleanUpEffect))
self.track = Sequence(self.startEffect, Wait(1.0), self.endEffect)
def cleanUpEffect(self):
self.f.disable()
self.detachNode()
self.checkInEffect(self)
def destroy(self):
EffectController.destroy(self)
PooledEffect.destroy(self) | 412 | 0.800923 | 1 | 0.800923 | game-dev | MEDIA | 0.677692 | game-dev,graphics-rendering | 0.632623 | 1 | 0.632623 |
oscarhiggott/PyMatching | 3,638 | src/pymatching/sparse_blossom/tracker/flood_check_event.h | // Copyright 2022 PyMatching Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef PYMATCHING2_FLOOD_CHECK_EVENT_H
#define PYMATCHING2_FLOOD_CHECK_EVENT_H
#include "pymatching/sparse_blossom/ints.h"
namespace pm {
class DetectorNode;
struct GraphFillRegion;
class SearchDetectorNode;
enum FloodCheckEventType : uint8_t {
/// A placeholder value indicating there was no event.
NO_FLOOD_CHECK_EVENT,
/// Indicates that an event may be happening at a detector node. The event could be:
/// - The node's region growing into an empty neighbor.
/// - The node's region colliding with an adjacent boundary.
/// - The node's region colliding with an adjacent region.
LOOK_AT_NODE,
/// Indicates that a region-level event might be happening. The event could be:
/// - The region shrinking enough that a detector node needs to be removed from it.
/// - The region being a blossom and shrinking to the point where it must shatter.
/// - The region shrinking to point and causing a degenerate collision between its neighbors.
LOOK_AT_SHRINKING_REGION,
/// Indicates that an event may be happening at a SearchDetectorNode during a Dijkstra search.
/// The event could be:
/// - The node's exploratory region growing into an empty neighbor.
/// - The node's exploratory region colliding with an adjacent boundary.
/// - The node's exploratory region colliding with an adjacent exploratory region.
LOOK_AT_SEARCH_NODE,
};
struct FloodCheckEvent {
union {
DetectorNode *data_look_at_node;
GraphFillRegion *data_look_at_shrinking_region;
SearchDetectorNode *data_look_at_search_node;
};
cyclic_time_int time;
FloodCheckEventType tentative_event_type;
FloodCheckEvent(DetectorNode *data, cyclic_time_int time);
FloodCheckEvent(GraphFillRegion *data, cyclic_time_int time);
FloodCheckEvent(SearchDetectorNode *data, cyclic_time_int time);
explicit FloodCheckEvent(cyclic_time_int time);
FloodCheckEvent() = delete;
bool operator==(const FloodCheckEvent &rhs) const;
bool operator!=(const FloodCheckEvent &rhs) const;
std::string str() const;
};
inline FloodCheckEvent::FloodCheckEvent(DetectorNode *data_look_at_node, cyclic_time_int time)
: data_look_at_node(data_look_at_node), time(time), tentative_event_type(LOOK_AT_NODE) {
}
inline FloodCheckEvent::FloodCheckEvent(GraphFillRegion *data_look_at_shrinking_region, cyclic_time_int time)
: data_look_at_shrinking_region(data_look_at_shrinking_region),
time(time),
tentative_event_type(LOOK_AT_SHRINKING_REGION) {
}
inline FloodCheckEvent::FloodCheckEvent(SearchDetectorNode *data_look_at_search_node, cyclic_time_int time)
: data_look_at_search_node(data_look_at_search_node), time(time), tentative_event_type(LOOK_AT_SEARCH_NODE) {
}
inline FloodCheckEvent::FloodCheckEvent(cyclic_time_int time) : time(time), tentative_event_type(NO_FLOOD_CHECK_EVENT) {
}
std::ostream &operator<<(std::ostream &out, const FloodCheckEvent &c);
} // namespace pm
#endif // PYMATCHING2_FLOOD_CHECK_EVENT_H
| 412 | 0.892373 | 1 | 0.892373 | game-dev | MEDIA | 0.91537 | game-dev | 0.607294 | 1 | 0.607294 |
LandSandBoat/server | 1,934 | scripts/zones/Arrapago_Reef/Zone.lua | -----------------------------------
-- Zone: Arrapago_Reef (54)
-----------------------------------
---@type TZone
local zoneObject = {}
zoneObject.onInitialize = function(zone)
zone:registerCuboidTriggerArea(1, -462, -4, -420, -455, -1, -392) -- approach the Cutter
end
zoneObject.onZoneIn = function(player, prevZone)
local cs = -1
if
player:getXPos() == 0 and
player:getYPos() == 0 and
player:getZPos() == 0
then
player:setPos(-456, -3, -405, 64)
end
if
prevZone == xi.zone.THE_ASHU_TALIF and
player:getCharVar('AgainstAllOdds') == 3
then
cs = 238
elseif prevZone == xi.zone.ILRUSI_ATOLL then
player:setPos(26, -7, 606, 222)
end
return cs
end
zoneObject.afterZoneIn = function(player)
player:entityVisualPacket('1pb1')
player:entityVisualPacket('2pb1')
end
zoneObject.onTriggerAreaEnter = function(player, triggerArea)
if
player:getQuestStatus(xi.questLog.AHT_URHGAN, xi.quest.id.ahtUrhgan.AGAINST_ALL_ODDS) == xi.questStatus.QUEST_ACCEPTED and
player:getCharVar('AgainstAllOdds') == 1
then
player:startEvent(237)
end
end
zoneObject.onGameDay = function()
xi.apkallu.updateHate(xi.zone.ARRAPAGO_REEF, -3)
end
zoneObject.onEventUpdate = function(player, csid, option, npc)
end
zoneObject.onEventFinish = function(player, csid, option, npc)
if csid == 108 then -- enter instance: illrusi atoll
player:setPos(0, 0, 0, 0, 55)
elseif csid == 222 then -- Enter instance: Black coffin
player:setPos(0, 0, 0, 0, 60)
elseif csid == 237 then
player:startEvent(240)
elseif csid == 238 then
npcUtil.completeQuest(player, xi.questLog.AHT_URHGAN, xi.quest.id.ahtUrhgan.AGAINST_ALL_ODDS, { item = 15266, var = 'AgainstAllOdds' })
elseif csid == 240 then
player:setCharVar('AgainstAllOdds', 2)
end
end
return zoneObject
| 412 | 0.790827 | 1 | 0.790827 | game-dev | MEDIA | 0.978549 | game-dev | 0.906079 | 1 | 0.906079 |
Fluorohydride/ygopro-scripts | 3,163 | c25862681.lua | --エンシェント・フェアリー・ドラゴン
function c25862681.initial_effect(c)
--synchro summon
aux.AddSynchroProcedure(c,nil,aux.NonTuner(nil),1)
c:EnableReviveLimit()
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(25862681,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1,25862681)
e1:SetCondition(c25862681.sumcon)
e1:SetCost(c25862681.cost)
e1:SetTarget(c25862681.sumtg)
e1:SetOperation(c25862681.sumop)
c:RegisterEffect(e1)
--destroy
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(25862681,1))
e2:SetCategory(CATEGORY_DESTROY+CATEGORY_RECOVER+CATEGORY_SEARCH)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1,25862682)
e2:SetCost(c25862681.cost)
e2:SetTarget(c25862681.destg)
e2:SetOperation(c25862681.desop)
c:RegisterEffect(e2)
end
function c25862681.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription())
end
function c25862681.sumcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetCurrentPhase()==PHASE_MAIN1
end
function c25862681.sumfilter(c,e,tp)
return c:IsLevelBelow(4) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c25862681.sumtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c25862681.sumfilter,tp,LOCATION_HAND,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,0,LOCATION_HAND)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_BP)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_OATH)
e1:SetTargetRange(1,0)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
end
function c25862681.sumop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c25862681.sumfilter,tp,LOCATION_HAND,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
function c25862681.destg(e,tp,eg,ep,ev,re,r,rp,chk)
local g=Duel.GetFieldGroup(tp,LOCATION_FZONE,LOCATION_FZONE)
if chk==0 then return g:GetCount()>0 end
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0)
Duel.SetOperationInfo(0,CATEGORY_RECOVER,nil,0,tp,1000)
end
function c25862681.ffilter(c,g)
return c:IsType(TYPE_FIELD) and c:IsAbleToHand() and not g:IsExists(Card.IsCode,1,nil,c:GetCode())
end
function c25862681.desop(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetFieldGroup(tp,LOCATION_FZONE,LOCATION_FZONE)
if g:GetCount()>0 then
Duel.Destroy(g,REASON_EFFECT)
local og=Duel.GetOperatedGroup()
if og:GetCount()>0 then
Duel.Recover(tp,1000,REASON_EFFECT)
local fg=Duel.GetMatchingGroup(c25862681.ffilter,tp,LOCATION_DECK,0,nil,og)
if fg:GetCount()>0 and Duel.SelectYesNo(tp,aux.Stringid(25862681,2)) then
Duel.BreakEffect()
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local sg=fg:Select(tp,1,1,nil)
Duel.SendtoHand(sg,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,sg)
end
end
end
end
| 412 | 0.882171 | 1 | 0.882171 | game-dev | MEDIA | 0.991048 | game-dev | 0.960177 | 1 | 0.960177 |
beyond-aion/aion-server | 3,359 | game-server/data/handlers/ai/instance/theobomosLab/TriroansSummonAI.java | package ai.instance.theobomosLab;
import java.util.concurrent.atomic.AtomicBoolean;
import com.aionemu.gameserver.ai.AIActions;
import com.aionemu.gameserver.ai.AIName;
import com.aionemu.gameserver.ai.manager.WalkManager;
import com.aionemu.gameserver.model.gameobjects.Npc;
import com.aionemu.gameserver.skillengine.SkillEngine;
import com.aionemu.gameserver.utils.PositionUtil;
import com.aionemu.gameserver.utils.ThreadPoolManager;
import ai.AggressiveNpcAI;
/**
* @author Ritsu
*/
@AIName("triroan_summon")
public class TriroansSummonAI extends AggressiveNpcAI {
private AtomicBoolean isDestroyed = new AtomicBoolean(false);
private int walkPosition;
private int helperSkill;
public TriroansSummonAI(Npc owner) {
super(owner);
}
@Override
public boolean canThink() {
return false;
}
@Override
protected void handleSpawned() {
super.handleSpawned();
switch (getNpcId()) {
case 280975:
walkPosition = 3;
helperSkill = 18493;
break;
case 280976:
walkPosition = 4;
helperSkill = 18492;
break;
case 280977:
walkPosition = 2;
helperSkill = 18485;
break;
case 280978:
walkPosition = 5;
helperSkill = 18491;
break;
}
}
@Override
protected void handleMoveArrived() {
super.handleMoveArrived();
int point = getOwner().getMoveController().getCurrentStep().getStepIndex();
if (walkPosition == point) {
if (isDestroyed.compareAndSet(false, true)) {
getSpawnTemplate().setWalkerId(null);
WalkManager.stopWalking(this);
useSkill();
startDespawnTask();
}
}
}
private synchronized void useSkill() {
Npc boss = getPosition().getWorldMapInstance().getNpc(214669);
if (boss != null && checkLocation(getOwner()) && !boss.isDead()) {
SkillEngine.getInstance().getSkill(boss, helperSkill, 50, boss).useSkill();
} else
checkSkillUse(boss);
}
private void checkSkillUse(final Npc boss) {
if (boss != null && checkDistance() == 0 && !boss.isDead()) {
if (!boss.isCasting())
SkillEngine.getInstance().getSkill(boss, helperSkill, 50, boss).useSkill();
else {
ThreadPoolManager.getInstance().schedule(new Runnable() {
@Override
public void run() {
if (checkDistance() == 0 && !boss.isDead())
checkSkillUse(boss);
}
}, 5000);
}
}
}
private boolean checkLocation(Npc npc) {
if (checkDistance() == 1 && npc.getNpcId() == 280975)
return true;
else if (checkDistance() == 2 && npc.getNpcId() == 280976)
return true;
else if (checkDistance() == 3 && npc.getNpcId() == 280977)
return true;
else if (checkDistance() == 4 && npc.getNpcId() == 280978)
return true;
else
return false;
}
public int checkDistance() {
Npc boss = getPosition().getWorldMapInstance().getNpc(214669);
if (PositionUtil.getDistance(boss, 624.002f, 474.241f, 196.160f) <= 5)
return 1;
else if (PositionUtil.getDistance(boss, 623.23f, 502.715f, 196.087f) <= 5)
return 2;
else if (PositionUtil.getDistance(boss, 579.943f, 500.999f, 196.604f) <= 5)
return 3;
else if (PositionUtil.getDistance(boss, 578.323f, 475.784f, 196.463f) <= 5)
return 4;
else
return 0;
}
private void startDespawnTask() {
ThreadPoolManager.getInstance().schedule(new Runnable() {
@Override
public void run() {
AIActions.deleteOwner(TriroansSummonAI.this);
}
}, 3000);
}
}
| 412 | 0.89794 | 1 | 0.89794 | game-dev | MEDIA | 0.991143 | game-dev | 0.935609 | 1 | 0.935609 |
benpollarduk/NetAF | 3,140 | NetAF.Example/Assets/Regions/Zelda/NPCs/Saria.cs | using NetAF.Assets;
using NetAF.Assets.Characters;
using NetAF.Assets.Locations;
using NetAF.Conversations;
using NetAF.Conversations.Instructions;
using NetAF.Example.Assets.Regions.Zelda.Items;
using NetAF.Extensions;
using NetAF.Utilities;
namespace NetAF.Example.Assets.Regions.Zelda.NPCs
{
public class Saria : IAssetTemplate<NonPlayableCharacter>
{
#region Constants
internal const string Name = "Saria";
private const string Description = "A pretty Kokiri elf, dresse.";
#endregion
#region Fields
private readonly Room room;
#endregion
#region Constructors
internal Saria(Room room)
{
this.room = room;
}
#endregion
#region Overrides of NonIAssetTemplate<PlayableCharacter>
/// <summary>
/// Instantiate a new instance of the asset.
/// </summary>
/// <returns>The asset.</returns>
public NonPlayableCharacter Instantiate()
{
NonPlayableCharacter saria = null;
Conversation conversation = new
(
new("Hi Link, how's it going?"),
new("I lost my red rupee, if you find it will you please bring it to me?"),
new("Oh Link you are so adorable."),
new("OK Link your annoying me now, I'm just going to ignore you.", new First())
);
saria = new NonPlayableCharacter(Name, Description, conversation: conversation, interaction: item =>
{
saria.FindItem(TailKey.Name, out var key);
if (Rupee.Name.EqualsIdentifier(item.Identifier) && key != null)
{
saria.RemoveItem(key);
room.AddItem(key);
return new(InteractionResult.ItemExpires, item, $"{saria.Identifier.Name} looks excited! \"Thanks Link, here take the Tail Key!\" Saria put the Tail Key down, awesome!");
}
if (Shield.Name.EqualsIdentifier(item.Identifier))
{
return new(InteractionResult.NoChange, item, $"{saria.Identifier.Name} looks at your shield, but seems pretty unimpressed.");
}
if (Sword.Name.EqualsIdentifier(item.Identifier) && saria.IsAlive)
{
saria.Kill();
if (!saria.HasItem(key))
return new(InteractionResult.NoChange, item, $"You strike {saria.Identifier.Name} in the face with the sword and she falls down dead.");
saria.RemoveItem(key);
room.AddItem(key);
return new(InteractionResult.NoChange, item, $"You strike {saria.Identifier.Name} in the face with the sword and she falls down dead. When she fell you saw something drop to out of her hand, it looked like a key...");
}
return new(InteractionResult.NoChange, item);
});
saria.AddItem(new TailKey().Instantiate());
return saria;
}
#endregion
}
}
| 412 | 0.800329 | 1 | 0.800329 | game-dev | MEDIA | 0.625208 | game-dev | 0.900918 | 1 | 0.900918 |
glitchassassin/screeps | 5,028 | src/Strategy/Acquire/findAcquireTarget.ts | import { roomPlans } from 'Selectors/roomPlans';
import { ACQUIRE_MAX_RCL, OFFICE_LIMIT } from 'config';
import { getOfficeDistanceByRoomPath } from '../../Selectors/getOfficeDistance';
import { rcl } from '../../Selectors/rcl';
import { scoreAcquireTarget } from './scoreAcquireTarget';
declare global {
interface Memory {
claim?: {
target: string;
claimer?: string; // creep name
};
}
}
export enum AcquireStatus {
CLAIM = 'claim',
SUPPORT = 'support',
DONE = 'done'
}
/**
* If GCL <= Memory.offices.length, return
* If an Acquire target is already saved (and still valid), use that
* Otherwise, for each office, find the closest room plan that isn't
* already an office. The closest is the winner.
*/
export const findAcquireTarget = () => {
if (Memory.claim && acquireTargetIsValid(Memory.claim.target) && !shouldPostponeAcquire(Memory.claim.target)) {
return Memory.claim.target;
} else {
Memory.claim = undefined;
}
const shouldAcquire = Object.keys(Memory.offices).length < Math.min(OFFICE_LIMIT, Game.gcl.level);
// Evaluate a new target every 50 ticks
if ((Game.time + 25) % 50 !== 0) return undefined;
// No cached target, scan for an acceptable one
const offices = Object.keys(Memory.offices);
let bestTarget: string | undefined;
let bestScore: number = Infinity;
// Look for acquire/support target in Offices if GCL = offices count
let targetRooms = shouldAcquire ? Object.keys(Memory.rooms) : Object.keys(Memory.offices);
for (const room of targetRooms) {
if (!acquireTargetIsValid(room) || shouldPostponeAcquire(room)) {
continue;
}
const distance = Math.min(
...offices
.filter(r => Game.rooms[r].energyCapacityAvailable >= 850)
.map(r => getOfficeDistanceByRoomPath(r, room) ?? Infinity),
Infinity
);
if (distance > 8) {
continue;
}
const score = scoreAcquireTarget(room);
// If no target, pick the first eligible one
// If the target has a better mineral, pick that one
// If the target's mineral ranking is the same but it's closer, pick that one
if (!bestTarget || score > bestScore) {
bestTarget = room;
bestScore = score;
}
}
if (bestTarget) {
delete Memory.rooms[bestTarget].lastAcquireAttempt;
Memory.claim = { target: bestTarget };
}
return Memory.claim?.target;
};
/**
* If acquire attempt fails, reschedule attempt on a progressive scale
* 20k ticks after first failure, 40k ticks after second, etc.
*/
const shouldPostponeAcquire = (roomName: string) => {
if (Game.rooms[roomName]?.controller?.my) return false; // already claimed
// If it's less than five ticks since Lawyer checked in,
// or Lawyer hasn't checked in yet, ignore
const timeSinceLastAttempt = Game.time - (Memory.rooms[roomName].lastAcquireAttempt ?? Game.time);
const attempts = Memory.rooms[roomName].acquireAttempts ?? 0;
if (timeSinceLastAttempt < 5) {
return false;
}
if (timeSinceLastAttempt > attempts * 20000) {
return false;
}
return true;
};
export const acquireTargetIsValid = (roomName: string) => {
return (
Memory.rooms[roomName] &&
Memory.rooms[roomName].eligibleForOffice &&
(!Memory.rooms[roomName].owner ||
(Memory.rooms[roomName].owner === 'LordGreywether' && (Game.rooms[roomName]?.controller?.level ?? 0) < 4)) &&
(!Memory.rooms[roomName].reserver || Memory.rooms[roomName].reserver === 'LordGreywether') &&
Memory.roomPlans[roomName]?.office &&
(Memory.rooms[roomName].owner === 'LordGreywether' || (Memory.rooms[roomName].safeModeCooldown ?? 0) < Game.time)
);
};
export const acquireStatus = () => {
if (!Memory.claim) return AcquireStatus.DONE;
if (!Game.rooms[Memory.claim.target]?.controller?.my) return AcquireStatus.CLAIM;
if (
// support until ACQUIRE_MAX_RCL and storage is complete
rcl(Memory.claim.target) <= ACQUIRE_MAX_RCL &&
!roomPlans(Memory.claim.target)?.headquarters?.storage.structure
)
return AcquireStatus.SUPPORT;
return AcquireStatus.DONE;
};
export const officeShouldAcquireTarget = (officeName: string) => {
const room = findAcquireTarget();
if (!room) return false;
if (officeName === room || rcl(officeName) < 5) return false;
const distance = getOfficeDistanceByRoomPath(officeName, room);
return distance && distance < CREEP_CLAIM_LIFE_TIME / 50 && acquireStatus() !== AcquireStatus.DONE;
};
export const officeShouldClaimAcquireTarget = (officeName: string) => {
// Sets acquireTarget and acquiringOffice. If we sohuld not
// support, we should not claim either.
if (!officeShouldAcquireTarget(officeName)) return false;
return acquireStatus() === AcquireStatus.CLAIM;
};
export const officeShouldSupportAcquireTarget = (officeName: string) => {
// Sets acquireTarget and acquiringOffice. If we sohuld not
// support, we should not claim either.
if (!officeShouldAcquireTarget(officeName)) return false;
return acquireStatus() === AcquireStatus.SUPPORT;
};
| 412 | 0.670082 | 1 | 0.670082 | game-dev | MEDIA | 0.897448 | game-dev | 0.818311 | 1 | 0.818311 |
AxGord/Pony | 1,728 | src/pony/ui/gui/AnimCore.hx | package pony.ui.gui;
import pony.events.Signal1;
import pony.events.Signal2;
import pony.time.Time;
import pony.time.DTimer;
import pony.time.DT;
import pony.math.MathTools;
/**
* AnimCore
* @author AxGord <axgord@gmail.com>
*/
#if (haxe_ver >= 4.2) abstract #end
class AnimCore implements pony.magic.HasAbstract implements pony.magic.HasSignal {
@:auto public var onFrame: Signal1<Int>;
@:auto public var onFrameUpdate: Signal2<Int, DT>;
@:auto public var onComplete: Signal1<DT>;
public var totalFrames(get, never): Int;
public var frame(default, set): Int = 0;
public var loop: Bool = true;
private var timer: DTimer;
public function new(frameTime: Time, fixedTime: Bool = false) {
timer = fixedTime ? DTimer.createFixedTimer(frameTime, -1) : DTimer.createTimer(frameTime, -1);
timer.complete << tick;
}
private function tick(dt: DT): Void {
if (frame >= totalFrames - 1) {
if (!loop) {
stop();
eComplete.dispatch(dt);
return;
}
frame = 0;
} else {
frame++;
}
eFrameUpdate.dispatch(frame, dt);
}
public inline function play(dt: DT = 0): Void timer.start(dt);
public inline function stop(): Void {
timer.stop();
timer.reset();
}
public inline function gotoAndPlay(frame: Int, dt: DT = 0): Void {
this.frame = frame;
play(dt);
}
public inline function gotoAndStop(frame: Int): Void {
this.frame = frame;
stop();
}
public function set_frame(n: Int): Int {
if (n < 0) n = 0;
else if (n > totalFrames) n = totalFrames;
if (n != frame) {
frame = n;
eFrame.dispatch(n);
}
return n;
}
@:abstract private function get_totalFrames(): Int;
public function destroy(): Void {
timer.destroy();
timer = null;
destroySignals();
}
} | 412 | 0.914286 | 1 | 0.914286 | game-dev | MEDIA | 0.612942 | game-dev | 0.968901 | 1 | 0.968901 |
magefree/mage | 3,295 | Mage.Sets/src/mage/cards/t/TheLostAndTheDamned.java | package mage.cards.t;
import mage.abilities.TriggeredAbilityImpl;
import mage.abilities.effects.common.CreateTokenEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Zone;
import mage.game.Game;
import mage.game.events.EntersTheBattlefieldEvent;
import mage.game.events.GameEvent;
import mage.game.permanent.token.SpawnToken;
import mage.game.stack.Spell;
import java.util.Optional;
import java.util.UUID;
public final class TheLostAndTheDamned extends CardImpl {
public TheLostAndTheDamned(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{1}{U}{R}");
// Whenever a land you control enters from anywhere other than your hand or you cast a spell from anywhere other than your hand, create 3/3 red Spawn creature token.
this.addAbility(new TheLostAndTheDamnedTriggeredAbility());
}
private TheLostAndTheDamned(final TheLostAndTheDamned card) {
super(card);
}
@Override
public TheLostAndTheDamned copy() {
return new TheLostAndTheDamned(this);
}
}
class TheLostAndTheDamnedTriggeredAbility extends TriggeredAbilityImpl {
TheLostAndTheDamnedTriggeredAbility() {
super(Zone.BATTLEFIELD, new CreateTokenEffect(new SpawnToken()));
setTriggerPhrase("Whenever a land you control enters from anywhere other than your hand or you cast a spell from anywhere other than your hand, ");
}
private TheLostAndTheDamnedTriggeredAbility(final TheLostAndTheDamnedTriggeredAbility ability) {
super(ability);
}
@Override
public TheLostAndTheDamnedTriggeredAbility copy() {
return new TheLostAndTheDamnedTriggeredAbility(this);
}
@Override
public boolean checkEventType(GameEvent event, Game game) {
return event.getType() == GameEvent.EventType.ENTERS_THE_BATTLEFIELD
|| event.getType() == GameEvent.EventType.SPELL_CAST;
}
@Override
public boolean checkTrigger(GameEvent event, Game game) {
if (!this.isControlledBy(event.getPlayerId())) {
return false;
}
switch (event.getType()) {
case ENTERS_THE_BATTLEFIELD:
EntersTheBattlefieldEvent eEvent = (EntersTheBattlefieldEvent) event;
return (!eEvent.getFromZone().match(Zone.HAND) || !(eEvent.getTarget().isOwnedBy(this.controllerId))) // if it's someone else's land, you can't have played it from your hand. This handles playing lands from opponent's hands.
&& eEvent.getTarget().isLand(game);
case SPELL_CAST:
return (!Optional
.ofNullable(game.getSpell(event.getTargetId()))
.map(Spell::getFromZone)
.orElse(Zone.ALL)
.equals(Zone.HAND) || !Optional
.ofNullable(game.getSpell(event.getTargetId()))
.map(Spell::getOwnerId)
.orElse(this.controllerId)
.equals(this.controllerId)); // if it's someone else's spell, it can't have been in your hand. This handles playing spells from opponent's hands.
}
return false;
}
}
| 412 | 0.964684 | 1 | 0.964684 | game-dev | MEDIA | 0.794471 | game-dev | 0.975035 | 1 | 0.975035 |
fallahn/crogine | 2,594 | extlibs/bullet/include/BulletCollision/BroadphaseCollision/btAxisSweep3.h | //Bullet Continuous Collision Detection and Physics Library
//Copyright (c) 2003-2006 Erwin Coumans https://bulletphysics.org
//
// btAxisSweep3.h
//
// Copyright (c) 2006 Simon Hobbs
//
// This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
#ifndef BT_AXIS_SWEEP_3_H
#define BT_AXIS_SWEEP_3_H
#include "LinearMath/btVector3.h"
#include "btOverlappingPairCache.h"
#include "btBroadphaseInterface.h"
#include "btBroadphaseProxy.h"
#include "btOverlappingPairCallback.h"
#include "btDbvtBroadphase.h"
#include "btAxisSweep3Internal.h"
/// The btAxisSweep3 is an efficient implementation of the 3d axis sweep and prune broadphase.
/// It uses arrays rather then lists for storage of the 3 axis. Also it operates using 16 bit integer coordinates instead of floats.
/// For large worlds and many objects, use bt32BitAxisSweep3 or btDbvtBroadphase instead. bt32BitAxisSweep3 has higher precision and allows more then 16384 objects at the cost of more memory and bit of performance.
class btAxisSweep3 : public btAxisSweep3Internal<unsigned short int>
{
public:
btAxisSweep3(const btVector3& worldAabbMin, const btVector3& worldAabbMax, unsigned short int maxHandles = 16384, btOverlappingPairCache* pairCache = 0, bool disableRaycastAccelerator = false);
};
/// The bt32BitAxisSweep3 allows higher precision quantization and more objects compared to the btAxisSweep3 sweep and prune.
/// This comes at the cost of more memory per handle, and a bit slower performance.
/// It uses arrays rather then lists for storage of the 3 axis.
class bt32BitAxisSweep3 : public btAxisSweep3Internal<unsigned int>
{
public:
bt32BitAxisSweep3(const btVector3& worldAabbMin, const btVector3& worldAabbMax, unsigned int maxHandles = 1500000, btOverlappingPairCache* pairCache = 0, bool disableRaycastAccelerator = false);
};
#endif
| 412 | 0.778465 | 1 | 0.778465 | game-dev | MEDIA | 0.94919 | game-dev | 0.807741 | 1 | 0.807741 |
glKarin/com.n0n3m4.diii4a | 2,257 | Q3E/src/main/jni/jk/codemp/cgame/fx_bowcaster.c | /*
===========================================================================
Copyright (C) 2000 - 2013, Raven Software, Inc.
Copyright (C) 2001 - 2013, Activision, Inc.
Copyright (C) 2013 - 2015, OpenJK contributors
This file is part of the OpenJK source code.
OpenJK is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <http://www.gnu.org/licenses/>.
===========================================================================
*/
// Bowcaster Weapon
#include "cg_local.h"
/*
---------------------------
FX_BowcasterProjectileThink
---------------------------
*/
void FX_BowcasterProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon )
{
vec3_t forward;
if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f )
{
forward[2] = 1.0f;
}
trap->FX_PlayEffectID( cgs.effects.bowcasterShotEffect, cent->lerpOrigin, forward, -1, -1, qfalse );
}
/*
---------------------------
FX_BowcasterHitWall
---------------------------
*/
void FX_BowcasterHitWall( vec3_t origin, vec3_t normal )
{
trap->FX_PlayEffectID( cgs.effects.bowcasterImpactEffect, origin, normal, -1, -1, qfalse );
}
/*
---------------------------
FX_BowcasterHitPlayer
---------------------------
*/
void FX_BowcasterHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid )
{
trap->FX_PlayEffectID( cgs.effects.bowcasterImpactEffect, origin, normal, -1, -1, qfalse );
}
/*
------------------------------
FX_BowcasterAltProjectileThink
------------------------------
*/
void FX_BowcasterAltProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon )
{
vec3_t forward;
if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f )
{
forward[2] = 1.0f;
}
trap->FX_PlayEffectID( cgs.effects.bowcasterShotEffect, cent->lerpOrigin, forward, -1, -1, qfalse );
}
| 412 | 0.86405 | 1 | 0.86405 | game-dev | MEDIA | 0.778143 | game-dev | 0.566392 | 1 | 0.566392 |
bazaarvoice/emodb | 2,666 | sor-api/src/main/java/com/bazaarvoice/emodb/sor/delta/impl/SetDeltaBuilderImpl.java | package com.bazaarvoice.emodb.sor.delta.impl;
import com.bazaarvoice.emodb.sor.delta.Delta;
import com.bazaarvoice.emodb.sor.delta.Deltas;
import com.bazaarvoice.emodb.sor.delta.Literal;
import com.bazaarvoice.emodb.sor.delta.SetDeltaBuilder;
import com.google.common.collect.Sets;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.Set;
import static com.google.common.base.Preconditions.checkArgument;
public class SetDeltaBuilderImpl implements SetDeltaBuilder {
private boolean _removeRest;
private final Set<Literal> _addedValues = Sets.newHashSet();
private final Set<Literal> _removedValues = Sets.newHashSet();
private boolean _deleteIfEmpty;
@Override
public SetDeltaBuilder remove(@Nullable Object value) {
Literal literal = value instanceof Literal ? (Literal) value : Deltas.literal(value);
checkArgument(!_addedValues.contains(literal) && _removedValues.add(literal),
"Multiple operations against the same value are not allowed: %s", value);
return this;
}
@Override
public SetDeltaBuilder removeAll(Object... values) {
return removeAll(Arrays.asList(values));
}
@Override
public SetDeltaBuilder removeAll(Iterable<Object> values) {
for (Object value : values) {
remove(value);
}
return this;
}
@Override
public SetDeltaBuilder add(@Nullable Object value) {
Literal literal = value instanceof Literal ? (Literal) value : Deltas.literal(value);
checkArgument(!_removedValues.contains(literal) && _addedValues.add(literal),
"Multiple operations against the same value are not allowed: %s", value);
return this;
}
@Override
public SetDeltaBuilder addAll(Object... values) {
return addAll(Arrays.asList(values));
}
@Override
public SetDeltaBuilder addAll(Iterable<Object> values) {
for (Object value : values) {
add(value);
}
return this;
}
@Override
public SetDeltaBuilder deleteIfEmpty() {
return deleteIfEmpty(true);
}
@Override
public SetDeltaBuilder deleteIfEmpty(boolean deleteIfEmpty) {
_deleteIfEmpty = deleteIfEmpty;
return this;
}
@Override
public SetDeltaBuilder removeRest() {
return removeRest(true);
}
@Override
public SetDeltaBuilder removeRest(boolean removeRest) {
_removeRest = removeRest;
return this;
}
@Override
public Delta build() {
return new SetDeltaImpl(_removeRest, _addedValues, _removedValues, _deleteIfEmpty);
}
}
| 412 | 0.750869 | 1 | 0.750869 | game-dev | MEDIA | 0.417765 | game-dev | 0.579041 | 1 | 0.579041 |
scala/compiler-benchmark | 3,321 | corpus/scala/21d12e9/library/scala/Product13.scala | /* __ *\
** ________ ___ / / ___ Scala API **
** / __/ __// _ | / / / _ | (c) 2002-2013, LAMP/EPFL **
** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ **
** /____/\___/_/ |_/____/_/ | | **
** |/ **
\* */
// GENERATED CODE: DO NOT EDIT. See scala.Function0 for timestamp.
package scala
object Product13 {
def unapply[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13](x: Product13[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13]): Option[Product13[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13]] =
Some(x)
}
/** Product13 is a Cartesian product of 13 components.
* @since 2.3
*/
trait Product13[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13] extends Any with Product {
/** The arity of this product.
* @return 13
*/
override def productArity = 13
/** Returns the n-th projection of this product if 0 <= n < productArity,
* otherwise throws an `IndexOutOfBoundsException`.
*
* @param n number of the projection to be returned
* @return same as `._(n+1)`, for example `productElement(0)` is the same as `._1`.
* @throws IndexOutOfBoundsException
*/
@throws(classOf[IndexOutOfBoundsException])
override def productElement(n: Int) = n match {
case 0 => _1
case 1 => _2
case 2 => _3
case 3 => _4
case 4 => _5
case 5 => _6
case 6 => _7
case 7 => _8
case 8 => _9
case 9 => _10
case 10 => _11
case 11 => _12
case 12 => _13
case _ => throw new IndexOutOfBoundsException(n.toString())
}
/** A projection of element 1 of this Product.
* @return A projection of element 1.
*/
def _1: T1
/** A projection of element 2 of this Product.
* @return A projection of element 2.
*/
def _2: T2
/** A projection of element 3 of this Product.
* @return A projection of element 3.
*/
def _3: T3
/** A projection of element 4 of this Product.
* @return A projection of element 4.
*/
def _4: T4
/** A projection of element 5 of this Product.
* @return A projection of element 5.
*/
def _5: T5
/** A projection of element 6 of this Product.
* @return A projection of element 6.
*/
def _6: T6
/** A projection of element 7 of this Product.
* @return A projection of element 7.
*/
def _7: T7
/** A projection of element 8 of this Product.
* @return A projection of element 8.
*/
def _8: T8
/** A projection of element 9 of this Product.
* @return A projection of element 9.
*/
def _9: T9
/** A projection of element 10 of this Product.
* @return A projection of element 10.
*/
def _10: T10
/** A projection of element 11 of this Product.
* @return A projection of element 11.
*/
def _11: T11
/** A projection of element 12 of this Product.
* @return A projection of element 12.
*/
def _12: T12
/** A projection of element 13 of this Product.
* @return A projection of element 13.
*/
def _13: T13
}
| 412 | 0.531718 | 1 | 0.531718 | game-dev | MEDIA | 0.175438 | game-dev | 0.553636 | 1 | 0.553636 |
skooter500/GE1-2024 | 2,257 | games-engines-2024/player.gd | extends CharacterBody3D
const SPEED = 5.0
const JUMP_VELOCITY = 10
var controlling = true
@export var rot_speed = 180
var relative:Vector2 = Vector2.ZERO
func print_stuff():
DebugDraw2D.set_text("position", position)
DebugDraw2D.set_text("global_position", position)
DebugDraw2D.set_text("rotation", rotation)
DebugDraw2D.set_text("global_rotation", global_rotation)
DebugDraw2D.set_text("basis.x", transform.basis.x)
DebugDraw2D.set_text("basis.y", transform.basis.y)
DebugDraw2D.set_text("basis.z", transform.basis.z)
DebugDraw2D.set_text("global basis.x", global_transform.basis.x)
DebugDraw2D.set_text("global basis.y", global_transform.basis.y)
DebugDraw2D.set_text("global basis.z", global_transform.basis.z)
func _input(event):
if event is InputEventMouseMotion and controlling:
relative = event.relative
if event.is_action_pressed("ui_cancel"):
if controlling:
Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE)
else:
Input.set_mouse_mode(Input.MOUSE_MODE_HIDDEN)
Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
controlling = ! controlling
# Called when the node enters the scene tree for the first time.
func _ready():
Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
pass # Replace with function body.
func _physics_process(delta: float) -> void:
print_stuff()
var v1 = global_transform.basis.z
var v2 = v1
v2.y = 0
v2 = v2.normalized()
var d = v1.dot(v2)
var f = acos(d)
DebugDraw2D.set_text("DOT: ", d)
DebugDraw2D.set_text("f: ", rad_to_deg(f))
rotate(Vector3.DOWN, deg_to_rad(relative.x * deg_to_rad(rot_speed) * delta))
if d > 0.5:
rotate(transform.basis.x,deg_to_rad(relative.y * deg_to_rad(rot_speed) * delta))
relative = Vector2.ZERO
# Add the gravity.
if not is_on_floor():
velocity += get_gravity() * delta
# Handle jump.
if Input.is_action_just_pressed("ui_accept") and is_on_floor():
velocity.y = JUMP_VELOCITY
# walk
var w = Input.get_axis("move_back", "move_forward")
if w:
var dir = global_transform.basis.z
dir.y = 0
dir = dir.normalized()
velocity += w * dir
# strafe
var s = Input.get_axis("turn_left", "turn_right")
if s:
velocity -= s * global_transform.basis.x * SPEED
# damping
velocity *= 0.9
move_and_slide()
| 412 | 0.778634 | 1 | 0.778634 | game-dev | MEDIA | 0.832702 | game-dev | 0.841676 | 1 | 0.841676 |
DarkStorm652/DarkBot | 1,584 | src/main/java/org/darkstorm/darkbot/mcwrapper/commands/PlayersCommand.java | package org.darkstorm.darkbot.mcwrapper.commands;
import java.util.*;
import org.darkstorm.darkbot.mcwrapper.MinecraftBotWrapper;
import org.darkstorm.darkbot.minecraftbot.event.*;
import org.darkstorm.darkbot.minecraftbot.event.EventListener;
import org.darkstorm.darkbot.minecraftbot.event.protocol.server.*;
public class PlayersCommand extends AbstractCommand implements EventListener {
private final List<String> users = new ArrayList<>();
public PlayersCommand(MinecraftBotWrapper bot) {
super(bot, "players", "List all players on the server");
}
@Override
public void execute(String[] args) {
String players;
synchronized(users) {
players = users.toString();
}
players = players.substring(1, players.length() - 1);
List<String> lines = new ArrayList<String>();
String[] parts = players.split(", ");
String current = "";
for(int i = 0; i < parts.length; i++) {
if(current.length() + parts[i].length() + 2 >= 100) {
lines.add(current);
current = parts[i] + ", ";
} else
current += parts[i] + ", ";
}
if(!current.isEmpty()) {
current = current.substring(0, current.length() - 2);
lines.add(current);
}
bot.say("Players:");
for(String line : lines)
bot.say(line);
}
@EventHandler
public void onPlayerListUpdate(PlayerListUpdateEvent event) {
synchronized(users) {
if(!users.contains(event.getPlayerName()))
users.add(event.getPlayerName());
}
}
@EventHandler
public void onPlayerListRemove(PlayerListRemoveEvent event) {
synchronized(users) {
users.remove(event.getPlayerName());
}
}
}
| 412 | 0.890691 | 1 | 0.890691 | game-dev | MEDIA | 0.916965 | game-dev | 0.963392 | 1 | 0.963392 |
DylanRJohnston/simon_says | 2,513 | game/src/ui/main_menu.rs | use bevy::prelude::*;
use crate::delayed_command::{DelayedCommand, DelayedCommandExt};
use super::*;
pub struct MainMenuPlugin;
impl Plugin for MainMenuPlugin {
fn build(&self, app: &mut App) {
app.add_systems(OnExit(GameState::Loading), setup)
.add_observer(start_game)
.add_observer(remove_ui)
.add_observer(spawn_main_menu)
.add_observer(refuse)
.add_systems(OnExit(GameState::MainMenu), destroy);
}
}
#[derive(Component)]
pub struct MainMenuRoot;
#[derive(Debug, Event)]
pub struct StartGame;
fn setup(mut commands: Commands) {
commands.trigger(SpawnMainMenu);
}
#[derive(Debug, Event)]
struct SpawnMainMenu;
fn spawn_main_menu(_trigger: Trigger<SpawnMainMenu>, mut commands: Commands) {
commands.delayed(0.5, |commands| {
commands.spawn((
Name::new("Main Menu Root"),
MainMenuRoot,
Node {
height: Val::Percent(100.0),
width: Val::Percent(100.0),
justify_content: JustifyContent::Center,
column_gap: Val::Px(UI_CONTAINER_GAP),
align_items: AlignItems::Center,
..default()
},
children![
button::Button::builder()
.text("Begin Cycle No. 4,815,162,342".into())
.on_click(|commands| commands.trigger(StartGame))
.build(),
button::Button::builder()
.text("Disobey".into())
.background_color(BUTTON_CANCEL_COLOR)
.on_click(|commands| {
commands.trigger(RemoveUI);
commands.trigger(Refuse);
})
.build()
],
));
});
}
fn destroy(mut commands: Commands) {
commands.trigger(RemoveUI);
}
#[derive(Debug, Event)]
pub struct RemoveUI;
#[derive(Debug, Event)]
pub struct Refuse;
fn refuse(_trigger: Trigger<Refuse>, mut commands: Commands) {
commands.spawn(DelayedCommand::new(35., |commands| {
commands.trigger(SpawnMainMenu);
}));
}
fn remove_ui(
_trigger: Trigger<RemoveUI>,
mut commands: Commands,
query: Query<Entity, With<MainMenuRoot>>,
) {
for entity in query.iter() {
commands.entity(entity).despawn();
}
}
fn start_game(_trigger: Trigger<StartGame>, mut next_state: ResMut<NextState<GameState>>) {
next_state.set(GameState::InGame);
}
| 412 | 0.881402 | 1 | 0.881402 | game-dev | MEDIA | 0.963088 | game-dev | 0.824057 | 1 | 0.824057 |
The-Final-Nights/The-Final-Nights | 3,873 | code/modules/events/stray_cargo.dm | ///Spawns a cargo pod containing a random cargo supply pack on a random area of the station
/datum/round_event_control/stray_cargo
name = "Stray Cargo Pod"
typepath = /datum/round_event/stray_cargo
weight = 20
max_occurrences = 4
earliest_start = 10 MINUTES
///Spawns a cargo pod containing a random cargo supply pack on a random area of the station
/datum/round_event/stray_cargo
var/area/impact_area ///Randomly picked area
announceChance = 75
var/list/possible_pack_types = list() ///List of possible supply packs dropped in the pod, if empty picks from the cargo list
var/static/list/stray_spawnable_supply_packs = list() ///List of default spawnable supply packs, filtered from the cargo list
/datum/round_event/stray_cargo/announce(fake)
priority_announce("Stray cargo pod detected on long-range scanners. Expected location of impact: [impact_area.name].", "Collision Alert")
/**
* Tries to find a valid area, throws an error if none are found
* Also randomizes the start timer
*/
/datum/round_event/stray_cargo/setup()
startWhen = rand(20, 40)
impact_area = find_event_area()
if(!impact_area)
CRASH("No valid areas for cargo pod found.")
var/list/turf_test = get_area_turfs(impact_area)
if(!turf_test.len)
CRASH("Stray Cargo Pod : No valid turfs found for [impact_area] - [impact_area.type]")
if(!stray_spawnable_supply_packs.len)
stray_spawnable_supply_packs = SSshuttle.supply_packs.Copy()
for(var/pack in stray_spawnable_supply_packs)
var/datum/supply_pack/pack_type = pack
if(initial(pack_type.special))
stray_spawnable_supply_packs -= pack
///Spawns a random supply pack, puts it in a pod, and spawns it on a random tile of the selected area
/datum/round_event/stray_cargo/start()
var/list/turf/valid_turfs = get_area_turfs(impact_area)
//Only target non-dense turfs to prevent wall-embedded pods
for(var/i in valid_turfs)
var/turf/T = i
if(T.density)
valid_turfs -= T
var/turf/LZ = pick(valid_turfs)
var/pack_type
if(possible_pack_types.len)
pack_type = pick(possible_pack_types)
else
pack_type = pick(stray_spawnable_supply_packs)
var/datum/supply_pack/SP = new pack_type
var/obj/structure/closet/crate/crate = SP.generate(null)
crate.locked = FALSE //Unlock secure crates
crate.update_appearance()
var/obj/structure/closet/supplypod/pod = make_pod()
new /obj/effect/pod_landingzone(LZ, pod, crate)
///Handles the creation of the pod, in case it needs to be modified beforehand
/datum/round_event/stray_cargo/proc/make_pod()
var/obj/structure/closet/supplypod/S = new
return S
///Picks an area that wouldn't risk critical damage if hit by a pod explosion
/datum/round_event/stray_cargo/proc/find_event_area()
var/static/list/allowed_areas
if(!allowed_areas)
///Places that shouldn't explode
var/list/safe_area_types = typecacheof(list(
/area/ai_monitored/turret_protected/ai,
/area/ai_monitored/turret_protected/ai_upload,
/area/engine,
/area/shuttle)
)
///Subtypes from the above that actually should explode.
var/list/unsafe_area_subtypes = typecacheof(list(/area/engine/break_room))
allowed_areas = make_associative(GLOB.the_station_areas) - safe_area_types + unsafe_area_subtypes
var/list/possible_areas = typecache_filter_list(GLOB.sortedAreas,allowed_areas)
if (length(possible_areas))
return pick(possible_areas)
///A rare variant that drops a crate containing syndicate uplink items
/datum/round_event_control/stray_cargo/syndicate
name = "Stray Syndicate Cargo Pod"
typepath = /datum/round_event/stray_cargo/syndicate
weight = 6
max_occurrences = 1
earliest_start = 30 MINUTES
/datum/round_event/stray_cargo/syndicate
possible_pack_types = list(/datum/supply_pack/misc/syndicate)
///Apply the syndicate pod skin
/datum/round_event/stray_cargo/syndicate/make_pod()
var/obj/structure/closet/supplypod/S = new
S.setStyle(STYLE_SYNDICATE)
return S
| 412 | 0.814511 | 1 | 0.814511 | game-dev | MEDIA | 0.980805 | game-dev | 0.959991 | 1 | 0.959991 |
dboglobal/DBOGLOBAL | 19,369 | NtlLib/Shared/NtlNavi/Source/NtlNaviWEWorld.cpp | #include "precomp_navi.h"
#include "NtlNaviWEWorld.h"
#include "NtlNaviLog.h"
CNtlNaviWEWorld::CNtlNaviWEWorld( CNtlNaviResMng* pNaviResMng )
{
m_pNaviResMng = pNaviResMng;
m_pNaviDataMng = new CNtlNaviDataMng;
}
CNtlNaviWEWorld::~CNtlNaviWEWorld( void )
{
Destroy();
if ( m_pNaviDataMng )
{
delete m_pNaviDataMng;
m_pNaviDataMng = NULL;
}
}
bool CNtlNaviWEWorld::ImportWEData( const char* pPath )
{
Destroy();
// Navigation data manager
if ( !m_pNaviDataMng->Create( pPath ) )
{
CNtlNaviLog::GetInstance()->Log( "[IMPORT] Creating the navi data manager failed. [%s]", pPath );
return false;
}
// Navigation world info ε
if ( NULL == m_pNaviDataMng->Load_World() )
{
CNtlNaviLog::GetInstance()->Log( "[IMPORT] Can not import world info data. [%s]", pPath );
return false;
}
return true;
}
bool CNtlNaviWEWorld::ExportPEData( const char* pPath )
{
CreateDirectory( pPath, NULL );
switch ( m_pNaviDataMng->GetLoadedWorld()->GetType() )
{
case eNAVI_INFO_WORLD_OUTDOOR:
{
// Export world info
if ( !ExportODWorldInfo( pPath ) )
{
return false;
}
// Export outdoor property
if ( !ExportODWorldProperty( pPath ) )
{
return false;
}
// Export outdoor world
if ( !ExportODWorldGroup( pPath ) )
{
return false;
}
return true;
}
break;
case eNAVI_INFO_WORLD_INDOOR:
{
// Export world info
if ( !ExportIDWorldInfo( pPath ) )
{
return false;
}
// Export indoor property
if ( !ExportIDWorldProperty( pPath ) )
{
return false;
}
// Export indoor world
if ( !ExportIDWorld( pPath ) )
{
return false;
}
return true;
}
break;
}
return false;
}
bool CNtlNaviWEWorld::ExportPEData( const char* pPath, vecdef_GroupIDList& list )
{
CreateDirectory( pPath, NULL );
switch ( m_pNaviDataMng->GetLoadedWorld()->GetType() )
{
case eNAVI_INFO_WORLD_OUTDOOR:
{
// Export world info
if ( !ExportODWorldInfo( pPath ) )
{
return false;
}
// Export outdoor property
if ( !ExportODWorldProperty( pPath, list ) )
{
return false;
}
// Export outdoor world
if ( !ExportODWorldGroup( pPath, list ) )
{
return false;
}
return true;
}
break;
case eNAVI_INFO_WORLD_INDOOR:
{
// Export world info
if ( !ExportIDWorldInfo( pPath ) )
{
return false;
}
// Export indoor property
if ( !ExportIDWorldProperty( pPath ) )
{
return false;
}
// Export indoor world
if ( !ExportIDWorld( pPath ) )
{
return false;
}
return true;
}
break;
}
return false;
}
bool CNtlNaviWEWorld::UpdateToolData( void )
{
vecdef_ODGROUP_EXPORTER_LIST::iterator itOD = m_defODGroupExporterList.begin();
for ( ; itOD != m_defODGroupExporterList.end(); )
{
CNtlNaviODGroupExporter* pExpoter = *itOD;
if ( pExpoter->Update() )
{
if ( pExpoter->GetCurState() == CNtlNaviODGroupExporter::eEXPORT_STATE_COMPLTE )
{
delete pExpoter;
itOD = m_defODGroupExporterList.erase( itOD );
}
else
{
++itOD;
}
}
else
{
delete pExpoter;
itOD = m_defODGroupExporterList.erase( itOD );
}
}
vecdef_IDGROUP_EXPORTER_LIST::iterator itID = m_defIDGroupExporterList.begin();
for ( ; itID != m_defIDGroupExporterList.end(); )
{
CNtlNaviIDGroupExporter* pExpoter = *itID;
if ( pExpoter->Update() )
{
if ( pExpoter->GetCurState() == CNtlNaviIDGroupExporter::eEXPORT_STATE_COMPLTE )
{
delete pExpoter;
itID = m_defIDGroupExporterList.erase( itID );
}
else
{
++itID;
}
}
else
{
delete pExpoter;
itID = m_defIDGroupExporterList.erase( itID );
}
}
return true;
}
unsigned int CNtlNaviWEWorld::GetWorldID( void )
{
if ( NULL == m_pNaviDataMng )
{
return 0xffffffff;
}
CNtlNaviWorldInfo* pWorldInfo = m_pNaviDataMng->GetLoadedWorld();
if ( NULL == pWorldInfo )
{
return 0xffffffff;
}
return pWorldInfo->GetWorldID();
}
void CNtlNaviWEWorld::Destroy( void )
{
ClearIDGroupExporter();
ClearODGroupExporter();
if ( m_pNaviDataMng )
{
m_pNaviDataMng->Delete();
}
}
bool CNtlNaviWEWorld::ExportODWorldInfo( const char* pExportPath )
{
CNtlNaviWorldOutDoorInfo* pWorldOD = (CNtlNaviWorldOutDoorInfo*)m_pNaviDataMng->GetLoadedWorld();
if ( NULL == pWorldOD )
{
CNtlNaviLog::GetInstance()->Log( "[EXPORT] Exporting the world info failed. [%s]", pExportPath );
return false;
}
if ( !pWorldOD->Export( pExportPath ) )
{
CNtlNaviLog::GetInstance()->Log( "[EXPORT] Exporting the world info failed. [%s]", pExportPath );
return false;
}
return true;
}
bool CNtlNaviWEWorld::ExportIDWorldInfo( const char* pExportPath )
{
CNtlNaviWorldInDoorInfo* pWorldID = (CNtlNaviWorldInDoorInfo*)m_pNaviDataMng->GetLoadedWorld();
if ( NULL == pWorldID )
{
CNtlNaviLog::GetInstance()->Log( "[EXPORT] Exporting the world info failed. [%s]", pExportPath );
return false;
}
if ( !pWorldID->Export( pExportPath ) )
{
CNtlNaviLog::GetInstance()->Log( "[EXPORT] Exporting the world info failed. [%s]", pExportPath );
return false;
}
return true;
}
bool CNtlNaviWEWorld::ExportODWorldGroup( const char* pExportPath )
{
// Build export path
std::string strExportPath = pExportPath;
AttachBackSlash( strExportPath );
strExportPath += PE_PATHENGINE_FOLDER;
// Create export path directory
::CreateDirectory( strExportPath.c_str(), NULL );
// Export world group
CNtlNaviWorldOutDoorInfo* pWorldOD = (CNtlNaviWorldOutDoorInfo*)m_pNaviDataMng->GetLoadedWorld();
CNtlNaviODGroupExporter::sINPUT_PARAM sInputParam;
sInputParam.strWorldName = pWorldOD->GetWorldName();
int nAgencyCnt = pWorldOD->GetAgencyCnt();
for ( int i = 0; i < nAgencyCnt; ++i )
{
sInputParam.vecdef_AgentList.push_back( pWorldOD->GetAgency( i ) );
}
pWorldOD->GetWorldMinPos( sInputParam.fMinWorldPosX, sInputParam.fMinWorldPosZ );
pWorldOD->GetWorldMaxPos( sInputParam.fMaxWorldPosX, sInputParam.fMaxWorldPosZ );
sInputParam.fFieldSize = pWorldOD->GetFieldSize();
sInputParam.fTileSize = pWorldOD->GetTileSize();
sInputParam.uiCrossFieldCntOfGroup = pWorldOD->GetCrossFieldCntOfGroup();
sInputParam.uiCrossFieldCntOfWorld = (unsigned int)((sInputParam.fMaxWorldPosX - sInputParam.fMinWorldPosX) / sInputParam.fFieldSize);
sInputParam.uiCrossGroupCntOfWorld = sInputParam.uiCrossFieldCntOfWorld / sInputParam.uiCrossFieldCntOfGroup;
sInputParam.uiCrossSectorCntOfField = (unsigned int)sqrt( (float)CNtlNaviGroupOutDoorInfo::eSECTOR_MAX );
sInputParam.fOverlapSize = pWorldOD->GetOverlapSize();
float fCrossGroupSize = sInputParam.uiCrossFieldCntOfGroup * sInputParam.fFieldSize;
for ( unsigned int z = 0; z < sInputParam.uiCrossGroupCntOfWorld; ++z )
{
for ( unsigned int x = 0; x < sInputParam.uiCrossGroupCntOfWorld; ++x )
{
sInputParam.fMinGroupPosX = sInputParam.fMinWorldPosX + x * fCrossGroupSize - sInputParam.fOverlapSize;
sInputParam.fMinGroupPosX = sInputParam.fMinGroupPosX < sInputParam.fMinWorldPosX ? sInputParam.fMinWorldPosX : sInputParam.fMinGroupPosX;
sInputParam.fMaxGroupPosX = sInputParam.fMinWorldPosX + (x+1) * fCrossGroupSize + sInputParam.fOverlapSize;
sInputParam.fMaxGroupPosX = sInputParam.fMaxGroupPosX > sInputParam.fMaxWorldPosX ? sInputParam.fMaxWorldPosX : sInputParam.fMaxGroupPosX;
sInputParam.fMinGroupPosZ = sInputParam.fMinWorldPosZ + z * fCrossGroupSize - sInputParam.fOverlapSize;
sInputParam.fMinGroupPosZ = sInputParam.fMinGroupPosZ < sInputParam.fMinWorldPosZ ? sInputParam.fMinWorldPosZ : sInputParam.fMinGroupPosZ;
sInputParam.fMaxGroupPosZ = sInputParam.fMinWorldPosZ + (z+1) * fCrossGroupSize + sInputParam.fOverlapSize;
sInputParam.fMaxGroupPosZ = sInputParam.fMaxGroupPosZ > sInputParam.fMaxWorldPosZ ? sInputParam.fMaxWorldPosZ : sInputParam.fMaxGroupPosZ;
sInputParam.uiMinXGroupID = (unsigned int)((sInputParam.fMinGroupPosX - sInputParam.fMinWorldPosX) / fCrossGroupSize);
sInputParam.uiMaxXGroupID = (unsigned int)((sInputParam.fMaxGroupPosX - sInputParam.fMinWorldPosX - 0.5f) / fCrossGroupSize);
sInputParam.uiMinZGroupID = (unsigned int)((sInputParam.fMinGroupPosZ - sInputParam.fMinWorldPosZ) / fCrossGroupSize);
sInputParam.uiMaxZGroupID = (unsigned int)((sInputParam.fMaxGroupPosZ - sInputParam.fMinWorldPosZ - 0.5f) / fCrossGroupSize);
sInputParam.uiGroupID = x + z * sInputParam.uiCrossGroupCntOfWorld;
sInputParam.uiCrossVertexCntOfGroup = (unsigned int)((sInputParam.fMaxGroupPosX - sInputParam.fMinGroupPosX) / sInputParam.fTileSize + 1);
sInputParam.uiVerticalVertexCntOfGroup = (unsigned int)((sInputParam.fMaxGroupPosZ - sInputParam.fMinGroupPosZ) / sInputParam.fTileSize + 1);
AttachODGroupExporter( strExportPath.c_str(), m_pNaviResMng, m_pNaviDataMng, sInputParam );
}
}
return true;
}
bool CNtlNaviWEWorld::ExportODWorldGroup( const char* pExportPath, vecdef_GroupIDList& list )
{
// Build export path
std::string strExportPath = pExportPath;
AttachBackSlash( strExportPath );
strExportPath += PE_PATHENGINE_FOLDER;
// Create export path directory
::CreateDirectory( strExportPath.c_str(), NULL );
// Export world group
CNtlNaviWorldOutDoorInfo* pWorldOD = (CNtlNaviWorldOutDoorInfo*)m_pNaviDataMng->GetLoadedWorld();
CNtlNaviODGroupExporter::sINPUT_PARAM sInputParam;
sInputParam.strWorldName = pWorldOD->GetWorldName();
CNtlNaviLog::GetInstance()->Log("Export world: [%s]", sInputParam.strWorldName.c_str());
int nAgencyCnt = pWorldOD->GetAgencyCnt();
for ( int i = 0; i < nAgencyCnt; ++i )
{
sInputParam.vecdef_AgentList.push_back( pWorldOD->GetAgency( i ) );
}
pWorldOD->GetWorldMinPos( sInputParam.fMinWorldPosX, sInputParam.fMinWorldPosZ );
pWorldOD->GetWorldMaxPos( sInputParam.fMaxWorldPosX, sInputParam.fMaxWorldPosZ );
sInputParam.fFieldSize = pWorldOD->GetFieldSize();
sInputParam.fTileSize = pWorldOD->GetTileSize();
sInputParam.uiCrossFieldCntOfGroup = pWorldOD->GetCrossFieldCntOfGroup();
sInputParam.uiCrossFieldCntOfWorld = (unsigned int)((sInputParam.fMaxWorldPosX - sInputParam.fMinWorldPosX) / sInputParam.fFieldSize);
sInputParam.uiCrossGroupCntOfWorld = sInputParam.uiCrossFieldCntOfWorld / sInputParam.uiCrossFieldCntOfGroup;
sInputParam.uiCrossSectorCntOfField = (unsigned int)sqrt( (float)CNtlNaviGroupOutDoorInfo::eSECTOR_MAX );
sInputParam.fOverlapSize = pWorldOD->GetOverlapSize();
float fCrossGroupSize = sInputParam.uiCrossFieldCntOfGroup * sInputParam.fFieldSize;
for ( unsigned int z = 0; z < sInputParam.uiCrossGroupCntOfWorld; ++z )
{
for ( unsigned int x = 0; x < sInputParam.uiCrossGroupCntOfWorld; ++x )
{
sInputParam.fMinGroupPosX = sInputParam.fMinWorldPosX + x * fCrossGroupSize - sInputParam.fOverlapSize;
sInputParam.fMinGroupPosX = sInputParam.fMinGroupPosX < sInputParam.fMinWorldPosX ? sInputParam.fMinWorldPosX : sInputParam.fMinGroupPosX;
sInputParam.fMaxGroupPosX = sInputParam.fMinWorldPosX + (x+1) * fCrossGroupSize + sInputParam.fOverlapSize;
sInputParam.fMaxGroupPosX = sInputParam.fMaxGroupPosX > sInputParam.fMaxWorldPosX ? sInputParam.fMaxWorldPosX : sInputParam.fMaxGroupPosX;
sInputParam.fMinGroupPosZ = sInputParam.fMinWorldPosZ + z * fCrossGroupSize - sInputParam.fOverlapSize;
sInputParam.fMinGroupPosZ = sInputParam.fMinGroupPosZ < sInputParam.fMinWorldPosZ ? sInputParam.fMinWorldPosZ : sInputParam.fMinGroupPosZ;
sInputParam.fMaxGroupPosZ = sInputParam.fMinWorldPosZ + (z+1) * fCrossGroupSize + sInputParam.fOverlapSize;
sInputParam.fMaxGroupPosZ = sInputParam.fMaxGroupPosZ > sInputParam.fMaxWorldPosZ ? sInputParam.fMaxWorldPosZ : sInputParam.fMaxGroupPosZ;
sInputParam.uiMinXGroupID = (unsigned int)((sInputParam.fMinGroupPosX - sInputParam.fMinWorldPosX) / fCrossGroupSize);
sInputParam.uiMaxXGroupID = (unsigned int)((sInputParam.fMaxGroupPosX - sInputParam.fMinWorldPosX - 0.5f) / fCrossGroupSize);
sInputParam.uiMinZGroupID = (unsigned int)((sInputParam.fMinGroupPosZ - sInputParam.fMinWorldPosZ) / fCrossGroupSize);
sInputParam.uiMaxZGroupID = (unsigned int)((sInputParam.fMaxGroupPosZ - sInputParam.fMinWorldPosZ - 0.5f) / fCrossGroupSize);
sInputParam.uiGroupID = x + z * sInputParam.uiCrossGroupCntOfWorld;
vecdef_GroupIDList::iterator it = std::find( list.begin(), list.end(), sInputParam.uiGroupID );
if( it == list.end() )
continue;
sInputParam.uiCrossVertexCntOfGroup = (unsigned int)((sInputParam.fMaxGroupPosX - sInputParam.fMinGroupPosX) / sInputParam.fTileSize + 1);
sInputParam.uiVerticalVertexCntOfGroup = (unsigned int)((sInputParam.fMaxGroupPosZ - sInputParam.fMinGroupPosZ) / sInputParam.fTileSize + 1);
AttachODGroupExporter( strExportPath.c_str(), m_pNaviResMng, m_pNaviDataMng, sInputParam );
}
}
return true;
}
bool CNtlNaviWEWorld::ExportODWorldProperty( const char* pExportPath )
{
// Build export path
std::string strExportPath = pExportPath;
AttachBackSlash( strExportPath );
strExportPath += PE_PROPERTY_FOLDER;
// Create export path directory
::CreateDirectory( strExportPath.c_str(), NULL );
// Import world property
CNtlNaviWorldOutDoorInfo* pWorldOD = (CNtlNaviWorldOutDoorInfo*)m_pNaviDataMng->GetLoadedWorld();
float fMinPosX, fMinPosZ, fMaxPosX, fMaxPosZ;
pWorldOD->GetWorldMinPos( fMinPosX, fMinPosZ );
pWorldOD->GetWorldMaxPos( fMaxPosX, fMaxPosZ );
float fFieldSize = pWorldOD->GetFieldSize();
unsigned int uiFieldCntOfWorld = (unsigned int)( (fMaxPosX - fMinPosX) / fFieldSize );
for ( float fZ = fMinPosZ; fZ < fMaxPosZ; fZ += fFieldSize )
{
for ( float fX = fMinPosX; fX < fMaxPosX; fX += fFieldSize )
{
unsigned int uiFieldID = (unsigned int) ( (fX - fMinPosX) / fFieldSize + (fZ - fMinPosZ) / fFieldSize * uiFieldCntOfWorld );
CNtlNaviPropOutDoorInfo* pPropInfo = m_pNaviDataMng->Load_PropOutDoor( uiFieldID );
if ( pPropInfo )
{
if ( !pPropInfo->Export( strExportPath.c_str() ) )
{
CNtlNaviLog::GetInstance()->Log( "Exporting the property failed. [%s]", strExportPath.c_str() );
}
m_pNaviDataMng->Unload_NaviInfo( (CNtlNaviInfo*&) pPropInfo );
}
}
}
return true;
}
bool CNtlNaviWEWorld::ExportODWorldProperty( const char* pExportPath, vecdef_GroupIDList& list )
{
// Build export path
std::string strExportPath = pExportPath;
AttachBackSlash( strExportPath );
strExportPath += PE_PROPERTY_FOLDER;
// Create export path directory
::CreateDirectory( strExportPath.c_str(), NULL );
// Import world property
CNtlNaviWorldOutDoorInfo* pWorldOD = (CNtlNaviWorldOutDoorInfo*)m_pNaviDataMng->GetLoadedWorld();
float fMinPosX, fMinPosZ, fMaxPosX, fMaxPosZ;
pWorldOD->GetWorldMinPos( fMinPosX, fMinPosZ );
pWorldOD->GetWorldMaxPos( fMaxPosX, fMaxPosZ );
float fFieldSize = pWorldOD->GetFieldSize();
unsigned int uiCrossFieldCntOfWorld = (unsigned int)( (fMaxPosX - fMinPosX) / fFieldSize );
for ( float fZ = fMinPosZ; fZ < fMaxPosZ; fZ += fFieldSize )
{
for ( float fX = fMinPosX; fX < fMaxPosX; fX += fFieldSize )
{
unsigned int uiFieldID = (unsigned int) ((unsigned int)((fX - fMinPosX) / fFieldSize) + (unsigned int)((fZ - fMinPosZ) / fFieldSize) * uiCrossFieldCntOfWorld );
// Field ()
unsigned int uiCrossFieldCntOfGroup = pWorldOD->GetCrossFieldCntOfGroup();
// ()
unsigned int uiCrossGroupCntOfWorld = uiCrossFieldCntOfWorld / uiCrossFieldCntOfGroup;
//
float fCrossGroupSize = uiCrossFieldCntOfGroup * fFieldSize;
unsigned int uiGroupID = (unsigned int) ((unsigned int)((fX - fMinPosX) / fCrossGroupSize) + (unsigned int)((fZ - fMinPosZ) / fCrossGroupSize) * uiCrossGroupCntOfWorld );
vecdef_GroupIDList::iterator it = std::find( list.begin(), list.end(), uiGroupID );
if( it == list.end() )
continue;
CNtlNaviPropOutDoorInfo* pPropInfo = m_pNaviDataMng->Load_PropOutDoor( uiFieldID );
if ( pPropInfo )
{
if ( !pPropInfo->Export( strExportPath.c_str() ) )
{
CNtlNaviLog::GetInstance()->Log( "Exporting the property failed. [%s]", strExportPath.c_str() );
}
m_pNaviDataMng->Unload_NaviInfo( (CNtlNaviInfo*&) pPropInfo );
}
}
}
return true;
}
bool CNtlNaviWEWorld::ExportIDWorld( const char* pExportPath )
{
// Build export path
std::string strExportPath = pExportPath;
AttachBackSlash( strExportPath );
strExportPath += PE_PATHENGINE_FOLDER;
// Create export path directory
::CreateDirectory( strExportPath.c_str(), NULL );
// Import world property
CNtlNaviWorldInDoorInfo* pWorldID = (CNtlNaviWorldInDoorInfo*)m_pNaviDataMng->GetLoadedWorld();
CNtlNaviIDGroupExporter::sINPUT_PARAM sInputParam;
int nAgencyCnt = pWorldID->GetAgencyCnt();
for ( int i = 0; i < nAgencyCnt; ++i )
{
sInputParam.vecdef_AgentList.push_back( pWorldID->GetAgency( i ) );
}
AttachIDGroupExporter( strExportPath.c_str(), m_pNaviResMng, m_pNaviDataMng, sInputParam );
return true;
}
bool CNtlNaviWEWorld::ExportIDWorldProperty( const char* pExportPath )
{
// Build export path
std::string strExportPath = pExportPath;
AttachBackSlash( strExportPath );
strExportPath += PE_PROPERTY_FOLDER;
// Create export path directory
::CreateDirectory( strExportPath.c_str(), NULL );
// Import world property
CNtlNaviWorldInDoorInfo* pWorldID = (CNtlNaviWorldInDoorInfo*)m_pNaviDataMng->GetLoadedWorld();
float fMinPosX, fMinPosZ, fMaxPosX, fMaxPosZ;
pWorldID->GetWorldMinPos( fMinPosX, fMinPosZ );
pWorldID->GetWorldMaxPos( fMaxPosX, fMaxPosZ );
float fBlockSize = pWorldID->GetBlockSize();
unsigned int uiBlockCntOfWorld = (unsigned int)( (fMaxPosX - fMinPosX) / fBlockSize );
for ( float fZ = fMinPosZ; fZ < fMaxPosZ; fZ += fBlockSize )
{
for ( float fX = fMinPosX; fX < fMaxPosX; fX += fBlockSize )
{
unsigned int uiBlockID = (unsigned int) ( (fX - fMinPosX) / fBlockSize + (fZ - fMinPosZ) / fBlockSize * uiBlockCntOfWorld );
CNtlNaviPropInDoorInfo* pPropInfo = m_pNaviDataMng->Load_PropInDoor( uiBlockID );
if ( pPropInfo )
{
if ( !pPropInfo->Export( strExportPath.c_str() ) )
{
CNtlNaviLog::GetInstance()->Log( "Exporting the property failed. [%s]", strExportPath.c_str() );
}
m_pNaviDataMng->Unload_NaviInfo( (CNtlNaviInfo*&) pPropInfo );
}
}
}
return true;
}
void CNtlNaviWEWorld::AttachODGroupExporter( const char* pExportPath, CNtlNaviResMng* pNaviResMng, CNtlNaviDataMng* pNaviDataMng, const CNtlNaviODGroupExporter::sINPUT_PARAM& sInputParam )
{
CNtlNaviODGroupExporter* pODGroupExporter = new CNtlNaviODGroupExporter( pExportPath, pNaviResMng, pNaviDataMng, sInputParam );
m_defODGroupExporterList.push_back( pODGroupExporter );
}
void CNtlNaviWEWorld::ClearODGroupExporter( void )
{
vecdef_ODGROUP_EXPORTER_LIST::iterator it = m_defODGroupExporterList.begin();
for ( ; it != m_defODGroupExporterList.end(); ++it )
{
delete *it;
}
m_defODGroupExporterList.clear();
}
void CNtlNaviWEWorld::AttachIDGroupExporter( const char* pExportPath, CNtlNaviResMng* pNaviResMng, CNtlNaviDataMng* pNaviDataMng, const CNtlNaviIDGroupExporter::sINPUT_PARAM& sInputParam )
{
CNtlNaviIDGroupExporter* pIDGroupExporter = new CNtlNaviIDGroupExporter( pExportPath, pNaviResMng, pNaviDataMng, sInputParam );
m_defIDGroupExporterList.push_back( pIDGroupExporter );
}
void CNtlNaviWEWorld::ClearIDGroupExporter( void )
{
vecdef_IDGROUP_EXPORTER_LIST::iterator it = m_defIDGroupExporterList.begin();
for ( ; it != m_defIDGroupExporterList.end(); ++it )
{
delete *it;
}
m_defIDGroupExporterList.clear();
}
| 412 | 0.870082 | 1 | 0.870082 | game-dev | MEDIA | 0.852311 | game-dev | 0.703646 | 1 | 0.703646 |
MetroidAdvRandomizerSystem/mars-fusion-asm | 5,960 | src/nonlinear/new-game-init.s | ; Rewrite new game init to account for starting items and location.
.org NewGameInit
.area 14Ch
push { lr }
sub sp, #4
mov r0, #10h
str r0, [sp]
mov r0, #3
mov r1, #0
ldr r2, =02037C00h
mov r3, #380h >> 2
lsl r3, #2
bl BitFill
mov r0, #10h
str r0, [sp]
mov r0, #3
ldr r1, =#0FFFFh
ldr r2, =02036000h
mov r3, #1200h >> 5
lsl r3, #5
bl BitFill
mov r0, #10h
str r0, [sp]
mov r0, #3
mov r1, #0
ldr r2, =TanksCollected
mov r3, #900h >> 4
lsl r3, #4
bl BitFill
mov r0, #0
mov r1, #7
ldr r2, =03000033h
@@bitfill_loop:
strb r0, [r2, r1]
sub r1, #1
bpl @@bitfill_loop
ldr r1, =GameTimer
strb r0, [r1, GameTimer_Hours]
strb r0, [r1, GameTimer_Minutes]
strb r0, [r1, GameTimer_Seconds]
strb r0, [r1, GameTimer_Frames]
strb r0, [r1, GameTimer_Maxed]
mov r0, #1
ldr r1, =0300134Ah
strb r0, [r1]
ldr r1, =StartingItems
ldr r2, =PermanentUpgrades
ldrb r0, [r1, SamusUpgrades_BeamUpgrades]
strb r0, [r2, PermanentUpgrades_BeamUpgrades]
ldrb r0, [r1, SamusUpgrades_ExplosiveUpgrades]
strb r0, [r2, PermanentUpgrades_ExplosiveUpgrades]
ldrb r0, [r1, SamusUpgrades_SuitUpgrades]
strb r0, [r2, PermanentUpgrades_SuitUpgrades]
mov r0, #0
strb r0, [r2, PermanentUpgrades_InfantMetroids]
ldr r2, =SamusUpgrades
ldrb r0, [r1, SamusUpgrades_SecurityLevel]
strb r0, [r2, SamusUpgrades_SecurityLevel]
ldr r3, =SecurityLevelFlash
strb r0, [r3]
strb r0, [r3, PowerOutageSecurityBackup - SecurityLevelFlash]
mov r0, #0
strb r0, [r2, SamusUpgrades_MapDownloads]
ldr r1, =03000B86h
strb r0, [r1]
mov r0, #0FFh
ldr r1, =PrevSubEvent
strb r0, [r1]
strb r0, [r1, PrevNavConversation - 03000B86h]
mov r0, #0
ldr r1, =0300004Ch
strb r0, [r1]
strb r0, [r1, #1]
.if RANDOMIZER
ldr r1, =StartingLocation
ldr r2, =CurrArea
ldrb r0, [r1, StartingLocation_Area]
strb r0, [r2]
ldrb r0, [r1, StartingLocation_Room]
strb r0, [r2, CurrRoom - CurrArea]
ldrb r0, [r1, StartingLocation_Door]
strb r0, [r2, PrevDoor - CurrArea]
ldr r2, =SamusState
mov r3, r2
add r3, #03001342h - SamusState
ldrh r0, [r1, StartingLocation_XPos]
strh r0, [r2, SamusState_PositionX]
strh r0, [r3]
ldrh r0, [r1, StartingLocation_YPos]
strh r0, [r2, SamusState_PositionY]
strh r0, [r3, #2]
ldrb r0, [r1, StartingLocation_Area]
ldrb r1, [r1, StartingLocation_Room]
orr r0, r1
beq @@init_map
mov r0, #0
ldr r1, =0300134Ah
strb r0, [r1]
.else
mov r0, #0
ldr r1, =CurrArea
strb r0, [r1]
strb r0, [r1, CurrRoom - CurrArea]
strb r0, [r1, PrevDoor - CurrArea]
ldr r1, =SamusState
mov r2, r1
add r2, #03001342h - SamusState
mov r0, #640h >> 3
lsl r0, #3
strh r0, [r1, SamusState_PositionX]
strh r0, [r2]
mov r0, #0FFh
add r0, #1DFh - 0FFh
strh r0, [r1, SamusState_PositionY]
strh r0, [r2, #2]
.endif
@@init_map:
bl InitStartingMap
mov r0, #0
ldr r1, =03000B8Bh
strb r0, [r1]
add sp, #4
pop { pc }
.pool
.endarea
.autoregion
.align 2
.func @InitSaveMeta
ldr r1, =StartingItems
ldrh r0, [r1, SamusUpgrades_CurrEnergy]
strh r0, [r2, SaveMeta_CurrEnergy]
ldrh r0, [r1, SamusUpgrades_MaxEnergy]
strh r0, [r2, SaveMeta_MaxEnergy]
; Set both current and max missiles to what's in CurrMissiles in the Starting Items Struct
; This value has been repurposed to be "Starting Ammo", with MaxMissiles repurposed as
; the increment when Missile Data is obtained.
ldrh r0, [r1, SamusUpgrades_CurrMissiles]
strh r0, [r2, SaveMeta_CurrMissiles]
ldrh r0, [r1, SamusUpgrades_CurrMissiles]
strh r0, [r2, SaveMeta_MaxMissiles]
ldrb r0, [r1, SamusUpgrades_SuitUpgrades]
strb r0, [r2, SaveMeta_SuitUpgrades]
.if RANDOMIZER
ldr r1, =StartingLocation
ldrb r0, [r1, StartingLocation_Area]
strb r0, [r2, SaveMeta_Area]
.endif
strb r3, [r2, SaveMeta_Exists]
strb r3, [r2, SaveMeta_Event]
strb r3, [r2, SaveMeta_IgtHours]
strb r3, [r2, SaveMeta_IgtMinutes]
bx lr
.pool
.endfunc
.endautoregion
.org 08080926h
.area 14h
bl @InitSaveMeta
b 0808093Ah
.endarea
.org 080A059Ah
.area 4
bl @FileSelectDrawInfoHighjack
.endarea
.autoregion
.align 2
; loads StartingItems to set default energy value on new file
.func @FileSelectDrawInfoHighjack
push { r4, lr }
ldr r4, =StartingItems
ldrh r0, [r4, SamusUpgrades_CurrEnergy]
; r1 contains Currentenergy offset for fileselect non-gameplay ram
strh r0, [r1]
ldrh r0, [r4, SamusUpgrades_MaxEnergy]
strh r0, [r1, SamusUpgrades_MaxEnergy - SamusUpgrades_CurrEnergy]
pop { r4, pc }
.pool
.endfunc
.align 2
.func SetNewFileHealthInfo
/* Register contents during highjack
r4 = MostRecentSaveFile 03000BD8
*/
push { lr }
ldr r6, =SaveData
ldrb r1, [r4]
mov r0, #SaveMeta_Size
mul r0, r1
add r0, r0, r6
ldr r0, [r0]
mov r1, #0C4h ; SamusUpgrades offset in SramWram
add r0, r0, r1
ldr r1, =StartingItems
ldrh r1, [r1, SamusUpgrades_MaxEnergy]
strh r1, [r0, SamusUpgrades_CurrEnergy]
strh r1, [r0, SamusUpgrades_MaxEnergy]
@@return:
pop { r0 }
bx r0
.pool
.endfunc
.endautoregion
| 412 | 0.832355 | 1 | 0.832355 | game-dev | MEDIA | 0.422946 | game-dev,os-kernel | 0.985328 | 1 | 0.985328 |
PipedreamHQ/pipedream | 1,465 | components/botpress/sources/common/polling.mjs | import {
ConfigurationError,
DEFAULT_POLLING_SOURCE_TIMER_INTERVAL,
} from "@pipedream/platform";
import app from "../../botpress.app.mjs";
export default {
props: {
app,
timer: {
type: "$.interface.timer",
label: "Polling Schedule",
description: "How often to poll the API",
default: {
intervalSeconds: DEFAULT_POLLING_SOURCE_TIMER_INTERVAL,
},
},
},
methods: {
generateMeta() {
throw new ConfigurationError("generateMeta is not implemented");
},
getResourceName() {
throw new ConfigurationError("getResourceName is not implemented");
},
getResourcesFn() {
throw new ConfigurationError("getResourcesFn is not implemented");
},
getResourcesFnArgs() {
throw new ConfigurationError("getResourcesFnArgs is not implemented");
},
processResource(resource) {
const meta = this.generateMeta(resource);
this.$emit(resource, meta);
},
async processResources(resources) {
Array.from(resources)
.reverse()
.forEach(this.processResource);
},
},
async run() {
const {
app,
getResourcesFn,
getResourcesFnArgs,
getResourceName,
processResources,
} = this;
const resources = await app.paginate({
resourcesFn: getResourcesFn(),
resourcesFnArgs: getResourcesFnArgs(),
resourceName: getResourceName(),
});
processResources(resources);
},
};
| 412 | 0.872183 | 1 | 0.872183 | game-dev | MEDIA | 0.227531 | game-dev | 0.914895 | 1 | 0.914895 |
wynand1004/Projects | 5,775 | SpaceWar/SpaceWar-9.py | #SpaceWar by @TokyoEdTech / Written in Python 2.7
#Part IX: Background Image/Window Title/Player & Missile Shape
import os
import random
import time
#Import the Turtle module
import turtle
#Required by MacOSX to show the window
turtle.fd(0)
#Set the animations speed to the maximum
turtle.speed(0)
#Change the background color
turtle.bgcolor("black")
#Change the window title
turtle.title("SpaceWar")
#Change the background image
turtle.bgpic("starfield.gif")
#Hide the default turtle
turtle.ht()
#This saves memory
turtle.setundobuffer(1)
#This speeds up drawing
turtle.tracer(0)
class Sprite(turtle.Turtle):
def __init__(self, spriteshape, color, startx, starty):
turtle.Turtle.__init__(self, shape = spriteshape)
self.speed(0)
self.penup()
self.color(color)
self.fd(0)
self.goto(startx, starty)
self.speed = 1
def move(self):
self.fd(self.speed)
#Boundary detection
if self.xcor() > 290:
self.setx(290)
self.rt(60)
if self.xcor() < -290:
self.setx(-290)
self.rt(60)
if self.ycor() > 290:
self.sety(290)
self.rt(60)
if self.ycor() < -290:
self.sety(-290)
self.rt(60)
def is_collision(self, other):
if (self.xcor() >= (other.xcor() - 20)) and \
(self.xcor() <= (other.xcor() + 20)) and \
(self.ycor() >= (other.ycor() - 20)) and \
(self.ycor() <= (other.ycor() + 20)):
return True
else:
return False
class Player(Sprite):
def __init__(self, spriteshape, color, startx, starty):
Sprite.__init__(self, spriteshape, color, startx, starty)
self.shapesize(stretch_wid=0.6, stretch_len=1.1, outline=None)
self.speed = 4
self.lives = 3
def turn_left(self):
self.lt(45)
def turn_right(self):
self.rt(45)
def accelerate(self):
self.speed += 1
def decelerate(self):
self.speed -= 1
class Enemy(Sprite):
def __init__(self, spriteshape, color, startx, starty):
Sprite.__init__(self, spriteshape, color, startx, starty)
self.speed = 6
self.setheading(random.randint(0,360))
class Ally(Sprite):
def __init__(self, spriteshape, color, startx, starty):
Sprite.__init__(self, spriteshape, color, startx, starty)
self.speed = 8
self.setheading(random.randint(0,360))
def move(self):
self.fd(self.speed)
#Boundary detection
if self.xcor() > 290:
self.setx(290)
self.lt(60)
if self.xcor() < -290:
self.setx(-290)
self.lt(60)
if self.ycor() > 290:
self.sety(290)
self.lt(60)
if self.ycor() < -290:
self.sety(-290)
self.lt(60)
class Missile(Sprite):
def __init__(self, spriteshape, color, startx, starty):
Sprite.__init__(self, spriteshape, color, startx, starty)
self.shapesize(stretch_wid=0.2, stretch_len=0.4, outline=None)
self.speed = 20
self.status = "ready"
self.goto(-1000, 1000)
def fire(self):
if self.status == "ready":
#Play missile sound
os.system("afplay laser.mp3&")
self.goto(player.xcor(), player.ycor())
self.setheading(player.heading())
self.status = "firing"
def move(self):
if self.status == "ready":
self.goto(-1000, 1000)
if self.status == "firing":
self.fd(self.speed)
#Border check
if self.xcor() < -290 or self.xcor() > 290 or \
self.ycor()< -290 or self.ycor()> 290:
self.goto(-1000,1000)
self.status = "ready"
class Game():
def __init__(self):
self.level = 1
self.score = 0
self.state = "playing"
self.pen = turtle.Turtle()
self.lives = 3
def draw_border(self):
#Draw border
self.pen.speed(0)
self.pen.color("white")
self.pen.pensize(3)
self.pen.penup()
self.pen.goto(-300, 300)
self.pen.pendown()
for side in range(4):
self.pen.fd(600)
self.pen.rt(90)
self.pen.penup()
self.pen.ht()
self.pen.pendown()
def show_status(self):
self.pen.undo()
msg = "Score: %s" %(self.score)
self.pen.penup()
self.pen.goto(-300, 310)
self.pen.write(msg, font=("Arial", 16, "normal"))
#Create game object
game = Game()
#Draw the game border
game.draw_border()
#Show the game status
game.show_status()
#Create my sprites
player = Player("triangle", "white", 0, 0)
#enemy = Enemy("circle", "red", -100, 0)
missile = Missile("triangle", "yellow", 0, 0)
#ally = Ally("square", "blue", 100, 0)
enemies =[]
for i in range(6):
enemies.append(Enemy("circle", "red", -100, 0))
allies =[]
for i in range(6):
allies.append(Ally("square", "blue", 100, 0))
#Keyboard bindings
turtle.onkey(player.turn_left, "Left")
turtle.onkey(player.turn_right, "Right")
turtle.onkey(player.accelerate, "Up")
turtle.onkey(player.decelerate, "Down")
turtle.onkey(missile.fire, "space")
turtle.listen()
#Main game loop
while True:
turtle.update()
time.sleep(0.02)
player.move()
missile.move()
for enemy in enemies:
enemy.move()
#Check for a collision with the player
if player.is_collision(enemy):
#Play explosion sound
os.system("afplay explosion.mp3&")
x = random.randint(-250, 250)
y = random.randint(-250, 250)
enemy.goto(x, y)
game.score -= 100
game.show_status()
#Check for a collision between the missile and the enemy
if missile.is_collision(enemy):
#Play explosion sound
os.system("afplay explosion.mp3&")
x = random.randint(-250, 250)
y = random.randint(-250, 250)
enemy.goto(x, y)
missile.status = "ready"
#Increase the score
game.score += 100
game.show_status()
for ally in allies:
ally.move()
#Check for a collision between the missile and the ally
if missile.is_collision(ally):
#Play explosion sound
os.system("afplay explosion.mp3&")
x = random.randint(-250, 250)
y = random.randint(-250, 250)
ally.goto(x, y)
missile.status = "ready"
#Decrease the score
game.score -= 50
game.show_status()
delay = raw_input("Press enter to finish. > ") | 412 | 0.822138 | 1 | 0.822138 | game-dev | MEDIA | 0.890691 | game-dev | 0.829279 | 1 | 0.829279 |
MegaMek/megameklab | 34,147 | megameklab/src/megameklab/ui/supportVehicle/SVStructureTab.java | /*
* Copyright (C) 2019-2025 The MegaMek Team. All Rights Reserved.
*
* This file is part of MegaMekLab.
*
* MegaMekLab is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License (GPL),
* version 3 or (at your option) any later version,
* as published by the Free Software Foundation.
*
* MegaMekLab is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* A copy of the GPL should have been included with this project;
* if not, see <https://www.gnu.org/licenses/>.
*
* NOTICE: The MegaMek organization is a non-profit group of volunteers
* creating free software for the BattleTech community.
*
* MechWarrior, BattleMech, `Mech and AeroTech are registered trademarks
* of The Topps Company, Inc. All Rights Reserved.
*
* Catalyst Game Labs and the Catalyst Game Labs logo are trademarks of
* InMediaRes Productions, LLC.
*
* MechWarrior Copyright Microsoft Corporation. MegaMek was created under
* Microsoft's "Game Content Usage Rules"
* <https://www.xbox.com/en-US/developers/rules> and it is not endorsed by or
* affiliated with Microsoft.
*/
package megameklab.ui.supportVehicle;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import megamek.common.SimpleTechLevel;
import megamek.common.bays.CrewQuartersCargoBay;
import megamek.common.bays.EjectionSeatCargoBay;
import megamek.common.bays.FirstClassQuartersCargoBay;
import megamek.common.bays.PillionSeatCargoBay;
import megamek.common.bays.SecondClassQuartersCargoBay;
import megamek.common.bays.StandardSeatCargoBay;
import megamek.common.bays.SteerageQuartersCargoBay;
import megamek.common.enums.Faction;
import megamek.common.enums.TechRating;
import megamek.common.equipment.Engine;
import megamek.common.equipment.EquipmentType;
import megamek.common.equipment.EquipmentTypeLookup;
import megamek.common.equipment.MiscMounted;
import megamek.common.equipment.MiscType;
import megamek.common.equipment.Mounted;
import megamek.common.equipment.Transporter;
import megamek.common.equipment.enums.FuelType;
import megamek.common.exceptions.LocationFullException;
import megamek.common.interfaces.ITechManager;
import megamek.common.units.Entity;
import megamek.common.units.EntityMovementMode;
import megamek.common.units.EntityWeightClass;
import megamek.common.units.FixedWingSupport;
import megamek.common.units.Tank;
import megamek.common.units.UnitRole;
import megamek.common.verifier.Ceil;
import megamek.common.verifier.TestEntity;
import megamek.common.verifier.TestSupportVehicle;
import megamek.logging.MMLogger;
import megameklab.ui.EntitySource;
import megameklab.ui.generalUnit.BasicInfoView;
import megameklab.ui.generalUnit.FuelView;
import megameklab.ui.generalUnit.IconView;
import megameklab.ui.generalUnit.MovementView;
import megameklab.ui.generalUnit.summary.*;
import megameklab.ui.listeners.SVBuildListener;
import megameklab.ui.util.ITab;
import megameklab.ui.util.RefreshListener;
import megameklab.util.UnitUtil;
/**
* Structure tab for support vehicle construction
*/
public class SVStructureTab extends ITab implements SVBuildListener {
private static final MMLogger LOGGER = MMLogger.create(SVStructureTab.class);
private RefreshListener refresh = null;
private JPanel masterPanel;
private BasicInfoView panBasicInfo;
private SVChassisView panChassis;
private MovementView panMovement;
private FuelView panFuel;
private SummaryView panSummary;
private SVChassisModView panChassisMod;
private SVCrewView panCrew;
private IconView iconView;
public SVStructureTab(EntitySource eSource) {
super(eSource);
setLayout(new BorderLayout());
setupPanels();
add(masterPanel, BorderLayout.CENTER);
refresh();
}
private Entity getSV() {
return eSource.getEntity();
}
private void setupPanels() {
masterPanel = new JPanel(new GridBagLayout());
panBasicInfo = new BasicInfoView(getSV().getConstructionTechAdvancement());
panChassis = new SVChassisView(panBasicInfo);
panMovement = new MovementView(panBasicInfo);
panFuel = new FuelView();
panChassisMod = new SVChassisModView(panBasicInfo);
panCrew = new SVCrewView();
iconView = new IconView();
panSummary = new SummaryView(eSource,
new UnitTypeSummaryItem(),
new StructureSummaryItem(),
new EngineSummaryItem(),
new FuelSummaryItem(),
new HeatSinkSummaryItem(),
new ControlsSummaryItem(),
new ArmorSummaryItem(),
new TurretSummaryItem(),
new PowerAmplifierSummaryItem(),
new EquipmentSummaryItem());
JPanel leftPanel = new JPanel();
JPanel midPanel = new JPanel();
JPanel rightPanel = new JPanel();
leftPanel.setLayout(new GridBagLayout());
midPanel.setLayout(new GridBagLayout());
rightPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy = 0;
leftPanel.add(panBasicInfo, gbc);
gbc.gridy++;
leftPanel.add(iconView, gbc);
gbc.gridy++;
leftPanel.add(panChassis, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
midPanel.add(panMovement, gbc);
gbc.gridy++;
midPanel.add(panFuel, gbc);
gbc.gridy++;
midPanel.add(panSummary, gbc);
gbc.gridx = 2;
gbc.gridy = 0;
rightPanel.add(panChassisMod, gbc);
gbc.gridy++;
rightPanel.add(panCrew, gbc);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = java.awt.GridBagConstraints.NONE;
gbc.weightx = 0.0;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.insets = new Insets(5, 5, 5, 5);
masterPanel.add(leftPanel, gbc);
gbc.gridx = 1;
masterPanel.add(midPanel, gbc);
gbc.gridx = 2;
masterPanel.add(rightPanel, gbc);
panBasicInfo.setBorder(BorderFactory.createTitledBorder("Basic Information"));
panChassis.setBorder(BorderFactory.createTitledBorder("Chassis"));
panMovement.setBorder(BorderFactory.createTitledBorder("Movement"));
panFuel.setBorder(BorderFactory.createTitledBorder("Fuel"));
panChassisMod.setBorder(BorderFactory.createTitledBorder("Chassis Modifications"));
panCrew.setBorder(BorderFactory.createTitledBorder("Crew and Quarters"));
}
public void refresh() {
removeAllListeners();
panBasicInfo.setFromEntity(getSV());
panChassis.setFromEntity(getSV());
panMovement.setFromEntity(getSV());
refreshFuel();
panChassisMod.setFromEntity(getSV());
panCrew.setFromEntity(getSV());
panSummary.refresh();
iconView.setFromEntity(getEntity());
addAllListeners();
}
public ITechManager getTechManager() {
return panBasicInfo;
}
/*
* Used by MekHQ to set the tech faction for custom refits.
*/
public void setTechFaction(Faction techFaction) {
panBasicInfo.setTechFaction(techFaction);
}
private void removeAllListeners() {
panBasicInfo.removeListener(this);
panChassis.removeListener(this);
panMovement.removeListener(this);
panFuel.removeListener(this);
panChassisMod.removeListener(this);
panCrew.removeListener(this);
}
private void addAllListeners() {
panBasicInfo.addListener(this);
panChassis.addListener(this);
panMovement.addListener(this);
panFuel.addListener(this);
panChassisMod.addListener(this);
panCrew.addListener(this);
}
public void addRefreshedListener(RefreshListener l) {
refresh = l;
}
/**
* Disables controls that cannot be changed when customizing a refit.
*/
public void setAsCustomization() {
panBasicInfo.setAsCustomization();
panChassis.setAsCustomization();
}
@Override
public void refreshSummary() {
panSummary.refresh();
}
@Override
public void chassisChanged(String chassis) {
getSV().setChassis(chassis);
refresh.refreshHeader();
refresh.refreshTransport();
refresh.refreshPreview();
iconView.refresh();
}
@Override
public void modelChanged(String model) {
getSV().setModel(model);
refresh.refreshHeader();
refresh.refreshPreview();
iconView.refresh();
}
@Override
public void yearChanged(int year) {
getSV().setYear(year);
updateTechLevel();
}
@Override
public void updateTechLevel() {
getEntity().setTechLevel(panBasicInfo.getTechLevel()
.getCompoundTechLevel(panBasicInfo.useClanTechBase()));
if (UnitUtil.checkEquipmentByTechLevel(getSV(), panBasicInfo)) {
refresh.refreshEquipment();
} else {
refresh.refreshEquipmentTable();
}
if (!getTechManager().isLegal(TestSupportVehicle.SVType.getVehicleType(getEntity()))) {
typeChanged(TestSupportVehicle.SVType.WHEELED);
}
panChassis.refresh();
panMovement.setFromEntity(getSV());
panChassisMod.setFromEntity(getSV());
refresh.refreshArmor();
refresh.refreshTransport();
refresh.refreshPreview();
}
@Override
public void sourceChanged(String source) {
getSV().setSource(source);
refresh.refreshPreview();
}
@Override
public void techBaseChanged(boolean clan, boolean mixed) {
if ((clan != getSV().isClan()) || (mixed != getSV().isMixedTech())) {
getSV().setMixedTech(mixed);
updateTechLevel();
}
}
@Override
public void techLevelChanged(SimpleTechLevel techLevel) {
updateTechLevel();
}
@Override
public void manualBVChanged(int manualBV) {
UnitUtil.setManualBV(manualBV, getEntity());
refresh.refreshStatus();
refresh.refreshPreview();
}
@Override
public void walkChanged(int walkMP) {
getSV().setOriginalWalkMP(walkMP);
panSummary.refresh();
refresh.refreshStatus();
refresh.refreshPreview();
panMovement.removeListener(this);
panMovement.setFromEntity(getSV());
panMovement.addListener(this);
panFuel.setFromEntity(getSV());
panChassis.refresh();
}
@Override
public void jumpChanged(int jumpMP, EquipmentType jumpJet) {
if (null != jumpJet) {
UnitUtil.removeAllMiscMounted(getSV(), MiscType.F_JUMP_JET);
getSV().setOriginalJumpMP(0);
for (int i = 0; i < jumpMP; i++) {
try {
getSV().addEquipment(jumpJet, Tank.LOC_BODY);
} catch (LocationFullException e) {
LOGGER.error("", e);
}
}
panSummary.refresh();
refresh.refreshBuild();
refresh.refreshStatus();
refresh.refreshSummary();
refresh.refreshPreview();
panMovement.removeListener(this);
panMovement.setFromEntity(getSV());
panMovement.addListener(this);
}
}
@Override
public void jumpTypeChanged(EquipmentType jumpJet) {
// Only one type of JJ for vehicles
}
@Override
public void tonnageChanged(double tonnage) {
boolean wasLarge = getEntity().getWeightClass() == EntityWeightClass.WEIGHT_LARGE_SUPPORT;
getEntity().setWeight(TestEntity.ceil(tonnage, tonnage < 5 ? Ceil.KILO : Ceil.HALF_TON));
if (!getEntity().isAero() && !getEntity().getMovementMode().equals(EntityMovementMode.VTOL)) {
if ((getEntity().getWeightClass() == EntityWeightClass.WEIGHT_LARGE_SUPPORT) != wasLarge) {
toggleLargeSupport();
}
}
panChassisMod.setFromEntity(getSV());
panFuel.setFromEntity(getSV());
panCrew.setFromEntity(getSV());
refresh.refreshArmor();
refresh.refreshEquipment();
refresh.refreshTransport();
refresh.refreshSummary();
refresh.refreshStatus();
refresh.refreshPreview();
}
/**
* Called when changing to or from large support vee, which may require instantiating a different Entity.
*/
private void toggleLargeSupport() {
// fixed wing/airship/satellite/VTOL do not change the number of locations
if (getEntity().isAero() || getEntity().getMovementMode().equals(EntityMovementMode.VTOL)) {
return;
}
Entity oldEntity = getEntity();
if (getEntity().getWeightClass() == EntityWeightClass.WEIGHT_LARGE_SUPPORT) {
eSource.createNewUnit(Entity.ETYPE_LARGE_SUPPORT_TANK, getEntity());
} else {
eSource.createNewUnit(Entity.ETYPE_SUPPORT_TANK, getEntity());
}
getEntity().setWeight(oldEntity.getWeight());
getEntity().setMovementMode(oldEntity.getMovementMode());
panChassis.refresh();
panSummary.refresh();
refresh.refreshArmor();
refresh.refreshEquipment();
refresh.refreshPreview();
refresh.refreshBuild();
refresh.refreshStatus();
}
@Override
public void typeChanged(TestSupportVehicle.SVType type) {
TestSupportVehicle.SVType oldType = TestSupportVehicle.SVType.getVehicleType(getSV());
if (!type.equals(oldType)) {
if (type.equals(TestSupportVehicle.SVType.FIXED_WING)) {
eSource.createNewUnit(Entity.ETYPE_FIXED_WING_SUPPORT, getSV());
} else if (type.equals(TestSupportVehicle.SVType.VTOL)) {
eSource.createNewUnit(Entity.ETYPE_SUPPORT_VTOL, getSV());
} else if (TestSupportVehicle.SVType.FIXED_WING.equals(oldType)
|| TestSupportVehicle.SVType.VTOL.equals(oldType)) {
eSource.createNewUnit(Entity.ETYPE_SUPPORT_TANK, getSV());
}
getSV().setMovementMode(type.defaultMovementMode);
panChassis.setFromEntity(getSV());
panMovement.setFromEntity(getSV());
refreshFuel();
panChassisMod.setFromEntity(getSV());
panCrew.setFromEntity(getSV());
panSummary.refresh();
refresh.refreshAll();
}
}
@Override
public void structuralTechRatingChanged(TechRating techRating) {
getSV().setStructuralTechRating(techRating);
getSV().recalculateTechAdvancement();
panSummary.refresh();
refresh.refreshStatus();
refresh.refreshPreview();
}
@Override
public void engineChanged(Engine engine) {
getSV().setEngine(engine);
if (engine.getEngineType() == Engine.NONE) {
getSV().setOriginalWalkMP(0);
}
// Switching between maglev and non-maglev engines changes movement mode
if (TestSupportVehicle.SVType.RAIL.equals(TestSupportVehicle.SVType.getVehicleType(getSV()))) {
getSV().setMovementMode(
(engine.getEngineType() == Engine.MAGLEV) ? EntityMovementMode.MAGLEV : EntityMovementMode.RAIL);
}
// Make sure the engine tech rating is at least the minimum for the engine type
if (getSV().getEngineTechRating().getIndex() < engine.getTechRating().getIndex()) {
getSV().setEngineTechRating(engine.getTechRating());
getSV().recalculateTechAdvancement();
}
// Fixed Wing support vehicles require the prop mod for an electric engine
if ((TestSupportVehicle.SVType.getVehicleType(getSV()) == TestSupportVehicle.SVType.FIXED_WING)
&& TestSupportVehicle.SVEngine.getEngineType(engine).electric
&& !getSV().hasMisc(MiscType.F_PROP)) {
setChassisMod(TestSupportVehicle.ChassisModification.PROP.equipment, true);
}
if (engine.getEngineType() != Engine.EXTERNAL) {
setChassisMod(TestSupportVehicle.ChassisModification.EXTERNAL_POWER_PICKUP.equipment, false);
}
// The chassis view needs to refresh the available engine rating combobox
panChassis.removeListener(this);
panChassis.setFromEntity(getSV());
panChassis.addListener(this);
refreshFuel();
panChassisMod.setFromEntity(getSV());
panSummary.refresh();
refresh.refreshEquipment();
refresh.refreshStatus();
refresh.refreshPreview();
}
@Override
public void engineTechRatingChanged(TechRating techRating) {
getSV().setEngineTechRating(techRating);
getSV().recalculateTechAdvancement();
panFuel.setFromEntity(getSV());
panSummary.refresh();
refresh.refreshStatus();
refresh.refreshPreview();
}
@Override
public void setChassisMod(EquipmentType mod, boolean installed) {
final Mounted<?> current = getSV().getMisc().stream().filter(m -> m.getType().equals(mod)).findFirst()
.orElse(null);
if (installed && (null == current)) {
try {
getSV().addEquipment(mod, getSV().isAero() ? FixedWingSupport.LOC_BODY : Tank.LOC_BODY);
} catch (LocationFullException e) {
// This should not be possible since chassis mods don't occupy slots
LOGGER.error("LocationFullException when adding chassis mod {}", mod.getName());
}
} else if (!installed && (null != current)) {
getSV().getMisc().remove(current);
getSV().getEquipment().remove(current);
UnitUtil.removeCriticalSlots(getSV(), current);
UnitUtil.changeMountStatus(getSV(), current, Entity.LOC_NONE, Entity.LOC_NONE, false);
}
if (mod.equals(TestSupportVehicle.ChassisModification.OMNI.equipment)) {
getEntity().setOmni(installed);
if (!getEntity().isOmni()) {
getEntity().getEquipment().forEach(m -> m.setOmniPodMounted(false));
List<Transporter> podTransports = getEntity().getTransports().stream()
.filter(t -> getEntity().isPodMountedTransport(t))
.toList();
podTransports.forEach(t -> {
getEntity().removeTransporter(t);
getEntity().addTransporter(t, false);
});
}
panChassis.setFromEntity(getEntity());
} else if (mod.equals(TestSupportVehicle.ChassisModification.ARMORED.equipment)) {
refresh.refreshArmor();
}
if (TestSupportVehicle.SVType.NAVAL.equals(TestSupportVehicle.SVType.getVehicleType(getEntity()))) {
if (getEntity().hasMisc(MiscType.F_HYDROFOIL)) {
getEntity().setMovementMode(EntityMovementMode.HYDROFOIL);
} else if (getEntity().hasMisc(MiscType.F_SUBMERSIBLE)) {
getEntity().setMovementMode(EntityMovementMode.SUBMARINE);
} else {
getEntity().setMovementMode(EntityMovementMode.NAVAL);
}
}
refreshFuel();
panChassisMod.refresh();
panSummary.refresh();
refresh.refreshTransport();
refresh.refreshStatus();
refresh.refreshPreview();
refresh.refreshBuild();
}
@Override
public void turretChanged(int turretConfig) {
if (!(getSV() instanceof Tank)) {
return;
}
if ((turretConfig != SVBuildListener.TURRET_DUAL)
&& !getTank().hasNoDualTurret()) {
removeTurret(getTank().getLocTurret2());
getTank().setHasNoDualTurret(true);
getTank().setBaseChassisTurret2Weight(Tank.BASE_CHASSIS_TURRET_WT_UNASSIGNED);
}
if ((turretConfig == SVBuildListener.TURRET_NONE)
&& !getTank().hasNoTurret()) {
removeTurret(getTank().getLocTurret());
getTank().setHasNoTurret(true);
getTank().setBaseChassisTurretWeight(Tank.BASE_CHASSIS_TURRET_WT_UNASSIGNED);
}
if (getTank().hasNoTurret() && (turretConfig != SVBuildListener.TURRET_NONE)) {
getTank().setHasNoTurret(false);
getTank().autoSetInternal();
initTurretArmor(getTank().getLocTurret());
}
if (getTank().hasNoDualTurret() && (turretConfig == SVBuildListener.TURRET_DUAL)) {
getTank().setHasNoDualTurret(false);
getTank().autoSetInternal();
initTurretArmor(getTank().getLocTurret2());
}
getTank().autoSetInternal();
panChassis.setFromEntity(getTank());
refresh.refreshArmor();
refresh.refreshBuild();
refresh.refreshPreview();
refresh.refreshStatus();
}
@Override
public void sponsonTurretChanged(boolean installed) {
final List<Mounted<?>> current = getSV().getMisc().stream()
.filter(m -> m.getType().hasFlag(MiscType.F_SPONSON_TURRET))
.collect(Collectors.toList());
if (installed && current.isEmpty()) {
try {
// superheavy FL/FR match L/R
getSV().addEquipment(EquipmentType.get(EquipmentTypeLookup.SPONSON_TURRET), Tank.LOC_LEFT);
getSV().addEquipment(EquipmentType.get(EquipmentTypeLookup.SPONSON_TURRET), Tank.LOC_RIGHT);
} catch (LocationFullException e) {
// This should not be possible since sponson turrets mods don't occupy slots
LOGGER.error("LocationFullException when adding sponson turret");
}
} else if (!installed) {
for (Mounted<?> m : getEntity().getEquipment()) {
m.setSponsonTurretMounted(false);
}
for (Mounted<?> sponson : current) {
if (sponson instanceof MiscMounted) {
getSV().getMisc().remove(sponson);
}
getSV().getEquipment().remove(sponson);
UnitUtil.removeCriticalSlots(getSV(), sponson);
UnitUtil.changeMountStatus(getSV(), sponson, Entity.LOC_NONE, Entity.LOC_NONE, false);
}
}
resetSponsonPintleWeight();
panChassis.setFromEntity(getEntity());
panSummary.refresh();
refresh.refreshBuild();
refresh.refreshStatus();
refresh.refreshPreview();
}
@Override
public void pintleTurretChanged(boolean addPintle, final int loc) {
final Optional<MiscMounted> installedPintle = getSV().getMisc().stream()
.filter(m -> m.is(EquipmentTypeLookup.PINTLE_TURRET))
.filter(m -> m.getLocation() == loc)
.findFirst();
if (addPintle && installedPintle.isEmpty()) {
try {
getSV().addEquipment(EquipmentType.get(EquipmentTypeLookup.PINTLE_TURRET), loc);
} catch (LocationFullException e) {
// This should not be possible since sponson turrets mods don't occupy slots
LOGGER.error("LocationFullException when adding pintle turret");
}
} else if (!addPintle && installedPintle.isPresent()) {
for (Mounted<?> m : getEntity().getEquipment()) {
if (m.getLocation() == loc) {
m.setPintleTurretMounted(false);
}
}
MiscMounted pintle = installedPintle.get();
getSV().getMisc().remove(pintle);
getSV().getEquipment().remove(pintle);
UnitUtil.removeCriticalSlots(getSV(), pintle);
UnitUtil.changeMountStatus(getSV(), pintle, Entity.LOC_NONE, Entity.LOC_NONE, false);
}
resetSponsonPintleWeight();
panChassis.setFromEntity(getEntity());
panSummary.refresh();
refresh.refreshBuild();
refresh.refreshStatus();
refresh.refreshPreview();
}
/**
* Checks for the presence of sponson or pintle mounts, and if none are found resets the base chassis weight.
*/
private void resetSponsonPintleWeight() {
if (getEntity() instanceof Tank) {
for (Mounted<?> m : getEntity().getMisc()) {
if (m.getType().hasFlag(MiscType.F_SPONSON_TURRET)
|| m.getType().hasFlag(MiscType.F_PINTLE_TURRET)) {
return;
}
}
getTank().setBaseChassisSponsonPintleWeight(Tank.BASE_CHASSIS_TURRET_WT_UNASSIGNED);
}
}
@Override
public void turretBaseWtChanged(double turret1, double turret2) {
if (getSV() instanceof Tank) {
getTank().setBaseChassisTurretWeight(turret1);
getTank().setBaseChassisTurret2Weight(turret2);
panSummary.refresh();
refresh.refreshStatus();
}
}
@Override
public void sponsonPintleBaseWtChanged(double turretWeight) {
if (getSV() instanceof Tank) {
getTank().setBaseChassisSponsonPintleWeight(turretWeight);
panSummary.refresh();
refresh.refreshStatus();
}
}
@Override
public void fireConChanged(int index) {
final Mounted<?> current = getSV().getMisc().stream()
.filter(m -> m.getType().hasFlag(MiscType.F_BASIC_FIRE_CONTROL)
|| m.getType().hasFlag(MiscType.F_ADVANCED_FIRE_CONTROL))
.findFirst().orElse(null);
if (null != current) {
getSV().getMisc().remove(current);
getSV().getEquipment().remove(current);
UnitUtil.removeCriticalSlots(getSV(), current);
UnitUtil.changeMountStatus(getSV(), current, Entity.LOC_NONE, Entity.LOC_NONE, false);
}
EquipmentType eq = null;
if (index == SVBuildListener.FIRE_CONTROL_BASIC) {
eq = EquipmentType.get("Basic Fire Control");
} else if (index == SVBuildListener.FIRE_CONTROL_ADVANCED) {
eq = EquipmentType.get("Advanced Fire Control");
}
if (null != eq) {
try {
getSV().addEquipment(eq, getSV().isAero() ? FixedWingSupport.LOC_BODY : Tank.LOC_BODY);
} catch (LocationFullException e) {
// This should not be possible since fire control doesn't occupy slots
LOGGER.error("LocationFullException when adding fire control {}", eq.getName());
}
}
panChassis.setFromEntity(getSV());
panSummary.refresh();
refresh.refreshStatus();
refresh.refreshPreview();
}
@Override
public void fireConWtChanged(double weight) {
getSV().setBaseChassisFireConWeight(weight);
panSummary.refresh();
refresh.refreshStatus();
}
@Override
public void resetChassis() {
UnitUtil.resetBaseChassis(getEntity());
refresh.refreshAll();
}
@Override
public void setSeating(int standard, int standardPod,
int pillion, int pillionPod,
int ejection, int ejectionPod) {
// Clear out any existing seating.
final List<Transporter> current = getSV().getTransports().stream()
.filter(t -> t instanceof StandardSeatCargoBay)
.toList();
for (Transporter t : current) {
getSV().removeTransporter(t);
}
// Create new ones as needed.
if (standard > 0) {
getSV().addTransporter(new StandardSeatCargoBay(standard), false);
}
if (standardPod > 0) {
getSV().addTransporter(new StandardSeatCargoBay(standardPod), true);
}
if (pillion > 0) {
getSV().addTransporter(new PillionSeatCargoBay(pillion), false);
}
if (pillionPod > 0) {
getSV().addTransporter(new PillionSeatCargoBay(pillionPod), true);
}
if (ejection > 0) {
getSV().addTransporter(new EjectionSeatCargoBay(ejection), false);
}
if (ejectionPod > 0) {
getSV().addTransporter(new EjectionSeatCargoBay(ejectionPod), true);
}
panCrew.setFromEntity(getSV());
panSummary.refresh();
refresh.refreshStatus();
refresh.refreshPreview();
}
@Override
public void setQuarters(int firstClass, int firstClassPod,
int secondClass, int secondClassPod,
int crew, int crewPod,
int steerage, int steeragePod) {
// Clear out any existing standard or pillion seating.
final List<Transporter> current = getSV().getTransports().stream()
.filter(t -> (t instanceof FirstClassQuartersCargoBay)
|| (t instanceof SecondClassQuartersCargoBay)
|| (t instanceof CrewQuartersCargoBay)
|| (t instanceof SteerageQuartersCargoBay))
.toList();
for (Transporter t : current) {
getSV().removeTransporter(t);
}
// Create new ones as needed.
if (firstClass > 0) {
getSV().addTransporter(new FirstClassQuartersCargoBay(firstClass), false);
}
if (firstClassPod > 0) {
getSV().addTransporter(new FirstClassQuartersCargoBay(firstClassPod), true);
}
if (secondClass > 0) {
getSV().addTransporter(new SecondClassQuartersCargoBay(secondClass), false);
}
if (secondClassPod > 0) {
getSV().addTransporter(new SecondClassQuartersCargoBay(secondClassPod), true);
}
if (crew > 0) {
getSV().addTransporter(new CrewQuartersCargoBay(crew), false);
}
if (crewPod > 0) {
getSV().addTransporter(new CrewQuartersCargoBay(crewPod), true);
}
if (steerage > 0) {
getSV().addTransporter(new SteerageQuartersCargoBay(steerage), false);
}
if (steeragePod > 0) {
getSV().addTransporter(new SteerageQuartersCargoBay(steeragePod), true);
}
panCrew.setFromEntity(getSV());
panSummary.refresh();
refresh.refreshStatus();
refresh.refreshPreview();
}
private void removeTurret(int loc) {
for (int slot = 0; slot < getTank().getNumberOfCriticalSlots(loc); slot++) {
getTank().setCritical(loc, slot, null);
}
for (Mounted<?> mount : getTank().getEquipment()) {
if (mount.getLocation() == loc) {
UnitUtil.changeMountStatus(getTank(), mount,
Entity.LOC_NONE, Entity.LOC_NONE, false);
}
}
}
private void initTurretArmor(int loc) {
getTank().initializeArmor(0, loc);
getTank().setArmorTechLevel(
getTank().getArmorTechLevel(Tank.LOC_FRONT),
loc);
getTank().setArmorType(getTank().getArmorType(Tank.LOC_FRONT),
loc);
}
@Override
public void fuelTonnageChanged(double tonnage) {
double fuelTons = TestEntity.round(tonnage,
TestEntity.usesKgStandard(getSV()) ? Ceil.KILO : Ceil.HALF_TON);
if (getSV().isAero()) {
getAero().setFuelTonnage(fuelTons);
} else {
getTank().setFuelTonnage(fuelTons);
}
refreshFuel();
panSummary.refresh();
refresh.refreshStatus();
refresh.refreshPreview();
}
@Override
public void fuelCapacityChanged(int capacity) {
if (getEntity().isAero()) {
getAero().setFuel(capacity);
} else {
double tonnage = capacity * getTank().fuelTonnagePer100km() / 100.0;
if (TestEntity.usesKgStandard(getEntity())) {
tonnage = TestEntity.round(tonnage, Ceil.KILO);
} else if (tonnage > getTank().getFuelTonnage()) {
// Round in the same direction as the change.
tonnage = TestEntity.ceil(tonnage, Ceil.HALF_TON);
} else {
tonnage = TestEntity.floor(tonnage, Ceil.HALF_TON);
}
getTank().setFuelTonnage(tonnage);
}
panFuel.setFromEntity(getSV());
panSummary.refresh();
refresh.refreshStatus();
refresh.refreshPreview();
}
@Override
public void fuelTypeChanged(FuelType fuelType) {
if (getEntity() instanceof Tank) {
getTank().setICEFuelType(fuelType);
}
panFuel.setFromEntity(getEntity());
}
/**
* Convenience method that removes the fuel if the vehicle does not require fuel mass then refreshes the fuel panel.
* Changes that can affect this are vehicle type, engine type, and the prop chassis mod.
*/
private void refreshFuel() {
if ((getSV() instanceof FixedWingSupport)
&& (((FixedWingSupport) getSV()).kgPerFuelPoint() == 0)) {
getAero().setFuelTonnage(0);
} else if ((getSV() instanceof Tank) && (getTank().fuelTonnagePer100km() == 0)) {
getTank().setFuelTonnage(0);
}
panFuel.setFromEntity(getSV());
}
@Override
public void mulIdChanged(int mulId) {
getEntity().setMulId(mulId);
refresh.refreshSummary();
}
@Override
public void roleChanged(UnitRole role) {
getEntity().setUnitRole(role);
refresh.refreshSummary();
refresh.refreshPreview();
}
}
| 412 | 0.95488 | 1 | 0.95488 | game-dev | MEDIA | 0.830852 | game-dev | 0.769138 | 1 | 0.769138 |
IJEMIN/Unity-Programming-Essence | 3,486 | 19/Done/Zombie Multiplayer/Assets/Photon/PhotonUnityNetworking/Demos/PunCockpit/Scripts/Lists/PlayerListCell.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="PlayerListCell.cs" company="Exit Games GmbH">
// Part of: Photon Unity Utilities,
// </copyright>
// <summary>
// Player list cell representing a given PhotonPlayer
// </summary>
// <author>developer@exitgames.com</author>
// --------------------------------------------------------------------------------------------------------------------
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using Photon.Realtime;
using Photon.Pun.UtilityScripts;
namespace Photon.Pun.Demo.Cockpit
{
/// <summary>
/// Player list cell representing a given PhotonPlayer
/// </summary>
public class PlayerListCell : MonoBehaviour
{
public PlayerListView ListManager;
public Text NumberText;
public Text NameText;
public Image ActiveFlag;
public Color InactiveColor;
public Color ActiveColor;
public Text isLocalText;
public Image isMasterFlag;
public LayoutElement LayoutElement;
Player _player;
public bool isInactiveCache;
public void RefreshInfo(ExitGames.Client.Photon.Hashtable changedProps)
{
UpdateInfo();
}
public void AddToList(Player info, bool animate = false)
{
//Debug.Log("AddToList " + info.ToStringFull());
_player = info;
UpdateInfo();
if (animate)
{
StartCoroutine("Add");
}
else
{
LayoutElement.minHeight = 30f;
}
}
public void RemoveFromList()
{
StartCoroutine("Remove");
}
public void OnClick()
{
ListManager.SelectPlayer(_player);
}
void UpdateInfo()
{
if (string.IsNullOrEmpty(_player.NickName))
{
NameText.text = _player.ActorNumber.ToString();
}
int _index = _player.GetPlayerNumber();
NumberText.text = "#" + _index.ToString("00"); // if this function was not called on every update, we would need to listen to the PlayerNumbering delegate
NameText.text = _player.NickName;
ActiveFlag.color = _player.IsInactive ? InactiveColor : ActiveColor;
isLocalText.gameObject.SetActive(_player.IsLocal);
isMasterFlag.gameObject.SetActive(_player.IsMasterClient);
// reorder the list to match player number
if (_index >= 0 && this.transform.GetSiblingIndex() != _index)
{
this.transform.SetSiblingIndex(_index + 1);
}
}
IEnumerator Add()
{
this.isInactiveCache = false;
LayoutElement.minHeight = 0f;
while (LayoutElement.minHeight != 30f)
{
LayoutElement.minHeight = Mathf.MoveTowards(LayoutElement.minHeight, 30f, 2f);
yield return new WaitForEndOfFrame();
}
}
IEnumerator Remove()
{
while (LayoutElement.minHeight != 0f)
{
LayoutElement.minHeight = Mathf.MoveTowards(LayoutElement.minHeight, 0f, 2f);
yield return new WaitForEndOfFrame();
}
Destroy(this.gameObject);
}
}
} | 412 | 0.869126 | 1 | 0.869126 | game-dev | MEDIA | 0.901456 | game-dev | 0.947764 | 1 | 0.947764 |
FTL13/FTL13 | 5,415 | code/_onclick/hud/action_button.dm | #define ACTION_BUTTON_DEFAULT_BACKGROUND "default"
/obj/screen/movable/action_button
var/datum/action/linked_action
var/actiontooltipstyle = ""
screen_loc = null
var/overlay_icon_state
var/button_icon_state
var/appearance_cache
/obj/screen/movable/action_button/Click(location,control,params)
var/list/modifiers = params2list(params)
if(modifiers["shift"])
moved = 0
usr.update_action_buttons() //redraw buttons that are no longer considered "moved"
return TRUE
if(modifiers["ctrl"])
locked = !locked
to_chat(usr, "<span class='notice'>Action button \"[name]\" [locked ? "" : "un"]locked.</span>")
return TRUE
if(usr.next_click > world.time)
return
usr.next_click = world.time + 1
linked_action.Trigger()
return TRUE
//Hide/Show Action Buttons ... Button
/obj/screen/movable/action_button/hide_toggle
name = "Hide Buttons"
desc = "Shift-click any button to reset its position, and Control-click it to lock it in place. Alt-click this button to reset all buttons to their default positions."
icon = 'icons/mob/actions.dmi'
icon_state = "bg_default"
var/hidden = 0
var/hide_icon = 'icons/mob/actions.dmi'
var/hide_state = "hide"
var/show_state = "show"
/obj/screen/movable/action_button/hide_toggle/Click(location,control,params)
var/list/modifiers = params2list(params)
if(modifiers["shift"])
moved = FALSE
usr.update_action_buttons(TRUE)
return TRUE
if(modifiers["ctrl"])
locked = !locked
to_chat(usr, "<span class='notice'>Action button \"[name]\" [locked ? "" : "un"]locked.</span>")
return TRUE
if(modifiers["alt"])
for(var/V in usr.actions)
var/datum/action/A = V
var/obj/screen/movable/action_button/B = A.button
B.moved = FALSE
B.locked = usr.client.prefs.buttons_locked
locked = usr.client.prefs.buttons_locked
moved = FALSE
usr.update_action_buttons(TRUE)
to_chat(usr, "<span class='notice'>Action button positions have been reset.</span>")
return TRUE
usr.hud_used.action_buttons_hidden = !usr.hud_used.action_buttons_hidden
hidden = usr.hud_used.action_buttons_hidden
if(hidden)
name = "Show Buttons"
else
name = "Hide Buttons"
UpdateIcon()
usr.update_action_buttons()
/obj/screen/movable/action_button/hide_toggle/AltClick(mob/user)
for(var/V in user.actions)
var/datum/action/A = V
var/obj/screen/movable/action_button/B = A.button
B.moved = FALSE
if(moved)
moved = FALSE
user.update_action_buttons(TRUE)
to_chat(user, "<span class='notice'>Action button positions have been reset.</span>")
/obj/screen/movable/action_button/hide_toggle/proc/InitialiseIcon(datum/hud/owner_hud)
var settings = owner_hud.get_action_buttons_icons()
icon = settings["bg_icon"]
icon_state = settings["bg_state"]
hide_icon = settings["toggle_icon"]
hide_state = settings["toggle_hide"]
show_state = settings["toggle_show"]
UpdateIcon()
/obj/screen/movable/action_button/hide_toggle/proc/UpdateIcon()
cut_overlays()
add_overlay(mutable_appearance(hide_icon, hidden ? show_state : hide_state))
/obj/screen/movable/action_button/MouseEntered(location,control,params)
openToolTip(usr,src,params,title = name,content = desc,theme = actiontooltipstyle)
/obj/screen/movable/action_button/MouseExited()
closeToolTip(usr)
/datum/hud/proc/get_action_buttons_icons()
. = list()
.["bg_icon"] = ui_style_icon
.["bg_state"] = "template"
//TODO : Make these fit theme
.["toggle_icon"] = 'icons/mob/actions.dmi'
.["toggle_hide"] = "hide"
.["toggle_show"] = "show"
//see human and alien hud for specific implementations.
/mob/proc/update_action_buttons_icon(status_only = FALSE)
for(var/X in actions)
var/datum/action/A = X
A.UpdateButtonIcon(status_only)
//This is the proc used to update all the action buttons.
/mob/proc/update_action_buttons(reload_screen)
if(!hud_used || !client)
return
if(hud_used.hud_shown != HUD_STYLE_STANDARD)
return
var/button_number = 0
if(hud_used.action_buttons_hidden)
for(var/datum/action/A in actions)
A.button.screen_loc = null
if(reload_screen)
client.screen += A.button
else
for(var/datum/action/A in actions)
button_number++
A.UpdateButtonIcon()
var/obj/screen/movable/action_button/B = A.button
if(!B.moved)
B.screen_loc = hud_used.ButtonNumberToScreenCoords(button_number)
else
B.screen_loc = B.moved
if(reload_screen)
client.screen += B
if(!button_number)
hud_used.hide_actions_toggle.screen_loc = null
return
if(!hud_used.hide_actions_toggle.moved)
hud_used.hide_actions_toggle.screen_loc = hud_used.ButtonNumberToScreenCoords(button_number+1)
else
hud_used.hide_actions_toggle.screen_loc = hud_used.hide_actions_toggle.moved
if(reload_screen)
client.screen += hud_used.hide_actions_toggle
#define AB_MAX_COLUMNS 10
/datum/hud/proc/ButtonNumberToScreenCoords(number) // TODO : Make this zero-indexed for readabilty
var/row = round((number - 1)/AB_MAX_COLUMNS)
var/col = ((number - 1)%(AB_MAX_COLUMNS)) + 1
var/coord_col = "+[col-1]"
var/coord_col_offset = 4 + 2 * col
var/coord_row = "[row ? -row : "+0"]"
return "WEST[coord_col]:[coord_col_offset],NORTH[coord_row]:-6"
/datum/hud/proc/SetButtonCoords(obj/screen/button,number)
var/row = round((number-1)/AB_MAX_COLUMNS)
var/col = ((number - 1)%(AB_MAX_COLUMNS)) + 1
var/x_offset = 32*(col-1) + 4 + 2*col
var/y_offset = -32*(row+1) + 26
var/matrix/M = matrix()
M.Translate(x_offset,y_offset)
button.transform = M
| 412 | 0.949088 | 1 | 0.949088 | game-dev | MEDIA | 0.821519 | game-dev | 0.962927 | 1 | 0.962927 |
knewjade/solution-finder | 6,205 | src/main/java/common/datastore/blocks/LongLongPieces.java | package common.datastore.blocks;
import common.comparator.PiecesNumberComparator;
import core.mino.Piece;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
// max <= 44であること
public class LongLongPieces implements Pieces, Comparable<LongLongPieces> {
private static final long[] SCALE = new long[22];
static {
for (int index = 0; index < SCALE.length; index++)
SCALE[index] = pow(index);
}
private static long pow(int number) {
long value = 1L;
for (int count = 0; count < number; count++)
value *= 7L;
return value;
}
private static long getScale(int index) {
return SCALE[index];
}
private static long parse(long pieces, List<Piece> blocks, int startIndex) {
for (int index = 0; index < blocks.size(); index++) {
Piece piece = blocks.get(index);
int scaleIndex = startIndex + index;
pieces += getScale(scaleIndex) * piece.getNumber();
}
return pieces;
}
private static int toHash(long pieces) {
return (int) (pieces ^ (pieces >>> 32));
}
private final long lowPieces;
private final long highPieces;
private final int max;
public LongLongPieces() {
this.lowPieces = 0L;
this.highPieces = 0L;
this.max = 0;
}
public LongLongPieces(Piece... pieces) {
this(Arrays.asList(pieces));
}
public LongLongPieces(Pieces pieces) {
this(pieces.blockStream());
}
public LongLongPieces(List<Piece> pieces) {
int size = pieces.size();
assert size <= 44;
if (size <= 22) {
this.lowPieces = parse(0L, pieces, 0);
this.highPieces = 0L;
this.max = size;
} else {
this.lowPieces = parse(0L, pieces.subList(0, 22), 0);
this.highPieces = parse(0L, pieces.subList(22, size), 0);
this.max = size;
}
}
private LongLongPieces(Stream<Piece> blocks) {
this(blocks.collect(Collectors.toList()));
}
private LongLongPieces(LongLongPieces parent, List<Piece> pieces) {
this(parent, pieces.stream());
}
private LongLongPieces(LongLongPieces parent, Piece piece) {
this(parent, Stream.of(piece));
}
private LongLongPieces(LongLongPieces parent, Stream<Piece> blocks) {
this(Stream.concat(parent.blockStream(), blocks));
}
@Override
public List<Piece> getPieces() {
ArrayList<Piece> pieces = new ArrayList<>();
{
long value = this.lowPieces;
for (int count = 0; count < Math.min(max, 22); count++) {
Piece piece = Piece.getBlock((int) (value % 7));
pieces.add(piece);
value = value / 7;
}
assert value == 0;
}
{
long value = this.highPieces;
for (int count = 22; count < max; count++) {
Piece piece = Piece.getBlock((int) (value % 7));
pieces.add(piece);
value = value / 7;
}
assert value == 0;
}
return pieces;
}
@Override
public Stream<Piece> blockStream() {
Stream.Builder<Piece> builder = Stream.builder();
{
long value = lowPieces;
for (int count = 0; count < Math.min(max, 22); count++) {
Piece piece = Piece.getBlock((int) (value % 7));
builder.accept(piece);
value = value / 7;
}
assert value == 0;
}
{
long value = highPieces;
for (int count = 22; count < max; count++) {
Piece piece = Piece.getBlock((int) (value % 7));
builder.accept(piece);
value = value / 7;
}
assert value == 0;
}
return builder.build();
}
@Override
public Piece[] getPieceArray() {
Piece[] pieces = new Piece[max];
{
long value = this.lowPieces;
for (int index = 0; index < Math.min(max, 22); index++) {
Piece piece = Piece.getBlock((int) (value % 7));
pieces[index] = piece;
value = value / 7;
}
assert value == 0;
}
{
long value = this.highPieces;
for (int index = 22; index < max; index++) {
Piece piece = Piece.getBlock((int) (value % 7));
pieces[index] = piece;
value = value / 7;
}
assert value == 0;
}
return pieces;
}
@Override
public Pieces addAndReturnNew(List<Piece> pieces) {
return new LongLongPieces(this, pieces);
}
@Override
public Pieces addAndReturnNew(Piece piece) {
return new LongLongPieces(this, piece);
}
@Override
public Pieces addAndReturnNew(Stream<Piece> blocks) {
return new LongLongPieces(this, blocks);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
if (o instanceof LongLongPieces) {
LongLongPieces that = (LongLongPieces) o;
return lowPieces == that.lowPieces && highPieces == that.highPieces && max == that.max;
} else if (o instanceof Pieces) {
Pieces that = (Pieces) o;
return PiecesNumberComparator.comparePieces(this, that) == 0;
}
return false;
}
@Override
public int hashCode() {
return toHash(highPieces) ^ toHash(lowPieces) >>> 23;
}
@Override
public int compareTo(LongLongPieces o) {
{
int compare = Long.compare(this.lowPieces, o.lowPieces);
if (compare != 0L) {
return compare;
}
}
return Long.compare(this.highPieces, o.highPieces);
}
@Override
public String toString() {
return String.format("LongLongPieces{%s,%s}", lowPieces, highPieces);
}
}
| 412 | 0.76781 | 1 | 0.76781 | game-dev | MEDIA | 0.49595 | game-dev | 0.713356 | 1 | 0.713356 |
Waterdish/Shipwright-Android | 23,058 | soh/src/overlays/actors/ovl_En_Du/z_en_du.c | #include "z_en_du.h"
#include "objects/object_du/object_du.h"
#include "scenes/overworld/spot18/spot18_scene.h"
#include "soh/OTRGlobals.h"
#include "soh/Enhancements/game-interactor/GameInteractor_Hooks.h"
#define FLAGS (ACTOR_FLAG_ATTENTION_ENABLED | ACTOR_FLAG_FRIENDLY | ACTOR_FLAG_UPDATE_DURING_OCARINA)
void EnDu_Init(Actor* thisx, PlayState* play);
void EnDu_Destroy(Actor* thisx, PlayState* play);
void EnDu_Update(Actor* thisx, PlayState* play);
void EnDu_Draw(Actor* thisx, PlayState* play);
void func_809FE3B4(EnDu* this, PlayState* play);
void func_809FE3C0(EnDu* this, PlayState* play);
void func_809FE638(EnDu* this, PlayState* play);
void func_809FE890(EnDu* this, PlayState* play);
void func_809FE4A4(EnDu* this, PlayState* play);
void func_809FE6CC(EnDu* this, PlayState* play);
void func_809FE740(EnDu* this, PlayState* play);
void func_809FE798(EnDu* this, PlayState* play);
void func_809FEC14(EnDu* this, PlayState* play);
void func_809FEC70(EnDu* this, PlayState* play);
void func_809FECE4(EnDu* this, PlayState* play);
void func_809FEB08(EnDu* this, PlayState* play);
const ActorInit En_Du_InitVars = {
ACTOR_EN_DU,
ACTORCAT_NPC,
FLAGS,
OBJECT_DU,
sizeof(EnDu),
(ActorFunc)EnDu_Init,
(ActorFunc)EnDu_Destroy,
(ActorFunc)EnDu_Update,
(ActorFunc)EnDu_Draw,
NULL,
};
static ColliderCylinderInit sCylinderInit = {
{
COLTYPE_NONE,
AT_NONE,
AC_NONE,
OC1_ON | OC1_TYPE_ALL,
OC2_TYPE_2,
COLSHAPE_CYLINDER,
},
{
ELEMTYPE_UNK0,
{ 0x00000000, 0x00, 0x00 },
{ 0x00000000, 0x00, 0x00 },
TOUCH_NONE,
BUMP_NONE,
OCELEM_ON,
},
{ 20, 46, 0, { 0, 0, 0 } },
};
static CollisionCheckInfoInit2 sColChkInfoInit = {
0, 0, 0, 0, MASS_IMMOVABLE,
};
typedef enum {
/* 0 */ ENDU_ANIM_0,
/* 1 */ ENDU_ANIM_1,
/* 2 */ ENDU_ANIM_2,
/* 3 */ ENDU_ANIM_3,
/* 4 */ ENDU_ANIM_4,
/* 5 */ ENDU_ANIM_5,
/* 6 */ ENDU_ANIM_6,
/* 7 */ ENDU_ANIM_7,
/* 8 */ ENDU_ANIM_8,
/* 9 */ ENDU_ANIM_9,
/* 10 */ ENDU_ANIM_10,
/* 11 */ ENDU_ANIM_11,
/* 12 */ ENDU_ANIM_12,
/* 13 */ ENDU_ANIM_13,
/* 14 */ ENDU_ANIM_14
} EnDuAnimation;
static AnimationInfo sAnimationInfo[] = {
{ &gDaruniaIdleAnim, 1.0f, 0.0f, -1.0f, ANIMMODE_LOOP, 0.0f },
{ &gDaruniaIdleAnim, 1.0f, 0.0f, -1.0f, ANIMMODE_LOOP, -10.0f },
{ &gDaruniaItemGiveAnim, 1.0f, 0.0f, -1.0f, ANIMMODE_LOOP, -10.0f },
{ &gDaruniaItemGiveIdleAnim, 1.0f, 0.0f, -1.0f, ANIMMODE_LOOP, -10.0f },
{ &gDaruniaHitLinkAnim, 1.0f, 0.0f, -1.0f, ANIMMODE_LOOP, -10.0f },
{ &gDaruniaHitBreastAnim, 1.0f, 0.0f, -1.0f, ANIMMODE_LOOP, -10.0f },
{ &gDaruniaStandUpAfterFallingAnim, 1.0f, 0.0f, -1.0f, ANIMMODE_LOOP, -10.0f },
{ &gDaruniaDancingLoop1Anim, 1.0f, 0.0f, -1.0f, ANIMMODE_ONCE, -10.0f },
{ &gDaruniaDancingLoop1Anim, 1.0f, 0.0f, -1.0f, ANIMMODE_ONCE, 0.0f },
{ &gDaruniaDancingLoop2Anim, 1.0f, 0.0f, -1.0f, ANIMMODE_ONCE, 0.0f },
{ &gDaruniaDancingLoop3Anim, 1.0f, 0.0f, -1.0f, ANIMMODE_ONCE, 0.0f },
{ &gDaruniaWrongSongAnim, 1.0f, 0.0f, -1.0f, ANIMMODE_ONCE, 0.0f },
{ &gDaruniaWrongSongEndAnim, 1.0f, 0.0f, -1.0f, ANIMMODE_LOOP, 0.0f },
{ &gDaruniaDancingLoop4Anim, 1.0f, 0.0f, -1.0f, ANIMMODE_ONCE, 0.0f },
{ &gDaruniaDancingEndAnim, 1.0f, 0.0f, -1.0f, ANIMMODE_ONCE, -6.0f },
};
// #region SOH [Enhancement] Only animations too fast need to be slowed down, otherwise not touched
static AnimationInfo sAnimationInfoFix[] = {
{ NULL },
{ NULL },
{ NULL },
{ NULL },
{ NULL },
{ NULL },
{ NULL },
{ &gDaruniaDancingLoop1Anim, 0.78f, 0.0f, -1.0f, ANIMMODE_ONCE, -10.0f }, //
{ &gDaruniaDancingLoop1Anim, 0.77f, 0.0f, -1.0f, ANIMMODE_ONCE, 0.0f }, // hop
{ &gDaruniaDancingLoop2Anim, 0.78f, 0.0f, -1.0f, ANIMMODE_ONCE, 0.0f }, // from hop to spin
{ &gDaruniaDancingLoop3Anim, 0.77f, 0.0f, -1.0f, ANIMMODE_ONCE, 0.0f }, // spin
{ NULL },
{ NULL },
{ &gDaruniaDancingLoop4Anim, 0.78f, 0.0f, -1.0f, ANIMMODE_ONCE, 0.0f }, // from spin to hop
{ NULL },
};
// #endregion
void EnDu_SetupAction(EnDu* this, EnDuActionFunc actionFunc) {
this->actionFunc = actionFunc;
}
u16 func_809FDC38(PlayState* play, Actor* actor) {
u16 reaction = Text_GetFaceReaction(play, 0x21);
if (reaction != 0) {
return reaction;
}
if (CUR_UPG_VALUE(UPG_STRENGTH) != 0) {
if (CHECK_QUEST_ITEM(QUEST_GORON_RUBY)) {
return 0x301E;
} else {
return 0x301D;
}
}
if (Flags_GetInfTable(INFTABLE_113)) {
return 0x301B;
} else {
return 0x301A;
}
}
s16 func_809FDCDC(PlayState* play, Actor* actor) {
switch (Message_GetState(&play->msgCtx)) {
case TEXT_STATE_NONE:
case TEXT_STATE_DONE_HAS_NEXT:
break;
case TEXT_STATE_CLOSING:
switch (actor->textId) {
case 0x301A:
Flags_SetInfTable(INFTABLE_113);
break;
case 0x301C:
case 0x301F:
return NPC_TALK_STATE_ACTION;
case 0x3020:
Flags_SetEventChkInf(EVENTCHKINF_22);
break;
}
return 0;
case TEXT_STATE_DONE_FADING:
case TEXT_STATE_CHOICE:
case TEXT_STATE_EVENT:
break;
case TEXT_STATE_DONE:
if (Message_ShouldAdvance(play)) {
return NPC_TALK_STATE_ITEM_GIVEN;
}
break;
case TEXT_STATE_SONG_DEMO_DONE:
case TEXT_STATE_8:
case TEXT_STATE_9:
break;
}
return NPC_TALK_STATE_TALKING;
}
s32 func_809FDDB4(EnDu* this, PlayState* play) {
if (play->sceneNum == SCENE_GORON_CITY && LINK_IS_CHILD) {
return 1;
} else if (play->sceneNum == SCENE_FIRE_TEMPLE && !Flags_GetInfTable(INFTABLE_SPOKE_TO_DARUNIA_IN_FIRE_TEMPLE) &&
LINK_IS_ADULT) {
return 1;
}
return 0;
}
void func_809FDE24(EnDu* this, PlayState* play) {
Player* player = GET_PLAYER(play);
s16 trackingMode = NPC_TRACKING_PLAYER_AUTO_TURN;
if (this->interactInfo.talkState == NPC_TALK_STATE_IDLE) {
trackingMode = NPC_TRACKING_NONE;
}
if (this->actionFunc == func_809FE890) {
trackingMode = NPC_TRACKING_NONE;
}
this->interactInfo.trackPos = player->actor.world.pos;
this->interactInfo.yOffset = 10.0f;
Npc_TrackPoint(&this->actor, &this->interactInfo, 3, trackingMode);
}
void func_809FDE9C(EnDu* this) {
if (this->blinkTimer > 0) {
this->blinkTimer--;
} else {
this->blinkTimer = 0;
}
if (this->blinkTimer < 3) {
this->eyeTexIndex = this->blinkTimer;
}
switch (this->unk_1EC) {
case 0:
if (this->blinkTimer == 0) {
this->blinkTimer = Rand_S16Offset(30, 30);
}
break;
case 1:
if (this->blinkTimer == 0) {
this->eyeTexIndex = 2;
}
break;
case 2:
if (this->blinkTimer == 0) {
this->eyeTexIndex = 2;
}
break;
case 3:
if (this->blinkTimer == 0) {
this->eyeTexIndex = 0;
}
break;
}
switch (this->unk_1ED) {
case 1:
this->mouthTexIndex = 1;
break;
case 2:
this->mouthTexIndex = 2;
break;
case 3:
this->mouthTexIndex = 3;
break;
default:
this->mouthTexIndex = 0;
break;
}
if (this->unk_1EE == 1) {
this->noseTexIndex = 1;
} else {
this->noseTexIndex = 0;
}
}
void func_809FDFC0(CsCmdActorCue* csAction, Vec3f* dst) {
dst->x = csAction->startPos.x;
dst->y = csAction->startPos.y;
dst->z = csAction->startPos.z;
}
void func_809FE000(CsCmdActorCue* csAction, Vec3f* dst) {
dst->x = csAction->endPos.x;
dst->y = csAction->endPos.y;
dst->z = csAction->endPos.z;
}
void func_809FE040(EnDu* this) {
s32 animationIndices[] = {
ENDU_ANIM_8, ENDU_ANIM_8, ENDU_ANIM_8, ENDU_ANIM_8, ENDU_ANIM_9, ENDU_ANIM_10, ENDU_ANIM_10, ENDU_ANIM_13,
};
if (Animation_OnFrame(&this->skelAnime, this->skelAnime.endFrame)) {
this->unk_1E6++;
if (this->unk_1E6 >= 8) {
this->unk_1E6 = 0;
}
// #region SOH[Enhancement]
if (CVarGetInteger(CVAR_ENHANCEMENT("FixDaruniaDanceSpeed"), 1)) {
Animation_ChangeByInfo(&this->skelAnime, sAnimationInfoFix, animationIndices[this->unk_1E6]);
// #endregion
} else {
Animation_ChangeByInfo(&this->skelAnime, sAnimationInfo, animationIndices[this->unk_1E6]);
}
}
}
void func_809FE104(EnDu* this) {
s32 animationIndices[] = {
ENDU_ANIM_8,
ENDU_ANIM_8,
ENDU_ANIM_11,
ENDU_ANIM_12,
};
if (this->unk_1E6 < 4) {
if (Animation_OnFrame(&this->skelAnime, this->skelAnime.endFrame)) {
this->unk_1E6++;
if (this->unk_1E6 < 4) {
// #region SOH[Enhancement]
if (CVarGetInteger(CVAR_ENHANCEMENT("FixDaruniaDanceSpeed"), 1) && this->unk_1E6 <= 1) {
Animation_ChangeByInfo(&this->skelAnime, sAnimationInfoFix, animationIndices[this->unk_1E6]);
// #endregion
} else {
Animation_ChangeByInfo(&this->skelAnime, sAnimationInfo, animationIndices[this->unk_1E6]);
}
}
}
}
}
void EnDu_Init(Actor* thisx, PlayState* play) {
EnDu* this = (EnDu*)thisx;
s32 pad;
ActorShape_Init(&this->actor.shape, 0.0f, ActorShadow_DrawCircle, 30.0f);
SkelAnime_InitFlex(play, &this->skelAnime, &gDaruniaSkel, NULL, 0, 0, 0);
Collider_InitCylinder(play, &this->collider);
Collider_SetCylinder(play, &this->collider, &this->actor, &sCylinderInit);
CollisionCheck_SetInfo2(&this->actor.colChkInfo, DamageTable_Get(0x16), &sColChkInfoInit);
if (func_809FDDB4(this, play) == 0) {
Actor_Kill(&this->actor);
return;
}
Animation_ChangeByInfo(&this->skelAnime, sAnimationInfo, ENDU_ANIM_0);
Actor_SetScale(&this->actor, 0.01f);
this->actor.targetMode = 1;
this->interactInfo.talkState = NPC_TALK_STATE_IDLE;
if (gSaveContext.cutsceneIndex >= 0xFFF0) {
play->csCtx.segment = SEGMENTED_TO_VIRTUAL(gGoronCityDarunia01Cs);
gSaveContext.cutsceneTrigger = 1;
EnDu_SetupAction(this, func_809FE890);
} else if (play->sceneNum == SCENE_FIRE_TEMPLE) {
EnDu_SetupAction(this, func_809FE638);
} else if (!LINK_IS_ADULT) {
EnDu_SetupAction(this, func_809FE3C0);
} else {
EnDu_SetupAction(this, func_809FE3B4);
}
}
void EnDu_Destroy(Actor* thisx, PlayState* play) {
EnDu* this = (EnDu*)thisx;
SkelAnime_Free(&this->skelAnime, play);
Collider_DestroyCylinder(play, &this->collider);
}
void func_809FE3B4(EnDu* this, PlayState* play) {
}
void func_809FE3C0(EnDu* this, PlayState* play) {
Player* player = GET_PLAYER(play);
if (player->stateFlags2 & PLAYER_STATE2_ATTEMPT_PLAY_FOR_ACTOR) {
func_8010BD88(play, OCARINA_ACTION_CHECK_SARIA);
player->stateFlags2 |= PLAYER_STATE2_PLAY_FOR_ACTOR;
player->unk_6A8 = &this->actor;
EnDu_SetupAction(this, func_809FE4A4);
return;
}
if (this->interactInfo.talkState == NPC_TALK_STATE_ACTION) {
Player_SetCsActionWithHaltedActors(play, &this->actor, 7);
this->interactInfo.talkState = NPC_TALK_STATE_IDLE;
}
if (this->actor.xzDistToPlayer < 116.0f + this->collider.dim.radius) {
player->stateFlags2 |= PLAYER_STATE2_NEAR_OCARINA_ACTOR;
}
}
void func_809FE4A4(EnDu* this, PlayState* play) {
Player* player = GET_PLAYER(play);
if (play->msgCtx.ocarinaMode == OCARINA_MODE_04) {
play->msgCtx.ocarinaMode = OCARINA_MODE_00;
EnDu_SetupAction(this, func_809FE3C0);
} else if (play->msgCtx.ocarinaMode >= OCARINA_MODE_06) {
if (GameInteractor_Should(VB_PLAY_DARUNIAS_JOY_CS, true)) {
play->csCtx.segment = SEGMENTED_TO_VIRTUAL(gGoronCityDaruniaWrongCs);
gSaveContext.cutsceneTrigger = 1;
}
this->unk_1E8 = 1;
EnDu_SetupAction(this, func_809FE890);
play->msgCtx.ocarinaMode = OCARINA_MODE_04;
} else if (play->msgCtx.ocarinaMode == OCARINA_MODE_03) {
Audio_PlaySoundGeneral(NA_SE_SY_CORRECT_CHIME, &gSfxDefaultPos, 4, &gSfxDefaultFreqAndVolScale,
&gSfxDefaultFreqAndVolScale, &gSfxDefaultReverb);
if (GameInteractor_Should(VB_PLAY_DARUNIAS_JOY_CS, true)) {
play->csCtx.segment = SEGMENTED_TO_VIRTUAL(gGoronCityDaruniaCorrectCs);
gSaveContext.cutsceneTrigger = 1;
}
this->unk_1E8 = 0;
EnDu_SetupAction(this, func_809FE890);
play->msgCtx.ocarinaMode = OCARINA_MODE_04;
} else {
player->stateFlags2 |= PLAYER_STATE2_NEAR_OCARINA_ACTOR;
}
}
void func_809FE638(EnDu* this, PlayState* play) {
Player* player = GET_PLAYER(play);
if (!(player->stateFlags1 & PLAYER_STATE1_IN_CUTSCENE)) {
OnePointCutscene_Init(play, 3330, -99, &this->actor, MAIN_CAM);
player->actor.shape.rot.y = player->actor.world.rot.y = this->actor.world.rot.y + 0x7FFF;
Audio_PlayFanfare(NA_BGM_APPEAR);
EnDu_SetupAction(this, func_809FE6CC);
this->unk_1E2 = 0x32;
}
}
void func_809FE6CC(EnDu* this, PlayState* play) {
s16 phi_v1;
if (this->unk_1E2 == 0) {
phi_v1 = 0;
} else {
this->unk_1E2--;
phi_v1 = this->unk_1E2;
}
if (phi_v1 == 0) {
this->actor.textId = 0x3039;
Message_StartTextbox(play, this->actor.textId, NULL);
this->interactInfo.talkState = NPC_TALK_STATE_TALKING;
EnDu_SetupAction(this, func_809FE740);
}
}
void func_809FE740(EnDu* this, PlayState* play) {
if (this->interactInfo.talkState == NPC_TALK_STATE_IDLE) {
func_8005B1A4(GET_ACTIVE_CAM(play));
this->unk_1E2 = 0x5A;
EnDu_SetupAction(this, func_809FE798);
}
}
void func_809FE798(EnDu* this, PlayState* play) {
s32 phi_v0;
if (this->unk_1E2 == 0) {
phi_v0 = 0;
} else {
this->unk_1E2--;
phi_v0 = this->unk_1E2;
}
if (phi_v0 != 0) {
switch (this->unk_1E2) {
case 0x50:
Audio_PlayActorSound2(&this->actor, NA_SE_EV_CHAIN_KEY_UNLOCK_B);
break;
case 0x3C:
Audio_PlayActorSound2(&this->actor, NA_SE_EV_SLIDE_DOOR_OPEN);
break;
case 0xF:
Audio_PlayActorSound2(&this->actor, NA_SE_EV_SLIDE_DOOR_CLOSE);
break;
case 5:
Audio_PlayActorSound2(&this->actor, NA_SE_EV_STONE_BOUND);
break;
}
if (this->unk_1E2 >= 0x3D) {
this->actor.world.pos.x -= 10.0f;
}
} else {
Actor_Kill(&this->actor);
Flags_SetInfTable(INFTABLE_SPOKE_TO_DARUNIA_IN_FIRE_TEMPLE);
}
}
void func_809FE890(EnDu* this, PlayState* play) {
f32 frame;
Vec3f startPos;
Vec3f endPos;
Vec3f velocity = { 0.0f, 0.0f, 0.0f };
CsCmdActorCue* csAction;
if (play->csCtx.state == CS_STATE_IDLE) {
Player_SetCsActionWithHaltedActors(play, &this->actor, 1);
EnDu_SetupAction(this, func_809FEB08);
return;
}
csAction = play->csCtx.npcActions[2];
if (csAction != NULL) {
func_809FDFC0(csAction, &startPos);
func_809FE000(csAction, &endPos);
if (this->unk_1EA == 0) {
func_809FDFC0(csAction, &startPos);
this->actor.world.pos = startPos;
}
if (this->unk_1EA != csAction->action) {
if (csAction->action == 1) {
Animation_ChangeByInfo(&this->skelAnime, sAnimationInfo, ENDU_ANIM_1);
}
if (csAction->action == 7 || csAction->action == 8) {
this->unk_1E6 = 0;
// #region SOH[Enhancement]
if (CVarGetInteger(CVAR_ENHANCEMENT("FixDaruniaDanceSpeed"), 1)) {
Animation_ChangeByInfo(&this->skelAnime, sAnimationInfoFix, ENDU_ANIM_7);
// #endregion
} else {
Animation_ChangeByInfo(&this->skelAnime, sAnimationInfo, ENDU_ANIM_7);
}
}
this->unk_1EA = csAction->action;
if (this->unk_1EA == 7) {
this->blinkTimer = 11;
this->unk_1EC = 2;
this->unk_1ED = 2;
this->unk_1EE = 1;
}
if (this->unk_1EA == 8) {
this->blinkTimer = 11;
this->unk_1EC = 3;
this->unk_1ED = 3;
this->unk_1EE = 0;
}
}
if (this->unk_1EA == 7) {
func_809FE040(this);
}
if (this->unk_1EA == 8) {
func_809FE104(this);
}
this->actor.shape.rot.x = csAction->urot.x;
this->actor.shape.rot.y = csAction->urot.y;
this->actor.shape.rot.z = csAction->urot.z;
this->actor.velocity = velocity;
if (play->csCtx.frames < csAction->endFrame) {
frame = csAction->endFrame - csAction->startFrame;
this->actor.velocity.x = (endPos.x - startPos.x) / frame;
this->actor.velocity.y = (endPos.y - startPos.y) / frame;
this->actor.velocity.y += this->actor.gravity;
if (this->actor.velocity.y < this->actor.minVelocityY) {
this->actor.velocity.y = this->actor.minVelocityY;
}
this->actor.velocity.z = (endPos.z - startPos.z) / frame;
}
}
}
void func_809FEB08(EnDu* this, PlayState* play) {
this->blinkTimer = 11;
this->unk_1EC = 0;
this->unk_1ED = 0;
this->unk_1EE = 0;
if (this->unk_1E8 == 1) {
Player_SetCsActionWithHaltedActors(play, &this->actor, 7);
Animation_ChangeByInfo(&this->skelAnime, sAnimationInfo, ENDU_ANIM_1);
EnDu_SetupAction(this, func_809FE3C0);
return;
}
if (GameInteractor_Should(VB_BE_ELIGIBLE_FOR_DARUNIAS_JOY_REWARD, CUR_UPG_VALUE(UPG_STRENGTH) <= 0)) {
Flags_SetRandomizerInf(RAND_INF_DARUNIAS_JOY);
this->actor.textId = 0x301C;
EnDu_SetupAction(this, func_809FEC14);
} else {
this->actor.textId = 0x301F;
EnDu_SetupAction(this, func_809FE3C0);
}
Message_StartTextbox(play, this->actor.textId, NULL);
Animation_ChangeByInfo(&this->skelAnime, sAnimationInfo, ENDU_ANIM_14);
this->interactInfo.talkState = NPC_TALK_STATE_TALKING;
}
void func_809FEC14(EnDu* this, PlayState* play) {
if (this->interactInfo.talkState == NPC_TALK_STATE_ACTION) {
Player_SetCsActionWithHaltedActors(play, &this->actor, 7);
EnDu_SetupAction(this, func_809FEC70);
func_809FEC70(this, play);
}
}
void func_809FEC70(EnDu* this, PlayState* play) {
if (Actor_HasParent(&this->actor, play) || !GameInteractor_Should(VB_GIVE_ITEM_STRENGTH_1, true)) {
this->actor.parent = NULL;
EnDu_SetupAction(this, func_809FECE4);
} else {
f32 xzRange = this->actor.xzDistToPlayer + 1.0f;
Actor_OfferGetItem(&this->actor, play, GI_BRACELET, xzRange, fabsf(this->actor.yDistToPlayer) + 1.0f);
}
}
void func_809FECE4(EnDu* this, PlayState* play) {
if (this->interactInfo.talkState == NPC_TALK_STATE_ITEM_GIVEN) {
this->interactInfo.talkState = NPC_TALK_STATE_IDLE;
EnDu_SetupAction(this, func_809FE3C0);
}
}
void EnDu_Update(Actor* thisx, PlayState* play) {
EnDu* this = (EnDu*)thisx;
s32 pad;
Collider_UpdateCylinder(&this->actor, &this->collider);
CollisionCheck_SetOC(play, &play->colChkCtx, &this->collider.base);
if (this->skelAnime.animation == &gDaruniaDancingEndAnim &&
Animation_OnFrame(&this->skelAnime, this->skelAnime.endFrame)) {
Animation_ChangeByInfo(&this->skelAnime, sAnimationInfo, ENDU_ANIM_1);
}
SkelAnime_Update(&this->skelAnime);
func_809FDE9C(this);
func_809FDE24(this, play);
if (this->actionFunc == func_809FE890) {
this->actor.world.pos.x += this->actor.velocity.x;
this->actor.world.pos.y += this->actor.velocity.y;
this->actor.world.pos.z += this->actor.velocity.z;
} else {
Actor_UpdatePos(&this->actor);
}
Actor_UpdateBgCheckInfo(play, &this->actor, 0.0f, 0.0f, 0.0f, 4);
if (this->actionFunc != func_809FE4A4) {
Npc_UpdateTalking(play, &this->actor, &this->interactInfo.talkState, this->collider.dim.radius + 116.0f,
func_809FDC38, func_809FDCDC);
}
this->actionFunc(this, play);
}
s32 EnDu_OverrideLimbDraw(PlayState* play, s32 limbIndex, Gfx** dList, Vec3f* pos, Vec3s* rot, void* thisx, Gfx** gfx) {
EnDu* this = (EnDu*)thisx;
Vec3s sp1C;
if (limbIndex == 16) {
Matrix_Translate(2400.0f, 0.0f, 0.0f, MTXMODE_APPLY);
sp1C = this->interactInfo.headRot;
Matrix_RotateX(BINANG_TO_RAD(sp1C.y), MTXMODE_APPLY);
Matrix_RotateZ(BINANG_TO_RAD(sp1C.x), MTXMODE_APPLY);
Matrix_Translate(-2400.0f, 0.0f, 0.0f, MTXMODE_APPLY);
}
if (limbIndex == 8) {
sp1C = this->interactInfo.torsoRot;
Matrix_RotateY(BINANG_TO_RAD(sp1C.y), MTXMODE_APPLY);
Matrix_RotateX(BINANG_TO_RAD(sp1C.x), MTXMODE_APPLY);
}
return 0;
}
void EnDu_PostLimbDraw(PlayState* play, s32 limbIndex, Gfx** dList, Vec3s* rot, void* thisx, Gfx** gfx) {
EnDu* this = (EnDu*)thisx;
Vec3f D_809FF40C = { 0.0f, -1000.0f, 0.0f };
if (limbIndex == 16) {
Matrix_MultVec3f(&D_809FF40C, &this->actor.focus.pos);
}
}
void EnDu_Draw(Actor* thisx, PlayState* play) {
static void* eyeTextures[] = {
gDaruniaEyeOpenTex,
gDaruniaEyeOpeningTex,
gDaruniaEyeShutTex,
gDaruniaEyeClosingTex,
};
static void* mouthTextures[] = {
gDaruniaMouthSeriousTex,
gDaruniaMouthGrinningTex,
gDaruniaMouthOpenTex,
gDaruniaMouthHappyTex,
};
static void* noseTextures[] = {
gDaruniaNoseSeriousTex,
gDaruniaNoseHappyTex,
};
EnDu* this = (EnDu*)thisx;
OPEN_DISPS(play->state.gfxCtx);
gSPSegment(POLY_OPA_DISP++, 0x08, SEGMENTED_TO_VIRTUAL(eyeTextures[this->eyeTexIndex]));
gSPSegment(POLY_OPA_DISP++, 0x09, SEGMENTED_TO_VIRTUAL(mouthTextures[this->mouthTexIndex]));
gSPSegment(POLY_OPA_DISP++, 0x0A, SEGMENTED_TO_VIRTUAL(noseTextures[this->noseTexIndex]));
func_80034BA0(play, &this->skelAnime, EnDu_OverrideLimbDraw, EnDu_PostLimbDraw, &this->actor, 255);
CLOSE_DISPS(play->state.gfxCtx);
}
| 412 | 0.871691 | 1 | 0.871691 | game-dev | MEDIA | 0.968195 | game-dev | 0.978672 | 1 | 0.978672 |
TeamLapen/Vampirism | 2,581 | src/main/java/de/teamlapen/vampirism/data/provider/parent/SkillTreeProvider.java | package de.teamlapen.vampirism.data.provider.parent;
import com.google.gson.JsonElement;
import com.mojang.serialization.JsonOps;
import de.teamlapen.vampirism.entity.player.skills.SkillTreeConfiguration;
import net.minecraft.core.HolderLookup;
import net.minecraft.data.CachedOutput;
import net.minecraft.data.DataProvider;
import net.minecraft.data.PackOutput;
import net.minecraft.resources.RegistryOps;
import net.minecraft.resources.ResourceLocation;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
public abstract class SkillTreeProvider implements DataProvider {
protected final PackOutput.PathProvider pathProvider;
private final CompletableFuture<HolderLookup.Provider> lookupProvider;
private final String modId;
public SkillTreeProvider(PackOutput packOutput, CompletableFuture<HolderLookup.Provider> lookupProvider, String modId) {
this.pathProvider = packOutput.createPathProvider(PackOutput.Target.DATA_PACK, "vampirism/configured_skill_tree");
this.lookupProvider = lookupProvider;
this.modId = modId;
}
@Override
public @NotNull CompletableFuture<?> run(@NotNull CachedOutput pOutput) {
return this.lookupProvider.thenCompose(provider -> {
Set<ResourceLocation> set = new HashSet<>();
List<CompletableFuture<?>> list = new ArrayList<>();
RegistryOps<JsonElement> ops = RegistryOps.create(JsonOps.INSTANCE, provider);
this.buildSkillTrees(provider, (id, skillTree) -> {
if (!set.add(id)) {
throw new IllegalStateException("Duplicate skill tree " + id);
} else {
list.add(DataProvider.saveStable(pOutput, provider, SkillTreeConfiguration.CODEC, skillTree, pathProvider.json(id)));
}
return id;
});
return CompletableFuture.allOf(list.toArray(CompletableFuture[]::new));
});
}
protected abstract void buildSkillTrees(HolderLookup.Provider provider, @NotNull SkillTreeOutput output);
@Override
public @NotNull String getName() {
return "Skill tree config";
}
protected @NotNull ResourceLocation modId(@NotNull String string) {
return ResourceLocation.fromNamespaceAndPath(this.modId, string);
}
public interface SkillTreeOutput {
ResourceLocation accept(ResourceLocation id, SkillTreeConfiguration skillTree);
}
}
| 412 | 0.932063 | 1 | 0.932063 | game-dev | MEDIA | 0.929831 | game-dev | 0.969963 | 1 | 0.969963 |
Kengxxiao/Punishing_GrayRaven_Tab | 2,718 | lua/xui/xuisocial/privatechatmodel/itemmodel/XUiGridTishi.lua | XUiGridTishi = XClass()
function XUiGridTishi:Ctor(ui)
self.GameObject = ui.gameObject
self.Transform = ui.transform
self:InitAutoScript()
end
-- auto
-- Automatic generation of code, forbid to edit
function XUiGridTishi:InitAutoScript()
self:AutoInitUi()
self.SpecialSoundMap = {}
self:AutoAddListener()
end
function XUiGridTishi:AutoInitUi()
self.TxtInfo = self.Transform:Find("ImageBg/TxtInfo"):GetComponent("Text")
-- self.TxtTime = XUiHelper.TryGetComponent(self.Transform, "TxtTime", "Text")
end
function XUiGridTishi:GetAutoKey(uiNode, eventName)
if not uiNode then
return
end
return eventName .. uiNode:GetHashCode()
end
function XUiGridTishi:RegisterListener(uiNode, eventName, func)
local key = self:GetAutoKey(uiNode, eventName)
if not key then
return
end
local listener = self.AutoCreateListeners[key]
if listener ~= nil then
uiNode[eventName]:RemoveListener(listener)
end
if func ~= nil then
if type(func) ~= "function" then
XLog.Error("XUiGridTishi:RegisterListener: func is not a function")
end
listener = function(...)
XSoundManager.PlayBtnMusic(self.SpecialSoundMap[key], eventName)
func(self, ...)
end
uiNode[eventName]:AddListener(listener)
self.AutoCreateListeners[key] = listener
end
end
function XUiGridTishi:AutoAddListener()
self.AutoCreateListeners = {}
end
-- auto
function XUiGridTishi:Refresh(chatData)
self.CreateTime = chatData.CreateTime
self.SenderId = chatData.SenderId
-- self.TxtTime.text = chatData:GetSendTime()
local friend = XDataCenter.SocialManager.GetFriendInfo(chatData.TargetId)
local text = ""
-- if chatData:CheckIsSelfChat() then
-- if (chatData:GetGiftChatType() == GiftChatType.Send) then
-- text = CS.XTextManager.GetText("GiftMoneySendNotReceive", friend.Nickname, chatData.Content)
-- else
-- text = CS.XTextManager.GetText("GiftMoneySendHaveReceive", friend.Nickname, chatData.Content)
-- end
-- else
-- if (chatData:GetGiftChatType() == GiftChatType.Send) then
-- text = CS.XTextManager.GetText("GiftMoneyReceiveNotReceive", chatData.NickName, chatData.Content)
-- else
-- text = CS.XTextManager.GetText("GiftMoneyReceiveHaveReceive", chatData.NickName, chatData.Content)
-- end
-- end
self.TxtInfo.text = text
end
function XUiGridTishi:Show()
self.GameObject:SetActive(true)
end
function XUiGridTishi:Hide()
self.GameObject:SetActive(false)
end
function XUiGridTishi:SetShow( code )
self.GameObject:SetActive(code)
end | 412 | 0.730096 | 1 | 0.730096 | game-dev | MEDIA | 0.924537 | game-dev | 0.902252 | 1 | 0.902252 |
iiYese/aery | 4,866 | examples/in_range.rs | use aery::prelude::Up;
use aery::prelude::*;
use bevy::log;
use bevy::prelude::*;
#[derive(Component)]
struct MovingEntity {
direction: f32, // Movement direction along the x-axis, positive or negative.
}
// Define a relationship where multiple entities can be linked non-exclusively.
// Symmetry is not set in this example, it may arise from the implementation,
// when we set Poly relation from both sides.
#[derive(Relation)]
#[aery(Poly)]
struct InRange;
const RANGE_THRESHOLD: f32 = 100.0;
fn setup(mut commands: Commands) {
// Spawning two moving entities with initial positions and directions.
commands.spawn((
Name::new("Alice"),
MovingEntity { direction: 1.0 },
Transform::from_xyz(-150.0, 0.0, 0.0),
GlobalTransform::default(),
));
commands.spawn((
Name::new("Bob"),
MovingEntity { direction: -1.0 },
Transform::from_xyz(150.0, 0.0, 0.0),
GlobalTransform::default(),
));
}
fn move_entities(mut query: Query<(&mut Transform, &mut MovingEntity)>, time: Res<Time>) {
for (mut transform, mut moving_entity) in query.iter_mut() {
// Update the position based on direction and elapsed time.
transform.translation.x += moving_entity.direction * time.delta_secs() * 50.0;
// Reverse direction if the entity moves beyond the bounds.
if transform.translation.x > 200.0 || transform.translation.x < -200.0 {
moving_entity.direction *= -1.0;
}
}
}
fn set_relations(
mut commands: Commands,
time: Res<Time>,
mut last_time: Local<f32>,
in_range_abstains: Query<(Entity, &Transform), (With<MovingEntity>, Abstains<InRange>)>,
query_all: Query<(Entity, &Transform), With<MovingEntity>>,
) {
if time.elapsed_secs() - *last_time < 0.1 {
return;
}
*last_time = time.elapsed_secs();
in_range_abstains.iter().for_each(|(entity_a, pos_a)| {
query_all.iter().for_each(|(entity_b, pos_b)| {
if entity_a != entity_b
&& pos_a.translation.distance(pos_b.translation) <= RANGE_THRESHOLD
{
// Set the relation if the entities are in range.
commands.entity(entity_a).set::<InRange>(entity_b);
}
});
});
}
fn unset_relations(
mut commands: Commands,
time: Res<Time>,
mut last_time: Local<f32>,
in_range_participates: Query<(Entity, &Transform, Relations<InRange>), With<MovingEntity>>,
moving_entities: Query<(Entity, &Transform), With<MovingEntity>>,
) {
if time.elapsed_secs() - *last_time < 0.1 {
return;
}
*last_time = time.elapsed_secs();
in_range_participates
.iter()
.for_each(|(entity_a, pos_a, relations)| {
relations.join::<Up<InRange>>(&moving_entities).for_each(
|(entity_b, _): (Entity, &Transform)| {
if entity_a != entity_b {
// Remove the relation if the entities are no longer in range.
if let Ok((_, pos_b)) = moving_entities.get(entity_b) {
let distance = pos_a.translation.distance(pos_b.translation);
if distance > RANGE_THRESHOLD {
commands.entity(entity_a).unset::<InRange>(entity_b);
}
}
}
},
);
});
}
fn relation_set(set: Trigger<SetEvent<InRange>>, names: Query<&Name>) {
// Do something when a new "InRange" relationship is established.
let first = set.entity();
let second = set.event().target;
let first_name = names.get(first).unwrap();
let second_name = names.get(second).unwrap();
log::info!(
"{}({}) is now in range of {}({})",
first_name,
first,
second_name,
second
);
}
fn relation_remove(unset: Trigger<UnsetEvent<InRange>>, names: Query<&Name>) {
// Do something when an "InRange" relationship is removed.
let first = unset.entity();
let second = unset.event().target;
let first_name = names.get(first).unwrap();
let second_name = names.get(second).unwrap();
log::info!(
"{}({}) is no longer in range of {}({})",
first_name,
first,
second_name,
second
);
}
pub struct InRangePlugin;
impl Plugin for InRangePlugin {
fn build(&self, app: &mut App) {
app.register_relation::<InRange>();
app.add_systems(Update, (set_relations, unset_relations));
app.add_observer(relation_set);
app.add_observer(relation_remove);
}
}
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.add_plugins(InRangePlugin)
.add_systems(Update, move_entities)
.run();
}
| 412 | 0.649207 | 1 | 0.649207 | game-dev | MEDIA | 0.56093 | game-dev | 0.814005 | 1 | 0.814005 |
drhelius/Gearlynx | 28,101 | platforms/windows/dependencies/SDL2-2.30.6/include/SDL_rwops.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2024 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_rwops.h
*
* This file provides a general interface for SDL to read and write
* data streams. It can easily be extended to files, memory, etc.
*/
#ifndef SDL_rwops_h_
#define SDL_rwops_h_
#include "SDL_stdinc.h"
#include "SDL_error.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/* RWops Types */
#define SDL_RWOPS_UNKNOWN 0U /**< Unknown stream type */
#define SDL_RWOPS_WINFILE 1U /**< Win32 file */
#define SDL_RWOPS_STDFILE 2U /**< Stdio file */
#define SDL_RWOPS_JNIFILE 3U /**< Android asset */
#define SDL_RWOPS_MEMORY 4U /**< Memory stream */
#define SDL_RWOPS_MEMORY_RO 5U /**< Read-Only memory stream */
/**
* This is the read/write operation structure -- very basic.
*/
typedef struct SDL_RWops
{
/**
* Return the size of the file in this rwops, or -1 if unknown
*/
Sint64 (SDLCALL * size) (struct SDL_RWops * context);
/**
* Seek to \c offset relative to \c whence, one of stdio's whence values:
* RW_SEEK_SET, RW_SEEK_CUR, RW_SEEK_END
*
* \return the final offset in the data stream, or -1 on error.
*/
Sint64 (SDLCALL * seek) (struct SDL_RWops * context, Sint64 offset,
int whence);
/**
* Read up to \c maxnum objects each of size \c size from the data
* stream to the area pointed at by \c ptr.
*
* \return the number of objects read, or 0 at error or end of file.
*/
size_t (SDLCALL * read) (struct SDL_RWops * context, void *ptr,
size_t size, size_t maxnum);
/**
* Write exactly \c num objects each of size \c size from the area
* pointed at by \c ptr to data stream.
*
* \return the number of objects written, or 0 at error or end of file.
*/
size_t (SDLCALL * write) (struct SDL_RWops * context, const void *ptr,
size_t size, size_t num);
/**
* Close and free an allocated SDL_RWops structure.
*
* \return 0 if successful or -1 on write error when flushing data.
*/
int (SDLCALL * close) (struct SDL_RWops * context);
Uint32 type;
union
{
#if defined(__ANDROID__)
struct
{
void *asset;
} androidio;
#elif defined(__WIN32__) || defined(__GDK__)
struct
{
SDL_bool append;
void *h;
struct
{
void *data;
size_t size;
size_t left;
} buffer;
} windowsio;
#endif
#ifdef HAVE_STDIO_H
struct
{
SDL_bool autoclose;
FILE *fp;
} stdio;
#endif
struct
{
Uint8 *base;
Uint8 *here;
Uint8 *stop;
} mem;
struct
{
void *data1;
void *data2;
} unknown;
} hidden;
} SDL_RWops;
/**
* \name RWFrom functions
*
* Functions to create SDL_RWops structures from various data streams.
*/
/* @{ */
/**
* Use this function to create a new SDL_RWops structure for reading from
* and/or writing to a named file.
*
* The `mode` string is treated roughly the same as in a call to the C
* library's fopen(), even if SDL doesn't happen to use fopen() behind the
* scenes.
*
* Available `mode` strings:
*
* - "r": Open a file for reading. The file must exist.
* - "w": Create an empty file for writing. If a file with the same name
* already exists its content is erased and the file is treated as a new
* empty file.
* - "a": Append to a file. Writing operations append data at the end of the
* file. The file is created if it does not exist.
* - "r+": Open a file for update both reading and writing. The file must
* exist.
* - "w+": Create an empty file for both reading and writing. If a file with
* the same name already exists its content is erased and the file is
* treated as a new empty file.
* - "a+": Open a file for reading and appending. All writing operations are
* performed at the end of the file, protecting the previous content to be
* overwritten. You can reposition (fseek, rewind) the internal pointer to
* anywhere in the file for reading, but writing operations will move it
* back to the end of file. The file is created if it does not exist.
*
* **NOTE**: In order to open a file as a binary file, a "b" character has to
* be included in the `mode` string. This additional "b" character can either
* be appended at the end of the string (thus making the following compound
* modes: "rb", "wb", "ab", "r+b", "w+b", "a+b") or be inserted between the
* letter and the "+" sign for the mixed modes ("rb+", "wb+", "ab+").
* Additional characters may follow the sequence, although they should have no
* effect. For example, "t" is sometimes appended to make explicit the file is
* a text file.
*
* This function supports Unicode filenames, but they must be encoded in UTF-8
* format, regardless of the underlying operating system.
*
* As a fallback, SDL_RWFromFile() will transparently open a matching filename
* in an Android app's `assets`.
*
* Closing the SDL_RWops will close the file handle SDL is holding internally.
*
* \param file a UTF-8 string representing the filename to open
* \param mode an ASCII string representing the mode to be used for opening
* the file.
* \returns a pointer to the SDL_RWops structure that is created, or NULL on
* failure; call SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_RWclose
* \sa SDL_RWFromConstMem
* \sa SDL_RWFromFP
* \sa SDL_RWFromMem
* \sa SDL_RWread
* \sa SDL_RWseek
* \sa SDL_RWtell
* \sa SDL_RWwrite
*/
extern DECLSPEC SDL_RWops *SDLCALL SDL_RWFromFile(const char *file,
const char *mode);
#ifdef HAVE_STDIO_H
extern DECLSPEC SDL_RWops *SDLCALL SDL_RWFromFP(FILE * fp, SDL_bool autoclose);
#else
/**
* Use this function to create an SDL_RWops structure from a standard I/O file
* pointer (stdio.h's `FILE*`).
*
* This function is not available on Windows, since files opened in an
* application on that platform cannot be used by a dynamically linked
* library.
*
* On some platforms, the first parameter is a `void*`, on others, it's a
* `FILE*`, depending on what system headers are available to SDL. It is
* always intended to be the `FILE*` type from the C runtime's stdio.h.
*
* \param fp the `FILE*` that feeds the SDL_RWops stream
* \param autoclose SDL_TRUE to close the `FILE*` when closing the SDL_RWops,
* SDL_FALSE to leave the `FILE*` open when the RWops is
* closed
* \returns a pointer to the SDL_RWops structure that is created, or NULL on
* failure; call SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_RWclose
* \sa SDL_RWFromConstMem
* \sa SDL_RWFromFile
* \sa SDL_RWFromMem
* \sa SDL_RWread
* \sa SDL_RWseek
* \sa SDL_RWtell
* \sa SDL_RWwrite
*/
extern DECLSPEC SDL_RWops *SDLCALL SDL_RWFromFP(void * fp,
SDL_bool autoclose);
#endif
/**
* Use this function to prepare a read-write memory buffer for use with
* SDL_RWops.
*
* This function sets up an SDL_RWops struct based on a memory area of a
* certain size, for both read and write access.
*
* This memory buffer is not copied by the RWops; the pointer you provide must
* remain valid until you close the stream. Closing the stream will not free
* the original buffer.
*
* If you need to make sure the RWops never writes to the memory buffer, you
* should use SDL_RWFromConstMem() with a read-only buffer of memory instead.
*
* \param mem a pointer to a buffer to feed an SDL_RWops stream
* \param size the buffer size, in bytes
* \returns a pointer to a new SDL_RWops structure, or NULL if it fails; call
* SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_RWclose
* \sa SDL_RWFromConstMem
* \sa SDL_RWFromFile
* \sa SDL_RWFromFP
* \sa SDL_RWFromMem
* \sa SDL_RWread
* \sa SDL_RWseek
* \sa SDL_RWtell
* \sa SDL_RWwrite
*/
extern DECLSPEC SDL_RWops *SDLCALL SDL_RWFromMem(void *mem, int size);
/**
* Use this function to prepare a read-only memory buffer for use with RWops.
*
* This function sets up an SDL_RWops struct based on a memory area of a
* certain size. It assumes the memory area is not writable.
*
* Attempting to write to this RWops stream will report an error without
* writing to the memory buffer.
*
* This memory buffer is not copied by the RWops; the pointer you provide must
* remain valid until you close the stream. Closing the stream will not free
* the original buffer.
*
* If you need to write to a memory buffer, you should use SDL_RWFromMem()
* with a writable buffer of memory instead.
*
* \param mem a pointer to a read-only buffer to feed an SDL_RWops stream
* \param size the buffer size, in bytes
* \returns a pointer to a new SDL_RWops structure, or NULL if it fails; call
* SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_RWclose
* \sa SDL_RWFromConstMem
* \sa SDL_RWFromFile
* \sa SDL_RWFromFP
* \sa SDL_RWFromMem
* \sa SDL_RWread
* \sa SDL_RWseek
* \sa SDL_RWtell
*/
extern DECLSPEC SDL_RWops *SDLCALL SDL_RWFromConstMem(const void *mem,
int size);
/* @} *//* RWFrom functions */
/**
* Use this function to allocate an empty, unpopulated SDL_RWops structure.
*
* Applications do not need to use this function unless they are providing
* their own SDL_RWops implementation. If you just need a SDL_RWops to
* read/write a common data source, you should use the built-in
* implementations in SDL, like SDL_RWFromFile() or SDL_RWFromMem(), etc.
*
* You must free the returned pointer with SDL_FreeRW(). Depending on your
* operating system and compiler, there may be a difference between the
* malloc() and free() your program uses and the versions SDL calls
* internally. Trying to mix the two can cause crashing such as segmentation
* faults. Since all SDL_RWops must free themselves when their **close**
* method is called, all SDL_RWops must be allocated through this function, so
* they can all be freed correctly with SDL_FreeRW().
*
* \returns a pointer to the allocated memory on success, or NULL on failure;
* call SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_FreeRW
*/
extern DECLSPEC SDL_RWops *SDLCALL SDL_AllocRW(void);
/**
* Use this function to free an SDL_RWops structure allocated by
* SDL_AllocRW().
*
* Applications do not need to use this function unless they are providing
* their own SDL_RWops implementation. If you just need a SDL_RWops to
* read/write a common data source, you should use the built-in
* implementations in SDL, like SDL_RWFromFile() or SDL_RWFromMem(), etc, and
* call the **close** method on those SDL_RWops pointers when you are done
* with them.
*
* Only use SDL_FreeRW() on pointers returned by SDL_AllocRW(). The pointer is
* invalid as soon as this function returns. Any extra memory allocated during
* creation of the SDL_RWops is not freed by SDL_FreeRW(); the programmer must
* be responsible for managing that memory in their **close** method.
*
* \param area the SDL_RWops structure to be freed
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_AllocRW
*/
extern DECLSPEC void SDLCALL SDL_FreeRW(SDL_RWops * area);
#define RW_SEEK_SET 0 /**< Seek from the beginning of data */
#define RW_SEEK_CUR 1 /**< Seek relative to current read point */
#define RW_SEEK_END 2 /**< Seek relative to the end of data */
/**
* Use this function to get the size of the data stream in an SDL_RWops.
*
* Prior to SDL 2.0.10, this function was a macro.
*
* \param context the SDL_RWops to get the size of the data stream from
* \returns the size of the data stream in the SDL_RWops on success, -1 if
* unknown or a negative error code on failure; call SDL_GetError()
* for more information.
*
* \since This function is available since SDL 2.0.10.
*/
extern DECLSPEC Sint64 SDLCALL SDL_RWsize(SDL_RWops *context);
/**
* Seek within an SDL_RWops data stream.
*
* This function seeks to byte `offset`, relative to `whence`.
*
* `whence` may be any of the following values:
*
* - `RW_SEEK_SET`: seek from the beginning of data
* - `RW_SEEK_CUR`: seek relative to current read point
* - `RW_SEEK_END`: seek relative to the end of data
*
* If this stream can not seek, it will return -1.
*
* SDL_RWseek() is actually a wrapper function that calls the SDL_RWops's
* `seek` method appropriately, to simplify application development.
*
* Prior to SDL 2.0.10, this function was a macro.
*
* \param context a pointer to an SDL_RWops structure
* \param offset an offset in bytes, relative to **whence** location; can be
* negative
* \param whence any of `RW_SEEK_SET`, `RW_SEEK_CUR`, `RW_SEEK_END`
* \returns the final offset in the data stream after the seek or -1 on error.
*
* \since This function is available since SDL 2.0.10.
*
* \sa SDL_RWclose
* \sa SDL_RWFromConstMem
* \sa SDL_RWFromFile
* \sa SDL_RWFromFP
* \sa SDL_RWFromMem
* \sa SDL_RWread
* \sa SDL_RWtell
* \sa SDL_RWwrite
*/
extern DECLSPEC Sint64 SDLCALL SDL_RWseek(SDL_RWops *context,
Sint64 offset, int whence);
/**
* Determine the current read/write offset in an SDL_RWops data stream.
*
* SDL_RWtell is actually a wrapper function that calls the SDL_RWops's `seek`
* method, with an offset of 0 bytes from `RW_SEEK_CUR`, to simplify
* application development.
*
* Prior to SDL 2.0.10, this function was a macro.
*
* \param context a SDL_RWops data stream object from which to get the current
* offset
* \returns the current offset in the stream, or -1 if the information can not
* be determined.
*
* \since This function is available since SDL 2.0.10.
*
* \sa SDL_RWclose
* \sa SDL_RWFromConstMem
* \sa SDL_RWFromFile
* \sa SDL_RWFromFP
* \sa SDL_RWFromMem
* \sa SDL_RWread
* \sa SDL_RWseek
* \sa SDL_RWwrite
*/
extern DECLSPEC Sint64 SDLCALL SDL_RWtell(SDL_RWops *context);
/**
* Read from a data source.
*
* This function reads up to `maxnum` objects each of size `size` from the
* data source to the area pointed at by `ptr`. This function may read less
* objects than requested. It will return zero when there has been an error or
* the data stream is completely read.
*
* SDL_RWread() is actually a function wrapper that calls the SDL_RWops's
* `read` method appropriately, to simplify application development.
*
* Prior to SDL 2.0.10, this function was a macro.
*
* \param context a pointer to an SDL_RWops structure
* \param ptr a pointer to a buffer to read data into
* \param size the size of each object to read, in bytes
* \param maxnum the maximum number of objects to be read
* \returns the number of objects read, or 0 at error or end of file; call
* SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.10.
*
* \sa SDL_RWclose
* \sa SDL_RWFromConstMem
* \sa SDL_RWFromFile
* \sa SDL_RWFromFP
* \sa SDL_RWFromMem
* \sa SDL_RWseek
* \sa SDL_RWwrite
*/
extern DECLSPEC size_t SDLCALL SDL_RWread(SDL_RWops *context,
void *ptr, size_t size,
size_t maxnum);
/**
* Write to an SDL_RWops data stream.
*
* This function writes exactly `num` objects each of size `size` from the
* area pointed at by `ptr` to the stream. If this fails for any reason, it'll
* return less than `num` to demonstrate how far the write progressed. On
* success, it returns `num`.
*
* SDL_RWwrite is actually a function wrapper that calls the SDL_RWops's
* `write` method appropriately, to simplify application development.
*
* Prior to SDL 2.0.10, this function was a macro.
*
* \param context a pointer to an SDL_RWops structure
* \param ptr a pointer to a buffer containing data to write
* \param size the size of an object to write, in bytes
* \param num the number of objects to write
* \returns the number of objects written, which will be less than **num** on
* error; call SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.10.
*
* \sa SDL_RWclose
* \sa SDL_RWFromConstMem
* \sa SDL_RWFromFile
* \sa SDL_RWFromFP
* \sa SDL_RWFromMem
* \sa SDL_RWread
* \sa SDL_RWseek
*/
extern DECLSPEC size_t SDLCALL SDL_RWwrite(SDL_RWops *context,
const void *ptr, size_t size,
size_t num);
/**
* Close and free an allocated SDL_RWops structure.
*
* SDL_RWclose() closes and cleans up the SDL_RWops stream. It releases any
* resources used by the stream and frees the SDL_RWops itself with
* SDL_FreeRW(). This returns 0 on success, or -1 if the stream failed to
* flush to its output (e.g. to disk).
*
* Note that if this fails to flush the stream to disk, this function reports
* an error, but the SDL_RWops is still invalid once this function returns.
*
* Prior to SDL 2.0.10, this function was a macro.
*
* \param context SDL_RWops structure to close
* \returns 0 on success or a negative error code on failure; call
* SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.10.
*
* \sa SDL_RWFromConstMem
* \sa SDL_RWFromFile
* \sa SDL_RWFromFP
* \sa SDL_RWFromMem
* \sa SDL_RWread
* \sa SDL_RWseek
* \sa SDL_RWwrite
*/
extern DECLSPEC int SDLCALL SDL_RWclose(SDL_RWops *context);
/**
* Load all the data from an SDL data stream.
*
* The data is allocated with a zero byte at the end (null terminated) for
* convenience. This extra byte is not included in the value reported via
* `datasize`.
*
* The data should be freed with SDL_free().
*
* \param src the SDL_RWops to read all available data from
* \param datasize if not NULL, will store the number of bytes read
* \param freesrc if non-zero, calls SDL_RWclose() on `src` before returning
* \returns the data, or NULL if there was an error.
*
* \since This function is available since SDL 2.0.6.
*/
extern DECLSPEC void *SDLCALL SDL_LoadFile_RW(SDL_RWops *src,
size_t *datasize,
int freesrc);
/**
* Load all the data from a file path.
*
* The data is allocated with a zero byte at the end (null terminated) for
* convenience. This extra byte is not included in the value reported via
* `datasize`.
*
* The data should be freed with SDL_free().
*
* Prior to SDL 2.0.10, this function was a macro wrapping around
* SDL_LoadFile_RW.
*
* \param file the path to read all available data from
* \param datasize if not NULL, will store the number of bytes read
* \returns the data, or NULL if there was an error.
*
* \since This function is available since SDL 2.0.10.
*/
extern DECLSPEC void *SDLCALL SDL_LoadFile(const char *file, size_t *datasize);
/**
* \name Read endian functions
*
* Read an item of the specified endianness and return in native format.
*/
/* @{ */
/**
* Use this function to read a byte from an SDL_RWops.
*
* \param src the SDL_RWops to read from
* \returns the read byte on success or 0 on failure; call SDL_GetError() for
* more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_WriteU8
*/
extern DECLSPEC Uint8 SDLCALL SDL_ReadU8(SDL_RWops * src);
/**
* Use this function to read 16 bits of little-endian data from an SDL_RWops
* and return in native format.
*
* SDL byteswaps the data only if necessary, so the data returned will be in
* the native byte order.
*
* \param src the stream from which to read data
* \returns 16 bits of data in the native byte order of the platform.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_ReadBE16
*/
extern DECLSPEC Uint16 SDLCALL SDL_ReadLE16(SDL_RWops * src);
/**
* Use this function to read 16 bits of big-endian data from an SDL_RWops and
* return in native format.
*
* SDL byteswaps the data only if necessary, so the data returned will be in
* the native byte order.
*
* \param src the stream from which to read data
* \returns 16 bits of data in the native byte order of the platform.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_ReadLE16
*/
extern DECLSPEC Uint16 SDLCALL SDL_ReadBE16(SDL_RWops * src);
/**
* Use this function to read 32 bits of little-endian data from an SDL_RWops
* and return in native format.
*
* SDL byteswaps the data only if necessary, so the data returned will be in
* the native byte order.
*
* \param src the stream from which to read data
* \returns 32 bits of data in the native byte order of the platform.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_ReadBE32
*/
extern DECLSPEC Uint32 SDLCALL SDL_ReadLE32(SDL_RWops * src);
/**
* Use this function to read 32 bits of big-endian data from an SDL_RWops and
* return in native format.
*
* SDL byteswaps the data only if necessary, so the data returned will be in
* the native byte order.
*
* \param src the stream from which to read data
* \returns 32 bits of data in the native byte order of the platform.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_ReadLE32
*/
extern DECLSPEC Uint32 SDLCALL SDL_ReadBE32(SDL_RWops * src);
/**
* Use this function to read 64 bits of little-endian data from an SDL_RWops
* and return in native format.
*
* SDL byteswaps the data only if necessary, so the data returned will be in
* the native byte order.
*
* \param src the stream from which to read data
* \returns 64 bits of data in the native byte order of the platform.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_ReadBE64
*/
extern DECLSPEC Uint64 SDLCALL SDL_ReadLE64(SDL_RWops * src);
/**
* Use this function to read 64 bits of big-endian data from an SDL_RWops and
* return in native format.
*
* SDL byteswaps the data only if necessary, so the data returned will be in
* the native byte order.
*
* \param src the stream from which to read data
* \returns 64 bits of data in the native byte order of the platform.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_ReadLE64
*/
extern DECLSPEC Uint64 SDLCALL SDL_ReadBE64(SDL_RWops * src);
/* @} *//* Read endian functions */
/**
* \name Write endian functions
*
* Write an item of native format to the specified endianness.
*/
/* @{ */
/**
* Use this function to write a byte to an SDL_RWops.
*
* \param dst the SDL_RWops to write to
* \param value the byte value to write
* \returns 1 on success or 0 on failure; call SDL_GetError() for more
* information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_ReadU8
*/
extern DECLSPEC size_t SDLCALL SDL_WriteU8(SDL_RWops * dst, Uint8 value);
/**
* Use this function to write 16 bits in native format to a SDL_RWops as
* little-endian data.
*
* SDL byteswaps the data only if necessary, so the application always
* specifies native format, and the data written will be in little-endian
* format.
*
* \param dst the stream to which data will be written
* \param value the data to be written, in native format
* \returns 1 on successful write, 0 on error.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_WriteBE16
*/
extern DECLSPEC size_t SDLCALL SDL_WriteLE16(SDL_RWops * dst, Uint16 value);
/**
* Use this function to write 16 bits in native format to a SDL_RWops as
* big-endian data.
*
* SDL byteswaps the data only if necessary, so the application always
* specifies native format, and the data written will be in big-endian format.
*
* \param dst the stream to which data will be written
* \param value the data to be written, in native format
* \returns 1 on successful write, 0 on error.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_WriteLE16
*/
extern DECLSPEC size_t SDLCALL SDL_WriteBE16(SDL_RWops * dst, Uint16 value);
/**
* Use this function to write 32 bits in native format to a SDL_RWops as
* little-endian data.
*
* SDL byteswaps the data only if necessary, so the application always
* specifies native format, and the data written will be in little-endian
* format.
*
* \param dst the stream to which data will be written
* \param value the data to be written, in native format
* \returns 1 on successful write, 0 on error.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_WriteBE32
*/
extern DECLSPEC size_t SDLCALL SDL_WriteLE32(SDL_RWops * dst, Uint32 value);
/**
* Use this function to write 32 bits in native format to a SDL_RWops as
* big-endian data.
*
* SDL byteswaps the data only if necessary, so the application always
* specifies native format, and the data written will be in big-endian format.
*
* \param dst the stream to which data will be written
* \param value the data to be written, in native format
* \returns 1 on successful write, 0 on error.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_WriteLE32
*/
extern DECLSPEC size_t SDLCALL SDL_WriteBE32(SDL_RWops * dst, Uint32 value);
/**
* Use this function to write 64 bits in native format to a SDL_RWops as
* little-endian data.
*
* SDL byteswaps the data only if necessary, so the application always
* specifies native format, and the data written will be in little-endian
* format.
*
* \param dst the stream to which data will be written
* \param value the data to be written, in native format
* \returns 1 on successful write, 0 on error.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_WriteBE64
*/
extern DECLSPEC size_t SDLCALL SDL_WriteLE64(SDL_RWops * dst, Uint64 value);
/**
* Use this function to write 64 bits in native format to a SDL_RWops as
* big-endian data.
*
* SDL byteswaps the data only if necessary, so the application always
* specifies native format, and the data written will be in big-endian format.
*
* \param dst the stream to which data will be written
* \param value the data to be written, in native format
* \returns 1 on successful write, 0 on error.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_WriteLE64
*/
extern DECLSPEC size_t SDLCALL SDL_WriteBE64(SDL_RWops * dst, Uint64 value);
/* @} *//* Write endian functions */
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_rwops_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 412 | 0.946241 | 1 | 0.946241 | game-dev | MEDIA | 0.345875 | game-dev | 0.748336 | 1 | 0.748336 |
magarena/magarena | 1,027 | release/Magarena/scripts/Whelming_Wave.groovy | [
new MagicSpellCardEvent() {
@Override
public MagicEvent getEvent(final MagicCardOnStack cardOnStack,final MagicPayedCost payedCost) {
return new MagicEvent(
cardOnStack,
this,
"Return all creatures to their owners' hands except for Krakens, Leviathans, Octopuses, and Serpents."
);
}
@Override
public void executeEvent(final MagicGame game, final MagicEvent event) {
final Collection<MagicPermanent> targets = CREATURE.filter(event);
for (final MagicPermanent target : targets) {
if (!target.hasSubType(MagicSubType.Kraken) &&
!target.hasSubType(MagicSubType.Leviathan) &&
!target.hasSubType(MagicSubType.Octopus) &&
!target.hasSubType(MagicSubType.Serpent)) {
game.doAction(new RemoveFromPlayAction(target,MagicLocationType.OwnersHand));
}
}
}
}
]
| 412 | 0.961931 | 1 | 0.961931 | game-dev | MEDIA | 0.923982 | game-dev | 0.778088 | 1 | 0.778088 |
ElunaLuaEngine/ElunaTrinityWotlk | 992,395 | src/server/game/Entities/Player/Player.cpp | /*
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Player.h"
#include "AccountMgr.h"
#include "AchievementMgr.h"
#include "ArenaTeam.h"
#include "ArenaTeamMgr.h"
#include "Bag.h"
#include "Battlefield.h"
#include "BattlefieldMgr.h"
#include "Battleground.h"
#include "BattlegroundMgr.h"
#include "BattlegroundPackets.h"
#include "BattlegroundScore.h"
#include "CellImpl.h"
#include "Channel.h"
#include "ChannelMgr.h"
#include "CharacterCache.h"
#include "CharacterDatabaseCleaner.h"
#include "Chat.h"
#include "CinematicMgr.h"
#include "CombatLogPackets.h"
#include "CombatPackets.h"
#include "Common.h"
#include "ConditionMgr.h"
#include "Containers.h"
#include "CreatureAI.h"
#include "DatabaseEnv.h"
#include "DisableMgr.h"
#include "Formulas.h"
#include "GameClient.h"
#include "GameEventMgr.h"
#include "GameObjectAI.h"
#include "GameTime.h"
#include "GitRevision.h"
#include "GossipDef.h"
#include "GridNotifiers.h"
#include "GridNotifiersImpl.h"
#include "Group.h"
#include "GroupMgr.h"
#include "Guild.h"
#include "GuildMgr.h"
#include "InstanceSaveMgr.h"
#include "InstanceScript.h"
#include "Item.h"
#include "KillRewarder.h"
#include "Language.h"
#include "LFGMgr.h"
#include "Log.h"
#include "LootItemStorage.h"
#include "LootMgr.h"
#include "Mail.h"
#include "MailPackets.h"
#include "MapManager.h"
#include "MiscPackets.h"
#include "MotionMaster.h"
#include "ObjectAccessor.h"
#include "ObjectMgr.h"
#include "Opcodes.h"
#include "OutdoorPvP.h"
#include "OutdoorPvPMgr.h"
#include "Pet.h"
#include "PetitionMgr.h"
#include "PoolMgr.h"
#include "QueryHolder.h"
#include "QuestDef.h"
#include "QuestPools.h"
#include "Realm.h"
#include "ReputationMgr.h"
#include "SkillDiscovery.h"
#include "SocialMgr.h"
#include "Spell.h"
#include "SpellAuraEffects.h"
#include "SpellAuras.h"
#include "SpellHistory.h"
#include "SpellMgr.h"
#include "SpellPackets.h"
#include "StringConvert.h"
#include "TalentPackets.h"
#include "TicketMgr.h"
#include "TradeData.h"
#include "Trainer.h"
#include "Transport.h"
#include "UpdateData.h"
#include "UpdateFieldFlags.h"
#include "UpdateMask.h"
#include "Util.h"
#include "Weather.h"
#include "WeatherMgr.h"
#include "World.h"
#include "WorldPacket.h"
#include "WorldSession.h"
#ifdef ELUNA
#include "LuaEngine.h"
#endif
#include "WorldStatePackets.h"
#define ZONE_UPDATE_INTERVAL (1*IN_MILLISECONDS)
// corpse reclaim times
#define DEATH_EXPIRE_STEP (5*MINUTE)
#define MAX_DEATH_COUNT 3
static uint32 corpseReclaimDelay[MAX_DEATH_COUNT] = { 30, 60, 120 };
uint32 const MAX_MONEY_AMOUNT = static_cast<uint32>(std::numeric_limits<int32>::max());
Player::Player(WorldSession* session): Unit(true)
{
m_objectType |= TYPEMASK_PLAYER;
m_objectTypeId = TYPEID_PLAYER;
m_valuesCount = PLAYER_END;
m_session = session;
m_ingametime = 0;
m_sharedQuestId = 0;
m_ExtraFlags = 0;
m_spellModTakingSpell = nullptr;
//m_pad = 0;
// players always accept
if (!GetSession()->HasPermission(rbac::RBAC_PERM_CAN_FILTER_WHISPERS))
SetAcceptWhispers(true);
m_regenTimer = 0;
m_regenTimerCount = 0;
m_foodEmoteTimerCount = 0;
m_weaponChangeTimer = 0;
m_zoneUpdateId = uint32(-1);
m_zoneUpdateTimer = 0;
m_areaUpdateId = 0;
m_team = 0;
m_needsZoneUpdate = false;
m_nextSave = sWorld->getIntConfig(CONFIG_INTERVAL_SAVE);
memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT);
m_social = nullptr;
// group is initialized in the reference constructor
SetGroupInvite(nullptr);
m_groupUpdateMask = 0;
m_auraRaidUpdateMask = 0;
m_bPassOnGroupLoot = false;
m_GuildIdInvited = 0;
m_ArenaTeamIdInvited = 0;
m_atLoginFlags = AT_LOGIN_NONE;
mSemaphoreTeleport_Near = false;
mSemaphoreTeleport_Far = false;
m_DelayedOperations = 0;
m_bCanDelayTeleport = false;
m_bHasDelayedTeleport = false;
m_teleport_options = 0;
m_trade = nullptr;
m_cinematic = 0;
m_movie = 0;
PlayerTalkClass = new PlayerMenu(GetSession());
m_currentBuybackSlot = BUYBACK_SLOT_START;
m_DailyQuestChanged = false;
m_lastDailyQuestTime = 0;
// Init rune flags
for (uint8 i = 0; i < MAX_RUNES; ++i)
{
SetRuneTimer(i, 0xFFFFFFFF);
SetLastRuneGraceTimer(i, 0);
}
for (uint8 i = 0; i < MAX_TIMERS; i++)
m_MirrorTimer[i] = DISABLED_MIRROR_TIMER;
m_MirrorTimerFlags = UNDERWATER_NONE;
m_MirrorTimerFlagsLast = UNDERWATER_NONE;
m_hostileReferenceCheckTimer = 0;
m_drunkTimer = 0;
m_deathTimer = 0;
m_deathExpireTime = 0;
m_swingErrorMsg = 0;
for (uint8 j = 0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; ++j)
{
m_bgBattlegroundQueueID[j].bgQueueTypeId = BATTLEGROUND_QUEUE_NONE;
m_bgBattlegroundQueueID[j].invitedToInstance = 0;
}
m_logintime = GameTime::GetGameTime();
m_Last_tick = m_logintime;
m_Played_time[PLAYED_TIME_TOTAL] = 0;
m_Played_time[PLAYED_TIME_LEVEL] = 0;
m_WeaponProficiency = 0;
m_ArmorProficiency = 0;
m_canParry = false;
m_canBlock = false;
m_canTitanGrip = false;
m_titanGripWeaponSubclasses = 0;
m_titanGripArmorSubclasses = 0;
m_titanGripPenaltySpellId = 0;
m_ammoDPS = 0.0f;
m_temporaryUnsummonedPetNumber = 0;
//cache for UNIT_CREATED_BY_SPELL to allow
//returning reagents for temporarily removed pets
//when dying/logging out
m_oldpetspell = 0;
m_lastpetnumber = 0;
////////////////////Rest System/////////////////////
_restTime = 0;
inn_triggerId = 0;
m_rest_bonus = 0;
_restFlagMask = 0;
////////////////////Rest System/////////////////////
m_mailsUpdated = false;
unReadMails = 0;
m_nextMailDelivereTime = 0;
m_itemUpdateQueueBlocked = false;
/////////////////// Instance System /////////////////////
m_HomebindTimer = 0;
m_InstanceValid = true;
m_dungeonDifficulty = DUNGEON_DIFFICULTY_NORMAL;
m_raidDifficulty = RAID_DIFFICULTY_10MAN_NORMAL;
m_raidMapDifficulty = RAID_DIFFICULTY_10MAN_NORMAL;
m_lastPotionId = 0;
_talentMgr = new PlayerTalentInfo();
for (uint8 i = 0; i < BASEMOD_END; ++i)
{
m_auraBaseFlatMod[i] = 0.0f;
m_auraBasePctMod[i] = 1.0f;
}
for (uint8 i = 0; i < MAX_COMBAT_RATING; i++)
m_baseRatingValue[i] = 0;
m_baseSpellPower = 0;
m_baseFeralAP = 0;
m_baseManaRegen = 0;
m_baseHealthRegen = 0;
m_spellPenetrationItemMod = 0;
// Honor System
m_lastHonorUpdateTime = GameTime::GetGameTime();
m_IsBGRandomWinner = false;
// Player summoning
m_summon_expire = 0;
m_seer = this;
m_homebindMapId = 0;
m_homebindAreaId = 0;
m_homebindX = 0;
m_homebindY = 0;
m_homebindZ = 0;
m_contestedPvPTimer = 0;
m_declinedname = nullptr;
m_isActive = true;
m_runes = nullptr;
m_lastFallTime = 0;
m_lastFallZ = 0;
m_grantableLevels = 0;
m_fishingSteps = 0;
m_ControlledByPlayer = true;
sWorld->IncreasePlayerCount();
m_ChampioningFaction = 0;
for (uint8 i = 0; i < MAX_POWERS; ++i)
m_powerFraction[i] = 0;
isDebugAreaTriggers = false;
m_WeeklyQuestChanged = false;
m_MonthlyQuestChanged = false;
m_SeasonalQuestChanged = false;
SetPendingBind(0, 0);
_activeCheats = CHEAT_NONE;
healthBeforeDuel = 0;
manaBeforeDuel = 0;
_cinematicMgr = new CinematicMgr(this);
m_achievementMgr = new AchievementMgr(this);
m_reputationMgr = new ReputationMgr(this);
m_groupUpdateTimer.Reset(5000);
}
Player::~Player()
{
// it must be unloaded already in PlayerLogout and accessed only for logged in player
//m_social = nullptr;
// Note: buy back item already deleted from DB when player was saved
for (uint8 i = 0; i < PLAYER_SLOTS_COUNT; ++i)
delete m_items[i];
delete _talentMgr;
//all mailed items should be deleted, also all mail should be deallocated
for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
delete *itr;
for (ItemMap::iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
delete PlayerTalkClass;
for (size_t x = 0; x < ItemSetEff.size(); x++)
delete ItemSetEff[x];
delete m_declinedname;
delete m_runes;
delete m_achievementMgr;
delete m_reputationMgr;
delete _cinematicMgr;
sWorld->DecreasePlayerCount();
}
void Player::CleanupsBeforeDelete(bool finalCleanup)
{
TradeCancel(false);
DuelComplete(DUEL_INTERRUPTED);
Unit::CleanupsBeforeDelete(finalCleanup);
// clean up player-instance binds, may unload some instance saves
for (uint8 i = 0; i < MAX_DIFFICULTY; ++i)
for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
itr->second.save->RemovePlayer(this);
}
bool Player::Create(ObjectGuid::LowType guidlow, CharacterCreateInfo* createInfo)
{
//FIXME: outfitId not used in player creating
/// @todo need more checks against packet modifications
Object::_Create(ObjectGuid::Create<HighGuid::Player>(guidlow));
m_name = createInfo->Name;
PlayerInfo const* info = sObjectMgr->GetPlayerInfo(createInfo->Race, createInfo->Class);
if (!info)
{
TC_LOG_ERROR("entities.player.cheat", "Player::Create: Possible hacking attempt: Account {} tried to create a character named '{}' with an invalid race/class pair ({}/{}) - refusing to do so.",
GetSession()->GetAccountId(), m_name, createInfo->Race, createInfo->Class);
return false;
}
for (uint8 i = 0; i < PLAYER_SLOTS_COUNT; i++)
m_items[i] = nullptr;
Relocate(info->positionX, info->positionY, info->positionZ, info->orientation);
ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(createInfo->Class);
if (!cEntry)
{
TC_LOG_ERROR("entities.player.cheat", "Player::Create: Possible hacking attempt: Account {} tried to create a character named '{}' with an invalid character class ({}) - refusing to do so (wrong DBC-files?)",
GetSession()->GetAccountId(), m_name, createInfo->Class);
return false;
}
SetMap(sMapMgr->CreateMap(info->mapId, this));
uint8 powertype = cEntry->DisplayPower;
SetObjectScale(1.0f);
SetFactionForRace(createInfo->Race);
if (!IsValidGender(createInfo->Gender))
{
TC_LOG_ERROR("entities.player.cheat", "Player::Create: Possible hacking attempt: Account {} tried to create a character named '{}' with an invalid gender ({}) - refusing to do so",
GetSession()->GetAccountId(), m_name, createInfo->Gender);
return false;
}
if (!ValidateAppearance(createInfo->Race, createInfo->Class, createInfo->Gender, createInfo->HairStyle, createInfo->HairColor, createInfo->Face, createInfo->FacialHair, createInfo->Skin, true))
{
TC_LOG_ERROR("entities.player.cheat", "Player::Create: Possible hacking attempt: Account {} tried to create a character named '{}' with invalid appearance attributes - refusing to do so",
GetSession()->GetAccountId(), m_name);
return false;
}
SetRace(createInfo->Race);
SetClass(createInfo->Class);
SetGender(Gender(createInfo->Gender));
SetPowerType(Powers(powertype), false);
InitDisplayIds();
if (sWorld->getIntConfig(CONFIG_GAME_TYPE) == REALM_TYPE_PVP || sWorld->getIntConfig(CONFIG_GAME_TYPE) == REALM_TYPE_RPPVP)
{
SetPvpFlag(UNIT_BYTE2_FLAG_PVP);
SetUnitFlag(UNIT_FLAG_PLAYER_CONTROLLED);
}
SetUnitFlag2(UNIT_FLAG2_REGENERATE_POWER);
SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1)); // -1 is default value
SetSkinId(createInfo->Skin);
SetFaceId(createInfo->Face);
SetHairStyleId(createInfo->HairStyle);
SetHairColorId(createInfo->HairColor);
SetFacialStyle(createInfo->FacialHair);
SetRestState((GetSession()->IsARecruiter() || GetSession()->GetRecruiterId() != 0) ? REST_STATE_RAF_LINKED : REST_STATE_NOT_RAF_LINKED);
SetNativeGender(Gender(createInfo->Gender));
// set starting level
SetLevel(GetStartLevel(createInfo->Class), false);
InitRunes();
SetMoney(GetClass() != CLASS_DEATH_KNIGHT
? sWorld->getIntConfig(CONFIG_START_PLAYER_MONEY)
: sWorld->getIntConfig(CONFIG_START_DEATH_KNIGHT_PLAYER_MONEY));
SetHonorPoints(sWorld->getIntConfig(CONFIG_START_HONOR_POINTS));
SetArenaPoints(sWorld->getIntConfig(CONFIG_START_ARENA_POINTS));
// Played time
m_Last_tick = GameTime::GetGameTime();
m_Played_time[PLAYED_TIME_TOTAL] = 0;
m_Played_time[PLAYED_TIME_LEVEL] = 0;
// base stats and related field values
InitStatsForLevel();
InitTaxiNodesForLevel();
InitGlyphsForLevel();
InitTalentForLevel();
InitPrimaryProfessions(); // to max set before any spell added
// apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
SetFullHealth();
SetFullPower(POWER_MANA);
// original spells
LearnDefaultSkills();
LearnCustomSpells();
// original action bar
for (PlayerCreateInfoActions::const_iterator action_itr = info->action.begin(); action_itr != info->action.end(); ++action_itr)
addActionButton(action_itr->button, action_itr->action, action_itr->type);
// original items
if (CharStartOutfitEntry const* oEntry = GetCharStartOutfitEntry(createInfo->Race, createInfo->Class, createInfo->Gender))
{
for (int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
{
if (oEntry->ItemID[j] <= 0)
continue;
uint32 itemId = oEntry->ItemID[j];
// just skip, reported in ObjectMgr::LoadItemTemplates
ItemTemplate const* iProto = sObjectMgr->GetItemTemplate(itemId);
if (!iProto)
continue;
// BuyCount by default
uint32 count = iProto->BuyCount;
// special amount for food/drink
if (iProto->Class == ITEM_CLASS_CONSUMABLE && iProto->SubClass == ITEM_SUBCLASS_FOOD_DRINK)
{
switch (iProto->Spells[0].SpellCategory)
{
case SPELL_CATEGORY_FOOD: // food
count = GetClass() == CLASS_DEATH_KNIGHT ? 10 : 4;
break;
case SPELL_CATEGORY_DRINK: // drink
count = 2;
break;
}
if (iProto->GetMaxStackSize() < count)
count = iProto->GetMaxStackSize();
}
StoreNewItemInBestSlots(itemId, count);
}
}
for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr != info->item.end(); ++item_id_itr)
StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);
// bags and main-hand weapon must equipped at this moment
// now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
// or ammo not equipped in special bag
for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
{
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
{
uint16 eDest;
// equip offhand weapon/shield if it attempt equipped before main-hand weapon
InventoryResult msg = CanEquipItem(NULL_SLOT, eDest, pItem, false);
if (msg == EQUIP_ERR_OK)
{
RemoveItem(INVENTORY_SLOT_BAG_0, i, true);
EquipItem(eDest, pItem, true);
}
// move other items to more appropriate slots (ammo not equipped in special bag)
else
{
ItemPosCountVec sDest;
msg = CanStoreItem(NULL_BAG, NULL_SLOT, sDest, pItem, false);
if (msg == EQUIP_ERR_OK)
{
RemoveItem(INVENTORY_SLOT_BAG_0, i, true);
StoreItem(sDest, pItem, true);
}
// if this is ammo then use it
msg = CanUseAmmo(pItem->GetEntry());
if (msg == EQUIP_ERR_OK)
SetAmmo(pItem->GetEntry());
}
}
}
// all item positions resolved
GetThreatManager().Initialize();
return true;
}
bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
{
TC_LOG_DEBUG("entities.player.items", "Player::StoreNewItemInBestSlots: Player '{}' ({}) creates initial item (ItemID: {}, Count: {})",
GetName(), GetGUID().ToString(), titem_id, titem_amount);
// attempt equip by one
while (titem_amount > 0)
{
uint16 eDest;
InventoryResult msg = CanEquipNewItem(NULL_SLOT, eDest, titem_id, false);
if (msg != EQUIP_ERR_OK)
break;
EquipNewItem(eDest, titem_id, true);
AutoUnequipOffhandIfNeed();
--titem_amount;
}
if (titem_amount == 0)
return true; // equipped
// attempt store
ItemPosCountVec sDest;
// store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
InventoryResult msg = CanStoreNewItem(INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount);
if (msg == EQUIP_ERR_OK)
{
StoreNewItem(sDest, titem_id, true, GenerateItemRandomPropertyId(titem_id));
return true; // stored
}
// item can't be added
TC_LOG_ERROR("entities.player.items", "Player::StoreNewItemInBestSlots: Player '{}' ({}) can't equip or store initial item (ItemID: {}, Race: {}, Class: {}, InventoryResult: {})",
GetName(), GetGUID().ToString(), titem_id, GetRace(), GetClass(), msg);
return false;
}
void Player::SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen)
{
if (int(MaxValue) == DISABLED_MIRROR_TIMER)
{
if (int(CurrentValue) != DISABLED_MIRROR_TIMER)
StopMirrorTimer(Type);
return;
}
SendDirectMessage(WorldPackets::Misc::StartMirrorTimer(Type, CurrentValue, MaxValue, Regen, false, 0).Write());
}
void Player::StopMirrorTimer(MirrorTimerType Type)
{
m_MirrorTimer[Type] = DISABLED_MIRROR_TIMER;
SendDirectMessage(WorldPackets::Misc::StopMirrorTimer(Type).Write());
}
bool Player::IsImmuneToEnvironmentalDamage() const
{
// check for GM and death state included in isAttackableByAOE
return !isTargetableForAttack(false);
}
uint32 Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage)
{
if (IsImmuneToEnvironmentalDamage())
return 0;
// Absorb, resist some environmental damage type
uint32 absorb = 0;
uint32 resist = 0;
switch (type)
{
case DAMAGE_LAVA:
case DAMAGE_SLIME:
case DAMAGE_FIRE:
{
DamageInfo dmgInfo(this, this, damage, nullptr, type == DAMAGE_SLIME ? SPELL_SCHOOL_MASK_NATURE : SPELL_SCHOOL_MASK_FIRE, DIRECT_DAMAGE, BASE_ATTACK);
Unit::CalcAbsorbResist(dmgInfo);
absorb = dmgInfo.GetAbsorb();
resist = dmgInfo.GetResist();
damage = dmgInfo.GetDamage();
break;
}
default:
break;
}
Unit::DealDamageMods(this, damage, &absorb);
WorldPackets::CombatLog::EnvironmentalDamageLog packet;
packet.Victim = GetGUID();
packet.Type = type != DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL;
packet.Amount = damage;
packet.Absorbed = absorb;
packet.Resisted = resist;
SendMessageToSet(packet.Write(), true);
uint32 final_damage = Unit::DealDamage(this, this, damage, nullptr, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false);
if (!IsAlive())
{
if (type == DAMAGE_FALL) // DealDamage does not apply item durability loss from self-induced damage.
{
TC_LOG_DEBUG("entities.player", "Player::EnvironmentalDamage: Player '{}' ({}) fall to death, losing {} durability",
GetName(), GetGUID().ToString(), sWorld->getRate(RATE_DURABILITY_LOSS_ON_DEATH));
DurabilityLossAll(sWorld->getRate(RATE_DURABILITY_LOSS_ON_DEATH), false);
// durability lost message
SendDurabilityLoss();
}
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM, 1, type);
#ifdef ELUNA
if (Eluna* e = GetEluna())
e->OnPlayerKilledByEnvironment(this, type);
#endif
}
return final_damage;
}
int32 Player::getMaxTimer(MirrorTimerType timer) const
{
switch (timer)
{
case FATIGUE_TIMER:
return MINUTE * IN_MILLISECONDS;
case BREATH_TIMER:
{
if (!IsAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) || GetSession()->GetSecurity() >= AccountTypes(sWorld->getIntConfig(CONFIG_DISABLE_BREATHING)))
return DISABLED_MIRROR_TIMER;
int32 UnderWaterTime = 3 * MINUTE * IN_MILLISECONDS;
UnderWaterTime *= GetTotalAuraMultiplier(SPELL_AURA_MOD_WATER_BREATHING);
return UnderWaterTime;
}
case FIRE_TIMER:
{
if (!IsAlive())
return DISABLED_MIRROR_TIMER;
return 1 * IN_MILLISECONDS;
}
default:
return 0;
}
}
void Player::UpdateMirrorTimers()
{
// Desync flags for update on next HandleDrowning
if (m_MirrorTimerFlags)
m_MirrorTimerFlagsLast = ~m_MirrorTimerFlags;
}
void Player::StopMirrorTimers()
{
StopMirrorTimer(FATIGUE_TIMER);
StopMirrorTimer(BREATH_TIMER);
StopMirrorTimer(FIRE_TIMER);
}
bool Player::IsMirrorTimerActive(MirrorTimerType type) const
{
return m_MirrorTimer[type] == getMaxTimer(type);
}
void Player::HandleDrowning(uint32 time_diff)
{
if (!m_MirrorTimerFlags)
return;
// In water
if (m_MirrorTimerFlags & UNDERWATER_INWATER)
{
// Breath timer not activated - activate it
if (m_MirrorTimer[BREATH_TIMER] == DISABLED_MIRROR_TIMER)
{
m_MirrorTimer[BREATH_TIMER] = getMaxTimer(BREATH_TIMER);
SendMirrorTimer(BREATH_TIMER, m_MirrorTimer[BREATH_TIMER], m_MirrorTimer[BREATH_TIMER], -1);
}
else // If activated - do tick
{
m_MirrorTimer[BREATH_TIMER] -= time_diff;
// Timer limit - need deal damage
if (m_MirrorTimer[BREATH_TIMER] < 0)
{
m_MirrorTimer[BREATH_TIMER] += 1 * IN_MILLISECONDS;
// Calculate and deal damage
/// @todo Check this formula
uint32 damage = GetMaxHealth() / 5 + urand(0, GetLevel() - 1);
EnvironmentalDamage(DAMAGE_DROWNING, damage);
}
else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INWATER)) // Update time in client if need
SendMirrorTimer(BREATH_TIMER, getMaxTimer(BREATH_TIMER), m_MirrorTimer[BREATH_TIMER], -1);
}
}
else if (m_MirrorTimer[BREATH_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
{
int32 UnderWaterTime = getMaxTimer(BREATH_TIMER);
// Need breath regen
m_MirrorTimer[BREATH_TIMER] += 10 * time_diff;
if (m_MirrorTimer[BREATH_TIMER] >= UnderWaterTime || !IsAlive())
StopMirrorTimer(BREATH_TIMER);
else if (m_MirrorTimerFlagsLast & UNDERWATER_INWATER)
SendMirrorTimer(BREATH_TIMER, UnderWaterTime, m_MirrorTimer[BREATH_TIMER], 10);
}
// In dark water
if (m_MirrorTimerFlags & UNDERWATER_INDARKWATER)
{
// Fatigue timer not activated - activate it
if (m_MirrorTimer[FATIGUE_TIMER] == DISABLED_MIRROR_TIMER)
{
m_MirrorTimer[FATIGUE_TIMER] = getMaxTimer(FATIGUE_TIMER);
SendMirrorTimer(FATIGUE_TIMER, m_MirrorTimer[FATIGUE_TIMER], m_MirrorTimer[FATIGUE_TIMER], -1);
}
else
{
m_MirrorTimer[FATIGUE_TIMER] -= time_diff;
// Timer limit - need deal damage or teleport ghost to graveyard
if (m_MirrorTimer[FATIGUE_TIMER] < 0)
{
m_MirrorTimer[FATIGUE_TIMER] += 1 * IN_MILLISECONDS;
if (IsAlive()) // Calculate and deal damage
{
uint32 damage = GetMaxHealth() / 5 + urand(0, GetLevel() - 1);
EnvironmentalDamage(DAMAGE_EXHAUSTED, damage);
}
else if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) // Teleport ghost to graveyard
RepopAtGraveyard();
}
else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INDARKWATER))
SendMirrorTimer(FATIGUE_TIMER, getMaxTimer(FATIGUE_TIMER), m_MirrorTimer[FATIGUE_TIMER], -1);
}
}
else if (m_MirrorTimer[FATIGUE_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
{
int32 DarkWaterTime = getMaxTimer(FATIGUE_TIMER);
m_MirrorTimer[FATIGUE_TIMER] += 10 * time_diff;
if (m_MirrorTimer[FATIGUE_TIMER] >= DarkWaterTime || !IsAlive())
StopMirrorTimer(FATIGUE_TIMER);
else if (m_MirrorTimerFlagsLast & UNDERWATER_INDARKWATER)
SendMirrorTimer(FATIGUE_TIMER, DarkWaterTime, m_MirrorTimer[FATIGUE_TIMER], 10);
}
if (m_MirrorTimerFlags & (UNDERWATER_INLAVA /*| UNDERWATER_INSLIME*/) && !(_lastLiquid && _lastLiquid->SpellID))
{
// Breath timer not activated - activate it
if (m_MirrorTimer[FIRE_TIMER] == DISABLED_MIRROR_TIMER)
m_MirrorTimer[FIRE_TIMER] = getMaxTimer(FIRE_TIMER);
else
{
m_MirrorTimer[FIRE_TIMER] -= time_diff;
if (m_MirrorTimer[FIRE_TIMER] < 0)
{
m_MirrorTimer[FIRE_TIMER] += 1 * IN_MILLISECONDS;
// Calculate and deal damage
/// @todo Check this formula
uint32 damage = urand(600, 700);
if (m_MirrorTimerFlags & UNDERWATER_INLAVA)
EnvironmentalDamage(DAMAGE_LAVA, damage);
// need to skip Slime damage in Undercity,
// maybe someone can find better way to handle environmental damage
//else if (m_zoneUpdateId != 1497)
// EnvironmentalDamage(DAMAGE_SLIME, damage);
}
}
}
else
m_MirrorTimer[FIRE_TIMER] = DISABLED_MIRROR_TIMER;
// Recheck timers flag
m_MirrorTimerFlags &= ~UNDERWATER_EXIST_TIMERS;
for (uint8 i = 0; i < MAX_TIMERS; ++i)
{
if (m_MirrorTimer[i] != DISABLED_MIRROR_TIMER)
{
m_MirrorTimerFlags |= UNDERWATER_EXIST_TIMERS;
break;
}
}
m_MirrorTimerFlagsLast = m_MirrorTimerFlags;
}
///The player sobers by 1% every 9 seconds
void Player::HandleSobering()
{
m_drunkTimer = 0;
uint8 currentDrunkValue = GetDrunkValue();
uint8 drunk = currentDrunkValue ? --currentDrunkValue : 0;
SetDrunkValue(drunk);
}
/*static*/ DrunkenState Player::GetDrunkenstateByValue(uint8 value)
{
if (value >= 90)
return DRUNKEN_SMASHED;
if (value >= 50)
return DRUNKEN_DRUNK;
if (value)
return DRUNKEN_TIPSY;
return DRUNKEN_SOBER;
}
void Player::SetDrunkValue(uint8 newDrunkValue, uint32 itemId /*= 0*/)
{
newDrunkValue = std::min<uint8>(newDrunkValue, 100);
if (newDrunkValue == GetDrunkValue())
return;
uint32 oldDrunkenState = Player::GetDrunkenstateByValue(GetDrunkValue());
uint32 newDrunkenState = Player::GetDrunkenstateByValue(newDrunkValue);
SetByteValue(PLAYER_BYTES_3, PLAYER_BYTES_3_OFFSET_INEBRIATION, newDrunkValue);
UpdateInvisibilityDrunkDetect();
m_drunkTimer = 0; // reset sobering timer
if (newDrunkenState == oldDrunkenState)
return;
WorldPackets::Misc::CrossedInebriationThreshold data;
data.Guid = GetGUID();
data.Threshold = newDrunkenState;
data.ItemID = itemId;
SendMessageToSet(data.Write(), true);
}
void Player::UpdateInvisibilityDrunkDetect()
{
// select drunk percent or total SPELL_AURA_MOD_FAKE_INEBRIATE amount, whichever is higher for visibility updates
uint8 drunkValue = GetDrunkValue();
int32 fakeDrunkValue = GetFakeDrunkValue();
int32 maxDrunkValue = std::max<int32>(drunkValue, fakeDrunkValue);
if (maxDrunkValue != 0)
{
m_invisibilityDetect.AddFlag(INVISIBILITY_DRUNK);
m_invisibilityDetect.SetValue(INVISIBILITY_DRUNK, maxDrunkValue);
}
else
m_invisibilityDetect.DelFlag(INVISIBILITY_DRUNK);
if (IsInWorld())
UpdateObjectVisibility();
}
void Player::Update(uint32 p_time)
{
if (!IsInWorld())
return;
// undelivered mail
if (m_nextMailDelivereTime && m_nextMailDelivereTime <= GameTime::GetGameTime())
{
SendNewMail();
++unReadMails;
// It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
m_nextMailDelivereTime = 0;
}
// Update cinematic location, if 500ms have passed and we're doing a cinematic now.
_cinematicMgr->m_cinematicDiff += p_time;
if (_cinematicMgr->m_cinematicCamera && _cinematicMgr->m_activeCinematicCameraId && GetMSTimeDiffToNow(_cinematicMgr->m_lastCinematicCheck) > CINEMATIC_UPDATEDIFF)
{
_cinematicMgr->m_lastCinematicCheck = GameTime::GetGameTimeMS();
_cinematicMgr->UpdateCinematicLocation(p_time);
}
//used to implement delayed far teleports
SetCanDelayTeleport(true);
Unit::Update(p_time);
SetCanDelayTeleport(false);
time_t now = GameTime::GetGameTime();
UpdatePvPFlag(now);
UpdateContestedPvP(p_time);
UpdateDuelFlag(now);
CheckDuelDistance(now);
UpdateAfkReport(now);
Unit::AIUpdateTick(p_time);
// Once per second, update items that have just a limited lifetime
if (now > m_Last_tick)
{
UpdateItemDuration(uint32(now - m_Last_tick));
UpdateSoulboundTradeItems();
}
// If mute expired, remove it from the DB
if (GetSession()->m_muteTime && GetSession()->m_muteTime < now)
{
GetSession()->m_muteTime = 0;
LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_MUTE_TIME);
stmt->setInt64(0, 0); // Set the mute time to 0
stmt->setString(1, "");
stmt->setString(2, "");
stmt->setUInt32(3, GetSession()->GetAccountId());
LoginDatabase.Execute(stmt);
}
if (!m_timedquests.empty())
{
QuestSet::iterator iter = m_timedquests.begin();
while (iter != m_timedquests.end())
{
QuestStatusData& q_status = m_QuestStatus[*iter];
if (q_status.Timer <= p_time)
{
uint32 quest_id = *iter;
++iter; // current iter will be removed in FailQuest
FailQuest(quest_id);
}
else
{
q_status.Timer -= p_time;
m_QuestStatusSave[*iter] = QUEST_DEFAULT_SAVE_TYPE;
++iter;
}
}
}
m_achievementMgr->UpdateTimedAchievements(p_time);
if (HasUnitState(UNIT_STATE_MELEE_ATTACKING) && !HasUnitState(UNIT_STATE_CASTING | UNIT_STATE_CHARGING))
{
if (Unit* victim = GetVictim())
{
// default combat reach 10
/// @todo add weapon, skill check
if (isAttackReady(BASE_ATTACK))
{
if (!IsWithinMeleeRange(victim))
{
setAttackTimer(BASE_ATTACK, 100);
if (m_swingErrorMsg != 1) // send single time (client auto repeat)
{
SendAttackSwingNotInRange();
m_swingErrorMsg = 1;
}
}
//120 degrees of radiant range
else if (!HasInArc(2 * float(M_PI) / 3, victim))
{
setAttackTimer(BASE_ATTACK, 100);
if (m_swingErrorMsg != 2) // send single time (client auto repeat)
{
SendAttackSwingBadFacingAttack();
m_swingErrorMsg = 2;
}
}
else
{
m_swingErrorMsg = 0; // reset swing error state
// prevent base and off attack in same time, delay attack at 0.2 sec
if (haveOffhandWeapon())
if (getAttackTimer(OFF_ATTACK) < ATTACK_DISPLAY_DELAY)
setAttackTimer(OFF_ATTACK, ATTACK_DISPLAY_DELAY);
// do attack
AttackerStateUpdate(victim, BASE_ATTACK);
resetAttackTimer(BASE_ATTACK);
}
}
if (haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
{
if (!IsWithinMeleeRange(victim))
setAttackTimer(OFF_ATTACK, 100);
else if (!HasInArc(2 * float(M_PI) / 3, victim))
setAttackTimer(OFF_ATTACK, 100);
else
{
// prevent base and off attack in same time, delay attack at 0.2 sec
if (getAttackTimer(BASE_ATTACK) < ATTACK_DISPLAY_DELAY)
setAttackTimer(BASE_ATTACK, ATTACK_DISPLAY_DELAY);
// do attack
AttackerStateUpdate(victim, OFF_ATTACK);
resetAttackTimer(OFF_ATTACK);
}
}
/*Unit* owner = victim->GetOwner();
Unit* u = owner ? owner : victim;
if (u->IsPvP() && (!duel || duel->opponent != u))
{
UpdatePvP(true);
RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
}*/
}
}
if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
{
if (roll_chance_i(3) && _restTime > 0) // freeze update
{
time_t currTime = GameTime::GetGameTime();
time_t timeDiff = currTime - _restTime;
if (timeDiff >= 10) // freeze update
{
_restTime = currTime;
float bubble = 0.125f * sWorld->getRate(RATE_REST_INGAME);
float extraPerSec = ((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP) / 72000.0f) * bubble;
// speed collect rest bonus (section/in hour)
float currRestBonus = GetRestBonus();
SetRestBonus(currRestBonus + timeDiff * extraPerSec);
}
}
}
if (m_weaponChangeTimer > 0)
{
if (p_time >= m_weaponChangeTimer)
m_weaponChangeTimer = 0;
else
m_weaponChangeTimer -= p_time;
}
if (m_zoneUpdateTimer > 0)
{
if (p_time >= m_zoneUpdateTimer)
{
// On zone update tick check if we are still in an inn if we are supposed to be in one
if (HasRestFlag(REST_FLAG_IN_TAVERN))
{
AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(GetInnTriggerId());
if (!atEntry || !IsInAreaTriggerRadius(atEntry))
RemoveRestFlag(REST_FLAG_IN_TAVERN);
}
uint32 newzone, newarea;
GetZoneAndAreaId(newzone, newarea);
if (m_zoneUpdateId != newzone)
UpdateZone(newzone, newarea); // also update area
else
{
// use area updates as well
// needed for free far all arenas for example
if (m_areaUpdateId != newarea)
UpdateArea(newarea);
m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
}
}
else
m_zoneUpdateTimer -= p_time;
}
if (IsAlive())
{
m_regenTimer += p_time;
RegenerateAll();
}
if (m_deathState == JUST_DIED)
KillPlayer();
if (m_nextSave > 0)
{
if (p_time >= m_nextSave)
{
// m_nextSave reset in SaveToDB call
SaveToDB();
TC_LOG_DEBUG("entities.player", "Player::Update: Player '{}' ({}) saved", GetName(), GetGUID().ToString());
}
else
m_nextSave -= p_time;
}
//Handle Water/drowning
HandleDrowning(p_time);
// Played time
if (now > m_Last_tick)
{
uint32 elapsed = uint32(now - m_Last_tick);
m_Played_time[PLAYED_TIME_TOTAL] += elapsed; // Total played time
m_Played_time[PLAYED_TIME_LEVEL] += elapsed; // Level played time
m_Last_tick = now;
}
if (GetDrunkValue())
{
m_drunkTimer += p_time;
if (m_drunkTimer > 9 * IN_MILLISECONDS)
HandleSobering();
}
if (HasPendingBind())
{
if (_pendingBindTimer <= p_time)
{
// Player left the instance
if (_pendingBindId == GetInstanceId())
BindToInstance();
SetPendingBind(0, 0);
}
else
_pendingBindTimer -= p_time;
}
// not auto-free ghost from body in instances or if its affected by risen ally
if (m_deathTimer > 0 && !GetMap()->Instanceable() && !HasAuraType(SPELL_AURA_PREVENT_RESURRECTION) && !IsGhouled())
{
if (p_time >= m_deathTimer)
{
m_deathTimer = 0;
BuildPlayerRepop();
RepopAtGraveyard();
}
else
m_deathTimer -= p_time;
}
UpdateEnchantTime(p_time);
UpdateHomebindTime(p_time);
if (GetClass() == CLASS_DEATH_KNIGHT)
{
// Update rune timers
for (uint8 i = 0; i < MAX_RUNES; ++i)
{
uint32 timer = GetRuneTimer(i);
// Don't update timer if rune is disabled
if (GetRuneCooldown(i))
continue;
// Timer has began
if (timer < 0xFFFFFFFF)
{
timer += p_time;
SetRuneTimer(i, std::min(uint32(2500), timer));
}
}
}
// group update
m_groupUpdateTimer.Update(p_time);
if (m_groupUpdateTimer.Passed())
{
SendUpdateToOutOfRangeGroupMembers();
m_groupUpdateTimer.Reset(5000);
}
Pet* pet = GetPet();
if (pet && !pet->IsWithinDistInMap(this, GetMap()->GetVisibilityRange()) && !pet->isPossessed())
//if (pet && !pet->IsWithinDistInMap(this, GetMap()->GetVisibilityDistance()) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID())))
RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
if (IsAlive())
{
if (m_hostileReferenceCheckTimer <= p_time)
{
m_hostileReferenceCheckTimer = 15 * IN_MILLISECONDS;
if (!GetMap()->IsDungeon())
GetCombatManager().EndCombatBeyondRange(GetVisibilityRange(), true);
}
else
m_hostileReferenceCheckTimer -= p_time;
}
if (IsHasDelayedTeleport())
TeleportTo(m_teleport_dest, m_teleport_options);
}
void Player::setDeathState(DeathState s)
{
uint32 ressSpellId = 0;
bool cur = IsAlive();
if (s == JUST_DIED)
{
if (!cur)
{
TC_LOG_ERROR("entities.player", "Player::setDeathState: Attempt to kill a dead player '{}' ({})", GetName(), GetGUID().ToString());
return;
}
// drunken state is cleared on death
SetDrunkValue(0);
// lost combo points at any target (targeted combo points clear in Unit::setDeathState)
ClearComboPoints();
ClearResurrectRequestData();
//FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequest and define pet unsummon here with (s == DEAD)
RemovePet(nullptr, PET_SAVE_NOT_IN_SLOT, true);
// save value before aura remove in Unit::setDeathState
ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
// passive spell
if (!ressSpellId)
ressSpellId = GetResurrectionSpellId();
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH, 1);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON, 1);
// reset all death criterias
ResetAchievementCriteria(ACHIEVEMENT_CRITERIA_CONDITION_NO_DEATH, 0);
}
Unit::setDeathState(s);
// restore resurrection spell id for player after aura remove
if (s == JUST_DIED && cur && ressSpellId)
SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
if (IsAlive() && !cur)
//clear aura case after resurrection by another way (spells will be applied before next death)
SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
}
bool Player::BuildEnumData(PreparedQueryResult result, WorldPacket* data)
{
// 0 1 2 3 4 5 6 7
// SELECT characters.guid, characters.name, characters.race, characters.class, characters.gender, characters.skin, characters.face, characters.hairStyle,
// 8 9 10 11 12 13 14 15
// characters.hairColor, characters.facialStyle, characters.level, characters.zone, characters.map, characters.position_x, characters.position_y, characters.position_z,
// 16 17 18 19 20 21 22
// guild_member.guildid, characters.playerFlags, characters.at_login, character_pet.entry, character_pet.modelid, character_pet.level, characters.equipmentCache,
// 23 24
// character_banned.guid, character_declinedname.genitive
Field* fields = result->Fetch();
ObjectGuid guid = ObjectGuid::Create<HighGuid::Player>(fields[0].GetUInt32());
uint8 playerRace = fields[2].GetUInt8();
uint8 playerClass = fields[3].GetUInt8();
uint8 gender = fields[4].GetUInt8();
PlayerInfo const* info = sObjectMgr->GetPlayerInfo(playerRace, playerClass);
if (!info)
{
TC_LOG_ERROR("entities.player.loading", "Player {} has incorrect race/class pair. Don't build enum.", guid);
return false;
}
else if (!IsValidGender(gender))
{
TC_LOG_ERROR("entities.player.loading", "Player ({}) has incorrect gender ({}), don't build enum.", guid, gender);
return false;
}
*data << guid;
*data << fields[1].GetString(); // name
*data << uint8(playerRace); // race
*data << uint8(playerClass); // class
*data << uint8(gender); // gender
uint8 skin = fields[5].GetUInt8();
uint8 face = fields[6].GetUInt8();
uint8 hairStyle = fields[7].GetUInt8();
uint8 hairColor = fields[8].GetUInt8();
uint8 facialStyle = fields[9].GetUInt8();
uint16 atLoginFlags = fields[18].GetUInt16();
if (!ValidateAppearance(uint8(playerRace), uint8(playerClass), gender, hairStyle, hairColor, face, facialStyle, skin))
{
TC_LOG_ERROR("entities.player.loading", "Player {} has wrong Appearance values (Hair/Skin/Color), forcing recustomize", guid);
// Make sure customization always works properly - send all zeroes instead
skin = 0, face = 0, hairStyle = 0, hairColor = 0, facialStyle = 0;
if (!(atLoginFlags & AT_LOGIN_CUSTOMIZE))
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ADD_AT_LOGIN_FLAG);
stmt->setUInt16(0, uint16(AT_LOGIN_CUSTOMIZE));
stmt->setUInt32(1, guid.GetCounter());
CharacterDatabase.Execute(stmt);
atLoginFlags |= AT_LOGIN_CUSTOMIZE;
}
}
*data << uint8(skin);
*data << uint8(face);
*data << uint8(hairStyle);
*data << uint8(hairColor);
*data << uint8(facialStyle);
*data << uint8(fields[10].GetUInt8()); // level
*data << uint32(fields[11].GetUInt16()); // zone
*data << uint32(fields[12].GetUInt16()); // map
*data << fields[13].GetFloat(); // x
*data << fields[14].GetFloat(); // y
*data << fields[15].GetFloat(); // z
*data << uint32(fields[16].GetUInt32()); // guild id
uint32 charFlags = 0;
uint32 playerFlags = fields[17].GetUInt32();
if (atLoginFlags & AT_LOGIN_RESURRECT)
playerFlags &= ~PLAYER_FLAGS_GHOST;
if (playerFlags & PLAYER_FLAGS_HIDE_HELM)
charFlags |= CHARACTER_FLAG_HIDE_HELM;
if (playerFlags & PLAYER_FLAGS_HIDE_CLOAK)
charFlags |= CHARACTER_FLAG_HIDE_CLOAK;
if (playerFlags & PLAYER_FLAGS_GHOST)
charFlags |= CHARACTER_FLAG_GHOST;
if (atLoginFlags & AT_LOGIN_RENAME)
charFlags |= CHARACTER_FLAG_RENAME;
if (fields[23].GetUInt32())
charFlags |= CHARACTER_FLAG_LOCKED_BY_BILLING;
if (sWorld->getBoolConfig(CONFIG_DECLINED_NAMES_USED))
{
if (!fields[24].GetString().empty())
charFlags |= CHARACTER_FLAG_DECLINED;
}
else
charFlags |= CHARACTER_FLAG_DECLINED;
*data << uint32(charFlags); // character flags
// character customize flags
if (atLoginFlags & AT_LOGIN_CUSTOMIZE)
*data << uint32(CHAR_CUSTOMIZE_FLAG_CUSTOMIZE);
else if (atLoginFlags & AT_LOGIN_CHANGE_FACTION)
*data << uint32(CHAR_CUSTOMIZE_FLAG_FACTION);
else if (atLoginFlags & AT_LOGIN_CHANGE_RACE)
*data << uint32(CHAR_CUSTOMIZE_FLAG_RACE);
else
*data << uint32(CHAR_CUSTOMIZE_FLAG_NONE);
// First login
*data << uint8(atLoginFlags & AT_LOGIN_FIRST ? 1 : 0);
// Pets info
uint32 petDisplayId = 0;
uint32 petLevel = 0;
CreatureFamily petFamily = CREATURE_FAMILY_NONE;
// show pet at selection character in character list only for non-ghost character
if (result && !(playerFlags & PLAYER_FLAGS_GHOST) && (playerClass == CLASS_WARLOCK || playerClass == CLASS_HUNTER || playerClass == CLASS_DEATH_KNIGHT))
{
uint32 entry = fields[19].GetUInt32();
CreatureTemplate const* creatureInfo = sObjectMgr->GetCreatureTemplate(entry);
if (creatureInfo)
{
petDisplayId = fields[20].GetUInt32();
petLevel = fields[21].GetUInt16();
petFamily = creatureInfo->family;
}
}
*data << uint32(petDisplayId);
*data << uint32(petLevel);
*data << uint32(petFamily);
std::vector<std::string_view> equipment = Trinity::Tokenize(fields[22].GetStringView(), ' ', false);
for (uint8 slot = 0; slot < INVENTORY_SLOT_BAG_END; ++slot)
{
uint32 const visualBase = slot * 2;
Optional<uint32> itemId;
if (visualBase < equipment.size())
itemId = Trinity::StringTo<uint32>(equipment[visualBase]);
ItemTemplate const* proto = nullptr;
if (itemId)
proto = sObjectMgr->GetItemTemplate(*itemId);
if (!proto)
{
if (!itemId || *itemId)
{
TC_LOG_WARN("entities.player.loading", "Player {} has invalid equipment '{}' in `equipmentcache` at index {}. Skipped.",
guid, (visualBase < equipment.size()) ? std::string(equipment[visualBase]) : "<none>", visualBase);
}
*data << uint32(0);
*data << uint8(0);
*data << uint32(0);
continue;
}
SpellItemEnchantmentEntry const* enchant = nullptr;
Optional<uint32> enchants;
if ((visualBase+1) < equipment.size())
enchants = Trinity::StringTo<uint32>(equipment[visualBase + 1]);
if (!enchants)
{
TC_LOG_WARN("entities.player.loading", "Player {} has invalid enchantment info '{}' in `equipmentcache` at index {}. Skipped.",
guid, ((visualBase+1) < equipment.size()) ? std::string(equipment[visualBase + 1]) : "<none>", visualBase + 1);
enchants = 0;
}
for (uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot <= TEMP_ENCHANTMENT_SLOT; ++enchantSlot)
{
// values stored in 2 uint16
uint32 enchantId = 0x0000FFFF & ((*enchants) >> enchantSlot * 16);
if (!enchantId)
continue;
enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId);
if (enchant)
break;
}
*data << uint32(proto->DisplayInfoID);
*data << uint8(proto->InventoryType);
*data << uint32(enchant ? enchant->ItemVisual : 0);
}
return true;
}
void Player::ToggleAFK()
{
ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
// afk player not allowed in battleground
if (!GetSession()->HasPermission(rbac::RBAC_PERM_CAN_AFK_ON_BATTLEGROUND) && isAFK() && InBattleground() && !InArena())
LeaveBattleground();
}
void Player::ToggleDND()
{
ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
}
uint8 Player::GetChatTag() const
{
uint8 tag = CHAT_TAG_NONE;
if (isGMChat())
tag |= CHAT_TAG_GM;
if (isDND())
tag |= CHAT_TAG_DND;
if (isAFK())
tag |= CHAT_TAG_AFK;
if (IsDeveloper())
tag |= CHAT_TAG_DEV;
return tag;
}
bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
{
if (!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
{
TC_LOG_ERROR("maps", "Player::TeleportTo: Invalid map ({}) or invalid coordinates (X: {}, Y: {}, Z: {}, O: {}) given when teleporting player '{}' ({}, MapID: {}, X: {}, Y: {}, Z: {}, O: {}).",
mapid, x, y, z, orientation, GetGUID().ToString(), GetName(), GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
return false;
}
if (!GetSession()->HasPermission(rbac::RBAC_PERM_SKIP_CHECK_DISABLE_MAP) && DisableMgr::IsDisabledFor(DISABLE_TYPE_MAP, mapid, this))
{
TC_LOG_ERROR("entities.player.cheat", "Player::TeleportTo: Player '{}' ({}) tried to enter a forbidden map (MapID: {})", GetGUID().ToString(), GetName(), mapid);
SendTransferAborted(mapid, TRANSFER_ABORT_MAP_NOT_ALLOWED);
return false;
}
// preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
Pet* pet = GetPet();
MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
// don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
// don't let gm level > 1 either
if (!InBattleground() && mEntry->IsBattlegroundOrArena())
return false;
// client without expansion support
if (GetSession()->Expansion() < mEntry->Expansion())
{
TC_LOG_DEBUG("maps", "Player '{}' ({}) using client without required expansion tried teleport to non accessible map (MapID: {})",
GetName(), GetGUID().ToString(), mapid);
if (Transport* transport = GetTransport())
{
transport->RemovePassenger(this);
RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
}
SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion());
return false; // normal client can't teleport to this map...
}
else
TC_LOG_DEBUG("maps", "Player {} ({}) is being teleported to map (MapID: {})", GetName(), GetGUID().ToString(), mapid);
if (m_vehicle)
ExitVehicle();
// reset movement flags at teleport, because player will continue move with these flags after teleport
SetUnitMovementFlags(GetUnitMovementFlags() & MOVEMENTFLAG_MASK_HAS_PLAYER_STATUS_OPCODE);
DisableSpline();
GetMotionMaster()->Remove(EFFECT_MOTION_TYPE);
if (Transport* transport = GetTransport())
{
if (options & TELE_TO_NOT_LEAVE_TRANSPORT)
AddUnitMovementFlag(MOVEMENTFLAG_ONTRANSPORT);
else
transport->RemovePassenger(this);
}
// The player was ported to another map and loses the duel immediately.
// We have to perform this check before the teleport, otherwise the
// ObjectAccessor won't find the flag.
if (duel && GetMapId() != mapid && GetMap()->GetGameObject(GetGuidValue(PLAYER_DUEL_ARBITER)))
DuelComplete(DUEL_FLED);
if (GetMapId() == mapid)
{
//lets reset far teleport flag if it wasn't reset during chained teleport
SetSemaphoreTeleportFar(false);
//setup delayed teleport flag
SetDelayedTeleportFlag(IsCanDelayTeleport());
//if teleport spell is cast in Unit::Update() func
//then we need to delay it until update process will be finished
if (IsHasDelayedTeleport())
{
SetSemaphoreTeleportNear(true);
//lets save teleport destination for player
m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
m_teleport_options = options;
return true;
}
if (!(options & TELE_TO_NOT_UNSUMMON_PET))
{
//same map, only remove pet if out of range for new position
if (pet && !pet->IsWithinDist3d(x, y, z, GetMap()->GetVisibilityRange()))
UnsummonPetTemporaryIfAny();
}
if (!IsAlive() && options & TELE_REVIVE_AT_TELEPORT)
ResurrectPlayer(0.5f);
if (!(options & TELE_TO_NOT_LEAVE_COMBAT))
CombatStop();
// this will be used instead of the current location in SaveToDB
m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
SetFallInformation(0, GetPositionZ());
// code for finish transfer called in WorldSession::HandleMovementOpcodes()
// at client packet MSG_MOVE_TELEPORT_ACK
SetSemaphoreTeleportNear(true);
// near teleport, triggering send MSG_MOVE_TELEPORT_ACK from client at landing
if (!GetSession()->PlayerLogout())
SendTeleportPacket(m_teleport_dest, (options & TELE_TO_TRANSPORT_TELEPORT) != 0);
}
else
{
if (GetClass() == CLASS_DEATH_KNIGHT && GetMapId() == 609 && !IsGameMaster() && !HasSpell(50977))
{
SendTransferAborted(mapid, TRANSFER_ABORT_UNIQUE_MESSAGE, 1);
return false;
}
// far teleport to another map
Map* oldmap = IsInWorld() ? GetMap() : nullptr;
// check if we can enter before stopping combat / removing pet / totems / interrupting spells
// Check enter rights before map getting to avoid creating instance copy for player
// this check not dependent from map instance copy and same for all instance copies of selected map
if (sMapMgr->PlayerCannotEnter(mapid, this, false))
return false;
//I think this always returns true. Correct me if I am wrong.
// If the map is not created, assume it is possible to enter it.
// It will be created in the WorldPortAck.
//Map* map = sMapMgr->FindBaseNonInstanceMap(mapid);
//if (!map || map->CanEnter(this))
{
//lets reset near teleport flag if it wasn't reset during chained teleports
SetSemaphoreTeleportNear(false);
//setup delayed teleport flag
SetDelayedTeleportFlag(IsCanDelayTeleport());
//if teleport spell is cast in Unit::Update() func
//then we need to delay it until update process will be finished
if (IsHasDelayedTeleport())
{
SetSemaphoreTeleportFar(true);
//lets save teleport destination for player
m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
m_teleport_options = options;
return true;
}
SetSelection(ObjectGuid::Empty);
CombatStop();
ResetContestedPvP();
// remove player from battleground on far teleport (when changing maps)
if (Battleground const* bg = GetBattleground())
{
// Note: at battleground join battleground id set before teleport
// and we already will found "current" battleground
// just need check that this is targeted map or leave
if (bg->GetMapId() != mapid)
LeaveBattleground(false); // don't teleport to entry point
}
// remove arena spell coldowns/buffs now to also remove pet's cooldowns before it's temporarily unsummoned
if (mEntry->IsBattleArena() && !IsGameMaster())
{
RemoveArenaSpellCooldowns(true);
RemoveArenaAuras();
if (pet)
pet->RemoveArenaAuras();
}
// remove pet on map change
if (pet)
UnsummonPetTemporaryIfAny();
// remove all dyn objects
RemoveAllDynObjects();
// stop spellcasting
// not attempt interrupt teleportation spell at caster teleport
if (!(options & TELE_TO_SPELL))
if (IsNonMeleeSpellCast(true))
InterruptNonMeleeSpells(true);
//remove auras before removing from map...
RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP | AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
if (!GetSession()->PlayerLogout())
{
// send transfer packets
WorldPacket data(SMSG_TRANSFER_PENDING, 4 + 4 + 4);
data << uint32(mapid);
if (Transport* transport = GetTransport())
data << transport->GetEntry() << GetMapId();
SendDirectMessage(&data);
}
// remove from old map now
if (oldmap)
oldmap->RemovePlayerFromMap(this, false);
// players on mount will be dismounted. the speed and height change should not require an ACK and should be applied directly
PurgeAndApplyPendingMovementChanges(false);
m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
m_teleport_options = options;
SetFallInformation(0, GetPositionZ());
// if the player is saved before worldportack (at logout for example)
// this will be used instead of the current location in SaveToDB
if (!GetSession()->PlayerLogout())
{
WorldPacket data(SMSG_NEW_WORLD, 4 + 4 + 4 + 4 + 4);
data << uint32(mapid);
if (GetTransport())
data << m_movementInfo.transport.pos.PositionXYZOStream();
else
data << m_teleport_dest.PositionXYZOStream();
SendDirectMessage(&data);
SendSavedInstances();
}
// move packet sent by client always after far teleport
// code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
SetSemaphoreTeleportFar(true);
}
//else
// return false;
}
return true;
}
bool Player::TeleportTo(WorldLocation const& loc, uint32 options /*= 0*/)
{
return TeleportTo(loc.GetMapId(), loc.GetPositionX(), loc.GetPositionY(), loc.GetPositionZ(), loc.GetOrientation(), options);
}
bool Player::TeleportToBGEntryPoint()
{
if (m_bgData.joinPos.m_mapId == MAPID_INVALID)
return false;
ScheduleDelayedOperation(DELAYED_BG_MOUNT_RESTORE);
ScheduleDelayedOperation(DELAYED_BG_TAXI_RESTORE);
return TeleportTo(m_bgData.joinPos);
}
void Player::ProcessDelayedOperations()
{
if (m_DelayedOperations == 0)
return;
if (m_DelayedOperations & DELAYED_RESURRECT_PLAYER)
ResurrectUsingRequestDataImpl();
if (m_DelayedOperations & DELAYED_SAVE_PLAYER)
SaveToDB();
if (m_DelayedOperations & DELAYED_SPELL_CAST_DESERTER)
CastSpell(this, 26013, true); // Deserter
if (m_DelayedOperations & DELAYED_BG_MOUNT_RESTORE)
{
if (m_bgData.mountSpell)
{
CastSpell(this, m_bgData.mountSpell, true);
m_bgData.mountSpell = 0;
}
}
if (m_DelayedOperations & DELAYED_BG_TAXI_RESTORE)
{
if (m_bgData.HasTaxiPath())
{
m_taxi.AddTaxiDestination(m_bgData.taxiPath[0]);
m_taxi.AddTaxiDestination(m_bgData.taxiPath[1]);
m_bgData.ClearTaxiPath();
ContinueTaxiFlight();
}
}
//we have executed ALL delayed ops, so clear the flag
m_DelayedOperations = 0;
}
void Player::AddToWorld()
{
///- Do not add/remove the player from the object storage
///- It will crash when updating the ObjectAccessor
///- The player should only be added when logging in
Unit::AddToWorld();
for (uint8 i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
if (m_items[i])
m_items[i]->AddToWorld();
}
void Player::RemoveFromWorld()
{
// cleanup
if (IsInWorld())
{
///- Release charmed creatures, unsummon totems and remove pets/guardians
StopCastingCharm();
StopCastingBindSight();
UnsummonPetTemporaryIfAny();
ClearComboPoints();
ClearComboPointHolders();
ObjectGuid lootGuid = GetLootGUID();
if (!lootGuid.IsEmpty())
m_session->DoLootRelease(lootGuid);
sOutdoorPvPMgr->HandlePlayerLeaveZone(this, m_zoneUpdateId);
sBattlefieldMgr->HandlePlayerLeaveZone(this, m_zoneUpdateId);
}
// Remove items from world before self - player must be found in Item::RemoveFromObjectUpdate
for (uint8 i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
{
if (m_items[i])
m_items[i]->RemoveFromWorld();
}
///- Do not add/remove the player from the object storage
///- It will crash when updating the ObjectAccessor
///- The player should only be removed when logging out
Unit::RemoveFromWorld();
for (ItemMap::iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
iter->second->RemoveFromWorld();
if (m_uint32Values)
{
if (WorldObject* viewpoint = GetViewpoint())
{
TC_LOG_ERROR("entities.player", "Player::RemoveFromWorld: Player '{}' ({}) has viewpoint (Entry:{}, Type: {}) when removed from world",
GetName(), GetGUID().ToString(), viewpoint->GetEntry(), viewpoint->GetTypeId());
SetViewpoint(viewpoint, false);
}
}
}
void Player::SetObjectScale(float scale)
{
Unit::SetObjectScale(scale);
SetBoundingRadius(scale * DEFAULT_PLAYER_BOUNDING_RADIUS);
SetCombatReach(scale * DEFAULT_PLAYER_COMBAT_REACH);
}
bool Player::IsImmunedToSpellEffect(SpellInfo const* spellInfo, SpellEffectInfo const& spellEffectInfo, WorldObject const* caster,
bool requireImmunityPurgesEffectAttribute /*= false*/) const
{
// players are immune to taunt (the aura and the spell effect)
if (spellEffectInfo.IsAura(SPELL_AURA_MOD_TAUNT))
return true;
if (spellEffectInfo.IsEffect(SPELL_EFFECT_ATTACK_ME))
return true;
return Unit::IsImmunedToSpellEffect(spellInfo, spellEffectInfo, caster, requireImmunityPurgesEffectAttribute);
}
void Player::RegenerateAll()
{
m_regenTimerCount += m_regenTimer;
m_foodEmoteTimerCount += m_regenTimer;
Regenerate(POWER_ENERGY);
Regenerate(POWER_MANA);
Regenerate(POWER_RAGE);
Regenerate(POWER_RUNIC_POWER);
// Runes act as cooldowns, and they don't need to send any data
if (GetClass() == CLASS_DEATH_KNIGHT)
for (uint8 i = 0; i < MAX_RUNES; ++i)
if (uint32 cd = GetRuneCooldown(i))
SetRuneCooldown(i, (cd > m_regenTimer) ? cd - m_regenTimer : 0);
if (m_regenTimerCount >= 2000)
{
// Not in combat or they have regeneration
if (!IsInCombat() || IsPolymorphed() || m_baseHealthRegen ||
HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT))
{
RegenerateHealth();
}
m_regenTimerCount -= 2000;
}
m_regenTimer = 0;
// Handles the emotes for drinking and eating.
// According to sniffs there is a background timer going on that repeats independed from the time window where the aura applies.
// That's why we dont need to reset the timer on apply. In sniffs I have seen that the first call for the spell visual is totally random, then after
// 5 seconds over and over again which confirms my theory that we have a independed timer.
if (m_foodEmoteTimerCount >= 5000)
{
std::vector<AuraEffect*> auraList;
AuraEffectList const& ModRegenAuras = GetAuraEffectsByType(SPELL_AURA_MOD_REGEN);
AuraEffectList const& ModPowerRegenAuras = GetAuraEffectsByType(SPELL_AURA_MOD_POWER_REGEN);
auraList.reserve(ModRegenAuras.size() + ModPowerRegenAuras.size());
auraList.insert(auraList.end(), ModRegenAuras.begin(), ModRegenAuras.end());
auraList.insert(auraList.end(), ModPowerRegenAuras.begin(), ModPowerRegenAuras.end());
for (auto itr = auraList.begin(); itr != auraList.end(); ++itr)
{
// Food emote comes above drinking emote if we have to decide (mage regen food for example)
if ((*itr)->GetBase()->HasEffectType(SPELL_AURA_MOD_REGEN) && (*itr)->GetSpellInfo()->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED)
{
SendPlaySpellVisualKit(SPELL_VISUAL_KIT_FOOD, 0);
break;
}
else if ((*itr)->GetBase()->HasEffectType(SPELL_AURA_MOD_POWER_REGEN) && (*itr)->GetSpellInfo()->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED)
{
SendPlaySpellVisualKit(SPELL_VISUAL_KIT_DRINK, 0);
break;
}
}
m_foodEmoteTimerCount -= 5000;
}
}
void Player::Regenerate(Powers power)
{
uint32 maxValue = GetMaxPower(power);
if (!maxValue)
return;
uint32 curValue = GetPower(power);
float addvalue = GetPowerRegen(power) * 0.001f * m_regenTimer;
if (addvalue < 0.0f)
{
if (curValue == 0)
return;
}
else if (addvalue > 0.0f)
{
if (curValue == maxValue)
return;
}
else
return;
addvalue += m_powerFraction[power];
uint32 integerValue = uint32(std::fabs(addvalue));
if (addvalue < 0.0f)
{
if (curValue > integerValue)
{
curValue -= integerValue;
m_powerFraction[power] = addvalue + integerValue;
}
else
{
curValue = 0;
m_powerFraction[power] = 0;
}
}
else
{
curValue += integerValue;
if (curValue > maxValue)
{
curValue = maxValue;
m_powerFraction[power] = 0;
}
else
m_powerFraction[power] = addvalue - integerValue;
}
if (m_regenTimerCount >= 2000 || curValue == maxValue || curValue == 0)
SetPower(power, curValue, true, true);
else
UpdateUInt32Value(UNIT_FIELD_POWER1 + AsUnderlyingType(power), curValue);
}
void Player::RegenerateHealth()
{
uint32 curValue = GetHealth();
uint32 maxValue = GetMaxHealth();
if (curValue >= maxValue)
return;
float HealthIncreaseRate = sWorld->getRate(RATE_HEALTH);
if (GetLevel() < 15)
HealthIncreaseRate = sWorld->getRate(RATE_HEALTH) * (2.066f - (GetLevel() * 0.066f));
float addValue = 0.0f;
// polymorphed case
if (IsPolymorphed())
addValue = float(GetMaxHealth()) / 3.0f;
// normal regen case (maybe partly in combat case)
else if (!IsInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
{
addValue = OCTRegenHPPerSpirit() * HealthIncreaseRate;
if (!IsInCombat())
{
addValue *= GetTotalAuraMultiplier(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
addValue += GetTotalAuraModifier(SPELL_AURA_MOD_REGEN) * 0.4f;
}
else if (HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
ApplyPct(addValue, GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT));
if (!IsStandState())
addValue *= 1.5f;
}
// always regeneration bonus (including combat)
addValue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
addValue += m_baseHealthRegen / 2.5f;
if (addValue < 0.0f)
addValue = 0.0f;
ModifyHealth(int32(addValue));
}
void Player::ResetAllPowers()
{
SetFullHealth();
switch (GetPowerType())
{
case POWER_MANA:
SetFullPower(POWER_MANA);
break;
case POWER_RAGE:
SetPower(POWER_RAGE, 0);
break;
case POWER_ENERGY:
SetFullPower(POWER_ENERGY);
break;
case POWER_RUNIC_POWER:
SetPower(POWER_RUNIC_POWER, 0);
break;
default:
break;
}
}
bool Player::CanInteractWithQuestGiver(Object* questGiver) const
{
switch (questGiver->GetTypeId())
{
case TYPEID_UNIT:
return GetNPCIfCanInteractWith(questGiver->GetGUID(), UNIT_NPC_FLAG_QUESTGIVER) != nullptr;
case TYPEID_GAMEOBJECT:
return GetGameObjectIfCanInteractWith(questGiver->GetGUID(), GAMEOBJECT_TYPE_QUESTGIVER) != nullptr;
case TYPEID_PLAYER:
return IsAlive() && questGiver->ToPlayer()->IsAlive();
case TYPEID_ITEM:
return IsAlive();
default:
break;
}
return false;
}
Creature* Player::GetNPCIfCanInteractWith(ObjectGuid const& guid, NPCFlags npcFlags) const
{
// unit checks
if (!guid)
return nullptr;
if (!IsInWorld())
return nullptr;
if (IsInFlight())
return nullptr;
// exist (we need look pets also for some interaction (quest/etc)
Creature* creature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, guid);
if (!creature)
return nullptr;
// Deathstate checks
if (!IsAlive() && !(creature->GetCreatureTemplate()->type_flags & CREATURE_TYPE_FLAG_VISIBLE_TO_GHOSTS))
return nullptr;
// alive or spirit healer
if (!creature->IsAlive() && !(creature->GetCreatureTemplate()->type_flags & CREATURE_TYPE_FLAG_INTERACT_WHILE_DEAD))
return nullptr;
// appropriate npc type
if (npcFlags && !creature->HasNpcFlag(npcFlags))
return nullptr;
// not allow interaction under control, but allow with own pets
if (!creature->GetCharmerGUID().IsEmpty())
return nullptr;
// not unfriendly/hostile
if (creature->GetReactionTo(this) <= REP_UNFRIENDLY)
return nullptr;
// not too far, taken from CGGameUI::SetInteractTarget
if (!creature->IsWithinDistInMap(this, creature->GetCombatReach() + 4.0f))
return nullptr;
return creature;
}
GameObject* Player::GetGameObjectIfCanInteractWith(ObjectGuid const& guid) const
{
if (!guid)
return nullptr;
if (!IsInWorld())
return nullptr;
if (IsInFlight())
return nullptr;
// exist
GameObject* go = ObjectAccessor::GetGameObject(*this, guid);
if (!go)
return nullptr;
// Players cannot interact with gameobjects that use the "Point" icon
if (go->GetGOInfo()->IconName == "Point")
return nullptr;
if (!go->IsWithinDistInMap(this))
return nullptr;
return go;
}
GameObject* Player::GetGameObjectIfCanInteractWith(ObjectGuid const& guid, GameobjectTypes type) const
{
GameObject* go = GetGameObjectIfCanInteractWith(guid);
if (!go)
return nullptr;
if (go->GetGoType() != type)
return nullptr;
return go;
}
bool Player::IsInAreaTriggerRadius(AreaTriggerEntry const* trigger) const
{
if (!trigger || GetMapId() != trigger->ContinentID)
return false;
if (trigger->Radius > 0.f)
{
// if we have radius check it
float dist = GetDistance(trigger->Pos.X, trigger->Pos.Y, trigger->Pos.Z);
if (dist > trigger->Radius)
return false;
}
else
{
Position center(trigger->Pos.X, trigger->Pos.Y, trigger->Pos.Z, trigger->BoxYaw);
if (!IsWithinBox(center, trigger->BoxLength / 2.f, trigger->BoxWidth / 2.f, trigger->BoxHeight / 2.f))
return false;
}
return true;
}
void Player::SetGameMaster(bool on)
{
if (on)
{
m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
SetFaction(FACTION_FRIENDLY);
SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
SetUnitFlag2(UNIT_FLAG2_ALLOW_CHEAT_SPELLS);
if (Pet* pet = GetPet())
pet->SetFaction(FACTION_FRIENDLY);
RemovePvpFlag(UNIT_BYTE2_FLAG_FFA_PVP);
ResetContestedPvP();
CombatStopWithPets();
SetPhaseMask(uint32(PHASEMASK_ANYWHERE), false); // see and visible in all phases
m_serverSideVisibilityDetect.SetValue(SERVERSIDE_VISIBILITY_GM, GetSession()->GetSecurity());
}
else
{
// restore phase
uint32 newPhase = 0;
AuraEffectList const& phases = GetAuraEffectsByType(SPELL_AURA_PHASE);
if (!phases.empty())
for (AuraEffectList::const_iterator itr = phases.begin(); itr != phases.end(); ++itr)
newPhase |= (*itr)->GetMiscValue();
if (!newPhase)
newPhase = PHASEMASK_NORMAL;
SetPhaseMask(newPhase, false);
m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
SetFactionForRace(GetRace());
RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
RemoveUnitFlag2(UNIT_FLAG2_ALLOW_CHEAT_SPELLS);
if (Pet* pet = GetPet())
pet->SetFaction(GetFaction());
// restore FFA PvP Server state
if (sWorld->IsFFAPvPRealm())
SetPvpFlag(UNIT_BYTE2_FLAG_FFA_PVP);
// restore FFA PvP area state, remove not allowed for GM mounts
UpdateArea(m_areaUpdateId);
m_serverSideVisibilityDetect.SetValue(SERVERSIDE_VISIBILITY_GM, SEC_PLAYER);
}
UpdateObjectVisibility();
}
bool Player::CanBeGameMaster() const
{
return GetSession()->HasPermission(rbac::RBAC_PERM_COMMAND_GM);
}
void Player::SetGMVisible(bool on)
{
if (on)
{
m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
m_serverSideVisibility.SetValue(SERVERSIDE_VISIBILITY_GM, SEC_PLAYER);
}
else
{
m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
SetAcceptWhispers(false);
SetGameMaster(true);
m_serverSideVisibility.SetValue(SERVERSIDE_VISIBILITY_GM, GetSession()->GetSecurity());
}
for (Channel* channel : m_channels)
channel->SetInvisible(this, !on);
}
bool Player::IsGroupVisibleFor(Player const* p) const
{
switch (sWorld->getIntConfig(CONFIG_GROUP_VISIBILITY))
{
default: return IsInSameGroupWith(p);
case 1: return IsInSameRaidWith(p);
case 2: return GetTeam() == p->GetTeam();
case 3: return false;
}
}
bool Player::IsInSameGroupWith(Player const* p) const
{
return p == this || (GetGroup() != nullptr &&
GetGroup() == p->GetGroup() &&
GetGroup()->SameSubGroup(this, p));
}
bool Player::IsInSameRaidWith(Player const* p) const
{
return p == this || (GetGroup() != nullptr && GetGroup() == p->GetGroup());
}
///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
void Player::UninviteFromGroup()
{
Group* group = GetGroupInvite();
if (!group)
return;
group->RemoveInvite(this);
if (group->IsCreated())
{
if (group->GetMembersCount() <= 1) // group has just 1 member => disband
group->Disband(true);
}
else
{
if (group->GetInviteeCount() <= 1)
{
group->RemoveAllInvites();
delete group;
}
}
}
void Player::RemoveFromGroup(Group* group, ObjectGuid guid, RemoveMethod method /*= GROUP_REMOVEMETHOD_DEFAULT*/, ObjectGuid kicker /*= ObjectGuid::Empty*/, char const* reason /*= nullptr*/)
{
if (!group)
return;
group->RemoveMember(guid, method, kicker, reason);
}
void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 BonusXP, bool recruitAFriend, float /*group_rate*/) const
{
WorldPacket data(SMSG_LOG_XPGAIN, 21); // guess size?
data << (victim ? victim->GetGUID() : ObjectGuid::Empty);
data << uint32(GivenXP + BonusXP); // given experience
data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
if (victim)
{
data << uint32(GivenXP); // experience without bonus
// should use group_rate here but can't figure out how
data << float(1); // 1 - none 0 - 100% group bonus output
}
data << uint8(recruitAFriend ? 1 : 0); // does the GivenXP include a RaF bonus?
SendDirectMessage(&data);
}
void Player::GiveXP(uint32 xp, Unit* victim, float group_rate)
{
if (xp < 1)
return;
if (!IsAlive() && !GetBattlegroundId())
return;
if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_NO_XP_GAIN))
return;
if (victim && victim->GetTypeId() == TYPEID_UNIT && !victim->ToCreature()->hasLootRecipient())
return;
uint8 level = GetLevel();
sScriptMgr->OnGivePlayerXP(this, xp, victim);
// XP to money conversion processed in Player::RewardQuest
if (IsMaxLevel())
return;
uint32 bonus_xp;
bool recruitAFriend = GetsRecruitAFriendBonus(true);
// RaF does NOT stack with rested experience
if (recruitAFriend)
bonus_xp = 2 * xp; // xp + bonus_xp must add up to 3 * xp for RaF; calculation for quests done client-side
else
bonus_xp = victim ? GetXPRestBonus(xp) : 0; // XP resting bonus
SendLogXPGain(xp, victim, bonus_xp, recruitAFriend, group_rate);
uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
uint32 newXP = GetXP() + xp + bonus_xp;
while (newXP >= nextLvlXP && !IsMaxLevel())
{
newXP -= nextLvlXP;
if (!IsMaxLevel())
GiveLevel(level + 1);
level = GetLevel();
nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
}
SetXP(newXP);
}
// Update player to next level
// Current player experience not update (must be update by caller)
void Player::GiveLevel(uint8 level)
{
uint8 oldLevel = GetLevel();
if (level == oldLevel)
return;
if (Guild* guild = GetGuild())
guild->UpdateMemberData(this, GUILD_MEMBER_DATA_LEVEL, level);
PlayerLevelInfo info;
sObjectMgr->GetPlayerLevelInfo(GetRace(), GetClass(), level, &info);
PlayerClassLevelInfo classInfo;
sObjectMgr->GetPlayerClassLevelInfo(GetClass(), level, &classInfo);
WorldPackets::Misc::LevelUpInfo packet;
packet.Level = level;
packet.HealthDelta = int32(classInfo.basehealth) - int32(GetCreateHealth());
/// @todo find some better solution
// for (int i = 0; i < MAX_POWERS; ++i)
packet.PowerDelta[0] = int32(classInfo.basemana) - int32(GetCreateMana());
packet.PowerDelta[1] = 0;
packet.PowerDelta[2] = 0;
packet.PowerDelta[3] = 0;
packet.PowerDelta[4] = 0;
packet.PowerDelta[5] = 0;
for (uint8 i = STAT_STRENGTH; i < MAX_STATS; ++i)
packet.StatDelta[i] = int32(info.stats[i]) - GetCreateStat(Stats(i));
SendDirectMessage(packet.Write());
SetUInt32Value(PLAYER_NEXT_LEVEL_XP, sObjectMgr->GetXPForLevel(level));
//update level, max level of skills
m_Played_time[PLAYED_TIME_LEVEL] = 0; // Level Played Time reset
_ApplyAllLevelScaleItemMods(false);
SetLevel(level);
UpdateSkillsForLevel();
// save base values (bonuses already included in stored stats
for (uint8 i = STAT_STRENGTH; i < MAX_STATS; ++i)
SetCreateStat(Stats(i), info.stats[i]);
SetCreateHealth(classInfo.basehealth);
SetCreateMana(classInfo.basemana);
InitTalentForLevel();
InitTaxiNodesForLevel();
InitGlyphsForLevel();
UpdateAllStats();
if (sWorld->getBoolConfig(CONFIG_ALWAYS_MAXSKILL)) // Max weapon skill when leveling up
UpdateWeaponsSkillsToMaxSkillsForLevel();
_ApplyAllLevelScaleItemMods(true);
// set current level health and mana/energy to maximum after applying all mods.
SetFullHealth();
SetFullPower(POWER_MANA);
// update level to hunter/summon pet
if (Pet* pet = GetPet())
pet->SynchronizeLevelWithOwner();
if (MailLevelReward const* mailReward = sObjectMgr->GetMailLevelReward(level, GetRaceMask()))
{
/// @todo Poor design of mail system
CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction();
MailDraft(mailReward->mailTemplateId).SendMailTo(trans, this, MailSender(MAIL_CREATURE, mailReward->senderEntry));
CharacterDatabase.CommitTransaction(trans);
}
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
// Refer-A-Friend
if (GetSession()->GetRecruiterId())
if (level < sWorld->getIntConfig(CONFIG_MAX_RECRUIT_A_FRIEND_BONUS_PLAYER_LEVEL))
if (level % 2 == 0)
{
++m_grantableLevels;
if (!HasByteFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTES_OFFSET_RAF_GRANTABLE_LEVEL, 0x01))
SetByteFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTES_OFFSET_RAF_GRANTABLE_LEVEL, 0x01);
}
SendQuestGiverStatusMultiple();
sScriptMgr->OnPlayerLevelChanged(this, oldLevel);
}
bool Player::IsMaxLevel() const
{
return GetLevel() >= GetUInt32Value(PLAYER_FIELD_MAX_LEVEL);
}
void Player::InitTalentForLevel()
{
uint8 level = GetLevel();
// talents base at level diff (talents = level - 9 but some can be used already)
if (level < 10)
{
// Remove all talent points
if (GetUsedTalentCount() > 0) // Free any used talents
{
ResetTalents(true);
SetFreeTalentPoints(0);
}
}
else
{
if (level < sWorld->getIntConfig(CONFIG_MIN_DUALSPEC_LEVEL) || GetSpecsCount() == 0)
{
SetSpecsCount(1);
SetActiveSpec(0);
}
uint32 talentPointsForLevel = CalculateTalentsPoints();
// if used more that have then reset
if (GetUsedTalentCount() > talentPointsForLevel)
{
if (!GetSession()->HasPermission(rbac::RBAC_PERM_SKIP_CHECK_MORE_TALENTS_THAN_ALLOWED))
ResetTalents(true);
else
SetFreeTalentPoints(0);
}
// else update amount of free points
else
SetFreeTalentPoints(talentPointsForLevel - GetUsedTalentCount());
}
if (!GetSession()->PlayerLoading())
SendTalentsInfoData(false); // update at client
}
void Player::InitStatsForLevel(bool reapplyMods)
{
if (reapplyMods) //reapply stats values only on .reset stats (level) command
_RemoveAllStatBonuses();
PlayerClassLevelInfo classInfo;
sObjectMgr->GetPlayerClassLevelInfo(GetClass(), GetLevel(), &classInfo);
PlayerLevelInfo info;
sObjectMgr->GetPlayerLevelInfo(GetRace(), GetClass(), GetLevel(), &info);
uint8 exp_max_lvl = GetMaxLevelForExpansion(GetSession()->Expansion());
uint8 conf_max_lvl = sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL);
if (exp_max_lvl == DEFAULT_MAX_LEVEL || exp_max_lvl >= conf_max_lvl)
SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, conf_max_lvl);
else
SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, exp_max_lvl);
SetUInt32Value(PLAYER_NEXT_LEVEL_XP, sObjectMgr->GetXPForLevel(GetLevel()));
// reset before any aura state sources (health set/aura apply)
SetUInt32Value(UNIT_FIELD_AURASTATE, 0);
UpdateSkillsForLevel();
// set default cast time multiplier
SetModCastingSpeed(1.0f);
// reset size before reapply auras
SetObjectScale(1.0f);
// save base values (bonuses already included in stored stats
for (uint8 i = STAT_STRENGTH; i < MAX_STATS; ++i)
SetCreateStat(Stats(i), info.stats[i]);
for (uint8 i = STAT_STRENGTH; i < MAX_STATS; ++i)
SetStat(Stats(i), info.stats[i]);
SetCreateHealth(classInfo.basehealth);
//set create powers
SetCreateMana(classInfo.basemana);
SetArmor(int32(m_createStats[STAT_AGILITY]*2));
InitStatBuffMods();
//reset rating fields values
for (uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
SetUInt32Value(index, 0);
SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS, 0);
for (uint8 i = SPELL_SCHOOL_NORMAL; i < MAX_SPELL_SCHOOL; ++i)
{
SetInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG + i, 0);
SetInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + i, 0);
SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT + i, 1.0f);
}
//reset attack power, damage and attack speed fields
for (uint8 i = BASE_ATTACK; i < MAX_ATTACK; ++i)
SetFloatValue(UNIT_FIELD_BASEATTACKTIME + i, float(BASE_ATTACK_TIME));
SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f);
SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f);
SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f);
SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f);
SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f);
SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f);
SetAttackPower(0);
SetAttackPowerModPos(0);
SetAttackPowerModNeg(0);
SetAttackPowerMultiplier(0.0f);
SetRangedAttackPower(0);
SetRangedAttackPowerModPos(0);
SetRangedAttackPowerModNeg(0);
SetRangedAttackPowerMultiplier(0.0f);
// Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
SetFloatValue(PLAYER_CRIT_PERCENTAGE, 0.0f);
SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE, 0.0f);
SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE, 0.0f);
// Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
for (uint8 i = 0; i < 7; ++i)
SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
// Dodge percentage
SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
// set armor (resistance 0) to original value (create_agility*2)
SetArmor(int32(m_createStats[STAT_AGILITY]*2));
SetFloatValue(UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE + AsUnderlyingType(SPELL_SCHOOL_NORMAL), 0.0f);
SetFloatValue(UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE + AsUnderlyingType(SPELL_SCHOOL_NORMAL), 0.0f);
// set other resistance to original value (0)
for (uint8 i = SPELL_SCHOOL_HOLY; i < MAX_SPELL_SCHOOL; ++i)
{
SetResistance(SpellSchools(i), 0);
SetFloatValue(UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE + i, 0.0f);
SetFloatValue(UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE + i, 0.0f);
}
SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE, 0);
SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE, 0);
for (uint8 i = SPELL_SCHOOL_NORMAL; i < MAX_SPELL_SCHOOL; ++i)
{
SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER + i, 0);
SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER + i, 0.0f);
}
// Reset no reagent cost field
for (uint8 i = 0; i < 3; ++i)
SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
// Init data for form but skip reapply item mods for form
InitDataForForm(reapplyMods);
// save new stats
for (uint8 i = POWER_MANA; i < MAX_POWERS; ++i)
SetMaxPower(Powers(i), uint32(GetCreatePowerValue(Powers(i))));
SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
// cleanup mounted state (it will set correctly at aura loading if player saved at mount.
SetMountDisplayId(0);
// cleanup unit flags (will be re-applied if need at aura load).
RemoveUnitFlag(
UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_REMOVE_CLIENT_CONTROL | UNIT_FLAG_NOT_ATTACKABLE_1 |
UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_NPC | UNIT_FLAG_LOOTING |
UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_UNINTERACTIBLE |
UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_ON_TAXI );
SetUnitFlag(UNIT_FLAG_PLAYER_CONTROLLED); // must be set
SetUnitFlag2(UNIT_FLAG2_REGENERATE_POWER);// must be set
// cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST | PLAYER_ALLOW_ONLY_ABILITY);
RemoveVisFlag(UNIT_VIS_FLAGS_ALL); // one form stealth modified bytes
RemovePvpFlag(UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);
// restore if need some important flags
SetUInt32Value(PLAYER_FIELD_BYTES2, 0); // flags empty by default
if (reapplyMods) // reapply stats values only on .reset stats (level) command
_ApplyAllStatBonuses();
// set current level health and mana/energy to maximum after applying all mods.
SetFullHealth();
SetFullPower(POWER_MANA);
SetFullPower(POWER_ENERGY);
if (GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
SetFullPower(POWER_RAGE);
SetFullPower(POWER_FOCUS);
SetPower(POWER_HAPPINESS, 0);
SetPower(POWER_RUNIC_POWER, 0);
// update level to hunter/summon pet
if (Pet* pet = GetPet())
pet->SynchronizeLevelWithOwner();
}
void Player::SendInitialSpells()
{
uint16 spellCooldowns = GetSpellHistory()->GetCooldownsSizeForPacket();
uint16 spellCount = 0;
WorldPacket data(SMSG_INITIAL_SPELLS, (1 + 2 + 4 * m_spells.size() + 2 + spellCooldowns * (2 + 2 + 2 + 4 + 4)));
data << uint8(0);
size_t countPos = data.wpos();
data << uint16(spellCount); // spell count placeholder
for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
{
if (itr->second.state == PLAYERSPELL_REMOVED)
continue;
if (!itr->second.active || itr->second.disabled)
continue;
data << uint32(itr->first);
data << uint16(0); // it's not slot id
++spellCount;
}
data.put<uint16>(countPos, spellCount); // write real count value
GetSpellHistory()->WritePacket<Player>(data);
SendDirectMessage(&data);
}
void Player::SendUnlearnSpells()
{
WorldPacket data(SMSG_SEND_UNLEARN_SPELLS, 4 + 4 * m_spells.size());
uint32 spellCount = 0;
size_t countPos = data.wpos();
data << uint32(spellCount); // spell count placeholder
for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
{
if (itr->second.state == PLAYERSPELL_REMOVED)
continue;
if (itr->second.active || itr->second.disabled)
continue;
auto skillLineAbilities = sSpellMgr->GetSkillLineAbilityMapBounds(itr->first);
if (skillLineAbilities.first == skillLineAbilities.second)
continue;
bool hasSupercededSpellInfoInClient = false;
for (auto boundsItr = skillLineAbilities.first; boundsItr != skillLineAbilities.second; ++boundsItr)
{
if (boundsItr->second->SupercededBySpell)
{
hasSupercededSpellInfoInClient = true;
break;
}
}
if (hasSupercededSpellInfoInClient)
continue;
uint32 nextRank = sSpellMgr->GetNextSpellInChain(itr->first);
if (!nextRank || !HasSpell(nextRank))
continue;
data << uint32(itr->first);
++spellCount;
}
data.put<uint32>(countPos, spellCount); // write real count value
SendDirectMessage(&data);
}
void Player::SendTameFailure(uint8 result)
{
WorldPacket data(SMSG_PET_TAME_FAILURE, 1);
data << uint8(result);
SendDirectMessage(&data);
}
void Player::RemoveMail(uint32 id)
{
for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
{
if ((*itr)->messageID == id)
{
//do not delete item, because Player::removeMail() is called when returning mail to sender.
m_mail.erase(itr);
return;
}
}
}
void Player::SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError, ObjectGuid::LowType item_guid, uint32 item_count) const
{
WorldPackets::Mail::MailCommandResult result;
result.MailID = mailId;
result.Command = mailAction;
result.ErrorCode = mailError;
result.BagResult = equipError;
result.AttachID = item_guid;
result.QtyInInventory = item_count;
SendDirectMessage(result.Write());
}
void Player::SendNewMail() const
{
// deliver undelivered mail
WorldPackets::Mail::NotifyReceivedMail notify;
notify.Delay = 0.0f;
SendDirectMessage(notify.Write());
}
void Player::UpdateNextMailTimeAndUnreads()
{
// calculate next delivery time (min. from non-delivered mails
// and recalculate unReadMail
time_t cTime = GameTime::GetGameTime();
m_nextMailDelivereTime = 0;
unReadMails = 0;
for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
{
if ((*itr)->deliver_time > cTime)
{
if (!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
m_nextMailDelivereTime = (*itr)->deliver_time;
}
else if (((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
++unReadMails;
}
}
void Player::AddNewMailDeliverTime(time_t deliver_time)
{
if (deliver_time <= GameTime::GetGameTime()) // ready now
{
++unReadMails;
SendNewMail();
}
else // not ready and no have ready mails
{
if (!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
m_nextMailDelivereTime = deliver_time;
}
}
void DeleteSpellFromAllPlayers(uint32 spellId)
{
CharacterDatabaseStatements stmts[2] = {CHAR_DEL_INVALID_SPELL_SPELLS, CHAR_DEL_INVALID_SPELL_TALENTS};
for (uint8 i = 0; i < 2; i++)
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(stmts[i]);
stmt->setUInt32(0, spellId);
CharacterDatabase.Execute(stmt);
}
}
bool Player::AddTalent(uint32 spellId, uint8 spec, bool learning)
{
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId);
if (!spellInfo)
{
// do character spell book cleanup (all characters)
if (!IsInWorld() && !learning) // spell load case
{
TC_LOG_ERROR("spells", "Player::AddTalent: Spell (ID: {}) does not exist. Deleting for all characters in `character_spell` and `character_talent`.", spellId);
DeleteSpellFromAllPlayers(spellId);
}
else
TC_LOG_ERROR("spells", "Player::AddTalent: Spell (ID: {}) does not exist", spellId);
return false;
}
if (!SpellMgr::IsSpellValid(spellInfo, this, false))
{
// do character spell book cleanup (all characters)
if (!IsInWorld() && !learning) // spell load case
{
TC_LOG_ERROR("spells", "Player::AddTalent: Spell (ID: {}) is invalid. Deleting for all characters in `character_spell` and `character_talent`.", spellId);
DeleteSpellFromAllPlayers(spellId);
}
else
TC_LOG_ERROR("spells", "Player::AddTalent: Spell (ID: {}) is invalid", spellId);
return false;
}
PlayerTalentMap::iterator itr = GetTalentMap(spec)->find(spellId);
if (itr != GetTalentMap(spec)->end())
itr->second->state = PLAYERSPELL_UNCHANGED;
else if (TalentSpellPos const* talentPos = GetTalentSpellPos(spellId))
{
if (TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentPos->talent_id))
{
for (uint8 rank = 0; rank < MAX_TALENT_RANK; ++rank)
{
// skip learning spell and no rank spell case
uint32 rankSpellId = talentInfo->SpellRank[rank];
if (!rankSpellId || rankSpellId == spellId)
continue;
itr = GetTalentMap(spec)->find(rankSpellId);
if (itr != GetTalentMap(spec)->end())
itr->second->state = PLAYERSPELL_REMOVED;
}
}
PlayerTalent* newtalent = new PlayerTalent();
newtalent->state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
newtalent->spec = spec;
(*GetTalentMap(spec))[spellId] = newtalent;
return true;
}
return false;
}
static bool IsUnlearnSpellsPacketNeededForSpell(uint32 spellId)
{
SpellInfo const* spellInfo = sSpellMgr->AssertSpellInfo(spellId);
if (spellInfo->IsRanked() && !spellInfo->IsStackableWithRanks())
{
auto skillLineAbilities = sSpellMgr->GetSkillLineAbilityMapBounds(spellId);
if (skillLineAbilities.first != skillLineAbilities.second)
{
bool hasSupercededSpellInfoInClient = false;
for (auto boundsItr = skillLineAbilities.first; boundsItr != skillLineAbilities.second; ++boundsItr)
{
if (boundsItr->second->SupercededBySpell)
{
hasSupercededSpellInfoInClient = true;
break;
}
}
return !hasSupercededSpellInfoInClient;
}
}
return false;
}
bool Player::AddSpell(uint32 spellId, bool active, bool learning, bool dependent, bool disabled, bool loading /*= false*/, uint32 fromSkill /*= 0*/)
{
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId);
if (!spellInfo)
{
// do character spell book cleanup (all characters)
if (!IsInWorld() && !learning) // spell load case
{
TC_LOG_ERROR("spells", "Player::AddSpell: Spell (ID: {}) does not exist. deleting for all characters in `character_spell` and `character_talent`.", spellId);
DeleteSpellFromAllPlayers(spellId);
}
else
TC_LOG_ERROR("spells", "Player::AddSpell: Spell (ID: {}) does not exist", spellId);
return false;
}
if (!SpellMgr::IsSpellValid(spellInfo, this, false))
{
// do character spell book cleanup (all characters)
if (!IsInWorld() && !learning) // spell load case
{
TC_LOG_ERROR("spells", "Player::AddSpell: Spell (ID: {}) is invalid. deleting for all characters in `character_spell` and `character_talent`.", spellId);
DeleteSpellFromAllPlayers(spellId);
}
else
TC_LOG_ERROR("spells", "Player::AddSpell: Spell (ID: {}) is invalid", spellId);
return false;
}
PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
bool dependent_set = false;
bool disabled_case = false;
bool superceded_old = false;
PlayerSpellMap::iterator itr = m_spells.find(spellId);
// Remove temporary spell if found to prevent conflicts
if (itr != m_spells.end() && itr->second.state == PLAYERSPELL_TEMPORARY)
RemoveTemporarySpell(spellId);
else if (itr != m_spells.end())
{
uint32 next_active_spell_id = 0;
// fix activate state for non-stackable low rank (and find next spell for !active case)
if (!spellInfo->IsStackableWithRanks() && spellInfo->IsRanked())
{
if (uint32 next = sSpellMgr->GetNextSpellInChain(spellId))
{
if (HasSpell(next))
{
// high rank already known so this must !active
active = false;
next_active_spell_id = next;
}
}
}
// not do anything if already known in expected state
if (itr->second.state != PLAYERSPELL_REMOVED && itr->second.active == active &&
itr->second.dependent == dependent && itr->second.disabled == disabled)
{
if (!IsInWorld() && !learning) // explicitly load from DB and then exist in it already and set correctly
itr->second.state = PLAYERSPELL_UNCHANGED;
return false;
}
// dependent spell known as not dependent, overwrite state
if (itr->second.state != PLAYERSPELL_REMOVED && !itr->second.dependent && dependent)
{
itr->second.dependent = dependent;
if (itr->second.state != PLAYERSPELL_NEW)
itr->second.state = PLAYERSPELL_CHANGED;
dependent_set = true;
}
// update active state for known spell
if (itr->second.active != active && itr->second.state != PLAYERSPELL_REMOVED && !itr->second.disabled)
{
itr->second.active = active;
if (!IsInWorld() && !learning && !dependent_set) // explicitly load from DB and then exist in it already and set correctly
itr->second.state = PLAYERSPELL_UNCHANGED;
else if (itr->second.state != PLAYERSPELL_NEW)
itr->second.state = PLAYERSPELL_CHANGED;
if (active)
{
if (spellInfo->IsPassive() && HandlePassiveSpellLearn(spellInfo))
CastSpell(this, spellId, true);
}
else if (IsInWorld())
{
if (next_active_spell_id)
{
SendSupercededSpell(spellId, next_active_spell_id);
if (IsUnlearnSpellsPacketNeededForSpell(spellId))
SendUnlearnSpells();
}
else
{
WorldPacket data(SMSG_REMOVED_SPELL, 4);
data << uint32(spellId);
SendDirectMessage(&data);
}
}
return active; // learn (show in spell book if active now)
}
if (itr->second.disabled != disabled && itr->second.state != PLAYERSPELL_REMOVED)
{
if (itr->second.state != PLAYERSPELL_NEW)
itr->second.state = PLAYERSPELL_CHANGED;
itr->second.disabled = disabled;
if (disabled)
return false;
disabled_case = true;
}
else switch (itr->second.state)
{
case PLAYERSPELL_UNCHANGED: // known saved spell
return false;
case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
{
m_spells.erase(itr);
state = PLAYERSPELL_CHANGED;
break; // need re-add
}
default: // known not saved yet spell (new or modified)
{
// can be in case spell loading but learned at some previous spell loading
if (!IsInWorld() && !learning && !dependent_set)
itr->second.state = PLAYERSPELL_UNCHANGED;
return false;
}
}
}
if (!disabled_case) // skip new spell adding if spell already known (disabled spells case)
{
// talent: unlearn all other talent ranks (high and low)
if (TalentSpellPos const* talentPos = GetTalentSpellPos(spellId))
{
if (TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentPos->talent_id))
{
for (uint8 rank = 0; rank < MAX_TALENT_RANK; ++rank)
{
// skip learning spell and no rank spell case
uint32 rankSpellId = talentInfo->SpellRank[rank];
if (!rankSpellId || rankSpellId == spellId)
continue;
RemoveSpell(rankSpellId, false, false);
}
}
}
// non talent spell: learn low ranks (recursive call)
else if (uint32 prev_spell = sSpellMgr->GetPrevSpellInChain(spellId))
{
if (!IsInWorld() || disabled) // at spells loading, no output, but allow save
AddSpell(prev_spell, active, true, true, disabled, false, fromSkill);
else // at normal learning
LearnSpell(prev_spell, true, fromSkill);
}
std::pair<PlayerSpellMap::iterator, bool> inserted = m_spells.emplace(std::piecewise_construct, std::forward_as_tuple(spellId), std::forward_as_tuple());
PlayerSpell& newspell = inserted.first->second;
// learning a previous rank might have given us this spell already from a skill autolearn, most likely with PLAYERSPELL_NEW state
// we dont want to do double insert if this happened during load from db so we force state to CHANGED, just in case
newspell.state = inserted.second ? state : PLAYERSPELL_CHANGED;
newspell.active = active;
newspell.dependent = dependent;
newspell.disabled = disabled;
bool needsUnlearnSpellsPacket = false;
// replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
if (newspell.active && !newspell.disabled && !spellInfo->IsStackableWithRanks() && spellInfo->IsRanked())
{
for (PlayerSpellMap::iterator itr2 = m_spells.begin(); itr2 != m_spells.end(); ++itr2)
{
if (itr2->second.state == PLAYERSPELL_REMOVED)
continue;
SpellInfo const* i_spellInfo = sSpellMgr->GetSpellInfo(itr2->first);
if (!i_spellInfo)
continue;
if (spellInfo->IsDifferentRankOf(i_spellInfo))
{
if (itr2->second.active)
{
if (spellInfo->IsHighRankOf(i_spellInfo))
{
if (IsInWorld()) // not send spell (re-/over-)learn packets at loading
{
SendSupercededSpell(itr2->first, spellId);
needsUnlearnSpellsPacket = needsUnlearnSpellsPacket || IsUnlearnSpellsPacketNeededForSpell(itr2->first);
}
// mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
itr2->second.active = false;
if (itr2->second.state != PLAYERSPELL_NEW)
itr2->second.state = PLAYERSPELL_CHANGED;
superceded_old = true; // new spell replace old in action bars and spell book.
}
else
{
if (IsInWorld()) // not send spell (re-/over-)learn packets at loading
{
SendSupercededSpell(spellId, itr2->first);
needsUnlearnSpellsPacket = needsUnlearnSpellsPacket || IsUnlearnSpellsPacketNeededForSpell(spellId);
}
// mark new spell as disable (not learned yet for client and will not learned)
newspell.active = false;
if (newspell.state != PLAYERSPELL_NEW)
newspell.state = PLAYERSPELL_CHANGED;
}
}
}
}
}
if (needsUnlearnSpellsPacket)
SendUnlearnSpells();
// return false if spell disabled
if (newspell.disabled)
return false;
}
uint32 talentCost = GetTalentSpellCost(spellId);
// cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
// note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
if (!loading && talentCost > 0 && spellInfo->HasEffect(SPELL_EFFECT_LEARN_SPELL))
{
// ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
CastSpell(this, spellId, true);
}
// also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
else if (spellInfo->IsPassive())
{
if (HandlePassiveSpellLearn(spellInfo))
CastSpell(this, spellId, true);
}
else if (spellInfo->HasEffect(SPELL_EFFECT_SKILL_STEP))
{
CastSpell(this, spellId, true);
return false;
}
// update used talent points count
SetUsedTalentCount(GetUsedTalentCount() + talentCost);
// update free primary prof.points (if any, can be none in case GM .learn prof. learning)
if (uint32 freeProfs = GetFreePrimaryProfessionPoints())
{
if (spellInfo->IsPrimaryProfessionFirstRank())
SetFreePrimaryProfessions(freeProfs-1);
}
SkillLineAbilityMapBounds skill_bounds = sSpellMgr->GetSkillLineAbilityMapBounds(spellId);
if (SpellLearnSkillNode const* spellLearnSkill = sSpellMgr->GetSpellLearnSkill(spellId))
{
// add dependent skills if this spell is not learned from adding skill already
if (spellLearnSkill->skill != fromSkill)
{
uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
if (skill_value < spellLearnSkill->value)
skill_value = spellLearnSkill->value;
uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : spellLearnSkill->maxvalue;
if (skill_max_value < new_skill_max_value)
skill_max_value = new_skill_max_value;
if (sWorld->getBoolConfig(CONFIG_ALWAYS_MAXSKILL) && !IsProfessionOrRidingSkill(spellLearnSkill->skill))
skill_value = skill_max_value;
SetSkill(spellLearnSkill->skill, spellLearnSkill->step, skill_value, skill_max_value);
}
}
else
{
// not ranked skills
for (SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx)
{
SkillLineEntry const* pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->SkillLine);
if (!pSkill)
continue;
if (pSkill->ID == fromSkill)
continue;
///@todo: confirm if rogues start with lockpicking skill at level 1 but only receive the spell to use it at level 16
// Also added for runeforging. It's already confirmed this happens upon learning for Death Knights, not from character creation.
if ((_spell_idx->second->AcquireMethod == SKILL_LINE_ABILITY_LEARNED_ON_SKILL_LEARN && !HasSkill(pSkill->ID)) || ((pSkill->ID == SKILL_LOCKPICKING || pSkill->ID == SKILL_RUNEFORGING) && _spell_idx->second->TrivialSkillLineRankHigh == 0))
LearnDefaultSkill(pSkill->ID, 0);
if (pSkill->ID == SKILL_MOUNTS && !Has310Flyer(false))
for (SpellEffectInfo const& spellEffectInfo : spellInfo->GetEffects())
if (spellEffectInfo.ApplyAuraName == SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED &&
spellEffectInfo.CalcValue() == 310)
SetHas310Flyer(true);
}
}
// learn dependent spells
SpellLearnSpellMapBounds spell_bounds = sSpellMgr->GetSpellLearnSpellMapBounds(spellId);
for (SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2)
{
if (!itr2->second.autoLearned)
{
if (!IsInWorld() || !itr2->second.active) // at spells loading, no output, but allow save
AddSpell(itr2->second.spell, itr2->second.active, true, true, false);
else // at normal learning
LearnSpell(itr2->second.spell, true);
}
}
if (!GetSession()->PlayerLoading())
{
// not ranked skills
for (SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx)
{
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE, _spell_idx->second->SkillLine);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS, _spell_idx->second->SkillLine);
}
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL, spellId);
}
// return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
return active && !disabled && !superceded_old;
}
void Player::AddTemporarySpell(uint32 spellId)
{
PlayerSpellMap::iterator itr = m_spells.find(spellId);
// spell already added - do not do anything
if (itr != m_spells.end())
return;
PlayerSpell* newspell = &m_spells[spellId];
newspell->state = PLAYERSPELL_TEMPORARY;
newspell->active = true;
newspell->dependent = false;
newspell->disabled = false;
}
void Player::RemoveTemporarySpell(uint32 spellId)
{
PlayerSpellMap::iterator itr = m_spells.find(spellId);
// spell already not in list - do not do anything
if (itr == m_spells.end())
return;
// spell has other state than temporary - do not change it
if (itr->second.state != PLAYERSPELL_TEMPORARY)
return;
m_spells.erase(itr);
}
bool Player::HandlePassiveSpellLearn(SpellInfo const* spellInfo)
{
// note: form passives activated with shapeshift spells be implemented by HandleShapeshiftBoosts instead of spell_learn_spell
// talent dependent passives activated at form apply have proper stance data
ShapeshiftForm form = GetShapeshiftForm();
bool need_cast = (!spellInfo->Stances || (form && (spellInfo->Stances & (UI64LIT(1) << (form - 1)))) ||
(!form && spellInfo->HasAttribute(SPELL_ATTR2_NOT_NEED_SHAPESHIFT)));
// Check EquippedItemClass
// passive spells which apply aura and have an item requirement are to be added manually, instead of casted
if (spellInfo->EquippedItemClass >= 0)
{
for (SpellEffectInfo const& spellEffectInfo : spellInfo->GetEffects())
{
if (spellEffectInfo.IsAura())
{
if (!HasAura(spellInfo->Id) && HasItemFitToSpellRequirements(spellInfo))
AddAura(spellInfo->Id, this);
return false;
}
}
}
//Check CasterAuraStates
return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraStateType(spellInfo->CasterAuraState)));
}
void Player::LearnSpell(uint32 spell_id, bool dependent, uint32 fromSkill /*= 0*/)
{
PlayerSpellMap::iterator itr = m_spells.find(spell_id);
bool disabled = (itr != m_spells.end()) ? itr->second.disabled : false;
bool active = disabled ? itr->second.active : true;
bool learning = AddSpell(spell_id, active, true, dependent, false, false, fromSkill);
// prevent duplicated entires in spell book, also not send if not in world (loading)
if (learning && IsInWorld())
{
WorldPacket data(SMSG_LEARNED_SPELL, 6);
data << uint32(spell_id);
data << uint16(0);
SendDirectMessage(&data);
#ifdef ELUNA
if (Eluna* e = GetEluna())
e->OnLearnSpell(this, spell_id);
#endif
}
// learn all disabled higher ranks and required spells (recursive)
if (disabled)
{
if (uint32 nextSpell = sSpellMgr->GetNextSpellInChain(spell_id))
{
PlayerSpellMap::iterator iter = m_spells.find(nextSpell);
if (iter != m_spells.end() && iter->second.disabled)
LearnSpell(nextSpell, false, fromSkill);
}
SpellsRequiringSpellMapBounds spellsRequiringSpell = sSpellMgr->GetSpellsRequiringSpellBounds(spell_id);
for (SpellsRequiringSpellMap::const_iterator itr2 = spellsRequiringSpell.first; itr2 != spellsRequiringSpell.second; ++itr2)
{
PlayerSpellMap::iterator iter2 = m_spells.find(itr2->second);
if (iter2 != m_spells.end() && iter2->second.disabled)
LearnSpell(itr2->second, false, fromSkill);
}
}
}
void Player::RemoveSpell(uint32 spell_id, bool disabled, bool learn_low_rank)
{
PlayerSpellMap::iterator itr = m_spells.find(spell_id);
if (itr == m_spells.end())
return;
if (itr->second.state == PLAYERSPELL_REMOVED || (disabled && itr->second.disabled) || itr->second.state == PLAYERSPELL_TEMPORARY)
return;
// unlearn non talent higher ranks (recursive)
if (uint32 nextSpell = sSpellMgr->GetNextSpellInChain(spell_id))
{
if (HasSpell(nextSpell) && !GetTalentSpellPos(nextSpell))
RemoveSpell(nextSpell, disabled, false);
}
//unlearn spells dependent from recently removed spells
SpellsRequiringSpellMapBounds spellsRequiringSpell = sSpellMgr->GetSpellsRequiringSpellBounds(spell_id);
for (SpellsRequiringSpellMap::const_iterator itr2 = spellsRequiringSpell.first; itr2 != spellsRequiringSpell.second; ++itr2)
RemoveSpell(itr2->second, disabled);
// re-search, it can be corrupted in prev loop
itr = m_spells.find(spell_id);
if (itr == m_spells.end())
return; // already unleared
bool giveTalentPoints = disabled || !itr->second.disabled;
bool cur_active = itr->second.active;
bool cur_dependent = itr->second.dependent;
if (disabled)
{
itr->second.disabled = disabled;
if (itr->second.state != PLAYERSPELL_NEW)
itr->second.state = PLAYERSPELL_CHANGED;
}
else
{
if (itr->second.state == PLAYERSPELL_NEW)
m_spells.erase(itr);
else
itr->second.state = PLAYERSPELL_REMOVED;
}
RemoveOwnedAura(spell_id, GetGUID());
// remove pet auras
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
if (PetAura const* petSpell = sSpellMgr->GetPetAura(spell_id, i))
RemovePetAura(petSpell);
// free talent points
uint32 talentCosts = GetTalentSpellCost(spell_id);
if (talentCosts > 0 && giveTalentPoints)
{
if (talentCosts < GetUsedTalentCount())
SetUsedTalentCount(GetUsedTalentCount() - talentCosts);
else
SetUsedTalentCount(0);
}
// update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spell_id);
if (spellInfo && spellInfo->IsPrimaryProfessionFirstRank())
{
uint32 freeProfs = GetFreePrimaryProfessionPoints()+1;
if (freeProfs <= sWorld->getIntConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
SetFreePrimaryProfessions(freeProfs);
}
// remove dependent skill
SpellLearnSkillNode const* spellLearnSkill = sSpellMgr->GetSpellLearnSkill(spell_id);
if (spellLearnSkill)
{
uint32 prev_spell = sSpellMgr->GetPrevSpellInChain(spell_id);
if (!prev_spell) // first rank, remove skill
SetSkill(spellLearnSkill->skill, 0, 0, 0);
else
{
// search prev. skill setting by spell ranks chain
SpellLearnSkillNode const* prevSkill = sSpellMgr->GetSpellLearnSkill(prev_spell);
while (!prevSkill && prev_spell)
{
prev_spell = sSpellMgr->GetPrevSpellInChain(prev_spell);
prevSkill = sSpellMgr->GetSpellLearnSkill(sSpellMgr->GetFirstSpellInChain(prev_spell));
}
if (!prevSkill) // not found prev skill setting, remove skill
SetSkill(spellLearnSkill->skill, 0, 0, 0);
else // set to prev. skill setting values
{
uint32 skill_value = GetPureSkillValue(prevSkill->skill);
uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
if (skill_value > prevSkill->value)
skill_value = prevSkill->value;
uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
if (skill_max_value > new_skill_max_value)
skill_max_value = new_skill_max_value;
SetSkill(prevSkill->skill, prevSkill->step, skill_value, skill_max_value);
}
}
}
else
{
// not ranked skills
SkillLineAbilityMapBounds bounds = sSpellMgr->GetSkillLineAbilityMapBounds(spell_id);
// most likely will never be used, haven't heard of cases where players unlearn a mount
if (Has310Flyer(false) && spellInfo)
{
for (SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
{
SkillLineEntry const* pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->SkillLine);
if (!pSkill)
continue;
if (_spell_idx->second->SkillLine == SKILL_MOUNTS)
{
for (SpellEffectInfo const& spellEffectInfo : spellInfo->GetEffects())
{
if (spellEffectInfo.ApplyAuraName == SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED &&
spellEffectInfo.CalcValue() == 310)
{
Has310Flyer(true, spell_id); // with true as first argument its also used to set/remove the flag
break;
}
}
}
}
}
}
// remove dependent spells
SpellLearnSpellMapBounds spell_bounds = sSpellMgr->GetSpellLearnSpellMapBounds(spell_id);
for (SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2)
RemoveSpell(itr2->second.spell, disabled);
// activate lesser rank in spellbook/action bar, and cast it if need
bool prev_activate = false;
bool needsUnlearnSpellsPacket = false;
if (uint32 prev_id = sSpellMgr->GetPrevSpellInChain(spell_id))
{
// if talent then lesser rank also talent and need learn
if (talentCosts)
{
// I cannot see why mangos has these lines.
//if (learn_low_rank)
// learnSpell(prev_id, false);
}
// if ranked non-stackable spell: need activate lesser rank and update dendence state
/// No need to check for spellInfo != nullptr here because if cur_active is true, then that means that the spell was already in m_spells, and only valid spells can be pushed there.
else if (cur_active && !spellInfo->IsStackableWithRanks() && spellInfo->IsRanked())
{
// need manually update dependence state (learn spell ignore like attempts)
PlayerSpellMap::iterator prev_itr = m_spells.find(prev_id);
if (prev_itr != m_spells.end())
{
if (prev_itr->second.dependent != cur_dependent)
{
prev_itr->second.dependent = cur_dependent;
if (prev_itr->second.state != PLAYERSPELL_NEW)
prev_itr->second.state = PLAYERSPELL_CHANGED;
}
// now re-learn if need re-activate
if (!prev_itr->second.active && learn_low_rank)
{
if (AddSpell(prev_id, true, false, prev_itr->second.dependent, prev_itr->second.disabled))
{
// downgrade spell ranks in spellbook and action bar
SendSupercededSpell(spell_id, prev_id);
needsUnlearnSpellsPacket = IsUnlearnSpellsPacketNeededForSpell(prev_id);
prev_activate = true;
}
}
}
}
}
if (m_canTitanGrip)
{
if (spellInfo && spellInfo->IsPassive() && spellInfo->HasEffect(SPELL_EFFECT_TITAN_GRIP))
{
RemoveAurasDueToSpell(m_titanGripPenaltySpellId);
SetCanTitanGrip(false);
}
}
if (m_canDualWield)
{
if (spellInfo && spellInfo->IsPassive() && spellInfo->HasEffect(SPELL_EFFECT_DUAL_WIELD))
SetCanDualWield(false);
}
if (sWorld->getBoolConfig(CONFIG_OFFHAND_CHECK_AT_SPELL_UNLEARN))
AutoUnequipOffhandIfNeed();
if (needsUnlearnSpellsPacket)
SendUnlearnSpells();
// remove from spell book if not replaced by lesser rank
if (!prev_activate)
{
WorldPacket data(SMSG_REMOVED_SPELL, 4);
data << uint32(spell_id);
SendDirectMessage(&data);
}
}
bool Player::Has310Flyer(bool checkAllSpells, uint32 excludeSpellId)
{
if (!checkAllSpells)
return (m_ExtraFlags & PLAYER_EXTRA_HAS_310_FLYER) != 0;
else
{
SetHas310Flyer(false);
SpellInfo const* spellInfo;
for (PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
{
if (itr->first == excludeSpellId)
continue;
SkillLineAbilityMapBounds bounds = sSpellMgr->GetSkillLineAbilityMapBounds(itr->first);
for (SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
{
if (_spell_idx->second->SkillLine != SKILL_MOUNTS)
break; // We can break because mount spells belong only to one skillline (at least 310 flyers do)
spellInfo = sSpellMgr->AssertSpellInfo(itr->first);
for (SpellEffectInfo const& spellEffectInfo : spellInfo->GetEffects())
{
if (spellEffectInfo.ApplyAuraName == SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED &&
spellEffectInfo.CalcValue() == 310)
{
SetHas310Flyer(true);
return true;
}
}
}
}
}
return false;
}
void Player::RemoveArenaSpellCooldowns(bool removeActivePetCooldowns)
{
// remove cooldowns on spells that have < 10 min CD
GetSpellHistory()->ResetCooldowns([](SpellHistory::CooldownStorageType::iterator itr) -> bool
{
SpellInfo const* spellInfo = sSpellMgr->AssertSpellInfo(itr->first);
int32 cooldown = -1;
int32 categoryCooldown = -1;
SpellHistory::GetCooldownDurations(spellInfo, itr->second.ItemId, &cooldown, nullptr, &categoryCooldown);
return cooldown < 10 * MINUTE * IN_MILLISECONDS && categoryCooldown < 10 * MINUTE * IN_MILLISECONDS;
}, true);
// pet cooldowns
if (removeActivePetCooldowns)
if (Pet* pet = GetPet())
pet->GetSpellHistory()->ResetAllCooldowns();
}
uint32 Player::ResetTalentsCost() const
{
if (sWorld->getBoolConfig(CONFIG_NO_RESET_TALENT_COST))
return 0;
// The first time reset costs 1 gold
if (GetTalentResetCost() < 1*GOLD)
return 1*GOLD;
// then 5 gold
else if (GetTalentResetCost() < 5*GOLD)
return 5*GOLD;
// After that it increases in increments of 5 gold
else if (GetTalentResetCost() < 10*GOLD)
return 10*GOLD;
else
{
uint64 months = (GameTime::GetGameTime() - GetTalentResetTime())/MONTH;
if (months > 0)
{
// This cost will be reduced by a rate of 5 gold per month
int32 new_cost = int32(GetTalentResetCost() - 5*GOLD*months);
// to a minimum of 10 gold.
return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
}
else
{
// After that it increases in increments of 5 gold
int32 new_cost = GetTalentResetCost() + 5*GOLD;
// until it hits a cap of 50 gold.
if (new_cost > 50*GOLD)
new_cost = 50*GOLD;
return new_cost;
}
}
}
void Player::IncreaseResetTalentsCostAndCounters(uint32 lastResetTalentsCost)
{
if (lastResetTalentsCost > 0) // We don't want to reset the accumulated talent reset cost if we decide to temporarily enable CONFIG_NO_RESET_TALENT_COST
_talentMgr->ResetTalentsCost = lastResetTalentsCost;
_talentMgr->ResetTalentsTime = GameTime::GetGameTime();
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS, lastResetTalentsCost);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS, 1);
}
bool Player::ResetTalents(bool involuntarily /*= false*/)
{
sScriptMgr->OnPlayerTalentsReset(this, involuntarily);
// not need after this call
if (HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
RemoveAtLoginFlag(AT_LOGIN_RESET_TALENTS, true);
uint32 talentPointsForLevel = CalculateTalentsPoints();
if (!GetUsedTalentCount())
{
SetFreeTalentPoints(talentPointsForLevel);
return false;
}
RemovePet(nullptr, PET_SAVE_NOT_IN_SLOT, true);
for (uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
{
TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
if (!talentInfo)
continue;
TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TabID);
if (!talentTabInfo)
continue;
// unlearn only talents for character class
// some spell learned by one class as normal spells or know at creation but another class learn it as talent,
// to prevent unexpected lost normal learned spell skip another class talents
if ((GetClassMask() & talentTabInfo->ClassMask) == 0)
continue;
for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank)
{
// skip non-existing talent ranks
if (talentInfo->SpellRank[rank] == 0)
continue;
SpellInfo const* _spellEntry = sSpellMgr->GetSpellInfo(talentInfo->SpellRank[rank]);
if (!_spellEntry)
continue;
RemoveSpell(talentInfo->SpellRank[rank], true);
// search for spells that the talent teaches and unlearn them
for (SpellEffectInfo const& spellEffectInfo : _spellEntry->GetEffects())
if (spellEffectInfo.IsEffect(SPELL_EFFECT_LEARN_SPELL) && spellEffectInfo.TriggerSpell > 0)
RemoveSpell(spellEffectInfo.TriggerSpell, true);
// if this talent rank can be found in the PlayerTalentMap, mark the talent as removed so it gets deleted
PlayerTalentMap::iterator plrTalent = GetTalentMap(GetActiveSpec())->find(talentInfo->SpellRank[rank]);
if (plrTalent != GetTalentMap(GetActiveSpec())->end())
plrTalent->second->state = PLAYERSPELL_REMOVED;
}
}
CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction();
_SaveTalents(trans);
_SaveSpells(trans);
CharacterDatabase.CommitTransaction(trans);
SetFreeTalentPoints(talentPointsForLevel);
if (involuntarily)
SendDirectMessage(WorldPackets::Talents::InvoluntarilyReset(false).Write());
return true;
}
void Player::SetFreeTalentPoints(uint32 points)
{
sScriptMgr->OnPlayerFreeTalentPointsChanged(this, points);
SetUInt32Value(PLAYER_CHARACTER_POINTS1, points);
}
Mail* Player::GetMail(uint32 id)
{
for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
if ((*itr)->messageID == id)
return (*itr);
return nullptr;
}
void Player::BuildCreateUpdateBlockForPlayer(UpdateData* data, Player* target) const
{
if (target == this)
{
for (uint8 i = 0; i < EQUIPMENT_SLOT_END; ++i)
{
if (m_items[i] == nullptr)
continue;
m_items[i]->BuildCreateUpdateBlockForPlayer(data, target);
}
for (uint8 i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
{
if (m_items[i] == nullptr)
continue;
m_items[i]->BuildCreateUpdateBlockForPlayer(data, target);
}
for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
{
if (m_items[i] == nullptr)
continue;
m_items[i]->BuildCreateUpdateBlockForPlayer(data, target);
}
}
Unit::BuildCreateUpdateBlockForPlayer(data, target);
}
void Player::DestroyForPlayer(Player* target, bool onDeath) const
{
Unit::DestroyForPlayer(target, onDeath);
for (uint8 i = 0; i < EQUIPMENT_SLOT_END; ++i)
{
if (m_items[i] == nullptr)
continue;
m_items[i]->DestroyForPlayer(target);
}
if (target == this)
{
for (uint8 i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
{
if (m_items[i] == nullptr)
continue;
m_items[i]->DestroyForPlayer(target);
}
for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
{
if (m_items[i] == nullptr)
continue;
m_items[i]->DestroyForPlayer(target);
}
}
}
bool Player::HasSpell(uint32 spell) const
{
PlayerSpellMap::const_iterator itr = m_spells.find(spell);
return (itr != m_spells.end() && itr->second.state != PLAYERSPELL_REMOVED &&
!itr->second.disabled);
}
bool Player::HasTalent(uint32 spell, uint8 spec) const
{
PlayerTalentMap::const_iterator itr = GetTalentMap(spec)->find(spell);
return (itr != GetTalentMap(spec)->end() && itr->second->state != PLAYERSPELL_REMOVED);
}
bool Player::HasActiveSpell(uint32 spell) const
{
PlayerSpellMap::const_iterator itr = m_spells.find(spell);
return (itr != m_spells.end() && itr->second.state != PLAYERSPELL_REMOVED &&
itr->second.active && !itr->second.disabled);
}
/**
* Deletes a character from the database
*
* The way characters will be deleted is decided based on the config option.
*
* @see Player::DeleteOldCharacters
*
* @param playerguid the low-GUID from the player which should be deleted
* @param accountId the account id from the player
* @param updateRealmChars when this flag is set, the amount of characters on that realm will be updated in the realmlist
* @param deleteFinally if this flag is set, the config option will be ignored and the character will be permanently removed from the database
*/
void Player::DeleteFromDB(ObjectGuid playerguid, uint32 accountId, bool updateRealmChars, bool deleteFinally)
{
// Avoid realm-update for non-existing account
if (accountId == 0)
updateRealmChars = false;
// Convert guid to low GUID for CharacterNameData, but also other methods on success
ObjectGuid::LowType guid = playerguid.GetCounter();
uint32 charDelete_method = sWorld->getIntConfig(CONFIG_CHARDELETE_METHOD);
CharacterCacheEntry const* characterInfo = sCharacterCache->GetCharacterCacheByGuid(playerguid);
std::string name;
if (characterInfo)
name = characterInfo->Name;
if (deleteFinally)
charDelete_method = CHAR_DELETE_REMOVE;
else if (characterInfo) // To avoid a query, we select loaded data. If it doesn't exist, return.
{
// Define the required variables
uint32 charDelete_minLvl = sWorld->getIntConfig(characterInfo->Class != CLASS_DEATH_KNIGHT ? CONFIG_CHARDELETE_MIN_LEVEL : CONFIG_CHARDELETE_DEATH_KNIGHT_MIN_LEVEL);
// if we want to finalize the character removal or the character does not meet the level requirement of either heroic or non-heroic settings,
// we set it to mode CHAR_DELETE_REMOVE
if (characterInfo->Level < charDelete_minLvl)
charDelete_method = CHAR_DELETE_REMOVE;
}
CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction();
if (ObjectGuid::LowType guildId = sCharacterCache->GetCharacterGuildIdByGuid(playerguid))
if (Guild* guild = sGuildMgr->GetGuildById(guildId))
guild->DeleteMember(trans, playerguid, false, false);
// close player ticket if any
GmTicket* ticket = sTicketMgr->GetTicketByPlayer(playerguid);
if (ticket)
sTicketMgr->CloseTicket(ticket->GetId(), playerguid);
// remove from arena teams
LeaveAllArenaTeams(playerguid);
// the player was uninvited already on logout so just remove from group
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_GROUP_MEMBER);
stmt->setUInt32(0, guid);
PreparedQueryResult resultGroup = CharacterDatabase.Query(stmt);
if (resultGroup)
if (Group* group = sGroupMgr->GetGroupByDbStoreId((*resultGroup)[0].GetUInt32()))
RemoveFromGroup(group, playerguid);
// Remove signs from petitions (also remove petitions if owner);
RemovePetitionsAndSigns(playerguid, CHARTER_TYPE_ANY);
switch (charDelete_method)
{
// Completely remove from the database
case CHAR_DELETE_REMOVE:
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_COD_ITEM_MAIL);
stmt->setUInt32(0, guid);
PreparedQueryResult resultMail = CharacterDatabase.Query(stmt);
if (resultMail)
{
std::unordered_map<uint32, std::vector<Item*>> itemsByMail;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_MAILITEMS);
stmt->setUInt32(0, guid);
PreparedQueryResult resultItems = CharacterDatabase.Query(stmt);
if (resultItems)
{
do
{
Field* fields = resultItems->Fetch();
uint32 mailId = fields[14].GetUInt32();
if (Item* mailItem = _LoadMailedItem(playerguid, nullptr, mailId, nullptr, fields))
itemsByMail[mailId].push_back(mailItem);
} while (resultItems->NextRow());
}
do
{
Field* mailFields = resultMail->Fetch();
uint32 mail_id = mailFields[0].GetUInt32();
uint8 mailType = mailFields[1].GetUInt8();
uint16 mailTemplateId= mailFields[2].GetUInt16();
ObjectGuid::LowType sender = mailFields[3].GetUInt32();
std::string subject = mailFields[4].GetString();
std::string body = mailFields[5].GetString();
uint32 money = mailFields[6].GetUInt32();
bool has_items = mailFields[7].GetBool();
// We can return mail now
// So firstly delete the old one
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_BY_ID);
stmt->setUInt32(0, mail_id);
trans->Append(stmt);
// Mail is not from player
if (mailType != MAIL_NORMAL)
{
if (has_items)
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_ITEM_BY_ID);
stmt->setUInt32(0, mail_id);
trans->Append(stmt);
}
continue;
}
MailDraft draft(subject, body);
if (mailTemplateId)
draft = MailDraft(mailTemplateId, false); // items are already included
auto itemsItr = itemsByMail.find(mail_id);
if (itemsItr != itemsByMail.end())
{
for (Item* item : itemsItr->second)
draft.AddItem(item);
// MailDraft will take care of freeing memory
itemsByMail.erase(itemsItr);
}
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_ITEM_BY_ID);
stmt->setUInt32(0, mail_id);
trans->Append(stmt);
uint32 pl_account = sCharacterCache->GetCharacterAccountIdByGuid(playerguid);
draft.AddMoney(money).SendReturnToSender(pl_account, guid, sender, trans);
}
while (resultMail->NextRow());
}
// Unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
// NOW we can finally clear other DB data related to character
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_PET_IDS);
stmt->setUInt32(0, guid);
PreparedQueryResult resultPets = CharacterDatabase.Query(stmt);
if (resultPets)
{
do
{
ObjectGuid::LowType petguidlow = (*resultPets)[0].GetUInt32();
Pet::DeleteFromDB(petguidlow);
} while (resultPets->NextRow());
}
// Delete char from social list of online chars
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_SOCIAL);
stmt->setUInt32(0, guid);
if (PreparedQueryResult resultFriends = CharacterDatabase.Query(stmt))
{
do
{
if (Player* playerFriend = ObjectAccessor::FindPlayer(ObjectGuid::Create<HighGuid::Player>((*resultFriends)[0].GetUInt32())))
{
playerFriend->GetSocial()->RemoveFromSocialList(playerguid, SOCIAL_FLAG_ALL);
sSocialMgr->SendFriendStatus(playerFriend, FRIEND_REMOVED, playerguid);
}
} while (resultFriends->NextRow());
}
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHARACTER);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_ACCOUNT_DATA);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_DECLINED_NAME);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACTION);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHARACTER_ARENA_STATS);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_AURA);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_BGDATA);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_BATTLEGROUND_RANDOM);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_GIFT);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_HOMEBIND);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INSTANCE);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INVENTORY);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_QUESTSTATUS);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_QUESTSTATUS_REWARDED);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_REPUTATION);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SPELL);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SPELL_COOLDOWNS);
stmt->setUInt32(0, guid);
trans->Append(stmt);
if (sWorld->getBoolConfig(CONFIG_DELETE_CHARACTER_TICKET_TRACE))
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_PLAYER_GM_TICKETS_ON_CHAR_DELETION);
stmt->setUInt32(0, guid);
trans->Append(stmt);
}
else
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_GM_TICKETS);
stmt->setUInt32(0, guid);
trans->Append(stmt);
}
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_INSTANCE_BY_OWNER);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SOCIAL_BY_FRIEND);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SOCIAL_BY_GUID);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_ITEMS);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_PET_BY_OWNER);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_PET_DECLINEDNAME_BY_OWNER);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACHIEVEMENTS);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACHIEVEMENT_PROGRESS);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_EQUIPMENTSETS);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_EVENTLOG_BY_PLAYER);
stmt->setUInt32(0, guid);
stmt->setUInt32(1, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_EVENTLOG_BY_PLAYER);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_GLYPHS);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHARACTER_QUESTSTATUS_DAILY);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHARACTER_QUESTSTATUS_WEEKLY);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHARACTER_QUESTSTATUS_MONTHLY);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHARACTER_QUESTSTATUS_SEASONAL);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_TALENT);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SKILLS);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_STATS);
stmt->setUInt32(0, guid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_FISHINGSTEPS);
stmt->setUInt32(0, guid);
trans->Append(stmt);
Corpse::DeleteFromDB(playerguid, trans);
break;
}
// The character gets unlinked from the account, the name gets freed up and appears as deleted ingame
case CHAR_DELETE_UNLINK:
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_DELETE_INFO);
stmt->setUInt32(0, guid);
trans->Append(stmt);
break;
}
default:
TC_LOG_ERROR("entities.player.cheat", "Player::DeleteFromDB: Tried to delete player ({}) with unsupported delete method ({}).",
playerguid.ToString(), charDelete_method);
if (trans->GetSize() > 0)
CharacterDatabase.CommitTransaction(trans);
return;
}
CharacterDatabase.CommitTransaction(trans);
if (updateRealmChars)
sWorld->UpdateRealmCharCount(accountId);
sCharacterCache->DeleteCharacterCacheEntry(playerguid, name);
}
/**
* Characters which were kept back in the database after being deleted and are now too old (see config option "CharDelete.KeepDays"), will be completely deleted.
*
* @see Player::DeleteFromDB
*/
void Player::DeleteOldCharacters()
{
uint32 keepDays = sWorld->getIntConfig(CONFIG_CHARDELETE_KEEP_DAYS);
if (!keepDays)
return;
Player::DeleteOldCharacters(keepDays);
}
/**
* Characters which were kept back in the database after being deleted and are older than the specified amount of days, will be completely deleted.
*
* @see Player::DeleteFromDB
*
* @param keepDays overwrite the config option by another amount of days
*/
void Player::DeleteOldCharacters(uint32 keepDays)
{
TC_LOG_INFO("entities.player", "Player::DeleteOldCharacters: Deleting all characters which have been deleted {} days before...", keepDays);
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_OLD_CHARS);
stmt->setUInt32(0, static_cast<uint32>(GameTime::GetGameTime() - static_cast<time_t>(keepDays) * DAY));
PreparedQueryResult result = CharacterDatabase.Query(stmt);
if (result)
{
TC_LOG_DEBUG("entities.player", "Player::DeleteOldCharacters: Found {} character(s) to delete", result->GetRowCount());
do
{
Field* fields = result->Fetch();
Player::DeleteFromDB(ObjectGuid::Create<HighGuid::Player>(fields[0].GetUInt32()), fields[1].GetUInt32(), true, true);
}
while (result->NextRow());
}
}
/* Preconditions:
- a resurrectable corpse must not be loaded for the player (only bones)
- the player must be in world
*/
void Player::BuildPlayerRepop()
{
WorldPackets::Misc::PreRessurect packet;
packet.PlayerGUID = GetGUID();
GetSession()->SendPacket(packet.Write());
if (GetRace() == RACE_NIGHTELF)
CastSpell(this, 20584, true);
CastSpell(this, 8326, true);
// there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
// there must be SMSG.STOP_MIRROR_TIMER
// the player cannot have a corpse already on current map, only bones which are not returned by GetCorpse
if (GetCorpseLocation().GetMapId() == GetMapId())
{
TC_LOG_ERROR("entities.player", "Player::BuildPlayerRepop: Player '{}' ({}) already has a corpse", GetName(), GetGUID().ToString());
return;
}
// create a corpse and place it at the player's location
Corpse* corpse = CreateCorpse();
if (!corpse)
{
TC_LOG_ERROR("entities.player", "Player::BuildPlayerRepop: Error creating corpse for player '{}' ({})", GetName(), GetGUID().ToString());
return;
}
GetMap()->AddToMap(corpse);
// convert player body to ghost
setDeathState(DEAD);
SetHealth(1);
SetWaterWalking(true);
if (!GetSession()->isLogingOut() && !HasUnitState(UNIT_STATE_STUNNED))
SetRooted(false);
// BG - remove insignia related
RemoveUnitFlag(UNIT_FLAG_SKINNABLE);
int32 corpseReclaimDelay = CalculateCorpseReclaimDelay();
if (corpseReclaimDelay >= 0)
SendCorpseReclaimDelay(corpseReclaimDelay);
// to prevent cheating
corpse->ResetGhostTime();
StopMirrorTimers(); //disable timers(bars)
// OnPlayerRepop hook
sScriptMgr->OnPlayerRepop(this);
}
void Player::ResurrectPlayer(float restore_percent, bool applySickness)
{
WorldPackets::Misc::DeathReleaseLoc packet;
packet.MapID = -1;
GetSession()->SendPacket(packet.Write());
// speed change, land walk
// remove death flag + set aura
RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_IS_OUT_OF_BOUNDS);
// This must be called always even on Players with race != RACE_NIGHTELF in case of faction change
RemoveAurasDueToSpell(20584); // RACE_NIGHTELF speed bonuses
RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
if (GetSession()->IsARecruiter() || (GetSession()->GetRecruiterId() != 0))
SetDynamicFlag(UNIT_DYNFLAG_REFER_A_FRIEND);
setDeathState(ALIVE);
// add the flag to make sure opcode is always sent
AddUnitMovementFlag(MOVEMENTFLAG_WATERWALKING);
SetWaterWalking(false);
if (!HasUnitState(UNIT_STATE_STUNNED))
SetRooted(false);
m_deathTimer = 0;
// set health/powers (0- will be set in caller)
if (restore_percent > 0.0f)
{
SetHealth(uint32(GetMaxHealth()*restore_percent));
SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
SetPower(POWER_RAGE, 0);
SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
}
// trigger update zone for alive state zone updates
uint32 newzone, newarea;
GetZoneAndAreaId(newzone, newarea);
UpdateZone(newzone, newarea);
sOutdoorPvPMgr->HandlePlayerResurrects(this, newzone);
if (InBattleground())
{
if (Battleground* bg = GetBattleground())
bg->HandlePlayerResurrect(this);
}
// update visibility
UpdateObjectVisibility();
// recast lost by death auras of any items held in the inventory
CastAllObtainSpells();
#ifdef ELUNA
if (Eluna* e = GetEluna())
e->OnResurrect(this);
#endif
if (!applySickness)
return;
//Characters from level 1-10 are not affected by resurrection sickness.
//Characters from level 11-19 will suffer from one minute of sickness
//for each level they are above 10.
//Characters level 20 and up suffer from ten minutes of sickness.
int32 startLevel = sWorld->getIntConfig(CONFIG_DEATH_SICKNESS_LEVEL);
ChrRacesEntry const* raceEntry = sChrRacesStore.AssertEntry(GetRace());
if (int32(GetLevel()) >= startLevel)
{
// set resurrection sickness
CastSpell(this, raceEntry->ResSicknessSpellID, true);
// not full duration
if (int32(GetLevel()) < startLevel+9)
{
int32 delta = (int32(GetLevel()) - startLevel + 1)*MINUTE;
if (Aura* aur = GetAura(raceEntry->ResSicknessSpellID, GetGUID()))
{
aur->SetDuration(delta*IN_MILLISECONDS);
}
}
}
}
void Player::RemoveGhoul()
{
RemoveAura(SPELL_DK_RAISE_ALLY);
}
void Player::KillPlayer()
{
if (IsFlying() && !GetTransport())
GetMotionMaster()->MoveFall();
SetRooted(true);
StopMirrorTimers(); //disable timers(bars)
setDeathState(CORPSE);
//SetUnitFlag(UNIT_FLAG_NOT_IN_PVP);
ReplaceAllDynamicFlags(UNIT_DYNFLAG_NONE);
ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable() && !HasAuraType(SPELL_AURA_PREVENT_RESURRECTION));
// 6 minutes until repop at graveyard
m_deathTimer = 6 * MINUTE * IN_MILLISECONDS;
UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
int32 corpseReclaimDelay = CalculateCorpseReclaimDelay();
if (corpseReclaimDelay >= 0)
SendCorpseReclaimDelay(corpseReclaimDelay);
// don't create corpse at this moment, player might be falling
// update visibility
UpdateObjectVisibility();
}
void Player::OfflineResurrect(ObjectGuid const& guid, CharacterDatabaseTransaction trans)
{
Corpse::DeleteFromDB(guid, trans);
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ADD_AT_LOGIN_FLAG);
stmt->setUInt16(0, uint16(AT_LOGIN_RESURRECT));
stmt->setUInt64(1, guid.GetCounter());
CharacterDatabase.ExecuteOrAppend(trans, stmt);
}
Corpse* Player::CreateCorpse()
{
// prevent the existence of 2 corpses for one player
SpawnCorpseBones();
uint32 _cfb1, _cfb2;
Corpse* corpse = new Corpse((m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE);
SetPvPDeath(false);
if (!corpse->Create(GetMap()->GenerateLowGuid<HighGuid::Corpse>(), this))
{
delete corpse;
return nullptr;
}
_corpseLocation.WorldRelocate(*this);
_cfb1 = ((0x00) | (GetRace() << 8) | (GetNativeGender() << 16) | (GetSkinId() << 24));
_cfb2 = (GetFaceId() | (GetHairStyleId() << 8) | (GetHairColorId() << 16) | (GetFacialStyle() << 24));
corpse->SetUInt32Value(CORPSE_FIELD_BYTES_1, _cfb1);
corpse->SetUInt32Value(CORPSE_FIELD_BYTES_2, _cfb2);
uint32 flags = CORPSE_FLAG_UNK2;
if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
flags |= CORPSE_FLAG_HIDE_HELM;
if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
flags |= CORPSE_FLAG_HIDE_CLOAK;
if (InBattleground() && !InArena())
flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
corpse->SetUInt32Value(CORPSE_FIELD_FLAGS, flags);
corpse->SetUInt32Value(CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId());
corpse->SetUInt32Value(CORPSE_FIELD_GUILD, GetGuildId());
uint32 iDisplayID;
uint32 iIventoryType;
uint32 _cfi;
for (uint8 i = 0; i < EQUIPMENT_SLOT_END; i++)
{
if (m_items[i])
{
iDisplayID = m_items[i]->GetTemplate()->DisplayInfoID;
iIventoryType = m_items[i]->GetTemplate()->InventoryType;
_cfi = iDisplayID | (iIventoryType << 24);
corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i, _cfi);
}
}
// register for player, but not show
GetMap()->AddCorpse(corpse);
// we do not need to save corpses for BG/arenas
if (!GetMap()->IsBattlegroundOrArena())
corpse->SaveToDB();
return corpse;
}
void Player::SpawnCorpseBones(bool triggerSave /*= true*/)
{
_corpseLocation.WorldRelocate();
if (GetMap()->ConvertCorpseToBones(GetGUID()))
if (triggerSave && !GetSession()->PlayerLogoutWithSave()) // at logout we will already store the player
SaveToDB(); // prevent loading as ghost without corpse
}
Corpse* Player::GetCorpse() const
{
return GetMap()->GetCorpseByPlayer(GetGUID());
}
void Player::SendDurabilityLoss()
{
SendDirectMessage(WorldPackets::Misc::DurabilityDamageDeath().Write());
}
void Player::DurabilityLossAll(double percent, bool inventory)
{
for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
DurabilityLoss(pItem, percent);
if (inventory)
{
// bags not have durability
// for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
DurabilityLoss(pItem, percent);
// keys not have durability
//for (int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
if (Bag* pBag = GetBagByPos(i))
for (uint32 j = 0; j < pBag->GetBagSize(); j++)
if (Item* pItem = GetItemByPos(i, j))
DurabilityLoss(pItem, percent);
}
}
void Player::DurabilityLoss(Item* item, double percent)
{
if (!item)
return;
uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
if (!pMaxDurability)
return;
uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
if (pDurabilityLoss < 1)
pDurabilityLoss = 1;
DurabilityPointsLoss(item, pDurabilityLoss);
}
void Player::DurabilityPointsLossAll(int32 points, bool inventory)
{
for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
DurabilityPointsLoss(pItem, points);
if (inventory)
{
// bags not have durability
// for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
DurabilityPointsLoss(pItem, points);
// keys not have durability
//for (int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
if (Bag* pBag = static_cast<Bag*>(GetItemByPos(INVENTORY_SLOT_BAG_0, i)))
for (uint32 j = 0; j < pBag->GetBagSize(); j++)
if (Item* pItem = GetItemByPos(i, j))
DurabilityPointsLoss(pItem, points);
}
}
void Player::DurabilityPointsLoss(Item* item, int32 points)
{
if (HasAuraType(SPELL_AURA_PREVENT_DURABILITY_LOSS))
return;
int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
int32 pNewDurability = pOldDurability - points;
if (pNewDurability < 0)
pNewDurability = 0;
else if (pNewDurability > pMaxDurability)
pNewDurability = pMaxDurability;
if (pOldDurability != pNewDurability)
{
// modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
if (pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
_ApplyItemMods(item, item->GetSlot(), false);
item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
// modify item stats _after_ restore durability to pass _ApplyItemMods internal check
if (pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
_ApplyItemMods(item, item->GetSlot(), true);
item->SetState(ITEM_CHANGED, this);
}
}
void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
{
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, slot))
DurabilityPointsLoss(pItem, 1);
}
void Player::DurabilityRepairAll(bool takeCost, float discountMod, bool guildBank)
{
// Collecting all items that can be repaired and repair costs
std::list<std::pair<Item*, uint32>> itemRepairCostStore;
// equipped, backpack, bags itself
for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
if (Item* item = GetItemByPos(((INVENTORY_SLOT_BAG_0 << 8) | i)))
if (uint32 cost = item->CalculateDurabilityRepairCost(discountMod))
itemRepairCostStore.push_back(std::make_pair(item, cost));
// bank, buyback and keys not repaired
// items in inventory bags
for (uint8 j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; j++)
for (uint8 i = 0; i < MAX_BAG_SIZE; i++)
if (Item* item = GetItemByPos(((j << 8) | i)))
if (uint32 cost = item->CalculateDurabilityRepairCost(discountMod))
itemRepairCostStore.push_back(std::make_pair(item, cost));
// Handling a free repair case - just repair every item without taking cost.
if (!takeCost)
{
for (auto const& [item, cost] : itemRepairCostStore)
DurabilityRepair(item->GetPos(), false, 0.f);
return;
}
if (guildBank)
{
// Handling a repair for guild money case.
// We have to repair items one by one until the guild bank has enough money available for withdrawal or until all items are repaired.
Guild* guild = GetGuild();
if (!guild)
return; // silent return, client shouldn't display this button for players without guild.
uint64 const availableGuildMoney = guild->GetMemberAvailableMoneyForRepairItems(GetGUID());
if (availableGuildMoney == 0)
return;
// Sort the items by repair cost from lowest to highest
itemRepairCostStore.sort([](auto const& a, auto const& b) -> bool { return a.second < b.second; });
// We must calculate total repair cost and take money once to avoid spam in the guild bank log and reduce number of transactions in the database
uint32 totalCost = 0;
for (auto const& [item, cost] : itemRepairCostStore)
{
uint64 newTotalCost = totalCost + cost;
if (newTotalCost > availableGuildMoney || newTotalCost > MAX_MONEY_AMOUNT)
break;
totalCost = static_cast<uint32>(newTotalCost);
// Repair item without taking cost. We'll do it later.
DurabilityRepair(item->GetPos(), false, 0.f);
}
// Take money for repairs from the guild bank
guild->HandleMemberWithdrawMoney(GetSession(), totalCost, true);
}
else
{
// Handling a repair for player's money case.
// Unlike repairing for guild money, in this case we must first check if player has enough money to repair all the items at once.
uint32 totalCost = 0;
for (auto const& [item, cost] : itemRepairCostStore)
totalCost += cost;
if (!HasEnoughMoney(totalCost))
return; // silent return, client should display error by itself and not send opcode.
ModifyMoney(-int32(totalCost));
// Payment for repair has already been taken, so just repair every item without taking cost.
for (auto const& [item, cost] : itemRepairCostStore)
DurabilityRepair(item->GetPos(), false, 0.f);
}
}
void Player::DurabilityRepair(uint16 pos, bool takeCost, float discountMod)
{
Item* item = GetItemByPos(pos);
if (!item)
return;
if (takeCost)
{
uint32 cost = item->CalculateDurabilityRepairCost(discountMod);
if (!HasEnoughMoney(cost))
{
TC_LOG_DEBUG("entities.player.items", "Player::DurabilityRepair: Player '{}' ({}) has not enough money to repair item",
GetName(), GetGUID().ToString());
return;
}
ModifyMoney(-int32(cost));
}
bool isBroken = item->IsBroken();
item->SetUInt32Value(ITEM_FIELD_DURABILITY, item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY));
item->SetState(ITEM_CHANGED, this);
// reapply mods for total broken and repaired item if equipped
if (IsEquipmentPos(pos) && isBroken)
_ApplyItemMods(item, pos & 255, true);
}
void Player::RepopAtGraveyard()
{
// note: this can be called also when the player is alive
// for example from WorldSession::HandleMovementOpcodes
AreaTableEntry const* zone = sAreaTableStore.LookupEntry(GetAreaId());
bool shouldResurrect = false;
// Such zones are considered unreachable as a ghost and the player must be automatically revived
if ((!IsAlive() && zone && zone->Flags & AREA_FLAG_NEED_FLY) || GetTransport() || GetPositionZ() < GetMap()->GetMinHeight(GetPositionX(), GetPositionY()))
{
shouldResurrect = true;
SpawnCorpseBones();
}
WorldSafeLocsEntry const* ClosestGrave;
// Special handle for battleground maps
if (Battleground* bg = GetBattleground())
ClosestGrave = bg->GetClosestGraveyard(this);
else
{
if (Battlefield* bf = sBattlefieldMgr->GetBattlefieldToZoneId(GetZoneId()))
ClosestGrave = bf->GetClosestGraveyard(this);
else
ClosestGrave = sObjectMgr->GetClosestGraveyard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam(), this);
}
// stop countdown until repop
m_deathTimer = 0;
// if no grave found, stay at the current location
// and don't show spirit healer location
if (ClosestGrave)
{
TeleportTo(ClosestGrave->Continent, ClosestGrave->Loc.X, ClosestGrave->Loc.Y, ClosestGrave->Loc.Z, GetOrientation(), shouldResurrect ? TELE_REVIVE_AT_TELEPORT : 0);
if (isDead()) // not send if alive, because it used in TeleportTo()
{
WorldPackets::Misc::DeathReleaseLoc packet;
packet.MapID = ClosestGrave->Continent;
packet.Loc = Position(ClosestGrave->Loc.X, ClosestGrave->Loc.Y, ClosestGrave->Loc.Z);
GetSession()->SendPacket(packet.Write());
}
}
else if (GetPositionZ() < GetMap()->GetMinHeight(GetPositionX(), GetPositionY()))
TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation());
RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_IS_OUT_OF_BOUNDS);
}
bool Player::CanJoinConstantChannelInZone(ChatChannelsEntry const* channel, AreaTableEntry const* zone) const
{
if (channel->Flags & CHANNEL_DBC_FLAG_ZONE_DEP && zone->Flags & AREA_FLAG_ARENA_INSTANCE)
return false;
if ((channel->Flags & CHANNEL_DBC_FLAG_CITY_ONLY) && (!(zone->Flags & AREA_FLAG_SLAVE_CAPITAL)))
return false;
if ((channel->Flags & CHANNEL_DBC_FLAG_GUILD_REQ) && GetGuildId())
return false;
return true;
}
void Player::JoinedChannel(Channel* c)
{
m_channels.push_back(c);
}
void Player::LeftChannel(Channel* c)
{
m_channels.remove(c);
}
void Player::CleanupChannels()
{
while (!m_channels.empty())
{
Channel* ch = *m_channels.begin();
m_channels.erase(m_channels.begin()); // remove from player's channel list
ch->LeaveChannel(this, false); // not send to client, not remove from player's channel list
// delete channel if empty
if (ChannelMgr* cMgr = ChannelMgr::forTeam(GetTeam()))
if (ch->IsConstant())
cMgr->LeftChannel(ch->GetChannelId(), ch->GetZoneEntry());
}
TC_LOG_DEBUG("chat.system", "Player::CleanupChannels: Channels of player '{}' ({}) cleaned up.", GetName(), GetGUID().ToString());
}
void Player::UpdateLocalChannels(uint32 newZone)
{
if (GetSession()->PlayerLoading() && !IsBeingTeleportedFar())
return; // The client handles it automatically after loading, but not after teleporting
AreaTableEntry const* current_zone = sAreaTableStore.LookupEntry(newZone);
if (!current_zone)
return;
ChannelMgr* cMgr = ChannelMgr::forTeam(GetTeam());
if (!cMgr)
return;
for (uint32 i = 0; i < sChatChannelsStore.GetNumRows(); ++i)
{
ChatChannelsEntry const* channelEntry = sChatChannelsStore.LookupEntry(i);
if (!channelEntry)
continue;
Channel* usedChannel = nullptr;
for (Channel* channel : m_channels)
{
if (channel->GetChannelId() == i)
{
usedChannel = channel;
break;
}
}
Channel* removeChannel = nullptr;
Channel* joinChannel = nullptr;
bool sendRemove = true;
if (CanJoinConstantChannelInZone(channelEntry, current_zone))
{
if (!(channelEntry->Flags & CHANNEL_DBC_FLAG_GLOBAL))
{
if (channelEntry->Flags & CHANNEL_DBC_FLAG_CITY_ONLY && usedChannel)
continue; // Already on the channel, as city channel names are not changing
joinChannel = cMgr->GetSystemChannel(channelEntry->ID, current_zone);
if (usedChannel)
{
if (joinChannel != usedChannel)
{
removeChannel = usedChannel;
sendRemove = false; // Do not send leave channel, it already replaced at client
}
else
joinChannel = nullptr;
}
}
else
joinChannel = cMgr->GetSystemChannel(channelEntry->ID);
}
else
removeChannel = usedChannel;
if (joinChannel)
joinChannel->JoinChannel(this); // Changed Channel: ... or Joined Channel: ...
if (removeChannel)
{
removeChannel->LeaveChannel(this, sendRemove); // Leave old channel
LeftChannel(removeChannel); // Remove from player's channel list
cMgr->LeftChannel(removeChannel->GetChannelId(), removeChannel->GetZoneEntry()); // Delete if empty
}
}
}
void Player::LeaveLFGChannel()
{
for (JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i)
{
if ((*i)->IsLFG())
{
(*i)->LeaveChannel(this);
break;
}
}
}
void Player::UpdateDefense()
{
if (UpdateSkill(SKILL_DEFENSE, sWorld->getIntConfig(CONFIG_SKILL_GAIN_DEFENSE)))
UpdateDefenseBonusesMod(); // update dependent from defense skill part
}
void Player::HandleBaseModFlatValue(BaseModGroup modGroup, float amount, bool apply)
{
if (modGroup >= BASEMOD_END)
{
TC_LOG_ERROR("spells", "Player::HandleBaseModValue: Invalid BaseModGroup/BaseModType ({}/{}) for player '{}' ({})",
modGroup, FLAT_MOD, GetName(), GetGUID().ToString());
return;
}
m_auraBaseFlatMod[modGroup] += apply ? amount : -amount;
UpdateBaseModGroup(modGroup);
}
void Player::ApplyBaseModPctValue(BaseModGroup modGroup, float pct)
{
if (modGroup >= BASEMOD_END)
{
TC_LOG_ERROR("spells", "Player::HandleBaseModValue: Invalid BaseModGroup/BaseModType ({}/{}) for player '{}' ({})",
modGroup, FLAT_MOD, GetName(), GetGUID().ToString());
return;
}
m_auraBasePctMod[modGroup] += CalculatePct(1.0f, pct);
UpdateBaseModGroup(modGroup);
}
void Player::SetBaseModFlatValue(BaseModGroup modGroup, float val)
{
if (m_auraBaseFlatMod[modGroup] == val)
return;
m_auraBaseFlatMod[modGroup] = val;
UpdateBaseModGroup(modGroup);
}
void Player::SetBaseModPctValue(BaseModGroup modGroup, float val)
{
if (m_auraBasePctMod[modGroup] == val)
return;
m_auraBasePctMod[modGroup] = val;
UpdateBaseModGroup(modGroup);
}
void Player::UpdateDamageDoneMods(WeaponAttackType attackType, int32 skipEnchantSlot /*= -1*/)
{
Unit::UpdateDamageDoneMods(attackType, skipEnchantSlot);
UnitMods unitMod;
switch (attackType)
{
case BASE_ATTACK:
unitMod = UNIT_MOD_DAMAGE_MAINHAND;
break;
case OFF_ATTACK:
unitMod = UNIT_MOD_DAMAGE_OFFHAND;
break;
case RANGED_ATTACK:
unitMod = UNIT_MOD_DAMAGE_RANGED;
break;
default:
ABORT();
break;
}
float amount = 0.0f;
Item* item = GetWeaponForAttack(attackType, true);
if (!item)
return;
for (uint8 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
{
if (skipEnchantSlot == slot)
continue;
SpellItemEnchantmentEntry const* enchantmentEntry = sSpellItemEnchantmentStore.LookupEntry(item->GetEnchantmentId(EnchantmentSlot(slot)));
if (!enchantmentEntry)
continue;
for (uint8 i = 0; i < MAX_ITEM_ENCHANTMENT_EFFECTS; ++i)
{
switch (enchantmentEntry->Effect[i])
{
case ITEM_ENCHANTMENT_TYPE_DAMAGE:
amount += enchantmentEntry->EffectPointsMin[i];
break;
case ITEM_ENCHANTMENT_TYPE_TOTEM:
if (GetClass() == CLASS_SHAMAN)
amount += enchantmentEntry->EffectPointsMin[i] * item->GetTemplate()->Delay / 1000.0f;
break;
default:
break;
}
}
}
HandleStatFlatModifier(unitMod, TOTAL_VALUE, amount, true);
}
void Player::UpdateBaseModGroup(BaseModGroup modGroup)
{
if (!CanModifyStats())
return;
switch (modGroup)
{
case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
default: break;
}
}
float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
{
if (modGroup >= BASEMOD_END || modType >= MOD_END)
{
TC_LOG_ERROR("spells", "Player::GetBaseModValue: Invalid BaseModGroup/BaseModType ({}/{}) for player '{}' ({})",
modGroup, modType, GetName(), GetGUID().ToString());
return 0.0f;
}
return (modType == FLAT_MOD ? m_auraBaseFlatMod[modGroup] : m_auraBasePctMod[modGroup]);
}
float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
{
if (modGroup >= BASEMOD_END)
{
TC_LOG_ERROR("spells", "Player::GetTotalBaseModValue: Invalid BaseModGroup ({}) for player '{}' ({})",
modGroup, GetName(), GetGUID().ToString());
return 0.0f;
}
return m_auraBaseFlatMod[modGroup] * m_auraBasePctMod[modGroup];
}
uint32 Player::GetShieldBlockValue() const
{
float value = std::max(0.f, (m_auraBaseFlatMod[SHIELD_BLOCK_VALUE] + GetStat(STAT_STRENGTH) * 0.5f - 10) * m_auraBasePctMod[SHIELD_BLOCK_VALUE]);
return uint32(value);
}
float Player::GetMeleeCritFromAgility() const
{
uint8 level = GetLevel();
uint32 pclass = GetClass();
if (level > GT_MAX_LEVEL)
level = GT_MAX_LEVEL;
GtChanceToMeleeCritBaseEntry const* critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
GtChanceToMeleeCritEntry const* critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
if (critBase == nullptr || critRatio == nullptr)
return 0.0f;
float crit = critBase->Data + GetStat(STAT_AGILITY)*critRatio->Data;
return crit*100.0f;
}
void Player::GetDodgeFromAgility(float &diminishing, float &nondiminishing) const
{
// Table for base dodge values
const float dodge_base[MAX_CLASSES] =
{
0.036640f, // Warrior
0.034943f, // Paladin
-0.040873f, // Hunter
0.020957f, // Rogue
0.034178f, // Priest
0.036640f, // DK
0.021080f, // Shaman
0.036587f, // Mage
0.024211f, // Warlock
0.0f, // ??
0.056097f // Druid
};
// Crit/agility to dodge/agility coefficient multipliers; 3.2.0 increased required agility by 15%
const float crit_to_dodge[MAX_CLASSES] =
{
0.85f/1.15f, // Warrior
1.00f/1.15f, // Paladin
1.11f/1.15f, // Hunter
2.00f/1.15f, // Rogue
1.00f/1.15f, // Priest
0.85f/1.15f, // DK
1.60f/1.15f, // Shaman
1.00f/1.15f, // Mage
0.97f/1.15f, // Warlock (?)
0.0f, // ??
2.00f/1.15f // Druid
};
uint8 level = GetLevel();
uint32 pclass = GetClass();
if (level > GT_MAX_LEVEL)
level = GT_MAX_LEVEL;
// Dodge per agility is proportional to crit per agility, which is available from DBC files
GtChanceToMeleeCritEntry const* dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
if (dodgeRatio == nullptr || pclass > MAX_CLASSES)
return;
/// @todo research if talents/effects that increase total agility by x% should increase non-diminishing part
float base_agility = GetCreateStat(STAT_AGILITY) * GetPctModifierValue(UnitMods(UNIT_MOD_STAT_START + AsUnderlyingType(STAT_AGILITY)), BASE_PCT);
float bonus_agility = GetStat(STAT_AGILITY) - base_agility;
// calculate diminishing (green in char screen) and non-diminishing (white) contribution
diminishing = 100.0f * bonus_agility * dodgeRatio->Data * crit_to_dodge[pclass-1];
nondiminishing = 100.0f * (dodge_base[pclass-1] + base_agility * dodgeRatio->Data * crit_to_dodge[pclass-1]);
}
float Player::GetSpellCritFromIntellect() const
{
uint8 level = GetLevel();
uint32 pclass = GetClass();
if (level > GT_MAX_LEVEL)
level = GT_MAX_LEVEL;
GtChanceToSpellCritBaseEntry const* critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass - 1);
GtChanceToSpellCritEntry const* critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass - 1) * GT_MAX_LEVEL + level - 1);
if (critBase == nullptr || critRatio == nullptr)
return 0.0f;
float crit = critBase->Data + GetStat(STAT_INTELLECT) * critRatio->Data;
return crit * 100.0f;
}
float Player::GetRatingMultiplier(CombatRating cr) const
{
uint8 level = GetLevel();
if (level > GT_MAX_LEVEL)
level = GT_MAX_LEVEL;
GtCombatRatingsEntry const* Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
// gtOCTClassCombatRatingScalarStore.dbc starts with 1, CombatRating with zero, so cr+1
GtOCTClassCombatRatingScalarEntry const* classRating = sGtOCTClassCombatRatingScalarStore.LookupEntry((GetClass()-1)*GT_MAX_RATING+cr+1);
if (!Rating || !classRating)
return 1.0f; // By default use minimum coefficient (not must be called)
return classRating->Data / Rating->Data;
}
float Player::GetRatingBonusValue(CombatRating cr) const
{
return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + AsUnderlyingType(cr))) * GetRatingMultiplier(cr);
}
float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
{
switch (attType)
{
case BASE_ATTACK:
return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
case OFF_ATTACK:
return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
default:
break;
}
return 0.0f;
}
float Player::OCTRegenHPPerSpirit() const
{
uint8 level = GetLevel();
uint32 pclass = GetClass();
if (level > GT_MAX_LEVEL)
level = GT_MAX_LEVEL;
GtOCTRegenHPEntry const* baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
GtRegenHPPerSptEntry const* moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
if (baseRatio == nullptr || moreRatio == nullptr)
return 0.0f;
// Formula from PaperDollFrame script
float spirit = GetStat(STAT_SPIRIT);
float baseSpirit = spirit;
if (baseSpirit > 50)
baseSpirit = 50;
float moreSpirit = spirit - baseSpirit;
float regen = baseSpirit * baseRatio->Data + moreSpirit * moreRatio->Data;
return regen;
}
float Player::OCTRegenMPPerSpirit() const
{
uint8 level = GetLevel();
uint32 pclass = GetClass();
if (level > GT_MAX_LEVEL)
level = GT_MAX_LEVEL;
// GtOCTRegenMPEntry const* baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
GtRegenMPPerSptEntry const* moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
if (moreRatio == nullptr)
return 0.0f;
// Formula get from PaperDollFrame script
float spirit = GetStat(STAT_SPIRIT);
float regen = spirit * moreRatio->Data;
return regen;
}
void Player::ApplyRatingMod(CombatRating combatRating, int32 value, bool apply)
{
float oldRating = m_baseRatingValue[combatRating];
m_baseRatingValue[combatRating] += (apply ? value : -value);
// explicit affected values
float const multiplier = GetRatingMultiplier(combatRating);
float const oldVal = oldRating * multiplier;
float const newVal = m_baseRatingValue[combatRating] * multiplier;
switch (combatRating)
{
case CR_HASTE_MELEE:
ApplyAttackTimePercentMod(BASE_ATTACK, oldVal, false);
ApplyAttackTimePercentMod(OFF_ATTACK, oldVal, false);
ApplyAttackTimePercentMod(BASE_ATTACK, newVal, true);
ApplyAttackTimePercentMod(OFF_ATTACK, newVal, true);
break;
case CR_HASTE_RANGED:
ApplyAttackTimePercentMod(RANGED_ATTACK, oldVal, false);
ApplyAttackTimePercentMod(RANGED_ATTACK, newVal, true);
break;
case CR_HASTE_SPELL:
ApplyCastTimePercentMod(oldVal, false);
ApplyCastTimePercentMod(newVal, true);
break;
default:
break;
}
UpdateRating(combatRating);
}
void Player::UpdateRating(CombatRating cr)
{
int32 amount = m_baseRatingValue[cr];
// Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
// stat used stored in miscValueB for this aura
AuraEffectList const& modRatingFromStat = GetAuraEffectsByType(SPELL_AURA_MOD_RATING_FROM_STAT);
for (AuraEffect const* aurEff : modRatingFromStat)
if (aurEff->GetMiscValue() & (1 << cr))
amount += int32(CalculatePct(GetStat(Stats(aurEff->GetMiscValueB())), aurEff->GetAmount()));
if (amount < 0)
amount = 0;
SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + AsUnderlyingType(cr), uint32(amount));
bool affectStats = CanModifyStats();
switch (cr)
{
case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
case CR_DEFENSE_SKILL:
UpdateDefenseBonusesMod();
break;
case CR_DODGE:
UpdateDodgePercentage();
break;
case CR_PARRY:
UpdateParryPercentage();
break;
case CR_BLOCK:
UpdateBlockPercentage();
break;
case CR_HIT_MELEE:
UpdateMeleeHitChances();
break;
case CR_HIT_RANGED:
UpdateRangedHitChances();
break;
case CR_HIT_SPELL:
UpdateSpellHitChances();
break;
case CR_CRIT_MELEE:
if (affectStats)
{
UpdateCritPercentage(BASE_ATTACK);
UpdateCritPercentage(OFF_ATTACK);
}
break;
case CR_CRIT_RANGED:
if (affectStats)
UpdateCritPercentage(RANGED_ATTACK);
break;
case CR_CRIT_SPELL:
if (affectStats)
UpdateAllSpellCritChances();
break;
case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
case CR_HIT_TAKEN_RANGED:
break;
case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
break;
case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
case CR_CRIT_TAKEN_RANGED:
break;
case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
break;
case CR_HASTE_MELEE: // Implemented in Player::ApplyRatingMod
case CR_HASTE_RANGED:
case CR_HASTE_SPELL:
break;
case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
case CR_WEAPON_SKILL_OFFHAND:
case CR_WEAPON_SKILL_RANGED:
break;
case CR_EXPERTISE:
if (affectStats)
{
UpdateExpertise(BASE_ATTACK);
UpdateExpertise(OFF_ATTACK);
}
break;
case CR_ARMOR_PENETRATION:
if (affectStats)
UpdateArmorPenetration(amount);
break;
}
}
void Player::UpdateAllRatings()
{
for (uint8 cr = 0; cr < MAX_COMBAT_RATING; ++cr)
UpdateRating(CombatRating(cr));
}
void Player::SetRegularAttackTime()
{
for (uint8 i = 0; i < MAX_ATTACK; ++i)
{
Item* tmpitem = GetWeaponForAttack(WeaponAttackType(i), true);
if (tmpitem && !tmpitem->IsBroken())
{
ItemTemplate const* proto = tmpitem->GetTemplate();
if (proto->Delay)
SetAttackTime(WeaponAttackType(i), proto->Delay);
}
else
SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME); // If there is no weapon reset attack time to base (might have been changed from forms)
}
}
void Player::StoreRaidMapDifficulty()
{
m_raidMapDifficulty = GetMap()->GetDifficulty();
}
//skill+step, checking for max value
bool Player::UpdateSkill(uint32 skill_id, uint32 step)
{
if (!skill_id)
return false;
SkillStatusMap::iterator itr = mSkillStatus.find(skill_id);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return false;
uint16 value = GetSkillRankByPos(itr->second.pos);
uint16 max = GetSkillMaxRankByPos(itr->second.pos);
if (!max || !value || value >= max)
return false;
if (value < max)
{
uint16 new_value = std::min(uint16(value + step), max);
SetSkillRank(itr->second.pos, new_value);
if (itr->second.uState != SKILL_NEW)
itr->second.uState = SKILL_CHANGED;
UpdateSkillEnchantments(skill_id, value, new_value);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL, skill_id);
return true;
}
return false;
}
inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
{
if (SkillValue >= GrayLevel)
return sWorld->getIntConfig(CONFIG_SKILL_CHANCE_GREY)*10;
if (SkillValue >= GreenLevel)
return sWorld->getIntConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
if (SkillValue >= YellowLevel)
return sWorld->getIntConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
return sWorld->getIntConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
}
bool Player::UpdateCraftSkill(uint32 spellid)
{
TC_LOG_DEBUG("entities.player.skills", "Player::UpdateCraftSkill: Player '{}' ({}), SpellID: {}",
GetName(), GetGUID().ToString(), spellid);
SkillLineAbilityMapBounds bounds = sSpellMgr->GetSkillLineAbilityMapBounds(spellid);
for (SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
{
if (_spell_idx->second->SkillLine)
{
uint32 SkillValue = GetPureSkillValue(_spell_idx->second->SkillLine);
// Alchemy Discoveries here
SpellInfo const* spellEntry = sSpellMgr->GetSpellInfo(spellid);
if (spellEntry && spellEntry->Mechanic == MECHANIC_DISCOVERY)
{
if (uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->SkillLine, spellid, this))
LearnSpell(discoveredSpell, false);
}
uint32 craft_skill_gain = sWorld->getIntConfig(CONFIG_SKILL_GAIN_CRAFTING);
return UpdateSkillPro(_spell_idx->second->SkillLine, SkillGainChance(SkillValue,
_spell_idx->second->TrivialSkillLineRankHigh,
(_spell_idx->second->TrivialSkillLineRankHigh + _spell_idx->second->TrivialSkillLineRankLow)/2,
_spell_idx->second->TrivialSkillLineRankLow),
craft_skill_gain);
}
}
return false;
}
bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator)
{
TC_LOG_DEBUG("entities.player.skills", "Player::UpdateGatherSkill: Player '{}' ({}), SkillID: {}, SkillLevel: {}, RedLevel: {})",
GetName(), GetGUID().ToString(), SkillId, SkillValue, RedLevel);
uint32 gathering_skill_gain = sWorld->getIntConfig(CONFIG_SKILL_GAIN_GATHERING);
// For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
switch (SkillId)
{
case SKILL_HERBALISM:
case SKILL_LOCKPICKING:
case SKILL_JEWELCRAFTING:
case SKILL_INSCRIPTION:
return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator, gathering_skill_gain);
case SKILL_SKINNING:
if (sWorld->getIntConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS) == 0)
return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator, gathering_skill_gain);
else
return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld->getIntConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
case SKILL_MINING:
if (sWorld->getIntConfig(CONFIG_SKILL_CHANCE_MINING_STEPS) == 0)
return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator, gathering_skill_gain);
else
return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld->getIntConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)), gathering_skill_gain);
}
return false;
}
uint8 GetFishingStepsNeededToLevelUp(uint32 SkillValue)
{
// These formulas are guessed to be as close as possible to how the skill difficulty curve for fishing was on Retail.
if (SkillValue < 75)
return 1;
if (SkillValue <= 300)
return SkillValue / 44;
return SkillValue / 31;
}
bool Player::UpdateFishingSkill()
{
TC_LOG_DEBUG("entities.player.skills", "Player::UpdateFishingSkill: Player '{}' ({})", GetName(), GetGUID().ToString());
uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
if (SkillValue >= GetMaxSkillValue(SKILL_FISHING))
return false;
uint8 stepsNeededToLevelUp = GetFishingStepsNeededToLevelUp(SkillValue);
++m_fishingSteps;
if (m_fishingSteps >= stepsNeededToLevelUp)
{
m_fishingSteps = 0;
uint32 gathering_skill_gain = sWorld->getIntConfig(CONFIG_SKILL_GAIN_GATHERING);
return UpdateSkillPro(SKILL_FISHING, 100*10, gathering_skill_gain);
}
return false;
}
bool Player::UpdateSkillPro(uint16 skillId, int32 chance, uint32 step)
{
// levels sync. with spell requirement for skill levels to learn
// bonus abilities in sSkillLineAbilityStore
// Used only to avoid scan DBC at each skill grow
uint32 const bonusSkillLevels[] = { 75, 150, 225, 300, 375, 450 };
TC_LOG_DEBUG("entities.player.skills", "Player::UpdateSkillPro: Player '{}' ({}), SkillID: {}, Chance: {:3.1f}%)",
GetName(), GetGUID().ToString(), skillId, chance / 10.0f);
if (!skillId)
return false;
if (chance <= 0) // speedup in 0 chance case
{
TC_LOG_DEBUG("entities.player.skills", "Player::UpdateSkillPro: Player '{}' ({}), SkillID: {}, Chance: {:3.1f}% missed",
GetName(), GetGUID().ToString(), skillId, chance / 10.0f);
return false;
}
SkillStatusMap::iterator itr = mSkillStatus.find(skillId);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return false;
uint16 value = GetSkillRankByPos(itr->second.pos);
uint16 max = GetSkillMaxRankByPos(itr->second.pos);
if (!max || !value || value >= max)
return false;
if (irand(1, 1000) > chance)
{
TC_LOG_DEBUG("entities.player.skills",
"Player::UpdateSkillPro: Player '{}' ({}), SkillID: {}, Chance: {:3.1f}% missed",
GetName(), GetGUID().ToString(), skillId, chance / 10.0f);
return false;
}
uint16 new_value = value + step;
if (new_value > max)
new_value = max;
SetSkillRank(itr->second.pos, new_value);
if (itr->second.uState != SKILL_NEW)
itr->second.uState = SKILL_CHANGED;
for (uint32 bsl : bonusSkillLevels)
{
if (value < bsl && new_value >= bsl)
{
LearnSkillRewardedSpells(skillId, new_value);
break;
}
}
UpdateSkillEnchantments(skillId, value, new_value);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL, skillId);
#ifdef ELUNA
if (Eluna* e = GetEluna())
e->OnSkillChange(this, skillId, new_value);
#endif
TC_LOG_DEBUG("entities.player.skills", "Player::UpdateSkillPro: Player '{}' ({}), SkillID: {}, Chance: {:3.1f}% taken",
GetName(), GetGUID().ToString(), skillId, chance / 10.0f);
return true;
}
void Player::UpdateWeaponSkill(Unit* victim, WeaponAttackType attType)
{
if (IsInFeralForm())
return; // always maximized SKILL_FERAL_COMBAT in fact
if (GetShapeshiftForm() == FORM_TREE)
return; // use weapon but not skill up
if (victim->GetTypeId() == TYPEID_UNIT && (victim->ToCreature()->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_NO_SKILL_GAINS))
return;
uint32 weapon_skill_gain = sWorld->getIntConfig(CONFIG_SKILL_GAIN_WEAPON);
Item* tmpitem = GetWeaponForAttack(attType, true);
if (!tmpitem && attType == BASE_ATTACK)
{
// Keep unarmed & fist weapon skills in sync
UpdateSkill(SKILL_UNARMED, weapon_skill_gain);
UpdateSkill(SKILL_FIST_WEAPONS, weapon_skill_gain);
}
else if (tmpitem)
{
switch (tmpitem->GetTemplate()->SubClass)
{
case ITEM_SUBCLASS_WEAPON_FISHING_POLE:
break;
case ITEM_SUBCLASS_WEAPON_FIST_WEAPON:
UpdateSkill(SKILL_UNARMED, weapon_skill_gain);
[[fallthrough]];
default:
UpdateSkill(tmpitem->GetSkill(), weapon_skill_gain);
break;
}
}
UpdateAllCritPercentages();
}
void Player::UpdateCombatSkills(Unit* victim, WeaponAttackType attType, bool defense)
{
int32 plevel = GetLevel(); // if defense than victim == attacker
int32 greylevel = Trinity::XP::GetGrayLevel(plevel);
int32 moblevel = victim->GetLevelForTarget(this);
if (moblevel > plevel + 5)
moblevel = plevel + 5;
int32 lvldif = moblevel - greylevel;
if (lvldif < 3)
lvldif = 3;
int32 skilldif = 5 * plevel - int32(defense ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
if (skilldif <= 0)
return;
float chance = float(3 * lvldif * skilldif) / plevel;
if (!defense)
if (GetClass() == CLASS_WARRIOR || GetClass() == CLASS_ROGUE)
chance += chance * 0.02f * GetStat(STAT_INTELLECT);
chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
if (roll_chance_f(chance))
{
if (defense)
UpdateDefense();
else
UpdateWeaponSkill(victim, attType);
}
}
void Player::ModifySkillBonus(uint32 skillid, int32 val, bool talent)
{
SkillStatusMap::const_iterator itr = mSkillStatus.find(skillid);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return;
if (talent) // permanent bonus stored in high part
SetSkillPermBonus(itr->second.pos, GetSkillPermBonusByPos(itr->second.pos) + val);
else // temporary/item bonus stored in low part
SetSkillTempBonus(itr->second.pos, GetSkillTempBonusByPos(itr->second.pos) + val);
}
void Player::UpdateSkillsForLevel()
{
uint16 maxconfskill = sWorld->GetConfigMaxSkillValue();
uint32 maxSkill = GetMaxSkillValueForLevel();
bool alwaysMaxSkill = sWorld->getBoolConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL);
for (SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); ++itr)
{
if (itr->second.uState == SKILL_DELETED)
continue;
uint32 pskill = itr->first;
SkillRaceClassInfoEntry const* rcEntry = GetSkillRaceClassInfo(pskill, GetRace(), GetClass());
if (!rcEntry)
continue;
if (GetSkillRangeType(rcEntry) != SKILL_RANGE_LEVEL)
continue;
uint16 max = GetSkillMaxRankByPos(itr->second.pos);
/// update only level dependent max skill values
if (max != 1)
{
/// maximize skill always
if (alwaysMaxSkill || (rcEntry->Flags & SKILL_FLAG_ALWAYS_MAX_VALUE))
{
SetSkillRank(itr->second.pos, maxSkill);
SetSkillMaxRank(itr->second.pos, maxSkill);
if (itr->second.uState != SKILL_NEW)
itr->second.uState = SKILL_CHANGED;
}
else if (max != maxconfskill) /// update max skill value if current max skill not maximized
{
SetSkillMaxRank(itr->second.pos, maxSkill);
if (itr->second.uState != SKILL_NEW)
itr->second.uState = SKILL_CHANGED;
}
}
}
}
void Player::UpdateWeaponsSkillsToMaxSkillsForLevel()
{
for (SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); ++itr)
{
if (itr->second.uState == SKILL_DELETED)
continue;
uint32 pskill = itr->first;
if (IsProfessionOrRidingSkill(pskill))
continue;
uint16 max = GetSkillMaxRankByPos(itr->second.pos);
if (max > 1)
{
SetSkillRank(itr->second.pos, max);
if (itr->second.uState != SKILL_NEW)
itr->second.uState = SKILL_CHANGED;
}
if (pskill == SKILL_DEFENSE)
UpdateDefenseBonusesMod();
}
}
// This functions sets a skill line value (and adds if doesn't exist yet)
// To "remove" a skill line, set it's values to zero
void Player::SetSkill(uint32 id, uint16 step, uint16 newVal, uint16 maxVal)
{
if (!id)
return;
uint16 currVal;
SkillStatusMap::iterator itr = mSkillStatus.find(id);
//has skill
if (itr != mSkillStatus.end() && itr->second.uState != SKILL_DELETED)
{
currVal = GetSkillRankByPos(itr->second.pos);
if (newVal)
{
// if skill value is going down, update enchantments before setting the new value
if (newVal < currVal)
UpdateSkillEnchantments(id, currVal, newVal);
// update step
SetSkillStep(itr->second.pos, step);
// update value
SetSkillRank(itr->second.pos, newVal);
SetSkillMaxRank(itr->second.pos, maxVal);
if (itr->second.uState != SKILL_NEW)
itr->second.uState = SKILL_CHANGED;
LearnSkillRewardedSpells(id, newVal);
// if skill value is going up, update enchantments after setting the new value
if (newVal > currVal)
UpdateSkillEnchantments(id, currVal, newVal);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL, id);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL, id);
}
else //remove
{
//remove enchantments needing this skill
UpdateSkillEnchantments(id, currVal, 0);
// clear skill fields
SetSkillLineId(itr->second.pos, 0);
SetSkillStep(itr->second.pos, 0);
SetSkillRank(itr->second.pos, 0);
SetSkillMaxRank(itr->second.pos, 0);
SetSkillTempBonus(itr->second.pos, 0);
SetSkillPermBonus(itr->second.pos, 0);
// mark as deleted or simply remove from map if not saved yet
if (itr->second.uState != SKILL_NEW)
itr->second.uState = SKILL_DELETED;
else
mSkillStatus.erase(itr);
// remove all spells that related to this skill
if (std::vector<SkillLineAbilityEntry const*> const* skillLineAbilities = GetSkillLineAbilitiesBySkill(id))
for (SkillLineAbilityEntry const* skillLineAbility : *skillLineAbilities)
RemoveSpell(sSpellMgr->GetFirstSpellInChain(skillLineAbility->Spell));
}
}
else if (newVal) //add
{
currVal = 0;
for (uint32 i = 0; i < PLAYER_MAX_SKILLS; ++i)
{
if (!GetSkillLineIdByPos(i))
{
SkillLineEntry const* pSkill = sSkillLineStore.LookupEntry(id);
if (!pSkill)
{
TC_LOG_ERROR("misc", "Player::SetSkill: Skill (SkillID: {}) not found in SkillLineStore for player '{}' ({})",
id, GetName(), GetGUID().ToString());
return;
}
SetSkillLineId(i, id);
SetSkillStep(i, step);
SetSkillRank(i, newVal);
SetSkillMaxRank(i, maxVal);
UpdateSkillEnchantments(id, currVal, newVal);
// insert new entry or update if not deleted old entry yet
if (itr != mSkillStatus.end())
{
itr->second.pos = i;
itr->second.uState = SKILL_CHANGED;
}
else
mSkillStatus.insert(SkillStatusMap::value_type(id, SkillStatusData(i, SKILL_NEW)));
// apply skill bonuses
SetSkillTempBonus(i, 0);
SetSkillPermBonus(i, 0);
// temporary bonuses
AuraEffectList const& mModSkill = GetAuraEffectsByType(SPELL_AURA_MOD_SKILL);
for (AuraEffectList::const_iterator j = mModSkill.begin(); j != mModSkill.end(); ++j)
if ((*j)->GetMiscValue() == int32(id))
(*j)->HandleEffect(this, AURA_EFFECT_HANDLE_SKILL, true);
// permanent bonuses
AuraEffectList const& mModSkillTalent = GetAuraEffectsByType(SPELL_AURA_MOD_SKILL_TALENT);
for (AuraEffectList::const_iterator j = mModSkillTalent.begin(); j != mModSkillTalent.end(); ++j)
if ((*j)->GetMiscValue() == int32(id))
(*j)->HandleEffect(this, AURA_EFFECT_HANDLE_SKILL, true);
// Learn all spells for skill
LearnSkillRewardedSpells(id, newVal);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL, id);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL, id);
return;
}
}
}
}
bool Player::HasSkill(uint32 skill) const
{
if (!skill)
return false;
SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
return (itr != mSkillStatus.end() && itr->second.uState != SKILL_DELETED);
}
uint16 Player::GetSkillStep(uint32 skill) const
{
if (!skill)
return 0;
SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return 0;
return GetSkillStepByPos(itr->second.pos);
}
uint16 Player::GetSkillValue(uint32 skill) const
{
if (!skill)
return 0;
SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return 0;
int32 result = int32(GetSkillRankByPos(itr->second.pos));
result += int32(GetSkillTempBonusByPos(itr->second.pos));
result += int32(GetSkillPermBonusByPos(itr->second.pos));
return result < 0 ? 0 : result;
}
uint16 Player::GetMaxSkillValue(uint32 skill) const
{
if (!skill)
return 0;
SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return 0;
int32 result = int32(GetSkillMaxRankByPos(itr->second.pos));
result += int32(GetSkillTempBonusByPos(itr->second.pos));
result += int32(GetSkillPermBonusByPos(itr->second.pos));
return result < 0 ? 0 : result;
}
uint16 Player::GetPureMaxSkillValue(uint32 skill) const
{
if (!skill)
return 0;
SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return 0;
return GetSkillMaxRankByPos(itr->second.pos);
}
uint16 Player::GetBaseSkillValue(uint32 skill) const
{
if (!skill)
return 0;
SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return 0;
int32 result = int32(GetSkillRankByPos(itr->second.pos));
result += int32(GetSkillPermBonusByPos(itr->second.pos));
return result < 0 ? 0 : result;
}
uint16 Player::GetPureSkillValue(uint32 skill) const
{
if (!skill)
return 0;
SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return 0;
return GetSkillRankByPos(itr->second.pos);
}
int16 Player::GetSkillPermBonusValue(uint32 skill) const
{
if (!skill)
return 0;
SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return 0;
return GetSkillPermBonusByPos(itr->second.pos);
}
int16 Player::GetSkillTempBonusValue(uint32 skill) const
{
if (!skill)
return 0;
SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return 0;
return GetSkillTempBonusByPos(itr->second.pos);
}
void Player::SendActionButtons(uint32 state) const
{
WorldPacket data(SMSG_ACTION_BUTTONS, 1+(MAX_ACTION_BUTTONS*4));
data << uint8(state);
/*
state can be 0, 1, 2
0 - Sends initial action buttons, client does not validate if we have the spell or not
1 - Used used after spec swaps, client validates if a spell is known.
2 - Clears the action bars client sided. This is sent during spec swap before unlearning and before sending the new buttons
*/
if (state != 2)
{
for (uint8 button = 0; button < MAX_ACTION_BUTTONS; ++button)
{
ActionButtonList::const_iterator itr = m_actionButtons.find(button);
if (itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
data << uint32(itr->second.packedData);
else
data << uint32(0);
}
}
SendDirectMessage(&data);
}
bool Player::IsActionButtonDataValid(uint8 button, uint32 action, uint8 type) const
{
if (button >= MAX_ACTION_BUTTONS)
{
TC_LOG_ERROR("entities.player", "Player::IsActionButtonDataValid: Action {} not added into button {} for player {} ({}): button must be < {}",
action, button, GetName(), GetGUID().ToString(), MAX_ACTION_BUTTONS);
return false;
}
if (action >= MAX_ACTION_BUTTON_ACTION_VALUE)
{
TC_LOG_ERROR("entities.player", "Player::IsActionButtonDataValid: Action {} not added into button {} for player {} ({}): action must be < {}",
action, button, GetName(), GetGUID().ToString(), MAX_ACTION_BUTTON_ACTION_VALUE);
return false;
}
switch (type)
{
case ACTION_BUTTON_SPELL:
if (!sSpellMgr->GetSpellInfo(action))
{
TC_LOG_DEBUG("entities.player", "Player::IsActionButtonDataValid: Spell action {} not added into button {} for player {} ({}): spell does not exist. This can be due to a character imported from a different expansion",
action, button, GetName(), GetGUID().ToString());
return false;
}
if (!HasSpell(action))
{
TC_LOG_DEBUG("entities.player", "Player::IsActionButtonDataValid: Spell action {} not added into button {} for player {} ({}): player does not known this spell, this can be due to a player changing their talents",
action, button, GetName(), GetGUID().ToString());
return false;
}
break;
case ACTION_BUTTON_ITEM:
if (!sObjectMgr->GetItemTemplate(action))
{
TC_LOG_ERROR("entities.player", "Player::IsActionButtonDataValid: Item action {} not added into button {} for player {} ({}): item not exist",
action, button, GetName(), GetGUID().ToString());
return false;
}
break;
case ACTION_BUTTON_C:
case ACTION_BUTTON_CMACRO:
case ACTION_BUTTON_MACRO:
case ACTION_BUTTON_EQSET:
break;
default:
TC_LOG_ERROR("entities.player", "Player::IsActionButtonDataValid: Unknown action type {}", type);
return false; // other cases not checked at this moment
}
return true;
}
ActionButton* Player::addActionButton(uint8 button, uint32 action, uint8 type)
{
if (!IsActionButtonDataValid(button, action, type))
return nullptr;
// it create new button (NEW state) if need or return existing
ActionButton& ab = m_actionButtons[button];
// set data and update to CHANGED if not NEW
ab.SetActionAndType(action, ActionButtonType(type));
TC_LOG_DEBUG("entities.player", "Player::AddActionButton: Player '{}' ({}) added action '{}' (type {}) to button '{}'",
GetName(), GetGUID().ToString(), action, type, button);
return &ab;
}
void Player::removeActionButton(uint8 button)
{
ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
if (buttonItr == m_actionButtons.end() || buttonItr->second.uState == ACTIONBUTTON_DELETED)
return;
if (buttonItr->second.uState == ACTIONBUTTON_NEW)
m_actionButtons.erase(buttonItr); // new and not saved
else
buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
TC_LOG_DEBUG("entities.player", "Player::RemoveActionButton: Player '{}' ({}) removed action button '{}'",
GetName(), GetGUID().ToString(), button);
}
ActionButton const* Player::GetActionButton(uint8 button)
{
ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
if (buttonItr == m_actionButtons.end() || buttonItr->second.uState == ACTIONBUTTON_DELETED)
return nullptr;
return &buttonItr->second;
}
bool Player::UpdatePosition(float x, float y, float z, float orientation, bool teleport)
{
if (!Unit::UpdatePosition(x, y, z, orientation, teleport))
return false;
//if (movementInfo.flags & MOVEMENTFLAG_MOVING)
// mover->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE);
//if (movementInfo.flags & MOVEMENTFLAG_TURNING)
// mover->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
//AURA_INTERRUPT_FLAG_JUMP not sure
// Update player zone if needed
if (m_needsZoneUpdate)
{
uint32 newZone, newArea;
GetZoneAndAreaId(newZone, newArea);
UpdateZone(newZone, newArea);
m_needsZoneUpdate = false;
}
// group update
if (GetGroup())
SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
CheckAreaExploreAndOutdoor();
return true;
}
void Player::SendMessageToSetInRange(WorldPacket const* data, float dist, bool self) const
{
if (self)
SendDirectMessage(data);
Trinity::MessageDistDeliverer notifier(this, data, dist);
Cell::VisitWorldObjects(this, notifier, dist);
}
void Player::SendMessageToSetInRange(WorldPacket const* data, float dist, bool self, bool own_team_only, bool required3dDist /*= false*/) const
{
if (self)
SendDirectMessage(data);
Trinity::MessageDistDeliverer notifier(this, data, dist, own_team_only, nullptr, required3dDist);
Cell::VisitWorldObjects(this, notifier, dist);
}
void Player::SendMessageToSet(WorldPacket const* data, Player const* skipped_rcvr) const
{
if (skipped_rcvr != this)
SendDirectMessage(data);
// we use World::GetMaxVisibleDistance() because i cannot see why not use a distance
// update: replaced by GetMap()->GetVisibilityDistance()
Trinity::MessageDistDeliverer notifier(this, data, GetVisibilityRange(), false, skipped_rcvr);
Cell::VisitWorldObjects(this, notifier, GetVisibilityRange());
}
void Player::SendDirectMessage(WorldPacket const* data) const
{
m_session->SendPacket(data);
}
void Player::SendCinematicStart(uint32 CinematicSequenceId) const
{
WorldPackets::Misc::TriggerCinematic packet;
packet.CinematicID = CinematicSequenceId;
SendDirectMessage(packet.Write());
if (CinematicSequencesEntry const* sequence = sCinematicSequencesStore.LookupEntry(CinematicSequenceId))
_cinematicMgr->SetActiveCinematicCamera(sequence->Camera[0]);
}
void Player::SendMovieStart(uint32 movieId)
{
SetMovie(movieId);
WorldPackets::Misc::TriggerMovie packet;
packet.MovieID = movieId;
SendDirectMessage(packet.Write());
}
void Player::CheckAreaExploreAndOutdoor()
{
if (!IsAlive())
return;
if (IsInFlight())
return;
if (sWorld->getBoolConfig(CONFIG_VMAP_INDOOR_CHECK) && !IsOutdoors())
RemoveAurasWithAttribute(SPELL_ATTR0_OUTDOORS_ONLY);
uint32 const areaId = GetAreaId();
if (!areaId)
return;
AreaTableEntry const* areaEntry = sAreaTableStore.LookupEntry(areaId);
if (!areaEntry)
{
TC_LOG_ERROR("entities.player", "Player '{}' ({}) discovered unknown area (x: {} y: {} z: {} map: {})",
GetName(), GetGUID().ToString(), GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId());
return;
}
uint32 offset = areaEntry->AreaBit / 32;
if (offset >= PLAYER_EXPLORED_ZONES_SIZE)
{
TC_LOG_ERROR("entities.player", "Player::CheckAreaExploreAndOutdoor: Wrong area flag {} in map data for (X: {} Y: {}) point to field PLAYER_EXPLORED_ZONES_1 + {} ( {} must be < {} ).",
areaEntry->AreaBit, GetPositionX(), GetPositionY(), offset, offset, PLAYER_EXPLORED_ZONES_SIZE);
return;
}
uint32 val = (uint32)(1 << (areaEntry->AreaBit % 32));
uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
if (!(currFields & val))
{
#ifdef ELUNA
if (Eluna* e = GetEluna())
e->OnDiscoverArea(this, GetAreaId());
#endif
SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA, GetAreaId());
if (areaEntry->ExplorationLevel > 0)
{
if (IsMaxLevel())
{
SendExplorationExperience(areaId, 0);
}
else
{
int32 diff = int32(GetLevel()) - areaEntry->ExplorationLevel;
uint32 XP;
if (diff < -5)
{
XP = uint32(sObjectMgr->GetBaseXP(GetLevel()+5)*sWorld->getRate(RATE_XP_EXPLORE));
}
else if (diff > 5)
{
int32 exploration_percent = 100 - ((diff - 5) * 5);
if (exploration_percent < 0)
exploration_percent = 0;
XP = uint32(sObjectMgr->GetBaseXP(areaEntry->ExplorationLevel)*exploration_percent/100*sWorld->getRate(RATE_XP_EXPLORE));
}
else
{
XP = uint32(sObjectMgr->GetBaseXP(areaEntry->ExplorationLevel)*sWorld->getRate(RATE_XP_EXPLORE));
}
if (sWorld->getIntConfig(CONFIG_MIN_DISCOVERED_SCALED_XP_RATIO))
{
uint32 minScaledXP = uint32(sObjectMgr->GetBaseXP(areaEntry->ExplorationLevel)*sWorld->getRate(RATE_XP_EXPLORE)) * sWorld->getIntConfig(CONFIG_MIN_DISCOVERED_SCALED_XP_RATIO) / 100;
XP = std::max(minScaledXP, XP);
}
GiveXP(XP, nullptr);
SendExplorationExperience(areaId, XP);
}
TC_LOG_DEBUG("entities.player", "Player '{}' ({}) discovered a new area: {}", GetName(),GetGUID().ToString(), areaId);
}
}
}
uint32 Player::TeamForRace(uint8 race)
{
if (ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race))
{
switch (rEntry->BaseLanguage)
{
case 1: return HORDE;
case 7: return ALLIANCE;
}
TC_LOG_ERROR("entities.player", "Race ({}) has wrong teamid ({}) in DBC: wrong DBC files?", uint32(race), rEntry->BaseLanguage);
}
else
TC_LOG_ERROR("entities.player", "Race ({}) not found in DBC: wrong DBC files?", uint32(race));
return ALLIANCE;
}
void Player::SetFactionForRace(uint8 race)
{
m_team = TeamForRace(race);
ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
SetFaction(rEntry ? rEntry->FactionID : 0);
}
ReputationRank Player::GetReputationRank(uint32 faction) const
{
FactionEntry const* factionEntry = sFactionStore.LookupEntry(faction);
return GetReputationMgr().GetRank(factionEntry);
}
// Calculate total reputation percent player gain with quest/creature level
int32 Player::CalculateReputationGain(ReputationSource source, uint32 creatureOrQuestLevel, int32 rep, int32 faction, bool noQuestBonus)
{
float percent = 100.0f;
float repMod = noQuestBonus ? 0.0f : float(GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN));
// faction specific auras only seem to apply to kills
if (source == REPUTATION_SOURCE_KILL)
repMod += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_FACTION_REPUTATION_GAIN, faction);
percent += rep > 0 ? repMod : -repMod;
float rate;
switch (source)
{
case REPUTATION_SOURCE_KILL:
rate = sWorld->getRate(RATE_REPUTATION_LOWLEVEL_KILL);
break;
case REPUTATION_SOURCE_QUEST:
case REPUTATION_SOURCE_DAILY_QUEST:
case REPUTATION_SOURCE_WEEKLY_QUEST:
case REPUTATION_SOURCE_MONTHLY_QUEST:
case REPUTATION_SOURCE_REPEATABLE_QUEST:
rate = sWorld->getRate(RATE_REPUTATION_LOWLEVEL_QUEST);
break;
case REPUTATION_SOURCE_SPELL:
default:
rate = 1.0f;
break;
}
if (rate != 1.0f && creatureOrQuestLevel <= Trinity::XP::GetGrayLevel(GetLevel()))
percent *= rate;
if (percent <= 0.0f)
return 0;
// Multiply result with the faction specific rate
if (RepRewardRate const* repData = sObjectMgr->GetRepRewardRate(faction))
{
float repRate = 0.0f;
switch (source)
{
case REPUTATION_SOURCE_KILL:
repRate = repData->creatureRate;
break;
case REPUTATION_SOURCE_QUEST:
repRate = repData->questRate;
break;
case REPUTATION_SOURCE_DAILY_QUEST:
repRate = repData->questDailyRate;
break;
case REPUTATION_SOURCE_WEEKLY_QUEST:
repRate = repData->questWeeklyRate;
break;
case REPUTATION_SOURCE_MONTHLY_QUEST:
repRate = repData->questMonthlyRate;
break;
case REPUTATION_SOURCE_REPEATABLE_QUEST:
repRate = repData->questRepeatableRate;
break;
case REPUTATION_SOURCE_SPELL:
repRate = repData->spellRate;
break;
}
// for custom, a rate of 0.0 will totally disable reputation gain for this faction/type
if (repRate <= 0.0f)
return 0;
percent *= repRate;
}
if (source != REPUTATION_SOURCE_SPELL && GetsRecruitAFriendBonus(false))
percent *= 1.0f + sWorld->getRate(RATE_REPUTATION_RECRUIT_A_FRIEND_BONUS);
return CalculatePct(rep, percent);
}
// Calculates how many reputation points player gains in victim's enemy factions
void Player::RewardReputation(Unit* victim, float rate)
{
if (!victim || victim->GetTypeId() == TYPEID_PLAYER)
return;
if (victim->ToCreature()->IsReputationGainDisabled())
return;
ReputationOnKillEntry const* Rep = sObjectMgr->GetReputationOnKilEntry(victim->ToCreature()->GetCreatureTemplate()->Entry);
if (!Rep)
return;
uint32 ChampioningFaction = 0;
if (GetChampioningFaction())
{
// support for: Championing - http://www.wowwiki.com/Championing
Map const* map = GetMap();
if (map->IsNonRaidDungeon())
if (LFGDungeonEntry const* dungeon = GetLFGDungeon(map->GetId(), map->GetDifficulty()))
if (dungeon->TargetLevel == 80)
ChampioningFaction = GetChampioningFaction();
}
uint32 team = GetTeam();
if (Rep->RepFaction1 && (!Rep->TeamDependent || team == ALLIANCE))
{
int32 donerep1 = CalculateReputationGain(REPUTATION_SOURCE_KILL, victim->GetLevel(), Rep->RepValue1, ChampioningFaction ? ChampioningFaction : Rep->RepFaction1);
donerep1 = int32(donerep1 * rate);
FactionEntry const* factionEntry1 = sFactionStore.LookupEntry(ChampioningFaction ? ChampioningFaction : Rep->RepFaction1);
uint32 current_reputation_rank1 = GetReputationMgr().GetRank(factionEntry1);
if (factionEntry1)
GetReputationMgr().ModifyReputation(factionEntry1, donerep1, current_reputation_rank1 > Rep->ReputationMaxCap1);
}
if (Rep->RepFaction2 && (!Rep->TeamDependent || team == HORDE))
{
int32 donerep2 = CalculateReputationGain(REPUTATION_SOURCE_KILL, victim->GetLevel(), Rep->RepValue2, ChampioningFaction ? ChampioningFaction : Rep->RepFaction2);
donerep2 = int32(donerep2 * rate);
FactionEntry const* factionEntry2 = sFactionStore.LookupEntry(ChampioningFaction ? ChampioningFaction : Rep->RepFaction2);
uint32 current_reputation_rank2 = GetReputationMgr().GetRank(factionEntry2);
if (factionEntry2)
GetReputationMgr().ModifyReputation(factionEntry2, donerep2, current_reputation_rank2 > Rep->ReputationMaxCap2);
}
}
// Calculate how many reputation points player gain with the quest
void Player::RewardReputation(Quest const* quest)
{
for (uint8 i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
{
uint32 rewardFactionId = quest->RewardFactionId[i];
if (!rewardFactionId)
continue;
if (!GetReputationMgr().IsReputationAllowedForTeam(GetTeamId(), rewardFactionId))
continue;
int32 rep = 0;
bool noQuestBonus = false;
if (quest->RewardFactionValueIdOverride[i])
{
rep = quest->RewardFactionValueIdOverride[i] / 100;
noQuestBonus = true;
}
else
{
uint32 row = ((quest->RewardFactionValueId[i] < 0) ? 1 : 0) + 1;
if (QuestFactionRewEntry const* questFactionRewEntry = sQuestFactionRewardStore.LookupEntry(row))
{
uint32 field = abs(quest->RewardFactionValueId[i]);
rep = questFactionRewEntry->Difficulty[field];
}
}
if (!rep)
continue;
if (quest->IsDaily())
rep = CalculateReputationGain(REPUTATION_SOURCE_DAILY_QUEST, GetQuestLevel(quest), rep, rewardFactionId, noQuestBonus);
else if (quest->IsWeekly())
rep = CalculateReputationGain(REPUTATION_SOURCE_WEEKLY_QUEST, GetQuestLevel(quest), rep, rewardFactionId, noQuestBonus);
else if (quest->IsMonthly())
rep = CalculateReputationGain(REPUTATION_SOURCE_MONTHLY_QUEST, GetQuestLevel(quest), rep, rewardFactionId, noQuestBonus);
else if (quest->IsRepeatable())
rep = CalculateReputationGain(REPUTATION_SOURCE_REPEATABLE_QUEST, GetQuestLevel(quest), rep, rewardFactionId, noQuestBonus);
else
rep = CalculateReputationGain(REPUTATION_SOURCE_QUEST, GetQuestLevel(quest), rep, rewardFactionId, noQuestBonus);
if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(rewardFactionId))
GetReputationMgr().ModifyReputation(factionEntry, rep);
}
}
void Player::UpdateHonorFields()
{
/// called when rewarding honor and at each save
time_t now = GameTime::GetGameTime();
time_t today = GameTime::GetGameTime() / DAY * DAY;
if (m_lastHonorUpdateTime < today)
{
time_t yesterday = today - DAY;
uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
// update yesterday's contribution
if (m_lastHonorUpdateTime >= yesterday)
{
SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
// this is the first update today, reset today's contribution
SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0, kills_today));
}
else
{
// no honor/kills yesterday or today, reset
SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
SetUInt32Value(PLAYER_FIELD_KILLS, 0);
}
}
m_lastHonorUpdateTime = now;
}
///Calculate the amount of honor gained based on the victim
///and the size of the group for which the honor is divided
///An exact honor value can also be given (overriding the calcs)
bool Player::RewardHonor(Unit* victim, uint32 groupsize, int32 honor, bool pvptoken)
{
// do not reward honor in arenas, but enable onkill spellproc
if (InArena())
{
if (!victim || victim == this || victim->GetTypeId() != TYPEID_PLAYER)
return false;
if (GetBGTeam() == victim->ToPlayer()->GetBGTeam())
return false;
return true;
}
// 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
if (HasAura(SPELL_AURA_PLAYER_INACTIVE))
return false;
ObjectGuid victim_guid;
uint32 victim_rank = 0;
// need call before fields update to have chance move yesterday data to appropriate fields before today data change.
UpdateHonorFields();
// do not reward honor in arenas, but return true to enable onkill spellproc
if (InBattleground() && GetBattleground() && GetBattleground()->isArena())
return true;
// Promote to float for calculations
float honor_f = (float)honor;
if (honor_f <= 0)
{
if (!victim || victim == this || victim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
return false;
victim_guid = victim->GetGUID();
if (Player* plrVictim = victim->ToPlayer())
{
if (GetTeam() == plrVictim->GetTeam() && !sWorld->IsFFAPvPRealm())
return false;
uint8 k_level = GetLevel();
uint8 k_grey = Trinity::XP::GetGrayLevel(k_level);
uint8 v_level = victim->GetLevel();
if (v_level <= k_grey)
return false;
// PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
// [0] Just name
// [1..14] Alliance honor titles and player name
// [15..28] Horde honor titles and player name
// [29..38] Other title and player name
// [39+] Nothing
uint32 victim_title = victim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
// Get Killer titles, CharTitlesEntry::MaskID
// Ranks:
// title[1..14] -> rank[5..18]
// title[15..28] -> rank[5..18]
// title[other] -> 0
if (victim_title == 0)
victim_guid.Clear(); // Don't show HK: <rank> message, only log.
else if (victim_title < 15)
victim_rank = victim_title + 4;
else if (victim_title < 29)
victim_rank = victim_title - 14 + 4;
else
victim_guid.Clear(); // Don't show HK: <rank> message, only log.
honor_f = std::ceil(Trinity::Honor::hk_honor_at_level_f(k_level) * (v_level - k_grey) / (k_level - k_grey));
// count the number of playerkills in one day
ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
// and those in a lifetime
ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORABLE_KILLS, 1, true);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS, victim->GetClass());
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_RACE, victim->GetRace());
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL_AT_AREA, GetAreaId());
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL, 1, 0, victim);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL, 1, 0, victim);
}
else
{
if (!victim->ToCreature()->IsRacialLeader())
return false;
honor_f = 100.0f; // ??? need more info
victim_rank = 19; // HK: Leader
}
}
if (victim != nullptr)
{
if (groupsize > 1)
honor_f /= groupsize;
// apply honor multiplier from aura (not stacking-get highest)
AddPct(honor_f, GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HONOR_GAIN_PCT));
}
honor_f *= sWorld->getRate(RATE_HONOR);
// Back to int now
honor = int32(honor_f);
// honor - for show honor points in log
// victim_guid - for show victim name in log
// victim_rank [1..4] HK: <dishonored rank>
// victim_rank [5..19] HK: <alliance\horde rank>
// victim_rank [0, 20+] HK: <>
WorldPacket data(SMSG_PVP_CREDIT, 4+8+4);
data << uint32(honor);
data << victim_guid;
data << uint32(victim_rank);
SendDirectMessage(&data);
// add honor points
ModifyHonorPoints(honor);
ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, honor, true);
if (InBattleground() && honor > 0)
{
if (Battleground* bg = GetBattleground())
{
bg->UpdatePlayerScore(this, SCORE_BONUS_HONOR, honor, false); //false: prevent looping
}
}
if (sWorld->getBoolConfig(CONFIG_PVP_TOKEN_ENABLE) && pvptoken)
{
if (!victim || victim == this || victim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
return true;
if (victim->GetTypeId() == TYPEID_PLAYER)
{
// Check if allowed to receive it in current map
uint8 MapType = sWorld->getIntConfig(CONFIG_PVP_TOKEN_MAP_TYPE);
if ((MapType == 1 && !InBattleground() && !IsFFAPvP())
|| (MapType == 2 && !IsFFAPvP())
|| (MapType == 3 && !InBattleground()))
return true;
uint32 itemId = sWorld->getIntConfig(CONFIG_PVP_TOKEN_ID);
int32 count = sWorld->getIntConfig(CONFIG_PVP_TOKEN_COUNT);
if (AddItem(itemId, count))
ChatHandler(GetSession()).PSendSysMessage("You have been awarded a token for slaying another player.");
}
}
return true;
}
void Player::SetHonorPoints(uint32 value)
{
if (value > sWorld->getIntConfig(CONFIG_MAX_HONOR_POINTS))
value = sWorld->getIntConfig(CONFIG_MAX_HONOR_POINTS);
SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, value);
if (value)
AddKnownCurrency(ITEM_HONOR_POINTS_ID);
}
void Player::SetArenaPoints(uint32 value)
{
if (value > sWorld->getIntConfig(CONFIG_MAX_ARENA_POINTS))
value = sWorld->getIntConfig(CONFIG_MAX_ARENA_POINTS);
SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, value);
if (value)
AddKnownCurrency(ITEM_ARENA_POINTS_ID);
}
void Player::ModifyHonorPoints(int32 value, CharacterDatabaseTransaction trans)
{
int32 newValue = int32(GetHonorPoints()) + value;
if (newValue < 0)
newValue = 0;
SetHonorPoints(uint32(newValue));
if (trans)
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_HONOR_POINTS);
stmt->setUInt32(0, newValue);
stmt->setUInt32(1, GetGUID().GetCounter());
trans->Append(stmt);
}
}
void Player::ModifyArenaPoints(int32 value, CharacterDatabaseTransaction trans)
{
int32 newValue = int32(GetArenaPoints()) + value;
if (newValue < 0)
newValue = 0;
SetArenaPoints(uint32(newValue));
if (trans)
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_ARENA_POINTS);
stmt->setUInt32(0, newValue);
stmt->setUInt32(1, GetGUID().GetCounter());
trans->Append(stmt);
}
}
void Player::SetInArenaTeam(uint32 ArenaTeamId, uint8 slot, uint8 type)
{
SetArenaTeamInfoField(slot, ARENA_TEAM_ID, ArenaTeamId);
SetArenaTeamInfoField(slot, ARENA_TEAM_TYPE, type);
}
void Player::SetArenaTeamInfoField(uint8 slot, ArenaTeamInfoType type, uint32 value)
{
SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (slot * ARENA_TEAM_END) + type, value);
}
uint32 Player::GetZoneIdFromDB(ObjectGuid guid)
{
ObjectGuid::LowType guidLow = guid.GetCounter();
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_ZONE);
stmt->setUInt32(0, guidLow);
PreparedQueryResult result = CharacterDatabase.Query(stmt);
if (!result)
return 0;
Field* fields = result->Fetch();
uint32 zone = fields[0].GetUInt16();
if (!zone)
{
// stored zone is zero, use generic and slow zone detection
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_POSITION_XYZ);
stmt->setUInt32(0, guidLow);
result = CharacterDatabase.Query(stmt);
if (!result)
return 0;
fields = result->Fetch();
uint32 map = fields[0].GetUInt16();
float posx = fields[1].GetFloat();
float posy = fields[2].GetFloat();
float posz = fields[3].GetFloat();
if (!sMapStore.LookupEntry(map))
return 0;
zone = sMapMgr->GetZoneId(PHASEMASK_NORMAL, map, posx, posy, posz);
if (zone > 0)
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ZONE);
stmt->setUInt16(0, uint16(zone));
stmt->setUInt32(1, guidLow);
CharacterDatabase.Execute(stmt);
}
}
return zone;
}
void Player::UpdateArea(uint32 newArea)
{
#ifdef ELUNA
uint32 oldArea = m_areaUpdateId;
#endif
// FFA_PVP flags are area and not zone id dependent
// so apply them accordingly
m_areaUpdateId = newArea;
AreaTableEntry const* area = sAreaTableStore.LookupEntry(newArea);
bool oldFFAPvPArea = pvpInfo.IsInFFAPvPArea;
pvpInfo.IsInFFAPvPArea = area && (area->Flags & AREA_FLAG_ARENA);
UpdatePvPState(true);
// check if we were in ffa arena and we left
if (oldFFAPvPArea && !pvpInfo.IsInFFAPvPArea)
ValidateAttackersAndOwnTarget();
UpdateAreaDependentAuras(newArea);
// previously this was in UpdateZone (but after UpdateArea) so nothing will break
pvpInfo.IsInNoPvPArea = false;
if (area && area->IsSanctuary()) // in sanctuary
{
SetPvpFlag(UNIT_BYTE2_FLAG_SANCTUARY);
pvpInfo.IsInNoPvPArea = true;
if (!duel && GetCombatManager().HasPvPCombat())
CombatStopWithPets();
}
else
RemovePvpFlag(UNIT_BYTE2_FLAG_SANCTUARY);
uint32 const areaRestFlag = (GetTeam() == ALLIANCE) ? AREA_FLAG_REST_ZONE_ALLIANCE : AREA_FLAG_REST_ZONE_HORDE;
if (area && area->Flags & areaRestFlag)
SetRestFlag(REST_FLAG_IN_FACTION_AREA);
else
RemoveRestFlag(REST_FLAG_IN_FACTION_AREA);
#ifdef ELUNA
// We only want the hook to trigger when the old and new area is actually different
if (Eluna* e = GetEluna())
if(oldArea != newArea)
e->OnUpdateArea(this, oldArea, newArea);
#endif
}
void Player::UpdateZone(uint32 newZone, uint32 newArea)
{
if (!IsInWorld())
return;
uint32 const oldZone = m_zoneUpdateId;
m_zoneUpdateId = newZone;
m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
GetMap()->UpdatePlayerZoneStats(oldZone, newZone);
// call leave script hooks immedately (before updating flags)
if (oldZone != newZone)
{
sOutdoorPvPMgr->HandlePlayerLeaveZone(this, oldZone);
sBattlefieldMgr->HandlePlayerLeaveZone(this, oldZone);
}
// group update
if (GetGroup())
SetGroupUpdateFlag(GROUP_UPDATE_FULL);
// zone changed, so area changed as well, update it
UpdateArea(newArea);
AreaTableEntry const* zone = sAreaTableStore.LookupEntry(newZone);
if (!zone)
return;
if (sWorld->getBoolConfig(CONFIG_WEATHER))
GetMap()->GetOrGenerateZoneDefaultWeather(newZone);
GetMap()->SendZoneDynamicInfo(newZone, this);
// in PvP, any not controlled zone (except zone->FactionGroupMask == 6, default case)
// in PvE, only opposition team capital
switch (zone->FactionGroupMask)
{
case AREATEAM_ALLY:
pvpInfo.IsInHostileArea = GetTeam() != ALLIANCE && (sWorld->IsPvPRealm() || zone->Flags & AREA_FLAG_CAPITAL);
break;
case AREATEAM_HORDE:
pvpInfo.IsInHostileArea = GetTeam() != HORDE && (sWorld->IsPvPRealm() || zone->Flags & AREA_FLAG_CAPITAL);
break;
case AREATEAM_NONE:
// overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
pvpInfo.IsInHostileArea = sWorld->IsPvPRealm() || InBattleground() || zone->Flags & AREA_FLAG_WINTERGRASP;
break;
default: // 6 in fact
pvpInfo.IsInHostileArea = false;
break;
}
// Treat players having a quest flagging for PvP as always in hostile area
pvpInfo.IsHostile = pvpInfo.IsInHostileArea || HasPvPForcingQuest();
if (zone->Flags & AREA_FLAG_CAPITAL) // Is in a capital city
{
if (!pvpInfo.IsHostile || zone->IsSanctuary())
SetRestFlag(REST_FLAG_IN_CITY);
pvpInfo.IsInNoPvPArea = true;
}
else
RemoveRestFlag(REST_FLAG_IN_CITY); // Recently left a capital city
UpdatePvPState();
// remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
// if player resurrected at teleport this will be applied in resurrect code
if (IsAlive())
DestroyZoneLimitedItem(true, newZone);
// check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
AutoUnequipOffhandIfNeed();
// recent client version not send leave/join channel packets for built-in local channels
UpdateLocalChannels(newZone);
UpdateZoneDependentAuras(newZone);
// call enter script hooks after everyting else has processed
sScriptMgr->OnPlayerUpdateZone(this, newZone, newArea);
if (oldZone != newZone)
{
sOutdoorPvPMgr->HandlePlayerEnterZone(this, newZone);
sBattlefieldMgr->HandlePlayerEnterZone(this, newZone);
SendInitWorldStates(newZone, newArea); // only if really enters to new zone, not just area change, works strange...
if (Guild* guild = GetGuild())
guild->UpdateMemberData(this, GUILD_MEMBER_DATA_ZONEID, newZone);
}
}
//If players are too far away from the duel flag... they lose the duel
void Player::CheckDuelDistance(time_t currTime)
{
if (!duel)
return;
ObjectGuid duelFlagGUID = GetGuidValue(PLAYER_DUEL_ARBITER);
GameObject* obj = GetMap()->GetGameObject(duelFlagGUID);
if (!obj)
return;
if (!duel->OutOfBoundsTime)
{
if (!IsWithinDistInMap(obj, 50))
{
duel->OutOfBoundsTime = currTime + 10;
WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
SendDirectMessage(&data);
}
}
else
{
if (IsWithinDistInMap(obj, 40))
{
duel->OutOfBoundsTime = 0;
WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
SendDirectMessage(&data);
}
else if (currTime >= duel->OutOfBoundsTime)
DuelComplete(DUEL_FLED);
}
}
bool Player::IsOutdoorPvPActive() const
{
return IsAlive() && !HasInvisibilityAura() && !HasStealthAura() && IsPvP() && !HasUnitMovementFlag(MOVEMENTFLAG_FLYING) && !IsInFlight();
}
void Player::DuelComplete(DuelCompleteType type)
{
// duel not requested
if (!duel)
return;
// Check if DuelComplete() has been called already up in the stack and in that case don't do anything else here
if (duel->State == DUEL_STATE_COMPLETED)
return;
Player* opponent = duel->Opponent;
duel->State = DUEL_STATE_COMPLETED;
opponent->duel->State = DUEL_STATE_COMPLETED;
TC_LOG_DEBUG("entities.unit", "Player::DuelComplete: Player '{}' ({}), Opponent: '{}' ({})",
GetName(), GetGUID().ToString(), opponent->GetName(), opponent->GetGUID().ToString());
WorldPacket data(SMSG_DUEL_COMPLETE, (1));
data << uint8((type != DUEL_INTERRUPTED) ? 1 : 0);
SendDirectMessage(&data);
if (opponent->GetSession())
opponent->SendDirectMessage(&data);
if (type != DUEL_INTERRUPTED)
{
data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
data << uint8(type == DUEL_WON ? 0 : 1); // 0 = just won; 1 = fled
data << opponent->GetName();
data << GetName();
SendMessageToSet(&data, true);
}
sScriptMgr->OnPlayerDuelEnd(opponent, this, type);
switch (type)
{
case DUEL_FLED:
// if initiator and opponent are on the same team
// or initiator and opponent are not PvP enabled, forcibly stop attacking
if (GetTeam() == opponent->GetTeam())
{
AttackStop();
opponent->AttackStop();
}
else
{
if (!IsPvP())
AttackStop();
if (!opponent->IsPvP())
opponent->AttackStop();
}
break;
case DUEL_WON:
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL, 1);
opponent->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL, 1);
// Credit for quest Death's Challenge
if (GetClass() == CLASS_DEATH_KNIGHT && opponent->GetQuestStatus(12733) == QUEST_STATUS_INCOMPLETE)
opponent->CastSpell(opponent, 52994, true);
// Honor points after duel (the winner) - ImpConfig
if (uint32 amount = sWorld->getIntConfig(CONFIG_HONOR_AFTER_DUEL))
opponent->RewardHonor(nullptr, 1, amount);
break;
default:
break;
}
// Victory emote spell
if (type != DUEL_INTERRUPTED)
opponent->CastSpell(opponent, 52852, true);
//Remove Duel Flag object
GameObject* obj = GetMap()->GetGameObject(GetGuidValue(PLAYER_DUEL_ARBITER));
if (obj)
duel->Initiator->RemoveGameObject(obj, true);
/* remove auras */
AuraApplicationMap &itsAuras = opponent->GetAppliedAuras();
for (AuraApplicationMap::iterator i = itsAuras.begin(); i != itsAuras.end();)
{
Aura const* aura = i->second->GetBase();
if (!i->second->IsPositive() && aura->GetCasterGUID() == GetGUID() && aura->GetApplyTime() >= duel->StartTime)
opponent->RemoveAura(i);
else
++i;
}
AuraApplicationMap &myAuras = GetAppliedAuras();
for (AuraApplicationMap::iterator i = myAuras.begin(); i != myAuras.end();)
{
Aura const* aura = i->second->GetBase();
if (!i->second->IsPositive() && aura->GetCasterGUID() == opponent->GetGUID() && aura->GetApplyTime() >= duel->StartTime)
RemoveAura(i);
else
++i;
}
// cleanup combo points
if (GetComboTarget() && GetComboTarget()->GetControllingPlayer() == opponent)
ClearComboPoints();
if (opponent->GetComboTarget() && opponent->GetComboTarget()->GetControllingPlayer() == this)
opponent->ClearComboPoints();
//cleanups
SetGuidValue(PLAYER_DUEL_ARBITER, ObjectGuid::Empty);
SetUInt32Value(PLAYER_DUEL_TEAM, 0);
opponent->SetGuidValue(PLAYER_DUEL_ARBITER, ObjectGuid::Empty);
opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
opponent->duel.reset(nullptr);
duel.reset(nullptr);
}
//---------------------------------------------------------//
void Player::_ApplyItemMods(Item* item, uint8 slot, bool apply, bool updateItemAuras /*= true*/)
{
if (slot >= INVENTORY_SLOT_BAG_END || !item)
return;
ItemTemplate const* proto = item->GetTemplate();
if (!proto)
return;
// not apply/remove mods for broken item
if (item->IsBroken())
return;
TC_LOG_DEBUG("entities.player.items", "Player::_ApplyItemMods: Applying mods for item {}", item->GetGUID().ToString());
if (proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
CorrectMetaGemEnchants(slot, apply);
_ApplyItemBonuses(proto, slot, apply);
if (slot == EQUIPMENT_SLOT_RANGED)
_ApplyAmmoBonuses();
ApplyItemEquipSpell(item, apply);
if (updateItemAuras)
{
ApplyItemDependentAuras(item, apply);
WeaponAttackType const attackType = Player::GetAttackBySlot(slot);
if (attackType != MAX_ATTACK)
UpdateWeaponDependentAuras(attackType);
}
ApplyEnchantment(item, apply);
TC_LOG_DEBUG("entities.player.items", "Player::_ApplyItemMods: completed");
}
ScalingStatDistributionEntry const* Player::GetScalingStatDistributionFor(ItemTemplate const& itemTemplate) const
{
if (!itemTemplate.ScalingStatDistribution)
return nullptr;
return sScalingStatDistributionStore.LookupEntry(itemTemplate.ScalingStatDistribution);
}
ScalingStatValuesEntry const* Player::GetScalingStatValuesFor(ItemTemplate const& itemTemplate) const
{
if (!itemTemplate.ScalingStatValue)
return nullptr;
ScalingStatDistributionEntry const* ssd = GetScalingStatDistributionFor(itemTemplate);
if (!ssd)
return nullptr;
// req. check at equip, but allow use for extended range if range limit max level, set proper level
uint32 const ssd_level = std::min(uint32(GetLevel()), ssd->Maxlevel);
return sScalingStatValuesStore.LookupEntry(ssd_level);
}
void Player::_ApplyItemBonuses(ItemTemplate const* proto, uint8 slot, bool apply, bool only_level_scale /*= false*/)
{
if (slot >= INVENTORY_SLOT_BAG_END || !proto)
return;
ScalingStatDistributionEntry const* ssd = GetScalingStatDistributionFor(*proto);
ScalingStatValuesEntry const* ssv = GetScalingStatValuesFor(*proto);
if (only_level_scale && (!ssd || !ssv))
return;
for (uint8 i = 0; i < MAX_ITEM_PROTO_STATS; ++i)
{
uint32 statType = 0;
int32 val = 0;
// If set ScalingStatDistribution need get stats and values from it
if (ssd && ssv)
{
if (ssd->StatID[i] < 0)
continue;
statType = ssd->StatID[i];
val = (ssv->getssdMultiplier(proto->ScalingStatValue) * ssd->Bonus[i]) / 10000;
}
else
{
if (i >= proto->StatsCount)
continue;
statType = proto->ItemStat[i].ItemStatType;
val = proto->ItemStat[i].ItemStatValue;
}
if (val == 0)
continue;
switch (statType)
{
case ITEM_MOD_MANA:
HandleStatFlatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
break;
case ITEM_MOD_HEALTH: // modify HP
HandleStatFlatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
break;
case ITEM_MOD_AGILITY: // modify agility
HandleStatFlatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
UpdateStatBuffMod(STAT_AGILITY);
break;
case ITEM_MOD_STRENGTH: //modify strength
HandleStatFlatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
UpdateStatBuffMod(STAT_STRENGTH);
break;
case ITEM_MOD_INTELLECT: //modify intellect
HandleStatFlatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
UpdateStatBuffMod(STAT_INTELLECT);
break;
case ITEM_MOD_SPIRIT: //modify spirit
HandleStatFlatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
UpdateStatBuffMod(STAT_SPIRIT);
break;
case ITEM_MOD_STAMINA: //modify stamina
HandleStatFlatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
UpdateStatBuffMod(STAT_STAMINA);
break;
case ITEM_MOD_DEFENSE_SKILL_RATING:
ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
break;
case ITEM_MOD_DODGE_RATING:
ApplyRatingMod(CR_DODGE, int32(val), apply);
break;
case ITEM_MOD_PARRY_RATING:
ApplyRatingMod(CR_PARRY, int32(val), apply);
break;
case ITEM_MOD_BLOCK_RATING:
ApplyRatingMod(CR_BLOCK, int32(val), apply);
break;
case ITEM_MOD_HIT_MELEE_RATING:
ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
break;
case ITEM_MOD_HIT_RANGED_RATING:
ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
break;
case ITEM_MOD_HIT_SPELL_RATING:
ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
break;
case ITEM_MOD_CRIT_MELEE_RATING:
ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
break;
case ITEM_MOD_CRIT_RANGED_RATING:
ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
break;
case ITEM_MOD_CRIT_SPELL_RATING:
ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
break;
case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
break;
case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
break;
case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
break;
case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
break;
case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
break;
case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
break;
case ITEM_MOD_HASTE_MELEE_RATING:
ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
break;
case ITEM_MOD_HASTE_RANGED_RATING:
ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
break;
case ITEM_MOD_HASTE_SPELL_RATING:
ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
break;
case ITEM_MOD_HIT_RATING:
ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
break;
case ITEM_MOD_CRIT_RATING:
ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
break;
case ITEM_MOD_HIT_TAKEN_RATING:
ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
break;
case ITEM_MOD_CRIT_TAKEN_RATING:
ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
break;
case ITEM_MOD_RESILIENCE_RATING:
ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
break;
case ITEM_MOD_HASTE_RATING:
ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
break;
case ITEM_MOD_EXPERTISE_RATING:
ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
break;
case ITEM_MOD_ATTACK_POWER:
HandleStatFlatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), apply);
HandleStatFlatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
break;
case ITEM_MOD_RANGED_ATTACK_POWER:
HandleStatFlatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
break;
// case ITEM_MOD_FERAL_ATTACK_POWER:
// ApplyFeralAPBonus(int32(val), apply);
// break;
case ITEM_MOD_MANA_REGENERATION:
ApplyManaRegenBonus(int32(val), apply);
break;
case ITEM_MOD_ARMOR_PENETRATION_RATING:
ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
break;
case ITEM_MOD_SPELL_POWER:
ApplySpellPowerBonus(int32(val), apply);
break;
case ITEM_MOD_HEALTH_REGEN:
ApplyHealthRegenBonus(int32(val), apply);
break;
case ITEM_MOD_SPELL_PENETRATION:
ApplySpellPenetrationBonus(val, apply);
break;
case ITEM_MOD_BLOCK_VALUE:
HandleBaseModFlatValue(SHIELD_BLOCK_VALUE, float(val), apply);
break;
// deprecated item mods
case ITEM_MOD_SPELL_HEALING_DONE:
case ITEM_MOD_SPELL_DAMAGE_DONE:
break;
}
}
// Apply Spell Power from ScalingStatValue if set
if (ssv)
if (int32 spellbonus = ssv->getSpellBonus(proto->ScalingStatValue))
ApplySpellPowerBonus(spellbonus, apply);
// If set ScalingStatValue armor get it or use item armor
uint32 armor = proto->Armor;
if (ssv)
{
if (uint32 ssvarmor = ssv->getArmorMod(proto->ScalingStatValue))
armor = ssvarmor;
}
else if (armor && proto->ArmorDamageModifier)
armor -= uint32(proto->ArmorDamageModifier);
if (armor)
{
UnitModifierFlatType modType = TOTAL_VALUE;
if (proto->Class == ITEM_CLASS_ARMOR)
{
switch (proto->SubClass)
{
case ITEM_SUBCLASS_ARMOR_CLOTH:
case ITEM_SUBCLASS_ARMOR_LEATHER:
case ITEM_SUBCLASS_ARMOR_MAIL:
case ITEM_SUBCLASS_ARMOR_PLATE:
case ITEM_SUBCLASS_ARMOR_SHIELD:
modType = BASE_VALUE;
break;
}
}
HandleStatFlatModifier(UNIT_MOD_ARMOR, modType, float(armor), apply);
}
// Add armor bonus from ArmorDamageModifier if > 0
if (proto->ArmorDamageModifier > 0)
HandleStatFlatModifier(UNIT_MOD_ARMOR, TOTAL_VALUE, float(proto->ArmorDamageModifier), apply);
if (proto->Block)
HandleBaseModFlatValue(SHIELD_BLOCK_VALUE, float(proto->Block), apply);
if (proto->HolyRes)
HandleStatFlatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
if (proto->FireRes)
HandleStatFlatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
if (proto->NatureRes)
HandleStatFlatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
if (proto->FrostRes)
HandleStatFlatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
if (proto->ShadowRes)
HandleStatFlatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
if (proto->ArcaneRes)
HandleStatFlatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
WeaponAttackType attType = Player::GetAttackBySlot(slot);
if (attType != MAX_ATTACK)
_ApplyWeaponDamage(slot, proto, apply);
// Druids get feral AP bonus from weapon dps (also use DPS from ScalingStatValue)
if (GetClass() == CLASS_DRUID)
{
int32 dpsMod = 0;
int32 feral_bonus = 0;
if (ssv)
{
dpsMod = ssv->getDPSMod(proto->ScalingStatValue);
feral_bonus += ssv->getFeralBonus(proto->ScalingStatValue);
}
feral_bonus += proto->getFeralBonus(dpsMod);
if (feral_bonus)
ApplyFeralAPBonus(feral_bonus, apply);
}
}
void Player::_ApplyWeaponDamage(uint8 slot, ItemTemplate const* proto, bool apply)
{
WeaponAttackType attType = Player::GetAttackBySlot(slot);
if (!IsInFeralForm() && apply && !CanUseAttackType(attType))
return;
ScalingStatValuesEntry const* ssv = GetScalingStatValuesFor(*proto);
for (uint8 i = 0; i < MAX_ITEM_PROTO_DAMAGES; ++i)
{
float minDamage = proto->Damage[i].DamageMin;
float maxDamage = proto->Damage[i].DamageMax;
// If set dpsMod in ScalingStatValue use it for min (70% from average), max (130% from average) damage
if (ssv && i == 0) // scaling stats only for first damage
{
int32 extraDPS = ssv->getDPSMod(proto->ScalingStatValue);
if (extraDPS)
{
float average = extraDPS * proto->Delay / 1000.0f;
float mod = ssv->isTwoHand(proto->ScalingStatValue) ? 0.2f : 0.3f;
minDamage = (1.0f - mod) * average;
maxDamage = (1.0f + mod) * average;
}
}
if (apply)
{
if (minDamage > 0.f)
SetBaseWeaponDamage(attType, MINDAMAGE, minDamage, i);
if (maxDamage > 0.f)
SetBaseWeaponDamage(attType, MAXDAMAGE, maxDamage, i);
}
}
if (!apply)
{
for (uint8 i = 0; i < MAX_ITEM_PROTO_DAMAGES; ++i)
{
SetBaseWeaponDamage(attType, MINDAMAGE, 0.f, i);
SetBaseWeaponDamage(attType, MAXDAMAGE, 0.f, i);
}
if (attType == BASE_ATTACK)
{
SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, BASE_MINDAMAGE);
SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, BASE_MAXDAMAGE);
}
}
if (proto->Delay && !IsInFeralForm())
SetAttackTime(attType, apply ? proto->Delay : BASE_ATTACK_TIME);
// No need to modify any physical damage for ferals as it is calculated from stats only
if (IsInFeralForm())
return;
if (CanModifyStats() && (GetWeaponDamageRange(attType, MAXDAMAGE) || proto->Delay))
UpdateDamagePhysical(attType);
}
SpellSchoolMask Player::GetMeleeDamageSchoolMask(WeaponAttackType attackType /*= BASE_ATTACK*/, uint8 damageIndex /*= 0*/) const
{
if (Item const* weapon = GetWeaponForAttack(attackType, true))
return SpellSchoolMask(1 << weapon->GetTemplate()->Damage[damageIndex].DamageType);
return SPELL_SCHOOL_MASK_NORMAL;
}
void Player::CastAllObtainSpells()
{
for (uint8 slot = INVENTORY_SLOT_ITEM_START; slot < INVENTORY_SLOT_ITEM_END; ++slot)
if (Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot))
ApplyItemObtainSpells(item, true);
for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
{
Bag* bag = GetBagByPos(i);
if (!bag)
continue;
for (uint32 slot = 0; slot < bag->GetBagSize(); ++slot)
if (Item* item = bag->GetItemByPos(slot))
ApplyItemObtainSpells(item, true);
}
}
void Player::ApplyItemObtainSpells(Item* item, bool apply)
{
ItemTemplate const* itemTemplate = item->GetTemplate();
for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
{
if (itemTemplate->Spells[i].SpellTrigger != ITEM_SPELLTRIGGER_ON_NO_DELAY_USE) // On obtain trigger
continue;
int32 const spellId = itemTemplate->Spells[i].SpellId;
if (spellId <= 0)
continue;
if (apply)
{
if (!HasAura(spellId))
CastSpell(this, spellId, item);
}
else
RemoveAurasDueToSpell(spellId);
}
}
// this one rechecks weapon auras and stores them in BaseModGroup container
// needed for things like axe specialization applying only to axe weapons in case of dual-wield
void Player::UpdateWeaponDependentCritAuras(WeaponAttackType attackType)
{
BaseModGroup modGroup;
switch (attackType)
{
case BASE_ATTACK:
modGroup = CRIT_PERCENTAGE;
break;
case OFF_ATTACK:
modGroup = OFFHAND_CRIT_PERCENTAGE;
break;
case RANGED_ATTACK:
modGroup = RANGED_CRIT_PERCENTAGE;
break;
default:
ABORT();
break;
}
float amount = 0.0f;
amount += GetTotalAuraModifier(SPELL_AURA_MOD_WEAPON_CRIT_PERCENT, std::bind(&Unit::CheckAttackFitToAuraRequirement, this, attackType, std::placeholders::_1));
// these auras don't have item requirement (only Combat Expertise in 3.3.5a)
amount += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_PCT);
SetBaseModFlatValue(modGroup, amount);
}
void Player::UpdateAllWeaponDependentCritAuras()
{
for (uint8 i = BASE_ATTACK; i < MAX_ATTACK; ++i)
UpdateWeaponDependentCritAuras(WeaponAttackType(i));
}
void Player::UpdateWeaponDependentAuras(WeaponAttackType attackType)
{
UpdateWeaponDependentCritAuras(attackType);
UpdateDamageDoneMods(attackType);
UpdateDamagePctDoneMods(attackType);
}
void Player::ApplyItemDependentAuras(Item* item, bool apply)
{
if (apply)
{
PlayerSpellMap const& spells = GetSpellMap();
for (auto itr = spells.begin(); itr != spells.end(); ++itr)
{
if (itr->second.state == PLAYERSPELL_REMOVED || itr->second.disabled)
continue;
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(itr->first);
if (!spellInfo || !spellInfo->IsPassive() || spellInfo->EquippedItemClass < 0)
continue;
if (!HasAura(itr->first) && HasItemFitToSpellRequirements(spellInfo))
AddAura(itr->first, this); // no SMSG_SPELL_GO in sniff found
}
}
else
RemoveItemDependentAurasAndCasts(item);
}
bool Player::CheckAttackFitToAuraRequirement(WeaponAttackType attackType, AuraEffect const* aurEff) const
{
SpellInfo const* spellInfo = aurEff->GetSpellInfo();
if (spellInfo->EquippedItemClass == -1)
return true;
Item* item = GetWeaponForAttack(attackType, true);
if (!item || !item->IsFitToSpellRequirements(spellInfo))
return false;
return true;
}
void Player::ApplyItemEquipSpell(Item* item, bool apply, bool form_change)
{
if (!item)
return;
ItemTemplate const* proto = item->GetTemplate();
if (!proto)
return;
for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
{
_Spell const& spellData = proto->Spells[i];
// no spell
if (spellData.SpellId <= 0)
continue;
// wrong triggering type
if (apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
continue;
// check if it is valid spell
SpellInfo const* spellproto = sSpellMgr->GetSpellInfo(spellData.SpellId);
if (!spellproto)
continue;
ApplyEquipSpell(spellproto, item, apply, form_change);
}
}
void Player::ApplyEquipSpell(SpellInfo const* spellInfo, Item* item, bool apply, bool form_change)
{
if (apply)
{
// Cannot be used in this stance/form
if (spellInfo->CheckShapeshift(GetShapeshiftForm()) != SPELL_CAST_OK)
return;
if (form_change) // check aura active state from other form
{
AuraApplicationMapBounds range = GetAppliedAuras().equal_range(spellInfo->Id);
for (AuraApplicationMap::const_iterator itr = range.first; itr != range.second; ++itr)
if (!item || itr->second->GetBase()->GetCastItemGUID() == item->GetGUID())
return;
}
TC_LOG_DEBUG("entities.player", "Player::ApplyEquipSpell: Player '{}' ({}) cast {} equip spell (ID: {})",
GetName(), GetGUID().ToString(), (item ? "item" : "itemset"), spellInfo->Id);
CastSpell(this, spellInfo->Id, item);
}
else
{
if (form_change) // check aura compatibility
{
// Cannot be used in this stance/form
if (spellInfo->CheckShapeshift(GetShapeshiftForm()) == SPELL_CAST_OK)
return; // and remove only not compatible at form change
}
if (item)
RemoveAurasDueToItemSpell(spellInfo->Id, item->GetGUID()); // un-apply all spells, not only at-equipped
else
RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
}
}
void Player::UpdateEquipSpellsAtFormChange()
{
for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (m_items[i] && !m_items[i]->IsBroken() && CanUseAttackType(GetAttackBySlot(i)))
{
ApplyItemEquipSpell(m_items[i], false, true); // remove spells that not fit to form
ApplyItemEquipSpell(m_items[i], true, true); // add spells that fit form but not active
}
}
// item set bonuses not dependent from item broken state
for (size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
{
ItemSetEffect* eff = ItemSetEff[setindex];
if (!eff)
continue;
for (uint32 y = 0; y < MAX_ITEM_SET_SPELLS; ++y)
{
SpellInfo const* spellInfo = eff->spells[y];
if (!spellInfo)
continue;
ApplyEquipSpell(spellInfo, nullptr, false, true); // remove spells that not fit to form
ApplyEquipSpell(spellInfo, nullptr, true, true); // add spells that fit form but not active
}
}
}
void Player::CastItemCombatSpell(DamageInfo const& damageInfo)
{
Unit* target = damageInfo.GetVictim();
if (!target || !target->IsAlive() || target == this)
return;
for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
{
// If usable, try to cast item spell
if (Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
{
if (!item->IsBroken() && CanUseAttackType(damageInfo.GetAttackType()))
{
if (ItemTemplate const* proto = item->GetTemplate())
{
// Additional check for weapons
if (proto->Class == ITEM_CLASS_WEAPON)
{
// offhand item cannot proc from main hand hit etc
EquipmentSlots slot;
switch (damageInfo.GetAttackType())
{
case BASE_ATTACK:
slot = EQUIPMENT_SLOT_MAINHAND;
break;
case OFF_ATTACK:
slot = EQUIPMENT_SLOT_OFFHAND;
break;
case RANGED_ATTACK:
slot = EQUIPMENT_SLOT_RANGED;
break;
default:
slot = EQUIPMENT_SLOT_END;
break;
}
if (slot != i)
continue;
// Check if item is useable (forms or disarm)
if (damageInfo.GetAttackType() == BASE_ATTACK)
if (!IsUseEquipedWeapon(true) && !IsInFeralForm())
continue;
}
CastItemCombatSpell(damageInfo, item, proto);
}
}
}
}
}
void Player::CastItemCombatSpell(DamageInfo const& damageInfo, Item* item, ItemTemplate const* proto)
{
// Can do effect if any damage done to target
// for done procs allow normal + critical + absorbs by default
bool canTrigger = (damageInfo.GetHitMask() & (PROC_HIT_NORMAL | PROC_HIT_CRITICAL | PROC_HIT_ABSORB)) != 0;
if (canTrigger)
{
for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
{
_Spell const& spellData = proto->Spells[i];
// no spell
if (spellData.SpellId <= 0)
continue;
// wrong triggering type
if (spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
continue;
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellData.SpellId);
if (!spellInfo)
{
TC_LOG_ERROR("entities.player.items", "Player::CastItemCombatSpell: Player '{}' ({}) cast unknown item spell (ID: {})",
GetName(), GetGUID().ToString(), spellData.SpellId);
continue;
}
float chance = (float)spellInfo->ProcChance;
if (spellData.SpellPPMRate)
{
uint32 WeaponSpeed = GetAttackTime(damageInfo.GetAttackType());
chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate, spellInfo);
}
else if (chance > 100.0f)
chance = GetWeaponProcChance();
if (roll_chance_f(chance) && sScriptMgr->OnCastItemCombatSpell(this, damageInfo.GetVictim(), spellInfo, item))
CastSpell(damageInfo.GetVictim(), spellInfo->Id, item);
}
}
// item combat enchantments
for (uint8 e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
{
uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
SpellItemEnchantmentEntry const* pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if (!pEnchant)
continue;
for (uint8 s = 0; s < MAX_ITEM_ENCHANTMENT_EFFECTS; ++s)
{
if (pEnchant->Effect[s] != ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
continue;
SpellEnchantProcEntry const* entry = sSpellMgr->GetSpellEnchantProcEvent(enchant_id);
if (entry && entry->HitMask)
{
// Check hit/crit/dodge/parry requirement
if ((entry->HitMask & damageInfo.GetHitMask()) == 0)
continue;
}
else
{
// Can do effect if any damage done to target
// for done procs allow normal + critical + absorbs by default
if (!canTrigger)
continue;
}
// check if enchant procs only on white hits
if (entry && (entry->AttributesMask & ENCHANT_PROC_ATTR_WHITE_HIT) && damageInfo.GetSpellInfo())
continue;
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(pEnchant->EffectArg[s]);
if (!spellInfo)
{
TC_LOG_ERROR("entities.player.items", "Player::CastItemCombatSpell: Player '{}' ({}) cast unknown spell (EnchantID: {}, SpellID: {}), ignoring",
GetName(), GetGUID().ToString(), pEnchant->ID, pEnchant->EffectArg[s]);
continue;
}
float chance = pEnchant->EffectPointsMin[s] != 0 ? float(pEnchant->EffectPointsMin[s]) : GetWeaponProcChance();
if (entry)
{
if (entry->ProcsPerMinute)
chance = GetPPMProcChance(proto->Delay, entry->ProcsPerMinute, spellInfo);
else if (entry->Chance)
chance = entry->Chance;
}
// Apply spell mods
ApplySpellMod(pEnchant->EffectArg[s], SPELLMOD_CHANCE_OF_SUCCESS, chance);
// Shiv has 100% chance to apply the poison
if (FindCurrentSpellBySpellId(5938) && e_slot == TEMP_ENCHANTMENT_SLOT)
chance = 100.0f;
if (roll_chance_f(chance))
{
Unit* target = spellInfo->IsPositive() ? this : damageInfo.GetVictim();
CastSpellExtraArgs args(item);
// reduce effect values if enchant is limited
if (entry && (entry->AttributesMask & ENCHANT_PROC_ATTR_LIMIT_60) && target->GetLevel() > 60)
{
int32 const lvlDifference = target->GetLevel() - 60;
int32 const lvlPenaltyFactor = 4; // 4% lost effectiveness per level
int32 const effectPct = std::max(0, 100 - (lvlDifference * lvlPenaltyFactor));
for (SpellEffectInfo const& spellEffectInfo : spellInfo->GetEffects())
if (spellEffectInfo.IsEffect())
args.AddSpellMod(static_cast<SpellValueMod>(SPELLVALUE_BASE_POINT0 + AsUnderlyingType(spellEffectInfo.EffectIndex)), CalculatePct(spellEffectInfo.CalcValue(this), effectPct));
}
CastSpell(target, spellInfo->Id, args);
}
}
}
}
void Player::CastItemUseSpell(Item* item, SpellCastTargets const& targets, uint8 cast_count, uint32 glyphIndex)
{
ItemTemplate const* proto = item->GetTemplate();
// special learning case
if (proto->Spells[0].SpellId == 483 || proto->Spells[0].SpellId == 55884)
{
uint32 learn_spell_id = proto->Spells[0].SpellId;
uint32 learning_spell_id = proto->Spells[1].SpellId;
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(learn_spell_id);
if (!spellInfo)
{
TC_LOG_ERROR("entities.player", "Player::CastItemUseSpell: Item (Entry: {}) has wrong spell id {}, ignoring.", proto->ItemId, learn_spell_id);
SendEquipError(EQUIP_ERR_NONE, item, nullptr);
return;
}
Spell* spell = new Spell(this, spellInfo, TRIGGERED_NONE);
spell->m_fromClient = true;
spell->m_CastItem = item;
spell->m_cast_count = cast_count; //set count of casts
spell->SetSpellValue(SPELLVALUE_BASE_POINT0, learning_spell_id);
spell->prepare(targets);
return;
}
// item spells cast at use
for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
{
_Spell const& spellData = proto->Spells[i];
// no spell
if (spellData.SpellId <= 0)
continue;
// wrong triggering type
if (spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
continue;
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellData.SpellId);
if (!spellInfo)
{
TC_LOG_ERROR("entities.player", "Player::CastItemUseSpell: Item (Entry: {}) has wrong spell id {}, ignoring", proto->ItemId, spellData.SpellId);
continue;
}
Spell* spell = new Spell(this, spellInfo, TRIGGERED_NONE);
spell->m_fromClient = true;
spell->m_CastItem = item;
spell->m_cast_count = cast_count; // set count of casts
spell->m_glyphIndex = glyphIndex; // glyph index
spell->prepare(targets);
return;
}
// Item enchantments spells cast at use
for (uint8 e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
{
uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
SpellItemEnchantmentEntry const* pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if (!pEnchant)
continue;
for (uint8 s = 0; s < MAX_ITEM_ENCHANTMENT_EFFECTS; ++s)
{
if (pEnchant->Effect[s] != ITEM_ENCHANTMENT_TYPE_USE_SPELL)
continue;
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(pEnchant->EffectArg[s]);
if (!spellInfo)
{
TC_LOG_ERROR("entities.player", "Player::CastItemUseSpell: Enchant {}, cast unknown spell {}", pEnchant->ID, pEnchant->EffectArg[s]);
continue;
}
Spell* spell = new Spell(this, spellInfo, TRIGGERED_NONE);
spell->m_fromClient = true;
spell->m_CastItem = item;
spell->m_cast_count = cast_count; // set count of casts
spell->m_glyphIndex = glyphIndex; // glyph index
spell->prepare(targets);
return;
}
}
}
void Player::_RemoveAllItemMods()
{
TC_LOG_DEBUG("entities.player.items", "_RemoveAllItemMods start.");
for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (m_items[i])
{
ItemTemplate const* proto = m_items[i]->GetTemplate();
if (!proto)
continue;
// item set bonuses not dependent from item broken state
if (proto->ItemSet)
RemoveItemsSetItem(this, proto);
if (m_items[i]->IsBroken() || !CanUseAttackType(GetAttackBySlot(i)))
continue;
ApplyItemEquipSpell(m_items[i], false);
ApplyEnchantment(m_items[i], false);
}
}
for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (m_items[i])
{
if (m_items[i]->IsBroken() || !CanUseAttackType(GetAttackBySlot(i)))
continue;
ItemTemplate const* proto = m_items[i]->GetTemplate();
if (!proto)
continue;
ApplyItemDependentAuras(m_items[i], false);
_ApplyItemBonuses(proto, i, false);
if (i == EQUIPMENT_SLOT_RANGED)
_ApplyAmmoBonuses();
}
}
TC_LOG_DEBUG("entities.player.items", "_RemoveAllItemMods complete.");
}
void Player::_ApplyAllItemMods()
{
TC_LOG_DEBUG("entities.player.items", "_ApplyAllItemMods start.");
for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (m_items[i])
{
if (m_items[i]->IsBroken() || !CanUseAttackType(GetAttackBySlot(i)))
continue;
ItemTemplate const* proto = m_items[i]->GetTemplate();
if (!proto)
continue;
ApplyItemDependentAuras(m_items[i], true);
_ApplyItemBonuses(proto, i, true);
WeaponAttackType const attackType = Player::GetAttackBySlot(i);
if (attackType != MAX_ATTACK)
UpdateWeaponDependentAuras(attackType);
if (i == EQUIPMENT_SLOT_RANGED)
_ApplyAmmoBonuses();
}
}
for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (m_items[i])
{
ItemTemplate const* proto = m_items[i]->GetTemplate();
if (!proto)
continue;
// item set bonuses not dependent from item broken state
if (proto->ItemSet)
AddItemsSetItem(this, m_items[i]);
if (m_items[i]->IsBroken() || !CanUseAttackType(GetAttackBySlot(i)))
continue;
ApplyItemEquipSpell(m_items[i], true);
ApplyEnchantment(m_items[i], true);
}
}
TC_LOG_DEBUG("entities.player.items", "_ApplyAllItemMods complete.");
}
void Player::_ApplyAllLevelScaleItemMods(bool apply)
{
for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (m_items[i])
{
if (m_items[i]->IsBroken() || !CanUseAttackType(GetAttackBySlot(i)))
continue;
ItemTemplate const* proto = m_items[i]->GetTemplate();
if (!proto)
continue;
_ApplyItemBonuses(proto, i, apply, true);
}
}
}
void Player::_ApplyAmmoBonuses()
{
// check ammo
uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
if (!ammo_id)
return;
float currentAmmoDPS;
ItemTemplate const* ammo_proto = sObjectMgr->GetItemTemplate(ammo_id);
if (!ammo_proto || ammo_proto->Class != ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
currentAmmoDPS = 0.0f;
else
currentAmmoDPS = (ammo_proto->Damage[0].DamageMin + ammo_proto->Damage[0].DamageMax) / 2;
if (currentAmmoDPS == GetAmmoDPS())
return;
m_ammoDPS = currentAmmoDPS;
if (CanModifyStats())
UpdateDamagePhysical(RANGED_ATTACK);
}
bool Player::CheckAmmoCompatibility(ItemTemplate const* ammo_proto) const
{
if (!ammo_proto)
return false;
// check ranged weapon
Item* weapon = GetWeaponForAttack(RANGED_ATTACK);
if (!weapon || weapon->IsBroken())
return false;
ItemTemplate const* weapon_proto = weapon->GetTemplate();
if (!weapon_proto || weapon_proto->Class != ITEM_CLASS_WEAPON)
return false;
// check ammo ws. weapon compatibility
switch (weapon_proto->SubClass)
{
case ITEM_SUBCLASS_WEAPON_BOW:
case ITEM_SUBCLASS_WEAPON_CROSSBOW:
if (ammo_proto->SubClass != ITEM_SUBCLASS_ARROW)
return false;
break;
case ITEM_SUBCLASS_WEAPON_GUN:
if (ammo_proto->SubClass != ITEM_SUBCLASS_BULLET)
return false;
break;
default:
return false;
}
return true;
}
/* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
Called by remove insignia spell effect */
void Player::RemovedInsignia(Player* looterPlr)
{
// If player is not in battleground and not in worldpvpzone
if (!GetBattlegroundId() && !IsInWorldPvpZone())
return;
// If not released spirit, do it !
if (m_deathTimer > 0)
{
m_deathTimer = 0;
BuildPlayerRepop();
RepopAtGraveyard();
}
_corpseLocation.WorldRelocate();
// We have to convert player corpse to bones, not to be able to resurrect there
// SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
Corpse* bones = GetMap()->ConvertCorpseToBones(GetGUID(), true);
if (!bones)
return;
// Now we must make bones lootable, and send player loot
bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
// We store the level of our player in the gold field
// We retrieve this information at Player::SendLoot()
bones->loot.gold = GetLevel();
bones->lootRecipient = looterPlr;
looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
}
void Player::SendLootRelease(ObjectGuid guid) const
{
WorldPacket data(SMSG_LOOT_RELEASE_RESPONSE, (8+1));
data << guid << uint8(1);
SendDirectMessage(&data);
}
void Player::SendLoot(ObjectGuid guid, LootType loot_type)
{
ObjectGuid currentLootGuid = GetLootGUID();
if (!currentLootGuid.IsEmpty())
m_session->DoLootRelease(currentLootGuid);
Loot* loot;
PermissionTypes permission = ALL_PERMISSION;
TC_LOG_DEBUG("loot", "Player::SendLoot: Player: '{}' ({}), Loot: {}",
GetName(), GetGUID().ToString(), guid.ToString());
if (guid.IsGameObject())
{
GameObject* go = GetMap()->GetGameObject(guid);
auto shouldLootRelease = [this](GameObject* go, LootType lootType) -> bool
{
// not check distance for GO in case owned GO (fishing bobber case, for example)
// And permit out of range GO with no owner in case fishing hole
if (!go)
return true;
if (lootType == LOOT_SKINNING)
{
// Disarm Trap
if (!go->IsWithinDistInMap(this, 20.f))
return true;
}
else
{
if (lootType != LOOT_FISHINGHOLE && ((lootType != LOOT_FISHING && lootType != LOOT_FISHING_JUNK) || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this))
return true;
if (lootType == LOOT_CORPSE && go->GetRespawnTime() && go->isSpawnedByDefault())
return true;
}
return false;
};
if (shouldLootRelease(go, loot_type))
{
SendLootRelease(guid);
return;
}
loot = &go->loot;
// loot was generated and respawntime has passed since then, allow to recreate loot
// to avoid bugs, this rule covers spawned gameobjects only
// Don't allow to regenerate chest loot inside instances and raids, to avoid exploits with duplicate boss loot being given for some encounters
if (go->isSpawnedByDefault() && go->getLootState() == GO_ACTIVATED && !go->loot.isLooted() && !go->GetMap()->Instanceable() && go->GetLootGenerationTime() + go->GetRespawnDelay() < GameTime::GetGameTime())
go->SetLootState(GO_READY);
if (go->getLootState() == GO_READY)
{
uint32 lootid = go->GetGOInfo()->GetLootId();
if (Battleground* bg = GetBattleground())
if (!bg->CanActivateGO(go->GetEntry(), GetTeam()))
{
SendLootRelease(guid);
return;
}
if (lootid)
{
loot->clear();
Group* group = GetGroup();
bool groupRules = (group && go->GetGOInfo()->type == GAMEOBJECT_TYPE_CHEST && go->GetGOInfo()->chest.groupLootRules);
// check current RR player and get next if necessary
if (groupRules)
group->UpdateLooterGuid(go, true);
loot->FillLoot(lootid, LootTemplates_Gameobject, this, !groupRules, false, go->GetLootMode());
go->SetLootGenerationTime();
// get next RR player (for next loot)
if (groupRules && !go->loot.empty())
group->UpdateLooterGuid(go);
}
if (go->GetLootMode() > 0)
if (GameObjectTemplateAddon const* addon = go->GetTemplateAddon())
loot->generateMoneyLoot(addon->Mingold, addon->Maxgold);
if (loot_type == LOOT_FISHING)
go->getFishLoot(loot, this);
else if (loot_type == LOOT_FISHING_JUNK)
go->getFishLootJunk(loot, this);
if (go->GetGOInfo()->type == GAMEOBJECT_TYPE_CHEST && go->GetGOInfo()->chest.groupLootRules)
{
if (Group* group = GetGroup())
{
switch (group->GetLootMethod())
{
case GROUP_LOOT:
// GroupLoot: rolls items over threshold. Items with quality < threshold, round robin
group->GroupLoot(loot, go);
break;
case NEED_BEFORE_GREED:
group->NeedBeforeGreed(loot, go);
break;
case MASTER_LOOT:
group->MasterLoot(loot, go);
break;
default:
break;
}
}
}
go->SetLootState(GO_ACTIVATED, this);
}
if (go->getLootState() == GO_ACTIVATED)
{
if (Group* group = GetGroup())
{
switch (group->GetLootMethod())
{
case MASTER_LOOT:
permission = group->GetMasterLooterGuid() == GetGUID() ? MASTER_PERMISSION : RESTRICTED_PERMISSION;
break;
case FREE_FOR_ALL:
permission = ALL_PERMISSION;
break;
case ROUND_ROBIN:
permission = ROUND_ROBIN_PERMISSION;
break;
default:
permission = GROUP_PERMISSION;
break;
}
}
else
permission = ALL_PERMISSION;
}
}
else if (guid.IsItem())
{
Item* item = GetItemByGuid(guid);
if (!item)
{
SendLootRelease(guid);
return;
}
permission = OWNER_PERMISSION;
loot = &item->loot;
// Store container id
loot->containerID = item->GetGUID().GetCounter();
// If item doesn't already have loot, attempt to load it. If that
// fails then this is first time opening, generate loot
if (!item->m_lootGenerated && !sLootItemStorage->LoadStoredLoot(item, this))
{
item->m_lootGenerated = true;
loot->clear();
switch (loot_type)
{
case LOOT_DISENCHANTING:
loot->FillLoot(item->GetTemplate()->DisenchantID, LootTemplates_Disenchant, this, true);
break;
case LOOT_PROSPECTING:
loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this, true);
break;
case LOOT_MILLING:
loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this, true);
break;
default:
loot->generateMoneyLoot(item->GetTemplate()->MinMoneyLoot, item->GetTemplate()->MaxMoneyLoot);
loot->FillLoot(item->GetEntry(), LootTemplates_Item, this, true, loot->gold != 0);
// Force save the loot and money items that were just rolled
// Also saves the container item ID in Loot struct (not to DB)
if (loot->gold > 0 || loot->unlootedCount > 0)
sLootItemStorage->AddNewStoredLoot(loot, this);
break;
}
}
}
else if (guid.IsCorpse()) // remove insignia
{
Corpse* bones = ObjectAccessor::GetCorpse(*this, guid);
if (!bones || !(loot_type == LOOT_CORPSE || loot_type == LOOT_INSIGNIA) || bones->GetType() != CORPSE_BONES)
{
SendLootRelease(guid);
return;
}
loot = &bones->loot;
if (loot->loot_type == LOOT_NONE)
{
uint32 pLevel = bones->loot.gold;
bones->loot.clear();
// For AV Achievement
if (Battleground* bg = GetBattleground())
{
if (bg->GetTypeID(true) == BATTLEGROUND_AV)
loot->FillLoot(PLAYER_CORPSE_LOOT_ENTRY, LootTemplates_Creature, this, true);
}
// For wintergrasp Quests
else if (GetZoneId() == AREA_WINTERGRASP)
loot->FillLoot(PLAYER_CORPSE_LOOT_ENTRY, LootTemplates_Creature, this, true);
// It may need a better formula
// Now it works like this: lvl10: ~6copper, lvl70: ~9silver
bones->loot.gold = uint32(urand(50, 150) * 0.016f * std::pow(float(pLevel) / 5.76f, 2.5f) * sWorld->getRate(RATE_DROP_MONEY));
}
if (bones->lootRecipient != this)
permission = NONE_PERMISSION;
else
permission = OWNER_PERMISSION;
}
else
{
Creature* creature = GetMap()->GetCreature(guid);
// must be in range and creature must be alive for pickpocket and must be dead for another loot
if (!creature || creature->IsAlive() != (loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this, INTERACTION_DISTANCE))
{
SendLootRelease(guid);
return;
}
if (loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
{
SendLootRelease(guid);
return;
}
loot = &creature->loot;
if (loot_type == LOOT_PICKPOCKETING)
{
if (loot->loot_type != LOOT_PICKPOCKETING)
{
if (creature->CanGeneratePickPocketLoot())
{
creature->StartPickPocketRefillTimer();
loot->clear();
if (uint32 lootid = creature->GetCreatureTemplate()->pickpocketLootId)
loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, true);
// Generate extra money for pick pocket loot
const uint32 a = urand(0, creature->GetLevel() / 2);
const uint32 b = urand(0, GetLevel() / 2);
loot->gold = uint32(10 * (a + b) * sWorld->getRate(RATE_DROP_MONEY));
permission = OWNER_PERMISSION;
}
else
{
SendLootError(guid, LOOT_ERROR_ALREADY_PICKPOCKETED);
return;
}
} // else - still has pickpocket loot generated & not fully taken
}
else
{
// exploit fix
if (!creature->HasDynamicFlag(UNIT_DYNFLAG_LOOTABLE))
{
SendLootError(guid, LOOT_ERROR_DIDNT_KILL);
return;
}
// the player whose group may loot the corpse
Player* recipient = creature->GetLootRecipient();
Group* recipientGroup = creature->GetLootRecipientGroup();
if (!recipient && !recipientGroup)
{
SendLootError(guid, LOOT_ERROR_DIDNT_KILL);
return;
}
if (loot->loot_type == LOOT_NONE)
{
// for creature, loot is filled when creature is killed.
if (Group* group = creature->GetLootRecipientGroup())
{
switch (group->GetLootMethod())
{
case GROUP_LOOT:
// GroupLoot: rolls items over threshold. Items with quality < threshold, round robin
group->GroupLoot(loot, creature);
break;
case NEED_BEFORE_GREED:
group->NeedBeforeGreed(loot, creature);
break;
case MASTER_LOOT:
group->MasterLoot(loot, creature);
break;
default:
break;
}
}
}
// if loot is already skinning loot then don't do anything else
if (loot->loot_type == LOOT_SKINNING)
{
loot_type = LOOT_SKINNING;
permission = creature->GetLootRecipientGUID() == GetGUID() ? OWNER_PERMISSION : NONE_PERMISSION;
}
else if (loot_type == LOOT_SKINNING)
{
loot->clear();
loot->FillLoot(creature->GetCreatureTemplate()->SkinLootId, LootTemplates_Skinning, this, true);
permission = OWNER_PERMISSION;
// Set new loot recipient
creature->SetLootRecipient(this, false);
}
// set group rights only for loot_type != LOOT_SKINNING
else
{
if (creature->GetLootRecipientGroup())
{
Group* group = GetGroup();
if (group == creature->GetLootRecipientGroup())
{
switch (group->GetLootMethod())
{
case MASTER_LOOT:
permission = group->GetMasterLooterGuid() == GetGUID() ? MASTER_PERMISSION : RESTRICTED_PERMISSION;
break;
case FREE_FOR_ALL:
permission = ALL_PERMISSION;
break;
case ROUND_ROBIN:
permission = ROUND_ROBIN_PERMISSION;
break;
default:
permission = GROUP_PERMISSION;
break;
}
}
else
permission = NONE_PERMISSION;
}
else if (creature->GetLootRecipient() == this)
permission = OWNER_PERMISSION;
else
permission = NONE_PERMISSION;
}
}
}
// LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client
switch (loot_type)
{
case LOOT_INSIGNIA: loot_type = LOOT_SKINNING; break;
case LOOT_FISHINGHOLE: loot_type = LOOT_FISHING; break;
case LOOT_FISHING_JUNK: loot_type = LOOT_FISHING; break;
default: break;
}
// need know merged fishing/corpse loot type for achievements
loot->loot_type = loot_type;
if (permission != NONE_PERMISSION)
{
SetLootGUID(guid);
WorldPacket data(SMSG_LOOT_RESPONSE, (9 + 50)); // we guess size
data << guid;
data << uint8(loot_type);
data << LootView(*loot, this, permission);
SendDirectMessage(&data);
// add 'this' player as one of the players that are looting 'loot'
loot->AddLooter(GetGUID());
if (loot_type == LOOT_CORPSE && !guid.IsItem())
SetUnitFlag(UNIT_FLAG_LOOTING);
}
else
SendLootError(GetLootGUID(), LOOT_ERROR_DIDNT_KILL);
}
void Player::SendLootError(ObjectGuid guid, LootError error) const
{
WorldPacket data(SMSG_LOOT_RESPONSE, 10);
data << guid;
data << uint8(LOOT_NONE);
data << uint8(error);
SendDirectMessage(&data);
}
void Player::SendNotifyLootMoneyRemoved() const
{
WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
SendDirectMessage(&data);
}
void Player::SendNotifyLootItemRemoved(uint8 lootSlot) const
{
WorldPacket data(SMSG_LOOT_REMOVED, 1);
data << uint8(lootSlot);
SendDirectMessage(&data);
}
void Player::SendUpdateWorldState(uint32 variable, uint32 value) const
{
WorldPackets::WorldState::UpdateWorldState worldstate;
worldstate.VariableID = variable;
worldstate.Value = value;
SendDirectMessage(worldstate.Write());
}
// TODO - InitWorldStates should NOT always send the same states
// Some should keep the same value between different zoneIds and areaIds on the same map
void Player::SendInitWorldStates(uint32 zoneId, uint32 areaId)
{
uint32 mapId = GetMapId();
Battleground* battleground = GetBattleground();
OutdoorPvP* outdoorPvP = sOutdoorPvPMgr->GetOutdoorPvPToZoneId(zoneId);
InstanceScript* instance = GetInstanceScript();
Battlefield* battlefield = sBattlefieldMgr->GetBattlefieldToZoneId(zoneId);
TC_LOG_DEBUG("network", "Player::SendInitWorldStates: Sending SMSG_INIT_WORLD_STATES for Map: {}, Zone: {}", mapId, zoneId);
WorldPackets::WorldState::InitWorldStates packet;
packet.MapID = mapId;
packet.ZoneID = zoneId;
packet.AreaID = areaId;
packet.Worldstates.emplace_back(2264, 0); // SCOURGE_EVENT_WORLDSTATE_EASTERN_PLAGUELANDS
packet.Worldstates.emplace_back(2263, 0); // SCOURGE_EVENT_WORLDSTATE_TANARIS
packet.Worldstates.emplace_back(2262, 0); // SCOURGE_EVENT_WORLDSTATE_BURNING_STEPPES
packet.Worldstates.emplace_back(2261, 0); // SCOURGE_EVENT_WORLDSTATE_BLASTED_LANDS
packet.Worldstates.emplace_back(2260, 0); // SCOURGE_EVENT_WORLDSTATE_AZSHARA
packet.Worldstates.emplace_back(2259, 0); // SCOURGE_EVENT_WORLDSTATE_WINTERSPRING
// ARENA_SEASON_IN_PROGRESS
// 7 - arena season in progress
// 0 - end of season
packet.Worldstates.emplace_back(3191, sWorld->getBoolConfig(CONFIG_ARENA_SEASON_IN_PROGRESS) ? sWorld->getIntConfig(CONFIG_ARENA_SEASON_ID) : 0);
// Previous arena season id
int32 previousArenaSeason = 0;
if (sWorld->getBoolConfig(CONFIG_ARENA_SEASON_IN_PROGRESS) && sWorld->getIntConfig(CONFIG_ARENA_SEASON_ID) > 0)
previousArenaSeason = sWorld->getIntConfig(CONFIG_ARENA_SEASON_ID) - 1;
packet.Worldstates.emplace_back(3901, previousArenaSeason);
if (mapId == 530) // Outland
{
packet.Worldstates.emplace_back(2495, 0); // NA_UI_OUTLAND_01 "Progress: %2494w"
packet.Worldstates.emplace_back(2493, 15); // NA_UI_GUARDS_MAX
packet.Worldstates.emplace_back(2491, 15); // NA_UI_GUARDS_LEFT
}
switch (zoneId)
{
case 1: // Dun Morogh
case 11: // Wetlands
case 12: // Elwynn Forest
case 38: // Loch Modan
case 40: // Westfall
case 51: // Searing Gorge
case 1519: // Stormwind City
case 1537: // Ironforge
case 2257: // Deeprun Tram
case 3703: // Shattrath City
break;
case 139: // Eastern Plaguelands
if (outdoorPvP && outdoorPvP->GetTypeId() == OUTDOOR_PVP_EP)
outdoorPvP->FillInitialWorldStates(packet);
else
{
packet.Worldstates.emplace_back(2426, 0); // GENERAL_WORLDSTATES_01 "Progress: %2427w"
packet.Worldstates.emplace_back(2327, 0); // EP_UI_TOWER_COUNT_A
packet.Worldstates.emplace_back(2328, 0); // EP_UI_TOWER_COUNT_H
packet.Worldstates.emplace_back(2427, 50); // GENERAL_WORLDSTATES_02
packet.Worldstates.emplace_back(2428, 50); // GENERAL_WORLDSTATES_03
packet.Worldstates.emplace_back(2355, 1); // EP_CGT_N
packet.Worldstates.emplace_back(2374, 0); // EP_CGT_N_A
packet.Worldstates.emplace_back(2375, 0); // EP_CGT_N_H
packet.Worldstates.emplace_back(2376, 0); // GENERAL_WORLDSTATES_04
packet.Worldstates.emplace_back(2377, 0); // GENERAL_WORLDSTATES_05
packet.Worldstates.emplace_back(2378, 0); // EP_CGT_A
packet.Worldstates.emplace_back(2379, 0); // EP_CGT_H
packet.Worldstates.emplace_back(2354, 0); // EP_EWT_A
packet.Worldstates.emplace_back(2356, 0); // EP_EWT_H
packet.Worldstates.emplace_back(2357, 0); // GENERAL_WORLDSTATES_06
packet.Worldstates.emplace_back(2358, 0); // GENERAL_WORLDSTATES_07
packet.Worldstates.emplace_back(2359, 0); // EP_EWT_N_A
packet.Worldstates.emplace_back(2360, 0); // EP_EWT_N_H
packet.Worldstates.emplace_back(2361, 1); // EP_EWT_N
packet.Worldstates.emplace_back(2352, 1); // EP_NPT_N
packet.Worldstates.emplace_back(2362, 0); // EP_NPT_N_A
packet.Worldstates.emplace_back(2363, 0); // GENERAL_WORLDSTATES_08
packet.Worldstates.emplace_back(2364, 0); // GENERAL_WORLDSTATES_09
packet.Worldstates.emplace_back(2365, 0); // GENERAL_WORLDSTATES_10
packet.Worldstates.emplace_back(2372, 0); // EP_NPT_A
packet.Worldstates.emplace_back(2373, 0); // EP_NPT_H
packet.Worldstates.emplace_back(2353, 1); // EP_PWT_N
packet.Worldstates.emplace_back(2366, 0); // EP_PWT_N_A
//packet.Worldstates.emplace_back(2367, 1); // GENERAL_WORLDSTATES_13 grey horde not in dbc!
packet.Worldstates.emplace_back(2368, 0); // GENERAL_WORLDSTATES_11
packet.Worldstates.emplace_back(2369, 0); // GENERAL_WORLDSTATES_12
packet.Worldstates.emplace_back(2370, 0); // EP_PWT_A
packet.Worldstates.emplace_back(2371, 0); // EP_PWT_H
}
break;
case 1377: // Silithus
if (outdoorPvP && outdoorPvP->GetTypeId() == OUTDOOR_PVP_SI)
outdoorPvP->FillInitialWorldStates(packet);
else
{
packet.Worldstates.emplace_back(2313, 0); // SI_GATHERED_A
packet.Worldstates.emplace_back(2314, 0); // SI_GATHERED_H
packet.Worldstates.emplace_back(2317, 0); // SI_SILITHYST_MAX
}
// unknown, aq opening?
packet.Worldstates.emplace_back(2322, 0); // AQ_SANDWORM_N
packet.Worldstates.emplace_back(2323, 0); // AQ_SANDWORM_S
packet.Worldstates.emplace_back(2324, 0); // AQ_SANDWORM_SW
packet.Worldstates.emplace_back(2325, 0); // AQ_SANDWORM_E
break;
case 2597: // Alterac Valley
if (battleground && battleground->GetTypeID(true) == BATTLEGROUND_AV)
battleground->FillInitialWorldStates(packet);
else
{
packet.Worldstates.emplace_back(1966, 1); // AV_SNOWFALL_N
packet.Worldstates.emplace_back(1330, 1); // AV_FROSTWOLFHUT_H_C
packet.Worldstates.emplace_back(1329, 0); // AV_FROSTWOLFHUT_A_C
packet.Worldstates.emplace_back(1326, 0); // AV_AID_A_A
packet.Worldstates.emplace_back(1393, 0); // East Frostwolf Tower Horde Assaulted - UNUSED
packet.Worldstates.emplace_back(1392, 0); // West Frostwolf Tower Horde Assaulted - UNUSED
packet.Worldstates.emplace_back(1383, 1); // AV_FROSTWOLFE_CONTROLLED
packet.Worldstates.emplace_back(1382, 1); // AV_FROSTWOLFW_CONTROLLED
packet.Worldstates.emplace_back(1360, 1); // AV_N_MINE_N
packet.Worldstates.emplace_back(1348, 0); // AV_ICEBLOOD_A_A
packet.Worldstates.emplace_back(1334, 0); // AV_PIKEGRAVE_H_C
packet.Worldstates.emplace_back(1333, 1); // AV_PIKEGRAVE_A_C
packet.Worldstates.emplace_back(1304, 0); // AV_STONEHEART_A_A
packet.Worldstates.emplace_back(1303, 0); // AV_STONEHEART_H_A
packet.Worldstates.emplace_back(1396, 0); // unk
packet.Worldstates.emplace_back(1395, 0); // Iceblood Tower Horde Assaulted - UNUSED
packet.Worldstates.emplace_back(1394, 0); // Towerpoint Horde Assaulted - UNUSED
packet.Worldstates.emplace_back(1391, 0); // unk
packet.Worldstates.emplace_back(1390, 0); // AV_ICEBLOOD_ASSAULTED
packet.Worldstates.emplace_back(1389, 0); // AV_TOWERPOINT_ASSAULTED
packet.Worldstates.emplace_back(1388, 0); // AV_FROSTWOLFE_ASSAULTED
packet.Worldstates.emplace_back(1387, 0); // AV_FROSTWOLFW_ASSAULTED
packet.Worldstates.emplace_back(1386, 1); // unk
packet.Worldstates.emplace_back(1385, 1); // AV_ICEBLOOD_CONTROLLED
packet.Worldstates.emplace_back(1384, 1); // AV_TOWERPOINT_CONTROLLED
packet.Worldstates.emplace_back(1381, 0); // AV_STONEH_ASSAULTED
packet.Worldstates.emplace_back(1380, 0); // AV_ICEWING_ASSAULTED
packet.Worldstates.emplace_back(1379, 0); // AV_DUNN_ASSAULTED
packet.Worldstates.emplace_back(1378, 0); // AV_DUNS_ASSAULTED
packet.Worldstates.emplace_back(1377, 0); // Stoneheart Bunker Alliance Assaulted - UNUSED
packet.Worldstates.emplace_back(1376, 0); // Icewing Bunker Alliance Assaulted - UNUSED
packet.Worldstates.emplace_back(1375, 0); // Dunbaldar South Alliance Assaulted - UNUSED
packet.Worldstates.emplace_back(1374, 0); // Dunbaldar North Alliance Assaulted - UNUSED
packet.Worldstates.emplace_back(1373, 0); // AV_STONEH_DESTROYED
packet.Worldstates.emplace_back(966, 0); // AV_UNK_02
packet.Worldstates.emplace_back(964, 0); // AV_UNK_01
packet.Worldstates.emplace_back(962, 0); // AV_STORMPIKE_COMMANDERS
packet.Worldstates.emplace_back(1302, 1); // AV_STONEHEART_A_C
packet.Worldstates.emplace_back(1301, 0); // AV_STONEHEART_H_C
packet.Worldstates.emplace_back(950, 0); // AV_STORMPIKE_LIEUTENANTS
packet.Worldstates.emplace_back(1372, 0); // AV_ICEWING_DESTROYED
packet.Worldstates.emplace_back(1371, 0); // AV_DUNN_DESTROYED
packet.Worldstates.emplace_back(1370, 0); // AV_DUNS_DESTROYED
packet.Worldstates.emplace_back(1369, 0); // unk
packet.Worldstates.emplace_back(1368, 0); // AV_ICEBLOOD_DESTROYED
packet.Worldstates.emplace_back(1367, 0); // AV_TOWERPOINT_DESTROYED
packet.Worldstates.emplace_back(1366, 0); // AV_FROSTWOLFE_DESTROYED
packet.Worldstates.emplace_back(1365, 0); // AV_FROSTWOLFW_DESTROYED
packet.Worldstates.emplace_back(1364, 1); // AV_STONEH_CONTROLLED
packet.Worldstates.emplace_back(1363, 1); // AV_ICEWING_CONTROLLED
packet.Worldstates.emplace_back(1362, 1); // AV_DUNN_CONTROLLED
packet.Worldstates.emplace_back(1361, 1); // AV_DUNS_CONTROLLED
packet.Worldstates.emplace_back(1359, 0); // AV_N_MINE_H
packet.Worldstates.emplace_back(1358, 0); // AV_N_MINE_A
packet.Worldstates.emplace_back(1357, 1); // AV_S_MINE_N
packet.Worldstates.emplace_back(1356, 0); // AV_S_MINE_H
packet.Worldstates.emplace_back(1355, 0); // AV_S_MINE_A
packet.Worldstates.emplace_back(1349, 0); // AV_ICEBLOOD_H_A
packet.Worldstates.emplace_back(1347, 1); // AV_ICEBLOOD_H_C
packet.Worldstates.emplace_back(1346, 0); // AV_ICEBLOOD_A_C
packet.Worldstates.emplace_back(1344, 0); // AV_SNOWFALL_H_A
packet.Worldstates.emplace_back(1343, 0); // AV_SNOWFALL_A_A
packet.Worldstates.emplace_back(1342, 0); // AV_SNOWFALL_H_C
packet.Worldstates.emplace_back(1341, 0); // AV_SNOWFALL_A_C
packet.Worldstates.emplace_back(1340, 0); // AV_FROSTWOLF_H_A
packet.Worldstates.emplace_back(1339, 0); // AV_FROSTWOLF_A_A
packet.Worldstates.emplace_back(1338, 1); // AV_FROSTWOLF_H_C
packet.Worldstates.emplace_back(1337, 0); // AV_FROSTWOLF_A_C
packet.Worldstates.emplace_back(1336, 0); // AV_PIKEGRAVE_H_A
packet.Worldstates.emplace_back(1335, 0); // AV_PIKEGRAVE_A_A
packet.Worldstates.emplace_back(1332, 0); // AV_FROSTWOLFHUT_H_A
packet.Worldstates.emplace_back(1331, 0); // AV_FROSTWOLFHUT_A_A
packet.Worldstates.emplace_back(1328, 0); // AV_AID_H_A
packet.Worldstates.emplace_back(1327, 0); // AV_AID_H_C
packet.Worldstates.emplace_back(1325, 1); // AV_AID_A_C
}
break;
case 3277: // Warsong Gulch
if (battleground && battleground->GetTypeID(true) == BATTLEGROUND_WS)
battleground->FillInitialWorldStates(packet);
else
{
packet.Worldstates.emplace_back(1581, 0); // alliance flag captures
packet.Worldstates.emplace_back(1582, 0); // horde flag captures
packet.Worldstates.emplace_back(1545, 0); // unk, set to 1 on alliance flag pickup...
packet.Worldstates.emplace_back(1546, 0); // unk, set to 1 on horde flag pickup, after drop it's -1
packet.Worldstates.emplace_back(1547, 2); // unk
packet.Worldstates.emplace_back(1601, 3); // unk (max flag captures?)
packet.Worldstates.emplace_back(2338, 1); // horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
packet.Worldstates.emplace_back(2339, 1); // alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
}
break;
case 3358: // Arathi Basin
if (battleground && battleground->GetTypeID(true) == BATTLEGROUND_AB)
battleground->FillInitialWorldStates(packet);
else
{
packet.Worldstates.emplace_back(1767, 0); // stables alliance
packet.Worldstates.emplace_back(1768, 0); // stables horde
packet.Worldstates.emplace_back(1769, 0); // stables alliance controlled
packet.Worldstates.emplace_back(1770, 0); // stables horde controlled
packet.Worldstates.emplace_back(1772, 0); // farm alliance
packet.Worldstates.emplace_back(1773, 0); // farm horde
packet.Worldstates.emplace_back(1774, 0); // farm alliance controlled
packet.Worldstates.emplace_back(1775, 0); // farm horde controlled
packet.Worldstates.emplace_back(1776, 0); // alliance resources
packet.Worldstates.emplace_back(1777, 0); // horde resources
packet.Worldstates.emplace_back(1778, 0); // horde bases
packet.Worldstates.emplace_back(1779, 0); // alliance bases
packet.Worldstates.emplace_back(1780, 2000); // max resources (2000)
packet.Worldstates.emplace_back(1782, 0); // blacksmith alliance
packet.Worldstates.emplace_back(1783, 0); // blacksmith horde
packet.Worldstates.emplace_back(1784, 0); // blacksmith alliance controlled
packet.Worldstates.emplace_back(1785, 0); // blacksmith horde controlled
packet.Worldstates.emplace_back(1787, 0); // gold mine alliance
packet.Worldstates.emplace_back(1788, 0); // gold mine horde
packet.Worldstates.emplace_back(1789, 0); // gold mine alliance controlled
packet.Worldstates.emplace_back(1790, 0); // gold mine horde controlled
packet.Worldstates.emplace_back(1792, 0); // lumber mill alliance
packet.Worldstates.emplace_back(1793, 0); // lumber mill horde
packet.Worldstates.emplace_back(1794, 0); // lumber mill alliance controlled
packet.Worldstates.emplace_back(1795, 0); // lumber mill horde controlled
packet.Worldstates.emplace_back(1842, 1); // stables (1 - uncontrolled)
packet.Worldstates.emplace_back(1843, 1); // gold mine (1 - uncontrolled)
packet.Worldstates.emplace_back(1844, 1); // lumber mill (1 - uncontrolled)
packet.Worldstates.emplace_back(1845, 1); // farm (1 - uncontrolled)
packet.Worldstates.emplace_back(1846, 1); // blacksmith (1 - uncontrolled)
packet.Worldstates.emplace_back(1861, 2); // unk
packet.Worldstates.emplace_back(1955, 1800); // warning limit (1800)
}
break;
case 3820: // Eye of the Storm
if (battleground && battleground->GetTypeID(true) == BATTLEGROUND_EY)
battleground->FillInitialWorldStates(packet);
else
{
packet.Worldstates.emplace_back(2753, 0); // Horde Bases
packet.Worldstates.emplace_back(2752, 0); // Alliance Bases
packet.Worldstates.emplace_back(2742, 0); // Mage Tower - Horde conflict
packet.Worldstates.emplace_back(2741, 0); // Mage Tower - Alliance conflict
packet.Worldstates.emplace_back(2740, 0); // Fel Reaver - Horde conflict
packet.Worldstates.emplace_back(2739, 0); // Fel Reaver - Alliance conflict
packet.Worldstates.emplace_back(2738, 0); // Draenei - Alliance conflict
packet.Worldstates.emplace_back(2737, 0); // Draenei - Horde conflict
packet.Worldstates.emplace_back(2736, 0); // unk (0 at start)
packet.Worldstates.emplace_back(2735, 0); // unk (0 at start)
packet.Worldstates.emplace_back(2733, 0); // Draenei - Horde control
packet.Worldstates.emplace_back(2732, 0); // Draenei - Alliance control
packet.Worldstates.emplace_back(2731, 1); // Draenei uncontrolled (1 - yes, 0 - no)
packet.Worldstates.emplace_back(2730, 0); // Mage Tower - Alliance control
packet.Worldstates.emplace_back(2729, 0); // Mage Tower - Horde control
packet.Worldstates.emplace_back(2728, 1); // Mage Tower uncontrolled (1 - yes, 0 - no)
packet.Worldstates.emplace_back(2727, 0); // Fel Reaver - Horde control
packet.Worldstates.emplace_back(2726, 0); // Fel Reaver - Alliance control
packet.Worldstates.emplace_back(2725, 1); // Fel Reaver uncontrolled (1 - yes, 0 - no)
packet.Worldstates.emplace_back(2724, 0); // Boold Elf - Horde control
packet.Worldstates.emplace_back(2723, 0); // Boold Elf - Alliance control
packet.Worldstates.emplace_back(2722, 1); // Boold Elf uncontrolled (1 - yes, 0 - no)
packet.Worldstates.emplace_back(2757, 1); // Flag (1 - show, 0 - hide) - doesn't work exactly this way!
packet.Worldstates.emplace_back(2770, 1); // Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
packet.Worldstates.emplace_back(2769, 1); // Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
packet.Worldstates.emplace_back(2750, 0); // Horde resources
packet.Worldstates.emplace_back(2749, 0); // Alliance resources
packet.Worldstates.emplace_back(2565, 142); // unk, constant?
packet.Worldstates.emplace_back(2720, 0); // Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
packet.Worldstates.emplace_back(2719, 0); // Capturing progress-bar (0 - left, 100 - right)
packet.Worldstates.emplace_back(2718, 0); // Capturing progress-bar (1 - show, 0 - hide)
packet.Worldstates.emplace_back(3085, 379); // unk, constant?
// missing unknowns
}
break;
case 3483: // Hellfire Peninsula
if (outdoorPvP && outdoorPvP->GetTypeId() == OUTDOOR_PVP_HP)
outdoorPvP->FillInitialWorldStates(packet);
else
{
packet.Worldstates.emplace_back(2490, 1); // add ally tower main gui icon
packet.Worldstates.emplace_back(2489, 1); // add horde tower main gui icon
packet.Worldstates.emplace_back(2485, 0); // show neutral broken hill icon
packet.Worldstates.emplace_back(2484, 1); // show icon above broken hill
packet.Worldstates.emplace_back(2483, 0); // show ally broken hill icon
packet.Worldstates.emplace_back(2482, 0); // show neutral overlook icon
packet.Worldstates.emplace_back(2481, 1); // show the overlook arrow
packet.Worldstates.emplace_back(2480, 0); // show ally overlook icon
packet.Worldstates.emplace_back(2478, 0); // horde pvp objectives captured
packet.Worldstates.emplace_back(2476, 0); // ally pvp objectives captured
packet.Worldstates.emplace_back(2475, 100); // horde slider grey area
packet.Worldstates.emplace_back(2474, 50); // horde slider percentage, 100 for ally, 0 for horde
packet.Worldstates.emplace_back(2473, 0); // horde slider display
packet.Worldstates.emplace_back(2472, 0); // show the neutral stadium icon
packet.Worldstates.emplace_back(2471, 0); // show the ally stadium icon
packet.Worldstates.emplace_back(2470, 1); // show the horde stadium icon
}
break;
case 3518: // Nagrand
if (outdoorPvP && outdoorPvP->GetTypeId() == OUTDOOR_PVP_NA)
outdoorPvP->FillInitialWorldStates(packet);
else
{
packet.Worldstates.emplace_back(2503, 0); // NA_UI_HORDE_GUARDS_SHOW
packet.Worldstates.emplace_back(2502, 0); // NA_UI_ALLIANCE_GUARDS_SHOW
packet.Worldstates.emplace_back(2493, 0); // NA_UI_GUARDS_MAX
packet.Worldstates.emplace_back(2491, 0); // NA_UI_GUARDS_LEFT
packet.Worldstates.emplace_back(2495, 0); // NA_UI_OUTLAND_01
packet.Worldstates.emplace_back(2494, 0); // NA_UI_UNK_1
packet.Worldstates.emplace_back(2497, 0); // NA_UI_UNK_2
packet.Worldstates.emplace_back(2762, 0); // NA_MAP_WYVERN_NORTH_NEU_H
packet.Worldstates.emplace_back(2662, 0); // NA_MAP_WYVERN_NORTH_NEU_A
packet.Worldstates.emplace_back(2663, 0); // NA_MAP_WYVERN_NORTH_H
packet.Worldstates.emplace_back(2664, 0); // NA_MAP_WYVERN_NORTH_A
packet.Worldstates.emplace_back(2760, 0); // NA_MAP_WYVERN_SOUTH_NEU_H
packet.Worldstates.emplace_back(2670, 0); // NA_MAP_WYVERN_SOUTH_NEU_A
packet.Worldstates.emplace_back(2668, 0); // NA_MAP_WYVERN_SOUTH_H
packet.Worldstates.emplace_back(2669, 0); // NA_MAP_WYVERN_SOUTH_A
packet.Worldstates.emplace_back(2761, 0); // NA_MAP_WYVERN_WEST_NEU_H
packet.Worldstates.emplace_back(2667, 0); // NA_MAP_WYVERN_WEST_NEU_A
packet.Worldstates.emplace_back(2665, 0); // NA_MAP_WYVERN_WEST_H
packet.Worldstates.emplace_back(2666, 0); // NA_MAP_WYVERN_WEST_A
packet.Worldstates.emplace_back(2763, 0); // NA_MAP_WYVERN_EAST_NEU_H
packet.Worldstates.emplace_back(2659, 0); // NA_MAP_WYVERN_EAST_NEU_A
packet.Worldstates.emplace_back(2660, 0); // NA_MAP_WYVERN_EAST_H
packet.Worldstates.emplace_back(2661, 0); // NA_MAP_WYVERN_EAST_A
packet.Worldstates.emplace_back(2671, 0); // NA_MAP_HALAA_NEUTRAL
packet.Worldstates.emplace_back(2676, 0); // NA_MAP_HALAA_NEU_A
packet.Worldstates.emplace_back(2677, 0); // NA_MAP_HALAA_NEU_H
packet.Worldstates.emplace_back(2672, 0); // NA_MAP_HALAA_HORDE
packet.Worldstates.emplace_back(2673, 0); // NA_MAP_HALAA_ALLIANCE
}
break;
case 3519: // Terokkar Forest
if (outdoorPvP && outdoorPvP->GetTypeId() == OUTDOOR_PVP_TF)
outdoorPvP->FillInitialWorldStates(packet);
else
{
packet.Worldstates.emplace_back(2625, 0); // TF_UI_CAPTURE_BAR_POS
packet.Worldstates.emplace_back(2624, 20); // TF_UI_CAPTURE_BAR_NEUTRAL
packet.Worldstates.emplace_back(2623, 0); // TF_UI_SHOW CAPTURE BAR
packet.Worldstates.emplace_back(2622, 0); // TF_UI_TOWER_COUNT_H
packet.Worldstates.emplace_back(2621, 5); // TF_UI_TOWER_COUNT_A
packet.Worldstates.emplace_back(2620, 0); // TF_UI_TOWERS_CONTROLLED_DISPLAY
packet.Worldstates.emplace_back(2696, 0); // TF_TOWER_NUM_15 - SE Neutral
packet.Worldstates.emplace_back(2695, 0); // TF_TOWER_NUM_14 - SE Horde
packet.Worldstates.emplace_back(2694, 0); // TF_TOWER_NUM_13 - SE Alliance
packet.Worldstates.emplace_back(2693, 0); // TF_TOWER_NUM_12 - S Neutral
packet.Worldstates.emplace_back(2692, 0); // TF_TOWER_NUM_11 - S Horde
packet.Worldstates.emplace_back(2691, 0); // TF_TOWER_NUM_10 - S Alliance
packet.Worldstates.emplace_back(2690, 0); // TF_TOWER_NUM_09 - NE Neutral
packet.Worldstates.emplace_back(2689, 0); // TF_TOWER_NUM_08 - NE Horde
packet.Worldstates.emplace_back(2688, 0); // TF_TOWER_NUM_07 - NE Alliance
packet.Worldstates.emplace_back(2687, 0); // TF_TOWER_NUM_16 - unk
packet.Worldstates.emplace_back(2686, 0); // TF_TOWER_NUM_06 - N Neutral
packet.Worldstates.emplace_back(2685, 0); // TF_TOWER_NUM_05 - N Horde
packet.Worldstates.emplace_back(2684, 0); // TF_TOWER_NUM_04 - N Alliance
packet.Worldstates.emplace_back(2683, 0); // TF_TOWER_NUM_03 - NW Alliance
packet.Worldstates.emplace_back(2682, 0); // TF_TOWER_NUM_02 - NW Horde
packet.Worldstates.emplace_back(2681, 0); // TF_TOWER_NUM_01 - NW Neutral
packet.Worldstates.emplace_back(2512, 5); // TF_UI_LOCKED_TIME_MINUTES_FIRST_DIGIT
packet.Worldstates.emplace_back(2510, 0); // TF_UI_LOCKED_TIME_MINUTES_SECOND_DIGIT
packet.Worldstates.emplace_back(2509, 0); // TF_UI_LOCKED_TIME_HOURS
packet.Worldstates.emplace_back(2508, 0); // TF_UI_LOCKED_DISPLAY_NEUTRAL
packet.Worldstates.emplace_back(2768, 0); // TF_UI_LOCKED_DISPLAY_HORDE
packet.Worldstates.emplace_back(2767, 1); // TF_UI_LOCKED_DISPLAY_ALLIANCE
}
break;
case 3521: // Zangarmarsh
if (outdoorPvP && outdoorPvP->GetTypeId() == OUTDOOR_PVP_ZM)
outdoorPvP->FillInitialWorldStates(packet);
else
{
packet.Worldstates.emplace_back(2529, 0); // ZM_UNK_1
packet.Worldstates.emplace_back(2528, 0); // ZM_UNK_2
packet.Worldstates.emplace_back(2527, 0); // ZM_UNK_3
packet.Worldstates.emplace_back(2653, 1); // ZM_WORLDSTATE_UNK_1
packet.Worldstates.emplace_back(2652, 0); // ZM_MAP_TOWER_EAST_N
packet.Worldstates.emplace_back(2651, 1); // ZM_MAP_TOWER_EAST_H
packet.Worldstates.emplace_back(2650, 0); // ZM_MAP_TOWER_EAST_A
packet.Worldstates.emplace_back(2649, 1); // ZM_MAP_GRAVEYARD_H - Twin spire graveyard horde
packet.Worldstates.emplace_back(2648, 0); // ZM_MAP_GRAVEYARD_A
packet.Worldstates.emplace_back(2647, 0); // ZM_MAP_GRAVEYARD_N
packet.Worldstates.emplace_back(2646, 0); // ZM_MAP_TOWER_WEST_N
packet.Worldstates.emplace_back(2645, 1); // ZM_MAP_TOWER_WEST_H
packet.Worldstates.emplace_back(2644, 0); // ZM_MAP_TOWER_WEST_A
packet.Worldstates.emplace_back(2535, 0); // ZM_UNK_4
packet.Worldstates.emplace_back(2534, 0); // ZM_UNK_5
packet.Worldstates.emplace_back(2533, 0); // ZM_UNK_6
packet.Worldstates.emplace_back(2560, 0); // ZM_UI_TOWER_EAST_N
packet.Worldstates.emplace_back(2559, 1); // ZM_UI_TOWER_EAST_H
packet.Worldstates.emplace_back(2558, 0); // ZM_UI_TOWER_EAST_A
packet.Worldstates.emplace_back(2557, 0); // ZM_UI_TOWER_WEST_N
packet.Worldstates.emplace_back(2556, 1); // ZM_UI_TOWER_WEST_H
packet.Worldstates.emplace_back(2555, 0); // ZM_UI_TOWER_WEST_A
packet.Worldstates.emplace_back(2658, 0); // ZM_MAP_HORDE_FLAG_READY
packet.Worldstates.emplace_back(2657, 1); // ZM_MAP_HORDE_FLAG_NOT_READY
packet.Worldstates.emplace_back(2656, 1); // ZM_MAP_ALLIANCE_FLAG_NOT_READY
packet.Worldstates.emplace_back(2655, 0); // ZM_MAP_ALLIANCE_FLAG_READY
}
break;
case 3698: // Nagrand Arena
if (battleground && battleground->GetTypeID(true) == BATTLEGROUND_NA)
battleground->FillInitialWorldStates(packet);
else
{
packet.Worldstates.emplace_back(2575, 0); // BATTLEGROUND_NAGRAND_ARENA_GOLD
packet.Worldstates.emplace_back(2576, 0); // BATTLEGROUND_NAGRAND_ARENA_GREEN
packet.Worldstates.emplace_back(2577, 0); // BATTLEGROUND_NAGRAND_ARENA_SHOW
}
break;
case 3702: // Blade's Edge Arena
if (battleground && battleground->GetTypeID(true) == BATTLEGROUND_BE)
battleground->FillInitialWorldStates(packet);
else
{
packet.Worldstates.emplace_back(2544, 0); // BATTLEGROUND_BLADES_EDGE_ARENA_GOLD
packet.Worldstates.emplace_back(2545, 0); // BATTLEGROUND_BLADES_EDGE_ARENA_GREEN
packet.Worldstates.emplace_back(2547, 0); // BATTLEGROUND_BLADES_EDGE_ARENA_SHOW
}
break;
case 3968: // Ruins of Lordaeron
if (battleground && battleground->GetTypeID(true) == BATTLEGROUND_RL)
battleground->FillInitialWorldStates(packet);
else
{
packet.Worldstates.emplace_back(3000, 0); // BATTELGROUND_RUINS_OF_LORDAERNON_GOLD
packet.Worldstates.emplace_back(3001, 0); // BATTELGROUND_RUINS_OF_LORDAERNON_GREEN
packet.Worldstates.emplace_back(3002, 0); // BATTELGROUND_RUINS_OF_LORDAERNON_SHOW
}
break;
case 4378: // Dalaran Sewers
if (battleground && battleground->GetTypeID(true) == BATTLEGROUND_DS)
battleground->FillInitialWorldStates(packet);
else
{
packet.Worldstates.emplace_back(3601, 0); // ARENA_WORLD_STATE_ALIVE_PLAYERS_GOLD
packet.Worldstates.emplace_back(3600, 0); // ARENA_WORLD_STATE_ALIVE_PLAYERS_GREEN
packet.Worldstates.emplace_back(3610, 0); // ARENA_WORLD_STATE_ALIVE_PLAYERS_SHOW
}
break;
case 4384: // Strand of the Ancients
if (battleground && battleground->GetTypeID(true) == BATTLEGROUND_SA)
battleground->FillInitialWorldStates(packet);
else
{
packet.Worldstates.emplace_back(3849, 0); // Gate of Temple
packet.Worldstates.emplace_back(3638, 0); // Gate of Yellow Moon
packet.Worldstates.emplace_back(3623, 0); // Gate of Green Emerald
packet.Worldstates.emplace_back(3620, 0); // Gate of Blue Sapphire
packet.Worldstates.emplace_back(3617, 0); // Gate of Red Sun
packet.Worldstates.emplace_back(3614, 0); // Gate of Purple Ametyst
packet.Worldstates.emplace_back(3571, 0); // bonus timer (1 - on, 0 - off)
packet.Worldstates.emplace_back(3565, 0); // Horde Attacker
packet.Worldstates.emplace_back(3564, 0); // Alliance Attacker
// End Round timer, example: 19:59 -> A:BC
packet.Worldstates.emplace_back(3561, 0); // C
packet.Worldstates.emplace_back(3560, 0); // B
packet.Worldstates.emplace_back(3559, 0); // A
packet.Worldstates.emplace_back(3637, 0); // BG_SA_CENTER_GY_ALLIANCE
packet.Worldstates.emplace_back(3636, 0); // BG_SA_RIGHT_GY_ALLIANCE
packet.Worldstates.emplace_back(3635, 0); // BG_SA_LEFT_GY_ALLIANCE
packet.Worldstates.emplace_back(3634, 0); // BG_SA_CENTER_GY_HORDE
packet.Worldstates.emplace_back(3633, 0); // BG_SA_LEFT_GY_HORDE
packet.Worldstates.emplace_back(3632, 0); // BG_SA_RIGHT_GY_HORDE
packet.Worldstates.emplace_back(3631, 0); // BG_SA_HORDE_DEFENCE_TOKEN
packet.Worldstates.emplace_back(3630, 0); // BG_SA_ALLIANCE_DEFENCE_TOKEN
packet.Worldstates.emplace_back(3629, 0); // BG_SA_LEFT_ATT_TOKEN_HRD
packet.Worldstates.emplace_back(3628, 0); // BG_SA_RIGHT_ATT_TOKEN_HRD
packet.Worldstates.emplace_back(3627, 0); // BG_SA_RIGHT_ATT_TOKEN_ALL
packet.Worldstates.emplace_back(3626, 0); // BG_SA_LEFT_ATT_TOKEN_ALL
// missing unknowns
}
break;
case 4406: // Ring of Valor
if (battleground && battleground->GetTypeID(true) == BATTLEGROUND_RV)
battleground->FillInitialWorldStates(packet);
else
{
packet.Worldstates.emplace_back(3600, 0); // ARENA_WORLD_STATE_ALIVE_PLAYERS_GREEN
packet.Worldstates.emplace_back(3601, 0); // ARENA_WORLD_STATE_ALIVE_PLAYERS_GOLD
packet.Worldstates.emplace_back(3610, 0); // ARENA_WORLD_STATE_ALIVE_PLAYERS_SHOW
}
break;
case 4710: // Isle of Conquest
if (battleground && battleground->GetTypeID(true) == BATTLEGROUND_IC)
battleground->FillInitialWorldStates(packet);
else
{
packet.Worldstates.emplace_back(4221, 1); // BG_IC_ALLIANCE_RENFORT_SET
packet.Worldstates.emplace_back(4222, 1); // BG_IC_HORDE_RENFORT_SET
packet.Worldstates.emplace_back(4226, 300); // BG_IC_ALLIANCE_RENFORT
packet.Worldstates.emplace_back(4227, 300); // BG_IC_HORDE_RENFORT
packet.Worldstates.emplace_back(4322, 1); // BG_IC_GATE_FRONT_H_WS_OPEN
packet.Worldstates.emplace_back(4321, 1); // BG_IC_GATE_WEST_H_WS_OPEN
packet.Worldstates.emplace_back(4320, 1); // BG_IC_GATE_EAST_H_WS_OPEN
packet.Worldstates.emplace_back(4323, 1); // BG_IC_GATE_FRONT_A_WS_OPEN
packet.Worldstates.emplace_back(4324, 1); // BG_IC_GATE_WEST_A_WS_OPEN
packet.Worldstates.emplace_back(4325, 1); // BG_IC_GATE_EAST_A_WS_OPEN
packet.Worldstates.emplace_back(4317, 1); // unk
packet.Worldstates.emplace_back(4301, 1); // BG_IC_DOCKS_UNCONTROLLED
packet.Worldstates.emplace_back(4296, 1); // BG_IC_HANGAR_UNCONTROLLED
packet.Worldstates.emplace_back(4306, 1); // BG_IC_QUARRY_UNCONTROLLED
packet.Worldstates.emplace_back(4311, 1); // BG_IC_REFINERY_UNCONTROLLED
packet.Worldstates.emplace_back(4294, 1); // BG_IC_WORKSHOP_UNCONTROLLED
packet.Worldstates.emplace_back(4243, 1); // unk
packet.Worldstates.emplace_back(4345, 1); // unk
}
break;
case 4987: // The Ruby Sanctum
if (instance)
instance->FillInitialWorldStates(packet);
else
{
packet.Worldstates.emplace_back(5049, 50); // WORLDSTATE_CORPOREALITY_MATERIAL
packet.Worldstates.emplace_back(5050, 50); // WORLDSTATE_CORPOREALITY_TWILIGHT
packet.Worldstates.emplace_back(5051, 0); // WORLDSTATE_CORPOREALITY_TOGGLE
}
break;
case 4812: // Icecrown Citadel
if (instance)
instance->FillInitialWorldStates(packet);
else
{
packet.Worldstates.emplace_back(4903, 0); // WORLDSTATE_SHOW_TIMER (Blood Quickening weekly)
packet.Worldstates.emplace_back(4904, 30); // WORLDSTATE_EXECUTION_TIME
packet.Worldstates.emplace_back(4940, 0); // WORLDSTATE_SHOW_ATTEMPTS
packet.Worldstates.emplace_back(4941, 50); // WORLDSTATE_ATTEMPTS_REMAINING
packet.Worldstates.emplace_back(4942, 50); // WORLDSTATE_ATTEMPTS_MAX
}
break;
case 4100: // The Culling of Stratholme
if (instance)
instance->FillInitialWorldStates(packet);
else
{
packet.Worldstates.emplace_back(3479, 0); // WORLDSTATE_SHOW_CRATES
packet.Worldstates.emplace_back(3480, 0); // WORLDSTATE_CRATES_REVEALED
packet.Worldstates.emplace_back(3504, 0); // WORLDSTATE_WAVE_COUNT
packet.Worldstates.emplace_back(3931, 25); // WORLDSTATE_TIME_GUARDIAN
packet.Worldstates.emplace_back(3932, 0); // WORLDSTATE_TIME_GUARDIAN_SHOW
}
break;
case 4228: // The Oculus
if (instance)
instance->FillInitialWorldStates(packet);
else
{
packet.Worldstates.emplace_back(3524, 0); // WORLD_STATE_CENTRIFUGE_CONSTRUCT_SHOW
packet.Worldstates.emplace_back(3486, 0); // WORLD_STATE_CENTRIFUGE_CONSTRUCT_AMOUNT
}
break;
case 4273: // Ulduar
if (instance)
instance->FillInitialWorldStates(packet);
else
{
packet.Worldstates.emplace_back(4132, 0); // WORLDSTATE_ALGALON_TIMER_ENABLED
packet.Worldstates.emplace_back(4131, 0); // WORLDSTATE_ALGALON_DESPAWN_TIMER
}
break;
case 4415: // Violet Hold
if (instance)
instance->FillInitialWorldStates(packet);
else
{
packet.Worldstates.emplace_back(3816, 0); // WORLD_STATE_VH_SHOW
packet.Worldstates.emplace_back(3815, 100); // WORLD_STATE_VH_PRISON_STATE
packet.Worldstates.emplace_back(3810, 0); // WORLD_STATE_VH_WAVE_COUNT
}
break;
case 4820: // Halls of Refection
if (instance)
instance->FillInitialWorldStates(packet);
else
{
packet.Worldstates.emplace_back(4884, 0); // WORLD_STATE_HOR_WAVES_ENABLED
packet.Worldstates.emplace_back(4882, 0); // WORLD_STATE_HOR_WAVE_COUNT
}
break;
case AREA_WINTERGRASP: // Wintergrasp
if (battlefield && battlefield->GetTypeId() == BATTLEFIELD_WG)
battlefield->FillInitialWorldStates(packet);
else
{
}
break;
default:
break;
}
SendDirectMessage(packet.Write());
SendBGWeekendWorldStates();
SendBattlefieldWorldStates();
}
void Player::SendBGWeekendWorldStates() const
{
for (uint32 i = 1; i < sBattlemasterListStore.GetNumRows(); ++i)
{
BattlemasterListEntry const* bl = sBattlemasterListStore.LookupEntry(i);
if (bl && bl->HolidayWorldState)
{
if (BattlegroundMgr::IsBGWeekend((BattlegroundTypeId)bl->ID))
SendUpdateWorldState(bl->HolidayWorldState, 1);
else
SendUpdateWorldState(bl->HolidayWorldState, 0);
}
}
}
void Player::SendBattlefieldWorldStates() const
{
/// Send misc stuff that needs to be sent on every login, like the battle timers.
if (sWorld->getBoolConfig(CONFIG_WINTERGRASP_ENABLE))
{
if (Battlefield* wg = sBattlefieldMgr->GetBattlefieldByBattleId(BATTLEFIELD_BATTLEID_WG))
{
SendUpdateWorldState(WS_BATTLEFIELD_WG_ACTIVE, wg->IsWarTime() ? 0 : 1);
uint32 timer = wg->IsWarTime() ? 0 : (wg->GetTimer() / 1000); // 0 - Time to next battle
SendUpdateWorldState(WS_BATTLEFIELD_WG_TIME_NEXT_BATTLE, uint32(GameTime::GetGameTime() + timer));
}
}
}
uint32 Player::GetXPRestBonus(uint32 xp)
{
uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
if (rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
rested_bonus = xp;
SetRestBonus(GetRestBonus() - rested_bonus);
TC_LOG_DEBUG("entities.player", "Player::GetXPRestBonus: Player '{}' ({}) gain {} xp (+{} Rested Bonus). Rested points={}", GetGUID().ToString(), GetName(), xp + rested_bonus, rested_bonus, GetRestBonus());
return rested_bonus;
}
void Player::SetBindPoint(ObjectGuid guid) const
{
WorldPackets::Misc::BinderConfirm packet(guid);
SendDirectMessage(packet.Write());
}
void Player::SendTalentWipeConfirm(ObjectGuid trainerGuid) const
{
SendDirectMessage(WorldPackets::Talents::RespecWipeConfirm(trainerGuid, ResetTalentsCost()).Write());
}
void Player::ResetPetTalents()
{
// This needs another gossip option + NPC text as a confirmation.
// The confirmation gossip listid has the text: "Yes, please do."
Pet* pet = GetPet();
if (!pet || pet->getPetType() != HUNTER_PET || pet->m_usedTalentCount == 0)
return;
CharmInfo* charmInfo = pet->GetCharmInfo();
if (!charmInfo)
{
TC_LOG_ERROR("entities.player", "Object {} is considered pet-like, but doesn't have charm info!", pet->GetGUID().ToString());
return;
}
pet->resetTalents();
SendTalentsInfoData(true);
}
/*********************************************************/
/*** STORAGE SYSTEM ***/
/*********************************************************/
void Player::SetVirtualItemSlot(uint8 i, Item* item)
{
ASSERT(i < 3);
if (i < 2 && item)
{
if (!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
return;
uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
if (charges == 0)
return;
if (charges > 1)
item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT, charges-1);
else
{
ApplyEnchantment(item, TEMP_ENCHANTMENT_SLOT, false);
item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
}
}
}
void Player::SetSheath(SheathState sheathed)
{
switch (sheathed)
{
case SHEATH_STATE_UNARMED: // no prepared weapon
SetVirtualItemSlot(0, nullptr);
SetVirtualItemSlot(1, nullptr);
SetVirtualItemSlot(2, nullptr);
break;
case SHEATH_STATE_MELEE: // prepared melee weapon
SetVirtualItemSlot(0, GetWeaponForAttack(BASE_ATTACK, true));
SetVirtualItemSlot(1, GetWeaponForAttack(OFF_ATTACK, true));
SetVirtualItemSlot(2, nullptr);
break;
case SHEATH_STATE_RANGED: // prepared ranged weapon
SetVirtualItemSlot(0, nullptr);
SetVirtualItemSlot(1, nullptr);
SetVirtualItemSlot(2, GetWeaponForAttack(RANGED_ATTACK, true));
break;
default:
SetVirtualItemSlot(0, nullptr);
SetVirtualItemSlot(1, nullptr);
SetVirtualItemSlot(2, nullptr);
break;
}
Unit::SetSheath(sheathed); // this must visualize Sheath changing for other players...
}
uint8 Player::FindEquipSlot(Item const* item, uint32 slot, bool swap) const
{
std::array<uint8, 4> slots = { NULL_SLOT, NULL_SLOT, NULL_SLOT, NULL_SLOT };
ItemTemplate const* proto = item->GetTemplate();
switch (proto->InventoryType)
{
case INVTYPE_HEAD:
slots[0] = EQUIPMENT_SLOT_HEAD;
break;
case INVTYPE_NECK:
slots[0] = EQUIPMENT_SLOT_NECK;
break;
case INVTYPE_SHOULDERS:
slots[0] = EQUIPMENT_SLOT_SHOULDERS;
break;
case INVTYPE_BODY:
slots[0] = EQUIPMENT_SLOT_BODY;
break;
case INVTYPE_CHEST:
slots[0] = EQUIPMENT_SLOT_CHEST;
break;
case INVTYPE_ROBE:
slots[0] = EQUIPMENT_SLOT_CHEST;
break;
case INVTYPE_WAIST:
slots[0] = EQUIPMENT_SLOT_WAIST;
break;
case INVTYPE_LEGS:
slots[0] = EQUIPMENT_SLOT_LEGS;
break;
case INVTYPE_FEET:
slots[0] = EQUIPMENT_SLOT_FEET;
break;
case INVTYPE_WRISTS:
slots[0] = EQUIPMENT_SLOT_WRISTS;
break;
case INVTYPE_HANDS:
slots[0] = EQUIPMENT_SLOT_HANDS;
break;
case INVTYPE_FINGER:
slots[0] = EQUIPMENT_SLOT_FINGER1;
slots[1] = EQUIPMENT_SLOT_FINGER2;
break;
case INVTYPE_TRINKET:
slots[0] = EQUIPMENT_SLOT_TRINKET1;
slots[1] = EQUIPMENT_SLOT_TRINKET2;
break;
case INVTYPE_CLOAK:
slots[0] = EQUIPMENT_SLOT_BACK;
break;
case INVTYPE_WEAPON:
{
slots[0] = EQUIPMENT_SLOT_MAINHAND;
// suggest offhand slot only if know dual wielding
// (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
if (CanDualWield())
slots[1] = EQUIPMENT_SLOT_OFFHAND;
break;
}
case INVTYPE_SHIELD:
slots[0] = EQUIPMENT_SLOT_OFFHAND;
break;
case INVTYPE_RANGED:
slots[0] = EQUIPMENT_SLOT_RANGED;
break;
case INVTYPE_2HWEAPON:
slots[0] = EQUIPMENT_SLOT_MAINHAND;
if (CanDualWield() && CanTitanGrip(item))
slots[1] = EQUIPMENT_SLOT_OFFHAND;
break;
case INVTYPE_TABARD:
slots[0] = EQUIPMENT_SLOT_TABARD;
break;
case INVTYPE_WEAPONMAINHAND:
slots[0] = EQUIPMENT_SLOT_MAINHAND;
break;
case INVTYPE_WEAPONOFFHAND:
slots[0] = EQUIPMENT_SLOT_OFFHAND;
break;
case INVTYPE_HOLDABLE:
slots[0] = EQUIPMENT_SLOT_OFFHAND;
break;
case INVTYPE_THROWN:
slots[0] = EQUIPMENT_SLOT_RANGED;
break;
case INVTYPE_RANGEDRIGHT:
slots[0] = EQUIPMENT_SLOT_RANGED;
break;
case INVTYPE_BAG:
slots = { INVENTORY_SLOT_BAG_START + 0, INVENTORY_SLOT_BAG_START + 1, INVENTORY_SLOT_BAG_START + 2, INVENTORY_SLOT_BAG_START + 3 };
break;
case INVTYPE_RELIC:
{
uint8 playerClass = GetClass();
switch (proto->SubClass)
{
case ITEM_SUBCLASS_ARMOR_LIBRAM:
if (playerClass == CLASS_PALADIN)
slots[0] = EQUIPMENT_SLOT_RANGED;
break;
case ITEM_SUBCLASS_ARMOR_IDOL:
if (playerClass == CLASS_DRUID)
slots[0] = EQUIPMENT_SLOT_RANGED;
break;
case ITEM_SUBCLASS_ARMOR_TOTEM:
if (playerClass == CLASS_SHAMAN)
slots[0] = EQUIPMENT_SLOT_RANGED;
break;
case ITEM_SUBCLASS_ARMOR_MISCELLANEOUS:
if (playerClass == CLASS_WARLOCK)
slots[0] = EQUIPMENT_SLOT_RANGED;
break;
case ITEM_SUBCLASS_ARMOR_SIGIL:
if (playerClass == CLASS_DEATH_KNIGHT)
slots[0] = EQUIPMENT_SLOT_RANGED;
break;
}
break;
}
default:
return NULL_SLOT;
}
if (slot != NULL_SLOT)
{
if (swap || !GetItemByPos(INVENTORY_SLOT_BAG_0, slot))
for (uint8 i = 0; i < 4; ++i)
if (slots[i] == slot)
return slot;
}
else
{
// search free slot at first
for (uint8 i = 0; i < 4; ++i)
if (slots[i] != NULL_SLOT && !GetItemByPos(INVENTORY_SLOT_BAG_0, slots[i]))
// in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
if (slots[i] != EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
return slots[i];
// if not found free and can swap return first appropriate from used
for (uint8 i = 0; i < 4; ++i)
if (slots[i] != NULL_SLOT && swap)
return slots[i];
}
// no free position
return NULL_SLOT;
}
InventoryResult Player::CanUnequipItems(uint32 item, uint32 count) const
{
uint32 tempcount = 0;
InventoryResult res = EQUIP_ERR_OK;
for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->GetEntry() == item)
{
InventoryResult ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
if (ires == EQUIP_ERR_OK)
{
tempcount += pItem->GetCount();
if (tempcount >= count)
return EQUIP_ERR_OK;
}
else
res = ires;
}
for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->GetEntry() == item)
{
tempcount += pItem->GetCount();
if (tempcount >= count)
return EQUIP_ERR_OK;
}
for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->GetEntry() == item)
{
tempcount += pItem->GetCount();
if (tempcount >= count)
return EQUIP_ERR_OK;
}
for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
if (Bag* pBag = GetBagByPos(i))
for (uint32 j = 0; j < pBag->GetBagSize(); ++j)
if (Item* pItem = GetItemByPos(i, j))
if (pItem->GetEntry() == item)
{
tempcount += pItem->GetCount();
if (tempcount >= count)
return EQUIP_ERR_OK;
}
// not found req. item count and have unequippable items
return res;
}
uint32 Player::GetItemCount(uint32 item, bool inBankAlso, Item* skipItem) const
{
uint32 count = 0;
for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem != skipItem && pItem->GetEntry() == item)
count += pItem->GetCount();
for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem != skipItem && pItem->GetEntry() == item)
count += pItem->GetCount();
for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
if (Bag* pBag = GetBagByPos(i))
count += pBag->GetItemCount(item, skipItem);
if (skipItem && skipItem->GetTemplate()->GemProperties)
for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem != skipItem && pItem->GetTemplate()->Socket[0].Color)
count += pItem->GetGemCountWithID(item);
if (inBankAlso)
{
// checking every item from 39 to 74 (including bank bags)
for (uint8 i = BANK_SLOT_ITEM_START; i < BANK_SLOT_BAG_END; ++i)
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem != skipItem && pItem->GetEntry() == item)
count += pItem->GetCount();
for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
if (Bag* pBag = GetBagByPos(i))
count += pBag->GetItemCount(item, skipItem);
if (skipItem && skipItem->GetTemplate()->GemProperties)
for (uint8 i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem != skipItem && pItem->GetTemplate()->Socket[0].Color)
count += pItem->GetGemCountWithID(item);
}
return count;
}
uint32 Player::GetItemCountWithLimitCategory(uint32 limitCategory, Item* skipItem) const
{
uint32 count = 0;
for (int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem != skipItem)
if (ItemTemplate const* pProto = pItem->GetTemplate())
if (pProto->ItemLimitCategory == limitCategory)
count += pItem->GetCount();
for (int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem != skipItem)
if (ItemTemplate const* pProto = pItem->GetTemplate())
if (pProto->ItemLimitCategory == limitCategory)
count += pItem->GetCount();
for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
if (Bag* pBag = GetBagByPos(i))
count += pBag->GetItemCountWithLimitCategory(limitCategory, skipItem);
for (int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_BAG_END; ++i)
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem != skipItem)
if (ItemTemplate const* pProto = pItem->GetTemplate())
if (pProto->ItemLimitCategory == limitCategory)
count += pItem->GetCount();
for (int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
if (Bag* pBag = GetBagByPos(i))
count += pBag->GetItemCountWithLimitCategory(limitCategory, skipItem);
return count;
}
Item* Player::GetItemByGuid(ObjectGuid guid) const
{
for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->GetGUID() == guid)
return pItem;
for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->GetGUID() == guid)
return pItem;
for (int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_BAG_END; ++i)
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->GetGUID() == guid)
return pItem;
for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
if (Bag* pBag = GetBagByPos(i))
for (uint32 j = 0; j < pBag->GetBagSize(); ++j)
if (Item* pItem = pBag->GetItemByPos(j))
if (pItem->GetGUID() == guid)
return pItem;
for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
if (Bag* pBag = GetBagByPos(i))
for (uint32 j = 0; j < pBag->GetBagSize(); ++j)
if (Item* pItem = pBag->GetItemByPos(j))
if (pItem->GetGUID() == guid)
return pItem;
return nullptr;
}
Item* Player::GetItemByPos(uint16 pos) const
{
uint8 bag = pos >> 8;
uint8 slot = pos & 255;
return GetItemByPos(bag, slot);
}
Item* Player::GetItemByPos(uint8 bag, uint8 slot) const
{
if (bag == INVENTORY_SLOT_BAG_0 && (slot < BANK_SLOT_BAG_END || (slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)))
return m_items[slot];
if (Bag* pBag = GetBagByPos(bag))
return pBag->GetItemByPos(slot);
return nullptr;
}
//Does additional check for disarmed weapons
Item* Player::GetUseableItemByPos(uint8 bag, uint8 slot) const
{
if (!CanUseAttackType(GetAttackBySlot(slot)))
return nullptr;
return GetItemByPos(bag, slot);
}
Bag* Player::GetBagByPos(uint8 bag) const
{
if ((bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
|| (bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END))
if (Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, bag))
return item->ToBag();
return nullptr;
}
uint32 Player::GetFreeInventorySpace() const
{
uint32 freeSpace = 0;
// Check backpack
for (uint8 slot = INVENTORY_SLOT_ITEM_START; slot < INVENTORY_SLOT_ITEM_END; ++slot)
{
Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
if (!item)
freeSpace += 1;
}
// Check bags
for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
{
if (Bag* bag = GetBagByPos(i))
freeSpace += bag->GetFreeSlots();
}
return freeSpace;
}
Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable /*= false*/) const
{
uint8 slot;
switch (attackType)
{
case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
default: return nullptr;
}
Item* item;
if (useable)
item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, slot);
else
item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
if (!item || item->GetTemplate()->Class != ITEM_CLASS_WEAPON)
return nullptr;
if (!useable)
return item;
if (item->IsBroken() || IsInFeralForm())
return nullptr;
return item;
}
Item* Player::GetShield(bool useable) const
{
Item* item;
if (useable)
item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
else
item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
if (!item || item->GetTemplate()->Class != ITEM_CLASS_ARMOR)
return nullptr;
if (!useable)
return item;
if (item->IsBroken())
return nullptr;
return item;
}
WeaponAttackType Player::GetAttackBySlot(uint8 slot)
{
switch (slot)
{
case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
default: return MAX_ATTACK;
}
}
bool Player::IsInventoryPos(uint8 bag, uint8 slot)
{
if (bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT)
return true;
if (bag == INVENTORY_SLOT_BAG_0 && (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END))
return true;
if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
return true;
if (bag == INVENTORY_SLOT_BAG_0 && (slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END))
return true;
return false;
}
bool Player::IsEquipmentPos(uint8 bag, uint8 slot)
{
if (bag == INVENTORY_SLOT_BAG_0 && (slot < EQUIPMENT_SLOT_END))
return true;
if (bag == INVENTORY_SLOT_BAG_0 && (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END))
return true;
return false;
}
bool Player::IsBankPos(uint8 bag, uint8 slot)
{
if (bag == INVENTORY_SLOT_BAG_0 && (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END))
return true;
if (bag == INVENTORY_SLOT_BAG_0 && (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END))
return true;
if (bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END)
return true;
return false;
}
bool Player::IsBagPos(uint16 pos)
{
uint8 bag = pos >> 8;
uint8 slot = pos & 255;
if (bag == INVENTORY_SLOT_BAG_0 && (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END))
return true;
if (bag == INVENTORY_SLOT_BAG_0 && (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END))
return true;
return false;
}
bool Player::IsValidPos(uint8 bag, uint8 slot, bool explicit_pos) const
{
// post selected
if (bag == NULL_BAG && !explicit_pos)
return true;
if (bag == INVENTORY_SLOT_BAG_0)
{
// any post selected
if (slot == NULL_SLOT && !explicit_pos)
return true;
// equipment
if (slot < EQUIPMENT_SLOT_END)
return true;
// bag equip slots
if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
return true;
// backpack slots
if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
return true;
// keyring slots
if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
return true;
// bank main slots
if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
return true;
// bank bag slots
if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
return true;
return false;
}
// bag content slots
// bank bag content slots
if (Bag* pBag = GetBagByPos(bag))
{
// any post selected
if (slot == NULL_SLOT && !explicit_pos)
return true;
return slot < pBag->GetBagSize();
}
// where this?
return false;
}
bool Player::HasItemCount(uint32 item, uint32 count, bool inBankAlso) const
{
uint32 tempcount = 0;
for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
{
Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
if (pItem && pItem->GetEntry() == item && !pItem->IsInTrade())
{
tempcount += pItem->GetCount();
if (tempcount >= count)
return true;
}
}
for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
{
Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
if (pItem && pItem->GetEntry() == item && !pItem->IsInTrade())
{
tempcount += pItem->GetCount();
if (tempcount >= count)
return true;
}
}
for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
{
if (Bag* pBag = GetBagByPos(i))
{
for (uint32 j = 0; j < pBag->GetBagSize(); j++)
{
Item* pItem = GetItemByPos(i, j);
if (pItem && pItem->GetEntry() == item && !pItem->IsInTrade())
{
tempcount += pItem->GetCount();
if (tempcount >= count)
return true;
}
}
}
}
if (inBankAlso)
{
for (uint8 i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
{
Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
if (pItem && pItem->GetEntry() == item && !pItem->IsInTrade())
{
tempcount += pItem->GetCount();
if (tempcount >= count)
return true;
}
}
for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
{
if (Bag* pBag = GetBagByPos(i))
{
for (uint32 j = 0; j < pBag->GetBagSize(); j++)
{
Item* pItem = GetItemByPos(i, j);
if (pItem && pItem->GetEntry() == item && !pItem->IsInTrade())
{
tempcount += pItem->GetCount();
if (tempcount >= count)
return true;
}
}
}
}
}
return false;
}
bool Player::HasItemOrGemWithIdEquipped(uint32 item, uint32 count, uint8 except_slot) const
{
uint32 tempcount = 0;
for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
{
if (i == except_slot)
continue;
Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
if (pItem && pItem->GetEntry() == item)
{
tempcount += pItem->GetCount();
if (tempcount >= count)
return true;
}
}
ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(item);
if (pProto && pProto->GemProperties)
{
for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
{
if (i == except_slot)
continue;
Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
if (pItem && pItem->GetTemplate()->Socket[0].Color)
{
tempcount += pItem->GetGemCountWithID(item);
if (tempcount >= count)
return true;
}
}
}
return false;
}
bool Player::HasItemWithLimitCategoryEquipped(uint32 limitCategory, uint32 count, uint8 except_slot) const
{
uint32 tempcount = 0;
for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
{
if (i == except_slot)
continue;
Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
if (!pItem)
continue;
ItemTemplate const* pProto = pItem->GetTemplate();
if (!pProto)
continue;
if (pProto->ItemLimitCategory == limitCategory)
{
tempcount += pItem->GetCount();
if (tempcount >= count)
return true;
}
}
return false;
}
bool Player::HasGemWithLimitCategoryEquipped(uint32 limitCategory, uint32 count, uint8 except_slot) const
{
uint32 tempcount = 0;
for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
{
if (i == except_slot)
continue;
Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
if (!pItem)
continue;
ItemTemplate const* pProto = pItem->GetTemplate();
if (!pProto)
continue;
if (pProto->Socket[0].Color || pItem->GetEnchantmentId(PRISMATIC_ENCHANTMENT_SLOT))
{
tempcount += pItem->GetGemCountWithLimitCategory(limitCategory);
if (tempcount >= count)
return true;
}
}
return false;
}
InventoryResult Player::CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count /*= nullptr*/, uint32* itemLimitCategory /*= nullptr*/) const
{
ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(entry);
if (!pProto)
{
if (no_space_count)
*no_space_count = count;
return EQUIP_ERR_ITEM_MAX_COUNT;
}
if (pItem && pItem->m_lootGenerated)
return EQUIP_ERR_LOOT_GONE;
// no maximum
if ((pProto->MaxCount <= 0 && pProto->ItemLimitCategory == 0) || pProto->MaxCount == 2147483647)
return EQUIP_ERR_OK;
if (pProto->MaxCount > 0)
{
uint32 curcount = GetItemCount(pProto->ItemId, true, pItem);
if (curcount + count > uint32(pProto->MaxCount))
{
if (no_space_count)
*no_space_count = count + curcount - pProto->MaxCount;
return EQUIP_ERR_ITEM_MAX_COUNT;
}
}
// check unique-equipped limit
if (pProto->ItemLimitCategory)
{
ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(pProto->ItemLimitCategory);
if (!limitEntry)
{
if (no_space_count)
*no_space_count = count;
return EQUIP_ERR_NOT_EQUIPPABLE;
}
if (limitEntry->Flags == ITEM_LIMIT_CATEGORY_MODE_HAVE)
{
uint32 curcount = GetItemCountWithLimitCategory(pProto->ItemLimitCategory, pItem);
if (curcount + count > uint32(limitEntry->Quantity))
{
if (no_space_count)
*no_space_count = count + curcount - limitEntry->Quantity;
if (itemLimitCategory)
*itemLimitCategory = pProto->ItemLimitCategory;
return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED_IS;
}
}
}
return EQUIP_ERR_OK;
}
InventoryResult Player::CanTakeMoreSimilarItems(Item* pItem, uint32* itemLimitCategory /*= nullptr*/) const
{
return CanTakeMoreSimilarItems(pItem->GetEntry(), pItem->GetCount(), pItem, nullptr, itemLimitCategory);
}
InventoryResult Player::CanStoreNewItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, uint32 item, uint32 count, uint32* no_space_count /*= nullptr*/) const
{
return CanStoreItem(bag, slot, dest, item, count, nullptr, false, no_space_count);
}
InventoryResult Player::CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, Item* pItem, bool swap /*= false*/) const
{
if (!pItem)
return EQUIP_ERR_ITEM_NOT_FOUND;
uint32 count = pItem->GetCount();
return CanStoreItem(bag, slot, dest, pItem->GetEntry(), count, pItem, swap, nullptr);
}
bool Player::HasItemTotemCategory(uint32 TotemCategory) const
{
Item* pItem;
for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
{
pItem = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, i);
if (pItem && IsTotemCategoryCompatiableWith(pItem->GetTemplate()->TotemCategory, TotemCategory))
return true;
}
for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
{
pItem = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, i);
if (pItem && IsTotemCategoryCompatiableWith(pItem->GetTemplate()->TotemCategory, TotemCategory))
return true;
}
for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (Bag* pBag = GetBagByPos(i))
{
for (uint32 j = 0; j < pBag->GetBagSize(); ++j)
{
pItem = GetUseableItemByPos(i, j);
if (pItem && IsTotemCategoryCompatiableWith(pItem->GetTemplate()->TotemCategory, TotemCategory))
return true;
}
}
}
return false;
}
InventoryResult Player::CanStoreItem_InSpecificSlot(uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemTemplate const* pProto, uint32& count, bool swap, Item* pSrcItem) const
{
Item* pItem2 = GetItemByPos(bag, slot);
// ignore move item (this slot will be empty at move)
if (pItem2 == pSrcItem)
pItem2 = nullptr;
uint32 need_space;
if (pSrcItem && pSrcItem->IsNotEmptyBag() && !IsBagPos(uint16(bag) << 8 | slot))
return EQUIP_ERR_DESTROY_NONEMPTY_BAG;
// empty specific slot - check item fit to slot
if (!pItem2 || swap)
{
if (bag == INVENTORY_SLOT_BAG_0)
{
// keyring case
if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
return EQUIP_ERR_WRONG_BAG_TYPE;
// currencytoken case
if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->IsCurrencyToken()))
return EQUIP_ERR_WRONG_BAG_TYPE;
// prevent cheating
if ((slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END) || slot >= PLAYER_SLOT_END)
return EQUIP_ERR_WRONG_BAG_TYPE;
}
else
{
Bag* pBag = GetBagByPos(bag);
if (!pBag)
return EQUIP_ERR_WRONG_BAG_TYPE;
ItemTemplate const* pBagProto = pBag->GetTemplate();
if (!pBagProto)
return EQUIP_ERR_WRONG_BAG_TYPE;
if (slot >= pBagProto->ContainerSlots)
return EQUIP_ERR_WRONG_BAG_TYPE;
if (!ItemCanGoIntoBag(pProto, pBagProto))
return EQUIP_ERR_WRONG_BAG_TYPE;
}
// non empty stack with space
need_space = pProto->GetMaxStackSize();
}
// non empty slot, check item type
else
{
// can be merged at least partly
InventoryResult res = pItem2->CanBeMergedPartlyWith(pProto);
if (res != EQUIP_ERR_OK)
return res;
// free stack space or infinity
need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
}
if (need_space > count)
need_space = count;
ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
if (!newPosition.isContainedIn(dest))
{
dest.push_back(newPosition);
count -= need_space;
}
return EQUIP_ERR_OK;
}
InventoryResult Player::CanStoreItem_InBag(uint8 bag, ItemPosCountVec &dest, ItemTemplate const* pProto, uint32& count, bool merge, bool non_specialized, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot) const
{
// skip specific bag already processed in first called CanStoreItem_InBag
if (bag == skip_bag)
return EQUIP_ERR_WRONG_BAG_TYPE;
// skip non-existing bag or self targeted bag
Bag* pBag = GetBagByPos(bag);
if (!pBag || pBag == pSrcItem)
return EQUIP_ERR_WRONG_BAG_TYPE;
if (pSrcItem && pSrcItem->IsNotEmptyBag())
return EQUIP_ERR_DESTROY_NONEMPTY_BAG;
ItemTemplate const* pBagProto = pBag->GetTemplate();
if (!pBagProto)
return EQUIP_ERR_WRONG_BAG_TYPE;
// specialized bag mode or non-specialized
if (non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER))
return EQUIP_ERR_WRONG_BAG_TYPE;
if (!ItemCanGoIntoBag(pProto, pBagProto))
return EQUIP_ERR_WRONG_BAG_TYPE;
for (uint32 j = 0; j < pBag->GetBagSize(); j++)
{
// skip specific slot already processed in first called CanStoreItem_InSpecificSlot
if (j == skip_slot)
continue;
Item* pItem2 = GetItemByPos(bag, j);
// ignore move item (this slot will be empty at move)
if (pItem2 == pSrcItem)
pItem2 = nullptr;
// if merge skip empty, if !merge skip non-empty
if ((pItem2 != nullptr) != merge)
continue;
uint32 need_space = pProto->GetMaxStackSize();
if (pItem2)
{
// can be merged at least partly
if (pItem2->CanBeMergedPartlyWith(pProto) != EQUIP_ERR_OK)
continue;
// descrease at current stacksize
need_space -= pItem2->GetCount();
}
if (need_space > count)
need_space = count;
ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
if (!newPosition.isContainedIn(dest))
{
dest.push_back(newPosition);
count -= need_space;
if (count==0)
return EQUIP_ERR_OK;
}
}
return EQUIP_ERR_OK;
}
InventoryResult Player::CanStoreItem_InInventorySlots(uint8 slot_begin, uint8 slot_end, ItemPosCountVec &dest, ItemTemplate const* pProto, uint32& count, bool merge, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot) const
{
//this is never called for non-bag slots so we can do this
if (pSrcItem && pSrcItem->IsNotEmptyBag())
return EQUIP_ERR_DESTROY_NONEMPTY_BAG;
for (uint32 j = slot_begin; j < slot_end; j++)
{
// skip specific slot already processed in first called CanStoreItem_InSpecificSlot
if (INVENTORY_SLOT_BAG_0 == skip_bag && j == skip_slot)
continue;
Item* pItem2 = GetItemByPos(INVENTORY_SLOT_BAG_0, j);
// ignore move item (this slot will be empty at move)
if (pItem2 == pSrcItem)
pItem2 = nullptr;
// if merge skip empty, if !merge skip non-empty
if ((pItem2 != nullptr) != merge)
continue;
uint32 need_space = pProto->GetMaxStackSize();
if (pItem2)
{
// can be merged at least partly
if (pItem2->CanBeMergedPartlyWith(pProto) != EQUIP_ERR_OK)
continue;
// descrease at current stacksize
need_space -= pItem2->GetCount();
}
if (need_space > count)
need_space = count;
ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
if (!newPosition.isContainedIn(dest))
{
dest.push_back(newPosition);
count -= need_space;
if (count==0)
return EQUIP_ERR_OK;
}
}
return EQUIP_ERR_OK;
}
InventoryResult Player::CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item* pItem, bool swap, uint32* no_space_count) const
{
TC_LOG_DEBUG("entities.player.items", "Player::CanStoreItem: Bag: {}, Slot: {}, Item: {}, Count: {}", bag, slot, entry, count);
ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(entry);
if (!pProto)
{
if (no_space_count)
*no_space_count = count;
return swap ? EQUIP_ERR_CANT_SWAP : EQUIP_ERR_ITEM_NOT_FOUND;
}
if (pItem)
{
// swapping/merging with currently looted item
if (GetLootGUID() == pItem->GetGUID())
{
if (no_space_count)
*no_space_count = count;
return EQUIP_ERR_LOOT_GONE;
}
if (pItem->IsBindedNotWith(this))
{
if (no_space_count)
*no_space_count = count;
return EQUIP_ERR_NOT_OWNER;
}
}
// check count of items (skip for auto move for same player from bank)
uint32 no_similar_count = 0; // can't store this amount similar items
InventoryResult res = CanTakeMoreSimilarItems(entry, count, pItem, &no_similar_count);
if (res != EQUIP_ERR_OK)
{
if (count == no_similar_count)
{
if (no_space_count)
*no_space_count = no_similar_count;
return res;
}
count -= no_similar_count;
}
// in specific slot
if (bag != NULL_BAG && slot != NULL_SLOT)
{
res = CanStoreItem_InSpecificSlot(bag, slot, dest, pProto, count, swap, pItem);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_ITEM_MAX_COUNT;
}
}
// not specific slot or have space for partly store only in specific slot
// in specific bag
if (bag != NULL_BAG)
{
// search stack in bag for merge to
if (pProto->Stackable != 1)
{
if (bag == INVENTORY_SLOT_BAG_0) // inventory
{
res = CanStoreItem_InInventorySlots(KEYRING_SLOT_START, CURRENCYTOKEN_SLOT_END, dest, pProto, count, true, pItem, bag, slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_ITEM_MAX_COUNT;
}
res = CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START, INVENTORY_SLOT_ITEM_END, dest, pProto, count, true, pItem, bag, slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_ITEM_MAX_COUNT;
}
}
else // equipped bag
{
// we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
res = CanStoreItem_InBag(bag, dest, pProto, count, true, false, pItem, NULL_BAG, slot);
if (res != EQUIP_ERR_OK)
res = CanStoreItem_InBag(bag, dest, pProto, count, true, true, pItem, NULL_BAG, slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_ITEM_MAX_COUNT;
}
}
}
// search free slot in bag for place to
if (bag == INVENTORY_SLOT_BAG_0) // inventory
{
// search free slot - keyring case
if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
{
uint32 keyringSize = GetMaxKeyringSize();
res = CanStoreItem_InInventorySlots(KEYRING_SLOT_START, KEYRING_SLOT_START+keyringSize, dest, pProto, count, false, pItem, bag, slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_ITEM_MAX_COUNT;
}
res = CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START, CURRENCYTOKEN_SLOT_END, dest, pProto, count, false, pItem, bag, slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_ITEM_MAX_COUNT;
}
}
else if (pProto->IsCurrencyToken())
{
res = CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START, CURRENCYTOKEN_SLOT_END, dest, pProto, count, false, pItem, bag, slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_ITEM_MAX_COUNT;
}
}
res = CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START, INVENTORY_SLOT_ITEM_END, dest, pProto, count, false, pItem, bag, slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_ITEM_MAX_COUNT;
}
}
else // equipped bag
{
res = CanStoreItem_InBag(bag, dest, pProto, count, false, false, pItem, NULL_BAG, slot);
if (res != EQUIP_ERR_OK)
res = CanStoreItem_InBag(bag, dest, pProto, count, false, true, pItem, NULL_BAG, slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_ITEM_MAX_COUNT;
}
}
}
// not specific bag or have space for partly store only in specific bag
// search stack for merge to
if (pProto->Stackable != 1)
{
res = CanStoreItem_InInventorySlots(KEYRING_SLOT_START, CURRENCYTOKEN_SLOT_END, dest, pProto, count, true, pItem, bag, slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_ITEM_MAX_COUNT;
}
res = CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START, INVENTORY_SLOT_ITEM_END, dest, pProto, count, true, pItem, bag, slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_ITEM_MAX_COUNT;
}
if (pProto->BagFamily)
{
for (uint32 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
{
res = CanStoreItem_InBag(i, dest, pProto, count, true, false, pItem, bag, slot);
if (res != EQUIP_ERR_OK)
continue;
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_ITEM_MAX_COUNT;
}
}
}
for (uint32 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
{
res = CanStoreItem_InBag(i, dest, pProto, count, true, true, pItem, bag, slot);
if (res != EQUIP_ERR_OK)
continue;
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_ITEM_MAX_COUNT;
}
}
}
// search free slot - special bag case
if (pProto->BagFamily)
{
if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
{
uint32 keyringSize = GetMaxKeyringSize();
res = CanStoreItem_InInventorySlots(KEYRING_SLOT_START, KEYRING_SLOT_START+keyringSize, dest, pProto, count, false, pItem, bag, slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_ITEM_MAX_COUNT;
}
}
else if (pProto->IsCurrencyToken())
{
res = CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START, CURRENCYTOKEN_SLOT_END, dest, pProto, count, false, pItem, bag, slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_ITEM_MAX_COUNT;
}
}
for (uint32 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
{
res = CanStoreItem_InBag(i, dest, pProto, count, false, false, pItem, bag, slot);
if (res != EQUIP_ERR_OK)
continue;
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_ITEM_MAX_COUNT;
}
}
}
if (pItem && pItem->IsNotEmptyBag())
return EQUIP_ERR_BAG_IN_BAG;
// search free slot
res = CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START, INVENTORY_SLOT_ITEM_END, dest, pProto, count, false, pItem, bag, slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_ITEM_MAX_COUNT;
}
for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
{
res = CanStoreItem_InBag(i, dest, pProto, count, false, true, pItem, bag, slot);
if (res != EQUIP_ERR_OK)
continue;
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_ITEM_MAX_COUNT;
}
}
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_INV_FULL;
}
//////////////////////////////////////////////////////////////////////////
InventoryResult Player::CanStoreItems(Item** items, int count, uint32* itemLimitCategory) const
{
Item* item2;
// fill space tables, creating a mock-up of the player's inventory
// counts
uint32 inventoryCounts[INVENTORY_SLOT_ITEM_END - INVENTORY_SLOT_ITEM_START] = {};
uint32 bagCounts[INVENTORY_SLOT_BAG_END - INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE] = {};
uint32 keyringCounts[KEYRING_SLOT_END - KEYRING_SLOT_START] = {};
uint32 currencyCounts[CURRENCYTOKEN_SLOT_END - CURRENCYTOKEN_SLOT_START] = {};
// Item pointers
Item* inventoryPointers[INVENTORY_SLOT_ITEM_END - INVENTORY_SLOT_ITEM_START] = {};
Item* bagPointers[INVENTORY_SLOT_BAG_END - INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE] = {};
Item* keyringPointers[KEYRING_SLOT_END - KEYRING_SLOT_START] = {};
Item* currencyPointers[CURRENCYTOKEN_SLOT_END - CURRENCYTOKEN_SLOT_START] = {};
// filling inventory
for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
{
// build items in stock backpack
item2 = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
if (item2 && !item2->IsInTrade())
{
inventoryCounts[i - INVENTORY_SLOT_ITEM_START] = item2->GetCount();
inventoryPointers[i - INVENTORY_SLOT_ITEM_START] = item2;
}
}
for (uint8 i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
{
// build items in key ring 'bag'
item2 = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
if (item2 && !item2->IsInTrade())
{
keyringCounts[i - KEYRING_SLOT_START] = item2->GetCount();
keyringPointers[i - KEYRING_SLOT_START] = item2;
}
}
for (uint8 i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; i++)
{
// build items in currency 'bag'
item2 = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
if (item2 && !item2->IsInTrade())
{
currencyCounts[i - CURRENCYTOKEN_SLOT_START] = item2->GetCount();
currencyPointers[i - CURRENCYTOKEN_SLOT_START] = item2;
}
}
for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
if (Bag* pBag = GetBagByPos(i))
for (uint32 j = 0; j < pBag->GetBagSize(); j++)
{
// build item counts in equippable bags
item2 = GetItemByPos(i, j);
if (item2 && !item2->IsInTrade())
{
bagCounts[i - INVENTORY_SLOT_BAG_START][j] = item2->GetCount();
bagPointers[i - INVENTORY_SLOT_BAG_START][j] = item2;
}
}
// check free space for all items that we wish to add
for (int k = 0; k < count; ++k)
{
// Incoming item
Item* item = items[k];
// no item
if (!item)
continue;
uint32_t remaining_count = item->GetCount();
TC_LOG_DEBUG("entities.player.items", "Player::CanStoreItems: Player '{}' ({}), Index: {} ItemID: {}, Count: {}",
GetName(), GetGUID().ToString(), k + 1, item->GetEntry(), remaining_count);
ItemTemplate const* pProto = item->GetTemplate();
// strange item
if (!pProto)
return EQUIP_ERR_ITEM_NOT_FOUND;
if (item->m_lootGenerated || GetLootGUID() == item->GetGUID())
return EQUIP_ERR_LOOT_GONE;
// item it 'bind'
if (item->IsBindedNotWith(this))
return EQUIP_ERR_NOT_OWNER;
ItemTemplate const* pBagProto;
// item is 'one item only'
InventoryResult res = CanTakeMoreSimilarItems(item, itemLimitCategory);
if (res != EQUIP_ERR_OK)
return res;
// search stack for merge to
if (pProto->Stackable != 1)
{
bool b_found = false;
for (uint8 t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; ++t)
{
item2 = keyringPointers[t-KEYRING_SLOT_START];
if (item2 && item2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && keyringCounts[t-KEYRING_SLOT_START] < pProto->GetMaxStackSize())
{
keyringCounts[t-KEYRING_SLOT_START] += remaining_count;
remaining_count = keyringCounts[t-KEYRING_SLOT_START] < pProto->GetMaxStackSize() ? 0 : keyringCounts[t-KEYRING_SLOT_START] - pProto->GetMaxStackSize();
b_found = remaining_count == 0;
// if no pieces of the stack remain, then stop checking keyring
if (b_found)
break;
}
}
if (b_found)
continue;
for (int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
{
item2 = currencyPointers[t-CURRENCYTOKEN_SLOT_START];
if (item2 && item2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && currencyCounts[t-CURRENCYTOKEN_SLOT_START] < pProto->GetMaxStackSize())
{
currencyCounts[t-CURRENCYTOKEN_SLOT_START] += remaining_count;
remaining_count = currencyCounts[t-CURRENCYTOKEN_SLOT_START] < pProto->GetMaxStackSize() ? 0 : currencyCounts[t-CURRENCYTOKEN_SLOT_START] - pProto->GetMaxStackSize();
b_found = remaining_count == 0;
// if no pieces of the stack remain, then stop checking currency 'bag'
if (b_found)
break;
}
}
if (b_found)
continue;
for (int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
{
item2 = inventoryPointers[t-INVENTORY_SLOT_ITEM_START];
if (item2 && item2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inventoryCounts[t-INVENTORY_SLOT_ITEM_START] < pProto->GetMaxStackSize())
{
inventoryCounts[t-INVENTORY_SLOT_ITEM_START] += remaining_count;
remaining_count = inventoryCounts[t-INVENTORY_SLOT_ITEM_START] < pProto->GetMaxStackSize() ? 0 : inventoryCounts[t-INVENTORY_SLOT_ITEM_START] - pProto->GetMaxStackSize();
b_found = remaining_count == 0;
// if no pieces of the stack remain, then stop checking stock bag
if (b_found)
break;
}
}
if (b_found)
continue;
for (int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
{
if (Bag* bag = GetBagByPos(t))
{
if (!ItemCanGoIntoBag(item->GetTemplate(), bag->GetTemplate()))
continue;
for (uint32 j = 0; j < bag->GetBagSize(); j++)
{
item2 = bagPointers[t-INVENTORY_SLOT_BAG_START][j];
if (item2 && item2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && bagCounts[t-INVENTORY_SLOT_BAG_START][j] < pProto->GetMaxStackSize())
{
// add count to stack so that later items in the list do not double-book
bagCounts[t-INVENTORY_SLOT_BAG_START][j] += remaining_count;
remaining_count = bagCounts[t-INVENTORY_SLOT_BAG_START][j] < pProto->GetMaxStackSize() ? 0 : bagCounts[t-INVENTORY_SLOT_BAG_START][j] - pProto->GetMaxStackSize();
b_found = remaining_count == 0;
// if no pieces of the stack remain, then stop checking equippable bags
if (b_found)
break;
}
}
}
}
if (b_found)
continue;
}
// special bag case
if (pProto->BagFamily)
{
bool b_found = false;
if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
{
uint32 keyringSize = GetMaxKeyringSize();
for (uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
{
if (keyringCounts[t-KEYRING_SLOT_START] == 0)
{
keyringCounts[t-KEYRING_SLOT_START] = remaining_count;
keyringPointers[t-KEYRING_SLOT_START] = item;
b_found = true;
break;
}
}
}
if (b_found)
continue;
if (pProto->IsCurrencyToken())
{
for (uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
{
if (currencyCounts[t-CURRENCYTOKEN_SLOT_START] == 0)
{
currencyCounts[t-CURRENCYTOKEN_SLOT_START] = remaining_count;
currencyPointers [t-CURRENCYTOKEN_SLOT_START] = item;
b_found = true;
break;
}
}
}
if (b_found)
continue;
for (int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
{
if (Bag* bag = GetBagByPos(t))
{
pBagProto = bag->GetTemplate();
// not plain container check
if (pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
ItemCanGoIntoBag(pProto, pBagProto))
{
for (uint32 j = 0; j < bag->GetBagSize(); j++)
{
if (bagCounts[t-INVENTORY_SLOT_BAG_START][j] == 0)
{
bagCounts[t-INVENTORY_SLOT_BAG_START][j] = remaining_count;
bagPointers[t-INVENTORY_SLOT_BAG_START][j] = item;
b_found = true;
break;
}
}
}
}
}
if (b_found)
continue;
}
// search free slot
bool b_found = false;
for (int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
{
if (inventoryCounts[t-INVENTORY_SLOT_ITEM_START] == 0)
{
inventoryCounts[t-INVENTORY_SLOT_ITEM_START] = remaining_count;
inventoryPointers[t-INVENTORY_SLOT_ITEM_START] = item;
b_found = true;
break;
}
}
if (b_found)
continue;
// search free slot in bags
for (uint8 t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
{
if (Bag* bag = GetBagByPos(t))
{
pBagProto = bag->GetTemplate();
// special bag already checked
if (pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER))
continue;
for (uint32 j = 0; j < bag->GetBagSize(); j++)
{
if (bagCounts[t-INVENTORY_SLOT_BAG_START][j] == 0)
{
bagCounts[t-INVENTORY_SLOT_BAG_START][j] = remaining_count;
bagPointers[t-INVENTORY_SLOT_BAG_START][j] = item;
b_found = true;
break;
}
}
}
}
// if no free slot found for all pieces of the item, then return an error
if (!b_found)
return EQUIP_ERR_BAG_FULL;
}
return EQUIP_ERR_OK;
}
//////////////////////////////////////////////////////////////////////////
InventoryResult Player::CanEquipNewItem(uint8 slot, uint16 &dest, uint32 item, bool swap) const
{
dest = 0;
Item* pItem = Item::CreateItem(item, 1, this);
if (pItem)
{
InventoryResult result = CanEquipItem(slot, dest, pItem, swap);
delete pItem;
return result;
}
return EQUIP_ERR_ITEM_NOT_FOUND;
}
InventoryResult Player::CanEquipItem(uint8 slot, uint16 &dest, Item* pItem, bool swap, bool not_loading) const
{
dest = 0;
if (pItem)
{
TC_LOG_DEBUG("entities.player.items", "Player::CanEquipItem: Player '{}' ({}), Slot: {}, Item: {}, Count: {}",
GetName(), GetGUID().ToString(), slot, pItem->GetEntry(), pItem->GetCount());
ItemTemplate const* pProto = pItem->GetTemplate();
if (pProto)
{
if (GetLootGUID() == pItem->GetGUID())
return EQUIP_ERR_LOOT_GONE;
if (pItem->IsBindedNotWith(this))
return EQUIP_ERR_NOT_OWNER;
// check count of items (skip for auto move for same player from bank)
InventoryResult res = CanTakeMoreSimilarItems(pItem);
if (res != EQUIP_ERR_OK)
return res;
// check this only in game
if (not_loading)
{
// May be here should be more stronger checks; STUNNED checked
// ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
if (HasUnitState(UNIT_STATE_STUNNED))
return EQUIP_ERR_GENERIC_STUNNED;
if (IsCharmed())
return EQUIP_ERR_CLIENT_LOCKED_OUT; // @todo is this the correct error?
// do not allow equipping gear except weapons, offhands, projectiles, relics in
// - combat
// - in-progress arenas
if (!pProto->CanChangeEquipStateInCombat())
{
if (IsInCombat())
return EQUIP_ERR_NOT_IN_COMBAT;
if (Battleground* bg = GetBattleground())
if (bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS)
return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
}
if (IsInCombat()&& (pProto->Class == ITEM_CLASS_WEAPON || pProto->InventoryType == INVTYPE_RELIC) && m_weaponChangeTimer != 0)
return EQUIP_ERR_CLIENT_LOCKED_OUT; // maybe exist better err
if (IsNonMeleeSpellCast(false))
return EQUIP_ERR_CLIENT_LOCKED_OUT;
}
ScalingStatDistributionEntry const* ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : 0;
// check allowed level (extend range to upper values if MaxLevel more or equal max player level, this let GM set high level with 1...max range items)
if (ssd && ssd->Maxlevel < DEFAULT_MAX_LEVEL && ssd->Maxlevel < GetLevel())
return EQUIP_ERR_NOT_EQUIPPABLE;
uint8 eslot = FindEquipSlot(pItem, slot, swap);
if (eslot == NULL_SLOT)
return EQUIP_ERR_NOT_EQUIPPABLE;
res = CanUseItem(pItem, not_loading);
if (res != EQUIP_ERR_OK)
return res;
if (!swap && GetItemByPos(INVENTORY_SLOT_BAG_0, eslot))
return EQUIP_ERR_NO_SLOT_AVAILABLE;
// if we are swapping 2 equiped items, CanEquipUniqueItem check
// should ignore the item we are trying to swap, and not the
// destination item. CanEquipUniqueItem should ignore destination
// item only when we are swapping weapon from bag
uint8 ignore = uint8(NULL_SLOT);
switch (eslot)
{
case EQUIPMENT_SLOT_MAINHAND:
ignore = EQUIPMENT_SLOT_OFFHAND;
break;
case EQUIPMENT_SLOT_OFFHAND:
ignore = EQUIPMENT_SLOT_MAINHAND;
break;
case EQUIPMENT_SLOT_FINGER1:
ignore = EQUIPMENT_SLOT_FINGER2;
break;
case EQUIPMENT_SLOT_FINGER2:
ignore = EQUIPMENT_SLOT_FINGER1;
break;
case EQUIPMENT_SLOT_TRINKET1:
ignore = EQUIPMENT_SLOT_TRINKET2;
break;
case EQUIPMENT_SLOT_TRINKET2:
ignore = EQUIPMENT_SLOT_TRINKET1;
break;
}
if (ignore == uint8(NULL_SLOT) || pItem != GetItemByPos(INVENTORY_SLOT_BAG_0, ignore))
ignore = eslot;
InventoryResult res2 = CanEquipUniqueItem(pItem, swap ? ignore : uint8(NULL_SLOT));
if (res2 != EQUIP_ERR_OK)
return res2;
// check unique-equipped special item classes
if (pProto->Class == ITEM_CLASS_QUIVER)
for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
if (Item* pBag = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pBag != pItem)
if (ItemTemplate const* pBagProto = pBag->GetTemplate())
if (pBagProto->Class == pProto->Class && (!swap || pBag->GetSlot() != eslot))
return (pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
? EQUIP_ERR_ONLY_ONE_AMMO
: EQUIP_ERR_ONLY_ONE_QUIVER;
uint32 type = pProto->InventoryType;
if (eslot == EQUIPMENT_SLOT_OFFHAND)
{
// Do not allow polearm to be equipped in the offhand (rare case for the only 1h polearm 41750)
if (type == INVTYPE_WEAPON && pProto->SubClass == ITEM_SUBCLASS_WEAPON_POLEARM)
return EQUIP_ERR_WRONG_SLOT;
else if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
{
if (!CanDualWield())
return EQUIP_ERR_2HSKILLNOTFOUND;
}
else if (type == INVTYPE_2HWEAPON)
{
if (!CanDualWield() || !CanTitanGrip(pItem))
return EQUIP_ERR_2HSKILLNOTFOUND;
}
if (IsTwoHandUsed())
return EQUIP_ERR_2HANDED_EQUIPPED;
}
// equip two-hand weapon case (with possible unequip 2 items)
if (eslot == EQUIPMENT_SLOT_MAINHAND)
{
if (!CanTitanGrip(pItem))
{
// offhand item must can be stored in inventory for offhand item and it also must be unequipped
Item* offItem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
ItemPosCountVec off_dest;
if (offItem && (!not_loading ||
CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND, false) != EQUIP_ERR_OK ||
CanStoreItem(NULL_BAG, NULL_SLOT, off_dest, offItem, false) != EQUIP_ERR_OK))
return swap ? EQUIP_ERR_CANT_SWAP : EQUIP_ERR_INV_FULL;
}
}
dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
return EQUIP_ERR_OK;
}
}
return !swap ? EQUIP_ERR_ITEM_NOT_FOUND : EQUIP_ERR_CANT_SWAP;
}
InventoryResult Player::CanUnequipItem(uint16 pos, bool swap) const
{
// Applied only to equipped items and bank bags
if (!IsEquipmentPos(pos) && !IsBagPos(pos))
return EQUIP_ERR_OK;
Item* pItem = GetItemByPos(pos);
// Applied only to existing equipped item
if (!pItem)
return EQUIP_ERR_OK;
TC_LOG_DEBUG("entities.player.items", "Player::CanUnequipItem: Player '{}' ({}), Slot: {}, Item: {}, Count: {}",
GetName(), GetGUID().ToString(), pos, pItem->GetEntry(), pItem->GetCount());
ItemTemplate const* pProto = pItem->GetTemplate();
if (!pProto)
return EQUIP_ERR_ITEM_NOT_FOUND;
if (GetLootGUID() == pItem->GetGUID())
return EQUIP_ERR_LOOT_GONE;
if (IsCharmed())
return EQUIP_ERR_CLIENT_LOCKED_OUT; // @todo is this the correct error?
// do not allow unequipping gear except weapons, offhands, projectiles, relics in
// - combat
// - in-progress arenas
if (!pProto->CanChangeEquipStateInCombat())
{
if (IsInCombat())
return EQUIP_ERR_NOT_IN_COMBAT;
if (Battleground* bg = GetBattleground())
if (bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS)
return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
}
if (!swap && pItem->IsNotEmptyBag())
return EQUIP_ERR_DESTROY_NONEMPTY_BAG;
return EQUIP_ERR_OK;
}
InventoryResult Player::CanBankItem(uint8 bag, uint8 slot, ItemPosCountVec &dest, Item* pItem, bool swap, bool not_loading) const
{
if (!pItem)
return swap ? EQUIP_ERR_CANT_SWAP : EQUIP_ERR_ITEM_NOT_FOUND;
uint32 count = pItem->GetCount();
TC_LOG_DEBUG("entities.player.items", "Player::CanBankItem: Player '{}' ({}), Bag: {}, Slot: {}, Item: {}, Count: {}",
GetName(), GetGUID().ToString(), bag, slot, pItem->GetEntry(), pItem->GetCount());
ItemTemplate const* pProto = pItem->GetTemplate();
if (!pProto)
return swap ? EQUIP_ERR_CANT_SWAP : EQUIP_ERR_ITEM_NOT_FOUND;
if (GetLootGUID() == pItem->GetGUID())
return EQUIP_ERR_LOOT_GONE;
if (pItem->IsBindedNotWith(this))
return EQUIP_ERR_NOT_OWNER;
// Currency tokens are not supposed to be swapped out of their hidden bag
uint8 pItemslot = pItem->GetSlot();
if (pItemslot >= CURRENCYTOKEN_SLOT_START && pItemslot < CURRENCYTOKEN_SLOT_END)
{
TC_LOG_ERROR("entities.player.cheat", "Possible hacking attempt: Player {} ({}) tried to move token [{} entry: {}] out of the currency bag!",
GetName(), GetGUID().ToString(), pItem->GetGUID().ToString(), pProto->ItemId);
return EQUIP_ERR_CANT_SWAP;
}
// check count of items (skip for auto move for same player from bank)
InventoryResult res = CanTakeMoreSimilarItems(pItem);
if (res != EQUIP_ERR_OK)
return res;
// in specific slot
if (bag != NULL_BAG && slot != NULL_SLOT)
{
if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
{
if (!pItem->IsBag())
return EQUIP_ERR_WRONG_SLOT;
if (slot - BANK_SLOT_BAG_START >= GetBankBagSlotCount())
return EQUIP_ERR_NO_BANK_SLOT;
res = CanUseItem(pItem, not_loading);
if (res != EQUIP_ERR_OK)
return res;
}
res = CanStoreItem_InSpecificSlot(bag, slot, dest, pProto, count, swap, pItem);
if (res != EQUIP_ERR_OK)
return res;
if (count == 0)
return EQUIP_ERR_OK;
}
// not specific slot or have space for partly store only in specific slot
// in specific bag
if (bag != NULL_BAG)
{
if (pItem->IsNotEmptyBag())
return EQUIP_ERR_BAG_IN_BAG;
// search stack in bag for merge to
if (pProto->Stackable != 1)
{
if (bag == INVENTORY_SLOT_BAG_0)
{
res = CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START, BANK_SLOT_ITEM_END, dest, pProto, count, true, pItem, bag, slot);
if (res != EQUIP_ERR_OK)
return res;
if (count == 0)
return EQUIP_ERR_OK;
}
else
{
res = CanStoreItem_InBag(bag, dest, pProto, count, true, false, pItem, NULL_BAG, slot);
if (res != EQUIP_ERR_OK)
res = CanStoreItem_InBag(bag, dest, pProto, count, true, true, pItem, NULL_BAG, slot);
if (res != EQUIP_ERR_OK)
return res;
if (count == 0)
return EQUIP_ERR_OK;
}
}
// search free slot in bag
if (bag == INVENTORY_SLOT_BAG_0)
{
res = CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START, BANK_SLOT_ITEM_END, dest, pProto, count, false, pItem, bag, slot);
if (res != EQUIP_ERR_OK)
return res;
if (count == 0)
return EQUIP_ERR_OK;
}
else
{
res = CanStoreItem_InBag(bag, dest, pProto, count, false, false, pItem, NULL_BAG, slot);
if (res != EQUIP_ERR_OK)
res = CanStoreItem_InBag(bag, dest, pProto, count, false, true, pItem, NULL_BAG, slot);
if (res != EQUIP_ERR_OK)
return res;
if (count == 0)
return EQUIP_ERR_OK;
}
}
// not specific bag or have space for partly store only in specific bag
// search stack for merge to
if (pProto->Stackable != 1)
{
// in slots
res = CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START, BANK_SLOT_ITEM_END, dest, pProto, count, true, pItem, bag, slot);
if (res != EQUIP_ERR_OK)
return res;
if (count == 0)
return EQUIP_ERR_OK;
// in special bags
if (pProto->BagFamily)
{
for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
{
res = CanStoreItem_InBag(i, dest, pProto, count, true, false, pItem, bag, slot);
if (res != EQUIP_ERR_OK)
continue;
if (count == 0)
return EQUIP_ERR_OK;
}
}
for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
{
res = CanStoreItem_InBag(i, dest, pProto, count, true, true, pItem, bag, slot);
if (res != EQUIP_ERR_OK)
continue;
if (count == 0)
return EQUIP_ERR_OK;
}
}
// search free place in special bag
if (pProto->BagFamily)
{
for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
{
res = CanStoreItem_InBag(i, dest, pProto, count, false, false, pItem, bag, slot);
if (res != EQUIP_ERR_OK)
continue;
if (count == 0)
return EQUIP_ERR_OK;
}
}
// search free space
res = CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START, BANK_SLOT_ITEM_END, dest, pProto, count, false, pItem, bag, slot);
if (res != EQUIP_ERR_OK)
return res;
if (count == 0)
return EQUIP_ERR_OK;
for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
{
res = CanStoreItem_InBag(i, dest, pProto, count, false, true, pItem, bag, slot);
if (res != EQUIP_ERR_OK)
continue;
if (count == 0)
return EQUIP_ERR_OK;
}
return EQUIP_ERR_BANK_FULL;
}
InventoryResult Player::CanUseItem(Item* pItem, bool not_loading) const
{
if (pItem)
{
TC_LOG_DEBUG("entities.player.items", "Player::CanUseItem: Player '{}' ({}), Item: {}",
GetName(), GetGUID().ToString(), pItem->GetEntry());
if (!IsAlive() && not_loading)
return EQUIP_ERR_PLAYER_DEAD;
//if (isStunned())
// return EQUIP_ERR_YOU_ARE_STUNNED;
ItemTemplate const* pProto = pItem->GetTemplate();
if (pProto)
{
if (pItem->IsBindedNotWith(this))
return EQUIP_ERR_NOT_OWNER;
InventoryResult res = CanUseItem(pProto);
if (res != EQUIP_ERR_OK)
return res;
if (pItem->GetSkill() != 0)
{
bool allowEquip = false;
uint32 itemSkill = pItem->GetSkill();
// Armor that is binded to account can "morph" from plate to mail, etc. if skill is not learned yet.
if (pProto->Quality == ITEM_QUALITY_HEIRLOOM && pProto->Class == ITEM_CLASS_ARMOR && !HasSkill(itemSkill))
{
/// @todo when you right-click already equipped item it throws EQUIP_ERR_PROFICIENCY_NEEDED.
// In fact it's a visual bug, everything works properly... I need sniffs of operations with
// binded to account items from off server.
switch (GetClass())
{
case CLASS_HUNTER:
case CLASS_SHAMAN:
allowEquip = (itemSkill == SKILL_MAIL);
break;
case CLASS_PALADIN:
case CLASS_WARRIOR:
allowEquip = (itemSkill == SKILL_PLATE_MAIL);
break;
}
}
if (!allowEquip && GetSkillValue(itemSkill) == 0)
return EQUIP_ERR_PROFICIENCY_NEEDED;
}
if (pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
return EQUIP_ERR_CANT_EQUIP_REPUTATION;
return EQUIP_ERR_OK;
}
}
return EQUIP_ERR_ITEM_NOT_FOUND;
}
InventoryResult Player::CanUseItem(ItemTemplate const* proto) const
{
// Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
if (!proto)
return EQUIP_ERR_ITEM_NOT_FOUND;
if (((proto->Flags2 & ITEM_FLAG2_FACTION_HORDE) && GetTeam() != HORDE) ||
(((proto->Flags2 & ITEM_FLAG2_FACTION_ALLIANCE) && GetTeam() != ALLIANCE)))
return EQUIP_ERR_CANT_EQUIP_EVER;
if ((proto->AllowableClass & GetClassMask()) == 0 || (proto->AllowableRace & GetRaceMask()) == 0)
return EQUIP_ERR_CANT_EQUIP_EVER;
if (proto->RequiredSkill != 0)
{
if (GetSkillValue(proto->RequiredSkill) == 0)
return EQUIP_ERR_PROFICIENCY_NEEDED;
else if (GetSkillValue(proto->RequiredSkill) < proto->RequiredSkillRank)
return EQUIP_ERR_CANT_EQUIP_SKILL;
}
if (proto->RequiredSpell != 0 && !HasSpell(proto->RequiredSpell))
return EQUIP_ERR_PROFICIENCY_NEEDED;
if (GetLevel() < proto->RequiredLevel)
return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
// If World Event is not active, prevent using event dependant items
if (proto->HolidayId && !IsHolidayActive((HolidayIds)proto->HolidayId))
return EQUIP_ERR_CLIENT_LOCKED_OUT;
// learning (recipes, mounts, pets, etc.)
if (proto->Spells[0].SpellId == 483 || proto->Spells[0].SpellId == 55884)
if (HasSpell(proto->Spells[1].SpellId))
return EQUIP_ERR_NONE;
#ifdef ELUNA
if (Eluna* e = GetEluna())
{
InventoryResult eres = e->OnCanUseItem(this, proto->ItemId);
if (eres != EQUIP_ERR_OK)
return eres;
}
#endif
return EQUIP_ERR_OK;
}
InventoryResult Player::CanRollForItemInLFG(ItemTemplate const* proto, WorldObject const* lootedObject) const
{
if (!GetGroup() || !GetGroup()->isLFGGroup())
return EQUIP_ERR_OK; // not in LFG group
// check if looted object is inside the lfg dungeon
Map const* map = lootedObject->GetMap();
if (!sLFGMgr->inLfgDungeonMap(GetGroup()->GetGUID(), map->GetId(), map->GetDifficulty()))
return EQUIP_ERR_OK;
if (!proto)
return EQUIP_ERR_ITEM_NOT_FOUND;
// Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
const static uint32 item_weapon_skills[MAX_ITEM_SUBCLASS_WEAPON] =
{
SKILL_AXES, SKILL_2H_AXES, SKILL_BOWS, SKILL_GUNS, SKILL_MACES,
SKILL_2H_MACES, SKILL_POLEARMS, SKILL_SWORDS, SKILL_2H_SWORDS, 0,
SKILL_STAVES, 0, 0, SKILL_FIST_WEAPONS, 0,
SKILL_DAGGERS, SKILL_THROWN, SKILL_ASSASSINATION, SKILL_CROSSBOWS, SKILL_WANDS,
SKILL_FISHING
}; //Copy from function Item::GetSkill()
if ((proto->AllowableClass & GetClassMask()) == 0 || (proto->AllowableRace & GetRaceMask()) == 0)
return EQUIP_ERR_CANT_EQUIP_EVER;
if (proto->RequiredSpell != 0 && !HasSpell(proto->RequiredSpell))
return EQUIP_ERR_PROFICIENCY_NEEDED;
if (proto->RequiredSkill != 0)
{
if (!GetSkillValue(proto->RequiredSkill))
return EQUIP_ERR_PROFICIENCY_NEEDED;
else if (GetSkillValue(proto->RequiredSkill) < proto->RequiredSkillRank)
return EQUIP_ERR_CANT_EQUIP_SKILL;
}
uint8 _class = GetClass();
if (proto->Class == ITEM_CLASS_WEAPON && GetSkillValue(item_weapon_skills[proto->SubClass]) == 0)
return EQUIP_ERR_PROFICIENCY_NEEDED;
if (proto->Class == ITEM_CLASS_ARMOR && proto->SubClass > ITEM_SUBCLASS_ARMOR_MISCELLANEOUS && proto->SubClass < ITEM_SUBCLASS_ARMOR_BUCKLER && proto->InventoryType != INVTYPE_CLOAK)
{
if (_class == CLASS_WARRIOR || _class == CLASS_PALADIN || _class == CLASS_DEATH_KNIGHT)
{
if (GetLevel() < 40)
{
if (proto->SubClass != ITEM_SUBCLASS_ARMOR_MAIL)
return EQUIP_ERR_CLIENT_LOCKED_OUT;
}
else if (proto->SubClass != ITEM_SUBCLASS_ARMOR_PLATE)
return EQUIP_ERR_CLIENT_LOCKED_OUT;
}
else if (_class == CLASS_HUNTER || _class == CLASS_SHAMAN)
{
if (GetLevel() < 40)
{
if (proto->SubClass != ITEM_SUBCLASS_ARMOR_LEATHER)
return EQUIP_ERR_CLIENT_LOCKED_OUT;
}
else if (proto->SubClass != ITEM_SUBCLASS_ARMOR_MAIL)
return EQUIP_ERR_CLIENT_LOCKED_OUT;
}
if (_class == CLASS_ROGUE || _class == CLASS_DRUID)
if (proto->SubClass != ITEM_SUBCLASS_ARMOR_LEATHER)
return EQUIP_ERR_CLIENT_LOCKED_OUT;
if (_class == CLASS_MAGE || _class == CLASS_PRIEST || _class == CLASS_WARLOCK)
if (proto->SubClass != ITEM_SUBCLASS_ARMOR_CLOTH)
return EQUIP_ERR_CLIENT_LOCKED_OUT;
}
return EQUIP_ERR_OK;
}
InventoryResult Player::CanUseAmmo(uint32 item) const
{
TC_LOG_DEBUG("entities.player.items", "STORAGE: CanUseAmmo item = {}", item);
if (!IsAlive())
return EQUIP_ERR_PLAYER_DEAD;
//if (isStunned())
// return EQUIP_ERR_YOU_ARE_STUNNED;
ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(item);
if (pProto)
{
if (pProto->InventoryType!= INVTYPE_AMMO)
return EQUIP_ERR_AMMO_ONLY;
InventoryResult res = CanUseItem(pProto);
if (res != EQUIP_ERR_OK)
return res;
/*if (GetReputationMgr().GetReputation() < pProto->RequiredReputation)
return EQUIP_ERR_CANT_EQUIP_REPUTATION;
*/
// Requires No Ammo
if (HasAura(46699))
return EQUIP_ERR_BAG_FULL_4;
return EQUIP_ERR_OK;
}
return EQUIP_ERR_ITEM_NOT_FOUND;
}
void Player::SetAmmo(uint32 item)
{
if (!item)
return;
// already set
if (GetUInt32Value(PLAYER_AMMO_ID) == item)
return;
// check ammo
InventoryResult msg = CanUseAmmo(item);
if (msg != EQUIP_ERR_OK)
{
SendEquipError(msg, nullptr, nullptr, item);
return;
}
SetUInt32Value(PLAYER_AMMO_ID, item);
_ApplyAmmoBonuses();
}
void Player::RemoveAmmo()
{
SetUInt32Value(PLAYER_AMMO_ID, 0);
m_ammoDPS = 0.0f;
if (CanModifyStats())
UpdateDamagePhysical(RANGED_ATTACK);
}
// Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
Item* Player::StoreNewItem(ItemPosCountVec const& dest, uint32 item, bool update, int32 randomPropertyId, GuidSet const& allowedLooters)
{
uint32 count = 0;
for (ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
count += itr->count;
Item* pItem = Item::CreateItem(item, count, this);
if (pItem)
{
if (randomPropertyId)
pItem->SetItemRandomProperties(randomPropertyId);
pItem = StoreItem(dest, pItem, update);
ItemAddedQuestCheck(item, count);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM, item, count);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, item, count);
if (allowedLooters.size() > 1 && pItem->GetTemplate()->GetMaxStackSize() == 1 && pItem->IsSoulBound())
{
pItem->SetSoulboundTradeable(allowedLooters);
pItem->SetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME, GetTotalPlayedTime());
AddTradeableItem(pItem);
// save data
std::ostringstream ss;
GuidSet::const_iterator itr = allowedLooters.begin();
ss << itr->GetCounter();
for (++itr; itr != allowedLooters.end(); ++itr)
ss << ' ' << itr->GetCounter();
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_ITEM_BOP_TRADE);
stmt->setUInt32(0, pItem->GetGUID().GetCounter());
stmt->setString(1, ss.str());
CharacterDatabase.Execute(stmt);
}
#ifdef ELUNA
if (Eluna* e = GetEluna())
e->OnAdd(this, pItem);
#endif
}
return pItem;
}
Item* Player::StoreItem(ItemPosCountVec const& dest, Item* pItem, bool update)
{
if (!pItem)
return nullptr;
Item* lastItem = pItem;
for (ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end();)
{
uint16 pos = itr->pos;
uint32 count = itr->count;
++itr;
if (itr == dest.end())
{
lastItem = _StoreItem(pos, pItem, count, false, update);
break;
}
lastItem = _StoreItem(pos, pItem, count, true, update);
}
return lastItem;
}
// Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
Item* Player::_StoreItem(uint16 pos, Item* pItem, uint32 count, bool clone, bool update)
{
if (!pItem)
return nullptr;
uint8 bag = pos >> 8;
uint8 slot = pos & 255;
TC_LOG_DEBUG("entities.player.items", "Player::_StoreItem: Player '{}' ({}), Bag: {}, Slot: {}, Item: {} ({}), Count: {}",
GetName(), GetGUID().ToString(), bag, slot, pItem->GetEntry(), pItem->GetGUID().ToString(), count);
Item* pItem2 = GetItemByPos(bag, slot);
if (!pItem2)
{
if (clone)
pItem = pItem->CloneItem(count, this);
else
pItem->SetCount(count);
if (!pItem)
return nullptr;
if (pItem->GetTemplate()->Bonding == BIND_WHEN_PICKED_UP ||
pItem->GetTemplate()->Bonding == BIND_QUEST_ITEM ||
(pItem->GetTemplate()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
pItem->SetBinding(true);
Bag* pBag = (bag == INVENTORY_SLOT_BAG_0) ? nullptr : GetBagByPos(bag);
if (!pBag)
{
m_items[slot] = pItem;
SetGuidValue(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID());
pItem->SetGuidValue(ITEM_FIELD_CONTAINED, GetGUID());
pItem->SetOwnerGUID(GetGUID());
pItem->SetSlot(slot);
pItem->SetContainer(nullptr);
// need update known currency
if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
AddKnownCurrency(pItem->GetEntry());
}
else
pBag->StoreItem(slot, pItem, update);
if (IsInWorld() && update)
{
pItem->AddToWorld();
pItem->SendUpdateToPlayer(this);
}
pItem->SetState(ITEM_CHANGED, this);
if (pBag)
pBag->SetState(ITEM_CHANGED, this);
AddEnchantmentDurations(pItem);
AddItemDurations(pItem);
if (bag == INVENTORY_SLOT_BAG_0 || (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END))
ApplyItemObtainSpells(pItem, true);
return pItem;
}
else
{
if (pItem2->GetTemplate()->Bonding == BIND_WHEN_PICKED_UP ||
pItem2->GetTemplate()->Bonding == BIND_QUEST_ITEM ||
(pItem2->GetTemplate()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
pItem2->SetBinding(true);
pItem2->SetCount(pItem2->GetCount() + count);
if (IsInWorld() && update)
pItem2->SendUpdateToPlayer(this);
if (!clone)
{
// delete item (it not in any slot currently)
if (IsInWorld() && update)
{
pItem->RemoveFromWorld();
pItem->DestroyForPlayer(this);
}
RemoveEnchantmentDurations(pItem);
RemoveItemDurations(pItem);
pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
pItem->SetNotRefundable(this);
pItem->ClearSoulboundTradeable(this);
RemoveTradeableItem(pItem);
pItem->SetState(ITEM_REMOVED, this);
}
AddEnchantmentDurations(pItem2);
pItem2->SetState(ITEM_CHANGED, this);
if (bag == INVENTORY_SLOT_BAG_0 || (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END))
ApplyItemObtainSpells(pItem2, true);
return pItem2;
}
}
Item* Player::EquipNewItem(uint16 pos, uint32 item, bool update)
{
if (Item* pItem = Item::CreateItem(item, 1, this))
{
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM, item, 1);
Item* equippedItem = EquipItem(pos, pItem, update);
ItemAddedQuestCheck(item, 1);
return equippedItem;
}
return nullptr;
}
Item* Player::EquipItem(uint16 pos, Item* pItem, bool update)
{
AddEnchantmentDurations(pItem);
AddItemDurations(pItem);
uint8 bag = pos >> 8;
uint8 slot = pos & 255;
Item* pItem2 = GetItemByPos(bag, slot);
if (!pItem2)
{
VisualizeItem(slot, pItem);
if (IsAlive())
{
ItemTemplate const* pProto = pItem->GetTemplate();
// item set bonuses applied only at equip and removed at unequip, and still active for broken items
if (pProto && pProto->ItemSet)
AddItemsSetItem(this, pItem);
_ApplyItemMods(pItem, slot, true);
if (pProto && IsInCombat() && (pProto->Class == ITEM_CLASS_WEAPON || pProto->InventoryType == INVTYPE_RELIC) && m_weaponChangeTimer == 0)
{
uint32 cooldownSpell = GetClass() == CLASS_ROGUE ? 6123 : 6119;
SpellInfo const* spellProto = sSpellMgr->GetSpellInfo(cooldownSpell);
if (!spellProto)
TC_LOG_ERROR("entities.player", "Player::EquipItem: Weapon switch cooldown spell {} for player '{}' ({}) couldn't be found in Spell.dbc",
cooldownSpell, GetName(), GetGUID().ToString());
else
{
m_weaponChangeTimer = spellProto->StartRecoveryTime;
GetSpellHistory()->AddGlobalCooldown(spellProto, m_weaponChangeTimer);
WorldPacket data;
GetSpellHistory()->BuildCooldownPacket(data, SPELL_COOLDOWN_FLAG_INCLUDE_GCD, cooldownSpell, 0);
SendDirectMessage(&data);
}
}
}
if (IsInWorld() && update)
{
pItem->AddToWorld();
pItem->SendUpdateToPlayer(this);
}
ApplyEquipCooldown(pItem);
// update expertise and armor penetration - passive auras may need it
if (slot == EQUIPMENT_SLOT_MAINHAND)
UpdateExpertise(BASE_ATTACK);
else if (slot == EQUIPMENT_SLOT_OFFHAND)
UpdateExpertise(OFF_ATTACK);
switch (slot)
{
case EQUIPMENT_SLOT_MAINHAND:
case EQUIPMENT_SLOT_OFFHAND:
case EQUIPMENT_SLOT_RANGED:
RecalculateRating(CR_ARMOR_PENETRATION);
break;
default:
break;
}
}
else
{
pItem2->SetCount(pItem2->GetCount() + pItem->GetCount());
if (IsInWorld() && update)
pItem2->SendUpdateToPlayer(this);
// delete item (it not in any slot currently)
//pItem->DeleteFromDB();
if (IsInWorld() && update)
{
pItem->RemoveFromWorld();
pItem->DestroyForPlayer(this);
}
RemoveEnchantmentDurations(pItem);
RemoveItemDurations(pItem);
pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
pItem->SetNotRefundable(this);
pItem->ClearSoulboundTradeable(this);
RemoveTradeableItem(pItem);
pItem->SetState(ITEM_REMOVED, this);
pItem2->SetState(ITEM_CHANGED, this);
ApplyEquipCooldown(pItem2);
#ifdef ELUNA
if (Eluna* e = GetEluna())
{
e->OnEquip(this, pItem2, bag, slot); // This should be removed in the future
e->OnItemEquip(this, pItem2, slot);
}
#endif
return pItem2;
}
if (slot == EQUIPMENT_SLOT_MAINHAND || slot == EQUIPMENT_SLOT_OFFHAND)
CheckTitanGripPenalty();
// only for full equip instead adding to stack
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM, slot, pItem->GetEntry());
#ifdef ELUNA
if (Eluna* e = GetEluna())
{
e->OnEquip(this, pItem, bag, slot); // This should be removed in the future
e->OnItemEquip(this, pItem, slot);
}
#endif
return pItem;
}
void Player::QuickEquipItem(uint16 pos, Item* pItem)
{
if (pItem)
{
AddEnchantmentDurations(pItem);
AddItemDurations(pItem);
uint8 slot = pos & 255;
VisualizeItem(slot, pItem);
if (IsInWorld())
{
pItem->AddToWorld();
pItem->SendUpdateToPlayer(this);
}
if (slot == EQUIPMENT_SLOT_MAINHAND || slot == EQUIPMENT_SLOT_OFFHAND)
CheckTitanGripPenalty();
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM, slot, pItem->GetEntry());
#ifdef ELUNA
if (Eluna* e = GetEluna())
{
e->OnEquip(this, pItem, (pos >> 8), slot); // This should be removed in the future
e->OnItemEquip(this, pItem, slot);
}
#endif
}
}
void Player::SetVisibleItemSlot(uint8 slot, Item* pItem)
{
if (pItem)
{
SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), pItem->GetEntry());
SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0, pItem->GetEnchantmentId(PERM_ENCHANTMENT_SLOT));
SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 1, pItem->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT));
}
else
{
SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), 0);
SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0);
}
}
void Player::VisualizeItem(uint8 slot, Item* pItem)
{
if (!pItem)
return;
// check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
if (pItem->GetTemplate()->Bonding == BIND_WHEN_EQUIPED || pItem->GetTemplate()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetTemplate()->Bonding == BIND_QUEST_ITEM)
pItem->SetBinding(true);
TC_LOG_DEBUG("entities.player.items", "Player::SetVisibleItemSlot: Player '{}' ({}), Slot: {}, Item: {}",
GetName(), GetGUID().ToString(), slot, pItem->GetEntry());
m_items[slot] = pItem;
SetGuidValue(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID());
pItem->SetGuidValue(ITEM_FIELD_CONTAINED, GetGUID());
pItem->SetOwnerGUID(GetGUID());
pItem->SetSlot(slot);
pItem->SetContainer(nullptr);
if (slot < EQUIPMENT_SLOT_END)
SetVisibleItemSlot(slot, pItem);
pItem->SetState(ITEM_CHANGED, this);
}
Item* Player::BankItem(ItemPosCountVec const& dest, Item* pItem, bool update)
{
return StoreItem(dest, pItem, update);
}
void Player::RemoveItem(uint8 bag, uint8 slot, bool update)
{
// note: removeitem does not actually change the item
// it only takes the item out of storage temporarily
// note2: if removeitem is to be used for delinking
// the item must be removed from the player's updatequeue
Item* pItem = GetItemByPos(bag, slot);
if (pItem)
{
TC_LOG_DEBUG("entities.player.items", "Player::RemoveItem: Player '{}' ({}), Bag: {}, Slot: {}, Item: {}",
GetName(), GetGUID().ToString(), bag, slot, pItem->GetEntry());
RemoveEnchantmentDurations(pItem);
RemoveItemDurations(pItem);
RemoveTradeableItem(pItem);
if (bag == INVENTORY_SLOT_BAG_0)
{
if (slot < INVENTORY_SLOT_BAG_END)
{
// item set bonuses applied only at equip and removed at unequip, and still active for broken items
ItemTemplate const* pProto = ASSERT_NOTNULL(pItem->GetTemplate());
if (pProto->ItemSet)
RemoveItemsSetItem(this, pProto);
_ApplyItemMods(pItem, slot, false, update);
// remove item dependent auras and casts (only weapon and armor slots)
if (slot < EQUIPMENT_SLOT_END)
{
// remove held enchantments, update expertise
if (slot == EQUIPMENT_SLOT_MAINHAND)
{
if (pItem->GetItemSuffixFactor())
{
pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
}
else
{
pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
}
UpdateExpertise(BASE_ATTACK);
}
else if (slot == EQUIPMENT_SLOT_OFFHAND)
UpdateExpertise(OFF_ATTACK);
// update armor penetration - passive auras may need it
switch (slot)
{
case EQUIPMENT_SLOT_MAINHAND:
case EQUIPMENT_SLOT_OFFHAND:
case EQUIPMENT_SLOT_RANGED:
RecalculateRating(CR_ARMOR_PENETRATION);
break;
default:
break;
}
#ifdef ELUNA
if (Eluna* e = GetEluna())
e->OnItemUnEquip(this, pItem, slot);
#endif
}
}
m_items[slot] = nullptr;
SetGuidValue(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), ObjectGuid::Empty);
if (slot < EQUIPMENT_SLOT_END)
{
SetVisibleItemSlot(slot, nullptr);
if (slot == EQUIPMENT_SLOT_MAINHAND || slot == EQUIPMENT_SLOT_OFFHAND)
CheckTitanGripPenalty();
}
}
else if (Bag* pBag = GetBagByPos(bag))
pBag->RemoveItem(slot, update);
pItem->SetGuidValue(ITEM_FIELD_CONTAINED, ObjectGuid::Empty);
// pItem->SetUInt64Value(ITEM_FIELD_OWNER, 0); not clear owner at remove (it will be set at store). This used in mail and auction code
pItem->SetSlot(NULL_SLOT);
if (IsInWorld() && update)
pItem->SendUpdateToPlayer(this);
}
}
// Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
{
if (Item* it = GetItemByPos(bag, slot))
{
RemoveItem(bag, slot, update);
ItemRemovedQuestCheck(it->GetEntry(), it->GetCount());
it->SetNotRefundable(this, false);
RemoveItemFromUpdateQueueOf(it, this);
if (it->IsInWorld())
{
it->RemoveFromWorld();
it->DestroyForPlayer(this);
}
}
}
// Common operation need to add item from inventory without delete in trade, guild bank, mail....
void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
{
uint32 itemId = pItem->GetEntry();
uint32 count = pItem->GetCount();
// store item
Item* pLastItem = StoreItem(dest, pItem, update);
// only set if not merged to existing stack (pItem can be deleted already but we can compare pointers any way)
if (pLastItem == pItem)
{
// update owner for last item (this can be original item with wrong owner
if (pLastItem->GetOwnerGUID() != GetGUID())
pLastItem->SetOwnerGUID(GetGUID());
// if this original item then it need create record in inventory
// in case trade we already have item in other player inventory
pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
if (pLastItem->IsBOPTradeable())
AddTradeableItem(pLastItem);
}
// update quest counters
ItemAddedQuestCheck(itemId, count);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM, itemId, count);
}
void Player::DestroyItem(uint8 bag, uint8 slot, bool update)
{
Item* pItem = GetItemByPos(bag, slot);
if (pItem)
{
TC_LOG_DEBUG("entities.player.items", "Player::DestroyItem: Player '{}' ({}), Bag: {}, Slot: {}, Item: {}",
GetName(), GetGUID().ToString(), bag, slot, pItem->GetEntry());
// Also remove all contained items if the item is a bag.
// This if () prevents item saving crashes if the condition for a bag to be empty before being destroyed was bypassed somehow.
if (pItem->IsNotEmptyBag())
for (uint8 i = 0; i < MAX_BAG_SIZE; ++i)
DestroyItem(slot, i, update);
if (pItem->IsWrapped())
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GIFT);
stmt->setUInt32(0, pItem->GetGUID().GetCounter());
CharacterDatabase.Execute(stmt);
}
RemoveEnchantmentDurations(pItem);
RemoveItemDurations(pItem);
pItem->SetNotRefundable(this);
pItem->ClearSoulboundTradeable(this);
RemoveTradeableItem(pItem);
ApplyItemObtainSpells(pItem, false);
sScriptMgr->OnItemRemove(this, pItem);
ItemTemplate const* pProto = pItem->GetTemplate();
if (bag == INVENTORY_SLOT_BAG_0)
{
SetGuidValue(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), ObjectGuid::Empty);
// equipment and equipped bags can have applied bonuses
if (slot < INVENTORY_SLOT_BAG_END)
{
// item set bonuses applied only at equip and removed at unequip, and still active for broken items
if (pProto->ItemSet)
RemoveItemsSetItem(this, pProto);
_ApplyItemMods(pItem, slot, false);
}
if (slot < EQUIPMENT_SLOT_END)
{
// update expertise and armor penetration - passive auras may need it
switch (slot)
{
case EQUIPMENT_SLOT_MAINHAND:
case EQUIPMENT_SLOT_OFFHAND:
case EQUIPMENT_SLOT_RANGED:
RecalculateRating(CR_ARMOR_PENETRATION);
break;
default:
break;
}
if (slot == EQUIPMENT_SLOT_MAINHAND)
UpdateExpertise(BASE_ATTACK);
else if (slot == EQUIPMENT_SLOT_OFFHAND)
UpdateExpertise(OFF_ATTACK);
// equipment visual show
SetVisibleItemSlot(slot, nullptr);
#ifdef ELUNA
if (Eluna* e = GetEluna())
e->OnItemUnEquip(this, pItem, slot);
#endif
}
m_items[slot] = nullptr;
}
else if (Bag* pBag = GetBagByPos(bag))
pBag->RemoveItem(slot, update);
// Delete rolled money / loot from db.
// MUST be done before RemoveFromWorld() or GetTemplate() fails
if (pProto->HasFlag(ITEM_FLAG_HAS_LOOT))
sLootItemStorage->RemoveStoredLootForContainer(pItem->GetGUID().GetCounter());
ItemRemovedQuestCheck(pItem->GetEntry(), pItem->GetCount());
if (IsInWorld() && update)
{
pItem->RemoveFromWorld();
pItem->DestroyForPlayer(this);
}
//pItem->SetOwnerGUID(0);
pItem->SetGuidValue(ITEM_FIELD_CONTAINED, ObjectGuid::Empty);
pItem->SetSlot(NULL_SLOT);
pItem->SetState(ITEM_REMOVED, this);
}
}
uint32 Player::DestroyItemCount(uint32 itemEntry, uint32 count, bool update, bool unequip_check)
{
TC_LOG_DEBUG("entities.player.items", "Player::DestroyItemCount: Player '{}' ({}), Item: {}, Count: {}",
GetName(), GetGUID().ToString(), itemEntry, count);
uint32 remcount = 0;
// in inventory
for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
{
if (Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
{
if (item->GetEntry() == itemEntry && !item->IsInTrade())
{
if (item->GetCount() + remcount <= count)
{
// all items in inventory can unequipped
remcount += item->GetCount();
DestroyItem(INVENTORY_SLOT_BAG_0, i, update);
if (remcount >= count)
return remcount;
}
else
{
item->SetCount(item->GetCount() - count + remcount);
ItemRemovedQuestCheck(item->GetEntry(), count - remcount);
if (IsInWorld() && update)
item->SendUpdateToPlayer(this);
item->SetState(ITEM_CHANGED, this);
return count;
}
}
}
}
for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
{
if (Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
{
if (item->GetEntry() == itemEntry && !item->IsInTrade())
{
if (item->GetCount() + remcount <= count)
{
// all keys can be unequipped
remcount += item->GetCount();
DestroyItem(INVENTORY_SLOT_BAG_0, i, update);
if (remcount >= count)
return remcount;
}
else
{
item->SetCount(item->GetCount() - count + remcount);
ItemRemovedQuestCheck(item->GetEntry(), count - remcount);
if (IsInWorld() && update)
item->SendUpdateToPlayer(this);
item->SetState(ITEM_CHANGED, this);
return count;
}
}
}
}
// in inventory bags
for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
{
if (Bag* bag = GetBagByPos(i))
{
for (uint32 j = 0; j < bag->GetBagSize(); j++)
{
if (Item* item = bag->GetItemByPos(j))
{
if (item->GetEntry() == itemEntry && !item->IsInTrade())
{
// all items in bags can be unequipped
if (item->GetCount() + remcount <= count)
{
remcount += item->GetCount();
DestroyItem(i, j, update);
if (remcount >= count)
return remcount;
}
else
{
item->SetCount(item->GetCount() - count + remcount);
ItemRemovedQuestCheck(item->GetEntry(), count - remcount);
if (IsInWorld() && update)
item->SendUpdateToPlayer(this);
item->SetState(ITEM_CHANGED, this);
return count;
}
}
}
}
}
}
// in equipment and bag list
for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
{
if (Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
{
if (item->GetEntry() == itemEntry && !item->IsInTrade())
{
if (item->GetCount() + remcount <= count)
{
if (!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false) == EQUIP_ERR_OK)
{
remcount += item->GetCount();
DestroyItem(INVENTORY_SLOT_BAG_0, i, update);
if (remcount >= count)
return remcount;
}
}
else
{
item->SetCount(item->GetCount() - count + remcount);
ItemRemovedQuestCheck(item->GetEntry(), count - remcount);
if (IsInWorld() && update)
item->SendUpdateToPlayer(this);
item->SetState(ITEM_CHANGED, this);
return count;
}
}
}
}
// in bank
for (uint8 i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
{
if (Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
{
if (item->GetEntry() == itemEntry && !item->IsInTrade())
{
if (item->GetCount() + remcount <= count)
{
remcount += item->GetCount();
DestroyItem(INVENTORY_SLOT_BAG_0, i, update);
if (remcount >= count)
return remcount;
}
else
{
item->SetCount(item->GetCount() - count + remcount);
ItemRemovedQuestCheck(item->GetEntry(), count - remcount);
if (IsInWorld() && update)
item->SendUpdateToPlayer(this);
item->SetState(ITEM_CHANGED, this);
return count;
}
}
}
}
// in bank bags
for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
{
if (Bag* bag = GetBagByPos(i))
{
for (uint32 j = 0; j < bag->GetBagSize(); j++)
{
if (Item* item = bag->GetItemByPos(j))
{
if (item->GetEntry() == itemEntry && !item->IsInTrade())
{
// all items in bags can be unequipped
if (item->GetCount() + remcount <= count)
{
remcount += item->GetCount();
DestroyItem(i, j, update);
if (remcount >= count)
return remcount;
}
else
{
item->SetCount(item->GetCount() - count + remcount);
ItemRemovedQuestCheck(item->GetEntry(), count - remcount);
if (IsInWorld() && update)
item->SendUpdateToPlayer(this);
item->SetState(ITEM_CHANGED, this);
return count;
}
}
}
}
}
}
return remcount;
}
void Player::DestroyZoneLimitedItem(bool update, uint32 new_zone)
{
TC_LOG_DEBUG("entities.player.items", "Player::DestroyZoneLimitedItem: In map {} and area {} for player '{}' ({})",
GetMapId(), new_zone, GetName(), GetGUID().ToString());
// in inventory
for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
DestroyItem(INVENTORY_SLOT_BAG_0, i, update);
for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
DestroyItem(INVENTORY_SLOT_BAG_0, i, update);
// in inventory bags
for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
if (Bag* pBag = GetBagByPos(i))
for (uint32 j = 0; j < pBag->GetBagSize(); j++)
if (Item* pItem = pBag->GetItemByPos(j))
if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
DestroyItem(i, j, update);
// in equipment and bag list
for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
DestroyItem(INVENTORY_SLOT_BAG_0, i, update);
}
void Player::DestroyConjuredItems(bool update)
{
// used when entering arena
// destroys all conjured items
TC_LOG_DEBUG("entities.player.items", "Player::DestroyConjuredItems: Player '{}' ({})",
GetName(), GetGUID().ToString());
// in inventory
for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->IsConjuredConsumable())
DestroyItem(INVENTORY_SLOT_BAG_0, i, update);
// in inventory bags
for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
if (Bag* pBag = GetBagByPos(i))
for (uint32 j = 0; j < pBag->GetBagSize(); j++)
if (Item* pItem = pBag->GetItemByPos(j))
if (pItem->IsConjuredConsumable())
DestroyItem(i, j, update);
// in equipment and bag list
for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->IsConjuredConsumable())
DestroyItem(INVENTORY_SLOT_BAG_0, i, update);
}
Item* Player::GetItemByEntry(uint32 entry) const
{
// in inventory
for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->GetEntry() == entry)
return pItem;
for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->GetEntry() == entry)
return pItem;
for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
if (Bag* pBag = GetBagByPos(i))
for (uint32 j = 0; j < pBag->GetBagSize(); ++j)
if (Item* pItem = pBag->GetItemByPos(j))
if (pItem->GetEntry() == entry)
return pItem;
for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->GetEntry() == entry)
return pItem;
return nullptr;
}
void Player::DestroyItemCount(Item* pItem, uint32 &count, bool update)
{
if (!pItem)
return;
TC_LOG_DEBUG("entities.player.items", "Player::DestroyItemCount: Player '{}' ({}), Item ({}, Entry: {}), Count: {}",
GetName(), GetGUID().ToString(), pItem->GetGUID().ToString(), pItem->GetEntry(), count);
if (pItem->GetCount() <= count)
{
count -= pItem->GetCount();
DestroyItem(pItem->GetBagSlot(), pItem->GetSlot(), update);
}
else
{
pItem->SetCount(pItem->GetCount() - count);
ItemRemovedQuestCheck(pItem->GetEntry(), count);
count = 0;
if (IsInWorld() && update)
pItem->SendUpdateToPlayer(this);
pItem->SetState(ITEM_CHANGED, this);
}
}
void Player::SplitItem(uint16 src, uint16 dst, uint32 count)
{
uint8 srcbag = src >> 8;
uint8 srcslot = src & 255;
uint8 dstbag = dst >> 8;
uint8 dstslot = dst & 255;
Item* pSrcItem = GetItemByPos(srcbag, srcslot);
if (!pSrcItem)
{
SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, nullptr);
return;
}
if (pSrcItem->m_lootGenerated) // prevent split looting item (item
{
//best error message found for attempting to split while looting
SendEquipError(EQUIP_ERR_SPLIT_FAILED, pSrcItem, nullptr);
return;
}
// not let split all items (can be only at cheating)
if (pSrcItem->GetCount() == count)
{
SendEquipError(EQUIP_ERR_SPLIT_FAILED, pSrcItem, nullptr);
return;
}
// not let split more existing items (can be only at cheating)
if (pSrcItem->GetCount() < count)
{
SendEquipError(EQUIP_ERR_TOO_FEW_TO_SPLIT, pSrcItem, nullptr);
return;
}
//! If trading
if (TradeData* tradeData = GetTradeData())
{
//! If current item is in trade window (only possible with packet spoofing - silent return)
if (tradeData->GetTradeSlotForItem(pSrcItem->GetGUID()) != TRADE_SLOT_INVALID)
return;
}
TC_LOG_DEBUG("entities.player.items", "Player::SplitItem: Player '{}' ({}), Bag: {}, Slot: {}, Item: {}, Count: {}",
GetName(), GetGUID().ToString(), dstbag, dstslot, pSrcItem->GetEntry(), count);
Item* pNewItem = pSrcItem->CloneItem(count, this);
if (!pNewItem)
{
SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, nullptr);
return;
}
if (IsInventoryPos(dst))
{
// change item amount before check (for unique max count check)
pSrcItem->SetCount(pSrcItem->GetCount() - count);
ItemPosCountVec dest;
InventoryResult msg = CanStoreItem(dstbag, dstslot, dest, pNewItem, false);
if (msg != EQUIP_ERR_OK)
{
delete pNewItem;
pSrcItem->SetCount(pSrcItem->GetCount() + count);
SendEquipError(msg, pSrcItem, nullptr);
return;
}
if (IsInWorld())
pSrcItem->SendUpdateToPlayer(this);
pSrcItem->SetState(ITEM_CHANGED, this);
StoreItem(dest, pNewItem, true);
}
else if (IsBankPos(dst))
{
// change item amount before check (for unique max count check)
pSrcItem->SetCount(pSrcItem->GetCount() - count);
ItemPosCountVec dest;
InventoryResult msg = CanBankItem(dstbag, dstslot, dest, pNewItem, false);
if (msg != EQUIP_ERR_OK)
{
delete pNewItem;
pSrcItem->SetCount(pSrcItem->GetCount() + count);
SendEquipError(msg, pSrcItem, nullptr);
return;
}
if (IsInWorld())
pSrcItem->SendUpdateToPlayer(this);
pSrcItem->SetState(ITEM_CHANGED, this);
BankItem(dest, pNewItem, true);
}
else if (IsEquipmentPos(dst))
{
// change item amount before check (for unique max count check), provide space for splitted items
pSrcItem->SetCount(pSrcItem->GetCount() - count);
uint16 dest;
InventoryResult msg = CanEquipItem(dstslot, dest, pNewItem, false);
if (msg != EQUIP_ERR_OK)
{
delete pNewItem;
pSrcItem->SetCount(pSrcItem->GetCount() + count);
SendEquipError(msg, pSrcItem, nullptr);
return;
}
if (IsInWorld())
pSrcItem->SendUpdateToPlayer(this);
pSrcItem->SetState(ITEM_CHANGED, this);
EquipItem(dest, pNewItem, true);
AutoUnequipOffhandIfNeed();
}
}
void Player::SwapItem(uint16 src, uint16 dst)
{
uint8 srcbag = src >> 8;
uint8 srcslot = src & 255;
uint8 dstbag = dst >> 8;
uint8 dstslot = dst & 255;
Item* pSrcItem = GetItemByPos(srcbag, srcslot);
Item* pDstItem = GetItemByPos(dstbag, dstslot);
if (!pSrcItem)
return;
TC_LOG_DEBUG("entities.player.items", "Player::SwapItem: Player '{}' ({}), Bag: {}, Slot: {}, Item: {}",
GetName(), GetGUID().ToString(), dstbag, dstslot, pSrcItem->GetEntry());
if (!IsAlive())
{
SendEquipError(EQUIP_ERR_PLAYER_DEAD, pSrcItem, pDstItem);
return;
}
// SRC checks
// check unequip potability for equipped items and bank bags
if (IsEquipmentPos(src) || IsBagPos(src))
{
// bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
InventoryResult msg = CanUnequipItem(src, !IsBagPos(src) || IsBagPos(dst) || (pDstItem && pDstItem->ToBag() && pDstItem->ToBag()->IsEmpty()));
if (msg != EQUIP_ERR_OK)
{
SendEquipError(msg, pSrcItem, pDstItem);
return;
}
}
// prevent put equipped/bank bag in self
if (IsBagPos(src) && srcslot == dstbag)
{
SendEquipError(EQUIP_ERR_BAG_IN_BAG, pSrcItem, pDstItem);
return;
}
// prevent equipping bag in the same slot from its inside
if (IsBagPos(dst) && srcbag == dstslot)
{
SendEquipError(EQUIP_ERR_CANT_SWAP, pSrcItem, pDstItem);
return;
}
// DST checks
if (pDstItem)
{
// check unequip potability for equipped items and bank bags
if (IsEquipmentPos(dst) || IsBagPos(dst))
{
// bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
InventoryResult msg = CanUnequipItem(dst, !IsBagPos(dst) || IsBagPos(src) || (pSrcItem->ToBag() && pSrcItem->ToBag()->IsEmpty()));
if (msg != EQUIP_ERR_OK)
{
SendEquipError(msg, pSrcItem, pDstItem);
return;
}
}
}
// NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
// or swap empty bag with another empty or not empty bag (with items exchange)
// Move case
if (!pDstItem)
{
if (IsInventoryPos(dst))
{
ItemPosCountVec dest;
InventoryResult msg = CanStoreItem(dstbag, dstslot, dest, pSrcItem, false);
if (msg != EQUIP_ERR_OK)
{
SendEquipError(msg, pSrcItem, nullptr);
return;
}
RemoveItem(srcbag, srcslot, true);
StoreItem(dest, pSrcItem, true);
if (IsBankPos(src))
ItemAddedQuestCheck(pSrcItem->GetEntry(), pSrcItem->GetCount());
}
else if (IsBankPos(dst))
{
ItemPosCountVec dest;
InventoryResult msg = CanBankItem(dstbag, dstslot, dest, pSrcItem, false);
if (msg != EQUIP_ERR_OK)
{
SendEquipError(msg, pSrcItem, nullptr);
return;
}
RemoveItem(srcbag, srcslot, true);
BankItem(dest, pSrcItem, true);
ItemRemovedQuestCheck(pSrcItem->GetEntry(), pSrcItem->GetCount());
}
else if (IsEquipmentPos(dst))
{
uint16 dest;
InventoryResult msg = CanEquipItem(dstslot, dest, pSrcItem, false);
if (msg != EQUIP_ERR_OK)
{
SendEquipError(msg, pSrcItem, nullptr);
return;
}
RemoveItem(srcbag, srcslot, true);
EquipItem(dest, pSrcItem, true);
AutoUnequipOffhandIfNeed();
}
return;
}
// attempt merge to / fill target item
if (!pSrcItem->IsBag() && !pDstItem->IsBag())
{
InventoryResult msg;
ItemPosCountVec sDest;
uint16 eDest = 0;
if (IsInventoryPos(dst))
msg = CanStoreItem(dstbag, dstslot, sDest, pSrcItem, false);
else if (IsBankPos(dst))
msg = CanBankItem(dstbag, dstslot, sDest, pSrcItem, false);
else if (IsEquipmentPos(dst))
msg = CanEquipItem(dstslot, eDest, pSrcItem, false);
else
return;
// can be merge/fill
if (msg == EQUIP_ERR_OK)
{
if (pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetTemplate()->GetMaxStackSize())
{
RemoveItem(srcbag, srcslot, true);
if (IsInventoryPos(dst))
StoreItem(sDest, pSrcItem, true);
else if (IsBankPos(dst))
BankItem(sDest, pSrcItem, true);
else if (IsEquipmentPos(dst))
{
EquipItem(eDest, pSrcItem, true);
AutoUnequipOffhandIfNeed();
}
}
else
{
pSrcItem->SetCount(pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetTemplate()->GetMaxStackSize());
pDstItem->SetCount(pSrcItem->GetTemplate()->GetMaxStackSize());
pSrcItem->SetState(ITEM_CHANGED, this);
pDstItem->SetState(ITEM_CHANGED, this);
if (IsInWorld())
{
pSrcItem->SendUpdateToPlayer(this);
pDstItem->SendUpdateToPlayer(this);
}
}
SendRefundInfo(pDstItem);
return;
}
}
// impossible merge/fill, do real swap
InventoryResult msg = EQUIP_ERR_OK;
// check src->dest move possibility
ItemPosCountVec sDest;
uint16 eDest = 0;
if (IsInventoryPos(dst))
msg = CanStoreItem(dstbag, dstslot, sDest, pSrcItem, true);
else if (IsBankPos(dst))
msg = CanBankItem(dstbag, dstslot, sDest, pSrcItem, true);
else if (IsEquipmentPos(dst))
{
msg = CanEquipItem(dstslot, eDest, pSrcItem, true);
if (msg == EQUIP_ERR_OK)
msg = CanUnequipItem(eDest, true);
}
if (msg != EQUIP_ERR_OK)
{
SendEquipError(msg, pSrcItem, pDstItem);
return;
}
// check dest->src move possibility
ItemPosCountVec sDest2;
uint16 eDest2 = 0;
if (IsInventoryPos(src))
msg = CanStoreItem(srcbag, srcslot, sDest2, pDstItem, true);
else if (IsBankPos(src))
msg = CanBankItem(srcbag, srcslot, sDest2, pDstItem, true);
else if (IsEquipmentPos(src))
{
msg = CanEquipItem(srcslot, eDest2, pDstItem, true);
if (msg == EQUIP_ERR_OK)
msg = CanUnequipItem(eDest2, true);
}
if (msg != EQUIP_ERR_OK)
{
SendEquipError(msg, pDstItem, pSrcItem);
return;
}
// Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
if (Bag* srcBag = pSrcItem->ToBag())
{
if (Bag* dstBag = pDstItem->ToBag())
{
Bag* emptyBag = nullptr;
Bag* fullBag = nullptr;
if (srcBag->IsEmpty() && !IsBagPos(src))
{
emptyBag = srcBag;
fullBag = dstBag;
}
else if (dstBag->IsEmpty() && !IsBagPos(dst))
{
emptyBag = dstBag;
fullBag = srcBag;
}
// bag swap (with items exchange) case
if (emptyBag && fullBag)
{
ItemTemplate const* emptyProto = emptyBag->GetTemplate();
uint32 count = 0;
for (uint32 i=0; i < fullBag->GetBagSize(); ++i)
{
Item* bagItem = fullBag->GetItemByPos(i);
if (!bagItem)
continue;
ItemTemplate const* bagItemProto = bagItem->GetTemplate();
if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emptyProto))
{
// one from items not go to empty target bag
SendEquipError(EQUIP_ERR_BAG_IN_BAG, pSrcItem, pDstItem);
return;
}
++count;
}
if (count > emptyBag->GetBagSize())
{
// too small targeted bag
SendEquipError(EQUIP_ERR_CANT_SWAP, pSrcItem, pDstItem);
return;
}
// Items swap
count = 0; // will pos in new bag
for (uint32 i = 0; i< fullBag->GetBagSize(); ++i)
{
Item* bagItem = fullBag->GetItemByPos(i);
if (!bagItem)
continue;
fullBag->RemoveItem(i, true);
emptyBag->StoreItem(count, bagItem, true);
bagItem->SetState(ITEM_CHANGED, this);
++count;
}
}
}
}
// now do moves, remove...
RemoveItem(dstbag, dstslot, false);
RemoveItem(srcbag, srcslot, false);
// add to dest
if (IsInventoryPos(dst))
StoreItem(sDest, pSrcItem, true);
else if (IsBankPos(dst))
BankItem(sDest, pSrcItem, true);
else if (IsEquipmentPos(dst))
EquipItem(eDest, pSrcItem, true);
// add to src
if (IsInventoryPos(src))
StoreItem(sDest2, pDstItem, true);
else if (IsBankPos(src))
BankItem(sDest2, pDstItem, true);
else if (IsEquipmentPos(src))
EquipItem(eDest2, pDstItem, true);
// if inventory item was moved, check if we can remove dependent auras, because they were not removed in Player::RemoveItem (update was set to false)
// do this after swaps are done, we pass nullptr because both weapons could be swapped and none of them should be ignored
if ((srcbag == INVENTORY_SLOT_BAG_0 && srcslot < INVENTORY_SLOT_BAG_END) || (dstbag == INVENTORY_SLOT_BAG_0 && dstslot < INVENTORY_SLOT_BAG_END))
ApplyItemDependentAuras((Item*)nullptr, false);
// if player is moving bags and is looting an item inside this bag
// release the loot
if (!GetLootGUID().IsEmpty())
{
bool released = false;
if (IsBagPos(src))
{
Bag* bag = pSrcItem->ToBag();
for (uint32 i = 0; i < bag->GetBagSize(); ++i)
{
if (Item* bagItem = bag->GetItemByPos(i))
{
if (bagItem->GetGUID() == GetLootGUID())
{
m_session->DoLootRelease(GetLootGUID());
released = true; // so we don't need to look at dstBag
break;
}
}
}
}
if (!released && IsBagPos(dst))
{
Bag* bag = pDstItem->ToBag();
for (uint32 i = 0; i < bag->GetBagSize(); ++i)
{
if (Item* bagItem = bag->GetItemByPos(i))
{
if (bagItem->GetGUID() == GetLootGUID())
{
m_session->DoLootRelease(GetLootGUID());
break;
}
}
}
}
}
AutoUnequipOffhandIfNeed();
}
void Player::AddItemToBuyBackSlot(Item* pItem)
{
if (pItem)
{
uint32 slot = m_currentBuybackSlot;
// if current back slot non-empty search oldest or free
if (m_items[slot])
{
uint32 oldest_time = GetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1);
uint32 oldest_slot = BUYBACK_SLOT_START;
for (uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i)
{
// found empty
if (!m_items[i])
{
oldest_slot = i;
break;
}
uint32 i_time = GetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
if (oldest_time > i_time)
{
oldest_time = i_time;
oldest_slot = i;
}
}
// find oldest
slot = oldest_slot;
}
RemoveItemFromBuyBackSlot(slot, true);
TC_LOG_DEBUG("entities.player.items", "Player::AddItemToBuyBackSlot: Player '{}' ({}), Item: {}, Slot: {}",
GetName(), GetGUID().ToString(), pItem->GetEntry(), slot);
m_items[slot] = pItem;
time_t base = GameTime::GetGameTime();
uint32 etime = uint32(base - m_logintime + (30 * 3600));
uint32 eslot = slot - BUYBACK_SLOT_START;
SetGuidValue(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), pItem->GetGUID());
if (ItemTemplate const* proto = pItem->GetTemplate())
SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, proto->SellPrice * pItem->GetCount());
else
SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0);
SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime);
// move to next (for non filled list is move most optimized choice)
if (m_currentBuybackSlot < BUYBACK_SLOT_END - 1)
++m_currentBuybackSlot;
}
}
Item* Player::GetItemFromBuyBackSlot(uint32 slot)
{
TC_LOG_DEBUG("entities.player.items", "Player::GetItemFromBuyBackSlot: Player '{}' ({}), Slot: {}",
GetName(), GetGUID().ToString(), slot);
if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
return m_items[slot];
return nullptr;
}
void Player::RemoveItemFromBuyBackSlot(uint32 slot, bool del)
{
TC_LOG_DEBUG("entities.player.items", "Player::RemoveItemFromBuyBackSlot: Player '{}' ({}), Slot: {}",
GetName(), GetGUID().ToString(), slot);
if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
{
Item* pItem = m_items[slot];
if (pItem)
{
pItem->RemoveFromWorld();
if (del)
{
if (ItemTemplate const* itemTemplate = pItem->GetTemplate())
if (itemTemplate->HasFlag(ITEM_FLAG_HAS_LOOT))
sLootItemStorage->RemoveStoredLootForContainer(pItem->GetGUID().GetCounter());
pItem->SetState(ITEM_REMOVED, this);
}
}
m_items[slot] = nullptr;
uint32 eslot = slot - BUYBACK_SLOT_START;
SetGuidValue(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), ObjectGuid::Empty);
SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0);
SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0);
// if current backslot is filled set to now free slot
if (m_items[m_currentBuybackSlot])
m_currentBuybackSlot = slot;
}
}
void Player::SendEquipError(InventoryResult msg, Item* pItem, Item* pItem2, uint32 itemid) const
{
WorldPacket data(SMSG_INVENTORY_CHANGE_FAILURE, (22));
data << uint8(msg);
if (msg != EQUIP_ERR_OK)
{
data << (pItem ? pItem->GetGUID() : ObjectGuid::Empty);
data << (pItem2 ? pItem2->GetGUID() : ObjectGuid::Empty);
data << uint8(0); // bag type subclass, used with EQUIP_ERR_EVENT_AUTOEQUIP_BIND_CONFIRM and EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG2
switch (msg)
{
case EQUIP_ERR_CANT_EQUIP_LEVEL_I:
case EQUIP_ERR_PURCHASE_LEVEL_TOO_LOW:
{
ItemTemplate const* proto = pItem ? pItem->GetTemplate() : sObjectMgr->GetItemTemplate(itemid);
data << uint32(proto ? proto->RequiredLevel : 0);
break;
}
case EQUIP_ERR_EVENT_AUTOEQUIP_BIND_CONFIRM: // no idea about this one...
{
data << uint64(0); // item guid
data << uint32(0); // slot
data << uint64(0); // container
break;
}
case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED_IS:
case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_SOCKETED_EXCEEDED_IS:
case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS:
{
ItemTemplate const* proto = pItem ? pItem->GetTemplate() : sObjectMgr->GetItemTemplate(itemid);
data << uint32(proto ? proto->ItemLimitCategory : 0);
break;
}
default:
break;
}
}
SendDirectMessage(&data);
}
void Player::SendBuyError(BuyResult msg, Creature* creature, uint32 item, uint32 param) const
{
WorldPacket data(SMSG_BUY_FAILED, (8+4+4+1));
data << (creature ? creature->GetGUID() : ObjectGuid::Empty);
data << uint32(item);
if (param > 0)
data << uint32(param);
data << uint8(msg);
SendDirectMessage(&data);
}
void Player::SendSellError(SellResult msg, Creature* creature, ObjectGuid guid, uint32 param) const
{
WorldPacket data(SMSG_SELL_ITEM, (8+8+(4)+1)); // last check 2.0.10
data << (creature ? creature->GetGUID() : ObjectGuid::Empty);
data << guid;
if (param > 0)
data << uint32(param);
data << uint8(msg);
SendDirectMessage(&data);
}
bool Player::IsUseEquipedWeapon(bool mainhand) const
{
// disarm applied only to mainhand weapon
return !IsInFeralForm() && (!mainhand || !HasUnitFlag(UNIT_FLAG_DISARMED));
}
bool Player::CanTitanGrip(Item const* item) const
{
if (!m_canTitanGrip)
return false;
ItemTemplate const* itemTemplate = item->GetTemplate();
uint32 subClassMask = [&]
{
switch (itemTemplate->Class)
{
case ITEM_CLASS_WEAPON:
return m_titanGripWeaponSubclasses;
case ITEM_CLASS_ARMOR:
return m_titanGripArmorSubclasses;
default:
break;
}
return 0u;
}();
return !subClassMask || subClassMask & (1 << itemTemplate->SubClass);
}
void Player::SetCanTitanGrip(bool value, uint32 penaltySpellId /*= 0*/, int32 allowedItemClass /*= 0*/, int32 allowedItemSubClassMask /*= 0*/)
{
m_canTitanGrip = value;
if (value)
{
switch (allowedItemClass)
{
case ITEM_CLASS_WEAPON:
m_titanGripWeaponSubclasses = allowedItemSubClassMask;
break;
case ITEM_CLASS_ARMOR:
m_titanGripArmorSubclasses = allowedItemSubClassMask;
break;
default:
break;
}
}
else
{
m_titanGripWeaponSubclasses = 0;
m_titanGripArmorSubclasses = 0;
}
m_titanGripPenaltySpellId = penaltySpellId;
}
void Player::CheckTitanGripPenalty()
{
if (!m_titanGripPenaltySpellId)
return;
bool apply = IsUsingTwoHandedWeaponInOneHand();
if (apply)
{
if (!HasAura(m_titanGripPenaltySpellId))
CastSpell((Unit*)nullptr, m_titanGripPenaltySpellId, true);
}
else
RemoveAurasDueToSpell(m_titanGripPenaltySpellId);
}
bool Player::IsTwoHandUsed() const
{
Item* mainItem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
return mainItem && mainItem->GetTemplate()->InventoryType == INVTYPE_2HWEAPON && !CanTitanGrip(mainItem);
}
bool Player::IsUsingTwoHandedWeaponInOneHand() const
{
Item* offItem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
if (offItem && offItem->GetTemplate()->InventoryType == INVTYPE_2HWEAPON)
return true;
Item* mainItem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
if (!mainItem || mainItem->GetTemplate()->InventoryType != INVTYPE_2HWEAPON)
return false;
if (!offItem)
return false;
return true;
}
void Player::TradeCancel(bool sendback, TradeStatus status /*= TRADE_STATUS_TRADE_CANCELED*/)
{
if (m_trade)
{
Player* trader = m_trade->GetTrader();
if (sendback)
GetSession()->SendCancelTrade(status);
trader->GetSession()->SendCancelTrade(status);
// cleanup
delete m_trade;
m_trade = nullptr;
delete trader->m_trade;
trader->m_trade = nullptr;
}
}
void Player::UpdateSoulboundTradeItems()
{
// also checks for garbage data
for (GuidUnorderedSet::iterator itr = m_itemSoulboundTradeable.begin(); itr != m_itemSoulboundTradeable.end();)
{
Item* item = GetItemByGuid(*itr);
if (!item || item->GetOwnerGUID() != GetGUID() || item->CheckSoulboundTradeExpire())
itr = m_itemSoulboundTradeable.erase(itr);
else
++itr;
}
}
void Player::AddTradeableItem(Item* item)
{
m_itemSoulboundTradeable.insert(item->GetGUID());
}
void Player::RemoveTradeableItem(Item* item)
{
m_itemSoulboundTradeable.erase(item->GetGUID());
}
void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
{
if (m_itemDuration.empty())
return;
TC_LOG_DEBUG("entities.player.items", "Player::UpdateItemDuration: Player '{}' ({}), Time: {}, RealTimeOnly: {}",
GetName(), GetGUID().ToString(), time, realtimeonly);
for (ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end();)
{
Item* item = *itr;
++itr; // current element can be erased in UpdateDuration
if (!realtimeonly || item->GetTemplate()->HasFlag(ITEM_FLAGS_CU_DURATION_REAL_TIME))
item->UpdateDuration(this, time);
}
}
void Player::UpdateEnchantTime(uint32 time)
{
for (EnchantDurationList::iterator itr = m_enchantDuration.begin(), next; itr != m_enchantDuration.end(); itr = next)
{
ASSERT(itr->item);
next = itr;
if (!itr->item->GetEnchantmentId(itr->slot))
{
next = m_enchantDuration.erase(itr);
}
else if (itr->leftduration <= time)
{
ApplyEnchantment(itr->item, itr->slot, false, false);
itr->item->ClearEnchantment(itr->slot);
next = m_enchantDuration.erase(itr);
}
else if (itr->leftduration > time)
{
itr->leftduration -= time;
++next;
}
}
}
void Player::AddEnchantmentDurations(Item* item)
{
for (int x = 0; x < MAX_ENCHANTMENT_SLOT; ++x)
{
if (!item->GetEnchantmentId(EnchantmentSlot(x)))
continue;
uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
if (duration > 0)
AddEnchantmentDuration(item, EnchantmentSlot(x), duration);
}
}
void Player::RemoveEnchantmentDurations(Item* item)
{
for (EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end();)
{
if (itr->item == item)
{
// save duration in item
item->SetEnchantmentDuration(EnchantmentSlot(itr->slot), itr->leftduration, this);
itr = m_enchantDuration.erase(itr);
}
else
++itr;
}
}
void Player::RemoveEnchantmentDurationsReferences(Item* item)
{
for (EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end();)
{
if (itr->item == item)
itr = m_enchantDuration.erase(itr);
else
++itr;
}
}
void Player::RemoveArenaEnchantments(EnchantmentSlot slot)
{
// remove enchantments from equipped items first to clean up the m_enchantDuration list
for (EnchantDurationList::iterator itr = m_enchantDuration.begin(), next; itr != m_enchantDuration.end(); itr = next)
{
next = itr;
if (itr->slot == slot)
{
if (itr->item && itr->item->GetEnchantmentId(slot))
{
// Poisons and DK runes are enchants which are allowed on arenas
if (sSpellMgr->IsArenaAllowedEnchancment(itr->item->GetEnchantmentId(slot)))
{
++next;
continue;
}
// remove from stats
ApplyEnchantment(itr->item, slot, false, false);
// remove visual
itr->item->ClearEnchantment(slot);
}
// remove from update list
next = m_enchantDuration.erase(itr);
}
else
++next;
}
// remove enchants from inventory items
// NOTE: no need to remove these from stats, since these aren't equipped
// in inventory
for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->GetEnchantmentId(slot))
pItem->ClearEnchantment(slot);
// in inventory bags
for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
if (Bag* pBag = GetBagByPos(i))
for (uint32 j = 0; j < pBag->GetBagSize(); j++)
if (Item* pItem = pBag->GetItemByPos(j))
if (pItem->GetEnchantmentId(slot))
pItem->ClearEnchantment(slot);
}
// duration == 0 will remove item enchant
void Player::AddEnchantmentDuration(Item* item, EnchantmentSlot slot, uint32 duration)
{
if (!item)
return;
if (slot >= MAX_ENCHANTMENT_SLOT)
return;
for (EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
{
if (itr->item == item && itr->slot == slot)
{
itr->item->SetEnchantmentDuration(itr->slot, itr->leftduration, this);
m_enchantDuration.erase(itr);
break;
}
}
if (duration > 0)
{
GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(), slot, uint32(duration/1000));
m_enchantDuration.push_back(EnchantDuration(item, slot, duration));
}
}
void Player::ApplyEnchantment(Item* item, bool apply)
{
for (uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
ApplyEnchantment(item, EnchantmentSlot(slot), apply);
}
void Player::ApplyEnchantment(Item* item, EnchantmentSlot slot, bool apply, bool apply_dur, bool ignore_condition)
{
if (!item || !item->IsEquipped())
return;
if (slot >= MAX_ENCHANTMENT_SLOT)
return;
uint32 enchant_id = item->GetEnchantmentId(slot);
if (!enchant_id)
return;
SpellItemEnchantmentEntry const* pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if (!pEnchant)
return;
if (!ignore_condition && pEnchant->ConditionID && !EnchantmentFitsRequirements(pEnchant->ConditionID, -1))
return;
if (pEnchant->MinLevel > GetLevel())
return;
if (pEnchant->RequiredSkillID > 0 && pEnchant->RequiredSkillRank > GetSkillValue(pEnchant->RequiredSkillID))
return;
// If we're dealing with a gem inside a prismatic socket we need to check the prismatic socket requirements
// rather than the gem requirements itself. If the socket has no color it is a prismatic socket.
if ((slot == SOCK_ENCHANTMENT_SLOT || slot == SOCK_ENCHANTMENT_SLOT_2 || slot == SOCK_ENCHANTMENT_SLOT_3)
&& !item->GetTemplate()->Socket[slot-SOCK_ENCHANTMENT_SLOT].Color)
{
// Check if the requirements for the prismatic socket are met before applying the gem stats
SpellItemEnchantmentEntry const* pPrismaticEnchant = sSpellItemEnchantmentStore.LookupEntry(item->GetEnchantmentId(PRISMATIC_ENCHANTMENT_SLOT));
if (!pPrismaticEnchant || (pPrismaticEnchant->RequiredSkillID > 0 && pPrismaticEnchant->RequiredSkillRank > GetSkillValue(pPrismaticEnchant->RequiredSkillID)))
return;
}
if (!item->IsBroken())
{
for (uint8 s = 0; s < MAX_ITEM_ENCHANTMENT_EFFECTS; ++s)
{
uint32 enchant_display_type = pEnchant->Effect[s];
uint32 enchant_amount = pEnchant->EffectPointsMin[s];
uint32 enchant_spell_id = pEnchant->EffectArg[s];
switch (enchant_display_type)
{
case ITEM_ENCHANTMENT_TYPE_NONE:
break;
case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
// processed in Player::CastItemCombatSpell
break;
case ITEM_ENCHANTMENT_TYPE_DAMAGE:
{
WeaponAttackType const attackType = Player::GetAttackBySlot(item->GetSlot());
if (attackType != MAX_ATTACK)
UpdateDamageDoneMods(attackType, apply ? -1 : slot);
break;
}
case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
if (enchant_spell_id)
{
if (apply)
{
int32 basepoints = 0;
// Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
if (item->GetItemRandomPropertyId())
{
ItemRandomSuffixEntry const* item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
if (item_rand)
{
// Search enchant_amount
for (int k = 0; k < MAX_ITEM_ENCHANTMENT_EFFECTS; ++k)
{
if (item_rand->Enchantment[k] == enchant_id)
{
basepoints = int32((item_rand->AllocationPct[k] * item->GetItemSuffixFactor()) / 10000);
break;
}
}
}
}
CastSpellExtraArgs args(item);
// Cast custom spell vs all equal basepoints got from enchant_amount
if (basepoints)
for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i)
args.AddSpellMod(SpellValueMod(SPELLVALUE_BASE_POINT0 + i), basepoints);
CastSpell(this, enchant_spell_id, args);
}
else
RemoveAurasDueToItemSpell(enchant_spell_id, item->GetGUID());
}
break;
case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
if (!enchant_amount)
{
ItemRandomSuffixEntry const* item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
if (item_rand)
{
for (int k = 0; k < MAX_ITEM_ENCHANTMENT_EFFECTS; ++k)
{
if (item_rand->Enchantment[k] == enchant_id)
{
enchant_amount = uint32((item_rand->AllocationPct[k] * item->GetItemSuffixFactor()) / 10000);
break;
}
}
}
}
HandleStatFlatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
break;
case ITEM_ENCHANTMENT_TYPE_STAT:
{
if (!enchant_amount)
{
ItemRandomSuffixEntry const* item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
if (item_rand_suffix)
{
for (int k = 0; k < MAX_ITEM_ENCHANTMENT_EFFECTS; ++k)
{
if (item_rand_suffix->Enchantment[k] == enchant_id)
{
enchant_amount = uint32((item_rand_suffix->AllocationPct[k] * item->GetItemSuffixFactor()) / 10000);
break;
}
}
}
}
TC_LOG_DEBUG("entities.player.items", "Adding {} to stat nb {}", enchant_amount, enchant_spell_id);
switch (enchant_spell_id)
{
case ITEM_MOD_MANA:
TC_LOG_DEBUG("entities.player.items", "+ {} MANA", enchant_amount);
HandleStatFlatModifier(UNIT_MOD_MANA, BASE_VALUE, float(enchant_amount), apply);
break;
case ITEM_MOD_HEALTH:
TC_LOG_DEBUG("entities.player.items", "+ {} HEALTH", enchant_amount);
HandleStatFlatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(enchant_amount), apply);
break;
case ITEM_MOD_AGILITY:
TC_LOG_DEBUG("entities.player.items", "+ {} AGILITY", enchant_amount);
HandleStatFlatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
UpdateStatBuffMod(STAT_AGILITY);
break;
case ITEM_MOD_STRENGTH:
TC_LOG_DEBUG("entities.player.items", "+ {} STRENGTH", enchant_amount);
HandleStatFlatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
UpdateStatBuffMod(STAT_STRENGTH);
break;
case ITEM_MOD_INTELLECT:
TC_LOG_DEBUG("entities.player.items", "+ {} INTELLECT", enchant_amount);
HandleStatFlatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
UpdateStatBuffMod(STAT_INTELLECT);
break;
case ITEM_MOD_SPIRIT:
TC_LOG_DEBUG("entities.player.items", "+ {} SPIRIT", enchant_amount);
HandleStatFlatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
UpdateStatBuffMod(STAT_SPIRIT);
break;
case ITEM_MOD_STAMINA:
TC_LOG_DEBUG("entities.player.items", "+ {} STAMINA", enchant_amount);
HandleStatFlatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
UpdateStatBuffMod(STAT_STAMINA);
break;
case ITEM_MOD_DEFENSE_SKILL_RATING:
ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
TC_LOG_DEBUG("entities.player.items", "+ {} DEFENSE", enchant_amount);
break;
case ITEM_MOD_DODGE_RATING:
ApplyRatingMod(CR_DODGE, enchant_amount, apply);
TC_LOG_DEBUG("entities.player.items", "+ {} DODGE", enchant_amount);
break;
case ITEM_MOD_PARRY_RATING:
ApplyRatingMod(CR_PARRY, enchant_amount, apply);
TC_LOG_DEBUG("entities.player.items", "+ {} PARRY", enchant_amount);
break;
case ITEM_MOD_BLOCK_RATING:
ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
TC_LOG_DEBUG("entities.player.items", "+ {} SHIELD_BLOCK", enchant_amount);
break;
case ITEM_MOD_HIT_MELEE_RATING:
ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
TC_LOG_DEBUG("entities.player.items", "+ {} MELEE_HIT", enchant_amount);
break;
case ITEM_MOD_HIT_RANGED_RATING:
ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
TC_LOG_DEBUG("entities.player.items", "+ {} RANGED_HIT", enchant_amount);
break;
case ITEM_MOD_HIT_SPELL_RATING:
ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
TC_LOG_DEBUG("entities.player.items", "+ {} SPELL_HIT", enchant_amount);
break;
case ITEM_MOD_CRIT_MELEE_RATING:
ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
TC_LOG_DEBUG("entities.player.items", "+ {} MELEE_CRIT", enchant_amount);
break;
case ITEM_MOD_CRIT_RANGED_RATING:
ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
TC_LOG_DEBUG("entities.player.items", "+ {} RANGED_CRIT", enchant_amount);
break;
case ITEM_MOD_CRIT_SPELL_RATING:
ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
TC_LOG_DEBUG("entities.player.items", "+ {} SPELL_CRIT", enchant_amount);
break;
// Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
// in Enchantments
// case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
// ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
// break;
// case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
// ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
// break;
// case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
// ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
// break;
// case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
// ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
// break;
// case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
// ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
// break;
// case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
// ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
// break;
// case ITEM_MOD_HASTE_MELEE_RATING:
// ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
// break;
// case ITEM_MOD_HASTE_RANGED_RATING:
// ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
// break;
case ITEM_MOD_HASTE_SPELL_RATING:
ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
break;
case ITEM_MOD_HIT_RATING:
ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
TC_LOG_DEBUG("entities.player.items", "+ {} HIT", enchant_amount);
break;
case ITEM_MOD_CRIT_RATING:
ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
TC_LOG_DEBUG("entities.player.items", "+ {} CRITICAL", enchant_amount);
break;
// Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
// case ITEM_MOD_HIT_TAKEN_RATING:
// ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
// ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
// ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
// break;
// case ITEM_MOD_CRIT_TAKEN_RATING:
// ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
// ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
// ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
// break;
case ITEM_MOD_RESILIENCE_RATING:
ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
TC_LOG_DEBUG("entities.player.items", "+ {} RESILIENCE", enchant_amount);
break;
case ITEM_MOD_HASTE_RATING:
ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
TC_LOG_DEBUG("entities.player.items", "+ {} HASTE", enchant_amount);
break;
case ITEM_MOD_EXPERTISE_RATING:
ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
TC_LOG_DEBUG("entities.player.items", "+ {} EXPERTISE", enchant_amount);
break;
case ITEM_MOD_ATTACK_POWER:
HandleStatFlatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
HandleStatFlatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
TC_LOG_DEBUG("entities.player.items", "+ {} ATTACK_POWER", enchant_amount);
break;
case ITEM_MOD_RANGED_ATTACK_POWER:
HandleStatFlatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
TC_LOG_DEBUG("entities.player.items", "+ {} RANGED_ATTACK_POWER", enchant_amount);
break;
// case ITEM_MOD_FERAL_ATTACK_POWER:
// ApplyFeralAPBonus(enchant_amount, apply);
// TC_LOG_DEBUG("entities.player.items", "+ {} FERAL_ATTACK_POWER", enchant_amount);
// break;
case ITEM_MOD_MANA_REGENERATION:
ApplyManaRegenBonus(enchant_amount, apply);
TC_LOG_DEBUG("entities.player.items", "+ {} MANA_REGENERATION", enchant_amount);
break;
case ITEM_MOD_ARMOR_PENETRATION_RATING:
ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
TC_LOG_DEBUG("entities.player.items", "+ {} ARMOR PENETRATION", enchant_amount);
break;
case ITEM_MOD_SPELL_POWER:
ApplySpellPowerBonus(enchant_amount, apply);
TC_LOG_DEBUG("entities.player.items", "+ {} SPELL_POWER", enchant_amount);
break;
case ITEM_MOD_HEALTH_REGEN:
ApplyHealthRegenBonus(enchant_amount, apply);
TC_LOG_DEBUG("entities.player.items", "+ {} HEALTH_REGENERATION", enchant_amount);
break;
case ITEM_MOD_SPELL_PENETRATION:
ApplySpellPenetrationBonus(enchant_amount, apply);
TC_LOG_DEBUG("entities.player.items", "+ {} SPELL_PENETRATION", enchant_amount);
break;
case ITEM_MOD_BLOCK_VALUE:
HandleBaseModFlatValue(SHIELD_BLOCK_VALUE, float(enchant_amount), apply);
TC_LOG_DEBUG("entities.player.items", "+ {} BLOCK_VALUE", enchant_amount);
break;
case ITEM_MOD_SPELL_HEALING_DONE: // deprecated
case ITEM_MOD_SPELL_DAMAGE_DONE: // deprecated
default:
break;
}
break;
}
case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
{
WeaponAttackType const attackType = Player::GetAttackBySlot(item->GetSlot());
if (attackType != MAX_ATTACK)
UpdateDamageDoneMods(attackType, apply ? -1 : slot);
break;
}
case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
// processed in Player::CastItemUseSpell
break;
case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
// nothing do..
break;
default:
TC_LOG_ERROR("entities.player", "Player::ApplyEnchantment: Unknown item enchantment (ID: {}, DisplayType: {}) for player '{}' ({})",
enchant_id, enchant_display_type, GetName(), GetGUID().ToString());
break;
}
}
}
// visualize enchantment at player and equipped items
if (slot == PERM_ENCHANTMENT_SLOT)
SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 0, apply ? item->GetEnchantmentId(slot) : 0);
if (slot == TEMP_ENCHANTMENT_SLOT)
SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 1, apply ? item->GetEnchantmentId(slot) : 0);
if (apply_dur)
{
if (apply)
{
// set duration
uint32 duration = item->GetEnchantmentDuration(slot);
if (duration > 0)
AddEnchantmentDuration(item, slot, duration);
}
else
{
// duration == 0 will remove EnchantDuration
AddEnchantmentDuration(item, slot, 0);
}
}
}
void Player::UpdateSkillEnchantments(uint16 skill_id, uint16 curr_value, uint16 new_value)
{
for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (m_items[i])
{
for (uint8 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
{
uint32 ench_id = m_items[i]->GetEnchantmentId(EnchantmentSlot(slot));
if (!ench_id)
continue;
SpellItemEnchantmentEntry const* Enchant = sSpellItemEnchantmentStore.LookupEntry(ench_id);
if (!Enchant)
return;
if (Enchant->RequiredSkillID == skill_id)
{
// Checks if the enchantment needs to be applied or removed
if (curr_value < Enchant->RequiredSkillRank && new_value >= Enchant->RequiredSkillRank)
ApplyEnchantment(m_items[i], EnchantmentSlot(slot), true);
else if (new_value < Enchant->RequiredSkillRank && curr_value >= Enchant->RequiredSkillRank)
ApplyEnchantment(m_items[i], EnchantmentSlot(slot), false);
}
// If we're dealing with a gem inside a prismatic socket we need to check the prismatic socket requirements
// rather than the gem requirements itself. If the socket has no color it is a prismatic socket.
if ((slot == SOCK_ENCHANTMENT_SLOT || slot == SOCK_ENCHANTMENT_SLOT_2 || slot == SOCK_ENCHANTMENT_SLOT_3)
&& !m_items[i]->GetTemplate()->Socket[slot-SOCK_ENCHANTMENT_SLOT].Color)
{
SpellItemEnchantmentEntry const* pPrismaticEnchant = sSpellItemEnchantmentStore.LookupEntry(m_items[i]->GetEnchantmentId(PRISMATIC_ENCHANTMENT_SLOT));
if (pPrismaticEnchant && pPrismaticEnchant->RequiredSkillID == skill_id)
{
if (curr_value < pPrismaticEnchant->RequiredSkillRank && new_value >= pPrismaticEnchant->RequiredSkillRank)
ApplyEnchantment(m_items[i], EnchantmentSlot(slot), true);
else if (new_value < pPrismaticEnchant->RequiredSkillRank && curr_value >= pPrismaticEnchant->RequiredSkillRank)
ApplyEnchantment(m_items[i], EnchantmentSlot(slot), false);
}
}
}
}
}
}
void Player::SendEnchantmentDurations()
{
for (EnchantDurationList::const_iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
{
GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(), itr->slot, uint32(itr->leftduration) / 1000);
}
}
void Player::SendItemDurations()
{
for (ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ++itr)
{
(*itr)->SendTimeUpdate(this);
}
}
void Player::SendNewItem(Item* item, uint32 count, bool received, bool created, bool broadcast, bool sendChatMessage)
{
if (!item) // prevent crash
return;
// last check 2.0.10
WorldPacket data(SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4));
data << GetGUID(); // player GUID
data << uint32(received); // 0=looted, 1=from npc
data << uint32(created); // 0=received, 1=created
data << uint32(sendChatMessage); // bool print message to chat
data << uint8(item->GetBagSlot()); // bagslot
// item slot, but when added to stack: 0xFFFFFFFF
data << uint32((item->GetCount() == count) ? item->GetSlot() : -1);
data << uint32(item->GetEntry()); // item id
data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
data << int32(item->GetItemRandomPropertyId()); // random item property id
data << uint32(count); // count of items
data << uint32(GetItemCount(item->GetEntry())); // count of items in inventory
if (broadcast && GetGroup())
GetGroup()->BroadcastPacket(&data, true);
else
SendDirectMessage(&data);
}
/*********************************************************/
/*** GOSSIP SYSTEM ***/
/*********************************************************/
void Player::PrepareGossipMenu(WorldObject* source, uint32 menuId /*= 0*/, bool showQuests /*= false*/)
{
PlayerMenu* menu = PlayerTalkClass;
menu->ClearMenus();
menu->GetGossipMenu().SetMenuId(menuId);
GossipMenuItemsMapBounds menuItemBounds = sObjectMgr->GetGossipMenuItemsMapBounds(menuId);
// if default menuId and no menu options exist for this, use options from default options
if (menuItemBounds.first == menuItemBounds.second && menuId == GetDefaultGossipMenuForSource(source))
menuItemBounds = sObjectMgr->GetGossipMenuItemsMapBounds(0);
uint32 npcflags = 0;
if (source->GetTypeId() == TYPEID_UNIT)
{
npcflags = source->GetUInt32Value(UNIT_NPC_FLAGS);
if (showQuests && npcflags & UNIT_NPC_FLAG_QUESTGIVER)
PrepareQuestMenu(source->GetGUID());
}
else if (source->GetTypeId() == TYPEID_GAMEOBJECT)
if (showQuests && source->ToGameObject()->GetGoType() == GAMEOBJECT_TYPE_QUESTGIVER)
PrepareQuestMenu(source->GetGUID());
for (GossipMenuItemsContainer::const_iterator itr = menuItemBounds.first; itr != menuItemBounds.second; ++itr)
{
bool canTalk = true;
if (!sConditionMgr->IsObjectMeetToConditions(this, source, itr->second.Conditions))
continue;
if (Creature* creature = source->ToCreature())
{
if (!(itr->second.OptionNpcFlag & npcflags))
continue;
switch (itr->second.OptionType)
{
case GOSSIP_OPTION_ARMORER:
canTalk = false; // added in special mode
break;
case GOSSIP_OPTION_SPIRITHEALER:
if (!isDead())
canTalk = false;
break;
case GOSSIP_OPTION_VENDOR:
{
VendorItemData const* vendorItems = creature->GetVendorItems();
if (!vendorItems || vendorItems->Empty())
{
TC_LOG_ERROR("sql.sql", "Creature {} ({} DB GUID: {}) has UNIT_NPC_FLAG_VENDOR set, but has an empty trading item list.", creature->GetName(), creature->GetGUID().ToString(), creature->GetSpawnId());
canTalk = false;
}
break;
}
case GOSSIP_OPTION_LEARNDUALSPEC:
case GOSSIP_OPTION_DUALSPEC_INFO:
if (!(GetSpecsCount() == 1 && creature->CanResetTalents(this, false) && !(GetLevel() < sWorld->getIntConfig(CONFIG_MIN_DUALSPEC_LEVEL))))
canTalk = false;
break;
case GOSSIP_OPTION_UNLEARNTALENTS:
if (!creature->CanResetTalents(this, false))
canTalk = false;
break;
case GOSSIP_OPTION_UNLEARNPETTALENTS:
if (!GetPet() || GetPet()->getPetType() != HUNTER_PET || GetPet()->m_spells.size() <= 1 || !creature->CanResetTalents(this, true))
canTalk = false;
break;
case GOSSIP_OPTION_TAXIVENDOR:
if (GetSession()->SendLearnNewTaxiNode(creature))
return;
break;
case GOSSIP_OPTION_BATTLEFIELD:
if (!creature->isCanInteractWithBattleMaster(this, false))
canTalk = false;
break;
case GOSSIP_OPTION_STABLEPET:
if (GetClass() != CLASS_HUNTER)
canTalk = false;
break;
case GOSSIP_OPTION_QUESTGIVER:
canTalk = false;
break;
case GOSSIP_OPTION_TRAINER:
{
Trainer::Trainer const* trainer = sObjectMgr->GetTrainer(creature->GetEntry());
if (!trainer || !trainer->IsTrainerValidForPlayer(this))
{
TC_LOG_ERROR("sql.sql", "GOSSIP_OPTION_TRAINER:: Player {} {} requested wrong gossip menu: {} at Creature: {} (Entry: {})",
GetName(), GetGUID().ToString(), menu->GetGossipMenu().GetMenuId(), creature->GetName(), creature->GetEntry());
canTalk = false;
}
[[fallthrough]];
}
case GOSSIP_OPTION_GOSSIP:
case GOSSIP_OPTION_SPIRITGUIDE:
case GOSSIP_OPTION_INNKEEPER:
case GOSSIP_OPTION_BANKER:
case GOSSIP_OPTION_PETITIONER:
case GOSSIP_OPTION_TABARDDESIGNER:
case GOSSIP_OPTION_AUCTIONEER:
break; // no checks
case GOSSIP_OPTION_OUTDOORPVP:
if (!sOutdoorPvPMgr->CanTalkTo(this, creature, itr->second))
canTalk = false;
break;
default:
TC_LOG_ERROR("sql.sql", "Creature entry {} has unknown gossip option {} for menu {}.", creature->GetEntry(), itr->second.OptionType, itr->second.MenuID);
canTalk = false;
break;
}
}
else if (GameObject* go = source->ToGameObject())
{
switch (itr->second.OptionType)
{
case GOSSIP_OPTION_GOSSIP:
if (go->GetGoType() != GAMEOBJECT_TYPE_QUESTGIVER && go->GetGoType() != GAMEOBJECT_TYPE_GOOBER)
canTalk = false;
break;
default:
canTalk = false;
break;
}
}
if (canTalk)
{
std::string strOptionText, strBoxText;
BroadcastText const* optionBroadcastText = sObjectMgr->GetBroadcastText(itr->second.OptionBroadcastTextID);
BroadcastText const* boxBroadcastText = sObjectMgr->GetBroadcastText(itr->second.BoxBroadcastTextID);
LocaleConstant locale = GetSession()->GetSessionDbLocaleIndex();
if (optionBroadcastText)
strOptionText = optionBroadcastText->GetText(locale, GetGender());
else
strOptionText = itr->second.OptionText;
if (boxBroadcastText)
strBoxText = boxBroadcastText->GetText(locale, GetGender());
else
strBoxText = itr->second.BoxText;
if (locale != DEFAULT_LOCALE)
{
if (!optionBroadcastText)
{
/// Find localizations from database.
if (GossipMenuItemsLocale const* gossipMenuLocale = sObjectMgr->GetGossipMenuItemsLocale(menuId, itr->second.OptionID))
ObjectMgr::GetLocaleString(gossipMenuLocale->OptionText, locale, strOptionText);
}
if (!boxBroadcastText)
{
/// Find localizations from database.
if (GossipMenuItemsLocale const* gossipMenuLocale = sObjectMgr->GetGossipMenuItemsLocale(menuId, itr->second.OptionID))
ObjectMgr::GetLocaleString(gossipMenuLocale->BoxText, locale, strBoxText);
}
}
menu->GetGossipMenu().AddMenuItem(itr->second.OptionID, itr->second.OptionIcon, strOptionText, 0, itr->second.OptionType, strBoxText, itr->second.BoxMoney, itr->second.BoxCoded);
menu->GetGossipMenu().AddGossipMenuItemData(itr->second.OptionID, itr->second.ActionMenuID, itr->second.ActionPoiID);
}
}
}
void Player::SendPreparedGossip(WorldObject* source)
{
if (!source)
return;
if (source->GetTypeId() == TYPEID_UNIT)
{
// in case no gossip flag and quest menu not empty, open quest menu (client expect gossip menu with this flag)
if (!source->ToCreature()->HasNpcFlag(UNIT_NPC_FLAG_GOSSIP) && !PlayerTalkClass->GetQuestMenu().Empty())
{
SendPreparedQuest(source->GetGUID());
return;
}
}
else if (source->GetTypeId() == TYPEID_GAMEOBJECT)
{
// probably need to find a better way here
if (!PlayerTalkClass->GetGossipMenu().GetMenuId() && !PlayerTalkClass->GetQuestMenu().Empty())
{
SendPreparedQuest(source->GetGUID());
return;
}
}
// in case non empty gossip menu (that not included quests list size) show it
// (quest entries from quest menu will be included in list)
uint32 textId = GetGossipTextId(source);
if (uint32 menuId = PlayerTalkClass->GetGossipMenu().GetMenuId())
textId = GetGossipTextId(menuId, source);
PlayerTalkClass->SendGossipMenu(textId, source->GetGUID());
}
void Player::OnGossipSelect(WorldObject* source, uint32 gossipListId, uint32 menuId)
{
GossipMenu& gossipMenu = PlayerTalkClass->GetGossipMenu();
// if not same, then something funky is going on
if (menuId != gossipMenu.GetMenuId())
return;
GossipMenuItem const* item = gossipMenu.GetItem(gossipListId);
if (!item)
return;
uint32 gossipOptionId = item->OptionType;
ObjectGuid guid = source->GetGUID();
if (source->GetTypeId() == TYPEID_GAMEOBJECT)
{
if (gossipOptionId > GOSSIP_OPTION_QUESTGIVER)
{
TC_LOG_ERROR("entities.player", "Player '{}' ({}) requests invalid gossip option for GameObject (Entry: {})",
GetName(), GetGUID().ToString(), source->GetEntry());
return;
}
}
GossipMenuItemData const* menuItemData = gossipMenu.GetItemData(gossipListId);
if (!menuItemData)
return;
int32 cost = int32(item->BoxMoney);
if (!HasEnoughMoney(cost))
{
SendBuyError(BUY_ERR_NOT_ENOUGHT_MONEY, nullptr, 0, 0);
PlayerTalkClass->SendCloseGossip();
return;
}
switch (gossipOptionId)
{
case GOSSIP_OPTION_GOSSIP:
case GOSSIP_OPTION_DUALSPEC_INFO:
{
if (menuItemData->GossipActionPoi)
PlayerTalkClass->SendPointOfInterest(menuItemData->GossipActionPoi);
if (menuItemData->GossipActionMenuId)
{
PrepareGossipMenu(source, menuItemData->GossipActionMenuId);
SendPreparedGossip(source);
}
break;
}
case GOSSIP_OPTION_OUTDOORPVP:
sOutdoorPvPMgr->HandleGossipOption(this, source->ToCreature(), gossipListId);
break;
case GOSSIP_OPTION_SPIRITHEALER:
if (isDead())
source->ToCreature()->CastSpell(source->ToCreature(), 17251, GetGUID());
break;
case GOSSIP_OPTION_QUESTGIVER:
PrepareQuestMenu(guid);
SendPreparedQuest(guid);
break;
case GOSSIP_OPTION_VENDOR:
case GOSSIP_OPTION_ARMORER:
GetSession()->SendListInventory(guid);
break;
case GOSSIP_OPTION_STABLEPET:
GetSession()->SendStablePet(guid);
break;
case GOSSIP_OPTION_TRAINER:
GetSession()->SendTrainerList(source->ToCreature());
break;
case GOSSIP_OPTION_LEARNDUALSPEC:
if (GetSpecsCount() == 1 && GetLevel() >= sWorld->getIntConfig(CONFIG_MIN_DUALSPEC_LEVEL))
{
// Cast spells that teach dual spec
// Both are also ImplicitTarget self and must be cast by player
CastSpell(this, 63680, GetGUID());
CastSpell(this, 63624, GetGUID());
PrepareGossipMenu(source, menuItemData->GossipActionMenuId);
SendPreparedGossip(source);
}
break;
case GOSSIP_OPTION_UNLEARNTALENTS:
PlayerTalkClass->SendCloseGossip();
SendTalentWipeConfirm(guid);
break;
case GOSSIP_OPTION_UNLEARNPETTALENTS:
PlayerTalkClass->SendCloseGossip();
ResetPetTalents();
break;
case GOSSIP_OPTION_TAXIVENDOR:
GetSession()->SendTaxiMenu(source->ToCreature());
break;
case GOSSIP_OPTION_INNKEEPER:
PlayerTalkClass->SendCloseGossip();
SetBindPoint(guid);
break;
case GOSSIP_OPTION_BANKER:
GetSession()->SendShowBank(guid);
break;
case GOSSIP_OPTION_PETITIONER:
PlayerTalkClass->SendCloseGossip();
GetSession()->SendPetitionShowList(guid);
break;
case GOSSIP_OPTION_TABARDDESIGNER:
PlayerTalkClass->SendCloseGossip();
GetSession()->SendTabardVendorActivate(guid);
break;
case GOSSIP_OPTION_AUCTIONEER:
GetSession()->SendAuctionHello(guid, source->ToCreature());
break;
case GOSSIP_OPTION_SPIRITGUIDE:
PrepareGossipMenu(source);
SendPreparedGossip(source);
break;
case GOSSIP_OPTION_BATTLEFIELD:
{
BattlegroundTypeId bgTypeId = sBattlegroundMgr->GetBattleMasterBG(source->GetEntry());
if (bgTypeId == BATTLEGROUND_TYPE_NONE)
{
TC_LOG_ERROR("entities.player", "Player '{}' ({}) requested battlegroundlist from an invalid creature ({})",
GetName(), GetGUID().ToString(), source->GetGUID().ToString());
return;
}
sBattlegroundMgr->SendBattlegroundList(this, guid, bgTypeId);
break;
}
}
ModifyMoney(-cost);
}
uint32 Player::GetGossipTextId(WorldObject* source)
{
if (!source)
return DEFAULT_GOSSIP_MESSAGE;
return GetGossipTextId(GetDefaultGossipMenuForSource(source), source);
}
uint32 Player::GetGossipTextId(uint32 menuId, WorldObject* source)
{
uint32 textId = DEFAULT_GOSSIP_MESSAGE;
if (!menuId)
return textId;
GossipMenusMapBounds menuBounds = sObjectMgr->GetGossipMenusMapBounds(menuId);
for (GossipMenusContainer::const_iterator itr = menuBounds.first; itr != menuBounds.second; ++itr)
{
if (sConditionMgr->IsObjectMeetToConditions(this, source, itr->second.Conditions))
textId = itr->second.TextID;
}
return textId;
}
uint32 Player::GetDefaultGossipMenuForSource(WorldObject* source)
{
switch (source->GetTypeId())
{
case TYPEID_UNIT:
return source->ToCreature()->GetCreatureTemplate()->GossipMenuId;
case TYPEID_GAMEOBJECT:
return source->ToGameObject()->GetGOInfo()->GetGossipMenuId();
default:
break;
}
return 0;
}
/*********************************************************/
/*** QUEST SYSTEM ***/
/*********************************************************/
void Player::PrepareQuestMenu(ObjectGuid guid)
{
QuestRelationResult objectQR;
QuestRelationResult objectQIR;
// pets also can have quests
Creature* creature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, guid);
if (creature)
{
objectQR = sObjectMgr->GetCreatureQuestRelations(creature->GetEntry());
objectQIR = sObjectMgr->GetCreatureQuestInvolvedRelations(creature->GetEntry());
}
else
{
//we should obtain map pointer from GetMap() in 99% of cases. Special case
//only for quests which cast teleport spells on player
Map* _map = IsInWorld() ? GetMap() : sMapMgr->FindMap(GetMapId(), GetInstanceId());
ASSERT(_map);
GameObject* gameObject = _map->GetGameObject(guid);
if (gameObject)
{
objectQR = sObjectMgr->GetGOQuestRelations(gameObject->GetEntry());
objectQIR = sObjectMgr->GetGOQuestInvolvedRelations(gameObject->GetEntry());
}
else
return;
}
QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
qm.ClearMenu();
for (uint32 quest_id : objectQIR)
{
QuestStatus status = GetQuestStatus(quest_id);
if (status == QUEST_STATUS_COMPLETE)
qm.AddMenuItem(quest_id, 4);
else if (status == QUEST_STATUS_INCOMPLETE)
qm.AddMenuItem(quest_id, 4);
//else if (status == QUEST_STATUS_AVAILABLE)
// qm.AddMenuItem(quest_id, 2);
}
for (uint32 quest_id : objectQR)
{
Quest const* quest = sObjectMgr->GetQuestTemplate(quest_id);
if (!quest)
continue;
if (!CanTakeQuest(quest, false))
continue;
if (quest->IsAutoComplete() && (!quest->IsRepeatable() || quest->IsDaily() || quest->IsWeekly() || quest->IsMonthly()))
qm.AddMenuItem(quest_id, 0);
else if (quest->IsAutoComplete())
qm.AddMenuItem(quest_id, 4);
else if (GetQuestStatus(quest_id) == QUEST_STATUS_NONE)
qm.AddMenuItem(quest_id, 2);
}
}
void Player::SendPreparedQuest(ObjectGuid guid)
{
QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
if (questMenu.Empty())
return;
// single element case
if (questMenu.GetMenuItemCount() == 1)
{
QuestMenuItem const& qmi0 = questMenu.GetItem(0);
uint32 questId = qmi0.QuestId;
// Auto open -- maybe also should verify there is no greeting
if (Quest const* quest = sObjectMgr->GetQuestTemplate(questId))
{
if (qmi0.QuestIcon == 4)
PlayerTalkClass->SendQuestGiverRequestItems(quest, guid, CanRewardQuest(quest, false), true);
// Send completable on repeatable and autoCompletable quest if player don't have quest
/// @todo verify if check for !quest->IsDaily() is really correct (possibly not)
else
{
Object* object = ObjectAccessor::GetObjectByTypeMask(*this, guid, TYPEMASK_UNIT | TYPEMASK_GAMEOBJECT | TYPEMASK_ITEM);
if (!object || (!object->hasQuest(questId) && !object->hasInvolvedQuest(questId)))
{
PlayerTalkClass->SendCloseGossip();
return;
}
if (quest->IsAutoAccept() && CanAddQuest(quest, true) && CanTakeQuest(quest, true))
AddQuestAndCheckCompletion(quest, object);
if (quest->IsAutoComplete() && quest->IsRepeatable() && !quest->IsDailyOrWeekly())
PlayerTalkClass->SendQuestGiverRequestItems(quest, guid, CanCompleteRepeatableQuest(quest), true);
else
PlayerTalkClass->SendQuestGiverQuestDetails(quest, guid, true);
}
}
}
// multiple entries
else
{
QEmote qe;
qe._Delay = 0;
qe._Emote = 0;
std::string title = "";
// need pet case for some quests
Creature* creature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, guid);
if (creature)
{
uint32 textid = GetGossipTextId(creature);
GossipText const* gossiptext = sObjectMgr->GetGossipText(textid);
if (gossiptext)
{
qe = gossiptext->Options[0].Emotes[0];
if (!gossiptext->Options[0].Text_0.empty())
{
title = gossiptext->Options[0].Text_0;
LocaleConstant localeConstant = GetSession()->GetSessionDbLocaleIndex();
if (localeConstant != LOCALE_enUS)
if (NpcTextLocale const* nl = sObjectMgr->GetNpcTextLocale(textid))
ObjectMgr::GetLocaleString(nl->Text_0[0], localeConstant, title);
}
else
{
title = gossiptext->Options[0].Text_1;
LocaleConstant localeConstant = GetSession()->GetSessionDbLocaleIndex();
if (localeConstant != LOCALE_enUS)
if (NpcTextLocale const* nl = sObjectMgr->GetNpcTextLocale(textid))
ObjectMgr::GetLocaleString(nl->Text_1[0], localeConstant, title);
}
}
}
PlayerTalkClass->SendQuestGiverQuestList(qe, title, guid);
}
}
bool Player::IsActiveQuest(uint32 quest_id) const
{
return m_QuestStatus.find(quest_id) != m_QuestStatus.end();
}
Quest const* Player::GetNextQuest(Object const* questGiver, Quest const* quest) const
{
uint32 nextQuestID = quest->GetNextQuestInChain();
if (!nextQuestID)
return nullptr;
if (questGiver == this)
{
if (!quest->HasFlag(QUEST_FLAGS_AUTOCOMPLETE))
return nullptr;
return sObjectMgr->GetQuestTemplate(nextQuestID);
}
//we should obtain map pointer from GetMap() in 99% of cases. Special case
//only for quests which cast teleport spells on player
if (WorldObject const* worldObjectQuestGiver = dynamic_cast<WorldObject const*>(questGiver))
if (!IsInMap(worldObjectQuestGiver))
return nullptr;
if (!questGiver->hasQuest(nextQuestID))
return nullptr;
return sObjectMgr->GetQuestTemplate(nextQuestID);
}
bool Player::CanSeeStartQuest(Quest const* quest) const
{
if (!DisableMgr::IsDisabledFor(DISABLE_TYPE_QUEST, quest->GetQuestId(), this) && SatisfyQuestClass(quest, false) && SatisfyQuestRace(quest, false) &&
SatisfyQuestSkill(quest, false) && SatisfyQuestExclusiveGroup(quest, false) && SatisfyQuestReputation(quest, false) &&
SatisfyQuestDependentQuests(quest, false) &&
SatisfyQuestDay(quest, false) && SatisfyQuestWeek(quest, false) &&
SatisfyQuestMonth(quest, false) && SatisfyQuestSeasonal(quest, false))
{
return GetLevel() + sWorld->getIntConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= quest->GetMinLevel();
}
return false;
}
bool Player::CanTakeQuest(Quest const* quest, bool msg) const
{
return !DisableMgr::IsDisabledFor(DISABLE_TYPE_QUEST, quest->GetQuestId(), this)
&& SatisfyQuestStatus(quest, msg) && SatisfyQuestExclusiveGroup(quest, msg)
&& SatisfyQuestClass(quest, msg) && SatisfyQuestRace(quest, msg) && SatisfyQuestLevel(quest, msg)
&& SatisfyQuestSkill(quest, msg) && SatisfyQuestReputation(quest, msg)
&& SatisfyQuestDependentQuests(quest, msg) && SatisfyQuestTimed(quest, msg)
&& SatisfyQuestDay(quest, msg) && SatisfyQuestWeek(quest, msg)
&& SatisfyQuestMonth(quest, msg) && SatisfyQuestSeasonal(quest, msg)
&& SatisfyQuestConditions(quest, msg);
}
bool Player::CanAddQuest(Quest const* quest, bool msg) const
{
if (!SatisfyQuestLog(msg))
return false;
uint32 srcitem = quest->GetSrcItemId();
if (srcitem > 0)
{
uint32 count = quest->GetSrcItemCount();
ItemPosCountVec dest;
InventoryResult msg2 = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, srcitem, count);
// player already have max number (in most case 1) source item, no additional item needed and quest can be added.
if (msg2 == EQUIP_ERR_ITEM_MAX_COUNT)
return true;
if (msg2 != EQUIP_ERR_OK)
{
SendEquipError(msg2, nullptr, nullptr, srcitem);
return false;
}
}
return true;
}
bool Player::CanCompleteQuest(uint32 quest_id)
{
if (quest_id)
{
Quest const* qInfo = sObjectMgr->GetQuestTemplate(quest_id);
if (!qInfo)
return false;
if (!qInfo->IsRepeatable() && GetQuestRewardStatus(quest_id))
return false; // not allow re-complete quest
// auto complete quest
if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
return true;
QuestStatusMap::iterator itr = m_QuestStatus.find(quest_id);
if (itr == m_QuestStatus.end())
return false;
QuestStatusData &q_status = itr->second;
if (q_status.Status == QUEST_STATUS_INCOMPLETE)
{
if (qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAGS_DELIVER))
{
for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; i++)
{
if (qInfo->RequiredItemCount[i]!= 0 && q_status.ItemCount[i] < qInfo->RequiredItemCount[i])
return false;
}
}
if (qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAGS_KILL | QUEST_SPECIAL_FLAGS_CAST | QUEST_SPECIAL_FLAGS_SPEAKTO))
{
for (uint8 i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
{
if (qInfo->RequiredNpcOrGo[i] == 0)
continue;
if (qInfo->RequiredNpcOrGoCount[i] != 0 && q_status.CreatureOrGOCount[i] < qInfo->RequiredNpcOrGoCount[i])
return false;
}
}
if (qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAGS_PLAYER_KILL))
if (qInfo->GetPlayersSlain() != 0 && q_status.PlayerCount < qInfo->GetPlayersSlain())
return false;
if (qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAGS_EXPLORATION_OR_EVENT) && !q_status.Explored)
return false;
if (qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAGS_TIMED) && q_status.Timer == 0)
return false;
if (qInfo->GetRewOrReqMoney() < 0)
{
if (!HasEnoughMoney(-qInfo->GetRewOrReqMoney()))
return false;
}
uint32 repFacId = qInfo->GetRepObjectiveFaction();
if (repFacId && GetReputationMgr().GetReputation(repFacId) < qInfo->GetRepObjectiveValue())
return false;
return true;
}
}
return false;
}
bool Player::CanCompleteRepeatableQuest(Quest const* quest)
{
// Solve problem that player don't have the quest and try complete it.
// if repeatable she must be able to complete event if player don't have it.
// Seem that all repeatable quest are DELIVER Flag so, no need to add more.
if (!CanTakeQuest(quest, false))
return false;
if (quest->HasSpecialFlag(QUEST_SPECIAL_FLAGS_DELIVER))
for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; i++)
if (quest->RequiredItemId[i] && quest->RequiredItemCount[i] && !HasItemCount(quest->RequiredItemId[i], quest->RequiredItemCount[i]))
return false;
if (!CanRewardQuest(quest, false))
return false;
return true;
}
bool Player::CanRewardQuest(Quest const* quest, bool msg)
{
// quest is disabled
if (DisableMgr::IsDisabledFor(DISABLE_TYPE_QUEST, quest->GetQuestId(), this))
return false;
// not auto complete quest and not completed quest (only cheating case, then ignore without message)
if (!quest->IsDFQuest() && !quest->IsAutoComplete() && GetQuestStatus(quest->GetQuestId()) != QUEST_STATUS_COMPLETE)
return false;
// daily quest can't be rewarded (25 daily quest already completed)
if (!SatisfyQuestDay(quest, msg) || !SatisfyQuestWeek(quest, msg) || !SatisfyQuestMonth(quest, msg) || !SatisfyQuestSeasonal(quest, msg))
return false;
// player no longer satisfies the quest's requirements (skill level etc.)
if (!SatisfyQuestLevel(quest, msg) || !SatisfyQuestSkill(quest, msg) || !SatisfyQuestReputation(quest, msg))
return false;
// rewarded and not repeatable quest (only cheating case, then ignore without message)
if (GetQuestRewardStatus(quest->GetQuestId()))
return false;
// prevent receive reward with quest items in bank
if (quest->HasSpecialFlag(QUEST_SPECIAL_FLAGS_DELIVER))
{
for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; i++)
{
if (quest->RequiredItemCount[i]!= 0 &&
GetItemCount(quest->RequiredItemId[i]) < quest->RequiredItemCount[i])
{
if (msg)
SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr, quest->RequiredItemId[i]);
return false;
}
}
}
// prevent receive reward with low money and GetRewOrReqMoney() < 0
if (quest->GetRewOrReqMoney() < 0 && !HasEnoughMoney(-quest->GetRewOrReqMoney()))
return false;
return true;
}
void Player::AddQuestAndCheckCompletion(Quest const* quest, Object* questGiver)
{
AddQuest(quest, questGiver);
if (CanCompleteQuest(quest->GetQuestId()))
CompleteQuest(quest->GetQuestId());
if (!questGiver)
return;
switch (questGiver->GetTypeId())
{
case TYPEID_UNIT:
PlayerTalkClass->ClearMenus();
#ifdef ELUNA
if (Eluna* e = GetEluna())
e->OnQuestAccept(this, questGiver->ToCreature(), quest);
#endif
questGiver->ToCreature()->AI()->OnQuestAccept(this, quest);
break;
case TYPEID_ITEM:
case TYPEID_CONTAINER:
{
Item* item = static_cast<Item*>(questGiver);
sScriptMgr->OnQuestAccept(this, item, quest);
// There are two cases where the source item is not destroyed when the quest is accepted:
// - It is required to finish the quest, and is an unique item
// - It is the same item present in the source item field (item that would be given on quest accept)
bool destroyItem = true;
for (int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
{
if (quest->RequiredItemId[i] == item->GetEntry() && item->GetTemplate()->MaxCount > 0)
{
destroyItem = false;
break;
}
}
if (quest->GetSrcItemId() == item->GetEntry())
destroyItem = false;
if (destroyItem)
DestroyItem(item->GetBagSlot(), item->GetSlot(), true);
break;
}
case TYPEID_GAMEOBJECT:
PlayerTalkClass->ClearMenus();
#ifdef ELUNA
if (Eluna* e = GetEluna())
e->OnQuestAccept(this, questGiver->ToGameObject(), quest);
#endif
questGiver->ToGameObject()->AI()->OnQuestAccept(this, quest);
break;
default:
break;
}
}
bool Player::CanRewardQuest(Quest const* quest, uint32 reward, bool msg)
{
ItemPosCountVec dest;
if (quest->GetRewChoiceItemsCount() > 0)
{
if (quest->RewardChoiceItemId[reward])
{
InventoryResult res = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, quest->RewardChoiceItemId[reward], quest->RewardChoiceItemCount[reward]);
if (res != EQUIP_ERR_OK)
{
if (msg)
SendQuestFailed(quest->GetQuestId(), res);
return false;
}
}
}
if (quest->GetRewItemsCount() > 0)
{
for (uint32 i = 0; i < quest->GetRewItemsCount(); ++i)
{
if (quest->RewardItemId[i])
{
InventoryResult res = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, quest->RewardItemId[i], quest->RewardItemIdCount[i]);
if (res != EQUIP_ERR_OK)
{
if (msg)
SendQuestFailed(quest->GetQuestId(), res);
return false;
}
}
}
}
return true;
}
void Player::AddQuest(Quest const* quest, Object* questGiver)
{
uint16 log_slot = FindQuestSlot(0);
if (log_slot >= MAX_QUEST_LOG_SIZE) // Player does not have any free slot in the quest log
return;
uint32 quest_id = quest->GetQuestId();
// if not exist then created with set uState == NEW and rewarded=false
QuestStatusData& questStatusData = m_QuestStatus[quest_id];
// check for repeatable quests status reset
questStatusData.Status = QUEST_STATUS_INCOMPLETE;
questStatusData.Explored = false;
if (quest->HasSpecialFlag(QUEST_SPECIAL_FLAGS_DELIVER))
{
for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
questStatusData.ItemCount[i] = 0;
}
if (quest->HasSpecialFlag(QUEST_SPECIAL_FLAGS_KILL | QUEST_SPECIAL_FLAGS_CAST | QUEST_SPECIAL_FLAGS_SPEAKTO))
{
for (uint8 i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
questStatusData.CreatureOrGOCount[i] = 0;
}
if (quest->HasSpecialFlag(QUEST_SPECIAL_FLAGS_PLAYER_KILL))
questStatusData.PlayerCount = 0;
GiveQuestSourceItem(quest);
AdjustQuestReqItemCount(quest, questStatusData);
if (quest->GetRepObjectiveFaction())
if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(quest->GetRepObjectiveFaction()))
GetReputationMgr().SetVisible(factionEntry);
if (quest->GetRepObjectiveFaction2())
if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(quest->GetRepObjectiveFaction2()))
GetReputationMgr().SetVisible(factionEntry);
uint32 qtime = 0;
if (quest->HasSpecialFlag(QUEST_SPECIAL_FLAGS_TIMED))
{
uint32 timeAllowed = quest->GetTimeAllowed();
// shared timed quest
if (questGiver && questGiver->GetTypeId() == TYPEID_PLAYER)
timeAllowed = questGiver->ToPlayer()->getQuestStatusMap()[quest_id].Timer / IN_MILLISECONDS;
AddTimedQuest(quest_id);
questStatusData.Timer = timeAllowed * IN_MILLISECONDS;
qtime = static_cast<uint32>(GameTime::GetGameTime()) + timeAllowed;
}
else
questStatusData.Timer = 0;
if (quest->HasFlag(QUEST_FLAGS_FLAGS_PVP))
{
pvpInfo.IsHostile = true;
UpdatePvPState();
}
SetQuestSlot(log_slot, quest_id, qtime);
m_QuestStatusSave[quest_id] = QUEST_DEFAULT_SAVE_TYPE;
StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_QUEST, quest_id);
SendQuestUpdate(quest_id);
if (sWorld->getBoolConfig(CONFIG_QUEST_ENABLE_QUEST_TRACKER)) // check if Quest Tracker is enabled
{
// prepare Quest Tracker datas
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_QUEST_TRACK);
stmt->setUInt32(0, quest_id);
stmt->setUInt32(1, GetGUID().GetCounter());
stmt->setString(2, GitRevision::GetHash());
stmt->setString(3, GitRevision::GetDate());
// add to Quest Tracker
CharacterDatabase.Execute(stmt);
}
sScriptMgr->OnQuestStatusChange(this, quest_id);
}
void Player::CompleteQuest(uint32 quest_id)
{
if (quest_id)
{
SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
uint16 log_slot = FindQuestSlot(quest_id);
if (log_slot < MAX_QUEST_LOG_SIZE)
SetQuestSlotState(log_slot, QUEST_STATE_COMPLETE);
if (Quest const* qInfo = sObjectMgr->GetQuestTemplate(quest_id))
if (qInfo->HasFlag(QUEST_FLAGS_TRACKING))
RewardQuest(qInfo, 0, this, false);
}
if (sWorld->getBoolConfig(CONFIG_QUEST_ENABLE_QUEST_TRACKER)) // check if Quest Tracker is enabled
{
// prepare Quest Tracker data
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_QUEST_TRACK_COMPLETE_TIME);
stmt->setUInt32(0, quest_id);
stmt->setUInt32(1, GetGUID().GetCounter());
// add to Quest Tracker
CharacterDatabase.Execute(stmt);
}
}
void Player::IncompleteQuest(uint32 quest_id)
{
if (quest_id)
{
SetQuestStatus(quest_id, QUEST_STATUS_INCOMPLETE);
uint16 log_slot = FindQuestSlot(quest_id);
if (log_slot < MAX_QUEST_LOG_SIZE)
RemoveQuestSlotState(log_slot, QUEST_STATE_COMPLETE);
}
}
void Player::RewardQuest(Quest const* quest, uint32 reward, Object* questGiver, bool announce)
{
//this THING should be here to protect code from quest, which cast on player far teleport as a reward
//should work fine, cause far teleport will be executed in Player::Update()
SetCanDelayTeleport(true);
uint32 quest_id = quest->GetQuestId();
for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
{
if (ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(quest->RequiredItemId[i]))
{
if (quest->RequiredItemCount[i] > 0 && itemTemplate->Bonding == BIND_QUEST_ITEM && !quest->IsRepeatable() && !HasQuestForItem(quest->RequiredItemId[i], quest_id, true))
DestroyItemCount(quest->RequiredItemId[i], 9999, true);
else
DestroyItemCount(quest->RequiredItemId[i], quest->RequiredItemCount[i], true);
}
}
for (uint8 i = 0; i < QUEST_SOURCE_ITEM_IDS_COUNT; ++i)
{
if (ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(quest->ItemDrop[i]))
{
if (quest->ItemDropQuantity[i] > 0 && itemTemplate->Bonding == BIND_QUEST_ITEM && !quest->IsRepeatable() && !HasQuestForItem(quest->ItemDrop[i], quest_id))
DestroyItemCount(quest->ItemDrop[i], 9999, true);
else
DestroyItemCount(quest->ItemDrop[i], quest->ItemDropQuantity[i], true);
}
}
RemoveTimedQuest(quest_id);
if (quest->GetRewItemsCount() > 0)
{
for (uint32 i = 0; i < quest->GetRewItemsCount(); ++i)
{
if (uint32 itemId = quest->RewardItemId[i])
{
ItemPosCountVec dest;
if (CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, itemId, quest->RewardItemIdCount[i]) == EQUIP_ERR_OK)
{
Item* item = StoreNewItem(dest, itemId, true, GenerateItemRandomPropertyId(itemId));
SendNewItem(item, quest->RewardItemIdCount[i], true, false, false, false);
}
else if (quest->IsDFQuest())
SendItemRetrievalMail(itemId, quest->RewardItemIdCount[i]);
}
}
}
if (quest->GetRewChoiceItemsCount() > 0)
{
if (uint32 itemId = quest->RewardChoiceItemId[reward])
{
ItemPosCountVec dest;
if (CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, itemId, quest->RewardChoiceItemCount[reward]) == EQUIP_ERR_OK)
{
Item* item = StoreNewItem(dest, itemId, true, GenerateItemRandomPropertyId(itemId));
SendNewItem(item, quest->RewardChoiceItemCount[reward], true, false, false, false);
}
}
}
uint16 log_slot = FindQuestSlot(quest_id);
if (log_slot < MAX_QUEST_LOG_SIZE)
SetQuestSlot(log_slot, 0);
bool rewarded = IsQuestRewarded(quest_id) && !quest->IsDFQuest();
// Not give XP in case already completed once repeatable quest
uint32 XP = rewarded ? 0 : uint32(quest->GetXPReward(this)*sWorld->getRate(RATE_XP_QUEST));
// handle SPELL_AURA_MOD_XP_QUEST_PCT auras
XP *= GetTotalAuraMultiplier(SPELL_AURA_MOD_XP_QUEST_PCT);
if (!IsMaxLevel())
GiveXP(XP, nullptr);
// Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
if (int32 moneyRew = quest->GetRewOrReqMoney(this))
{
ModifyMoney(moneyRew);
if (moneyRew > 0)
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, uint32(moneyRew));
}
// honor reward
if (uint32 honor = quest->CalculateHonorGain(GetLevel()))
RewardHonor(nullptr, 0, honor);
// title reward
if (quest->GetCharTitleId())
{
if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(quest->GetCharTitleId()))
SetTitle(titleEntry);
}
if (uint32 talents = quest->GetBonusTalents())
{
AddQuestRewardedTalentCount(talents);
InitTalentForLevel();
}
if (quest->GetRewArenaPoints())
ModifyArenaPoints(quest->GetRewArenaPoints());
// Send reward mail
if (uint32 mail_template_id = quest->GetRewMailTemplateId())
{
/// @todo Poor design of mail system
CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction();
if (uint32 questMailSender = quest->GetRewMailSenderEntry())
MailDraft(mail_template_id).SendMailTo(trans, this, questMailSender, MAIL_CHECK_MASK_HAS_BODY, quest->GetRewMailDelaySecs());
else
MailDraft(mail_template_id).SendMailTo(trans, this, questGiver, MAIL_CHECK_MASK_HAS_BODY, quest->GetRewMailDelaySecs());
CharacterDatabase.CommitTransaction(trans);
}
if (quest->IsDaily() || quest->IsDFQuest())
{
SetDailyQuestStatus(quest_id);
if (quest->IsDaily())
{
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, quest_id);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST_DAILY, quest_id);
}
}
else if (quest->IsWeekly())
SetWeeklyQuestStatus(quest_id);
else if (quest->IsMonthly())
SetMonthlyQuestStatus(quest_id);
else if (quest->IsSeasonal())
SetSeasonalQuestStatus(quest_id);
RemoveActiveQuest(quest_id, false);
if (quest->CanIncreaseRewardedQuestCounters())
SetRewardedQuest(quest_id);
if (announce)
SendQuestReward(quest, XP);
RewardReputation(quest);
// cast spells after mark quest complete (some spells have quest completed state requirements in spell_area data)
if (quest->GetRewSpellCast() > 0)
{
SpellInfo const* spellInfo = ASSERT_NOTNULL(sSpellMgr->GetSpellInfo(quest->GetRewSpellCast()));
if (questGiver->IsUnit() && !spellInfo->HasEffect(SPELL_EFFECT_LEARN_SPELL) && !spellInfo->HasEffect(SPELL_EFFECT_CREATE_ITEM) && !spellInfo->IsSelfCast())
{
if (Creature* creature = GetMap()->GetCreature(questGiver->GetGUID()))
creature->CastSpell(this, quest->GetRewSpellCast(), true);
}
else
CastSpell(this, quest->GetRewSpellCast(), true);
}
else if (quest->GetRewSpell() > 0)
{
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(quest->GetRewSpell());
if (questGiver->IsUnit() && !spellInfo->HasEffect(SPELL_EFFECT_LEARN_SPELL) && !spellInfo->HasEffect(SPELL_EFFECT_CREATE_ITEM) && !spellInfo->IsSelfCast())
{
if (Creature* creature = GetMap()->GetCreature(questGiver->GetGUID()))
creature->CastSpell(this, quest->GetRewSpell(), true);
}
else
CastSpell(this, quest->GetRewSpell(), true);
}
if (quest->GetZoneOrSort() > 0)
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE, quest->GetZoneOrSort());
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST, quest->GetQuestId());
// make full db save
SaveToDB(false);
if (quest->HasFlag(QUEST_FLAGS_FLAGS_PVP))
{
pvpInfo.IsHostile = pvpInfo.IsInHostileArea || HasPvPForcingQuest();
UpdatePvPState();
}
SendQuestUpdate(quest_id);
SendQuestGiverStatusMultiple();
//lets remove flag for delayed teleports
SetCanDelayTeleport(false);
sScriptMgr->OnQuestStatusChange(this, quest_id);
}
void Player::SetRewardedQuest(uint32 quest_id)
{
m_RewardedQuests.insert(quest_id);
m_RewardedQuestsSave[quest_id] = QUEST_DEFAULT_SAVE_TYPE;
}
void Player::FailQuest(uint32 questId)
{
if (Quest const* quest = sObjectMgr->GetQuestTemplate(questId))
{
QuestStatus qStatus = GetQuestStatus(questId);
// we can only fail incomplete quest or...
if (qStatus != QUEST_STATUS_INCOMPLETE)
{
// completed timed quest with no requirements
if (qStatus != QUEST_STATUS_COMPLETE || !quest->HasSpecialFlag(QUEST_SPECIAL_FLAGS_TIMED) || !quest->HasSpecialFlag(QUEST_SPECIAL_FLAGS_COMPLETED_AT_START))
return;
}
SetQuestStatus(questId, QUEST_STATUS_FAILED);
uint16 log_slot = FindQuestSlot(questId);
if (log_slot < MAX_QUEST_LOG_SIZE)
{
SetQuestSlotTimer(log_slot, 1);
SetQuestSlotState(log_slot, QUEST_STATE_FAIL);
}
if (quest->HasSpecialFlag(QUEST_SPECIAL_FLAGS_TIMED))
{
QuestStatusData& q_status = m_QuestStatus[questId];
RemoveTimedQuest(questId);
q_status.Timer = 0;
SendQuestTimerFailed(questId);
}
else
SendQuestFailed(questId);
// Destroy quest items on quest failure.
for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
if (ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(quest->RequiredItemId[i]))
if (quest->RequiredItemCount[i] > 0 && itemTemplate->Bonding == BIND_QUEST_ITEM)
DestroyItemCount(quest->RequiredItemId[i], 9999, true);
for (uint8 i = 0; i < QUEST_SOURCE_ITEM_IDS_COUNT; ++i)
if (ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(quest->ItemDrop[i]))
if (quest->ItemDropQuantity[i] > 0 && itemTemplate->Bonding == BIND_QUEST_ITEM)
DestroyItemCount(quest->ItemDrop[i], 9999, true);
}
}
void Player::AbandonQuest(uint32 questId)
{
if (Quest const* quest = sObjectMgr->GetQuestTemplate(questId))
{
// Destroy quest items on quest abandon.
for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
if (ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(quest->RequiredItemId[i]))
if (quest->RequiredItemCount[i] > 0 && itemTemplate->Bonding == BIND_QUEST_ITEM)
DestroyItemCount(quest->RequiredItemId[i], 9999, true);
for (uint8 i = 0; i < QUEST_SOURCE_ITEM_IDS_COUNT; ++i)
if (ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(quest->ItemDrop[i]))
if (quest->ItemDropQuantity[i] > 0 && itemTemplate->Bonding == BIND_QUEST_ITEM)
DestroyItemCount(quest->ItemDrop[i], 9999, true);
}
}
bool Player::SatisfyQuestSkill(Quest const* qInfo, bool msg) const
{
uint32 skill = qInfo->GetRequiredSkill();
// skip 0 case RequiredSkill
if (skill == 0)
return true;
// check skill value
if (GetSkillValue(skill) < qInfo->GetRequiredSkillValue())
{
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
TC_LOG_DEBUG("misc", "Player::SatisfyQuestSkill: Sent INVALIDREASON_DONT_HAVE_REQ (QuestID: {}) because player '{}' ({}) doesn't have the required skill value.",
qInfo->GetQuestId(), GetName(), GetGUID().ToString());
}
return false;
}
return true;
}
bool Player::SatisfyQuestLevel(Quest const* qInfo, bool msg) const
{
if (GetLevel() < qInfo->GetMinLevel())
{
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_QUEST_FAILED_LOW_LEVEL);
TC_LOG_DEBUG("misc", "Player::SatisfyQuestLevel: Sent INVALIDREASON_QUEST_FAILED_LOW_LEVEL (QuestID: {}) because player '{}' ({}) doesn't have the required (min) level.",
qInfo->GetQuestId(), GetName(), GetGUID().ToString());
}
return false;
}
if (qInfo->GetMaxLevel() > 0 && GetLevel() > qInfo->GetMaxLevel())
{
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); // There doesn't seem to be a specific response for too high player level
TC_LOG_DEBUG("misc", "Player::SatisfyQuestLevel: Sent INVALIDREASON_DONT_HAVE_REQ (QuestID: {}) because player '{}' ({}) doesn't have the required (max) level.",
qInfo->GetQuestId(), GetName(), GetGUID().ToString());
}
return false;
}
return true;
}
bool Player::SatisfyQuestLog(bool msg) const
{
// exist free slot
if (FindQuestSlot(0) < MAX_QUEST_LOG_SIZE)
return true;
if (msg)
{
WorldPacket data(SMSG_QUESTLOG_FULL, 0);
SendDirectMessage(&data);
}
return false;
}
bool Player::SatisfyQuestDependentQuests(Quest const* qInfo, bool msg) const
{
return SatisfyQuestPreviousQuest(qInfo, msg) && SatisfyQuestDependentPreviousQuests(qInfo, msg) &&
SatisfyQuestBreadcrumbQuest(qInfo, msg) && SatisfyQuestDependentBreadcrumbQuests(qInfo, msg);
}
bool Player::SatisfyQuestPreviousQuest(Quest const* qInfo, bool msg) const
{
// No previous quest (might be first quest in a series)
if (!qInfo->GetPrevQuestId())
return true;
uint32 prevId = std::abs(qInfo->GetPrevQuestId());
// If positive previous quest rewarded, return true
if (qInfo->GetPrevQuestId() > 0 && m_RewardedQuests.count(prevId) > 0)
return true;
// If negative previous quest active, return true
if (qInfo->GetPrevQuestId() < 0 && GetQuestStatus(prevId) == QUEST_STATUS_INCOMPLETE)
return true;
// Has positive prev. quest in non-rewarded state
// and negative prev. quest in non-active state
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
TC_LOG_DEBUG("misc", "Player::SatisfyQuestPreviousQuest: Sent INVALIDREASON_DONT_HAVE_REQ (QuestID: {}) because player '{}' ({}) doesn't have required quest {}.",
qInfo->GetQuestId(), GetName(), GetGUID().ToString(), prevId);
}
return false;
}
bool Player::SatisfyQuestDependentPreviousQuests(Quest const* qInfo, bool msg) const
{
// No previous quest (might be first quest in a series)
if (qInfo->DependentPreviousQuests.empty())
return true;
for (uint32 prevId : qInfo->DependentPreviousQuests)
{
// checked in startup
Quest const* questInfo = sObjectMgr->GetQuestTemplate(prevId);
ASSERT(questInfo);
// If any of the previous quests completed, return true
if (IsQuestRewarded(prevId))
{
// skip one-from-all exclusive group
if (questInfo->GetExclusiveGroup() >= 0)
return true;
// each-from-all exclusive group (< 0)
// can be start if only all quests in prev quest exclusive group completed and rewarded
auto bounds = sObjectMgr->GetExclusiveQuestGroupBounds(questInfo->GetExclusiveGroup());
for (auto itr = bounds.first; itr != bounds.second; ++itr)
{
// skip checked quest id, only state of other quests in group is interesting
uint32 exclusiveQuestId = itr->second;
if (exclusiveQuestId == prevId)
continue;
// alternative quest from group also must be completed and rewarded (reported)
if (!IsQuestRewarded(exclusiveQuestId))
{
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
TC_LOG_DEBUG("misc", "Player::SatisfyQuestDependentPreviousQuests: Sent INVALIDREASON_DONT_HAVE_REQ (QuestID: {}) because player '{}' ({}) doesn't have the required quest (1).",
qInfo->GetQuestId(), GetName(), GetGUID().ToString());
}
return false;
}
}
return true;
}
}
// Has only prev. quests in non-rewarded state
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
TC_LOG_DEBUG("misc", "Player::SatisfyQuestDependentPreviousQuests: Sent INVALIDREASON_DONT_HAVE_REQ (QuestID: {}) because player '{}' ({}) doesn't have required quest (2).",
qInfo->GetQuestId(), GetName(), GetGUID().ToString());
}
return false;
}
bool Player::SatisfyQuestBreadcrumbQuest(Quest const* qInfo, bool msg) const
{
uint32 breadcrumbTargetQuestId = std::abs(qInfo->GetBreadcrumbForQuestId());
//If this is not a breadcrumb quest.
if (!breadcrumbTargetQuestId)
return true;
// If the target quest is not available
if (!CanTakeQuest(sObjectMgr->GetQuestTemplate(breadcrumbTargetQuestId), false))
{
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
TC_LOG_DEBUG("misc", "Player::SatisfyQuestBreadcrumbQuest: Sent INVALIDREASON_DONT_HAVE_REQ (QuestID: {}) because target quest (QuestID: {}) is not available to player '{}' ({}).",
qInfo->GetQuestId(), breadcrumbTargetQuestId, GetName(), GetGUID().ToString());
}
return false;
}
return true;
}
bool Player::SatisfyQuestDependentBreadcrumbQuests(Quest const* qInfo, bool msg) const
{
for (uint32 breadcrumbQuestId : qInfo->DependentBreadcrumbQuests)
{
QuestStatus status = GetQuestStatus(breadcrumbQuestId);
// If any of the breadcrumb quests are in the quest log, return false.
if (status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_COMPLETE || status == QUEST_STATUS_FAILED)
{
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
TC_LOG_DEBUG("misc", "Player::SatisfyQuestDependentBreadcrumbQuests: Sent INVALIDREASON_DONT_HAVE_REQ (QuestID: {}) because player '{}' ({}) has a breadcrumb quest towards this quest in the quest log.",
qInfo->GetQuestId(), GetName(), GetGUID().ToString());
}
return false;
}
}
return true;
}
bool Player::SatisfyQuestClass(Quest const* qInfo, bool msg) const
{
uint32 reqClass = qInfo->GetRequiredClasses();
if (reqClass == 0)
return true;
if ((reqClass & GetClassMask()) == 0)
{
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
TC_LOG_DEBUG("misc", "Player::SatisfyQuestClass: Sent INVALIDREASON_DONT_HAVE_REQ (QuestID: {}) because player '{}' ({}) doesn't have required class.",
qInfo->GetQuestId(), GetName(), GetGUID().ToString());
}
return false;
}
return true;
}
bool Player::SatisfyQuestRace(Quest const* qInfo, bool msg) const
{
uint32 reqraces = qInfo->GetAllowableRaces();
if (reqraces == 0)
return true;
if ((reqraces & GetRaceMask()) == 0)
{
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_QUEST_FAILED_WRONG_RACE);
TC_LOG_DEBUG("misc", "Player::SatisfyQuestRace: Sent INVALIDREASON_QUEST_FAILED_WRONG_RACE (QuestID: {}) because player '{}' ({}) doesn't have required race.",
qInfo->GetQuestId(), GetName(), GetGUID().ToString());
}
return false;
}
return true;
}
bool Player::SatisfyQuestReputation(Quest const* qInfo, bool msg) const
{
uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
if (fIdMin && GetReputationMgr().GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
{
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
TC_LOG_DEBUG("misc", "Player::SatisfyQuestReputation: Sent INVALIDREASON_DONT_HAVE_REQ (QuestID: {}) because player '{}' ({}) doesn't required reputation (min).",
qInfo->GetQuestId(), GetName(), GetGUID().ToString());
}
return false;
}
uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
if (fIdMax && GetReputationMgr().GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
{
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
TC_LOG_DEBUG("misc", "SatisfyQuestReputation: Sent INVALIDREASON_DONT_HAVE_REQ (QuestID: {}) because player '{}' ({}) doesn't required reputation (max).",
qInfo->GetQuestId(), GetName(), GetGUID().ToString());
}
return false;
}
// ReputationObjective2 does not seem to be an objective requirement but a requirement
// to be able to accept the quest
uint32 fIdObj = qInfo->GetRepObjectiveFaction2();
if (fIdObj && GetReputationMgr().GetReputation(fIdObj) >= qInfo->GetRepObjectiveValue2())
{
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
TC_LOG_DEBUG("misc", "SatisfyQuestReputation: Sent INVALIDREASON_DONT_HAVE_REQ (questId: {}) because player does not have the required reputation (ReputationObjective2).", qInfo->GetQuestId());
}
return false;
}
return true;
}
bool Player::SatisfyQuestStatus(Quest const* qInfo, bool msg) const
{
if (GetQuestStatus(qInfo->GetQuestId()) == QUEST_STATUS_REWARDED)
{
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_QUEST_ALREADY_DONE);
TC_LOG_DEBUG("misc", "Player::SatisfyQuestStatus: Sent QUEST_STATUS_REWARDED (QuestID: {}) because player '{}' ({}) quest status is already REWARDED.",
qInfo->GetQuestId(), GetName(), GetGUID().ToString());
}
return false;
}
if (GetQuestStatus(qInfo->GetQuestId()) != QUEST_STATUS_NONE)
{
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_QUEST_ALREADY_ON);
TC_LOG_DEBUG("misc", "Player::SatisfyQuestStatus: Sent INVALIDREASON_QUEST_ALREADY_ON (QuestID: {}) because player '{}' ({}) quest status is not NONE.",
qInfo->GetQuestId(), GetName(), GetGUID().ToString());
}
return false;
}
return true;
}
bool Player::SatisfyQuestConditions(Quest const* qInfo, bool msg) const
{
if (!sConditionMgr->IsObjectMeetingNotGroupedConditions(CONDITION_SOURCE_TYPE_QUEST_AVAILABLE, qInfo->GetQuestId(), const_cast<Player*>(this)))
{
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
TC_LOG_DEBUG("misc", "Player::SatisfyQuestConditions: Sent INVALIDREASON_DONT_HAVE_REQ (QuestID: {}) because player '{}' ({}) doesn't meet conditions.",
qInfo->GetQuestId(), GetName(), GetGUID().ToString());
}
TC_LOG_DEBUG("condition", "Player::SatisfyQuestConditions: conditions not met for quest {}", qInfo->GetQuestId());
return false;
}
return true;
}
bool Player::SatisfyQuestTimed(Quest const* qInfo, bool msg) const
{
if (!m_timedquests.empty() && qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAGS_TIMED))
{
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_QUEST_ONLY_ONE_TIMED);
TC_LOG_DEBUG("misc", "Player::SatisfyQuestTimed: Sent INVALIDREASON_QUEST_ONLY_ONE_TIMED (QuestID: {}) because player '{}' ({}) is already on a timed quest.",
qInfo->GetQuestId(), GetName(), GetGUID().ToString());
}
return false;
}
return true;
}
bool Player::SatisfyQuestExclusiveGroup(Quest const* qInfo, bool msg) const
{
// non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
if (qInfo->GetExclusiveGroup() <= 0)
return true;
auto bounds = sObjectMgr->GetExclusiveQuestGroupBounds(qInfo->GetExclusiveGroup());
for (auto itr = bounds.first; itr != bounds.second; ++itr)
{
uint32 exclude_Id = itr->second;
// skip checked quest id, only state of other quests in group is interesting
if (exclude_Id == qInfo->GetQuestId())
continue;
// not allow have daily quest if daily quest from exclusive group already recently completed
Quest const* Nquest = sObjectMgr->GetQuestTemplate(exclude_Id);
ASSERT(Nquest);
if (!SatisfyQuestDay(Nquest, false) || !SatisfyQuestWeek(Nquest, false) || !SatisfyQuestSeasonal(Nquest, false))
{
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
TC_LOG_DEBUG("misc", "Player::SatisfyQuestExclusiveGroup: Sent INVALIDREASON_DONT_HAVE_REQ (QuestID: {}) because player '{}' ({}) already did daily quests in exclusive group.",
qInfo->GetQuestId(), GetName(), GetGUID().ToString());
}
return false;
}
// alternative quest already started or completed - but don't check rewarded states if both are repeatable
if (GetQuestStatus(exclude_Id) != QUEST_STATUS_NONE || (!(qInfo->IsRepeatable() && Nquest->IsRepeatable()) && GetQuestRewardStatus(exclude_Id)))
{
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
TC_LOG_DEBUG("misc", "Player::SatisfyQuestExclusiveGroup: Sent INVALIDREASON_DONT_HAVE_REQ (QuestID: {}) because player '{}' ({}) already did quest in exclusive group.",
qInfo->GetQuestId(), GetName(), GetGUID().ToString());
}
return false;
}
}
return true;
}
bool Player::SatisfyQuestDay(Quest const* qInfo, bool msg) const
{
if (!qInfo->IsDaily() && !qInfo->IsDFQuest())
return true;
if (qInfo->IsDFQuest())
{
if (m_DFQuests.find(qInfo->GetQuestId()) != m_DFQuests.end())
return false;
return true;
}
bool have_slot = false;
for (uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
{
uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
if (qInfo->GetQuestId() == id)
return false;
if (!id)
have_slot = true;
}
if (!have_slot)
{
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_DAILY_QUESTS_REMAINING);
TC_LOG_DEBUG("misc", "SatisfyQuestDay: Sent INVALIDREASON_DAILY_QUESTS_REMAINING (questId: {}) because player already did all possible quests today.", qInfo->GetQuestId());
}
return false;
}
return true;
}
bool Player::SatisfyQuestWeek(Quest const* qInfo, bool /*msg*/) const
{
if (!qInfo->IsWeekly() || m_weeklyquests.empty())
return true;
// if not found in cooldown list
return m_weeklyquests.find(qInfo->GetQuestId()) == m_weeklyquests.end();
}
bool Player::SatisfyQuestSeasonal(Quest const* qInfo, bool /*msg*/) const
{
if (!qInfo->IsSeasonal() || m_seasonalquests.empty())
return true;
auto itr = m_seasonalquests.find(qInfo->GetEventIdForQuest());
if (itr == m_seasonalquests.end() || itr->second.empty())
return true;
// if not found in cooldown list
return itr->second.find(qInfo->GetQuestId()) == itr->second.end();
}
bool Player::SatisfyQuestMonth(Quest const* qInfo, bool /*msg*/) const
{
if (!qInfo->IsMonthly() || m_monthlyquests.empty())
return true;
// if not found in cooldown list
return m_monthlyquests.find(qInfo->GetQuestId()) == m_monthlyquests.end();
}
bool Player::GiveQuestSourceItem(Quest const* quest)
{
uint32 srcitem = quest->GetSrcItemId();
if (srcitem > 0)
{
// Don't give source item if it is the same item used to start the quest
ItemTemplate const* itemTemplate = ASSERT_NOTNULL(sObjectMgr->GetItemTemplate(srcitem));
if (quest->GetQuestId() == itemTemplate->StartQuest)
return true;
uint32 count = quest->GetSrcItemCount();
if (count <= 0)
count = 1;
ItemPosCountVec dest;
InventoryResult msg = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, srcitem, count);
if (msg == EQUIP_ERR_OK)
{
Item* item = StoreNewItem(dest, srcitem, true);
SendNewItem(item, count, true, false);
return true;
}
// player already have max amount required item, just report success
else if (msg == EQUIP_ERR_ITEM_MAX_COUNT)
return true;
SendEquipError(msg, nullptr, nullptr, srcitem);
return false;
}
return true;
}
bool Player::TakeQuestSourceItem(uint32 questId, bool msg)
{
Quest const* quest = sObjectMgr->GetQuestTemplate(questId);
if (quest)
{
uint32 srcItemId = quest->GetSrcItemId();
ItemTemplate const* item = sObjectMgr->GetItemTemplate(srcItemId);
if (srcItemId > 0)
{
uint32 count = quest->GetSrcItemCount();
if (count <= 0)
count = 1;
// There are two cases where the source item is not destroyed:
// - Item cannot be unequipped (example: non-empty bags)
// - The source item is the item that started the quest, so the player is supposed to keep it (otherwise it was already destroyed in AddQuestAndCheckCompletion())
InventoryResult res = CanUnequipItems(srcItemId, count);
if (res != EQUIP_ERR_OK)
{
if (msg)
SendEquipError(res, nullptr, nullptr, srcItemId);
return false;
}
ASSERT(item);
if (item->StartQuest != questId)
DestroyItemCount(srcItemId, count, true, true);
}
}
return true;
}
bool Player::GetQuestRewardStatus(uint32 quest_id) const
{
Quest const* qInfo = sObjectMgr->GetQuestTemplate(quest_id);
if (qInfo)
{
if (qInfo->IsSeasonal() && !qInfo->IsRepeatable())
return !SatisfyQuestSeasonal(qInfo, false);
// for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
if (!qInfo->IsRepeatable())
return IsQuestRewarded(quest_id);
return false;
}
return false;
}
QuestStatus Player::GetQuestStatus(uint32 quest_id) const
{
if (quest_id)
{
QuestStatusMap::const_iterator itr = m_QuestStatus.find(quest_id);
if (itr != m_QuestStatus.end())
return itr->second.Status;
if (GetQuestRewardStatus(quest_id))
return QUEST_STATUS_REWARDED;
}
return QUEST_STATUS_NONE;
}
bool Player::CanShareQuest(uint32 quest_id) const
{
Quest const* qInfo = sObjectMgr->GetQuestTemplate(quest_id);
if (qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE))
{
QuestStatusMap::const_iterator itr = m_QuestStatus.find(quest_id);
if (itr != m_QuestStatus.end())
{
// in pool and not currently available (wintergrasp weekly, dalaran weekly) - can't share
if (!sQuestPoolMgr->IsQuestActive(quest_id))
{
SendPushToPartyResponse(this, QUEST_PARTY_MSG_CANT_BE_SHARED_TODAY);
return false;
}
return true;
}
}
return false;
}
void Player::SetQuestStatus(uint32 questId, QuestStatus status, bool update /*= true*/)
{
if (Quest const* quest = sObjectMgr->GetQuestTemplate(questId))
{
m_QuestStatus[questId].Status = status;
if (!quest->IsAutoComplete())
m_QuestStatusSave[questId] = QUEST_DEFAULT_SAVE_TYPE;
}
if (update)
SendQuestUpdate(questId);
sScriptMgr->OnQuestStatusChange(this, questId);
}
void Player::RemoveActiveQuest(uint32 questId, bool update /*= true*/)
{
QuestStatusMap::iterator itr = m_QuestStatus.find(questId);
if (itr != m_QuestStatus.end())
{
m_QuestStatus.erase(itr);
m_QuestStatusSave[questId] = QUEST_DELETE_SAVE_TYPE;
}
if (update)
SendQuestUpdate(questId);
}
void Player::RemoveRewardedQuest(uint32 questId, bool update /*= true*/)
{
RewardedQuestSet::iterator rewItr = m_RewardedQuests.find(questId);
if (rewItr != m_RewardedQuests.end())
{
m_RewardedQuests.erase(rewItr);
m_RewardedQuestsSave[questId] = QUEST_FORCE_DELETE_SAVE_TYPE;
}
// Remove seasonal quest also
Quest const* qInfo = sObjectMgr->GetQuestTemplate(questId);
ASSERT(qInfo);
if (qInfo->IsSeasonal())
{
uint16 eventId = qInfo->GetEventIdForQuest();
if (m_seasonalquests.find(eventId) != m_seasonalquests.end())
{
m_seasonalquests[eventId].erase(questId);
m_SeasonalQuestChanged = true;
}
}
if (update)
SendQuestUpdate(questId);
}
void Player::SendQuestUpdate(uint32 questId)
{
SpellAreaForQuestMapBounds saBounds = sSpellMgr->GetSpellAreaForQuestMapBounds(questId);
if (saBounds.first != saBounds.second)
{
std::set<uint32> aurasToRemove, aurasToCast;
uint32 zone = 0, area = 0;
GetZoneAndAreaId(zone, area);
for (SpellAreaForQuestMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
{
if (!itr->second->IsFitToRequirements(this, zone, area))
aurasToRemove.insert(itr->second->spellId);
else if (itr->second->autocast)
aurasToCast.insert(itr->second->spellId);
}
// Auras matching the requirements will be inside the aurasToCast container.
// Auras not matching the requirements may prevent using auras matching the requirements.
// aurasToCast will erase conflicting auras in aurasToRemove container to handle spells used by multiple quests.
for (auto itr = aurasToRemove.begin(); itr != aurasToRemove.end();)
{
bool auraRemoved = false;
for (const auto i : aurasToCast)
{
if (*itr == i)
{
itr = aurasToRemove.erase(itr);
auraRemoved = true;
break;
}
}
if (!auraRemoved)
++itr;
}
for (auto spellId : aurasToCast)
if (!HasAura(spellId))
CastSpell(this, spellId, true);
for (auto spellId : aurasToRemove)
RemoveAurasDueToSpell(spellId);
}
UpdateVisibleGameobjectsOrSpellClicks();
}
QuestGiverStatus Player::GetQuestDialogStatus(Object* questgiver)
{
QuestRelationResult qr, qir;
switch (questgiver->GetTypeId())
{
case TYPEID_GAMEOBJECT:
{
#ifdef ELUNA
if (Eluna* e = GetEluna())
e->GetDialogStatus(this, questgiver->ToGameObject());
#endif
if (auto ai = questgiver->ToGameObject()->AI())
if (auto questStatus = ai->GetDialogStatus(this))
return *questStatus;
qr = sObjectMgr->GetGOQuestRelations(questgiver->GetEntry());
qir = sObjectMgr->GetGOQuestInvolvedRelations(questgiver->GetEntry());
break;
}
case TYPEID_UNIT:
{
#ifdef ELUNA
if (Eluna* e = GetEluna())
e->GetDialogStatus(this, questgiver->ToCreature());
#endif
if (auto ai = questgiver->ToCreature()->AI())
if (auto questStatus = ai->GetDialogStatus(this))
return *questStatus;
qr = sObjectMgr->GetCreatureQuestRelations(questgiver->GetEntry());
qir = sObjectMgr->GetCreatureQuestInvolvedRelations(questgiver->GetEntry());
break;
}
default:
// it's impossible, but check
TC_LOG_ERROR("entities.player.quest", "GetQuestDialogStatus called for unexpected type {}", questgiver->GetTypeId());
return DIALOG_STATUS_NONE;
}
QuestGiverStatus result = DIALOG_STATUS_NONE;
for (uint32 questId : qir)
{
QuestGiverStatus result2 = DIALOG_STATUS_NONE;
Quest const* quest = sObjectMgr->GetQuestTemplate(questId);
if (!quest)
continue;
QuestStatus status = GetQuestStatus(questId);
if (status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(questId))
result2 = DIALOG_STATUS_REWARD;
else if (status == QUEST_STATUS_INCOMPLETE)
result2 = DIALOG_STATUS_INCOMPLETE;
if (quest->IsAutoComplete() && CanTakeQuest(quest, false) && quest->IsRepeatable() && !quest->IsDailyOrWeekly())
result2 = DIALOG_STATUS_REWARD_REP;
if (result2 > result)
result = result2;
}
for (uint32 questId : qr)
{
QuestGiverStatus result2 = DIALOG_STATUS_NONE;
Quest const* quest = sObjectMgr->GetQuestTemplate(questId);
if (!quest)
continue;
if (!sConditionMgr->IsObjectMeetingNotGroupedConditions(CONDITION_SOURCE_TYPE_QUEST_AVAILABLE, quest->GetQuestId(), this))
continue;
QuestStatus status = GetQuestStatus(questId);
if (status == QUEST_STATUS_NONE)
{
if (CanSeeStartQuest(quest))
{
if (SatisfyQuestLevel(quest, false))
{
bool isNotLowLevelQuest = GetLevel() <= (GetQuestLevel(quest) + sWorld->getIntConfig(CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF));
if (quest->IsRepeatable())
{
if (quest->IsDaily())
{
if (isNotLowLevelQuest)
result2 = DIALOG_STATUS_AVAILABLE_REP;
else
result2 = DIALOG_STATUS_LOW_LEVEL_AVAILABLE_REP;
}
else if (quest->IsWeekly() || quest->IsMonthly())
{
if (isNotLowLevelQuest)
result2 = DIALOG_STATUS_AVAILABLE;
else
result2 = DIALOG_STATUS_LOW_LEVEL_AVAILABLE;
}
else if (quest->IsAutoComplete())
{
if (isNotLowLevelQuest)
result2 = DIALOG_STATUS_REWARD_REP;
else
result2 = DIALOG_STATUS_LOW_LEVEL_REWARD_REP;
}
else
{
if (isNotLowLevelQuest)
result2 = DIALOG_STATUS_AVAILABLE;
else
result2 = DIALOG_STATUS_LOW_LEVEL_AVAILABLE;
}
}
else if (isNotLowLevelQuest)
result2 = DIALOG_STATUS_AVAILABLE;
else
result2 = DIALOG_STATUS_LOW_LEVEL_AVAILABLE;
}
else
result2 = DIALOG_STATUS_UNAVAILABLE;
}
}
if (result2 > result)
result = result2;
}
return result;
}
// not used in Trinity, but used in scripting code
uint16 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry) const
{
Quest const* qInfo = sObjectMgr->GetQuestTemplate(quest_id);
if (!qInfo)
return 0;
auto itr = m_QuestStatus.find(quest_id);
if (itr != m_QuestStatus.end())
for (uint8 j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
if (qInfo->RequiredNpcOrGo[j] == entry)
return itr->second.CreatureOrGOCount[j];
return 0;
}
void Player::AdjustQuestReqItemCount(Quest const* quest, QuestStatusData& questStatusData)
{
if (quest->HasSpecialFlag(QUEST_SPECIAL_FLAGS_DELIVER))
{
for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
{
uint32 reqitemcount = quest->RequiredItemCount[i];
if (reqitemcount != 0)
{
uint32 curitemcount = GetItemCount(quest->RequiredItemId[i], true);
questStatusData.ItemCount[i] = std::min(curitemcount, reqitemcount);
m_QuestStatusSave[quest->GetQuestId()] = QUEST_DEFAULT_SAVE_TYPE;
}
}
}
}
uint16 Player::FindQuestSlot(uint32 quest_id) const
{
for (uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
if (GetQuestSlotQuestId(i) == quest_id)
return i;
return MAX_QUEST_LOG_SIZE;
}
uint32 Player::GetQuestSlotQuestId(uint16 slot) const
{
return GetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_ID_OFFSET);
}
uint32 Player::GetQuestSlotState(uint16 slot) const
{
return GetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_STATE_OFFSET);
}
uint16 Player::GetQuestSlotCounter(uint16 slot, uint8 counter) const
{
return (uint16)(GetUInt64Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET) >> (counter * 16));
}
uint32 Player::GetQuestSlotTime(uint16 slot) const
{
return GetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_TIME_OFFSET);
}
void Player::SetQuestSlot(uint16 slot, uint32 quest_id, uint32 timer /*= 0*/)
{
SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_ID_OFFSET, quest_id);
SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_STATE_OFFSET, 0);
SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET, 0);
SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET + 1, 0);
SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_TIME_OFFSET, timer);
}
void Player::SetQuestSlotCounter(uint16 slot, uint8 counter, uint16 count)
{
uint64 val = GetUInt64Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET);
val &= ~((uint64)0xFFFF << (counter * 16));
val |= ((uint64)count << (counter * 16));
SetUInt64Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET, val);
}
void Player::SetQuestSlotState(uint16 slot, uint32 state)
{
SetFlag(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_STATE_OFFSET, state);
}
void Player::RemoveQuestSlotState(uint16 slot, uint32 state)
{
RemoveFlag(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_STATE_OFFSET, state);
}
void Player::SetQuestSlotTimer(uint16 slot, uint32 timer)
{
SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_TIME_OFFSET, timer);
}
void Player::SwapQuestSlot(uint16 slot1, uint16 slot2)
{
for (int i = 0; i < MAX_QUEST_OFFSET; ++i)
{
uint32 temp1 = GetUInt32Value(PLAYER_QUEST_LOG_1_1 + MAX_QUEST_OFFSET * slot1 + i);
uint32 temp2 = GetUInt32Value(PLAYER_QUEST_LOG_1_1 + MAX_QUEST_OFFSET * slot2 + i);
SetUInt32Value(PLAYER_QUEST_LOG_1_1 + MAX_QUEST_OFFSET * slot1 + i, temp2);
SetUInt32Value(PLAYER_QUEST_LOG_1_1 + MAX_QUEST_OFFSET * slot2 + i, temp1);
}
}
void Player::AreaExploredOrEventHappens(uint32 questId)
{
if (questId)
{
uint16 log_slot = FindQuestSlot(questId);
if (log_slot < MAX_QUEST_LOG_SIZE)
{
QuestStatusData& q_status = m_QuestStatus[questId];
// Dont complete failed quest
if (!q_status.Explored && q_status.Status != QUEST_STATUS_FAILED)
{
q_status.Explored = true;
m_QuestStatusSave[questId] = QUEST_DEFAULT_SAVE_TYPE;
SendQuestComplete(questId);
}
}
if (CanCompleteQuest(questId))
CompleteQuest(questId);
}
}
//not used in Trinityd, function for external script library
void Player::GroupEventHappens(uint32 questId, WorldObject const* pEventObject)
{
if (Group* group = GetGroup())
{
for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next())
{
Player* player = itr->GetSource();
// for any leave or dead (with not released body) group member at appropriate distance
if (player && player->IsAtGroupRewardDistance(pEventObject) && !player->GetCorpse())
player->AreaExploredOrEventHappens(questId);
}
}
else
AreaExploredOrEventHappens(questId);
}
void Player::ItemAddedQuestCheck(uint32 entry, uint32 count)
{
for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
{
uint32 questid = GetQuestSlotQuestId(i);
if (questid == 0)
continue;
QuestStatusData& q_status = m_QuestStatus[questid];
if (q_status.Status != QUEST_STATUS_INCOMPLETE)
continue;
Quest const* qInfo = sObjectMgr->GetQuestTemplate(questid);
if (!qInfo || !qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAGS_DELIVER))
continue;
for (uint8 j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
{
uint32 reqitem = qInfo->RequiredItemId[j];
if (reqitem == entry)
{
uint32 reqitemcount = qInfo->RequiredItemCount[j];
uint16 curitemcount = q_status.ItemCount[j];
if (curitemcount < reqitemcount)
{
q_status.ItemCount[j] = std::min<uint16>(q_status.ItemCount[j] + count, reqitemcount);
m_QuestStatusSave[questid] = QUEST_DEFAULT_SAVE_TYPE;
}
if (CanCompleteQuest(questid))
CompleteQuest(questid);
}
}
}
UpdateVisibleGameobjectsOrSpellClicks();
}
void Player::ItemRemovedQuestCheck(uint32 entry, uint32 count)
{
for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
{
uint32 questid = GetQuestSlotQuestId(i);
if (!questid)
continue;
Quest const* qInfo = sObjectMgr->GetQuestTemplate(questid);
if (!qInfo)
continue;
if (!qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAGS_DELIVER))
continue;
for (uint8 j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
{
uint32 reqitem = qInfo->RequiredItemId[j];
if (reqitem == entry)
{
QuestStatusData& q_status = m_QuestStatus[questid];
uint32 reqItemCount = qInfo->RequiredItemCount[j];
uint16 questStatusItemCount = q_status.ItemCount[j];
uint16 newItemCount = (count > questStatusItemCount) ? 0 : questStatusItemCount - count;
if (questStatusItemCount >= reqItemCount) // we may have more than what the status shows, we don't need reduce by count
newItemCount = GetItemCount(entry, false);
newItemCount = std::min<uint16>(newItemCount, reqItemCount);
if (newItemCount != q_status.ItemCount[j])
{
q_status.ItemCount[j] = newItemCount;
m_QuestStatusSave[questid] = QUEST_DEFAULT_SAVE_TYPE;
IncompleteQuest(questid);
}
}
}
}
UpdateVisibleGameobjectsOrSpellClicks();
}
void Player::KilledMonster(CreatureTemplate const* cInfo, ObjectGuid guid)
{
ASSERT(cInfo);
if (cInfo->Entry)
KilledMonsterCredit(cInfo->Entry, guid);
for (uint8 i = 0; i < MAX_KILL_CREDIT; ++i)
if (cInfo->KillCredit[i])
KilledMonsterCredit(cInfo->KillCredit[i], ObjectGuid::Empty);
}
void Player::KilledMonsterCredit(uint32 entry, ObjectGuid guid /*= ObjectGuid::Empty*/)
{
uint16 addkillcount = 1;
uint32 real_entry = entry;
Creature* killed = nullptr;
if (!guid.IsEmpty())
{
killed = GetMap()->GetCreature(guid);
if (killed && killed->GetEntry())
real_entry = killed->GetEntry();
}
StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_CREATURE, real_entry); // MUST BE CALLED FIRST
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, real_entry, addkillcount, killed);
for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
{
uint32 questid = GetQuestSlotQuestId(i);
if (!questid)
continue;
Quest const* qInfo = sObjectMgr->GetQuestTemplate(questid);
if (!qInfo)
continue;
// just if !ingroup || !noraidgroup || raidgroup
QuestStatusData& q_status = m_QuestStatus[questid];
if (q_status.Status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->IsAllowedInRaid(GetMap()->GetDifficulty())))
{
if (qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAGS_KILL) /*&& !qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAGS_CAST)*/)
{
for (uint8 j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
{
// skip GO activate objective or none
if (qInfo->RequiredNpcOrGo[j] <= 0)
continue;
uint32 reqkill = qInfo->RequiredNpcOrGo[j];
if (reqkill == real_entry)
{
uint32 reqkillcount = qInfo->RequiredNpcOrGoCount[j];
uint16 curkillcount = q_status.CreatureOrGOCount[j];
if (curkillcount < reqkillcount)
{
q_status.CreatureOrGOCount[j] = curkillcount + addkillcount;
m_QuestStatusSave[questid] = QUEST_DEFAULT_SAVE_TYPE;
SendQuestUpdateAddCreatureOrGo(qInfo, guid, j, curkillcount, addkillcount);
}
if (CanCompleteQuest(questid))
CompleteQuest(questid);
// same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
break;
}
}
}
}
}
}
void Player::KilledPlayerCredit(uint16 count)
{
for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
{
uint32 questid = GetQuestSlotQuestId(i);
if (!questid)
continue;
Quest const* qInfo = sObjectMgr->GetQuestTemplate(questid);
if (!qInfo)
continue;
// just if !ingroup || !noraidgroup || raidgroup
QuestStatusData& q_status = m_QuestStatus[questid];
if (q_status.Status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->IsAllowedInRaid(GetMap()->GetDifficulty())))
{
// PvP Killing quest require player to be in same zone as quest zone (only 2 quests so no doubt)
if (qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAGS_PLAYER_KILL) && GetZoneId() == static_cast<uint32>(qInfo->GetZoneOrSort()))
{
KilledPlayerCreditForQuest(count, qInfo);
break; // there is only one quest per zone
}
}
}
}
void Player::KilledPlayerCreditForQuest(uint16 count, Quest const* quest)
{
uint32 const questId = quest->GetQuestId();
auto it = m_QuestStatus.find(questId);
if (it == m_QuestStatus.end())
return;
QuestStatusData& questStatus = it->second;
uint16 curKill = questStatus.PlayerCount;
uint32 reqKill = quest->GetPlayersSlain();
if (curKill < reqKill)
{
count = std::min<uint16>(reqKill - curKill, count);
questStatus.PlayerCount = curKill + count;
m_QuestStatusSave[quest->GetQuestId()] = QUEST_DEFAULT_SAVE_TYPE;
SendQuestUpdateAddPlayer(quest, curKill, count);
}
if (CanCompleteQuest(questId))
CompleteQuest(questId);
}
void Player::KillCreditGO(uint32 entry, ObjectGuid guid)
{
uint16 addCastCount = 1;
for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
{
uint32 questid = GetQuestSlotQuestId(i);
if (!questid)
continue;
Quest const* qInfo = sObjectMgr->GetQuestTemplate(questid);
if (!qInfo)
continue;
QuestStatusData& q_status = m_QuestStatus[questid];
if (q_status.Status == QUEST_STATUS_INCOMPLETE)
{
if (qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAGS_CAST) /*&& !qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAGS_KILL)*/)
{
for (uint8 j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
{
uint32 reqTarget = 0;
// GO activate objective
if (qInfo->RequiredNpcOrGo[j] < 0)
// checked at quest_template loading
reqTarget = - qInfo->RequiredNpcOrGo[j];
// other not this creature/GO related objectives
if (reqTarget != entry)
continue;
uint32 reqCastCount = qInfo->RequiredNpcOrGoCount[j];
uint16 curCastCount = q_status.CreatureOrGOCount[j];
if (curCastCount < reqCastCount)
{
q_status.CreatureOrGOCount[j] = curCastCount + addCastCount;
m_QuestStatusSave[questid] = QUEST_DEFAULT_SAVE_TYPE;
SendQuestUpdateAddCreatureOrGo(qInfo, guid, j, curCastCount, addCastCount);
}
if (CanCompleteQuest(questid))
CompleteQuest(questid);
// same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
break;
}
}
}
}
}
void Player::TalkedToCreature(uint32 entry, ObjectGuid guid)
{
uint16 addTalkCount = 1;
for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
{
uint32 questid = GetQuestSlotQuestId(i);
if (!questid)
continue;
Quest const* qInfo = sObjectMgr->GetQuestTemplate(questid);
if (!qInfo)
continue;
QuestStatusData& q_status = m_QuestStatus[questid];
if (q_status.Status == QUEST_STATUS_INCOMPLETE)
{
if (qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAGS_KILL | QUEST_SPECIAL_FLAGS_CAST | QUEST_SPECIAL_FLAGS_SPEAKTO))
{
for (uint8 j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
{
// skip gameobject objectives
if (qInfo->RequiredNpcOrGo[j] < 0)
continue;
uint32 reqTarget = 0;
if (qInfo->RequiredNpcOrGo[j] > 0) // creature activate objectives
// checked at quest_template loading
reqTarget = qInfo->RequiredNpcOrGo[j];
else
continue;
if (reqTarget == entry)
{
uint32 reqTalkCount = qInfo->RequiredNpcOrGoCount[j];
uint16 curTalkCount = q_status.CreatureOrGOCount[j];
if (curTalkCount < reqTalkCount)
{
q_status.CreatureOrGOCount[j] = curTalkCount + addTalkCount;
m_QuestStatusSave[questid] = QUEST_DEFAULT_SAVE_TYPE;
SendQuestUpdateAddCreatureOrGo(qInfo, guid, j, curTalkCount, addTalkCount);
}
if (CanCompleteQuest(questid))
CompleteQuest(questid);
// same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
continue;
}
}
}
}
}
}
void Player::MoneyChanged(uint32 count)
{
for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
{
uint32 questid = GetQuestSlotQuestId(i);
if (!questid)
continue;
Quest const* qInfo = sObjectMgr->GetQuestTemplate(questid);
if (qInfo && qInfo->GetRewOrReqMoney() < 0)
{
QuestStatusData& q_status = m_QuestStatus[questid];
if (q_status.Status == QUEST_STATUS_INCOMPLETE)
{
if (int32(count) >= -qInfo->GetRewOrReqMoney())
{
if (CanCompleteQuest(questid))
CompleteQuest(questid);
}
}
else if (q_status.Status == QUEST_STATUS_COMPLETE)
{
if (int32(count) < -qInfo->GetRewOrReqMoney())
IncompleteQuest(questid);
}
}
}
}
void Player::ReputationChanged(FactionEntry const* factionEntry)
{
for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
{
if (uint32 questid = GetQuestSlotQuestId(i))
{
if (Quest const* qInfo = sObjectMgr->GetQuestTemplate(questid))
{
if (qInfo->GetRepObjectiveFaction() == factionEntry->ID)
{
QuestStatusData& q_status = m_QuestStatus[questid];
if (q_status.Status == QUEST_STATUS_INCOMPLETE)
{
if (GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
if (CanCompleteQuest(questid))
CompleteQuest(questid);
}
else if (q_status.Status == QUEST_STATUS_COMPLETE)
{
if (GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
IncompleteQuest(questid);
}
}
}
}
}
}
void Player::ReputationChanged2(FactionEntry const* factionEntry)
{
for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
{
if (uint32 questid = GetQuestSlotQuestId(i))
{
if (Quest const* qInfo = sObjectMgr->GetQuestTemplate(questid))
{
if (qInfo->GetRepObjectiveFaction2() == factionEntry->ID)
{
QuestStatusData& q_status = m_QuestStatus[questid];
if (q_status.Status == QUEST_STATUS_INCOMPLETE)
{
if (GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue2())
if (CanCompleteQuest(questid))
CompleteQuest(questid);
}
else if (q_status.Status == QUEST_STATUS_COMPLETE)
{
if (GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue2())
IncompleteQuest(questid);
}
}
}
}
}
}
bool Player::HasQuestForItem(uint32 itemid, uint32 excludeQuestId /* 0 */, bool turnIn /* false */) const
{
for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
{
uint32 questid = GetQuestSlotQuestId(i);
if (questid == 0 || questid == excludeQuestId)
continue;
QuestStatusMap::const_iterator qs_itr = m_QuestStatus.find(questid);
if (qs_itr == m_QuestStatus.end())
continue;
QuestStatusData const& q_status = qs_itr->second;
if ((q_status.Status == QUEST_STATUS_INCOMPLETE) || (turnIn && q_status.Status == QUEST_STATUS_COMPLETE))
{
Quest const* qinfo = sObjectMgr->GetQuestTemplate(questid);
if (!qinfo)
continue;
// hide quest if player is in raid-group and quest is no raid quest
if (GetGroup() && GetGroup()->isRaidGroup() && !qinfo->IsAllowedInRaid(GetMap()->GetDifficulty()))
if (!InBattleground()) //there are two ways.. we can make every bg-quest a raidquest, or add this code here.. i don't know if this can be exploited by other quests, but i think all other quests depend on a specific area.. but keep this in mind, if something strange happens later
continue;
// There should be no mixed ReqItem/ReqSource drop
// This part for ReqItem drop
for (uint8 j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
{
if ((itemid == qinfo->RequiredItemId[j] && q_status.ItemCount[j] < qinfo->RequiredItemCount[j]) || (turnIn && q_status.ItemCount[j] >= qinfo->RequiredItemCount[j]))
return true;
}
// This part - for ReqSource
for (uint8 j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j)
{
// examined item is a source item
if (qinfo->ItemDrop[j] == itemid)
{
ItemTemplate const* pProto = ASSERT_NOTNULL(sObjectMgr->GetItemTemplate(itemid));
uint32 ownedCount = GetItemCount(itemid, true);
// 'unique' item
if ((pProto->MaxCount && int32(ownedCount) < pProto->MaxCount) || (turnIn && int32(ownedCount) >= pProto->MaxCount))
return true;
// allows custom amount drop when not 0
if (qinfo->ItemDropQuantity[j])
{
if (ownedCount < qinfo->ItemDropQuantity[j] || turnIn )
return true;
} else if (ownedCount < pProto->GetMaxStackSize())
return true;
}
}
}
}
return false;
}
void Player::SendQuestComplete(uint32 quest_id) const
{
if (quest_id)
{
WorldPacket data(SMSG_QUESTUPDATE_COMPLETE, 4);
data << uint32(quest_id);
SendDirectMessage(&data);
}
}
void Player::SendQuestReward(Quest const* quest, uint32 XP) const
{
uint32 questId = quest->GetQuestId();
sGameEventMgr->HandleQuestComplete(questId);
uint32 xp;
if (!IsMaxLevel())
xp = XP;
else
xp = 0;
WorldPacket data(SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4));
data << uint32(questId);
data << uint32(xp);
data << uint32(quest->GetRewOrReqMoney(this));
data << uint32(10 * quest->CalculateHonorGain(GetQuestLevel(quest)));
data << uint32(quest->GetBonusTalents()); // bonus talents
data << uint32(quest->GetRewArenaPoints());
SendDirectMessage(&data);
}
void Player::SendQuestFailed(uint32 questId, InventoryResult reason) const
{
if (questId)
{
WorldPacket data(SMSG_QUESTGIVER_QUEST_FAILED, 4 + 4);
data << uint32(questId);
data << uint32(reason); // failed reason (valid reasons: 4, 16, 50, 17, 74, other values show default message)
SendDirectMessage(&data);
}
}
void Player::SendQuestTimerFailed(uint32 quest_id) const
{
if (quest_id)
{
WorldPacket data(SMSG_QUESTUPDATE_FAILEDTIMER, 4);
data << uint32(quest_id);
SendDirectMessage(&data);
TC_LOG_DEBUG("network", "WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
}
}
void Player::SendCanTakeQuestResponse(QuestFailedReason msg) const
{
WorldPacket data(SMSG_QUESTGIVER_QUEST_INVALID, 4);
data << uint32(msg);
SendDirectMessage(&data);
TC_LOG_DEBUG("network", "WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
}
void Player::SendQuestConfirmAccept(Quest const* quest, Player* pReceiver) const
{
if (pReceiver)
{
std::string strTitle = quest->GetTitle();
LocaleConstant localeConstant = pReceiver->GetSession()->GetSessionDbLocaleIndex();
if (localeConstant != LOCALE_enUS)
if (QuestLocale const* pLocale = sObjectMgr->GetQuestLocale(quest->GetQuestId()))
ObjectMgr::GetLocaleString(pLocale->Title, localeConstant, strTitle);
WorldPacket data(SMSG_QUEST_CONFIRM_ACCEPT, (4 + strTitle.size() + 8));
data << uint32(quest->GetQuestId());
data << strTitle;
data << GetGUID();
pReceiver->SendDirectMessage(&data);
TC_LOG_DEBUG("network", "WORLD: Sent SMSG_QUEST_CONFIRM_ACCEPT");
}
}
void Player::SendPushToPartyResponse(Player const* player, QuestShareMessages msg) const
{
if (player)
{
WorldPacket data(MSG_QUEST_PUSH_RESULT, 8 + 1);
data << player->GetGUID();
data << uint8(msg); // valid values: 0-8
SendDirectMessage(&data);
TC_LOG_DEBUG("network", "WORLD: Sent MSG_QUEST_PUSH_RESULT");
}
}
void Player::SendQuestUpdateAddItem(Quest const* /*quest*/, uint32 /*item_idx*/, uint16 /*count*/) const
{
WorldPacket data(SMSG_QUESTUPDATE_ADD_ITEM, 0);
TC_LOG_DEBUG("network", "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM");
//data << quest->RequiredItemId[item_idx];
//data << count;
SendDirectMessage(&data);
}
void Player::SendQuestUpdateAddCreatureOrGo(Quest const* quest, ObjectGuid guid, uint32 creatureOrGO_idx, uint16 old_count, uint16 add_count)
{
ASSERT(old_count + add_count < 65536 && "mob/GO count store in 16 bits 2^16 = 65536 (0..65536)");
int32 entry = quest->RequiredNpcOrGo[creatureOrGO_idx];
if (entry < 0)
// client expected gameobject template id in form (id|0x80000000)
entry = (-entry) | 0x80000000;
WorldPacket data(SMSG_QUESTUPDATE_ADD_KILL, (4*4+8));
TC_LOG_DEBUG("network", "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL");
data << uint32(quest->GetQuestId());
data << uint32(entry);
data << uint32(old_count + add_count);
data << uint32(quest->RequiredNpcOrGoCount[ creatureOrGO_idx ]);
data << guid;
SendDirectMessage(&data);
uint16 log_slot = FindQuestSlot(quest->GetQuestId());
if (log_slot < MAX_QUEST_LOG_SIZE)
SetQuestSlotCounter(log_slot, creatureOrGO_idx, GetQuestSlotCounter(log_slot, creatureOrGO_idx) + add_count);
sScriptMgr->OnQuestObjectiveProgress(this, quest, creatureOrGO_idx, old_count + add_count);
}
void Player::SendQuestUpdateAddPlayer(Quest const* quest, uint16 old_count, uint16 add_count)
{
ASSERT(old_count + add_count < 65536 && "player count store in 16 bits");
WorldPacket data(SMSG_QUESTUPDATE_ADD_PVP_KILL, (3*4));
data << uint32(quest->GetQuestId());
data << uint32(old_count + add_count);
data << uint32(quest->GetPlayersSlain());
SendDirectMessage(&data);
uint16 log_slot = FindQuestSlot(quest->GetQuestId());
if (log_slot < MAX_QUEST_LOG_SIZE)
SetQuestSlotCounter(log_slot, QUEST_PVP_KILL_SLOT, GetQuestSlotCounter(log_slot, QUEST_PVP_KILL_SLOT) + add_count);
}
void Player::SendQuestGiverStatusMultiple()
{
uint32 count = 0;
WorldPacket data(SMSG_QUESTGIVER_STATUS_MULTIPLE, 4);
data << uint32(count); // placeholder
for (auto itr = m_clientGUIDs.begin(); itr != m_clientGUIDs.end(); ++itr)
{
uint32 questStatus = DIALOG_STATUS_NONE;
if (itr->IsAnyTypeCreature())
{
// need also pet quests case support
Creature* questgiver = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, *itr);
if (!questgiver || questgiver->IsHostileTo(this))
continue;
if (!questgiver->HasNpcFlag(UNIT_NPC_FLAG_QUESTGIVER))
continue;
questStatus = GetQuestDialogStatus(questgiver);
data << questgiver->GetGUID();
data << uint8(questStatus);
++count;
}
else if (itr->IsGameObject())
{
GameObject* questgiver = GetMap()->GetGameObject(*itr);
if (!questgiver || questgiver->GetGoType() != GAMEOBJECT_TYPE_QUESTGIVER)
continue;
questStatus = GetQuestDialogStatus(questgiver);
data << questgiver->GetGUID();
data << uint8(questStatus);
++count;
}
}
data.put<uint32>(0, count); // write real count
SendDirectMessage(&data);
}
bool Player::HasPvPForcingQuest() const
{
for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
{
uint32 questId = GetQuestSlotQuestId(i);
if (questId == 0)
continue;
Quest const* quest = sObjectMgr->GetQuestTemplate(questId);
if (!quest)
continue;
if (quest->HasFlag(QUEST_FLAGS_FLAGS_PVP))
return true;
}
return false;
}
/*********************************************************/
/*** LOAD SYSTEM ***/
/*********************************************************/
void Player::_LoadDeclinedNames(PreparedQueryResult result)
{
if (!result)
return;
delete m_declinedname;
m_declinedname = new DeclinedName;
for (uint8 i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
m_declinedname->name[i] = (*result)[i].GetString();
}
void Player::_LoadArenaTeamInfo(PreparedQueryResult result)
{
// arenateamid, played_week, played_season, personal_rating
memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32) * MAX_ARENA_SLOT * ARENA_TEAM_END);
uint16 personalRatingCache[] = {0, 0, 0};
if (result)
{
do
{
Field* fields = result->Fetch();
uint32 arenaTeamId = fields[0].GetUInt32();
ArenaTeam* arenaTeam = sArenaTeamMgr->GetArenaTeamById(arenaTeamId);
if (!arenaTeam)
{
TC_LOG_ERROR("entities.player.loading", "Player::_LoadArenaTeamInfo: couldn't load arenateam {}", arenaTeamId);
continue;
}
uint8 arenaSlot = arenaTeam->GetSlot();
ASSERT(arenaSlot < 3);
personalRatingCache[arenaSlot] = fields[4].GetUInt16();
SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_ID, arenaTeamId);
SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_TYPE, arenaTeam->GetType());
SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_MEMBER, (arenaTeam->GetCaptain() == GetGUID()) ? 0 : 1);
SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_GAMES_WEEK, uint32(fields[1].GetUInt16()));
SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_GAMES_SEASON, uint32(fields[2].GetUInt16()));
SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_WINS_SEASON, uint32(fields[3].GetUInt16()));
}
while (result->NextRow());
}
for (uint8 slot = 0; slot <= 2; ++slot)
{
SetArenaTeamInfoField(slot, ARENA_TEAM_PERSONAL_RATING, uint32(personalRatingCache[slot]));
}
}
void Player::_LoadEquipmentSets(PreparedQueryResult result)
{
// SetPQuery(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS, "SELECT setguid, setindex, name, iconname, item0, item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14, item15, item16, item17, item18 FROM character_equipmentsets WHERE guid = '{}' ORDER BY setindex", GUID_LOPART(m_guid));
if (!result)
return;
do
{
Field* fields = result->Fetch();
EquipmentSetInfo eqSet;
eqSet.Data.Guid = fields[0].GetUInt64();
eqSet.Data.SetID = fields[1].GetUInt8();
eqSet.Data.SetName = fields[2].GetString();
eqSet.Data.SetIcon = fields[3].GetString();
eqSet.Data.IgnoreMask = fields[4].GetUInt32();
eqSet.State = EQUIPMENT_SET_UNCHANGED;
for (uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
if (ObjectGuid::LowType guid = fields[5 + i].GetUInt32())
eqSet.Data.Pieces[i] = ObjectGuid::Create<HighGuid::Item>(guid);
if (eqSet.Data.SetID >= MAX_EQUIPMENT_SET_INDEX) // client limit
continue;
_equipmentSets[eqSet.Data.Guid] = eqSet;
} while (result->NextRow());
}
void Player::_LoadBGData(PreparedQueryResult result)
{
if (!result)
return;
Field* fields = result->Fetch();
// Expecting only one row
// 0 1 2 3 4 5 6 7 8 9
// SELECT instanceId, team, joinX, joinY, joinZ, joinO, joinMapId, taxiStart, taxiEnd, mountSpell FROM character_battleground_data WHERE guid = ?
m_bgData.bgInstanceID = fields[0].GetUInt32();
m_bgData.bgTeam = fields[1].GetUInt16();
m_bgData.joinPos = WorldLocation(fields[6].GetUInt16(), // Map
fields[2].GetFloat(), // X
fields[3].GetFloat(), // Y
fields[4].GetFloat(), // Z
fields[5].GetFloat()); // Orientation
m_bgData.taxiPath[0] = fields[7].GetUInt32();
m_bgData.taxiPath[1] = fields[8].GetUInt32();
m_bgData.mountSpell = fields[9].GetUInt32();
}
bool Player::LoadPositionFromDB(uint32& mapid, float& x, float& y, float& z, float& o, bool& in_flight, ObjectGuid guid)
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_POSITION);
stmt->setUInt32(0, guid.GetCounter());
PreparedQueryResult result = CharacterDatabase.Query(stmt);
if (!result)
return false;
Field* fields = result->Fetch();
x = fields[0].GetFloat();
y = fields[1].GetFloat();
z = fields[2].GetFloat();
o = fields[3].GetFloat();
mapid = fields[4].GetUInt16();
in_flight = !fields[5].GetString().empty();
return true;
}
void Player::SetHomebind(WorldLocation const& loc, uint32 areaId)
{
loc.GetPosition(m_homebindX, m_homebindY, m_homebindZ);
m_homebindMapId = loc.GetMapId();
m_homebindAreaId = areaId;
// update sql homebind
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_PLAYER_HOMEBIND);
stmt->setUInt16(0, m_homebindMapId);
stmt->setUInt16(1, m_homebindAreaId);
stmt->setFloat (2, m_homebindX);
stmt->setFloat (3, m_homebindY);
stmt->setFloat (4, m_homebindZ);
stmt->setUInt32(5, GetGUID().GetCounter());
CharacterDatabase.Execute(stmt);
}
void Player::SendBindPointUpdate()
{
WorldPackets::Misc::BindPointUpdate packet;
packet.BindPosition = Position(m_homebindX, m_homebindY, m_homebindZ);
packet.BindMapID = m_homebindMapId;
packet.BindAreaID = m_homebindAreaId;
SendDirectMessage(packet.Write());
}
bool Player::IsLoading() const
{
return GetSession()->PlayerLoading();
}
bool Player::LoadFromDB(ObjectGuid guid, CharacterDatabaseQueryHolder const& holder)
{
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
//QueryResult* result = CharacterDatabase.PQuery("SELECT guid, account, name, race, class, gender, level, xp, money, skin, face, hairStyle, hairColor, facialStyle, bankSlots, restState, playerFlags, "
// 17 18 19 20 21 22 23 24 25 26 27 28 29
//"position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, "
// 30 31 32 33 34 35 36 37 38 39 40 41 42 43
//"resettalents_time, trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, online, death_expire_time, taxi_path, instance_mode_mask, "
// 44 45 46 47 48 49 50 51 52 53 54
//"arenaPoints, totalHonorPoints, todayHonorPoints, yesterdayHonorPoints, totalKills, todayKills, yesterdayKills, chosenTitle, knownCurrencies, watchedFaction, drunk, "
// 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
//"health, power1, power2, power3, power4, power5, power6, power7, instance_id, talentGroupsCount, activeTalentGroup, exploredZones, equipmentCache, ammoId, knownTitles, actionBars, grantableLevels, fishing_steps FROM characters WHERE guid = '{}'", guid);
PreparedQueryResult result = holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_FROM);
if (!result)
{
std::string name = "<unknown>";
sCharacterCache->GetCharacterNameByGuid(guid, name);
TC_LOG_ERROR("entities.player.loading", "Player::LoadFromDB: Player '{}' ({}) not found in table `characters`, can't load. ", name, guid.ToString());
return false;
}
Field* fields = result->Fetch();
uint32 dbAccountId = fields[1].GetUInt32();
// check if the character's account in the db and the logged in account match.
// player should be able to load/delete character only with correct account!
if (dbAccountId != GetSession()->GetAccountId())
{
TC_LOG_ERROR("entities.player.loading", "Player::LoadFromDB: Player ({}) loading from wrong account (is: {}, should be: {})", guid.ToString(), GetSession()->GetAccountId(), dbAccountId);
return false;
}
if (holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_BANNED))
{
TC_LOG_ERROR("entities.player.loading", "Player::LoadFromDB: Player ({}) is banned, can't load.", guid.ToString());
return false;
}
Object::_Create(guid);
m_name = fields[2].GetString();
// check name limitations
if (ObjectMgr::CheckPlayerName(m_name, GetSession()->GetSessionDbcLocale()) != CHAR_NAME_SUCCESS ||
(!GetSession()->HasPermission(rbac::RBAC_PERM_SKIP_CHECK_CHARACTER_CREATION_RESERVEDNAME) && sObjectMgr->IsReservedName(m_name)))
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ADD_AT_LOGIN_FLAG);
stmt->setUInt16(0, uint16(AT_LOGIN_RENAME));
stmt->setUInt32(1, guid.GetCounter());
CharacterDatabase.Execute(stmt);
return false;
}
Gender gender = Gender(fields[5].GetUInt8());
if (!IsValidGender(gender))
{
TC_LOG_ERROR("entities.player.loading", "Player::LoadFromDB: Player ({}) has wrong gender ({}), can't load.", guid.ToString(), uint32(gender));
return false;
}
SetRace(fields[3].GetUInt8());
SetClass(fields[4].GetUInt8());
SetGender(gender);
// check if race/class combination is valid
PlayerInfo const* info = sObjectMgr->GetPlayerInfo(GetRace(), GetClass());
if (!info)
{
TC_LOG_ERROR("entities.player.loading", "Player::LoadFromDB: Player ({}) has wrong race/class ({}/{}), can't load.", guid.ToString(), GetRace(), GetClass());
return false;
}
SetLevel(fields[6].GetUInt8(), false);
SetXP(fields[7].GetUInt32());
if (!_LoadIntoDataField(fields[66].GetString(), PLAYER_EXPLORED_ZONES_1, PLAYER_EXPLORED_ZONES_SIZE))
TC_LOG_WARN("entities.player.loading", "Player::LoadFromDB: Player ({}) has invalid exploredzones data ({}). Forcing partial load.", guid.ToString(), fields[66].GetCString());
if (!_LoadIntoDataField(fields[69].GetString(), PLAYER__FIELD_KNOWN_TITLES, KNOWN_TITLES_SIZE * 2))
TC_LOG_WARN("entities.player.loading", "Player::LoadFromDB: Player ({}) has invalid knowntitles mask ({}). Forcing partial load.", guid.ToString(), fields[69].GetCString());
SetObjectScale(1.0f);
SetHoverHeight(1.0f);
// load achievements before anything else to prevent multiple gains for the same achievement/criteria on every loading (as loading does call UpdateAchievementCriteria)
m_achievementMgr->LoadFromDB(holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_ACHIEVEMENTS), holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_CRITERIA_PROGRESS));
uint32 money = fields[8].GetUInt32();
if (money > MAX_MONEY_AMOUNT)
money = MAX_MONEY_AMOUNT;
SetMoney(money);
SetSkinId(fields[9].GetUInt8());
SetFaceId(fields[10].GetUInt8());
SetHairStyleId(fields[11].GetUInt8());
SetHairColorId(fields[12].GetUInt8());
SetFacialStyle(fields[13].GetUInt8());
SetBankBagSlotCount(fields[14].GetUInt8());
SetRestState(fields[15].GetUInt8());
SetNativeGender(Gender(fields[5].GetUInt8()));
SetByteValue(PLAYER_BYTES_3, PLAYER_BYTES_3_OFFSET_INEBRIATION, fields[54].GetUInt8());
if (!ValidateAppearance(
fields[3].GetUInt8(), // race
fields[4].GetUInt8(), // class
gender, GetHairStyleId(), GetHairColorId(), GetFaceId(), GetFacialStyle(), GetSkinId()))
{
TC_LOG_ERROR("entities.player.loading", "Player::LoadFromDB: Player ({}) has wrong Appearance values (Hair/Skin/Color), can't load.", guid.ToString());
return false;
}
SetUInt32Value(PLAYER_FLAGS, fields[16].GetUInt32());
SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, fields[53].GetUInt32());
SetUInt64Value(PLAYER_FIELD_KNOWN_CURRENCIES, fields[52].GetUInt64());
SetUInt32Value(PLAYER_AMMO_ID, fields[68].GetUInt32());
// set which actionbars the client has active - DO NOT REMOVE EVER AGAIN (can be changed though, if it does change fieldwise)
SetByteValue(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTES_OFFSET_ACTION_BAR_TOGGLES, fields[70].GetUInt8());
m_fishingSteps = fields[72].GetUInt8();
InitDisplayIds();
// cleanup inventory related item value fields (it will be filled correctly in _LoadInventory)
for (uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
{
SetGuidValue(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), ObjectGuid::Empty);
SetVisibleItemSlot(slot, nullptr);
delete m_items[slot];
m_items[slot] = nullptr;
}
TC_LOG_DEBUG("entities.player.loading", "Player::LoadFromDB: Load Basic value of player '{}' is: ", m_name);
outDebugValues();
//Need to call it to initialize m_team (m_team can be calculated from race)
//Other way is to saves m_team into characters table.
SetFactionForRace(GetRace());
// load home bind and check in same time class/race pair, it used later for restore broken positions
if (!_LoadHomeBind(holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_HOME_BIND)))
return false;
InitPrimaryProfessions(); // to max set before any spell loaded
// init saved position, and fix it later if problematic
ObjectGuid::LowType transLowGUID = fields[35].GetUInt32();
Relocate(fields[17].GetFloat(), fields[18].GetFloat(), fields[19].GetFloat(), fields[21].GetFloat());
uint32 mapId = fields[20].GetUInt16();
uint32 instanceId = fields[63].GetUInt32();
uint32 dungeonDiff = fields[43].GetUInt8() & 0x0F;
if (dungeonDiff >= MAX_DUNGEON_DIFFICULTY)
dungeonDiff = DUNGEON_DIFFICULTY_NORMAL;
uint32 raidDiff = (fields[43].GetUInt8() >> 4) & 0x0F;
if (raidDiff >= MAX_RAID_DIFFICULTY)
raidDiff = RAID_DIFFICULTY_10MAN_NORMAL;
SetDungeonDifficulty(Difficulty(dungeonDiff)); // may be changed in _LoadGroup
SetRaidDifficulty(Difficulty(raidDiff)); // may be changed in _LoadGroup
std::string taxi_nodes = fields[42].GetString();
auto RelocateToHomebind = [this, &mapId, &instanceId]() { mapId = m_homebindMapId; instanceId = 0; Relocate(m_homebindX, m_homebindY, m_homebindZ); };
_LoadGroup(holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_GROUP));
_LoadArenaTeamInfo(holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_ARENA_INFO));
SetArenaPoints(fields[44].GetUInt32());
// check arena teams integrity
for (uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
{
uint32 arena_team_id = GetArenaTeamId(arena_slot);
if (!arena_team_id)
continue;
if (ArenaTeam* at = sArenaTeamMgr->GetArenaTeamById(arena_team_id))
if (at->IsMember(GetGUID()))
continue;
// arena team not exist or not member, cleanup fields
for (int j = 0; j < 6; ++j)
SetArenaTeamInfoField(arena_slot, ArenaTeamInfoType(j), 0);
}
SetHonorPoints(fields[45].GetUInt32());
SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, fields[46].GetUInt32());
SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, fields[47].GetUInt32());
SetUInt32Value(PLAYER_FIELD_LIFETIME_HONORABLE_KILLS, fields[48].GetUInt32());
SetUInt16Value(PLAYER_FIELD_KILLS, 0, fields[49].GetUInt16());
SetUInt16Value(PLAYER_FIELD_KILLS, 1, fields[50].GetUInt16());
_LoadBoundInstances(holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_BOUND_INSTANCES));
_LoadBGData(holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_BG_DATA));
GetSession()->SetPlayer(this);
MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
Map* map = nullptr;
bool player_at_bg = false;
if (!mapEntry || !IsPositionValid())
{
TC_LOG_ERROR("entities.player.loading", "Player::LoadFromDB: Player ({}) has invalid coordinates (MapId: {} X: {} Y: {} Z: {} O: {}). Teleport to default race/class locations.",
guid.ToString(), mapId, GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
RelocateToHomebind();
}
// Player was saved in Arena or Bg
else if (mapEntry->IsBattlegroundOrArena())
{
Battleground* currentBg = nullptr;
if (m_bgData.bgInstanceID) //saved in Battleground
currentBg = sBattlegroundMgr->GetBattleground(m_bgData.bgInstanceID, BATTLEGROUND_TYPE_NONE);
player_at_bg = currentBg && currentBg->IsPlayerInBattleground(GetGUID());
if (player_at_bg && currentBg->GetStatus() != STATUS_WAIT_LEAVE)
{
map = currentBg->GetBgMap();
BattlegroundQueueTypeId bgQueueTypeId = BattlegroundMgr::BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetBracketId(), currentBg->GetArenaType());
AddBattlegroundQueueId(bgQueueTypeId);
m_bgData.bgTypeID = currentBg->GetTypeID();
//join player to battleground group
currentBg->EventPlayerLoggedIn(this);
SetInviteForBattlegroundQueueType(bgQueueTypeId, currentBg->GetInstanceID());
}
// Bg was not found - go to Entry Point
else
{
// leave bg
if (player_at_bg)
{
player_at_bg = false;
currentBg->RemovePlayerAtLeave(GetGUID(), false, true);
}
// Do not look for instance if bg not found
WorldLocation const& _loc = GetBattlegroundEntryPoint();
mapId = _loc.GetMapId();
instanceId = 0;
// Db field type is type int16, so it can never be MAPID_INVALID
//if (mapId == MAPID_INVALID) -- code kept for reference
if (int16(mapId) == int16(-1)) // Battleground Entry Point not found (???)
{
TC_LOG_ERROR("entities.player.loading", "Player::LoadFromDB: Player ({}) was in BG in database, but BG was not found and entry point was invalid! Teleport to default race/class locations.",
guid.ToString());
RelocateToHomebind();
}
else
Relocate(&_loc);
// We are not in BG anymore
m_bgData.bgInstanceID = 0;
}
}
// currently we do not support transport in bg
else if (transLowGUID)
{
ObjectGuid transGUID = ObjectGuid::Create<HighGuid::Mo_Transport>(transLowGUID);
Transport* transport = nullptr;
if (Transport* go = HashMapHolder<Transport>::Find(transGUID))
transport = go;
if (transport)
{
float x = fields[31].GetFloat(), y = fields[32].GetFloat(), z = fields[33].GetFloat(), o = fields[34].GetFloat();
m_movementInfo.transport.pos.Relocate(x, y, z, o);
transport->CalculatePassengerPosition(x, y, z, &o);
if (!Trinity::IsValidMapCoord(x, y, z, o) ||
// transport size limited
std::fabs(m_movementInfo.transport.pos.GetPositionX()) > 250.0f ||
std::fabs(m_movementInfo.transport.pos.GetPositionY()) > 250.0f ||
std::fabs(m_movementInfo.transport.pos.GetPositionZ()) > 250.0f)
{
TC_LOG_ERROR("entities.player.loading", "Player::LoadFromDB: Player ({}) has invalid transport coordinates (X: {} Y: {} Z: {} O: {}). Teleport to bind location.",
guid.ToString(), x, y, z, o);
m_movementInfo.transport.Reset();
RelocateToHomebind();
}
else
{
Relocate(x, y, z, o);
mapId = transport->GetMapId();
transport->AddPassenger(this);
}
}
else
{
TC_LOG_ERROR("entities.player.loading", "Player::LoadFromDB: Player ({}) has problems with transport guid ({}). Teleport to bind location.",
guid.ToString(), transLowGUID);
RelocateToHomebind();
}
}
// currently we do not support taxi in instance
else if (!taxi_nodes.empty())
{
instanceId = 0;
// Not finish taxi flight path
if (m_bgData.HasTaxiPath())
{
for (int i = 0; i < 2; ++i)
m_taxi.AddTaxiDestination(m_bgData.taxiPath[i]);
}
else if (!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes, GetTeam()))
{
// problems with taxi path loading
TaxiNodesEntry const* nodeEntry = nullptr;
if (uint32 node_id = m_taxi.GetTaxiSource())
nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
if (!nodeEntry) // don't know taxi start node, teleport to homebind
{
TC_LOG_ERROR("entities.player.loading", "Player::LoadFromDB: Player ({}) has wrong data in taxi destination list ({}), teleport to homebind.", GetGUID().ToString(), taxi_nodes);
RelocateToHomebind();
}
else // has start node, teleport to it
{
TC_LOG_ERROR("entities.player.loading", "Player::LoadFromDB: Player ({}) has too short taxi destination list ({}), teleport to original node.", GetGUID().ToString(), taxi_nodes);
mapId = nodeEntry->ContinentID;
Relocate(nodeEntry->Pos.X, nodeEntry->Pos.Y, nodeEntry->Pos.Z, 0.0f);
}
m_taxi.ClearTaxiDestinations();
}
if (uint32 node_id = m_taxi.GetTaxiSource())
{
// save source node as recall coord to prevent recall and fall from sky
TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
if (nodeEntry && nodeEntry->ContinentID == GetMapId())
{
ASSERT(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
mapId = nodeEntry->ContinentID;
Relocate(nodeEntry->Pos.X, nodeEntry->Pos.Y, nodeEntry->Pos.Z, 0.0f);
}
// flight will started later
}
}
// Map could be changed before
mapEntry = sMapStore.LookupEntry(mapId);
// client without expansion support
if (mapEntry)
{
if (GetSession()->Expansion() < mapEntry->Expansion())
{
TC_LOG_DEBUG("entities.player.loading", "Player::LoadFromDB: Player '{}' ({}) using client without required expansion tried login at non accessible map {}",
GetName(), GetGUID().ToString(), mapId);
RelocateToHomebind();
}
// fix crash (because of if (Map* map = _FindMap(instanceId)) in MapInstanced::CreateInstance)
if (instanceId)
if (InstanceSave* save = GetInstanceSave(mapId, mapEntry->IsRaid()))
if (save->GetInstanceId() != instanceId)
instanceId = 0;
}
// NOW player must have valid map
// load the player's map here if it's not already loaded
if (!map)
map = sMapMgr->CreateMap(mapId, this, instanceId);
AreaTriggerTeleport const* areaTrigger = nullptr;
bool check = false;
if (!map)
{
areaTrigger = sObjectMgr->GetGoBackTrigger(mapId);
check = true;
}
else if (map->IsDungeon()) // if map is dungeon...
{
if (Map::EnterState denyReason = ((InstanceMap*)map)->CannotEnter(this)) // ... and can't enter map, then look for entry point.
{
switch (denyReason)
{
case Map::CANNOT_ENTER_DIFFICULTY_UNAVAILABLE:
SendTransferAborted(map->GetId(), TRANSFER_ABORT_DIFFICULTY, map->GetDifficulty());
break;
case Map::CANNOT_ENTER_INSTANCE_BIND_MISMATCH:
ChatHandler(GetSession()).PSendSysMessage(GetSession()->GetTrinityString(LANG_INSTANCE_BIND_MISMATCH), map->GetMapName());
break;
case Map::CANNOT_ENTER_TOO_MANY_INSTANCES:
SendTransferAborted(map->GetId(), TRANSFER_ABORT_TOO_MANY_INSTANCES);
break;
case Map::CANNOT_ENTER_MAX_PLAYERS:
SendTransferAborted(map->GetId(), TRANSFER_ABORT_MAX_PLAYERS);
break;
case Map::CANNOT_ENTER_ZONE_IN_COMBAT:
SendTransferAborted(map->GetId(), TRANSFER_ABORT_ZONE_IN_COMBAT);
break;
default:
break;
}
areaTrigger = sObjectMgr->GetGoBackTrigger(mapId);
check = true;
}
else if (instanceId && !sInstanceSaveMgr->GetInstanceSave(instanceId)) // ... and instance is reseted then look for entrance.
{
areaTrigger = sObjectMgr->GetMapEntranceTrigger(mapId);
check = true;
}
}
if (check) // in case of special event when creating map...
{
if (areaTrigger) // ... if we have an areatrigger, then relocate to new map/coordinates.
{
Relocate(areaTrigger->target_X, areaTrigger->target_Y, areaTrigger->target_Z, GetOrientation());
if (mapId != areaTrigger->target_mapId)
{
mapId = areaTrigger->target_mapId;
map = sMapMgr->CreateMap(mapId, this);
}
}
else
{
TC_LOG_ERROR("entities.player.loading", "Player::LoadFromDB: Player '{}' ({}) Map: {}, X: {}, Y: {}, Z: {}, O: {}. Areatrigger not found.",
m_name, guid.ToString(), mapId, GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
RelocateToHomebind();
map = nullptr;
}
}
if (!map)
{
mapId = info->mapId;
Relocate(info->positionX, info->positionY, info->positionZ, 0.0f);
map = sMapMgr->CreateMap(mapId, this);
if (!map)
{
TC_LOG_ERROR("entities.player.loading", "Player::LoadFromDB: Player '{}' ({}) Map: {}, X: {}, Y: {}, Z: {}, O: {}. Invalid default map coordinates or instance couldn't be created.",
m_name, guid.ToString(), mapId, GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
return false;
}
}
SetMap(map);
StoreRaidMapDifficulty();
UpdatePositionData();
// now that map position is determined, check instance validity
if (!CheckInstanceValidity(true) && !IsInstanceLoginGameMasterException())
m_InstanceValid = false;
if (player_at_bg)
map->ToBattlegroundMap()->GetBG()->AddPlayer(this);
// randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
// this must help in case next save after mass player load after server startup
m_nextSave = urand(m_nextSave / 2, m_nextSave * 3 / 2);
SaveRecallPosition();
time_t now = GameTime::GetGameTime();
time_t logoutTime = time_t(fields[27].GetUInt32());
// since last logout (in seconds)
uint32 time_diff = uint32(now - logoutTime); //uint64 is excessive for a time_diff in seconds.. uint32 allows for 136~ year difference.
// set value, including drunk invisibility detection
// calculate sobering. after 15 minutes logged out, the player will be sober again
if (time_diff < uint32(GetDrunkValue()) * 9)
SetDrunkValue(GetDrunkValue() - time_diff / 9);
else
SetDrunkValue(0);
m_cinematic = fields[23].GetUInt8();
m_Played_time[PLAYED_TIME_TOTAL] = fields[24].GetUInt32();
m_Played_time[PLAYED_TIME_LEVEL] = fields[25].GetUInt32();
SetTalentResetCost(fields[29].GetUInt32());
SetTalentResetTime(time_t(fields[30].GetUInt32()));
if (!m_taxi.LoadTaxiMask(fields[22].GetString())) // must be before InitTaxiNodesForLevel
TC_LOG_WARN("entities.player.loading", "Player::LoadFromDB: Player ({}) has invalid taximask ({}) in DB. Forced partial load.", GetGUID().ToString(), fields[22].GetString());
uint32 extraflags = fields[36].GetUInt16();
_LoadPetStable(fields[37].GetUInt8(), holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_PET_SLOTS));
m_atLoginFlags = fields[38].GetUInt16();
if (HasAtLoginFlag(AT_LOGIN_RENAME))
{
TC_LOG_ERROR("entities.player.cheat", "Player::LoadFromDB: Player ({}) tried to login while forced to rename, can't load.'", GetGUID().ToString());
return false;
}
// Honor system
// Update Honor kills data
m_lastHonorUpdateTime = logoutTime;
UpdateHonorFields();
m_deathExpireTime = time_t(fields[41].GetUInt32());
if (m_deathExpireTime > now + MAX_DEATH_COUNT * DEATH_EXPIRE_STEP)
m_deathExpireTime = now + MAX_DEATH_COUNT * DEATH_EXPIRE_STEP - 1;
// clear channel spell data (if saved at channel spell casting)
SetChannelObjectGuid(ObjectGuid::Empty);
SetChannelSpellId(0);
// clear charm/summon related fields
SetOwnerGUID(ObjectGuid::Empty);
SetGuidValue(UNIT_FIELD_CHARMEDBY, ObjectGuid::Empty);
SetGuidValue(UNIT_FIELD_CHARM, ObjectGuid::Empty);
SetGuidValue(UNIT_FIELD_SUMMON, ObjectGuid::Empty);
SetGuidValue(PLAYER_FARSIGHT, ObjectGuid::Empty);
SetCreatorGUID(ObjectGuid::Empty);
RemoveUnitFlag2(UNIT_FLAG2_FORCE_MOVEMENT);
// reset some aura modifiers before aura apply
SetUInt32Value(PLAYER_TRACK_CREATURES, 0);
SetUInt32Value(PLAYER_TRACK_RESOURCES, 0);
// make sure the unit is considered out of combat for proper loading
ClearInCombat();
// make sure the unit is considered not in duel for proper loading
SetGuidValue(PLAYER_DUEL_ARBITER, ObjectGuid::Empty);
SetUInt32Value(PLAYER_DUEL_TEAM, 0);
// reset stats before loading any modifiers
InitStatsForLevel();
InitGlyphsForLevel();
InitTaxiNodesForLevel();
InitRunes();
// rest bonus can only be calculated after InitStatsForLevel()
m_rest_bonus = fields[26].GetFloat();
if (time_diff > 0)
{
//speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
float bubble0 = 0.031f;
//speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
float bubble1 = 0.125f;
float bubble = fields[28].GetUInt8() > 0
? bubble1*sWorld->getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
: bubble0*sWorld->getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
SetRestBonus(GetRestBonus() + time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP) / 72000)*bubble);
}
// load skills after InitStatsForLevel because it triggering aura apply also
_LoadSkills(holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_SKILLS));
UpdateSkillsForLevel(); //update skills after load, to make sure they are correctly update at player load
// apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
//mails are loaded only when needed ;-) - when player in game click on mailbox.
//_LoadMail();
SetSpecsCount(fields[64].GetUInt8());
SetActiveSpec(fields[65].GetUInt8());
// sanity check
if (GetSpecsCount() > MAX_TALENT_SPECS || GetActiveSpec() > MAX_TALENT_SPEC || GetSpecsCount() < MIN_TALENT_SPECS)
{
TC_LOG_ERROR("entities.player.loading", "Player::LoadFromDB: Player {} ({}) has invalid SpecCount = {} and/or invalid ActiveSpec = {}.",
GetName(), GetGUID().ToString(), uint32(GetSpecsCount()), uint32(GetActiveSpec()));
SetActiveSpec(0);
}
UpdateDisplayPower();
_LoadTalents(holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_TALENTS));
_LoadSpells(holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_SPELLS));
_LoadGlyphs(holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_GLYPHS));
_LoadAuras(holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_AURAS), time_diff);
_LoadGlyphAuras();
// add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
m_deathState = DEAD;
// after spell load, learn rewarded spell if need also
_LoadQuestStatus(holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_QUEST_STATUS));
_LoadQuestStatusRewarded(holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_QUEST_STATUS_REW));
_LoadDailyQuestStatus(holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_DAILY_QUEST_STATUS));
_LoadWeeklyQuestStatus(holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_WEEKLY_QUEST_STATUS));
_LoadSeasonalQuestStatus(holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_SEASONAL_QUEST_STATUS));
_LoadMonthlyQuestStatus(holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_MONTHLY_QUEST_STATUS));
_LoadRandomBGStatus(holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_RANDOM_BG));
// after spell and quest load
InitTalentForLevel();
LearnDefaultSkills();
LearnCustomSpells();
// must be before inventory (some items required reputation check)
m_reputationMgr->LoadFromDB(holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_REPUTATION));
_LoadInventory(holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_INVENTORY), time_diff);
// update items with duration and realtime
UpdateItemDuration(time_diff, true);
_LoadActions(holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_ACTIONS));
// unread mails and next delivery time, actual mails not loaded
_LoadMail(holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_MAILS), holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_MAIL_ITEMS));
m_social = sSocialMgr->LoadFromDB(holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_SOCIAL_LIST), GetGUID());
// check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
// note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
uint32 curTitle = fields[51].GetUInt32();
if (curTitle && !HasTitle(curTitle))
curTitle = 0;
SetUInt32Value(PLAYER_CHOSEN_TITLE, curTitle);
// has to be called after last Relocate() in Player::LoadFromDB
SetFallInformation(0, GetPositionZ());
GetSpellHistory()->LoadFromDB<Player>(holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_SPELL_COOLDOWNS));
uint32 savedHealth = fields[55].GetUInt32();
if (!savedHealth)
m_deathState = CORPSE;
// Spell code allow apply any auras to dead character in load time in aura/spell/item loading
// Do now before stats re-calculation cleanup for ghost state unexpected auras
if (!IsAlive())
RemoveAllAurasOnDeath();
else
RemoveAllAurasRequiringDeadTarget();
//apply all stat bonuses from items and auras
SetCanModifyStats(true);
UpdateAllStats();
// restore remembered power/health values (but not more max values)
SetHealth(savedHealth);
for (uint8 i = 0; i < MAX_POWERS; ++i)
{
uint32 savedPower = fields[56 + i].GetUInt32();
SetPower(static_cast<Powers>(i), savedPower);
}
TC_LOG_DEBUG("entities.player.loading", "Player::LoadFromDB: The value of player '{}' after load item and aura is: ", m_name);
outDebugValues();
// GM state
if (GetSession()->HasPermission(rbac::RBAC_PERM_RESTORE_SAVED_GM_STATE))
{
switch (sWorld->getIntConfig(CONFIG_GM_LOGIN_STATE))
{
default:
case 0: break; // disable
case 1: SetGameMaster(true); break; // enable
case 2: // save state
if (extraflags & PLAYER_EXTRA_GM_ON)
SetGameMaster(true);
break;
}
switch (sWorld->getIntConfig(CONFIG_GM_VISIBLE_STATE))
{
default:
case 0: SetGMVisible(false); break; // invisible
case 1: break; // visible
case 2: // save state
if (extraflags & PLAYER_EXTRA_GM_INVISIBLE)
SetGMVisible(false);
break;
}
switch (sWorld->getIntConfig(CONFIG_GM_CHAT))
{
default:
case 0: break; // disable
case 1: SetGMChat(true); break; // enable
case 2: // save state
if (extraflags & PLAYER_EXTRA_GM_CHAT)
SetGMChat(true);
break;
}
switch (sWorld->getIntConfig(CONFIG_GM_WHISPERING_TO))
{
default:
case 0: break; // disable
case 1: SetAcceptWhispers(true); break; // enable
case 2: // save state
if (extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
SetAcceptWhispers(true);
break;
}
}
InitPvP();
// RaF stuff.
m_grantableLevels = fields[71].GetUInt8();
if (GetSession()->IsARecruiter() || (GetSession()->GetRecruiterId() != 0))
SetDynamicFlag(UNIT_DYNFLAG_REFER_A_FRIEND);
if (m_grantableLevels > 0)
SetByteValue(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTES_OFFSET_RAF_GRANTABLE_LEVEL, 0x01);
_LoadDeclinedNames(holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_DECLINED_NAMES));
m_achievementMgr->CheckAllAchievementCriteria();
_LoadEquipmentSets(holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_EQUIPMENT_SETS));
return true;
}
bool Player::isAllowedToLoot(Creature const* creature) const
{
if (!creature->isDead() || !creature->IsDamageEnoughForLootingAndReward())
return false;
if (HasPendingBind())
return false;
Loot const* loot = &creature->loot;
if (loot->isLooted()) // nothing to loot or everything looted.
return false;
if (!loot->hasItemForAll() && !loot->hasItemFor(this)) // no loot in creature for this player
return false;
if (loot->loot_type == LOOT_SKINNING)
return creature->GetLootRecipientGUID() == GetGUID();
Group const* thisGroup = GetGroup();
if (!thisGroup)
return this == creature->GetLootRecipient();
else if (thisGroup != creature->GetLootRecipientGroup())
return false;
switch (thisGroup->GetLootMethod())
{
case MASTER_LOOT:
case FREE_FOR_ALL:
return true;
case ROUND_ROBIN:
// may only loot if the player is the loot roundrobin player
// or if there are free/quest/conditional item for the player
if (loot->roundRobinPlayer.IsEmpty() || loot->roundRobinPlayer == GetGUID())
return true;
return loot->hasItemFor(this);
case GROUP_LOOT:
case NEED_BEFORE_GREED:
// may only loot if the player is the loot roundrobin player
// or item over threshold (so roll(s) can be launched)
// or if there are free/quest/conditional item for the player
if (loot->roundRobinPlayer.IsEmpty() || loot->roundRobinPlayer == GetGUID())
return true;
if (loot->hasOverThresholdItem())
return true;
return loot->hasItemFor(this);
}
return false;
}
void Player::_LoadActions(PreparedQueryResult result)
{
m_actionButtons.clear();
if (result)
{
do
{
Field* fields = result->Fetch();
uint8 button = fields[0].GetUInt8();
uint32 action = fields[1].GetUInt32();
uint8 type = fields[2].GetUInt8();
if (ActionButton* ab = addActionButton(button, action, type))
ab->uState = ACTIONBUTTON_UNCHANGED;
else
{
TC_LOG_DEBUG("entities.player", "Player::_LoadActions: Player '{}' ({}) has an invalid action button (Button: {}, Action: {}, Type: {}). It will be deleted at next save. This can be due to a player changing their talents.",
GetName(), GetGUID().ToString(), button, action, type);
// Will be deleted in DB at next save (it can create data until save but marked as deleted).
m_actionButtons[button].uState = ACTIONBUTTON_DELETED;
}
} while (result->NextRow());
}
}
void Player::_LoadAuras(PreparedQueryResult result, uint32 timediff)
{
TC_LOG_DEBUG("entities.player.loading", "Player::_LoadAuras: Loading auras for {}", GetGUID().ToString());
/* 0 1 2 3 4 5 6 7 8 9 10 11
QueryResult* result = CharacterDatabase.PQuery("SELECT casterGuid, itemGuid, spell, effectMask, recalculateMask, stackCount, amount0, amount1, amount2, base_amount0, base_amount1, base_amount2,
12 13 14 15 16
maxDuration, remainTime, remainCharges, critChance, applyResilience FROM character_aura WHERE guid = '{}'", GetGUID().GetCounter());
*/
ObjectGuid casterGuid, itemGuid;
if (result)
{
do
{
Field* fields = result->Fetch();
int32 damage[3];
int32 baseDamage[3];
casterGuid.SetRawValue(fields[0].GetUInt64());
itemGuid.SetRawValue(fields[1].GetUInt64());
uint32 spellid = fields[2].GetUInt32();
uint8 effmask = fields[3].GetUInt8();
uint8 recalculatemask = fields[4].GetUInt8();
uint8 stackcount = fields[5].GetUInt8();
damage[0] = fields[6].GetInt32();
damage[1] = fields[7].GetInt32();
damage[2] = fields[8].GetInt32();
baseDamage[0] = fields[9].GetInt32();
baseDamage[1] = fields[10].GetInt32();
baseDamage[2] = fields[11].GetInt32();
int32 maxduration = fields[12].GetInt32();
int32 remaintime = fields[13].GetInt32();
uint8 remaincharges = fields[14].GetUInt8();
float critChance = fields[15].GetFloat();
bool applyResilience = fields[16].GetBool();
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellid);
if (!spellInfo)
{
TC_LOG_ERROR("entities.player", "Player::_LoadAuras: Player '{}' ({}) has an invalid aura (SpellID: {}), ignoring.",
GetName(), GetGUID().ToString(), spellid);
continue;
}
ChrRacesEntry const* raceEntry = sChrRacesStore.AssertEntry(GetRace());
// negative effects should continue counting down after logout
if (remaintime != -1 && ((!spellInfo->IsPositive() && spellInfo->Id != raceEntry->ResSicknessSpellID) || spellInfo->HasAttribute(SPELL_ATTR4_FADES_WHILE_LOGGED_OUT))) // Resurrection sickness should not fade while logged out
{
if (remaintime/IN_MILLISECONDS <= int32(timediff))
continue;
remaintime -= timediff*IN_MILLISECONDS;
}
// prevent wrong values of remaincharges
if (spellInfo->ProcCharges)
{
// we have no control over the order of applying auras and modifiers allow auras
// to have more charges than value in SpellInfo
if (remaincharges <= 0/* || remaincharges > spellproto->procCharges*/)
remaincharges = spellInfo->ProcCharges;
}
else
remaincharges = 0;
AuraCreateInfo createInfo(spellInfo, effmask, this);
createInfo
.SetCasterGUID(casterGuid)
.SetCastItemGUID(itemGuid)
.SetBaseAmount(baseDamage);
if (Aura* aura = Aura::TryCreate(createInfo))
{
if (!aura->CanBeSaved())
{
aura->Remove();
continue;
}
aura->SetLoadedState(maxduration, remaintime, remaincharges, stackcount, recalculatemask, critChance, applyResilience, &damage[0]);
aura->ApplyForTargets();
TC_LOG_DEBUG("entities.player", "Player::_LoadAuras: Added aura (SpellID: {}, EffectMask: {}) to player '{} ({})",
spellInfo->Id, effmask, GetName(), GetGUID().ToString());
}
}
while (result->NextRow());
}
}
void Player::_LoadGlyphAuras()
{
for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
{
if (uint32 glyph = GetGlyph(GetActiveSpec(), i))
{
if (GlyphPropertiesEntry const* gp = sGlyphPropertiesStore.LookupEntry(glyph))
{
if (GlyphSlotEntry const* gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(i)))
{
if (gp->GlyphSlotFlags == gs->Type)
{
CastSpell(this, gp->SpellID, true);
continue;
}
else
TC_LOG_ERROR("entities.player", "Player::_LoadGlyphAuras: Player '{}' ({}) has glyph with typeflags {} in slot with typeflags {}, removing.", GetName(), GetGUID().ToString(), gp->GlyphSlotFlags, gs->Type);
}
else
TC_LOG_ERROR("entities.player", "Player::_LoadGlyphAuras: Player '{}' ({}) has not existing glyph slot entry {} on index {}", GetName(), GetGUID().ToString(), GetGlyphSlot(i), i);
}
else
TC_LOG_ERROR("entities.player", "Player::_LoadGlyphAuras: Player '{}' ({}) has not existing glyph entry {} on index {}", GetName(), GetGUID().ToString(), glyph, i);
// On any error remove glyph
SetGlyph(i, 0);
}
}
}
void Player::LoadCorpse(PreparedQueryResult result)
{
if (IsAlive() || HasAtLoginFlag(AT_LOGIN_RESURRECT))
SpawnCorpseBones(false);
if (!IsAlive())
{
if (HasAtLoginFlag(AT_LOGIN_RESURRECT))
ResurrectPlayer(0.5f);
else if (result)
{
Field* fields = result->Fetch();
_corpseLocation.WorldRelocate(fields[0].GetUInt16(), fields[1].GetFloat(), fields[2].GetFloat(), fields[3].GetFloat(), fields[4].GetFloat());
ApplyModByteFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTES_OFFSET_FLAGS, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(_corpseLocation.GetMapId())->Instanceable());
}
}
RemoveAtLoginFlag(AT_LOGIN_RESURRECT);
}
void Player::_LoadInventory(PreparedQueryResult result, uint32 timeDiff)
{
//QueryResult* result = CharacterDatabase.PQuery("SELECT data, text, bag, slot, item, item_template FROM character_inventory JOIN item_instance ON character_inventory.item = item_instance.guid WHERE character_inventory.guid = '{}' ORDER BY bag, slot", GetGUID().GetCounter());
//NOTE: the "order by `bag`" is important because it makes sure
//the bagMap is filled before items in the bags are loaded
//NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
//expected to be equipped before offhand items (@todo fixme)
if (result)
{
uint32 zoneId = GetZoneId();
std::map<ObjectGuid, Bag*> bagMap; // fast guid lookup for bags
std::map<ObjectGuid, Item*> invalidBagMap; // fast guid lookup for bags
std::list<Item*> problematicItems;
CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction();
// Prevent items from being added to the queue while loading
m_itemUpdateQueueBlocked = true;
do
{
Field* fields = result->Fetch();
if (Item* item = _LoadItem(trans, zoneId, timeDiff, fields))
{
ObjectGuid bagGuid = fields[11].GetUInt32() ? ObjectGuid::Create<HighGuid::Item>(fields[11].GetUInt32()) : ObjectGuid::Empty;
uint8 slot = fields[12].GetUInt8();
InventoryResult err = EQUIP_ERR_OK;
// Item is not in bag
if (!bagGuid)
{
item->SetContainer(nullptr);
item->SetSlot(slot);
if (IsInventoryPos(INVENTORY_SLOT_BAG_0, slot))
{
ItemPosCountVec dest;
err = CanStoreItem(INVENTORY_SLOT_BAG_0, slot, dest, item, false);
if (err == EQUIP_ERR_OK)
item = StoreItem(dest, item, true);
}
else if (IsEquipmentPos(INVENTORY_SLOT_BAG_0, slot))
{
uint16 dest;
err = CanEquipItem(slot, dest, item, false, false);
if (err == EQUIP_ERR_OK)
QuickEquipItem(dest, item);
}
else if (IsBankPos(INVENTORY_SLOT_BAG_0, slot))
{
ItemPosCountVec dest;
err = CanBankItem(INVENTORY_SLOT_BAG_0, slot, dest, item, false, false);
if (err == EQUIP_ERR_OK)
item = BankItem(dest, item, true);
}
// Remember bags that may contain items in them
if (err == EQUIP_ERR_OK)
{
if (IsBagPos(item->GetPos()))
if (Bag* pBag = item->ToBag())
bagMap[item->GetGUID()] = pBag;
}
else
if (IsBagPos(item->GetPos()))
if (item->IsBag())
invalidBagMap[item->GetGUID()] = item;
}
else
{
item->SetSlot(NULL_SLOT);
// Item is in the bag, find the bag
std::map<ObjectGuid, Bag*>::iterator itr = bagMap.find(bagGuid);
if (itr != bagMap.end())
{
ItemPosCountVec dest;
err = CanStoreItem(itr->second->GetSlot(), slot, dest, item);
if (err == EQUIP_ERR_OK)
item = StoreItem(dest, item, true);
}
else if (invalidBagMap.find(bagGuid) != invalidBagMap.end())
{
std::map<ObjectGuid, Item*>::iterator invalidBagItr = invalidBagMap.find(bagGuid);
if (std::find(problematicItems.begin(), problematicItems.end(), invalidBagItr->second) != problematicItems.end())
err = EQUIP_ERR_INTERNAL_BAG_ERROR;
}
else
{
TC_LOG_ERROR("entities.player", "Player::_LoadInventory: Player '{}' ({}) has item ({}, entry: {}) which doesnt have a valid bag (Bag {}, slot: {}). Possible cheat?",
GetName(), GetGUID().ToString(), item->GetGUID().ToString(), item->GetEntry(), bagGuid, slot);
item->DeleteFromInventoryDB(trans);
delete item;
continue;
}
}
// Item's state may have changed after storing
if (err == EQUIP_ERR_OK)
item->SetState(ITEM_UNCHANGED, this);
else
{
TC_LOG_ERROR("entities.player", "Player::_LoadInventory: Player '{}' ({}) has item ({}, entry: {}) which can't be loaded into inventory (Bag {}, slot: {}) by reason {}. Item will be sent by mail.",
GetName(), GetGUID().ToString(), item->GetGUID().ToString(), item->GetEntry(), bagGuid, slot, uint32(err));
item->DeleteFromInventoryDB(trans);
problematicItems.push_back(item);
}
}
} while (result->NextRow());
m_itemUpdateQueueBlocked = false;
// Send problematic items by mail
while (!problematicItems.empty())
{
std::string subject = GetSession()->GetTrinityString(LANG_NOT_EQUIPPED_ITEM);
MailDraft draft(subject, "There were problems with equipping item(s).");
for (uint8 i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
{
draft.AddItem(problematicItems.front());
problematicItems.pop_front();
}
draft.SendMailTo(trans, this, MailSender(this, MAIL_STATIONERY_GM), MAIL_CHECK_MASK_COPIED);
}
CharacterDatabase.CommitTransaction(trans);
}
//if (IsAlive())
_ApplyAllItemMods();
}
Item* Player::_LoadItem(CharacterDatabaseTransaction trans, uint32 zoneId, uint32 timeDiff, Field* fields)
{
Item* item = nullptr;
ObjectGuid::LowType itemGuid = fields[13].GetUInt32();
uint32 itemEntry = fields[14].GetUInt32();
if (ItemTemplate const* proto = sObjectMgr->GetItemTemplate(itemEntry))
{
bool remove = false;
item = NewItemOrBag(proto);
if (item->LoadFromDB(itemGuid, GetGUID(), fields, itemEntry))
{
CharacterDatabasePreparedStatement* stmt;
// Do not allow to have item limited to another map/zone in alive state
if (IsAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(), zoneId))
{
TC_LOG_DEBUG("entities.player.loading", "Player::_LoadInventory: player ({}, name: '{}', map: {}) has item ({}) limited to another map ({}). Deleting item.",
GetGUID().ToString(), GetName(), GetMapId(), item->GetGUID().ToString(), zoneId);
remove = true;
}
// "Conjured items disappear if you are logged out for more than 15 minutes"
else if (timeDiff > 15 * MINUTE && proto->HasFlag(ITEM_FLAG_CONJURED))
{
TC_LOG_DEBUG("entities.player.loading", "Player::_LoadInventory: player ({}, name: '{}', diff: {}) has conjured item ({}) with expired lifetime (15 minutes). Deleting item.",
GetGUID().ToString(), GetName(), timeDiff, item->GetGUID().ToString());
remove = true;
}
else if (item->IsRefundable())
{
if (item->GetPlayedTime() > (2 * HOUR))
{
TC_LOG_DEBUG("entities.player.loading", "Player::_LoadInventory: player ({}, name: '{}') has item ({}) with expired refund time ({}). Deleting refund data and removing refundable flag.",
GetGUID().ToString(), GetName(), item->GetGUID().ToString(), item->GetPlayedTime());
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_REFUND_INSTANCE);
stmt->setUInt32(0, item->GetGUID().GetCounter());
trans->Append(stmt);
item->RemoveFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_REFUNDABLE);
}
else
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_ITEM_REFUNDS);
stmt->setUInt32(0, item->GetGUID().GetCounter());
stmt->setUInt32(1, GetGUID().GetCounter());
if (PreparedQueryResult result = CharacterDatabase.Query(stmt))
{
item->SetRefundRecipient(GetGUID());
item->SetPaidMoney((*result)[0].GetUInt32());
item->SetPaidExtendedCost((*result)[1].GetUInt16());
AddRefundReference(item->GetGUID());
}
else
{
TC_LOG_WARN("entities.player.loading", "Player::_LoadInventory: player ({}, name: '{}') has item ({}) with refundable flags, but without data in item_refund_instance. Removing flag.",
GetGUID().ToString(), GetName(), item->GetGUID().ToString());
item->RemoveFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_REFUNDABLE);
}
}
}
else if (item->IsBOPTradeable())
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_ITEM_BOP_TRADE);
stmt->setUInt32(0, item->GetGUID().GetCounter());
if (PreparedQueryResult result = CharacterDatabase.Query(stmt))
{
GuidSet looters;
for (std::string_view guidStr : Trinity::Tokenize((*result)[0].GetStringView(), ' ', false))
{
if (Optional<ObjectGuid::LowType> guid = Trinity::StringTo<ObjectGuid::LowType>(guidStr))
looters.insert(ObjectGuid::Create<HighGuid::Player>(*guid));
else
TC_LOG_WARN("entities.player.loading", "Player::_LoadInventory: invalid item_soulbound_trade_data GUID '{}' for item {}. Skipped.", std::string(guidStr), item->GetGUID().ToString());
}
if (looters.size() > 1 && item->GetTemplate()->GetMaxStackSize() == 1 && item->IsSoulBound())
{
item->SetSoulboundTradeable(looters);
AddTradeableItem(item);
}
else
item->ClearSoulboundTradeable(this);
}
else
{
TC_LOG_WARN("entities.player.loading", "Player::_LoadInventory: player ({}, name: '{}') has item ({}) with ITEM_FLAG_BOP_TRADEABLE flag, but without data in item_soulbound_trade_data. Removing flag.",
GetGUID().ToString(), GetName(), item->GetGUID().ToString());
item->RemoveFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_BOP_TRADEABLE);
}
}
else if (proto->HolidayId)
{
remove = true;
GameEventMgr::GameEventDataMap const& events = sGameEventMgr->GetEventMap();
GameEventMgr::ActiveEvents const& activeEventsList = sGameEventMgr->GetActiveEventList();
for (GameEventMgr::ActiveEvents::const_iterator itr = activeEventsList.begin(); itr != activeEventsList.end(); ++itr)
{
if (uint32(events[*itr].holiday_id) == proto->HolidayId)
{
remove = false;
break;
}
}
}
}
else
{
TC_LOG_ERROR("entities.player", "Player::_LoadInventory: player ({}, name: '{}') has a broken item (GUID: {}, entry: {}) in inventory. Deleting item.",
GetGUID().ToString(), GetName(), itemGuid, itemEntry);
remove = true;
}
// Remove item from inventory if necessary
if (remove)
{
Item::DeleteFromInventoryDB(trans, itemGuid);
item->FSetState(ITEM_REMOVED);
item->SaveToDB(trans); // it also deletes item object!
item = nullptr;
}
}
else
{
TC_LOG_ERROR("entities.player", "Player::_LoadInventory: player ({}, name: '{}') has an unknown item (entry: {}) in inventory. Deleting item.",
GetGUID().ToString(), GetName(), itemEntry);
Item::DeleteFromInventoryDB(trans, itemGuid);
Item::DeleteFromDB(trans, itemGuid);
}
return item;
}
// load mailed item which should receive current player
Item* Player::_LoadMailedItem(ObjectGuid const& playerGuid, Player* player, uint32 mailId, Mail* mail, Field* fields)
{
ObjectGuid::LowType itemGuid = fields[11].GetUInt32();
uint32 itemEntry = fields[12].GetUInt32();
ItemTemplate const* proto = sObjectMgr->GetItemTemplate(itemEntry);
if (!proto)
{
TC_LOG_ERROR("entities.player", "Player '{}' ({}) has unknown item in mailed items (GUID: {}, Entry: {}) in mail ({}), deleted.",
player ? player->GetName() : "<unknown>", playerGuid.ToString(), itemGuid, itemEntry, mailId);
CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction();
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INVALID_MAIL_ITEM);
stmt->setUInt32(0, itemGuid);
trans->Append(stmt);
Item::DeleteFromDB(trans, itemGuid);
CharacterDatabase.CommitTransaction(trans);
return nullptr;
}
Item* item = NewItemOrBag(proto);
ObjectGuid ownerGuid = fields[13].GetUInt32() ? ObjectGuid::Create<HighGuid::Player>(fields[13].GetUInt32()) : ObjectGuid::Empty;
if (!item->LoadFromDB(itemGuid, ownerGuid, fields, itemEntry))
{
TC_LOG_ERROR("entities.player", "Player::_LoadMailedItems: Item (GUID: {}) in mail ({}) doesn't exist, deleted from mail.", itemGuid, mailId);
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_ITEM);
stmt->setUInt32(0, itemGuid);
CharacterDatabase.Execute(stmt);
item->FSetState(ITEM_REMOVED);
CharacterDatabaseTransaction temp = CharacterDatabaseTransaction(nullptr);
item->SaveToDB(temp); // it also deletes item object !
return nullptr;
}
if (mail)
mail->AddItem(itemGuid, itemEntry);
if (player)
player->AddMItem(item);
return item;
}
void Player::_LoadMail(PreparedQueryResult mailsResult, PreparedQueryResult mailItemsResult)
{
m_mail.clear();
std::unordered_map<uint32, Mail*> mailById;
if (mailsResult)
{
do
{
Field* fields = mailsResult->Fetch();
Mail* m = new Mail;
m->messageID = fields[0].GetUInt32();
m->messageType = fields[1].GetUInt8();
m->sender = fields[2].GetUInt32();
m->receiver = fields[3].GetUInt32();
m->subject = fields[4].GetString();
m->body = fields[5].GetString();
m->expire_time = time_t(fields[6].GetUInt32());
m->deliver_time = time_t(fields[7].GetUInt32());
m->money = fields[8].GetUInt32();
m->COD = fields[9].GetUInt32();
m->checked = fields[10].GetUInt8();
m->stationery = fields[11].GetUInt8();
m->mailTemplateId = fields[12].GetInt16();
if (m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
{
TC_LOG_ERROR("entities.player", "Player::_LoadMail: Mail ({}) has nonexistent MailTemplateId ({}), remove at load", m->messageID, m->mailTemplateId);
m->mailTemplateId = 0;
}
m->state = MAIL_STATE_UNCHANGED;
m_mail.push_back(m);
mailById[m->messageID] = m;
}
while (mailsResult->NextRow());
}
if (mailItemsResult)
{
do
{
Field* fields = mailItemsResult->Fetch();
uint32 mailId = fields[14].GetUInt32();
_LoadMailedItem(GetGUID(), this, mailId, mailById[mailId], fields);
} while (mailItemsResult->NextRow());
}
UpdateNextMailTimeAndUnreads();
}
void Player::LoadPet()
{
//fixme: the pet should still be loaded if the player is not in world
// just not added to the map
if (m_petStable && IsInWorld())
{
Pet* pet = new Pet(this);
if (!pet->LoadPetFromDB(this, 0, 0, true))
delete pet;
}
}
void Player::_LoadQuestStatus(PreparedQueryResult result)
{
uint16 slot = 0;
//// 0 1 2 3 4 5 6 7 8 9 10
//QueryResult* result = CharacterDatabase.PQuery("SELECT quest, status, explored, timer, mobcount1, mobcount2, mobcount3, mobcount4, itemcount1, itemcount2, itemcount3,
// 11 12 13 14
// itemcount4, itemcount5, itemcount6, playercount FROM character_queststatus WHERE guid = '{}'", GetGUID().GetCounter());
if (result)
{
do
{
Field* fields = result->Fetch();
uint32 quest_id = fields[0].GetUInt32();
// used to be new, no delete?
Quest const* quest = sObjectMgr->GetQuestTemplate(quest_id);
if (quest)
{
// find or create
QuestStatusData& questStatusData = m_QuestStatus[quest_id];
uint8 qstatus = fields[1].GetUInt8();
if (qstatus < MAX_QUEST_STATUS)
questStatusData.Status = QuestStatus(qstatus);
else
{
questStatusData.Status = QUEST_STATUS_INCOMPLETE;
TC_LOG_ERROR("entities.player", "Player::_LoadQuestStatus: Player '{}' ({}) has invalid quest {} status ({}), replaced by QUEST_STATUS_INCOMPLETE(3).",
GetName(), GetGUID().ToString(), quest_id, qstatus);
}
questStatusData.Explored = (fields[2].GetUInt8() > 0);
time_t quest_time = time_t(fields[3].GetUInt32());
if (quest->HasSpecialFlag(QUEST_SPECIAL_FLAGS_TIMED) && !GetQuestRewardStatus(quest_id))
{
AddTimedQuest(quest_id);
if (quest_time <= GameTime::GetGameTime())
questStatusData.Timer = 1;
else
questStatusData.Timer = uint32((quest_time - GameTime::GetGameTime()) * IN_MILLISECONDS);
}
else
quest_time = 0;
for (uint32 i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
questStatusData.CreatureOrGOCount[i] = fields[4 + i].GetUInt16();
for (uint32 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
questStatusData.ItemCount[i] = fields[8 + i].GetUInt16();
questStatusData.PlayerCount = fields[14].GetUInt16();
// add to quest log
if (slot < MAX_QUEST_LOG_SIZE && questStatusData.Status != QUEST_STATUS_NONE)
{
SetQuestSlot(slot, quest_id, uint32(quest_time)); // cast can't be helped
if (questStatusData.Status == QUEST_STATUS_COMPLETE)
SetQuestSlotState(slot, QUEST_STATE_COMPLETE);
else if (questStatusData.Status == QUEST_STATUS_FAILED)
SetQuestSlotState(slot, QUEST_STATE_FAIL);
for (uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
if (questStatusData.CreatureOrGOCount[idx])
SetQuestSlotCounter(slot, idx, questStatusData.CreatureOrGOCount[idx]);
if (questStatusData.PlayerCount)
SetQuestSlotCounter(slot, QUEST_PVP_KILL_SLOT, questStatusData.PlayerCount);
++slot;
}
TC_LOG_DEBUG("entities.player.loading", "Player::_LoadQuestStatus: Quest status is {{}} for quest {{}} for player ({})", questStatusData.Status, quest_id, GetGUID().ToString());
}
}
while (result->NextRow());
}
// clear quest log tail
for (uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i)
SetQuestSlot(i, 0);
}
void Player::_LoadQuestStatusRewarded(PreparedQueryResult result)
{
// SELECT quest FROM character_queststatus_rewarded WHERE guid = ?
if (result)
{
do
{
Field* fields = result->Fetch();
uint32 quest_id = fields[0].GetUInt32();
// used to be new, no delete?
Quest const* quest = sObjectMgr->GetQuestTemplate(quest_id);
if (quest)
{
// learn rewarded spell if unknown
LearnQuestRewardedSpells(quest);
// set rewarded title if any
if (quest->GetCharTitleId())
{
if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(quest->GetCharTitleId()))
SetTitle(titleEntry);
}
if (uint32 talents = quest->GetBonusTalents())
AddQuestRewardedTalentCount(talents);
if (quest->CanIncreaseRewardedQuestCounters())
m_RewardedQuests.insert(quest_id);
}
}
while (result->NextRow());
}
}
void Player::_LoadDailyQuestStatus(PreparedQueryResult result)
{
m_DFQuests.clear();
//QueryResult* result = CharacterDatabase.PQuery("SELECT quest, time FROM character_queststatus_daily WHERE guid = '{}'", GetGUID().GetCounter());
if (result)
{
uint32 quest_daily_idx = 0;
do
{
Field* fields = result->Fetch();
uint32 quest_id = fields[0].GetUInt32();
if (Quest const* qQuest = sObjectMgr->GetQuestTemplate(quest_id))
{
if (qQuest->IsDFQuest())
{
m_DFQuests.insert(qQuest->GetQuestId());
m_lastDailyQuestTime = time_t(fields[1].GetUInt32());
continue;
}
}
if (quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
{
TC_LOG_ERROR("entities.player", "Player {} has more than 25 daily quest records in `charcter_queststatus_daily`", GetGUID().ToString());
break;
}
// save _any_ from daily quest times (it must be after last reset anyway)
m_lastDailyQuestTime = time_t(fields[1].GetUInt32());
Quest const* quest = sObjectMgr->GetQuestTemplate(quest_id);
if (!quest)
continue;
SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx, quest_id);
++quest_daily_idx;
TC_LOG_DEBUG("entities.player.loading", "Player::_LoadDailyQuestStatus: Loaded daily quest cooldown (QuestID: {}) for player '{}' ({})",
quest_id, GetName(), GetGUID().ToString());
}
while (result->NextRow());
}
m_DailyQuestChanged = false;
}
void Player::_LoadWeeklyQuestStatus(PreparedQueryResult result)
{
m_weeklyquests.clear();
if (result)
{
do
{
Field* fields = result->Fetch();
uint32 quest_id = fields[0].GetUInt32();
Quest const* quest = sObjectMgr->GetQuestTemplate(quest_id);
if (!quest)
continue;
m_weeklyquests.insert(quest_id);
TC_LOG_DEBUG("entities.player.loading", "Player::_LoadWeeklyQuestStatus: Loaded weekly quest cooldown (QuestID: {}) for player '{}' ({})",
quest_id, GetName(), GetGUID().ToString());
}
while (result->NextRow());
}
m_WeeklyQuestChanged = false;
}
void Player::_LoadSeasonalQuestStatus(PreparedQueryResult result)
{
m_seasonalquests.clear();
if (result)
{
do
{
Field* fields = result->Fetch();
uint32 quest_id = fields[0].GetUInt32();
uint32 event_id = fields[1].GetUInt32();
uint32 completedTime = fields[2].GetInt64();
Quest const* quest = sObjectMgr->GetQuestTemplate(quest_id);
if (!quest)
continue;
m_seasonalquests[event_id][quest_id] = completedTime;
TC_LOG_DEBUG("entities.player.loading", "Player::_LoadSeasonalQuestStatus: Loaded seasonal quest cooldown (QuestID: {}) for player '{}' ({})",
quest_id, GetName(), GetGUID().ToString());
}
while (result->NextRow());
}
m_SeasonalQuestChanged = false;
}
void Player::_LoadMonthlyQuestStatus(PreparedQueryResult result)
{
m_monthlyquests.clear();
if (result)
{
do
{
Field* fields = result->Fetch();
uint32 quest_id = fields[0].GetUInt32();
Quest const* quest = sObjectMgr->GetQuestTemplate(quest_id);
if (!quest)
continue;
m_monthlyquests.insert(quest_id);
TC_LOG_DEBUG("entities.player.loading", "Player::_LoadMonthlyQuestStatus: Loaded monthly quest cooldown (QuestID: {}) for player '{}' ({})",
quest_id, GetName(), GetGUID().ToString());
}
while (result->NextRow());
}
m_MonthlyQuestChanged = false;
}
void Player::_LoadSpells(PreparedQueryResult result)
{
//QueryResult* result = CharacterDatabase.PQuery("SELECT spell, active, disabled FROM character_spell WHERE guid = '{}'", GetGUID().GetCounter());
if (result)
{
do
AddSpell((*result)[0].GetUInt32(), (*result)[1].GetBool(), false, false, (*result)[2].GetBool(), true);
while (result->NextRow());
}
}
void Player::_LoadGroup(PreparedQueryResult result)
{
//QueryResult* result = CharacterDatabase.PQuery("SELECT guid FROM group_member WHERE memberGuid={}", GetGUID().GetCounter());
if (result)
{
if (Group* group = sGroupMgr->GetGroupByDbStoreId((*result)[0].GetUInt32()))
{
if (group->IsLeader(GetGUID()))
SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GROUP_LEADER);
uint8 subgroup = group->GetMemberGroup(GetGUID());
SetGroup(group, subgroup);
// Make sure the player's difficulty settings are always aligned with the group's settings in order to avoid issues when checking access requirements
SetDungeonDifficulty(group->GetDungeonDifficulty());
SetRaidDifficulty(group->GetRaidDifficulty());
}
}
if (!GetGroup() || !GetGroup()->IsLeader(GetGUID()))
RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GROUP_LEADER);
}
void Player::_LoadBoundInstances(PreparedQueryResult result)
{
for (uint8 i = 0; i < MAX_DIFFICULTY; ++i)
m_boundInstances[i].clear();
Group* group = GetGroup();
// 0 1 2 3 4 5
// SELECT id, permanent, map, difficulty, extendState, resettime FROM character_instance LEFT JOIN instance ON instance = id WHERE guid = ?
if (result)
{
do
{
Field* fields = result->Fetch();
bool perm = fields[1].GetBool();
uint32 mapId = fields[2].GetUInt16();
uint32 instanceId = fields[0].GetUInt32();
uint8 difficulty = fields[3].GetUInt8();
BindExtensionState extendState = BindExtensionState(fields[4].GetUInt8());
time_t resetTime = time_t(fields[5].GetUInt64());
// the resettime for normal instances is only saved when the InstanceSave is unloaded
// so the value read from the DB may be wrong here but only if the InstanceSave is loaded
// and in that case it is not used
bool deleteInstance = false;
MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
std::string mapname = mapEntry ? mapEntry->MapName[sWorld->GetDefaultDbcLocale()] : "Unknown";
if (!mapEntry || !mapEntry->IsDungeon())
{
TC_LOG_ERROR("entities.player", "Player::_LoadBoundInstances: Player '{}' ({}) has bind to not existed or not dungeon map {} ({})",
GetName(), GetGUID().ToString(), mapId, mapname);
deleteInstance = true;
}
else if (difficulty >= MAX_DIFFICULTY)
{
TC_LOG_ERROR("entities.player", "Player::_LoadBoundInstances: player '{}' ({}) has bind to not existed difficulty {} instance for map {} ({})",
GetName(), GetGUID().ToString(), difficulty, mapId, mapname);
deleteInstance = true;
}
else
{
MapDifficulty const* mapDiff = GetMapDifficultyData(mapId, Difficulty(difficulty));
if (!mapDiff)
{
TC_LOG_ERROR("entities.player", "Player::_LoadBoundInstances: player '{}' ({}) has bind to not existed difficulty {} instance for map {} ({})",
GetName(), GetGUID().ToString(), difficulty, mapId, mapname);
deleteInstance = true;
}
else if (!perm && group)
{
TC_LOG_ERROR("entities.player", "Player::_LoadBoundInstances: player '{}' ({}) is in group {} but has a non-permanent character bind to map {} ({}), {}, {}",
GetName(), GetGUID().ToString(), group->GetGUID().ToString(), mapId, mapname, instanceId, difficulty);
deleteInstance = true;
}
}
if (deleteInstance)
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE_GUID);
stmt->setUInt32(0, GetGUID().GetCounter());
stmt->setUInt32(1, instanceId);
CharacterDatabase.Execute(stmt);
continue;
}
// since non permanent binds are always solo bind, they can always be reset
if (InstanceSave* save = sInstanceSaveMgr->AddInstanceSave(mapId, instanceId, Difficulty(difficulty), resetTime, !perm, true))
BindToInstance(save, perm, extendState, true);
}
while (result->NextRow());
}
}
InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, Difficulty difficulty, bool withExpired)
{
// some instances only have one difficulty
MapDifficulty const* mapDiff = GetDownscaledMapDifficultyData(mapid, difficulty);
if (!mapDiff)
return nullptr;
BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
if (itr != m_boundInstances[difficulty].end())
if (itr->second.extendState || withExpired)
return &itr->second;
return nullptr;
}
InstanceSave* Player::GetInstanceSave(uint32 mapid, bool raid)
{
InstancePlayerBind* pBind = GetBoundInstance(mapid, GetDifficulty(raid));
InstanceSave* pSave = pBind ? pBind->save : nullptr;
if (!pBind || !pBind->perm)
if (Group* group = GetGroup())
if (InstanceGroupBind* groupBind = group->GetBoundInstance(GetDifficulty(raid), mapid))
pSave = groupBind->save;
return pSave;
}
void Player::UnbindInstance(uint32 mapid, Difficulty difficulty, bool unload)
{
BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
UnbindInstance(itr, difficulty, unload);
}
void Player::UnbindInstance(BoundInstancesMap::iterator &itr, Difficulty difficulty, bool unload)
{
if (itr != m_boundInstances[difficulty].end())
{
if (!unload)
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE_GUID);
stmt->setUInt32(0, GetGUID().GetCounter());
stmt->setUInt32(1, itr->second.save->GetInstanceId());
CharacterDatabase.Execute(stmt);
}
if (itr->second.perm)
GetSession()->SendCalendarRaidLockoutRemoved(itr->second.save);
itr->second.save->RemovePlayer(this); // save can become invalid
m_boundInstances[difficulty].erase(itr++);
}
}
InstancePlayerBind* Player::BindToInstance(InstanceSave* save, bool permanent, BindExtensionState extendState, bool load)
{
if (save)
{
InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
if (extendState == EXTEND_STATE_KEEP) // special flag, keep the player's current extend state when updating for new boss down
{
if (save == bind.save)
extendState = bind.extendState;
else
extendState = EXTEND_STATE_NORMAL;
}
if (!load)
{
if (bind.save)
{
// update the save when the group kills a boss
if (permanent != bind.perm || save != bind.save || extendState != bind.extendState)
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_INSTANCE);
stmt->setUInt32(0, save->GetInstanceId());
stmt->setBool(1, permanent);
stmt->setUInt8(2, extendState);
stmt->setUInt32(3, GetGUID().GetCounter());
stmt->setUInt32(4, bind.save->GetInstanceId());
CharacterDatabase.Execute(stmt);
}
}
else
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_INSTANCE);
stmt->setUInt32(0, GetGUID().GetCounter());
stmt->setUInt32(1, save->GetInstanceId());
stmt->setBool(2, permanent);
stmt->setUInt8(3, extendState);
CharacterDatabase.Execute(stmt);
}
}
if (bind.save != save)
{
if (bind.save)
bind.save->RemovePlayer(this);
save->AddPlayer(this);
}
if (permanent)
save->SetCanReset(false);
bind.save = save;
bind.perm = permanent;
bind.extendState = extendState;
if (!load)
TC_LOG_DEBUG("maps", "Player::BindToInstance: Player '{}' ({}) is now bound to map (ID: {}, Instance: {}, Difficulty: {})",
GetName(), GetGUID().ToString(), save->GetMapId(), save->GetInstanceId(), static_cast<uint32>(save->GetDifficulty()));
sScriptMgr->OnPlayerBindToInstance(this, save->GetDifficulty(), save->GetMapId(), permanent, extendState);
return &bind;
}
return nullptr;
}
void Player::BindToInstance()
{
InstanceSave* mapSave = sInstanceSaveMgr->GetInstanceSave(_pendingBindId);
if (!mapSave) //it seems sometimes mapSave is nullptr, but I did not check why
return;
WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
data << uint32(0);
SendDirectMessage(&data);
if (!IsGameMaster())
{
BindToInstance(mapSave, true, EXTEND_STATE_KEEP);
GetSession()->SendCalendarRaidLockoutAdded(mapSave);
}
}
void Player::SetPendingBind(uint32 instanceId, uint32 bindTimer)
{
_pendingBindId = instanceId;
_pendingBindTimer = bindTimer;
}
void Player::SendRaidInfo()
{
uint32 counter = 0;
WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
size_t p_counter = data.wpos();
data << uint32(counter); // placeholder
time_t now = GameTime::GetGameTime();
for (uint8 i = 0; i < MAX_DIFFICULTY; ++i)
{
for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
{
InstancePlayerBind const& bind = itr->second;
if (bind.perm)
{
InstanceSave* save = bind.save;
data << uint32(save->GetMapId()); // map id
data << uint32(save->GetDifficulty()); // difficulty
data << uint64(save->GetInstanceId()); // instance id
data << uint8(bind.extendState != EXTEND_STATE_EXPIRED); // expired = 0
data << uint8(bind.extendState == EXTEND_STATE_EXTENDED); // extended = 1
time_t nextReset = save->GetResetTime();
if (bind.extendState == EXTEND_STATE_EXTENDED)
nextReset = sInstanceSaveMgr->GetSubsequentResetTime(save->GetMapId(), save->GetDifficulty(), save->GetResetTime());
data << uint32(nextReset - now); // reset time
++counter;
}
}
}
data.put<uint32>(p_counter, counter);
SendDirectMessage(&data);
}
/*
- called on every successful teleportation to a map
*/
void Player::SendSavedInstances()
{
bool hasBeenSaved = false;
WorldPacket data;
for (uint8 i = 0; i < MAX_DIFFICULTY; ++i)
{
for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
{
if (itr->second.perm) // only permanent binds are sent
{
hasBeenSaved = true;
break;
}
}
}
//Send opcode SMSG_UPDATE_INSTANCE_OWNERSHIP. true or false means, whether you have current raid/heroic instances
data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP, 4);
data << uint32(hasBeenSaved);
SendDirectMessage(&data);
if (!hasBeenSaved)
return;
for (uint8 i = 0; i < MAX_DIFFICULTY; ++i)
{
for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
{
if (itr->second.perm)
{
data.Initialize(SMSG_UPDATE_LAST_INSTANCE, 4);
data << uint32(itr->second.save->GetMapId());
SendDirectMessage(&data);
}
}
}
}
bool Player::Satisfy(AccessRequirement const* ar, uint32 target_map, bool report)
{
if (!IsGameMaster() && ar)
{
uint8 LevelMin = 0;
uint8 LevelMax = 0;
MapEntry const* mapEntry = sMapStore.LookupEntry(target_map);
if (!mapEntry)
return false;
if (!sWorld->getBoolConfig(CONFIG_INSTANCE_IGNORE_LEVEL))
{
if (ar->levelMin && GetLevel() < ar->levelMin)
LevelMin = ar->levelMin;
if (ar->levelMax && GetLevel() > ar->levelMax)
LevelMax = ar->levelMax;
}
uint32 missingItem = 0;
if (ar->item)
{
if (!HasItemCount(ar->item) &&
(!ar->item2 || !HasItemCount(ar->item2)))
missingItem = ar->item;
}
else if (ar->item2 && !HasItemCount(ar->item2))
missingItem = ar->item2;
if (DisableMgr::IsDisabledFor(DISABLE_TYPE_MAP, target_map, this))
{
GetSession()->SendAreaTriggerMessage("%s", GetSession()->GetTrinityString(LANG_INSTANCE_CLOSED));
return false;
}
uint32 missingQuest = 0;
if (GetTeam() == ALLIANCE && ar->quest_A && !GetQuestRewardStatus(ar->quest_A))
missingQuest = ar->quest_A;
else if (GetTeam() == HORDE && ar->quest_H && !GetQuestRewardStatus(ar->quest_H))
missingQuest = ar->quest_H;
uint32 missingAchievement = 0;
Player* leader = this;
ObjectGuid leaderGuid = GetGroup() ? GetGroup()->GetLeaderGUID() : GetGUID();
if (leaderGuid != GetGUID())
leader = ObjectAccessor::FindPlayer(leaderGuid);
if (ar->achievement)
if (!leader || !leader->HasAchieved(ar->achievement))
missingAchievement = ar->achievement;
Difficulty target_difficulty = GetDifficulty(mapEntry->IsRaid());
MapDifficulty const* mapDiff = GetDownscaledMapDifficultyData(target_map, target_difficulty);
if (LevelMin || LevelMax || missingItem || missingQuest || missingAchievement)
{
if (report)
{
if (missingQuest && !ar->questFailedText.empty())
ChatHandler(GetSession()).PSendSysMessage("%s", ar->questFailedText.c_str());
else if (mapDiff->hasErrorMessage) // if (missingAchievement) covered by this case
SendTransferAborted(target_map, TRANSFER_ABORT_DIFFICULTY, target_difficulty);
else if (missingItem)
GetSession()->SendAreaTriggerMessage(GetSession()->GetTrinityString(LANG_LEVEL_MINREQUIRED_AND_ITEM), LevelMin, ASSERT_NOTNULL(sObjectMgr->GetItemTemplate(missingItem))->Name1.c_str());
else if (LevelMin)
GetSession()->SendAreaTriggerMessage(GetSession()->GetTrinityString(LANG_LEVEL_MINREQUIRED), LevelMin);
}
return false;
}
}
return true;
}
bool Player::IsInstanceLoginGameMasterException() const
{
if (CanBeGameMaster())
{
ChatHandler(GetSession()).SendSysMessage(LANG_INSTANCE_LOGIN_GAMEMASTER_EXCEPTION);
return true;
}
else
return false;
}
bool Player::CheckInstanceValidity(bool /*isLogin*/)
{
// game masters' instances are always valid
if (IsGameMaster())
return true;
// non-instances are always valid
Map* map = FindMap();
if (!map || !map->IsDungeon())
return true;
// raid instances require the player to be in a raid group to be valid
if (map->IsRaid() && !sWorld->getBoolConfig(CONFIG_INSTANCE_IGNORE_RAID))
if (!GetGroup() || !GetGroup()->isRaidGroup())
return false;
if (Group* group = GetGroup())
{
// check if player's group is bound to this instance
InstanceGroupBind* bind = group->GetBoundInstance(map->GetDifficulty(), map->GetId());
if (!bind || !bind->save || bind->save->GetInstanceId() != map->GetInstanceId())
return false;
Map::PlayerList const& players = map->GetPlayers();
if (!players.isEmpty())
for (Map::PlayerList::const_iterator it = players.begin(); it != players.end(); ++it)
{
if (Player* otherPlayer = it->GetSource())
{
if (otherPlayer->IsGameMaster())
continue;
if (!otherPlayer->m_InstanceValid) // ignore players that currently have a homebind timer active
continue;
if (group != otherPlayer->GetGroup())
return false;
}
}
}
else
{
// instance is invalid if we are not grouped and there are other players
if (map->GetPlayersCountExceptGMs() > 1)
return false;
// check if the player is bound to this instance
InstancePlayerBind* bind = GetBoundInstance(map->GetId(), map->GetDifficulty());
if (!bind || !bind->save || bind->save->GetInstanceId() != map->GetInstanceId())
return false;
}
return true;
}
bool Player::_LoadHomeBind(PreparedQueryResult result)
{
PlayerInfo const* info = sObjectMgr->GetPlayerInfo(GetRace(), GetClass());
if (!info)
{
TC_LOG_ERROR("entities.player", "Player::_LoadHomeBind: Player '{}' ({}) has incorrect race/class ({}/{}) pair. Can't load.",
GetGUID().ToString(), GetName(), uint32(GetRace()), uint32(GetClass()));
return false;
}
bool ok = false;
// SELECT mapId, zoneId, posX, posY, posZ FROM character_homebind WHERE guid = ?
if (result)
{
Field* fields = result->Fetch();
m_homebindMapId = fields[0].GetUInt16();
m_homebindAreaId = fields[1].GetUInt16();
m_homebindX = fields[2].GetFloat();
m_homebindY = fields[3].GetFloat();
m_homebindZ = fields[4].GetFloat();
MapEntry const* bindMapEntry = sMapStore.LookupEntry(m_homebindMapId);
// accept saved data only for valid position (and non instanceable), and accessable
if (MapManager::IsValidMapCoord(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ) &&
!bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion())
ok = true;
else
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_HOMEBIND);
stmt->setUInt32(0, GetGUID().GetCounter());
CharacterDatabase.Execute(stmt);
}
}
if (!ok)
{
m_homebindMapId = info->mapId;
m_homebindAreaId = info->areaId;
m_homebindX = info->positionX;
m_homebindY = info->positionY;
m_homebindZ = info->positionZ;
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_PLAYER_HOMEBIND);
stmt->setUInt32(0, GetGUID().GetCounter());
stmt->setUInt16(1, m_homebindMapId);
stmt->setUInt16(2, m_homebindAreaId);
stmt->setFloat (3, m_homebindX);
stmt->setFloat (4, m_homebindY);
stmt->setFloat (5, m_homebindZ);
CharacterDatabase.Execute(stmt);
}
TC_LOG_DEBUG("entities.player", "Player::_LoadHomeBind: Setting home position (MapID: {}, AreaID: {}, X: {}, Y: {}, Z: {}) of player '{}' ({})",
m_homebindMapId, m_homebindAreaId, m_homebindX, m_homebindY, m_homebindZ, GetName(), GetGUID().ToString());
return true;
}
/*********************************************************/
/*** SAVE SYSTEM ***/
/*********************************************************/
void Player::SaveToDB(bool create /*=false*/)
{
CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction();
SaveToDB(trans, create);
CharacterDatabase.CommitTransaction(trans);
}
void Player::SaveToDB(CharacterDatabaseTransaction trans, bool create /* = false */)
{
// delay auto save at any saves (manual, in code, or autosave)
m_nextSave = sWorld->getIntConfig(CONFIG_INTERVAL_SAVE);
//lets allow only players in world to be saved
if (IsBeingTeleportedFar())
{
ScheduleDelayedOperation(DELAYED_SAVE_PLAYER);
return;
}
// first save/honor gain after midnight will also update the player's honor fields
UpdateHonorFields();
TC_LOG_DEBUG("entities.unit", "Player::SaveToDB: The value of player {} at save: ", m_name);
outDebugValues();
if (!create)
sScriptMgr->OnPlayerSave(this);
CharacterDatabasePreparedStatement* stmt = nullptr;
uint8 index = 0;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_FISHINGSTEPS);
stmt->setUInt32(0, GetGUID().GetCounter());
trans->Append(stmt);
auto finiteAlways = [](float f) { return std::isfinite(f) ? f : 0.0f; };
if (create)
{
//! Insert query
/// @todo: Filter out more redundant fields that can take their default value at player create
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARACTER);
stmt->setUInt32(index++, GetGUID().GetCounter());
stmt->setUInt32(index++, GetSession()->GetAccountId());
stmt->setString(index++, GetName());
stmt->setUInt8(index++, GetRace());
stmt->setUInt8(index++, GetClass());
stmt->setUInt8(index++, GetNativeGender()); // save gender from PLAYER_BYTES_3, UNIT_BYTES_0 changes with every transform effect
stmt->setUInt8(index++, GetLevel());
stmt->setUInt32(index++, GetXP());
stmt->setUInt32(index++, GetMoney());
stmt->setUInt8(index++, GetSkinId());
stmt->setUInt8(index++, GetFaceId());
stmt->setUInt8(index++, GetHairStyleId());
stmt->setUInt8(index++, GetHairColorId());
stmt->setUInt8(index++, GetFacialStyle());
stmt->setUInt8(index++, GetBankBagSlotCount());
stmt->setUInt8(index++, GetRestState());
stmt->setUInt32(index++, GetUInt32Value(PLAYER_FLAGS));
stmt->setUInt16(index++, (uint16)GetMapId());
stmt->setUInt32(index++, (uint32)GetInstanceId());
stmt->setUInt8(index++, (uint8(GetDungeonDifficulty()) | uint8(GetRaidDifficulty()) << 4));
stmt->setFloat(index++, finiteAlways(GetPositionX()));
stmt->setFloat(index++, finiteAlways(GetPositionY()));
stmt->setFloat(index++, finiteAlways(GetPositionZ()));
stmt->setFloat(index++, finiteAlways(GetOrientation()));
stmt->setFloat(index++, finiteAlways(GetTransOffsetX()));
stmt->setFloat(index++, finiteAlways(GetTransOffsetY()));
stmt->setFloat(index++, finiteAlways(GetTransOffsetZ()));
stmt->setFloat(index++, finiteAlways(GetTransOffsetO()));
ObjectGuid::LowType transLowGUID = 0;
if (GetTransport())
transLowGUID = GetTransport()->GetGUID().GetCounter();
stmt->setUInt32(index++, transLowGUID);
std::ostringstream ss;
ss << m_taxi;
stmt->setString(index++, ss.str());
stmt->setUInt8(index++, m_cinematic);
stmt->setUInt32(index++, m_Played_time[PLAYED_TIME_TOTAL]);
stmt->setUInt32(index++, m_Played_time[PLAYED_TIME_LEVEL]);
stmt->setFloat(index++, finiteAlways(m_rest_bonus));
stmt->setUInt32(index++, uint32(GameTime::GetGameTime()));
stmt->setUInt8(index++, (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0));
//save, far from tavern/city
//save, but in tavern/city
stmt->setUInt32(index++, GetTalentResetCost());
stmt->setUInt32(index++, uint32(GetTalentResetTime()));
stmt->setUInt16(index++, (uint16)m_ExtraFlags);
stmt->setUInt8(index++, m_petStable ? m_petStable->MaxStabledPets : 0);
stmt->setUInt16(index++, (uint16)m_atLoginFlags);
stmt->setUInt16(index++, GetZoneId());
stmt->setUInt32(index++, uint32(m_deathExpireTime));
ss.str("");
ss << m_taxi.SaveTaxiDestinationsToString();
stmt->setString(index++, ss.str());
stmt->setUInt32(index++, GetArenaPoints());
stmt->setUInt32(index++, GetHonorPoints());
stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION));
stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORABLE_KILLS));
stmt->setUInt16(index++, GetUInt16Value(PLAYER_FIELD_KILLS, 0));
stmt->setUInt16(index++, GetUInt16Value(PLAYER_FIELD_KILLS, 1));
stmt->setUInt32(index++, GetUInt32Value(PLAYER_CHOSEN_TITLE));
stmt->setUInt64(index++, GetUInt64Value(PLAYER_FIELD_KNOWN_CURRENCIES));
stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX));
stmt->setUInt8(index++, GetDrunkValue());
stmt->setUInt32(index++, GetHealth());
for (uint32 i = 0; i < MAX_POWERS; ++i)
stmt->setUInt32(index++, GetPower(Powers(i)));
stmt->setUInt32(index++, GetSession()->GetLatency());
stmt->setUInt8(index++, GetSpecsCount());
stmt->setUInt8(index++, GetActiveSpec());
ss.str("");
for (uint32 i = 0; i < PLAYER_EXPLORED_ZONES_SIZE; ++i)
ss << GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + i) << ' ';
stmt->setString(index++, ss.str());
ss.str("");
// cache equipment...
for (uint32 i = 0; i < EQUIPMENT_SLOT_END * 2; ++i)
ss << GetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + i) << ' ';
// ...and bags for enum opcode
for (uint32 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
ss << item->GetEntry();
else
ss << '0';
ss << " 0 ";
}
stmt->setString(index++, ss.str());
stmt->setUInt32(index++, GetUInt32Value(PLAYER_AMMO_ID));
ss.str("");
for (uint32 i = 0; i < KNOWN_TITLES_SIZE*2; ++i)
ss << GetUInt32Value(PLAYER__FIELD_KNOWN_TITLES + i) << ' ';
stmt->setString(index++, ss.str());
stmt->setUInt8(index++, GetByteValue(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTES_OFFSET_ACTION_BAR_TOGGLES));
stmt->setUInt32(index++, m_grantableLevels);
}
else
{
// Update query
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHARACTER);
stmt->setString(index++, GetName());
stmt->setUInt8(index++, GetRace());
stmt->setUInt8(index++, GetClass());
stmt->setUInt8(index++, GetNativeGender()); // save gender from PLAYER_BYTES_3, UNIT_BYTES_0 changes with every transform effect
stmt->setUInt8(index++, GetLevel());
stmt->setUInt32(index++, GetXP());
stmt->setUInt32(index++, GetMoney());
stmt->setUInt8(index++, GetSkinId());
stmt->setUInt8(index++, GetFaceId());
stmt->setUInt8(index++, GetHairStyleId());
stmt->setUInt8(index++, GetHairColorId());
stmt->setUInt8(index++, GetFacialStyle());
stmt->setUInt8(index++, GetBankBagSlotCount());
stmt->setUInt8(index++, GetRestState());
stmt->setUInt32(index++, GetUInt32Value(PLAYER_FLAGS));
if (!IsBeingTeleported())
{
stmt->setUInt16(index++, (uint16)GetMapId());
stmt->setUInt32(index++, (uint32)GetInstanceId());
stmt->setUInt8(index++, (uint8(GetDungeonDifficulty()) | uint8(GetRaidDifficulty()) << 4));
stmt->setFloat(index++, finiteAlways(GetPositionX()));
stmt->setFloat(index++, finiteAlways(GetPositionY()));
stmt->setFloat(index++, finiteAlways(GetPositionZ()));
stmt->setFloat(index++, finiteAlways(GetOrientation()));
}
else
{
stmt->setUInt16(index++, (uint16)GetTeleportDest().GetMapId());
stmt->setUInt32(index++, (uint32)0);
stmt->setUInt8(index++, (uint8(GetDungeonDifficulty()) | uint8(GetRaidDifficulty()) << 4));
stmt->setFloat(index++, finiteAlways(GetTeleportDest().GetPositionX()));
stmt->setFloat(index++, finiteAlways(GetTeleportDest().GetPositionY()));
stmt->setFloat(index++, finiteAlways(GetTeleportDest().GetPositionZ()));
stmt->setFloat(index++, finiteAlways(GetTeleportDest().GetOrientation()));
}
stmt->setFloat(index++, finiteAlways(GetTransOffsetX()));
stmt->setFloat(index++, finiteAlways(GetTransOffsetY()));
stmt->setFloat(index++, finiteAlways(GetTransOffsetZ()));
stmt->setFloat(index++, finiteAlways(GetTransOffsetO()));
ObjectGuid::LowType transLowGUID = 0;
if (GetTransport())
transLowGUID = GetTransport()->GetGUID().GetCounter();
stmt->setUInt32(index++, transLowGUID);
std::ostringstream ss;
ss << m_taxi;
stmt->setString(index++, ss.str());
stmt->setUInt8(index++, m_cinematic);
stmt->setUInt32(index++, m_Played_time[PLAYED_TIME_TOTAL]);
stmt->setUInt32(index++, m_Played_time[PLAYED_TIME_LEVEL]);
stmt->setFloat(index++, finiteAlways(m_rest_bonus));
stmt->setUInt32(index++, uint32(GameTime::GetGameTime()));
stmt->setUInt8(index++, (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0));
//save, far from tavern/city
//save, but in tavern/city
stmt->setUInt32(index++, GetTalentResetCost());
stmt->setUInt32(index++, uint32(GetTalentResetTime()));
stmt->setUInt16(index++, (uint16)m_ExtraFlags);
stmt->setUInt8(index++, m_petStable ? m_petStable->MaxStabledPets : 0);
stmt->setUInt16(index++, (uint16)m_atLoginFlags);
stmt->setUInt16(index++, GetZoneId());
stmt->setUInt32(index++, uint32(m_deathExpireTime));
ss.str("");
ss << m_taxi.SaveTaxiDestinationsToString();
stmt->setString(index++, ss.str());
stmt->setUInt32(index++, GetArenaPoints());
stmt->setUInt32(index++, GetHonorPoints());
stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION));
stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORABLE_KILLS));
stmt->setUInt16(index++, GetUInt16Value(PLAYER_FIELD_KILLS, 0));
stmt->setUInt16(index++, GetUInt16Value(PLAYER_FIELD_KILLS, 1));
stmt->setUInt32(index++, GetUInt32Value(PLAYER_CHOSEN_TITLE));
stmt->setUInt64(index++, GetUInt64Value(PLAYER_FIELD_KNOWN_CURRENCIES));
stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX));
stmt->setUInt8(index++, GetDrunkValue());
stmt->setUInt32(index++, GetHealth());
for (uint32 i = 0; i < MAX_POWERS; ++i)
stmt->setUInt32(index++, GetPower(Powers(i)));
stmt->setUInt32(index++, GetSession()->GetLatency());
stmt->setUInt8(index++, GetSpecsCount());
stmt->setUInt8(index++, GetActiveSpec());
ss.str("");
for (uint32 i = 0; i < PLAYER_EXPLORED_ZONES_SIZE; ++i)
ss << GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + i) << ' ';
stmt->setString(index++, ss.str());
ss.str("");
// cache equipment...
for (uint32 i = 0; i < EQUIPMENT_SLOT_END * 2; ++i)
ss << GetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + i) << ' ';
// ...and bags for enum opcode
for (uint32 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
ss << item->GetEntry();
else
ss << '0';
ss << " 0 ";
}
stmt->setString(index++, ss.str());
stmt->setUInt32(index++, GetUInt32Value(PLAYER_AMMO_ID));
ss.str("");
for (uint32 i = 0; i < KNOWN_TITLES_SIZE*2; ++i)
ss << GetUInt32Value(PLAYER__FIELD_KNOWN_TITLES + i) << ' ';
stmt->setString(index++, ss.str());
stmt->setUInt8(index++, GetByteValue(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTES_OFFSET_ACTION_BAR_TOGGLES));
stmt->setUInt32(index++, m_grantableLevels);
stmt->setUInt8(index++, IsInWorld() && !GetSession()->PlayerLogout() ? 1 : 0);
// Index
stmt->setUInt32(index++, GetGUID().GetCounter());
}
trans->Append(stmt);
if (m_fishingSteps != 0)
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_FISHINGSTEPS);
index = 0;
stmt->setUInt32(index++, GetGUID().GetCounter());
stmt->setUInt32(index++, m_fishingSteps);
trans->Append(stmt);
}
if (m_mailsUpdated) //save mails only when needed
_SaveMail(trans);
_SaveBGData(trans);
_SaveInventory(trans);
_SaveQuestStatus(trans);
_SaveDailyQuestStatus(trans);
_SaveWeeklyQuestStatus(trans);
_SaveSeasonalQuestStatus(trans);
_SaveMonthlyQuestStatus(trans);
_SaveTalents(trans);
_SaveSpells(trans);
GetSpellHistory()->SaveToDB<Player>(trans);
_SaveActions(trans);
_SaveAuras(trans);
_SaveSkills(trans);
m_achievementMgr->SaveToDB(trans);
m_reputationMgr->SaveToDB(trans);
_SaveEquipmentSets(trans);
GetSession()->SaveTutorialsData(trans); // changed only while character in game
_SaveGlyphs(trans);
GetSession()->SaveInstanceTimeRestrictions(trans);
// check if stats should only be saved on logout
// save stats can be out of transaction
if (m_session->isLogingOut() || !sWorld->getBoolConfig(CONFIG_STATS_SAVE_ONLY_ON_LOGOUT))
_SaveStats(trans);
// save pet (hunter pet level and experience and all type pets health/mana).
if (Pet* pet = GetPet())
pet->SavePetToDB(PET_SAVE_AS_CURRENT);
}
// fast save function for item/money cheating preventing - save only inventory and money state
void Player::SaveInventoryAndGoldToDB(CharacterDatabaseTransaction trans)
{
_SaveInventory(trans);
SaveGoldToDB(trans);
}
void Player::SaveGoldToDB(CharacterDatabaseTransaction trans) const
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_MONEY);
stmt->setUInt32(0, GetMoney());
stmt->setUInt32(1, GetGUID().GetCounter());
trans->Append(stmt);
}
void Player::_SaveActions(CharacterDatabaseTransaction trans)
{
CharacterDatabasePreparedStatement* stmt;
for (ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end();)
{
switch (itr->second.uState)
{
case ACTIONBUTTON_NEW:
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_ACTION);
stmt->setUInt32(0, GetGUID().GetCounter());
stmt->setUInt8(1, GetActiveSpec());
stmt->setUInt8(2, itr->first);
stmt->setUInt32(3, itr->second.GetAction());
stmt->setUInt8(4, uint8(itr->second.GetType()));
trans->Append(stmt);
itr->second.uState = ACTIONBUTTON_UNCHANGED;
++itr;
break;
case ACTIONBUTTON_CHANGED:
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_ACTION);
stmt->setUInt32(0, itr->second.GetAction());
stmt->setUInt8(1, uint8(itr->second.GetType()));
stmt->setUInt32(2, GetGUID().GetCounter());
stmt->setUInt8(3, itr->first);
stmt->setUInt8(4, GetActiveSpec());
trans->Append(stmt);
itr->second.uState = ACTIONBUTTON_UNCHANGED;
++itr;
break;
case ACTIONBUTTON_DELETED:
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACTION_BY_BUTTON_SPEC);
stmt->setUInt32(0, GetGUID().GetCounter());
stmt->setUInt8(1, itr->first);
stmt->setUInt8(2, GetActiveSpec());
trans->Append(stmt);
m_actionButtons.erase(itr++);
break;
default:
++itr;
break;
}
}
}
void Player::_SaveAuras(CharacterDatabaseTransaction trans)
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_AURA);
stmt->setUInt32(0, GetGUID().GetCounter());
trans->Append(stmt);
for (AuraMap::const_iterator itr = m_ownedAuras.begin(); itr != m_ownedAuras.end(); ++itr)
{
if (!itr->second->CanBeSaved())
continue;
Aura* aura = itr->second;
int32 damage[MAX_SPELL_EFFECTS];
int32 baseDamage[MAX_SPELL_EFFECTS];
uint8 effMask = 0;
uint8 recalculateMask = 0;
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (AuraEffect const* effect = aura->GetEffect(i))
{
baseDamage[i] = effect->GetBaseAmount();
damage[i] = effect->GetAmount();
effMask |= 1 << i;
if (effect->CanBeRecalculated())
recalculateMask |= 1 << i;
}
else
{
baseDamage[i] = 0;
damage[i] = 0;
}
}
uint8 index = 0;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_AURA);
stmt->setUInt32(index++, GetGUID().GetCounter());
stmt->setUInt64(index++, itr->second->GetCasterGUID().GetRawValue());
stmt->setUInt64(index++, itr->second->GetCastItemGUID().GetRawValue());
stmt->setUInt32(index++, itr->second->GetId());
stmt->setUInt8(index++, effMask);
stmt->setUInt8(index++, recalculateMask);
stmt->setUInt8(index++, itr->second->GetStackAmount());
stmt->setInt32(index++, damage[0]);
stmt->setInt32(index++, damage[1]);
stmt->setInt32(index++, damage[2]);
stmt->setInt32(index++, baseDamage[0]);
stmt->setInt32(index++, baseDamage[1]);
stmt->setInt32(index++, baseDamage[2]);
stmt->setInt32(index++, itr->second->GetMaxDuration());
stmt->setInt32(index++, itr->second->GetDuration());
stmt->setUInt8(index++, itr->second->GetCharges());
stmt->setFloat(index++, itr->second->GetCritChance());
stmt->setBool (index++, itr->second->CanApplyResilience());
trans->Append(stmt);
}
}
void Player::_SaveInventory(CharacterDatabaseTransaction trans)
{
CharacterDatabasePreparedStatement* stmt;
// force items in buyback slots to new state
// and remove those that aren't already
for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; ++i)
{
Item* item = m_items[i];
if (!item)
continue;
if (item->GetState() == ITEM_NEW)
{
if (ItemTemplate const* itemTemplate = item->GetTemplate())
if (itemTemplate->HasFlag(ITEM_FLAG_HAS_LOOT))
sLootItemStorage->RemoveStoredLootForContainer(item->GetGUID().GetCounter());
continue;
}
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INVENTORY_BY_ITEM);
stmt->setUInt32(0, item->GetGUID().GetCounter());
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_INSTANCE);
stmt->setUInt32(0, item->GetGUID().GetCounter());
trans->Append(stmt);
m_items[i]->FSetState(ITEM_NEW);
if (ItemTemplate const* itemTemplate = item->GetTemplate())
if (itemTemplate->HasFlag(ITEM_FLAG_HAS_LOOT))
sLootItemStorage->RemoveStoredLootForContainer(item->GetGUID().GetCounter());
}
// Updated played time for refundable items. We don't do this in Player::Update because there's simply no need for it,
// the client auto counts down in real time after having received the initial played time on the first
// SMSG_ITEM_REFUND_INFO_RESPONSE packet.
// Item::UpdatePlayedTime is only called when needed, which is in DB saves, and item refund info requests.
GuidSet::iterator i_next;
for (GuidSet::iterator itr = m_refundableItems.begin(); itr!= m_refundableItems.end(); itr = i_next)
{
// use copy iterator because itr may be invalid after operations in this loop
i_next = itr;
++i_next;
Item* iPtr = GetItemByGuid(*itr);
if (iPtr)
{
iPtr->UpdatePlayedTime(this);
continue;
}
else
{
TC_LOG_ERROR("entities.player", "Player::_SaveInventory: Can't find item ({}) in refundable storage for player '{}' ({}), removing.",
itr->ToString(), GetName(), GetGUID().ToString());
m_refundableItems.erase(itr);
}
}
// update enchantment durations
for (EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
itr->item->SetEnchantmentDuration(itr->slot, itr->leftduration, this);
// if no changes
if (m_itemUpdateQueue.empty())
return;
for (size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
{
Item* item = m_itemUpdateQueue[i];
if (!item)
continue;
Bag* container = item->GetContainer();
if (item->GetState() != ITEM_REMOVED)
{
Item* test = GetItemByPos(item->GetBagSlot(), item->GetSlot());
if (test == nullptr)
{
ObjectGuid::LowType bagTestGUID = 0;
if (Item* test2 = GetItemByPos(INVENTORY_SLOT_BAG_0, item->GetBagSlot()))
bagTestGUID = test2->GetGUID().GetCounter();
TC_LOG_ERROR("entities.player", "Player::_SaveInventory: Player '{}' ({}) has incorrect values (Bag: {}, Slot: {}) for the item ({}, State: {}). The player doesn't have an item at that position.",
GetName(), GetGUID().ToString(), item->GetBagSlot(), item->GetSlot(), item->GetGUID().ToString(), (int32)item->GetState());
// according to the test that was just performed nothing should be in this slot, delete
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INVENTORY_BY_BAG_SLOT);
stmt->setUInt32(0, bagTestGUID);
stmt->setUInt8(1, item->GetSlot());
stmt->setUInt32(2, GetGUID().GetCounter());
trans->Append(stmt);
RemoveTradeableItem(item);
RemoveEnchantmentDurationsReferences(item);
RemoveItemDurations(item);
// also THIS item should be somewhere else, cheat attempt
item->FSetState(ITEM_REMOVED); // we are IN updateQueue right now, can't use SetState which modifies the queue
DeleteRefundReference(item->GetGUID());
// don't skip, let the switch delete it
//continue;
}
else if (test != item)
{
TC_LOG_ERROR("entities.player", "Player::_SaveInventory: Player '{}' ({}) has incorrect values (Bag: {}, Slot: {}) for the item ({}). {} is there instead!",
GetName(), GetGUID().ToString(), item->GetBagSlot(), item->GetSlot(), item->GetGUID().ToString(), test->GetGUID().ToString());
// save all changes to the item...
if (item->GetState() != ITEM_NEW) // only for existing items, no duplicates
item->SaveToDB(trans);
// ...but do not save position in inventory
continue;
}
}
switch (item->GetState())
{
case ITEM_NEW:
case ITEM_CHANGED:
stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_INVENTORY_ITEM);
stmt->setUInt32(0, GetGUID().GetCounter());
stmt->setUInt32(1, container ? container->GetGUID().GetCounter() : 0);
stmt->setUInt8 (2, item->GetSlot());
stmt->setUInt32(3, item->GetGUID().GetCounter());
trans->Append(stmt);
break;
case ITEM_REMOVED:
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INVENTORY_BY_ITEM);
stmt->setUInt32(0, item->GetGUID().GetCounter());
trans->Append(stmt);
break;
case ITEM_UNCHANGED:
break;
}
item->SaveToDB(trans); // item have unchanged inventory record and can be save standalone
}
m_itemUpdateQueue.clear();
}
void Player::_SaveMail(CharacterDatabaseTransaction trans)
{
CharacterDatabasePreparedStatement* stmt;
for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
{
Mail* m = (*itr);
if (m->state == MAIL_STATE_CHANGED)
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_MAIL);
stmt->setUInt8(0, uint8(m->HasItems() ? 1 : 0));
stmt->setUInt32(1, uint32(m->expire_time));
stmt->setUInt32(2, uint32(m->deliver_time));
stmt->setUInt32(3, m->money);
stmt->setUInt32(4, m->COD);
stmt->setUInt8(5, uint8(m->checked));
stmt->setUInt32(6, m->messageID);
trans->Append(stmt);
if (!m->removedItems.empty())
{
for (std::vector<ObjectGuid::LowType>::iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_ITEM);
stmt->setUInt32(0, *itr2);
trans->Append(stmt);
}
m->removedItems.clear();
}
m->state = MAIL_STATE_UNCHANGED;
}
else if (m->state == MAIL_STATE_DELETED)
{
if (m->HasItems())
{
for (MailItemInfoVec::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_INSTANCE);
stmt->setUInt32(0, itr2->item_guid);
trans->Append(stmt);
}
}
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_BY_ID);
stmt->setUInt32(0, m->messageID);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_ITEM_BY_ID);
stmt->setUInt32(0, m->messageID);
trans->Append(stmt);
}
}
//deallocate deleted mails...
for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();)
{
if ((*itr)->state == MAIL_STATE_DELETED)
{
Mail* m = *itr;
m_mail.erase(itr);
delete m;
itr = m_mail.begin();
}
else
++itr;
}
m_mailsUpdated = false;
}
void Player::_SaveQuestStatus(CharacterDatabaseTransaction trans)
{
bool isTransaction = bool(trans);
if (!isTransaction)
trans = CharacterDatabase.BeginTransaction();
QuestStatusSaveMap::iterator saveItr;
QuestStatusMap::iterator statusItr;
CharacterDatabasePreparedStatement* stmt;
bool keepAbandoned = !(sWorld->GetCleaningFlags() & CharacterDatabaseCleaner::CLEANING_FLAG_QUESTSTATUS);
for (saveItr = m_QuestStatusSave.begin(); saveItr != m_QuestStatusSave.end(); ++saveItr)
{
if (saveItr->second == QUEST_DEFAULT_SAVE_TYPE)
{
statusItr = m_QuestStatus.find(saveItr->first);
if (statusItr != m_QuestStatus.end() && (keepAbandoned || statusItr->second.Status != QUEST_STATUS_NONE))
{
uint8 index = 0;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_CHAR_QUESTSTATUS);
stmt->setUInt32(index++, GetGUID().GetCounter());
stmt->setUInt32(index++, statusItr->first);
stmt->setUInt8(index++, uint8(statusItr->second.Status));
stmt->setBool(index++, statusItr->second.Explored);
stmt->setUInt32(index++, uint32(statusItr->second.Timer / IN_MILLISECONDS+ GameTime::GetGameTime()));
for (uint8 i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
stmt->setUInt16(index++, statusItr->second.CreatureOrGOCount[i]);
for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; i++)
stmt->setUInt16(index++, statusItr->second.ItemCount[i]);
stmt->setUInt16(index, statusItr->second.PlayerCount);
trans->Append(stmt);
}
}
else
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_QUESTSTATUS_BY_QUEST);
stmt->setUInt32(0, GetGUID().GetCounter());
stmt->setUInt32(1, saveItr->first);
trans->Append(stmt);
}
}
m_QuestStatusSave.clear();
for (saveItr = m_RewardedQuestsSave.begin(); saveItr != m_RewardedQuestsSave.end(); ++saveItr)
{
if (saveItr->second == QUEST_DEFAULT_SAVE_TYPE)
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_QUESTSTATUS_REWARDED);
stmt->setUInt32(0, GetGUID().GetCounter());
stmt->setUInt32(1, saveItr->first);
trans->Append(stmt);
}
else if (saveItr->second == QUEST_FORCE_DELETE_SAVE_TYPE || !keepAbandoned)
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_QUESTSTATUS_REWARDED_BY_QUEST);
stmt->setUInt32(0, GetGUID().GetCounter());
stmt->setUInt32(1, saveItr->first);
trans->Append(stmt);
}
}
m_RewardedQuestsSave.clear();
if (!isTransaction)
CharacterDatabase.CommitTransaction(trans);
}
void Player::_SaveDailyQuestStatus(CharacterDatabaseTransaction trans)
{
if (!m_DailyQuestChanged)
return;
m_DailyQuestChanged = false;
// save last daily quest time for all quests: we need only mostly reset time for reset check anyway
// we don't need transactions here.
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHARACTER_QUESTSTATUS_DAILY);
stmt->setUInt32(0, GetGUID().GetCounter());
trans->Append(stmt);
for (uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
{
if (GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARACTER_QUESTSTATUS_DAILY);
stmt->setUInt32(0, GetGUID().GetCounter());
stmt->setUInt32(1, GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx));
stmt->setUInt64(2, uint64(m_lastDailyQuestTime));
trans->Append(stmt);
}
}
if (!m_DFQuests.empty())
{
for (DFQuestsDoneList::iterator itr = m_DFQuests.begin(); itr != m_DFQuests.end(); ++itr)
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARACTER_QUESTSTATUS_DAILY);
stmt->setUInt32(0, GetGUID().GetCounter());
stmt->setUInt32(1, (*itr));
stmt->setUInt64(2, uint64(m_lastDailyQuestTime));
trans->Append(stmt);
}
}
}
void Player::_SaveWeeklyQuestStatus(CharacterDatabaseTransaction trans)
{
if (!m_WeeklyQuestChanged || m_weeklyquests.empty())
return;
// we don't need transactions here.
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHARACTER_QUESTSTATUS_WEEKLY);
stmt->setUInt32(0, GetGUID().GetCounter());
trans->Append(stmt);
for (QuestSet::const_iterator iter = m_weeklyquests.begin(); iter != m_weeklyquests.end(); ++iter)
{
uint32 questId = *iter;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARACTER_QUESTSTATUS_WEEKLY);
stmt->setUInt32(0, GetGUID().GetCounter());
stmt->setUInt32(1, questId);
trans->Append(stmt);
}
m_WeeklyQuestChanged = false;
}
void Player::_SaveSeasonalQuestStatus(CharacterDatabaseTransaction trans)
{
if (!m_SeasonalQuestChanged)
return;
// we don't need transactions here.
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHARACTER_QUESTSTATUS_SEASONAL);
stmt->setUInt32(0, GetGUID().GetCounter());
trans->Append(stmt);
m_SeasonalQuestChanged = false;
if (m_seasonalquests.empty())
return;
for (SeasonalQuestMapByEvent::const_iterator iter = m_seasonalquests.begin(); iter != m_seasonalquests.end(); ++iter)
{
uint16 eventId = iter->first;
for (SeasonalQuestMapByQuest::const_iterator itr = iter->second.begin(); itr != iter->second.end(); ++itr)
{
uint32 questId = itr->first;
time_t completedTime = itr->second;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARACTER_QUESTSTATUS_SEASONAL);
stmt->setUInt32(0, GetGUID().GetCounter());
stmt->setUInt32(1, questId);
stmt->setUInt32(2, eventId);
stmt->setInt64(3, completedTime);
trans->Append(stmt);
}
}
}
void Player::_SaveMonthlyQuestStatus(CharacterDatabaseTransaction trans)
{
if (!m_MonthlyQuestChanged || m_monthlyquests.empty())
return;
// we don't need transactions here.
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHARACTER_QUESTSTATUS_MONTHLY);
stmt->setUInt32(0, GetGUID().GetCounter());
trans->Append(stmt);
for (QuestSet::const_iterator iter = m_monthlyquests.begin(); iter != m_monthlyquests.end(); ++iter)
{
uint32 questId = *iter;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARACTER_QUESTSTATUS_MONTHLY);
stmt->setUInt32(0, GetGUID().GetCounter());
stmt->setUInt32(1, questId);
trans->Append(stmt);
}
m_MonthlyQuestChanged = false;
}
void Player::_SaveSkills(CharacterDatabaseTransaction trans)
{
CharacterDatabasePreparedStatement* stmt;
// we don't need transactions here.
for (SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end();)
{
if (itr->second.uState == SKILL_UNCHANGED)
{
++itr;
continue;
}
if (itr->second.uState == SKILL_DELETED)
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SKILL_BY_SKILL);
stmt->setUInt32(0, GetGUID().GetCounter());
stmt->setUInt32(1, itr->first);
trans->Append(stmt);
mSkillStatus.erase(itr++);
continue;
}
uint16 value = GetSkillRankByPos(itr->second.pos);
uint16 max = GetSkillMaxRankByPos(itr->second.pos);
switch (itr->second.uState)
{
case SKILL_NEW:
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_SKILLS);
stmt->setUInt32(0, GetGUID().GetCounter());
stmt->setUInt16(1, uint16(itr->first));
stmt->setUInt16(2, value);
stmt->setUInt16(3, max);
trans->Append(stmt);
break;
case SKILL_CHANGED:
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_SKILLS);
stmt->setUInt16(0, value);
stmt->setUInt16(1, max);
stmt->setUInt32(2, GetGUID().GetCounter());
stmt->setUInt16(3, uint16(itr->first));
trans->Append(stmt);
break;
default:
break;
}
itr->second.uState = SKILL_UNCHANGED;
++itr;
}
}
void Player::_SaveSpells(CharacterDatabaseTransaction trans)
{
CharacterDatabasePreparedStatement* stmt;
for (PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end();)
{
if (itr->second.state == PLAYERSPELL_REMOVED || itr->second.state == PLAYERSPELL_CHANGED)
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SPELL_BY_SPELL);
stmt->setUInt32(0, itr->first);
stmt->setUInt32(1, GetGUID().GetCounter());
trans->Append(stmt);
}
// add only changed/new not dependent spells
if (!itr->second.dependent && (itr->second.state == PLAYERSPELL_NEW || itr->second.state == PLAYERSPELL_CHANGED))
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_SPELL);
stmt->setUInt32(0, GetGUID().GetCounter());
stmt->setUInt32(1, itr->first);
stmt->setBool(2, itr->second.active);
stmt->setBool(3, itr->second.disabled);
trans->Append(stmt);
}
if (itr->second.state == PLAYERSPELL_REMOVED)
{
itr = m_spells.erase(itr);
continue;
}
if (itr->second.state != PLAYERSPELL_TEMPORARY)
itr->second.state = PLAYERSPELL_UNCHANGED;
++itr;
}
}
// save player stats -- only for external usage
// real stats will be recalculated on player login
void Player::_SaveStats(CharacterDatabaseTransaction trans) const
{
// check if stat saving is enabled and if char level is high enough
if (!sWorld->getIntConfig(CONFIG_MIN_LEVEL_STAT_SAVE) || GetLevel() < sWorld->getIntConfig(CONFIG_MIN_LEVEL_STAT_SAVE))
return;
CharacterDatabasePreparedStatement* stmt;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_STATS);
stmt->setUInt32(0, GetGUID().GetCounter());
trans->Append(stmt);
uint8 index = 0;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_STATS);
stmt->setUInt32(index++, GetGUID().GetCounter());
stmt->setUInt32(index++, GetMaxHealth());
for (uint8 i = 0; i < MAX_POWERS; ++i)
stmt->setUInt32(index++, GetMaxPower(Powers(i)));
for (uint8 i = 0; i < MAX_STATS; ++i)
stmt->setUInt32(index++, GetStat(Stats(i)));
for (int i = 0; i < MAX_SPELL_SCHOOL; ++i)
stmt->setUInt32(index++, GetResistance(SpellSchools(i)));
stmt->setFloat(index++, GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
stmt->setFloat(index++, GetFloatValue(PLAYER_DODGE_PERCENTAGE));
stmt->setFloat(index++, GetFloatValue(PLAYER_PARRY_PERCENTAGE));
stmt->setFloat(index++, GetFloatValue(PLAYER_CRIT_PERCENTAGE));
stmt->setFloat(index++, GetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE));
// Store the max spell crit percentage out of all the possible schools
float spellCrit = 0.0f;
for (int i = 0; i < MAX_SPELL_SCHOOL; ++i)
spellCrit = std::max(spellCrit, GetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1 + i));
stmt->setFloat(index++, spellCrit);
stmt->setUInt32(index++, GetUInt32Value(UNIT_FIELD_ATTACK_POWER));
stmt->setUInt32(index++, GetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER));
stmt->setUInt32(index++, GetBaseSpellPowerBonus());
stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + AsUnderlyingType(CR_CRIT_TAKEN_SPELL)));
trans->Append(stmt);
}
void Player::outDebugValues() const
{
if (!sLog->ShouldLog("entities.unit", LOG_LEVEL_DEBUG))
return;
TC_LOG_DEBUG("entities.unit", "HP is: \t\t\t{}\t\tMP is: \t\t\t{}", GetMaxHealth(), GetMaxPower(POWER_MANA));
TC_LOG_DEBUG("entities.unit", "AGILITY is: \t\t{}\t\tSTRENGTH is: \t\t{}", GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
TC_LOG_DEBUG("entities.unit", "INTELLECT is: \t\t{}\t\tSPIRIT is: \t\t{}", GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
TC_LOG_DEBUG("entities.unit", "STAMINA is: \t\t{}", GetStat(STAT_STAMINA));
TC_LOG_DEBUG("entities.unit", "Armor is: \t\t{}\t\tBlock is: \t\t{}", GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
TC_LOG_DEBUG("entities.unit", "HolyRes is: \t\t{}\t\tFireRes is: \t\t{}", GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
TC_LOG_DEBUG("entities.unit", "NatureRes is: \t\t{}\t\tFrostRes is: \t\t{}", GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
TC_LOG_DEBUG("entities.unit", "ShadowRes is: \t\t{}\t\tArcaneRes is: \t\t{}", GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
TC_LOG_DEBUG("entities.unit", "MIN_DAMAGE is: \t\t{}\tMAX_DAMAGE is: \t\t{}", GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
TC_LOG_DEBUG("entities.unit", "MIN_OFFHAND_DAMAGE is: \t{}\tMAX_OFFHAND_DAMAGE is: \t{}", GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
TC_LOG_DEBUG("entities.unit", "MIN_RANGED_DAMAGE is: \t{}\tMAX_RANGED_DAMAGE is: \t{}", GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
TC_LOG_DEBUG("entities.unit", "ATTACK_TIME is: \t{}\t\tRANGE_ATTACK_TIME is: \t{}", GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
}
/*********************************************************/
/*** FLOOD FILTER SYSTEM ***/
/*********************************************************/
void Player::UpdateSpeakTime(ChatFloodThrottle::Index index)
{
// ignore chat spam protection for GMs in any mode
if (GetSession()->HasPermission(rbac::RBAC_PERM_SKIP_CHECK_CHAT_SPAM))
return;
uint32 limit;
uint32 delay;
switch (index)
{
case ChatFloodThrottle::REGULAR:
limit = sWorld->getIntConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
delay = sWorld->getIntConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
break;
case ChatFloodThrottle::ADDON:
limit = sWorld->getIntConfig(CONFIG_CHATFLOOD_ADDON_MESSAGE_COUNT);
delay = sWorld->getIntConfig(CONFIG_CHATFLOOD_ADDON_MESSAGE_DELAY);
break;
default:
return;
}
time_t current = GameTime::GetGameTime();
if (m_chatFloodData[index].Time > current)
{
if (!limit)
return;
++m_chatFloodData[index].Count;
if (m_chatFloodData[index].Count >= limit)
{
// prevent overwrite mute time, if message send just before mutes set, for example.
time_t new_mute = current + sWorld->getIntConfig(CONFIG_CHATFLOOD_MUTE_TIME);
if (GetSession()->m_muteTime < new_mute)
GetSession()->m_muteTime = new_mute;
m_chatFloodData[index].Count = 0;
}
}
else
m_chatFloodData[index].Count = 1;
m_chatFloodData[index].Time = current + delay;
}
/*********************************************************/
/*** LOW LEVEL FUNCTIONS:Notifiers ***/
/*********************************************************/
void Player::SavePositionInDB(WorldLocation const& loc, uint16 zoneId, ObjectGuid guid, CharacterDatabaseTransaction trans)
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHARACTER_POSITION);
stmt->setFloat(0, loc.GetPositionX());
stmt->setFloat(1, loc.GetPositionY());
stmt->setFloat(2, loc.GetPositionZ());
stmt->setFloat(3, loc.GetOrientation());
stmt->setUInt16(4, uint16(loc.GetMapId()));
stmt->setUInt16(5, zoneId);
stmt->setUInt32(6, guid.GetCounter());
CharacterDatabase.ExecuteOrAppend(trans, stmt);
}
void Player::Customize(CharacterCustomizeInfo const* customizeInfo, CharacterDatabaseTransaction trans)
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GENDER_AND_APPEARANCE);
stmt->setUInt8(0, customizeInfo->Gender);
stmt->setUInt8(1, customizeInfo->Skin);
stmt->setUInt8(2, customizeInfo->Face);
stmt->setUInt8(3, customizeInfo->HairStyle);
stmt->setUInt8(4, customizeInfo->HairColor);
stmt->setUInt8(5, customizeInfo->FacialHair);
stmt->setUInt32(6, customizeInfo->Guid.GetCounter());
CharacterDatabase.ExecuteOrAppend(trans, stmt);
}
void Player::SendAttackSwingCantAttack() const
{
SendDirectMessage(WorldPackets::Combat::AttackSwingCantAttack().Write());
}
void Player::SendAttackSwingCancelAttack() const
{
SendDirectMessage(WorldPackets::Combat::CancelCombat().Write());
}
void Player::SendAttackSwingDeadTarget() const
{
SendDirectMessage(WorldPackets::Combat::AttackSwingDeadTarget().Write());
}
void Player::SendAttackSwingNotInRange() const
{
SendDirectMessage(WorldPackets::Combat::AttackSwingNotInRange().Write());
}
void Player::SendAttackSwingBadFacingAttack() const
{
SendDirectMessage(WorldPackets::Combat::AttackSwingBadFacing().Write());
}
void Player::SendAutoRepeatCancel(Unit* target)
{
WorldPackets::Combat::CancelAutoRepeat cancelAutoRepeat;
cancelAutoRepeat.Guid = target->GetPackGUID(); // may be it's target guid
SendMessageToSet(cancelAutoRepeat.Write(), true);
}
void Player::SendExplorationExperience(uint32 Area, uint32 Experience) const
{
WorldPacket data(SMSG_EXPLORATION_EXPERIENCE, 8);
data << uint32(Area);
data << uint32(Experience);
SendDirectMessage(&data);
}
void Player::SendDungeonDifficulty(bool IsInGroup) const
{
uint8 val = 0x00000001;
WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
data << (uint32)GetDungeonDifficulty();
data << uint32(val);
data << uint32(IsInGroup);
SendDirectMessage(&data);
}
void Player::SendRaidDifficulty(bool IsInGroup, int32 forcedDifficulty) const
{
uint8 val = 0x00000001;
WorldPacket data(MSG_SET_RAID_DIFFICULTY, 12);
data << uint32(forcedDifficulty == -1 ? GetRaidDifficulty() : forcedDifficulty);
data << uint32(val);
data << uint32(IsInGroup);
SendDirectMessage(&data);
}
void Player::SendResetFailedNotify(uint32 mapid) const
{
WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
data << uint32(mapid);
SendDirectMessage(&data);
}
/// Reset all solo instances and optionally send a message on success for each
void Player::ResetInstances(uint8 method, bool isRaid)
{
// method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
// we assume that when the difficulty changes, all instances that can be reset will be
Difficulty diff = GetDifficulty(isRaid);
for (BoundInstancesMap::iterator itr = m_boundInstances[diff].begin(); itr != m_boundInstances[diff].end();)
{
InstanceSave* p = itr->second.save;
MapEntry const* entry = sMapStore.LookupEntry(itr->first);
if (!entry || entry->IsRaid() != isRaid || !p->CanReset())
{
++itr;
continue;
}
if (method == INSTANCE_RESET_ALL)
{
// the "reset all instances" method can only reset normal maps
if (entry->InstanceType == MAP_RAID || diff == DUNGEON_DIFFICULTY_HEROIC)
{
++itr;
continue;
}
}
// if the map is loaded, reset it
Map* map = sMapMgr->FindMap(p->GetMapId(), p->GetInstanceId());
if (map && map->IsDungeon())
if (!map->ToInstanceMap()->Reset(method))
{
++itr;
continue;
}
// since this is a solo instance there should not be any players inside
if (method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
SendResetInstanceSuccess(p->GetMapId());
p->DeleteFromDB();
m_boundInstances[diff].erase(itr++);
// the following should remove the instance save from the manager and delete it as well
p->RemovePlayer(this);
}
}
void Player::SendResetInstanceSuccess(uint32 MapId) const
{
WorldPacket data(SMSG_INSTANCE_RESET, 4);
data << uint32(MapId);
SendDirectMessage(&data);
}
void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId) const
{
/*reasons for instance reset failure:
// 0: There are players inside the instance.
// 1: There are players offline in your party.
// 2>: There are players in your party attempting to zone into an instance.
*/
WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 8);
data << uint32(reason);
data << uint32(MapId);
SendDirectMessage(&data);
}
/*********************************************************/
/*** Update timers ***/
/*********************************************************/
///checks the 15 afk reports per 5 minutes limit
void Player::UpdateAfkReport(time_t currTime)
{
if (m_bgData.bgAfkReportedTimer <= currTime)
{
m_bgData.bgAfkReportedCount = 0;
m_bgData.bgAfkReportedTimer = currTime+5*MINUTE;
}
}
void Player::SetContestedPvP(Player* attackedPlayer)
{
if (attackedPlayer && (attackedPlayer == this || (duel && duel->Opponent == attackedPlayer)))
return;
SetContestedPvPTimer(30000);
if (!HasUnitState(UNIT_STATE_ATTACK_PLAYER))
{
AddUnitState(UNIT_STATE_ATTACK_PLAYER);
SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP);
// call MoveInLineOfSight for nearby contested guards
Trinity::AIRelocationNotifier notifier(*this);
Cell::VisitWorldObjects(this, notifier, GetVisibilityRange());
}
for (Unit* unit : m_Controlled)
{
if (!unit->HasUnitState(UNIT_STATE_ATTACK_PLAYER))
{
unit->AddUnitState(UNIT_STATE_ATTACK_PLAYER);
Trinity::AIRelocationNotifier notifier(*unit);
Cell::VisitWorldObjects(this, notifier, GetVisibilityRange());
}
}
}
void Player::UpdateContestedPvP(uint32 diff)
{
if (!m_contestedPvPTimer || IsInCombat())
return;
if (m_contestedPvPTimer <= diff)
ResetContestedPvP();
else
m_contestedPvPTimer -= diff;
}
void Player::ResetContestedPvP()
{
ClearUnitState(UNIT_STATE_ATTACK_PLAYER);
RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP);
m_contestedPvPTimer = 0;
}
void Player::UpdatePvPFlag(time_t currTime)
{
if (!IsPvP())
return;
if (!pvpInfo.EndTimer || (currTime < pvpInfo.EndTimer +300) || pvpInfo.IsHostile)
return;
if (pvpInfo.EndTimer <= currTime)
{
pvpInfo.EndTimer = 0;
RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_PVP_TIMER);
}
UpdatePvP(false);
}
void Player::UpdateDuelFlag(time_t currTime)
{
if (duel && duel->State == DUEL_STATE_COUNTDOWN && duel->StartTime <= currTime)
{
sScriptMgr->OnPlayerDuelStart(this, duel->Opponent);
SetUInt32Value(PLAYER_DUEL_TEAM, 1);
duel->Opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
duel->State = DUEL_STATE_IN_PROGRESS;
duel->Opponent->duel->State = DUEL_STATE_IN_PROGRESS;
}
}
Pet* Player::GetPet() const
{
ObjectGuid pet_guid = GetPetGUID();
if (!pet_guid.IsEmpty())
{
if (!pet_guid.IsPet())
return nullptr;
Pet* pet = ObjectAccessor::GetPet(*this, pet_guid);
if (!pet)
return nullptr;
if (IsInWorld())
return pet;
// there may be a guardian in this slot
//TC_LOG_ERROR("entities.player", "Player::GetPet: Pet {} does not exist.", GUID_LOPART(pet_guid));
//const_cast<Player*>(this)->SetPetGUID(0);
}
return nullptr;
}
void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
{
if (!pet)
pet = GetPet();
if (pet)
{
TC_LOG_DEBUG("entities.pet", "Player::RemovePet: Player '{}' ({}), Pet (Entry: {}, Mode: {}, ReturnReagent: {})",
GetName(), GetGUID().ToString(), pet->GetEntry(), mode, returnreagent);
if (pet->m_removed)
return;
}
if (returnreagent && (pet || m_temporaryUnsummonedPetNumber) && !InBattleground())
{
//returning of reagents only for players, so best done here
uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId);
if (spellInfo)
{
for (uint32 i = 0; i < MAX_SPELL_REAGENTS; ++i)
{
if (spellInfo->Reagent[i] > 0)
{
ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
InventoryResult msg = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i]);
if (msg == EQUIP_ERR_OK)
{
Item* item = StoreNewItem(dest, spellInfo->Reagent[i], true);
if (IsInWorld())
SendNewItem(item, spellInfo->ReagentCount[i], true, false);
}
}
}
}
m_temporaryUnsummonedPetNumber = 0;
}
if (!pet)
{
if (mode == PET_SAVE_NOT_IN_SLOT && m_petStable && m_petStable->CurrentPet)
{
// Handle removing pet while it is in "temporarily unsummoned" state, for example on mount
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_PET_SLOT_BY_ID);
stmt->setUInt8(0, PET_SAVE_NOT_IN_SLOT);
stmt->setUInt32(1, GetGUID().GetCounter());
stmt->setUInt32(2, m_petStable->CurrentPet->PetNumber);
CharacterDatabase.Execute(stmt);
m_petStable->UnslottedPets.push_back(std::move(*m_petStable->CurrentPet));
m_petStable->CurrentPet.reset();
}
return;
}
pet->CombatStop();
// only if current pet in slot
pet->SavePetToDB(mode);
ASSERT(m_petStable->CurrentPet && m_petStable->CurrentPet->PetNumber == pet->GetCharmInfo()->GetPetNumber());
if (mode == PET_SAVE_NOT_IN_SLOT)
{
m_petStable->UnslottedPets.push_back(std::move(*m_petStable->CurrentPet));
m_petStable->CurrentPet.reset();
}
else if (mode == PET_SAVE_AS_DELETED)
m_petStable->CurrentPet.reset();
// else if (stable slots) handled in opcode handlers due to required swaps
// else (current pet) doesnt need to do anything
SetMinion(pet, false);
pet->AddObjectToRemoveList();
pet->m_removed = true;
if (pet->isControlled())
{
WorldPacket data(SMSG_PET_SPELLS, 8);
data << uint64(0);
SendDirectMessage(&data);
if (GetGroup())
SetGroupUpdateFlag(GROUP_UPDATE_PET);
}
}
void Player::AddPetAura(PetAura const* petSpell)
{
m_petAuras.insert(petSpell);
if (Pet* pet = GetPet())
pet->CastPetAura(petSpell);
}
void Player::RemovePetAura(PetAura const* petSpell)
{
m_petAuras.erase(petSpell);
if (Pet* pet = GetPet())
pet->RemoveAurasDueToSpell(petSpell->GetAura(pet->GetEntry()));
}
void Player::StopCastingCharm()
{
if (IsGhouled())
{
RemoveGhoul();
return;
}
Unit* charm = GetCharmed();
if (!charm)
return;
if (charm->GetTypeId() == TYPEID_UNIT)
{
if (charm->ToCreature()->HasUnitTypeMask(UNIT_MASK_PUPPET))
static_cast<Puppet*>(charm)->UnSummon();
else if (charm->IsVehicle())
{
ExitVehicle();
// Temporary for issue https://github.com/TrinityCore/TrinityCore/issues/24876
if (!GetCharmedGUID().IsEmpty() && !charm->HasAuraTypeWithCaster(SPELL_AURA_CONTROL_VEHICLE, GetGUID()))
{
TC_LOG_FATAL("entities.player", "Player::StopCastingCharm Player '{}' ({}) is not able to uncharm vehicle ({}) because of missing SPELL_AURA_CONTROL_VEHICLE",
GetName(), GetGUID().ToString(), GetCharmedGUID().ToString());
// attempt to recover from missing HandleAuraControlVehicle unapply handling
// THIS IS A HACK, NEED TO FIND HOW IS IT EVEN POSSBLE TO NOT HAVE THE AURA
_ExitVehicle();
}
}
}
if (!GetCharmedGUID().IsEmpty())
charm->RemoveCharmAuras();
if (!GetCharmedGUID().IsEmpty())
{
TC_LOG_FATAL("entities.player", "Player::StopCastingCharm: Player '{}' ({}) is not able to uncharm unit ({})", GetName(), GetGUID().ToString(), GetCharmedGUID().ToString());
if (!charm->GetCharmerGUID().IsEmpty())
{
TC_LOG_FATAL("entities.player", "Player::StopCastingCharm: Charmed unit has charmer {}\nPlayer debug info: {}\nCharm debug info: {}",
charm->GetCharmerGUID().ToString(), GetDebugInfo(), charm->GetDebugInfo());
ABORT();
}
SetCharm(charm, false);
}
}
void Player::Say(std::string_view text, Language language, WorldObject const* /*= nullptr*/)
{
std::string _text(text);
sScriptMgr->OnPlayerChat(this, CHAT_MSG_SAY, language, _text);
WorldPacket data;
ChatHandler::BuildChatPacket(data, CHAT_MSG_SAY, language, this, this, _text);
SendMessageToSetInRange(&data, sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_SAY), true, false, true);
}
void Player::Say(uint32 textId, WorldObject const* target /*= nullptr*/)
{
Talk(textId, CHAT_MSG_SAY, sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_SAY), target);
}
void Player::Yell(std::string_view text, Language language, WorldObject const* /*= nullptr*/)
{
std::string _text(text);
sScriptMgr->OnPlayerChat(this, CHAT_MSG_YELL, language, _text);
WorldPacket data;
ChatHandler::BuildChatPacket(data, CHAT_MSG_YELL, language, this, this, _text);
SendMessageToSetInRange(&data, sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_YELL), true, false, true);
}
void Player::Yell(uint32 textId, WorldObject const* target /*= nullptr*/)
{
Talk(textId, CHAT_MSG_YELL, sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_YELL), target);
}
void Player::TextEmote(std::string_view text, WorldObject const* /*= nullptr*/, bool /*= false*/)
{
std::string _text(text);
sScriptMgr->OnPlayerChat(this, CHAT_MSG_EMOTE, LANG_UNIVERSAL, _text);
WorldPacket data;
ChatHandler::BuildChatPacket(data, CHAT_MSG_EMOTE, LANG_UNIVERSAL, this, this, _text);
SendMessageToSetInRange(&data, sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE), true, !GetSession()->HasPermission(rbac::RBAC_PERM_TWO_SIDE_INTERACTION_CHAT), true);
}
void Player::WhisperAddon(std::string const& text, Player* receiver)
{
std::string _text(text);
sScriptMgr->OnPlayerChat(this, CHAT_MSG_WHISPER, uint32(LANG_ADDON), _text, receiver);
WorldPacket data;
ChatHandler::BuildChatPacket(data, CHAT_MSG_WHISPER, LANG_ADDON, this, this, _text);
receiver->SendDirectMessage(&data);
}
void Player::TextEmote(uint32 textId, WorldObject const* target /*= nullptr*/, bool /*isBossEmote = false*/)
{
Talk(textId, CHAT_MSG_EMOTE, sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE), target);
}
void Player::Whisper(std::string_view text, Language language, Player* target, bool /*= false*/)
{
ASSERT(target);
bool isAddonMessage = language == LANG_ADDON;
if (!isAddonMessage) // if not addon data
language = LANG_UNIVERSAL; // whispers should always be readable
std::string _text(text);
sScriptMgr->OnPlayerChat(this, CHAT_MSG_WHISPER, language, _text, target);
WorldPacket data;
ChatHandler::BuildChatPacket(data, CHAT_MSG_WHISPER, Language(language), this, this, _text);
target->SendDirectMessage(&data);
// rest stuff shouldn't happen in case of addon message
if (isAddonMessage)
return;
ChatHandler::BuildChatPacket(data, CHAT_MSG_WHISPER_INFORM, Language(language), target, target, _text);
SendDirectMessage(&data);
if (!isAcceptWhispers() && !IsGameMaster() && !target->IsGameMaster())
{
SetAcceptWhispers(true);
ChatHandler(GetSession()).SendSysMessage(LANG_COMMAND_WHISPERON);
}
// announce afk or dnd message
if (target->isAFK())
ChatHandler(GetSession()).PSendSysMessage(LANG_PLAYER_AFK, target->GetName().c_str(), target->autoReplyMsg.c_str());
else if (target->isDND())
ChatHandler(GetSession()).PSendSysMessage(LANG_PLAYER_DND, target->GetName().c_str(), target->autoReplyMsg.c_str());
}
void Player::Whisper(uint32 textId, Player* target, bool /*isBossWhisper = false*/)
{
if (!target)
return;
BroadcastText const* bct = sObjectMgr->GetBroadcastText(textId);
if (!bct)
{
TC_LOG_ERROR("entities.unit", "WorldObject::MonsterWhisper: `broadcast_text` was not {} found", textId);
return;
}
LocaleConstant locale = target->GetSession()->GetSessionDbLocaleIndex();
WorldPacket data;
ChatHandler::BuildChatPacket(data, CHAT_MSG_WHISPER, LANG_UNIVERSAL, this, target, bct->GetText(locale, GetGender()), 0, "", locale);
target->SendDirectMessage(&data);
}
Item* Player::GetMItem(ObjectGuid::LowType id)
{
ItemMap::const_iterator itr = mMitems.find(id);
return itr != mMitems.end() ? itr->second : nullptr;
}
void Player::AddMItem(Item* it)
{
ASSERT(it);
//ASSERT deleted, because items can be added before loading
mMitems[it->GetGUID().GetCounter()] = it;
}
bool Player::RemoveMItem(ObjectGuid::LowType id)
{
return mMitems.erase(id) ? true : false;
}
void Player::SendOnCancelExpectedVehicleRideAura() const
{
WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
SendDirectMessage(&data);
}
void Player::PetSpellInitialize()
{
Pet* pet = GetPet();
if (!pet)
return;
CharmInfo* charmInfo = pet->GetCharmInfo();
WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
data << pet->GetGUID();
data << uint16(pet->GetCreatureTemplate()->family); // creature family (required for pet talents)
data << uint32(pet->GetDuration());
data << uint8(pet->GetReactState());
data << uint8(charmInfo->GetCommandState());
data << uint16(0); // Flags, mostly unknown
TC_LOG_DEBUG("entities.pet", "Player::PetspellInitialize: Creating spellgroups for summoned pet");
// action bar loop
charmInfo->BuildActionBar(&data);
size_t spellsCountPos = data.wpos();
// spells count
uint8 addlist = 0;
data << uint8(addlist); // placeholder
if (pet->IsPermanentPetFor(this))
{
// spells loop
for (PetSpellMap::iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
{
if (itr->second.state == PETSPELL_REMOVED)
continue;
data << uint32(MAKE_UNIT_ACTION_BUTTON(itr->first, itr->second.active));
++addlist;
}
}
data.put<uint8>(spellsCountPos, addlist);
//Cooldowns
pet->GetSpellHistory()->WritePacket<Pet>(data);
SendDirectMessage(&data);
}
void Player::PossessSpellInitialize()
{
Unit* charm = GetCharmed();
if (!charm)
return;
CharmInfo* charmInfo = charm->GetCharmInfo();
if (!charmInfo)
{
TC_LOG_ERROR("entities.player", "Player::PossessSpellInitialize: charm ({}) has no charminfo!", charm->GetGUID().ToString());
return;
}
WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
data << charm->GetGUID();
data << uint16(0);
data << uint32(0);
data << uint32(0);
charmInfo->BuildActionBar(&data);
data << uint8(0); // spells count
data << uint8(0); // cooldowns count
SendDirectMessage(&data);
}
void Player::VehicleSpellInitialize()
{
Creature* vehicle = GetVehicleCreatureBase();
if (!vehicle)
return;
uint8 cooldownCount = vehicle->GetSpellHistory()->GetCooldownsSizeForPacket();
WorldPacket data(SMSG_PET_SPELLS, 8 + 2 + 4 + 4 + 4 * 10 + 1 + 1 + cooldownCount * (4 + 2 + 4 + 4));
data << vehicle->GetGUID(); // Guid
data << uint16(0); // Pet Family (0 for all vehicles)
data << uint32(vehicle->IsSummon() ? vehicle->ToTempSummon()->GetTimer() : 0); // Duration
// The following three segments are read by the client as one uint32
data << uint8(vehicle->GetReactState()); // React State
data << uint8(0); // Command State
data << uint16(0x800); // DisableActions (set for all vehicles)
for (uint32 i = 0; i < MAX_CREATURE_SPELLS; ++i)
{
uint32 spellId = vehicle->m_spells[i];
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId);
if (!spellInfo)
{
data << uint16(0) << uint8(0) << uint8(i+8);
continue;
}
if (!sConditionMgr->IsObjectMeetingVehicleSpellConditions(vehicle->GetEntry(), spellId, this, vehicle))
{
TC_LOG_DEBUG("condition", "Player::VehicleSpellInitialize: Player '{}' ({}) doesn't meet conditions for vehicle (Entry: {}, Spell: {})",
GetName(), GetGUID().ToString(), vehicle->ToCreature()->GetEntry(), spellId);
data << uint16(0) << uint8(0) << uint8(i+8);
continue;
}
if (spellInfo->IsPassive())
vehicle->CastSpell(vehicle, spellId, true);
data << uint32(MAKE_UNIT_ACTION_BUTTON(spellId, i+8));
}
for (uint32 i = MAX_CREATURE_SPELLS; i < MAX_SPELL_CONTROL_BAR; ++i)
data << uint32(0);
data << uint8(0); // Auras?
// Cooldowns
vehicle->GetSpellHistory()->WritePacket<Pet>(data);
SendDirectMessage(&data);
}
void Player::CharmSpellInitialize()
{
Unit* charm = GetFirstControlled();
if (!charm)
return;
CharmInfo* charmInfo = charm->GetCharmInfo();
if (!charmInfo)
{
TC_LOG_ERROR("entities.player", "Player::CharmSpellInitialize(): Player '{}' ({}) has a charm ({}) but no no charminfo!",
GetName(), GetGUID().ToString(), charm->GetGUID().ToString());
return;
}
uint8 addlist = 0;
if (charm->GetTypeId() != TYPEID_PLAYER)
{
//CreatureInfo const* cinfo = charm->ToCreature()->GetCreatureTemplate();
//if (cinfo && cinfo->type == CREATURE_TYPE_DEMON && GetClass() == CLASS_WARLOCK)
{
for (uint32 i = 0; i < MAX_SPELL_CHARM; ++i)
if (charmInfo->GetCharmSpell(i)->GetAction())
++addlist;
}
}
WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+4*addlist+1);
data << charm->GetGUID();
data << uint16(0);
data << uint32(0);
if (charm->GetTypeId() != TYPEID_PLAYER)
data << uint8(charm->ToCreature()->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
else
data << uint32(0);
charmInfo->BuildActionBar(&data);
data << uint8(addlist);
if (addlist)
{
for (uint32 i = 0; i < MAX_SPELL_CHARM; ++i)
{
CharmSpellInfo* cspell = charmInfo->GetCharmSpell(i);
if (cspell->GetAction())
data << uint32(cspell->packedData);
}
}
data << uint8(0); // cooldowns count
SendDirectMessage(&data);
}
void Player::SendRemoveControlBar() const
{
WorldPacket data(SMSG_PET_SPELLS, 8);
data << uint64(0);
SendDirectMessage(&data);
}
bool Player::IsAffectedBySpellmod(SpellInfo const* spellInfo, SpellModifier* mod, Spell* spell)
{
if (!mod || !spellInfo)
return false;
// First time this aura applies a mod to us and is out of charges
if (spell && mod->ownerAura->IsUsingCharges() && !mod->ownerAura->GetCharges() && !spell->m_appliedMods.count(mod->ownerAura))
return false;
// +duration to infinite duration spells making them limited
if (mod->op == SPELLMOD_DURATION && spellInfo->GetDuration() == -1)
return false;
// mod crit to spells that can't crit
if (mod->op == SPELLMOD_CRITICAL_CHANCE && !spellInfo->HasAttribute(SPELL_ATTR0_CU_CAN_CRIT))
return false;
return spellInfo->IsAffectedBySpellMod(mod);
}
template <class T>
void Player::ApplySpellMod(uint32 spellId, SpellModOp op, T& basevalue, Spell* spell /*= nullptr*/) const
{
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId);
if (!spellInfo)
return;
float totalmul = 1.0f;
int32 totalflat = 0;
auto calculateSpellMod = [&](SpellModifier* mod)
{
switch (mod->type)
{
case SPELLMOD_FLAT:
totalflat += mod->value;
break;
case SPELLMOD_PCT:
// special case (skip > 10sec spell casts for instant cast setting)
if (op == SPELLMOD_CASTING_TIME && mod->value <= -100 && basevalue >= T(10000))
return;
else if (!Player::HasSpellModApplied(mod, spell))
{
// Special case for Surge of Light, do not apply critical chance reduction if others mods was not applied (i.e. procs while casting another spell)
// (Surge of Light is the only PCT_MOD on critical chance)
if (op == SPELLMOD_CRITICAL_CHANCE)
return;
// Special case for Backdraft: do not apply GCD reduction if cast time reduction was not applied (i.e. when Backlash is consumed first).
// (Backdraft is the only PCT_MOD on global cooldown)
else if (op == SPELLMOD_GLOBAL_COOLDOWN)
return;
}
totalmul += CalculatePct(1.0f, mod->value);
break;
}
Player::ApplyModToSpell(mod, spell);
};
// Drop charges for triggering spells instead of triggered ones
if (m_spellModTakingSpell)
spell = m_spellModTakingSpell;
SpellModifier* chargedMod = nullptr;
for (SpellModifier* mod : m_spellMods[op])
{
if (!IsAffectedBySpellmod(spellInfo, mod, spell))
continue;
if (mod->ownerAura->IsUsingCharges())
{
if (!chargedMod || (chargedMod->ownerAura->GetSpellInfo()->Priority < mod->ownerAura->GetSpellInfo()->Priority))
chargedMod = mod;
continue;
}
calculateSpellMod(mod);
}
if (chargedMod)
calculateSpellMod(chargedMod);
basevalue = T(float(basevalue + totalflat) * totalmul);
}
template TC_GAME_API void Player::ApplySpellMod(uint32 spellId, SpellModOp op, int32& basevalue, Spell* spell) const;
template TC_GAME_API void Player::ApplySpellMod(uint32 spellId, SpellModOp op, uint32& basevalue, Spell* spell) const;
template TC_GAME_API void Player::ApplySpellMod(uint32 spellId, SpellModOp op, float& basevalue, Spell* spell) const;
void Player::AddSpellMod(SpellModifier* mod, bool apply)
{
TC_LOG_DEBUG("spells", "Player::AddSpellMod: Player '{}' ({}), SpellID: {}", GetName(), GetGUID().ToString(), mod->spellId);
uint16 opcode = (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
flag96 modMask;
for (uint8 i = 0; i < 3; ++i)
{
for (uint32 eff = 0; eff < 32; ++eff)
{
modMask[i] = uint32(1) << eff;
if ((mod->mask & modMask))
{
int32 val = 0;
for (SpellModifier* spellMod : m_spellMods[mod->op])
{
if (spellMod->type == mod->type && (spellMod->mask & modMask))
val += spellMod->value;
}
val += apply ? mod->value : -(mod->value);
WorldPacket data(opcode, (1 + 1 + 4));
data << uint8(eff + 32 * i);
data << uint8(mod->op);
data << int32(val);
SendDirectMessage(&data);
}
}
modMask[i] = 0;
}
if (apply)
m_spellMods[mod->op].insert(mod);
else
m_spellMods[mod->op].erase(mod);
}
void Player::ApplyModToSpell(SpellModifier* mod, Spell* spell)
{
if (!spell)
return;
// don't do anything with no charges
if (mod->ownerAura->IsUsingCharges() && !mod->ownerAura->GetCharges())
return;
// register inside spell, proc system uses this to drop charges
spell->m_appliedMods.insert(mod->ownerAura);
}
bool Player::HasSpellModApplied(SpellModifier* mod, Spell* spell)
{
if (!spell)
return false;
return spell->m_appliedMods.count(mod->ownerAura) != 0;
}
void Player::SetSpellModTakingSpell(Spell* spell, bool apply)
{
if (apply && m_spellModTakingSpell != nullptr)
return;
if (!apply && (!m_spellModTakingSpell || m_spellModTakingSpell != spell))
return;
m_spellModTakingSpell = apply ? spell : nullptr;
}
// send Proficiency
void Player::SendProficiency(ItemClass itemClass, uint32 itemSubclassMask) const
{
WorldPacket data(SMSG_SET_PROFICIENCY, 1 + 4);
data << uint8(itemClass) << uint32(itemSubclassMask);
SendDirectMessage(&data);
}
void Player::RemovePetitionsAndSigns(ObjectGuid guid, CharterTypes type)
{
sPetitionMgr->RemoveSignaturesBySignerAndType(guid, type);
sPetitionMgr->RemovePetitionsByOwnerAndType(guid, type);
}
void Player::LeaveAllArenaTeams(ObjectGuid guid)
{
CharacterCacheEntry const* characterInfo = sCharacterCache->GetCharacterCacheByGuid(guid);
if (!characterInfo)
return;
for (uint8 i = 0; i < MAX_ARENA_SLOT; ++i)
{
uint32 arenaTeamId = characterInfo->ArenaTeamId[i];
if (arenaTeamId != 0)
{
ArenaTeam* arenaTeam = sArenaTeamMgr->GetArenaTeamById(arenaTeamId);
if (arenaTeam)
arenaTeam->DelMember(guid, true);
}
}
}
void Player::SetRestBonus(float rest_bonus_new)
{
// Prevent resting on max level
if (IsMaxLevel())
rest_bonus_new = 0;
if (rest_bonus_new < 0)
rest_bonus_new = 0;
float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5f/2;
if (rest_bonus_new > rest_bonus_max)
m_rest_bonus = rest_bonus_max;
else
m_rest_bonus = rest_bonus_new;
// update data for client
if ((GetsRecruitAFriendBonus(true) && (GetSession()->IsARecruiter() || GetSession()->GetRecruiterId() != 0)))
SetRestState(REST_STATE_RAF_LINKED);
else
{
if (m_rest_bonus > 10)
SetRestState(REST_STATE_RESTED);
else if (m_rest_bonus <= 1)
SetRestState(REST_STATE_NOT_RAF_LINKED);
}
//RestTickUpdate
SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
}
bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc /*= nullptr*/, uint32 spellid /*= 0*/)
{
if (nodes.size() < 2)
return false;
// not let cheating with start flight in time of logout process || while in combat || has type state: stunned || has type state: root
if (GetSession()->isLogingOut() || IsInCombat() || HasUnitState(UNIT_STATE_STUNNED) || HasUnitState(UNIT_STATE_ROOT))
{
GetSession()->SendActivateTaxiReply(ERR_TAXIPLAYERBUSY);
return false;
}
if (HasUnitFlag(UNIT_FLAG_REMOVE_CLIENT_CONTROL))
return false;
// taximaster case
if (npc)
{
// not let cheating with start flight mounted
if (IsMounted())
{
GetSession()->SendActivateTaxiReply(ERR_TAXIPLAYERALREADYMOUNTED);
return false;
}
if (IsInDisallowedMountForm())
{
GetSession()->SendActivateTaxiReply(ERR_TAXIPLAYERSHAPESHIFTED);
return false;
}
// not let cheating with start flight in time of logout process || if casting not finished || while in combat || if not use Spell's with EffectSendTaxi
if (IsNonMeleeSpellCast(false))
{
GetSession()->SendActivateTaxiReply(ERR_TAXIPLAYERBUSY);
return false;
}
}
// cast case or scripted call case
else
{
RemoveAurasByType(SPELL_AURA_MOUNTED);
if (IsInDisallowedMountForm())
RemoveAurasByType(SPELL_AURA_MOD_SHAPESHIFT);
if (Spell* spell = GetCurrentSpell(CURRENT_GENERIC_SPELL))
if (spell->m_spellInfo->Id != spellid)
InterruptSpell(CURRENT_GENERIC_SPELL, false);
InterruptSpell(CURRENT_AUTOREPEAT_SPELL, false);
if (Spell* spell = GetCurrentSpell(CURRENT_CHANNELED_SPELL))
if (spell->m_spellInfo->Id != spellid)
InterruptSpell(CURRENT_CHANNELED_SPELL, true);
}
uint32 sourcenode = nodes[0];
// starting node too far away (cheat?)
TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
if (!node)
{
GetSession()->SendActivateTaxiReply(ERR_TAXINOSUCHPATH);
return false;
}
// Prepare to flight start now
// stop combat at start taxi flight if any
CombatStop();
StopCastingCharm();
StopCastingBindSight();
ExitVehicle();
// stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
TradeCancel(true);
// clean not finished taxi path if any
m_taxi.ClearTaxiDestinations();
// 0 element current node
m_taxi.AddTaxiDestination(sourcenode);
// fill destinations path tail
uint32 sourcepath = 0;
uint32 totalcost = 0;
uint32 firstcost = 0;
uint32 prevnode = sourcenode;
uint32 lastnode;
for (uint32 i = 1; i < nodes.size(); ++i)
{
uint32 path, cost;
lastnode = nodes[i];
sObjectMgr->GetTaxiPath(prevnode, lastnode, path, cost);
if (!path)
{
m_taxi.ClearTaxiDestinations();
return false;
}
totalcost += cost;
if (i == 1)
firstcost = cost;
if (prevnode == sourcenode)
sourcepath = path;
m_taxi.AddTaxiDestination(lastnode);
prevnode = lastnode;
}
// get mount model (in case non taximaster (npc == NULL) allow more wide lookup)
//
// Hack-Fix for Alliance not being able to use Acherus taxi. There is
// only one mount ID for both sides. Probably not good to use 315 in case DBC nodes
// change but I couldn't find a suitable alternative. OK to use class because only DK
// can use this taxi.
uint32 mount_display_id = sObjectMgr->GetTaxiMountDisplayId(sourcenode, GetTeam(), npc == nullptr || (sourcenode == 315 && GetClass() == CLASS_DEATH_KNIGHT));
// in spell case allow 0 model
if ((mount_display_id == 0 && spellid == 0) || sourcepath == 0)
{
GetSession()->SendActivateTaxiReply(ERR_TAXIUNSPECIFIEDSERVERERROR);
m_taxi.ClearTaxiDestinations();
return false;
}
uint32 money = GetMoney();
if (npc)
{
float discount = GetReputationPriceDiscount(npc);
totalcost = uint32(ceil(totalcost * discount));
firstcost = uint32(ceil(firstcost * discount));
m_taxi.SetFlightMasterFactionTemplateId(npc->GetFaction());
}
else
m_taxi.SetFlightMasterFactionTemplateId(0);
if (money < totalcost)
{
GetSession()->SendActivateTaxiReply(ERR_TAXINOTENOUGHMONEY);
m_taxi.ClearTaxiDestinations();
return false;
}
//Checks and preparations done, DO FLIGHT
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN, 1);
// prevent stealth flight
//RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TALK);
if (sWorld->getBoolConfig(CONFIG_INSTANT_TAXI))
{
TaxiNodesEntry const* lastPathNode = sTaxiNodesStore.LookupEntry(nodes[nodes.size()-1]);
ASSERT(lastPathNode);
m_taxi.ClearTaxiDestinations();
ModifyMoney(-(int32)totalcost);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, totalcost);
TeleportTo(lastPathNode->ContinentID, lastPathNode->Pos.X, lastPathNode->Pos.Y, lastPathNode->Pos.Z, GetOrientation());
return false;
}
else
{
ModifyMoney(-(int32)firstcost);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, firstcost);
GetSession()->SendActivateTaxiReply(ERR_TAXIOK);
GetSession()->SendDoFlight(mount_display_id, sourcepath);
}
return true;
}
bool Player::ActivateTaxiPathTo(uint32 taxi_path_id, uint32 spellid /*= 0*/)
{
TaxiPathEntry const* entry = sTaxiPathStore.LookupEntry(taxi_path_id);
if (!entry)
return false;
std::vector<uint32> nodes;
nodes.resize(2);
nodes[0] = entry->FromTaxiNode;
nodes[1] = entry->ToTaxiNode;
return ActivateTaxiPathTo(nodes, nullptr, spellid);
}
void Player::FinishTaxiFlight()
{
if (!IsInFlight())
return;
GetMotionMaster()->Remove(FLIGHT_MOTION_TYPE);
m_taxi.ClearTaxiDestinations(); // not destinations, clear source node
}
void Player::CleanupAfterTaxiFlight()
{
m_taxi.ClearTaxiDestinations(); // not destinations, clear source node
Dismount();
RemoveUnitFlag(UNIT_FLAG_REMOVE_CLIENT_CONTROL | UNIT_FLAG_ON_TAXI);
}
void Player::ContinueTaxiFlight() const
{
uint32 sourceNode = m_taxi.GetTaxiSource();
if (!sourceNode)
return;
TC_LOG_DEBUG("entities.unit", "Player::ContinueTaxiFlight: Restart {} taxi flight", GetGUID().ToString());
uint32 mountDisplayId = sObjectMgr->GetTaxiMountDisplayId(sourceNode, GetTeam(), true);
if (!mountDisplayId)
return;
uint32 path = m_taxi.GetCurrentTaxiPath();
// search appropriate start path node
uint32 startNode = 0;
TaxiPathNodeList const& nodeList = sTaxiPathNodesByPath[path];
float distPrev;
float distNext = GetExactDistSq(nodeList[0]->Loc.X, nodeList[0]->Loc.Y, nodeList[0]->Loc.Z);
for (uint32 i = 1; i < nodeList.size(); ++i)
{
TaxiPathNodeEntry const* node = nodeList[i];
TaxiPathNodeEntry const* prevNode = nodeList[i-1];
// skip nodes at another map
if (node->ContinentID != GetMapId())
continue;
distPrev = distNext;
distNext = GetExactDistSq(node->Loc.X, node->Loc.Y, node->Loc.Z);
float distNodes =
(node->Loc.X - prevNode->Loc.X)*(node->Loc.X - prevNode->Loc.X) +
(node->Loc.Y - prevNode->Loc.Y)*(node->Loc.Y - prevNode->Loc.Y) +
(node->Loc.Z - prevNode->Loc.Z)*(node->Loc.Z - prevNode->Loc.Z);
if (distNext + distPrev < distNodes)
{
startNode = i;
break;
}
}
GetSession()->SendDoFlight(mountDisplayId, path, startNode);
}
void Player::SendTaxiNodeStatusMultiple()
{
for (auto itr = m_clientGUIDs.begin(); itr != m_clientGUIDs.end(); ++itr)
{
if (!itr->IsCreature())
continue;
Creature* creature = ObjectAccessor::GetCreature(*this, *itr);
if (!creature || creature->IsHostileTo(this))
continue;
if (!creature->HasNpcFlag(UNIT_NPC_FLAG_FLIGHTMASTER))
continue;
uint32 nearestNode = sObjectMgr->GetNearestTaxiNode(creature->GetPositionX(), creature->GetPositionY(), creature->GetPositionZ(), creature->GetMapId(), GetTeam());
if (!nearestNode)
continue;
WorldPacket data(SMSG_TAXINODE_STATUS, 9);
data << *itr;
data << uint8(m_taxi.IsTaximaskNodeKnown(nearestNode) ? 1 : 0);
SendDirectMessage(&data);
}
}
void Player::InitDataForForm(bool reapplyMods)
{
ShapeshiftForm form = GetShapeshiftForm();
SpellShapeshiftFormEntry const* ssEntry = sSpellShapeshiftFormStore.LookupEntry(form);
if (ssEntry && ssEntry->CombatRoundTime)
{
SetAttackTime(BASE_ATTACK, ssEntry->CombatRoundTime);
SetAttackTime(OFF_ATTACK, ssEntry->CombatRoundTime);
SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
}
else
SetRegularAttackTime();
UpdateDisplayPower();
// update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
if (!reapplyMods)
UpdateEquipSpellsAtFormChange();
UpdateAttackPowerAndDamage();
UpdateAttackPowerAndDamage(true);
}
void Player::InitDisplayIds()
{
PlayerInfo const* info = sObjectMgr->GetPlayerInfo(GetRace(), GetClass());
if (!info)
{
TC_LOG_ERROR("entities.player", "Player::InitDisplayIds: Player '{}' ({}) has incorrect race/class pair. Can't init display ids.", GetName(), GetGUID().ToString());
return;
}
uint8 gender = GetNativeGender();
switch (gender)
{
case GENDER_FEMALE:
SetDisplayId(info->displayId_f);
SetNativeDisplayId(info->displayId_f);
break;
case GENDER_MALE:
SetDisplayId(info->displayId_m);
SetNativeDisplayId(info->displayId_m);
break;
default:
TC_LOG_ERROR("entities.player", "Player::InitDisplayIds: Player '{}' ({}) has invalid gender {}", GetName(), GetGUID().ToString(), gender);
}
}
inline bool Player::_StoreOrEquipNewItem(uint32 vendorslot, uint32 item, uint8 count, uint8 bag, uint8 slot, int32 price, ItemTemplate const* pProto, Creature* pVendor, VendorItem const* crItem, bool bStore)
{
uint32 stacks = count;
count = stacks * pProto->BuyCount;
ItemPosCountVec vDest;
uint16 uiDest = 0;
InventoryResult msg = bStore ?
CanStoreNewItem(bag, slot, vDest, item, count) :
CanEquipNewItem(slot, uiDest, item, false);
if (msg != EQUIP_ERR_OK)
{
SendEquipError(msg, nullptr, nullptr, item);
return false;
}
ModifyMoney(-price);
if (crItem->ExtendedCost) // case for new honor system
{
ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
ASSERT(iece);
if (iece->HonorPoints)
ModifyHonorPoints(-int32(iece->HonorPoints * stacks));
if (iece->ArenaPoints)
ModifyArenaPoints(-int32(iece->ArenaPoints * stacks));
for (uint8 i = 0; i < MAX_ITEM_EXTENDED_COST_REQUIREMENTS; ++i)
{
if (iece->ItemID[i])
DestroyItemCount(iece->ItemID[i], iece->ItemCount[i] * stacks, true);
}
}
Item* it = bStore ?
StoreNewItem(vDest, item, true) :
EquipNewItem(uiDest, item, true);
if (it)
{
uint32 new_count = pVendor->UpdateVendorItemCurrentCount(crItem, count);
WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
data << pVendor->GetGUID();
data << uint32(vendorslot + 1); // numbered from 1 at client
data << int32(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
data << uint32(stacks);
SendDirectMessage(&data);
SendNewItem(it, count, true, false, false);
if (!bStore)
AutoUnequipOffhandIfNeed();
if (pProto->HasFlag(ITEM_FLAG_ITEM_PURCHASE_RECORD) && crItem->ExtendedCost && pProto->GetMaxStackSize() == 1)
{
it->SetFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_REFUNDABLE);
it->SetRefundRecipient(GetGUID());
it->SetPaidMoney(price);
it->SetPaidExtendedCost(crItem->ExtendedCost);
it->SaveRefundDataToDB();
AddRefundReference(it->GetGUID());
}
}
return true;
}
// Return true is the bought item has a max count to force refresh of window by caller
bool Player::BuyItemFromVendorSlot(ObjectGuid vendorguid, uint32 vendorslot, uint32 item, uint32 count, uint8 bag, uint8 slot)
{
// cheating attempt
if (count < 1) count = 1;
// cheating attempt
if (slot != NULL_SLOT)
if ((bag != INVENTORY_SLOT_BAG_0 && slot > MAX_BAG_SIZE) || (bag == INVENTORY_SLOT_BAG_0 && slot >= INVENTORY_SLOT_ITEM_END))
return false;
if (!IsAlive())
return false;
ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(item);
if (!pProto)
{
SendBuyError(BUY_ERR_CANT_FIND_ITEM, nullptr, item, 0);
return false;
}
if (!(pProto->AllowableClass & GetClassMask()) && pProto->Bonding == BIND_WHEN_PICKED_UP && !IsGameMaster())
{
SendBuyError(BUY_ERR_CANT_FIND_ITEM, nullptr, item, 0);
return false;
}
if (!IsGameMaster() && ((pProto->Flags2 & ITEM_FLAG2_FACTION_HORDE && GetTeam() == ALLIANCE) || (pProto->Flags2 == ITEM_FLAG2_FACTION_ALLIANCE && GetTeam() == HORDE)))
return false;
Creature* creature = GetNPCIfCanInteractWith(vendorguid, UNIT_NPC_FLAG_VENDOR);
if (!creature)
{
TC_LOG_DEBUG("network", "Player::BuyItemFromVendorSlot: Vendor ({}) not found or player '{}' ({}) can't interact with him.",
vendorguid.ToString(), GetName(), GetGUID().ToString());
SendBuyError(BUY_ERR_DISTANCE_TOO_FAR, nullptr, item, 0);
return false;
}
if (!sConditionMgr->IsObjectMeetingVendorItemConditions(creature->GetEntry(), item, this, creature))
{
TC_LOG_DEBUG("condition", "Player::BuyItemFromVendorSlot: Player '{}' ({}) doesn't meed conditions for creature (Entry: {}, Item: {})",
GetName(), GetGUID().ToString(), creature->GetEntry(), item);
SendBuyError(BUY_ERR_CANT_FIND_ITEM, creature, item, 0);
return false;
}
VendorItemData const* vItems = creature->GetVendorItems();
if (!vItems || vItems->Empty())
{
SendBuyError(BUY_ERR_CANT_FIND_ITEM, creature, item, 0);
return false;
}
if (vendorslot >= vItems->GetItemCount())
{
SendBuyError(BUY_ERR_CANT_FIND_ITEM, creature, item, 0);
return false;
}
VendorItem const* crItem = vItems->GetItem(vendorslot);
// store diff item (cheating)
if (!crItem || crItem->item != item)
{
SendBuyError(BUY_ERR_CANT_FIND_ITEM, creature, item, 0);
return false;
}
// check current item amount if it limited
if (crItem->maxcount != 0)
{
if (creature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count)
{
SendBuyError(BUY_ERR_ITEM_ALREADY_SOLD, creature, item, 0);
return false;
}
}
if (pProto->RequiredReputationFaction && (uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank))
{
SendBuyError(BUY_ERR_REPUTATION_REQUIRE, creature, item, 0);
return false;
}
if (crItem->ExtendedCost)
{
uint32 stacks = count;
ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
if (!iece)
{
TC_LOG_ERROR("entities.player", "Player::BuyItemFromVendorSlot: Item {} has wrong ExtendedCost field value {}", pProto->ItemId, crItem->ExtendedCost);
return false;
}
// honor points price
if (GetHonorPoints() < (iece->HonorPoints * stacks))
{
SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, nullptr, nullptr);
return false;
}
// arena points price
if (GetArenaPoints() < (iece->ArenaPoints * stacks))
{
SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, nullptr, nullptr);
return false;
}
// item base price
for (uint8 i = 0; i < MAX_ITEM_EXTENDED_COST_REQUIREMENTS; ++i)
{
if (iece->ItemID[i] && !HasItemCount(iece->ItemID[i], iece->ItemCount[i] * stacks))
{
SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, nullptr, nullptr);
return false;
}
}
// check for personal arena rating requirement
if (GetMaxPersonalArenaRatingRequirement(iece->ArenaBracket) < iece->RequiredArenaRating)
{
// probably not the proper equip err
SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK, nullptr, nullptr);
return false;
}
}
uint32 price = 0;
if (crItem->IsGoldRequired(pProto) && pProto->BuyPrice > 0) //Assume price cannot be negative (do not know why it is int32)
{
uint32 maxCount = MAX_MONEY_AMOUNT / pProto->BuyPrice;
if (uint32(count) > maxCount)
{
TC_LOG_ERROR("entities.player.cheat", "Player::BuyItemFromVendorSlot: Player '{}' ({}) tried to buy item (ItemID: {}, Count: {}), causing overflow",
GetName(), GetGUID().ToString(), pProto->ItemId, uint32(count));
count = uint32(maxCount);
}
price = pProto->BuyPrice * count; //it should not exceed MAX_MONEY_AMOUNT
// reputation discount
price = uint32(floor(price * GetReputationPriceDiscount(creature)));
if (!HasEnoughMoney(price))
{
SendBuyError(BUY_ERR_NOT_ENOUGHT_MONEY, creature, item, 0);
return false;
}
}
if ((bag == NULL_BAG && slot == NULL_SLOT) || IsInventoryPos(bag, slot))
{
if (!_StoreOrEquipNewItem(vendorslot, item, count, bag, slot, price, pProto, creature, crItem, true))
return false;
}
else if (IsEquipmentPos(bag, slot))
{
if (pProto->BuyCount * count != 1)
{
SendEquipError(EQUIP_ERR_NOT_EQUIPPABLE, nullptr, nullptr);
return false;
}
if (!_StoreOrEquipNewItem(vendorslot, item, count, bag, slot, price, pProto, creature, crItem, false))
return false;
}
else
{
SendEquipError(EQUIP_ERR_WRONG_SLOT, nullptr, nullptr);
return false;
}
return crItem->maxcount != 0;
}
uint32 Player::GetMaxPersonalArenaRatingRequirement(uint32 minarenaslot) const
{
// returns the maximal personal arena rating that can be used to purchase items requiring this condition
// the personal rating of the arena team must match the required limit as well
// so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
uint32 max_personal_rating = 0;
for (uint8 i = minarenaslot; i < MAX_ARENA_SLOT; ++i)
{
if (ArenaTeam* at = sArenaTeamMgr->GetArenaTeamById(GetArenaTeamId(i)))
{
uint32 p_rating = GetArenaPersonalRating(i);
uint32 t_rating = at->GetRating();
p_rating = p_rating < t_rating ? p_rating : t_rating;
if (max_personal_rating < p_rating)
max_personal_rating = p_rating;
}
}
return max_personal_rating;
}
void Player::UpdateHomebindTime(uint32 time)
{
// GMs never get homebind timer online
if (m_InstanceValid || IsGameMaster())
{
if (m_HomebindTimer) // instance valid, but timer not reset
{
// hide reminder
WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
data << uint32(0);
data << uint32(0);
SendDirectMessage(&data);
}
// instance is valid, reset homebind timer
m_HomebindTimer = 0;
}
else if (m_HomebindTimer > 0)
{
if (time >= m_HomebindTimer)
{
// teleport to nearest graveyard
RepopAtGraveyard();
}
else
m_HomebindTimer -= time;
}
else
{
// instance is invalid, start homebind timer
m_HomebindTimer = 60000;
// send message to player
WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
data << uint32(m_HomebindTimer);
data << uint32(1);
SendDirectMessage(&data);
TC_LOG_DEBUG("maps", "Player::UpdateHomebindTime: Player '{}' ({}) will be teleported to homebind in 60 seconds",
GetName(), GetGUID().ToString());
}
}
void Player::InitPvP()
{
// pvp flag should stay after relog
if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_IN_PVP))
UpdatePvP(true, true);
}
void Player::UpdatePvPState(bool onlyFFA)
{
/// @todo should we always synchronize UNIT_FIELD_BYTES_2, 1 of controller and controlled?
// no, we shouldn't, those are checked for affecting player by client
if (!pvpInfo.IsInNoPvPArea && !IsGameMaster()
&& (pvpInfo.IsInFFAPvPArea || sWorld->IsFFAPvPRealm()))
{
if (!IsFFAPvP())
{
SetPvpFlag(UNIT_BYTE2_FLAG_FFA_PVP);
for (ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
(*itr)->SetPvpFlag(UNIT_BYTE2_FLAG_FFA_PVP);
}
}
else if (IsFFAPvP())
{
RemovePvpFlag(UNIT_BYTE2_FLAG_FFA_PVP);
for (ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
(*itr)->RemovePvpFlag(UNIT_BYTE2_FLAG_FFA_PVP);
}
if (onlyFFA)
return;
if (pvpInfo.IsHostile) // in hostile area
{
if (!IsPvP() || pvpInfo.EndTimer)
UpdatePvP(true, true);
}
else // in friendly area
{
if (IsPvP() && !HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_IN_PVP) && !pvpInfo.EndTimer)
pvpInfo.EndTimer = GameTime::GetGameTime(); // start toggle-off
}
}
void Player::SetPvP(bool state)
{
Unit::SetPvP(state);
for (ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
(*itr)->SetPvP(state);
}
void Player::UpdatePvP(bool state, bool _override)
{
if (!state || _override)
{
SetPvP(state);
pvpInfo.EndTimer = 0;
}
else
{
pvpInfo.EndTimer = GameTime::GetGameTime();
SetPvP(state);
}
}
void Player::UpdatePotionCooldown(Spell* spell)
{
// no potion used i combat or still in combat
if (!m_lastPotionId || IsInCombat())
return;
// Call not from spell cast, send cooldown event for item spells if no in combat
if (!spell)
{
// spell/item pair let set proper cooldown (except non-existing charged spell cooldown spellmods for potions)
if (ItemTemplate const* proto = sObjectMgr->GetItemTemplate(m_lastPotionId))
for (uint8 idx = 0; idx < MAX_ITEM_PROTO_SPELLS; ++idx)
if (proto->Spells[idx].SpellId && proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE)
if (SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(proto->Spells[idx].SpellId))
GetSpellHistory()->SendCooldownEvent(spellInfo, m_lastPotionId);
}
// from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
else
{
if (spell->IsIgnoringCooldowns())
return;
else
GetSpellHistory()->SendCooldownEvent(spell->m_spellInfo, m_lastPotionId, spell);
}
m_lastPotionId = 0;
}
void Player::SetResurrectRequestData(WorldObject const* caster, uint32 health, uint32 mana, uint32 appliedAura)
{
ASSERT(!IsResurrectRequested());
_resurrectionData.reset(new ResurrectionData());
_resurrectionData->GUID = caster->GetGUID();
_resurrectionData->Location.WorldRelocate(*caster);
_resurrectionData->Health = health;
_resurrectionData->Mana = mana;
_resurrectionData->Aura = appliedAura;
}
//slot to be excluded while counting
bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot) const
{
if (!enchantmentcondition)
return true;
SpellItemEnchantmentConditionEntry const* Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
if (!Condition)
return true;
uint8 curcount[4] = {0, 0, 0, 0};
//counting current equipped gem colors
for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
{
if (i == slot)
continue;
Item* pItem2 = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
if (pItem2 && !pItem2->IsBroken() && pItem2->GetTemplate()->Socket[0].Color)
{
for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
{
uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
if (!enchant_id)
continue;
SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if (!enchantEntry)
continue;
uint32 gemid = enchantEntry->SrcItemID;
if (!gemid)
continue;
ItemTemplate const* gemProto = sObjectMgr->GetItemTemplate(gemid);
if (!gemProto)
continue;
GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
if (!gemProperty)
continue;
uint8 GemColor = gemProperty->Type;
for (uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
{
if (tmpcolormask & GemColor)
++curcount[b];
}
}
}
}
bool activate = true;
for (uint8 i = 0; i < 5; i++)
{
if (!Condition->LtOperandType[i])
continue;
uint32 _cur_gem = curcount[Condition->LtOperandType[i] - 1];
// if have <CompareColor> use them as count, else use <value> from Condition
uint32 _cmp_gem = Condition->RtOperandType[i] ? curcount[Condition->RtOperandType[i] - 1]: Condition->RtOperand[i];
switch (Condition->Operator[i])
{
case 2: // requires less <color> than (<value> || <comparecolor>) gems
activate &= (_cur_gem < _cmp_gem) ? true : false;
break;
case 3: // requires more <color> than (<value> || <comparecolor>) gems
activate &= (_cur_gem > _cmp_gem) ? true : false;
break;
case 5: // requires at least <color> than (<value> || <comparecolor>) gems
activate &= (_cur_gem >= _cmp_gem) ? true : false;
break;
}
}
TC_LOG_DEBUG("entities.player.items", "Player::EnchantmentFitsRequirements: Checking Condition {}, there are {} Meta Gems, {} Red Gems, {} Yellow Gems and {} Blue Gems, Activate:{}",
enchantmentcondition, curcount[0], curcount[1], curcount[2], curcount[3], activate ? "yes" : "no");
return activate;
}
void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
{
//cycle all equipped items
for (uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
{
//enchants for the slot being socketed are handled by Player::ApplyItemMods
if (slot == exceptslot)
continue;
Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
if (!pItem || !pItem->GetTemplate()->Socket[0].Color)
continue;
for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
{
uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
if (!enchant_id)
continue;
SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if (!enchantEntry)
continue;
uint32 condition = enchantEntry->ConditionID;
if (condition)
{
//was enchant active with/without item?
bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
//should it now be?
if (wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
{
// ignore item gem conditions
//if state changed, (dis)apply enchant
ApplyEnchantment(pItem, EnchantmentSlot(enchant_slot), !wasactive, true, true);
}
}
}
}
}
//if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
{
//cycle all equipped items
for (int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
{
//enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recvData)
if (slot == exceptslot)
continue;
Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
if (!pItem || !pItem->GetTemplate()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
continue;
//cycle all (gem)enchants
for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
{
uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
if (!enchant_id) //if no enchant go to next enchant(slot)
continue;
SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if (!enchantEntry)
continue;
//only metagems to be (de)activated, so only enchants with condition
uint32 condition = enchantEntry->ConditionID;
if (condition)
ApplyEnchantment(pItem, EnchantmentSlot(enchant_slot), apply);
}
}
}
void Player::SetBattlegroundEntryPoint()
{
// Taxi path store
if (!m_taxi.empty())
{
m_bgData.mountSpell = 0;
m_bgData.taxiPath[0] = m_taxi.GetTaxiSource();
m_bgData.taxiPath[1] = m_taxi.GetTaxiDestination();
// On taxi we don't need check for dungeon
m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
}
else
{
m_bgData.ClearTaxiPath();
// Mount spell id storing
if (IsMounted())
{
AuraEffectList const& auras = GetAuraEffectsByType(SPELL_AURA_MOUNTED);
if (!auras.empty())
m_bgData.mountSpell = (*auras.begin())->GetId();
}
else
m_bgData.mountSpell = 0;
// If map is dungeon find linked graveyard
if (GetMap()->IsDungeon())
{
if (WorldSafeLocsEntry const* entry = sObjectMgr->GetClosestGraveyard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam(), this))
m_bgData.joinPos = WorldLocation(entry->Continent, entry->Loc.X, entry->Loc.Y, entry->Loc.Z, 0.0f);
else
TC_LOG_ERROR("entities.player", "Player::SetBattlegroundEntryPoint: Dungeon (MapID: {}) has no linked graveyard, setting home location as entry point.", GetMapId());
}
// If new entry point is not BG or arena set it
else if (!GetMap()->IsBattlegroundOrArena())
m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
}
if (m_bgData.joinPos.m_mapId == MAPID_INVALID) // In error cases use homebind position
m_bgData.joinPos = WorldLocation(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, 0.0f);
}
void Player::SetBGTeam(uint32 team)
{
m_bgData.bgTeam = team;
SetArenaFaction(uint8(team == ALLIANCE ? 1 : 0));
}
uint32 Player::GetBGTeam() const
{
return m_bgData.bgTeam ? m_bgData.bgTeam : GetTeam();
}
void Player::LeaveBattleground(bool teleportToEntryPoint /*= true*/, bool withoutDeserterDebuff /*= false*/)
{
Battleground* bg = GetBattleground();
if (!bg)
return;
bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
// call after remove to be sure that player resurrected for correct cast
if (bg->isBattleground() && sWorld->getBoolConfig(CONFIG_BATTLEGROUND_CAST_DESERTER))
{
if (!withoutDeserterDebuff && !GetSession()->HasPermission(rbac::RBAC_PERM_NO_BATTLEGROUND_DESERTER_DEBUFF))
{
if (bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN)
{
//lets check if player was teleported from BG and schedule delayed Deserter spell cast
if (IsBeingTeleportedFar())
{
ScheduleDelayedOperation(DELAYED_SPELL_CAST_DESERTER);
return;
}
CastSpell(this, 26013, true); // Deserter
}
}
}
// track if player leaves the BG while inside it
if (bg->isBattleground() && sWorld->getBoolConfig(CONFIG_BATTLEGROUND_TRACK_DESERTERS) &&
(bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN))
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_DESERTER_TRACK);
stmt->setUInt32(0, GetGUID().GetCounter());
stmt->setUInt8(1, BG_DESERTION_TYPE_LEAVE_BG);
CharacterDatabase.Execute(stmt);
}
}
bool Player::CanJoinToBattleground(Battleground const* bg) const
{
uint32 perm = rbac::RBAC_PERM_JOIN_NORMAL_BG;
if (bg->isArena())
perm = rbac::RBAC_PERM_JOIN_ARENAS;
else if (bg->IsRandom())
perm = rbac::RBAC_PERM_JOIN_RANDOM_BG;
return GetSession()->HasPermission(perm);
}
bool Player::CanReportAfkDueToLimit()
{
// a player can complain about 15 people per 5 minutes
if (m_bgData.bgAfkReportedCount++ >= 15)
return false;
return true;
}
///This player has been blamed to be inactive in a battleground
void Player::ReportedAfkBy(Player* reporter)
{
WorldPackets::Battleground::ReportPvPPlayerAFKResult reportAfkResult;
reportAfkResult.Offender = GetGUID();
Battleground* bg = GetBattleground();
// Battleground also must be in progress!
if (!bg || bg != reporter->GetBattleground() || GetTeam() != reporter->GetTeam() || bg->GetStatus() != STATUS_IN_PROGRESS)
{
reporter->SendDirectMessage(reportAfkResult.Write());
return;
}
// check if player has 'Idle' or 'Inactive' debuff
if (m_bgData.bgAfkReporter.find(reporter->GetGUID()) == m_bgData.bgAfkReporter.end() && !HasAura(43680) && !HasAura(43681) && reporter->CanReportAfkDueToLimit())
{
m_bgData.bgAfkReporter.insert(reporter->GetGUID());
// by default 3 players have to complain to apply debuff
if (m_bgData.bgAfkReporter.size() >= sWorld->getIntConfig(CONFIG_BATTLEGROUND_REPORT_AFK))
{
// cast 'Idle' spell
CastSpell(this, 43680, true);
m_bgData.bgAfkReporter.clear();
reportAfkResult.NumBlackMarksOnOffender = m_bgData.bgAfkReporter.size();
reportAfkResult.NumPlayersIHaveReported = reporter->m_bgData.bgAfkReportedCount;
reportAfkResult.Result = WorldPackets::Battleground::ReportPvPPlayerAFKResult::PVP_REPORT_AFK_SUCCESS;
}
}
reporter->SendDirectMessage(reportAfkResult.Write());
}
uint8 Player::GetStartLevel(uint8 playerClass) const
{
uint8 startLevel = sWorld->getIntConfig(CONFIG_START_PLAYER_LEVEL);
if (playerClass == CLASS_DEATH_KNIGHT)
startLevel = std::max<uint8>(sWorld->getIntConfig(CONFIG_START_DEATH_KNIGHT_PLAYER_LEVEL), startLevel);
if (m_session->HasPermission(rbac::RBAC_PERM_USE_START_GM_LEVEL))
startLevel = std::max<uint8>(sWorld->getIntConfig(CONFIG_START_GM_LEVEL), startLevel);
return startLevel;
}
WorldLocation Player::GetStartPosition() const
{
PlayerInfo const* info = sObjectMgr->GetPlayerInfo(GetRace(), GetClass());
ASSERT(info);
uint32 mapId = info->mapId;
if (GetClass() == CLASS_DEATH_KNIGHT && HasSpell(50977))
mapId = 0;
return WorldLocation(mapId, info->positionX, info->positionY, info->positionZ, 0);
}
bool Player::HaveAtClient(Object const* u) const
{
return u == this || m_clientGUIDs.find(u->GetGUID()) != m_clientGUIDs.end();
}
bool Player::IsNeverVisible(bool allowServersideObjects) const
{
if (Unit::IsNeverVisible(allowServersideObjects))
return true;
if (GetSession()->PlayerLogout() || GetSession()->PlayerLoading())
return true;
return false;
}
bool Player::CanAlwaysSee(WorldObject const* obj) const
{
// Always can see self
if (GetCharmedOrSelf() == obj)
return true;
ObjectGuid guid = GetGuidValue(PLAYER_FARSIGHT);
if (!guid.IsEmpty())
if (obj->GetGUID() == guid)
return true;
return false;
}
bool Player::IsAlwaysDetectableFor(WorldObject const* seer) const
{
if (Unit::IsAlwaysDetectableFor(seer))
return true;
if (duel && duel->State != DUEL_STATE_CHALLENGED && duel->Opponent == seer)
return false;
if (Player const* seerPlayer = seer->ToPlayer())
if (IsGroupVisibleFor(seerPlayer))
return true;
return false;
}
bool Player::IsVisibleGloballyFor(Player const* u) const
{
if (!u)
return false;
// Always can see self
if (u == this)
return true;
// Visible units, always are visible for all players
if (IsVisible())
return true;
// GMs are visible for higher gms (or players are visible for gms)
if (!AccountMgr::IsPlayerAccount(u->GetSession()->GetSecurity()))
return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
// non faction visibility non-breakable for non-GMs
return false;
}
template<class T>
inline void UpdateVisibilityOf_helper(GuidUnorderedSet& s64, T* target, std::set<Unit*>& /*v*/)
{
s64.insert(target->GetGUID());
}
template<>
inline void UpdateVisibilityOf_helper(GuidUnorderedSet& s64, GameObject* target, std::set<Unit*>& /*v*/)
{
// @HACK: This is to prevent objects like deeprun tram from disappearing when player moves far from its spawn point while riding it
if ((target->GetGOInfo()->type != GAMEOBJECT_TYPE_TRANSPORT))
s64.insert(target->GetGUID());
}
template<>
inline void UpdateVisibilityOf_helper(GuidUnorderedSet& s64, Creature* target, std::set<Unit*>& v)
{
s64.insert(target->GetGUID());
v.insert(target);
}
template<>
inline void UpdateVisibilityOf_helper(GuidUnorderedSet& s64, Player* target, std::set<Unit*>& v)
{
s64.insert(target->GetGUID());
v.insert(target);
}
template<class T>
inline void BeforeVisibilityDestroy(T* /*t*/, Player* /*p*/) { }
template<>
inline void BeforeVisibilityDestroy<Creature>(Creature* t, Player* p)
{
if (p->GetPetGUID() == t->GetGUID() && t->IsPet())
t->ToPet()->Remove(PET_SAVE_NOT_IN_SLOT, true);
}
void Player::UpdateVisibilityOf(WorldObject* target)
{
if (HaveAtClient(target))
{
if (!CanSeeOrDetect(target, false, true))
{
if (target->GetTypeId() == TYPEID_UNIT)
BeforeVisibilityDestroy<Creature>(target->ToCreature(), this);
target->DestroyForPlayer(this);
m_clientGUIDs.erase(target->GetGUID());
#ifdef TRINITY_DEBUG
TC_LOG_DEBUG("maps", "Object {} out of range for player {}. Distance = {}", target->GetGUID().ToString(), GetGUID().ToString(), GetDistance(target));
#endif
}
}
else
{
if (CanSeeOrDetect(target, false, true))
{
target->SendUpdateToPlayer(this);
m_clientGUIDs.insert(target->GetGUID());
#ifdef TRINITY_DEBUG
TC_LOG_DEBUG("maps", "Object {} is visible now for player {}. Distance = {}", target->GetGUID().ToString(), GetGUID().ToString(), GetDistance(target));
#endif
// target aura duration for caster show only if target exist at caster client
// send data at target visibility change (adding to client)
if (target->IsUnit())
SendInitialVisiblePackets(static_cast<Unit*>(target));
}
}
}
void Player::UpdateTriggerVisibility()
{
if (m_clientGUIDs.empty())
return;
if (!IsInWorld())
return;
UpdateData udata;
WorldPacket packet;
for (auto itr = m_clientGUIDs.begin(); itr != m_clientGUIDs.end(); ++itr)
{
if (itr->IsCreatureOrVehicle())
{
Creature* creature = GetMap()->GetCreature(*itr);
// Update fields of triggers, transformed units or uninteractible units (values dependent on GM state)
if (!creature || (!creature->IsTrigger() && !creature->HasAuraType(SPELL_AURA_TRANSFORM) && !creature->HasUnitFlag(UNIT_FLAG_UNINTERACTIBLE)))
continue;
creature->SetFieldNotifyFlag(UF_FLAG_PUBLIC);
creature->BuildValuesUpdateBlockForPlayer(&udata, this);
creature->RemoveFieldNotifyFlag(UF_FLAG_PUBLIC);
}
else if (itr->IsGameObject())
{
GameObject* go = GetMap()->GetGameObject(*itr);
if (!go)
continue;
go->SetFieldNotifyFlag(UF_FLAG_PUBLIC);
go->BuildValuesUpdateBlockForPlayer(&udata, this);
go->RemoveFieldNotifyFlag(UF_FLAG_PUBLIC);
}
}
if (!udata.HasData())
return;
udata.BuildPacket(&packet);
SendDirectMessage(&packet);
}
void Player::SendInitialVisiblePackets(Unit* target) const
{
SendAurasForTarget(target);
if (target->IsAlive())
{
if (target->HasUnitState(UNIT_STATE_MELEE_ATTACKING) && target->GetVictim())
target->SendMeleeAttackStart(target->GetVictim());
}
}
template<class T>
void Player::UpdateVisibilityOf(T* target, UpdateData& data, std::set<Unit*>& visibleNow)
{
if (HaveAtClient(target))
{
if (!CanSeeOrDetect(target, false, true))
{
BeforeVisibilityDestroy<T>(target, this);
target->BuildOutOfRangeUpdateBlock(&data);
m_clientGUIDs.erase(target->GetGUID());
#ifdef TRINITY_DEBUG
TC_LOG_DEBUG("maps", "Object {} is out of range for player {}. Distance = {}", target->GetGUID().ToString(), GetGUID().ToString(), GetDistance(target));
#endif
}
}
else //if (visibleNow.size() < 30 || target->GetTypeId() == TYPEID_UNIT && target->ToCreature()->IsVehicle())
{
if (CanSeeOrDetect(target, false, true))
{
target->BuildCreateUpdateBlockForPlayer(&data, this);
UpdateVisibilityOf_helper(m_clientGUIDs, target, visibleNow);
#ifdef TRINITY_DEBUG
TC_LOG_DEBUG("maps", "Object {} is visible now for player {}. Distance = {}", target->GetGUID().ToString(), GetGUID().ToString(), GetDistance(target));
#endif
}
}
}
template void Player::UpdateVisibilityOf(Player* target, UpdateData& data, std::set<Unit*>& visibleNow);
template void Player::UpdateVisibilityOf(Creature* target, UpdateData& data, std::set<Unit*>& visibleNow);
template void Player::UpdateVisibilityOf(Corpse* target, UpdateData& data, std::set<Unit*>& visibleNow);
template void Player::UpdateVisibilityOf(GameObject* target, UpdateData& data, std::set<Unit*>& visibleNow);
template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, std::set<Unit*>& visibleNow);
void Player::UpdateObjectVisibility(bool forced)
{
// Prevent updating visibility if player is not in world (example: LoadFromDB sets drunkstate which updates invisibility while player is not in map)
if (!IsInWorld())
return;
if (!forced)
AddToNotify(NOTIFY_VISIBILITY_CHANGED);
else
{
Unit::UpdateObjectVisibility(true);
UpdateVisibilityForPlayer();
}
}
void Player::UpdateVisibilityForPlayer()
{
// updates visibility of all objects around point of view for current player
Trinity::VisibleNotifier notifier(*this);
Cell::VisitAllObjects(m_seer, notifier, GetSightRange());
notifier.SendToSelf(); // send gathered data
}
void Player::SetPhaseMask(uint32 newPhaseMask, bool update)
{
if (newPhaseMask == GetPhaseMask())
return;
Unit::SetPhaseMask(newPhaseMask, false);
if (Unit* vehicle = GetVehicleRoot())
vehicle->SetPhaseMask(newPhaseMask, update);
if (update)
UpdateObjectVisibility();
}
void Player::InitPrimaryProfessions()
{
SetFreePrimaryProfessions(sWorld->getIntConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
}
bool Player::ModifyMoney(int32 amount, bool sendError /*= true*/)
{
if (!amount)
return true;
sScriptMgr->OnPlayerMoneyChanged(this, amount);
if (amount < 0)
SetMoney (GetMoney() > uint32(-amount) ? GetMoney() + amount : 0);
else
{
if (GetMoney() < MAX_MONEY_AMOUNT - static_cast<uint32>(amount))
SetMoney(GetMoney() + amount);
else
{
sScriptMgr->OnPlayerMoneyLimit(this, amount);
if (sendError)
SendEquipError(EQUIP_ERR_TOO_MUCH_GOLD, nullptr, nullptr);
return false;
}
}
return true;
}
void Player::SetMoney(uint32 value)
{
SetUInt32Value(PLAYER_FIELD_COINAGE, value);
MoneyChanged(value);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_GOLD_VALUE_OWNED);
}
bool Player::IsQuestRewarded(uint32 quest_id) const
{
return m_RewardedQuests.find(quest_id) != m_RewardedQuests.end();
}
Unit* Player::GetSelectedUnit() const
{
ObjectGuid selectionGUID = GetTarget();
if (!selectionGUID.IsEmpty())
return ObjectAccessor::GetUnit(*this, selectionGUID);
return nullptr;
}
Player* Player::GetSelectedPlayer() const
{
ObjectGuid selectionGUID = GetTarget();
if (!selectionGUID.IsEmpty())
return ObjectAccessor::FindConnectedPlayer(selectionGUID);
return nullptr;
}
void Player::SetGroup(Group* group, int8 subgroup)
{
if (group == nullptr)
m_group.unlink();
else
{
// never use SetGroup without a subgroup unless you specify NULL for group
ASSERT(subgroup >= 0);
m_group.link(group, this);
m_group.setSubGroup((uint8)subgroup);
}
UpdateObjectVisibility(false);
}
void Player::SendInitialPacketsBeforeAddToMap()
{
/// Pass 'this' as argument because we're not stored in ObjectAccessor yet
/// SMSG_CONTACT_LIST
GetSocial()->SendSocialList(this, SOCIAL_FLAG_ALL);
// guild bank list wtf?
/// SMSG_BINDPOINTUPDATE
SendBindPointUpdate();
// SMSG_SET_PROFICIENCY
// SMSG_SET_PCT_SPELL_MODIFIER
// SMSG_SET_FLAT_SPELL_MODIFIER
// SMSG_UPDATE_AURA_DURATION
/// SMSG_TALENTS_INFO
SendTalentsInfoData(false);
/// SMSG_INSTANCE_DIFFICULTY
WorldPacket data(SMSG_INSTANCE_DIFFICULTY, 4+4);
data << uint32(GetMap()->GetDifficulty());
data << uint32(GetMap()->GetEntry()->IsDynamicDifficultyMap() && GetMap()->IsHeroic()); // Raid dynamic difficulty
SendDirectMessage(&data);
/// SMSG_INITIAL_SPELLS
SendInitialSpells();
/// SMSG_SEND_UNLEARN_SPELLS
SendUnlearnSpells();
/// SMSG_ACTION_BUTTONS
SendInitialActionButtons();
/// SMSG_INITIALIZE_FACTIONS
m_reputationMgr->SendInitialReputations();
/// SMSG_ALL_ACHIEVEMENT_DATA
m_achievementMgr->SendAllAchievementData();
/// SMSG_EQUIPMENT_SET_LIST
SendEquipmentSetList();
/// SMSG_LOGIN_SET_TIME_SPEED
static float const TimeSpeed = 0.01666667f;
WorldPackets::Misc::LoginSetTimeSpeed loginSetTimeSpeed;
loginSetTimeSpeed.NewSpeed = TimeSpeed;
loginSetTimeSpeed.GameTime = *GameTime::GetWowTime();
loginSetTimeSpeed.GameTimeHolidayOffset = 0; /// @todo
SendDirectMessage(loginSetTimeSpeed.Write());
/// SMSG_SET_FORCED_REACTIONS
GetReputationMgr().SendForceReactions();
// SMSG_TALENTS_INFO x 2 for pet (unspent points and talents in separate packets...)
// SMSG_PET_GUIDS
// SMSG_UPDATE_WORLD_STATE
// SMSG_POWER_UPDATE
/// SMSG_RESYNC_RUNES
ResyncRunes();
GetGameClient()->SetMovedUnit(this, true);
}
void Player::SendInitialPacketsAfterAddToMap()
{
UpdateVisibilityForPlayer();
// update zone
uint32 newzone, newarea;
GetZoneAndAreaId(newzone, newarea);
UpdateZone(newzone, newarea); // also call SendInitWorldStates();
GetSession()->ResetTimeSync();
GetSession()->SendTimeSync();
CastSpell(this, 836, true); // LOGINEFFECT
// set some aura effects that send packet to player client after add player to map
// SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
// same auras state lost at far teleport, send it one more time in this case also
static const AuraType auratypes[] =
{
SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED, SPELL_AURA_NONE
};
for (AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
{
Unit::AuraEffectList const& auraList = GetAuraEffectsByType(*itr);
if (!auraList.empty())
auraList.front()->HandleEffect(this, AURA_EFFECT_HANDLE_SEND_FOR_CLIENT, true);
}
if (HasAuraType(SPELL_AURA_MOD_STUN))
SetRooted(true);
WorldPacket setCompoundState(SMSG_MULTIPLE_MOVES, 100);
setCompoundState << uint32(0); // size placeholder
// manual send package (have code in HandleEffect(this, AURA_EFFECT_HANDLE_SEND_FOR_CLIENT, true); that must not be re-applied.
if (HasAuraType(SPELL_AURA_MOD_ROOT))
{
setCompoundState << uint8(2 + GetPackGUID().size() + 4);
setCompoundState << uint16(SMSG_FORCE_MOVE_ROOT);
setCompoundState << GetPackGUID();
setCompoundState << uint32(0); //! movement counter
}
if (HasAuraType(SPELL_AURA_FEATHER_FALL))
{
setCompoundState << uint8(2 + GetPackGUID().size() + 4);
setCompoundState << uint16(SMSG_MOVE_FEATHER_FALL);
setCompoundState << GetPackGUID();
setCompoundState << uint32(0); //! movement counter0
}
if (HasAuraType(SPELL_AURA_WATER_WALK))
{
setCompoundState << uint8(2 + GetPackGUID().size() + 4);
setCompoundState << uint16(SMSG_MOVE_WATER_WALK);
setCompoundState << GetPackGUID();
setCompoundState << uint32(0); //! movement counter0
}
if (HasAuraType(SPELL_AURA_HOVER))
{
setCompoundState << uint8(2 + GetPackGUID().size() + 4);
setCompoundState << uint16(SMSG_MOVE_SET_HOVER);
setCompoundState << GetPackGUID();
setCompoundState << uint32(0); //! movement counter0
}
if (setCompoundState.size() > 4)
{
setCompoundState.put<uint32>(0, setCompoundState.size() - 4);
SendDirectMessage(&setCompoundState);
}
SendEnchantmentDurations(); // must be after add to map
SendItemDurations(); // must be after add to map
SendQuestGiverStatusMultiple();
SendTaxiNodeStatusMultiple();
// raid downscaling - send difficulty to player
if (GetMap()->IsRaid())
{
if (GetMap()->GetDifficulty() != GetRaidDifficulty())
{
StoreRaidMapDifficulty();
SendRaidDifficulty(GetGroup() != nullptr, GetStoredRaidDifficulty());
}
}
else if (GetRaidDifficulty() != GetStoredRaidDifficulty())
SendRaidDifficulty(GetGroup() != nullptr);
if (!GetPlayerSharingQuest().IsEmpty())
{
if (Quest const* quest = sObjectMgr->GetQuestTemplate(GetSharedQuestID()))
PlayerTalkClass->SendQuestGiverQuestDetails(quest, GetGUID(), true);
else
ClearQuestSharingInfo();
}
}
void Player::SendUpdateToOutOfRangeGroupMembers()
{
if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
return;
if (Group* group = GetGroup())
group->UpdatePlayerOutOfRange(this);
m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
m_auraRaidUpdateMask = 0;
if (Pet* pet = GetPet())
pet->ResetAuraUpdateMaskForRaid();
}
void Player::SendTransferAborted(uint32 mapid, TransferAbortReason reason, uint8 arg) const
{
WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
data << uint32(mapid);
data << uint8(reason); // transfer abort reason
switch (reason)
{
case TRANSFER_ABORT_INSUF_EXPAN_LVL:
case TRANSFER_ABORT_DIFFICULTY:
case TRANSFER_ABORT_UNIQUE_MESSAGE:
// these are the ONLY cases that have an extra argument in the packet!!!
data << uint8(arg);
break;
default:
break;
}
SendDirectMessage(&data);
}
void Player::SendInstanceResetWarning(uint32 mapid, Difficulty difficulty, uint32 time, bool welcome) const
{
// type of warning, based on the time remaining until reset
uint32 type;
if (welcome)
type = RAID_INSTANCE_WELCOME;
else if (time > 21600)
type = RAID_INSTANCE_WELCOME;
else if (time > 3600)
type = RAID_INSTANCE_WARNING_HOURS;
else if (time > 300)
type = RAID_INSTANCE_WARNING_MIN;
else
type = RAID_INSTANCE_WARNING_MIN_SOON;
WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4+4);
data << uint32(type);
data << uint32(mapid);
data << uint32(difficulty); // difficulty
data << uint32(time);
if (type == RAID_INSTANCE_WELCOME)
{
data << uint8(0); // is locked
data << uint8(0); // is extended, ignored if prev field is 0
}
SendDirectMessage(&data);
}
void Player::ApplyEquipCooldown(Item* pItem)
{
if (pItem->GetTemplate()->HasFlag(ITEM_FLAG_NO_EQUIP_COOLDOWN))
return;
TimePoint now = GameTime::Now();
for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
{
_Spell const& spellData = pItem->GetTemplate()->Spells[i];
// no spell
if (spellData.SpellId <= 0)
continue;
// apply proc cooldown to equip auras if we have any
if (spellData.SpellTrigger == ITEM_SPELLTRIGGER_ON_EQUIP)
{
SpellProcEntry const* procEntry = sSpellMgr->GetSpellProcEntry(spellData.SpellId);
if (!procEntry)
continue;
if (Aura* itemAura = GetAura(spellData.SpellId, GetGUID(), pItem->GetGUID()))
itemAura->AddProcCooldown(now + procEntry->Cooldown);
continue;
}
// wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
if (spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
continue;
// Don't replace longer cooldowns by equip cooldown if we have any.
if (GetSpellHistory()->GetRemainingCooldown(sSpellMgr->AssertSpellInfo(spellData.SpellId)) > 30 * IN_MILLISECONDS)
continue;
GetSpellHistory()->AddCooldown(spellData.SpellId, pItem->GetEntry(), std::chrono::seconds(30));
WorldPacket data(SMSG_ITEM_COOLDOWN, 8 + 4);
data << pItem->GetGUID();
data << uint32(spellData.SpellId);
SendDirectMessage(&data);
}
}
void Player::ResetSpells(bool myClassOnly)
{
// not need after this call
if (HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
RemoveAtLoginFlag(AT_LOGIN_RESET_SPELLS, true);
// make full copy of map (spells removed and marked as deleted at another spell remove
// and we can't use original map for safe iterative with visit each spell at loop end
PlayerSpellMap smap = GetSpellMap();
uint32 family;
if (myClassOnly)
{
ChrClassesEntry const* clsEntry = sChrClassesStore.LookupEntry(GetClass());
if (!clsEntry)
return;
family = clsEntry->SpellClassSet;
for (PlayerSpellMap::const_iterator iter = smap.begin(); iter != smap.end(); ++iter)
{
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(iter->first);
if (!spellInfo)
continue;
// skip server-side/triggered spells
if (spellInfo->SpellLevel == 0)
continue;
// skip wrong class/race skills
if (!IsSpellFitByClassAndRace(spellInfo->Id))
continue;
// skip other spell families
if (spellInfo->SpellFamilyName != family)
continue;
// skip spells with first rank learned as talent (and all talents then also)
uint32 firstRank = spellInfo->GetFirstRankSpell()->Id;
if (GetTalentSpellCost(firstRank) > 0)
continue;
// skip broken spells
if (!SpellMgr::IsSpellValid(spellInfo, this, false))
continue;
}
}
else
for (PlayerSpellMap::const_iterator iter = smap.begin(); iter != smap.end(); ++iter)
RemoveSpell(iter->first, false, false); // only iter->first can be accessed, object by iter->second can be deleted already
LearnDefaultSkills();
LearnCustomSpells();
LearnQuestRewardedSpells();
}
void Player::LearnCustomSpells()
{
if (!sWorld->getBoolConfig(CONFIG_START_ALL_SPELLS))
return;
// learn default race/class spells
PlayerInfo const* info = sObjectMgr->GetPlayerInfo(GetRace(), GetClass());
ASSERT(info);
for (PlayerCreateInfoSpells::const_iterator itr = info->customSpells.begin(); itr != info->customSpells.end(); ++itr)
{
uint32 tspell = *itr;
TC_LOG_DEBUG("entities.player.loading", "Player::LearnCustomSpells: Player '{}' ({}, Class: {} Race: {}): Adding initial spell (SpellID: {})",
GetName(), GetGUID().ToString(), uint32(GetClass()), uint32(GetRace()), tspell);
if (!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
AddSpell(tspell, true, true, true, false);
else // but send in normal spell in game learn case
LearnSpell(tspell, true);
}
}
void Player::LearnDefaultSkills()
{
// learn default race/class skills
PlayerInfo const* info = sObjectMgr->GetPlayerInfo(GetRace(), GetClass());
ASSERT(info);
for (PlayerCreateInfoSkills::const_iterator itr = info->skills.begin(); itr != info->skills.end(); ++itr)
{
uint32 skillId = itr->SkillId;
if (HasSkill(skillId))
continue;
LearnDefaultSkill(skillId, itr->Rank);
}
}
void Player::LearnDefaultSkill(uint32 skillId, uint16 rank)
{
SkillRaceClassInfoEntry const* rcInfo = GetSkillRaceClassInfo(skillId, GetRace(), GetClass());
if (!rcInfo)
return;
TC_LOG_DEBUG("entities.player.loading", "PLAYER (Class: {} Race: {}): Adding initial skill, id = {}", uint32(GetClass()), uint32(GetRace()), skillId);
switch (GetSkillRangeType(rcInfo))
{
case SKILL_RANGE_LANGUAGE:
SetSkill(skillId, 0, 300, 300);
break;
case SKILL_RANGE_LEVEL:
{
uint16 skillValue = 1;
uint16 maxValue = GetMaxSkillValueForLevel();
if (sWorld->getBoolConfig(CONFIG_ALWAYS_MAXSKILL) && !IsProfessionOrRidingSkill(skillId))
skillValue = maxValue;
else if (rcInfo->Flags & SKILL_FLAG_ALWAYS_MAX_VALUE)
skillValue = maxValue;
else if (GetClass() == CLASS_DEATH_KNIGHT)
skillValue = std::min(std::max<uint16>({ 1, uint16((GetLevel() - 1) * 5) }), maxValue);
else if (skillId == SKILL_FIST_WEAPONS)
skillValue = std::max<uint16>(1, GetSkillValue(SKILL_UNARMED));
else if (skillId == SKILL_LOCKPICKING)
skillValue = std::max<uint16>(1, GetSkillValue(SKILL_LOCKPICKING));
SetSkill(skillId, 0, skillValue, maxValue);
break;
}
case SKILL_RANGE_MONO:
SetSkill(skillId, 0, 1, 1);
break;
case SKILL_RANGE_RANK:
{
if (!rank)
break;
SkillTiersEntry const* tier = sSkillTiersStore.LookupEntry(rcInfo->SkillTierID);
uint16 maxValue = tier->Value[std::max<int32>(rank - 1, 0)];
uint16 skillValue = 1;
if (rcInfo->Flags & SKILL_FLAG_ALWAYS_MAX_VALUE)
skillValue = maxValue;
else if (GetClass() == CLASS_DEATH_KNIGHT)
skillValue = std::min(std::max<uint16>({ uint16(1), uint16((GetLevel() - 1) * 5) }), maxValue);
SetSkill(skillId, rank, skillValue, maxValue);
break;
}
default:
break;
}
}
void Player::LearnQuestRewardedSpells(Quest const* quest)
{
int32 spell_id = quest->GetRewSpellCast();
uint32 src_spell_id = quest->GetSrcSpell();
// skip quests without rewarded spell
if (!spell_id)
return;
// if RewSpellCast = -1 we remove aura do to SrcSpell from player.
if (spell_id == -1 && src_spell_id)
{
RemoveAurasDueToSpell(src_spell_id);
return;
}
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spell_id);
if (!spellInfo)
return;
// check learned spells state
bool found = false;
for (SpellEffectInfo const& spellEffectInfo : spellInfo->GetEffects())
{
if (spellEffectInfo.IsEffect(SPELL_EFFECT_LEARN_SPELL) && !HasSpell(spellEffectInfo.TriggerSpell))
{
found = true;
break;
}
}
// skip quests with not teaching spell or already known spell
if (!found)
return;
uint32 learned_0 = spellInfo->GetEffect(EFFECT_0).TriggerSpell;
if (!HasSpell(learned_0))
{
SpellInfo const* learnedInfo = sSpellMgr->GetSpellInfo(learned_0);
if (!learnedInfo)
return;
// profession specialization can be re-learned from npc
if (learnedInfo->GetEffect(EFFECT_0).Effect == SPELL_EFFECT_TRADE_SKILL && learnedInfo->GetEffect(EFFECT_1).Effect == 0 && !learnedInfo->SpellLevel)
return;
}
CastSpell(this, spell_id, true);
}
void Player::LearnQuestRewardedSpells()
{
// learn spells received from quest completing
for (RewardedQuestSet::const_iterator itr = m_RewardedQuests.begin(); itr != m_RewardedQuests.end(); ++itr)
{
Quest const* quest = sObjectMgr->GetQuestTemplate(*itr);
if (!quest)
continue;
LearnQuestRewardedSpells(quest);
}
}
void Player::LearnSkillRewardedSpells(uint32 skillId, uint32 skillValue)
{
uint32 raceMask = GetRaceMask();
uint32 classMask = GetClassMask();
std::vector<SkillLineAbilityEntry const*> const* skillLineAbilities = GetSkillLineAbilitiesBySkill(skillId);
if (!skillLineAbilities)
return;
for (SkillLineAbilityEntry const* ability : *skillLineAbilities)
{
if (!sSpellMgr->GetSpellInfo(ability->Spell))
continue;
if (ability->AcquireMethod != SKILL_LINE_ABILITY_LEARNED_ON_SKILL_VALUE && ability->AcquireMethod != SKILL_LINE_ABILITY_LEARNED_ON_SKILL_LEARN)
continue;
// Check race if set
if (ability->RaceMask && !(ability->RaceMask & raceMask))
continue;
// Check class if set
if (ability->ClassMask && !(ability->ClassMask & classMask))
continue;
// need unlearn spell
if (skillValue < ability->MinSkillLineRank && ability->AcquireMethod == SKILL_LINE_ABILITY_LEARNED_ON_SKILL_VALUE)
RemoveSpell(ability->Spell);
// need learn
else if (!IsInWorld())
AddSpell(ability->Spell, true, true, true, false, false, ability->SkillLine);
else
LearnSpell(ability->Spell, true, ability->SkillLine);
}
}
void Player::SendAurasForTarget(Unit* target, bool force /*= false*/) const
{
if (!target || (!force && target->GetVisibleAuras().empty())) // speedup things
return;
WorldPacket data(SMSG_AURA_UPDATE_ALL);
data << target->GetPackGUID();
Unit::VisibleAuraMap const& visibleAuras = target->GetVisibleAuras();
for (Unit::VisibleAuraMap::const_iterator itr = visibleAuras.begin(); itr != visibleAuras.end(); ++itr)
{
AuraApplication * auraApp = itr->second;
auraApp->BuildUpdatePacket(data, false);
}
SendDirectMessage(&data);
}
void Player::SetDailyQuestStatus(uint32 quest_id)
{
if (Quest const* qQuest = sObjectMgr->GetQuestTemplate(quest_id))
{
if (!qQuest->IsDFQuest())
{
for (uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
{
if (!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
{
SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx, quest_id);
m_lastDailyQuestTime = GameTime::GetGameTime(); // last daily quest time
m_DailyQuestChanged = true;
break;
}
}
} else
{
m_DFQuests.insert(quest_id);
m_lastDailyQuestTime = GameTime::GetGameTime();
m_DailyQuestChanged = true;
}
}
}
bool Player::IsDailyQuestDone(uint32 quest_id)
{
bool found = false;
if (sObjectMgr->GetQuestTemplate(quest_id))
{
for (uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
{
if (GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1 + quest_daily_idx) == quest_id)
{
found = true;
break;
}
}
}
return found;
}
void Player::SetWeeklyQuestStatus(uint32 quest_id)
{
m_weeklyquests.insert(quest_id);
m_WeeklyQuestChanged = true;
}
void Player::SetSeasonalQuestStatus(uint32 quest_id)
{
Quest const* quest = sObjectMgr->GetQuestTemplate(quest_id);
if (!quest)
return;
m_seasonalquests[quest->GetEventIdForQuest()][quest_id] = GameTime::GetGameTime();
m_SeasonalQuestChanged = true;
}
void Player::SetMonthlyQuestStatus(uint32 quest_id)
{
m_monthlyquests.insert(quest_id);
m_MonthlyQuestChanged = true;
}
void Player::ResetDailyQuestStatus()
{
for (uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx, 0);
m_DFQuests.clear(); // Dungeon Finder Quests.
// DB data deleted in caller
m_DailyQuestChanged = false;
m_lastDailyQuestTime = 0;
}
void Player::ResetWeeklyQuestStatus()
{
if (m_weeklyquests.empty())
return;
m_weeklyquests.clear();
// DB data deleted in caller
m_WeeklyQuestChanged = false;
}
void Player::ResetSeasonalQuestStatus(uint16 event_id, time_t eventStartTime)
{
// DB data deleted in caller
m_SeasonalQuestChanged = false;
auto eventItr = m_seasonalquests.find(event_id);
if (eventItr == m_seasonalquests.end())
return;
if (eventItr->second.empty())
return;
for (auto questItr = eventItr->second.begin(); questItr != eventItr->second.end(); )
{
if (questItr->second < eventStartTime)
questItr = eventItr->second.erase(questItr);
else
++questItr;
}
if (eventItr->second.empty())
m_seasonalquests.erase(eventItr);
}
void Player::ResetMonthlyQuestStatus()
{
if (m_monthlyquests.empty())
return;
m_monthlyquests.clear();
// DB data deleted in caller
m_MonthlyQuestChanged = false;
}
Battleground* Player::GetBattleground() const
{
if (GetBattlegroundId() == 0)
return nullptr;
return sBattlegroundMgr->GetBattleground(GetBattlegroundId(), m_bgData.bgTypeID);
}
bool Player::InBattlegroundQueue(bool ignoreArena) const
{
for (uint8 i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
if (m_bgBattlegroundQueueID[i].bgQueueTypeId != BATTLEGROUND_QUEUE_NONE
&& (!ignoreArena || m_bgBattlegroundQueueID[i].bgQueueTypeId.BattlemasterListId != BATTLEGROUND_AA))
return true;
return false;
}
BattlegroundQueueTypeId Player::GetBattlegroundQueueTypeId(uint32 index) const
{
return m_bgBattlegroundQueueID[index].bgQueueTypeId;
}
uint32 Player::GetBattlegroundQueueIndex(BattlegroundQueueTypeId bgQueueTypeId) const
{
for (uint8 i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
if (m_bgBattlegroundQueueID[i].bgQueueTypeId == bgQueueTypeId)
return i;
return PLAYER_MAX_BATTLEGROUND_QUEUES;
}
bool Player::IsInvitedForBattlegroundQueueType(BattlegroundQueueTypeId bgQueueTypeId) const
{
for (uint8 i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
if (m_bgBattlegroundQueueID[i].bgQueueTypeId == bgQueueTypeId)
return m_bgBattlegroundQueueID[i].invitedToInstance != 0;
return false;
}
bool Player::InBattlegroundQueueForBattlegroundQueueType(BattlegroundQueueTypeId bgQueueTypeId) const
{
return GetBattlegroundQueueIndex(bgQueueTypeId) < PLAYER_MAX_BATTLEGROUND_QUEUES;
}
void Player::SetBattlegroundId(uint32 val, BattlegroundTypeId bgTypeId)
{
m_bgData.bgInstanceID = val;
m_bgData.bgTypeID = bgTypeId;
}
uint32 Player::AddBattlegroundQueueId(BattlegroundQueueTypeId val)
{
for (uint8 i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
{
if (m_bgBattlegroundQueueID[i].bgQueueTypeId == BATTLEGROUND_QUEUE_NONE || m_bgBattlegroundQueueID[i].bgQueueTypeId == val)
{
m_bgBattlegroundQueueID[i].bgQueueTypeId = val;
m_bgBattlegroundQueueID[i].invitedToInstance = 0;
return i;
}
}
return PLAYER_MAX_BATTLEGROUND_QUEUES;
}
bool Player::HasFreeBattlegroundQueueId() const
{
for (uint8 i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
if (m_bgBattlegroundQueueID[i].bgQueueTypeId == BATTLEGROUND_QUEUE_NONE)
return true;
return false;
}
void Player::RemoveBattlegroundQueueId(BattlegroundQueueTypeId val)
{
for (uint8 i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
{
if (m_bgBattlegroundQueueID[i].bgQueueTypeId == val)
{
m_bgBattlegroundQueueID[i].bgQueueTypeId = BATTLEGROUND_QUEUE_NONE;
m_bgBattlegroundQueueID[i].invitedToInstance = 0;
return;
}
}
}
void Player::SetInviteForBattlegroundQueueType(BattlegroundQueueTypeId bgQueueTypeId, uint32 instanceId)
{
for (uint8 i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
if (m_bgBattlegroundQueueID[i].bgQueueTypeId == bgQueueTypeId)
m_bgBattlegroundQueueID[i].invitedToInstance = instanceId;
}
bool Player::IsInvitedForBattlegroundInstance(uint32 instanceId) const
{
for (uint8 i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
if (m_bgBattlegroundQueueID[i].invitedToInstance == instanceId)
return true;
return false;
}
bool Player::InArena() const
{
Battleground* bg = GetBattleground();
if (!bg || !bg->isArena())
return false;
return true;
}
bool Player::GetBGAccessByLevel(BattlegroundTypeId bgTypeId) const
{
// get a template bg instead of running one
Battleground* bg = sBattlegroundMgr->GetBattlegroundTemplate(bgTypeId);
if (!bg)
return false;
// limit check leel to dbc compatible level range
uint32 level = GetLevel();
if (level > DEFAULT_MAX_LEVEL)
level = DEFAULT_MAX_LEVEL;
if (level < bg->GetMinLevel() || level > bg->GetMaxLevel())
return false;
return true;
}
float Player::GetReputationPriceDiscount(Creature const* creature) const
{
return GetReputationPriceDiscount(creature->GetFactionTemplateEntry());
}
float Player::GetReputationPriceDiscount(FactionTemplateEntry const* factionTemplate) const
{
if (!factionTemplate || !factionTemplate->Faction)
return 1.0f;
ReputationRank rank = GetReputationRank(factionTemplate->Faction);
if (rank <= REP_NEUTRAL)
return 1.0f;
return 1.0f - 0.05f* (rank - REP_NEUTRAL);
}
Player* Player::GetTrader() const
{
return m_trade ? m_trade->GetTrader() : nullptr;
}
bool Player::IsSpellFitByClassAndRace(uint32 spell_id) const
{
uint32 racemask = GetRaceMask();
uint32 classmask = GetClassMask();
SkillLineAbilityMapBounds bounds = sSpellMgr->GetSkillLineAbilityMapBounds(spell_id);
if (bounds.first == bounds.second)
return true;
for (SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
{
// skip wrong race skills
if (_spell_idx->second->RaceMask && (_spell_idx->second->RaceMask & racemask) == 0)
continue;
// skip wrong class skills
if (_spell_idx->second->ClassMask && (_spell_idx->second->ClassMask & classmask) == 0)
continue;
// skip wrong class and race skill saved in SkillRaceClassInfo.dbc
if (!GetSkillRaceClassInfo(_spell_idx->second->SkillLine, GetRace(), GetClass()))
continue;
return true;
}
return false;
}
bool Player::HasQuestForGO(int32 GOId) const
{
for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
{
uint32 questid = GetQuestSlotQuestId(i);
if (questid == 0)
continue;
QuestStatusMap::const_iterator qs_itr = m_QuestStatus.find(questid);
if (qs_itr == m_QuestStatus.end())
continue;
QuestStatusData const& qs = qs_itr->second;
if (qs.Status == QUEST_STATUS_INCOMPLETE)
{
Quest const* qinfo = sObjectMgr->GetQuestTemplate(questid);
if (!qinfo)
continue;
if (GetGroup() && GetGroup()->isRaidGroup() && !qinfo->IsAllowedInRaid(GetMap()->GetDifficulty()))
continue;
for (uint8 j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
{
if (qinfo->RequiredNpcOrGo[j] >= 0) //skip non GO case
continue;
if ((-1)*GOId == qinfo->RequiredNpcOrGo[j] && qs.CreatureOrGOCount[j] < qinfo->RequiredNpcOrGoCount[j])
return true;
}
}
}
return false;
}
void Player::UpdateVisibleGameobjectsOrSpellClicks()
{
if (m_clientGUIDs.empty())
return;
UpdateData udata;
WorldPacket packet;
for (auto itr = m_clientGUIDs.begin(); itr != m_clientGUIDs.end(); ++itr)
{
if (itr->IsGameObject())
{
if (GameObject* obj = ObjectAccessor::GetGameObject(*this, *itr))
if (sObjectMgr->IsGameObjectForQuests(obj->GetEntry()))
obj->BuildValuesUpdateBlockForPlayer(&udata, this);
}
else if (itr->IsCreatureOrVehicle())
{
Creature* obj = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, *itr);
if (!obj)
continue;
// check if this unit requires quest specific flags
if (!obj->HasNpcFlag(UNIT_NPC_FLAG_SPELLCLICK))
continue;
auto clickBounds = sObjectMgr->GetSpellClickInfoMapBounds(obj->GetEntry());
for (auto const& clickPair : clickBounds)
{
if (sConditionMgr->GetConditionsForSpellClickEvent(obj->GetEntry(), clickPair.second.spellId))
{
obj->BuildValuesUpdateBlockForPlayer(&udata, this);
break;
}
}
}
}
udata.BuildPacket(&packet);
SendDirectMessage(&packet);
}
bool Player::HasSummonPending() const
{
return m_summon_expire >= GameTime::GetGameTime();
}
void Player::SendSummonRequestFrom(Unit* summoner)
{
if (!summoner)
return;
// Player already has active summon request
if (HasSummonPending())
return;
// Evil Twin (ignore player summon, but hide this for summoner)
if (HasAura(23445))
return;
m_summon_expire = GameTime::GetGameTime() + MAX_PLAYER_SUMMON_DELAY;
m_summon_location.WorldRelocate(*summoner);
WorldPacket data(SMSG_SUMMON_REQUEST, 8 + 4 + 4);
data << summoner->GetGUID(); // summoner guid
data << uint32(summoner->GetZoneId()); // summoner zone
data << uint32(MAX_PLAYER_SUMMON_DELAY*IN_MILLISECONDS); // auto decline after msecs
SendDirectMessage(&data);
}
void Player::SummonIfPossible(bool agree)
{
if (!agree)
{
m_summon_expire = 0;
return;
}
// expire and auto declined
if (m_summon_expire < GameTime::GetGameTime())
return;
// stop taxi flight at summon
FinishTaxiFlight();
// drop flag at summon
// this code can be reached only when GM is summoning player who carries flag, because player should be immune to summoning spells when he carries flag
if (Battleground* bg = GetBattleground())
bg->EventPlayerDroppedFlag(this);
m_summon_expire = 0;
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS, 1);
TeleportTo(m_summon_location);
}
void Player::RemoveItemDurations(Item* item)
{
for (ItemDurationList::iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ++itr)
{
if (*itr == item)
{
m_itemDuration.erase(itr);
break;
}
}
}
void Player::AddItemDurations(Item* item)
{
if (item->GetUInt32Value(ITEM_FIELD_DURATION))
{
m_itemDuration.push_back(item);
item->SendTimeUpdate(this);
}
}
void Player::AutoUnequipOffhandIfNeed(bool force /*= false*/)
{
Item* offItem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
if (!offItem)
return;
ItemTemplate const* offhandTemplate = offItem->GetTemplate();
// unequip offhand weapon if player doesn't have dual wield anymore
if (!CanDualWield() && (offhandTemplate->InventoryType == INVTYPE_WEAPONOFFHAND || offhandTemplate->InventoryType == INVTYPE_WEAPON))
force = true;
// need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
if (!force)
{
Item* mainItem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
if ((!mainItem || mainItem->GetTemplate()->InventoryType != INVTYPE_2HWEAPON)
&& offhandTemplate->InventoryType != INVTYPE_2HWEAPON)
return;
if ((!mainItem || CanTitanGrip(mainItem)) && CanTitanGrip(offItem))
return;
}
ItemPosCountVec off_dest;
if (CanStoreItem(NULL_BAG, NULL_SLOT, off_dest, offItem, false) == EQUIP_ERR_OK)
{
RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
StoreItem(off_dest, offItem, true);
}
else
{
MoveItemFromInventory(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction();
offItem->DeleteFromInventoryDB(trans); // deletes item from character's inventory
offItem->SaveToDB(trans); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
std::string subject = GetSession()->GetTrinityString(LANG_NOT_EQUIPPED_ITEM);
MailDraft(subject, "There were problems with equipping one or several items").AddItem(offItem).SendMailTo(trans, this, MailSender(this, MAIL_STATIONERY_GM), MAIL_CHECK_MASK_COPIED);
CharacterDatabase.CommitTransaction(trans);
}
}
OutdoorPvP* Player::GetOutdoorPvP() const
{
return sOutdoorPvPMgr->GetOutdoorPvPToZoneId(GetZoneId());
}
bool Player::HasItemFitToSpellRequirements(SpellInfo const* spellInfo, Item const* ignoreItem) const
{
if (spellInfo->EquippedItemClass < 0)
return true;
// scan other equipped items for same requirements (mostly 2 daggers/etc)
// for optimize check 2 used cases only
switch (spellInfo->EquippedItemClass)
{
case ITEM_CLASS_WEAPON:
{
for (uint8 i = EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
if (Item* item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, i))
if (item != ignoreItem && item->IsFitToSpellRequirements(spellInfo))
return true;
break;
}
case ITEM_CLASS_ARMOR:
{
// most used check: shield only
if (spellInfo->EquippedItemSubClassMask & ((1 << ITEM_SUBCLASS_ARMOR_BUCKLER) | (1 << ITEM_SUBCLASS_ARMOR_SHIELD)))
{
if (Item* item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
if (item != ignoreItem && item->IsFitToSpellRequirements(spellInfo))
return true;
// special check to filter things like Shield Wall, the aura is not permanent and must stay even without required item
if (!spellInfo->IsPassive())
for (SpellEffectInfo const& spellEffectInfo : spellInfo->GetEffects())
if (spellEffectInfo.IsAura())
return true;
}
// tabard not have dependent spells
for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_MAINHAND; ++i)
if (Item* item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, i))
if (item != ignoreItem && item->IsFitToSpellRequirements(spellInfo))
return true;
// ranged slot can have some armor subclasses
if (Item* item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
if (item != ignoreItem && item->IsFitToSpellRequirements(spellInfo))
return true;
break;
}
default:
TC_LOG_ERROR("entities.player", "Player::HasItemFitToSpellRequirements: Not handled spell requirement for item class {}", spellInfo->EquippedItemClass);
break;
}
return false;
}
bool Player::CanNoReagentCast(SpellInfo const* spellInfo) const
{
// don't take reagents for spells with SPELL_ATTR5_NO_REAGENT_WHILE_PREP
if (spellInfo->HasAttribute(SPELL_ATTR5_NO_REAGENT_WHILE_PREP) &&
HasUnitFlag(UNIT_FLAG_PREPARATION))
return true;
// Check no reagent use mask
flag96 noReagentMask;
noReagentMask[0] = GetUInt32Value(PLAYER_NO_REAGENT_COST_1);
noReagentMask[1] = GetUInt32Value(PLAYER_NO_REAGENT_COST_1+1);
noReagentMask[2] = GetUInt32Value(PLAYER_NO_REAGENT_COST_1+2);
if (spellInfo->SpellFamilyFlags & noReagentMask)
return true;
return false;
}
void Player::RemoveItemDependentAurasAndCasts(Item* pItem)
{
for (AuraMap::iterator itr = m_ownedAuras.begin(); itr != m_ownedAuras.end();)
{
Aura* aura = itr->second;
// skip not self applied auras
SpellInfo const* spellInfo = aura->GetSpellInfo();
if (aura->GetCasterGUID() != GetGUID())
{
++itr;
continue;
}
// skip if not item dependent or have alternative item
if (HasItemFitToSpellRequirements(spellInfo, pItem))
{
++itr;
continue;
}
// no alt item, remove aura, restart check
RemoveOwnedAura(itr);
}
// currently cast spells can be dependent from item
for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
if (Spell* spell = GetCurrentSpell(CurrentSpellTypes(i)))
if (spell->getState() != SPELL_STATE_DELAYED && !HasItemFitToSpellRequirements(spell->m_spellInfo, pItem))
InterruptSpell(CurrentSpellTypes(i));
}
uint32 Player::GetResurrectionSpellId()
{
// search priceless resurrection possibilities
uint32 prio = 0;
uint32 spell_id = 0;
AuraEffectList const& dummyAuras = GetAuraEffectsByType(SPELL_AURA_DUMMY);
for (AuraEffectList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
{
// Soulstone Resurrection // prio: 3 (max, non death persistent)
if (prio < 2 && (*itr)->GetSpellInfo()->SpellVisual[0] == 99 && (*itr)->GetSpellInfo()->SpellIconID == 92)
{
switch ((*itr)->GetId())
{
case 20707: spell_id = 3026; break; // rank 1
case 20762: spell_id = 20758; break; // rank 2
case 20763: spell_id = 20759; break; // rank 3
case 20764: spell_id = 20760; break; // rank 4
case 20765: spell_id = 20761; break; // rank 5
case 27239: spell_id = 27240; break; // rank 6
case 47883: spell_id = 47882; break; // rank 7
default:
TC_LOG_ERROR("entities.player", "Unhandled spell {}: S.Resurrection", (*itr)->GetId());
continue;
}
prio = 3;
}
// Twisting Nether // prio: 2 (max)
else if ((*itr)->GetId() == 23701 && roll_chance_i(10))
{
prio = 2;
spell_id = 23700;
}
}
// Reincarnation (passive spell) // prio: 1 // Glyph of Renewed Life
if (prio < 1 && HasSpell(20608) && !GetSpellHistory()->HasCooldown(21169) && (HasAura(58059) || HasItemCount(17030)))
spell_id = 21169;
return spell_id;
}
// Used in triggers for check "Only to targets that grant experience or honor" req
bool Player::isHonorOrXPTarget(Unit const* victim) const
{
uint8 v_level = victim->GetLevel();
uint8 k_grey = Trinity::XP::GetGrayLevel(GetLevel());
// Victim level less gray level
if (v_level <= k_grey && !sWorld->getIntConfig(CONFIG_MIN_CREATURE_SCALED_XP_RATIO))
return false;
if (Creature const* creature = victim->ToCreature())
{
if (creature->IsCritter() || creature->IsTotem())
return false;
}
return true;
}
bool Player::GetsRecruitAFriendBonus(bool forXP)
{
bool recruitAFriend = false;
if (GetLevel() <= sWorld->getIntConfig(CONFIG_MAX_RECRUIT_A_FRIEND_BONUS_PLAYER_LEVEL) || !forXP)
{
if (Group* group = GetGroup())
{
for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next())
{
Player* player = itr->GetSource();
if (!player)
continue;
if (!player->IsAtRecruitAFriendDistance(this))
continue; // member (alive or dead) or his corpse at req. distance
if (forXP)
{
// level must be allowed to get RaF bonus
if (player->GetLevel() > sWorld->getIntConfig(CONFIG_MAX_RECRUIT_A_FRIEND_BONUS_PLAYER_LEVEL))
continue;
// level difference must be small enough to get RaF bonus, UNLESS we are lower level
if (player->GetLevel() < GetLevel())
if (uint8(GetLevel() - player->GetLevel()) > sWorld->getIntConfig(CONFIG_MAX_RECRUIT_A_FRIEND_BONUS_PLAYER_LEVEL_DIFFERENCE))
continue;
}
bool ARecruitedB = (player->GetSession()->GetRecruiterId() == GetSession()->GetAccountId());
bool BRecruitedA = (GetSession()->GetRecruiterId() == player->GetSession()->GetAccountId());
if (ARecruitedB || BRecruitedA)
{
recruitAFriend = true;
break;
}
}
}
}
return recruitAFriend;
}
void Player::RewardPlayerAndGroupAtKill(Unit* victim, bool isBattleGround)
{
KillRewarder(this, victim, isBattleGround).Reward();
}
void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource)
{
if (!pRewardSource)
return;
ObjectGuid creature_guid = (pRewardSource->GetTypeId() == TYPEID_UNIT) ? pRewardSource->GetGUID() : ObjectGuid::Empty;
// prepare data for near group iteration
if (Group* group = GetGroup())
{
for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next())
{
Player* player = itr->GetSource();
if (!player)
continue;
if (!player->IsAtGroupRewardDistance(pRewardSource))
continue; // member (alive or dead) or his corpse at req. distance
// quest objectives updated only for alive group member or dead but with not released body
if (player->IsAlive()|| !player->GetCorpse())
player->KilledMonsterCredit(creature_id, creature_guid);
}
}
else // if (!group)
KilledMonsterCredit(creature_id, creature_guid);
}
bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
{
if (!pRewardSource || !IsInMap(pRewardSource))
return false;
WorldObject const* player = GetCorpse();
if (!player || IsAlive())
player = this;
if (pRewardSource->GetMap()->IsDungeon())
return true;
return pRewardSource->GetDistance(player) <= sWorld->getFloatConfig(CONFIG_GROUP_XP_DISTANCE);
}
bool Player::IsAtRecruitAFriendDistance(WorldObject const* pOther) const
{
if (!pOther || !IsInMap(pOther))
return false;
WorldObject const* player = GetCorpse();
if (!player || IsAlive())
player = this;
return pOther->GetDistance(player) <= sWorld->getFloatConfig(CONFIG_MAX_RECRUIT_A_FRIEND_DISTANCE);
}
uint32 Player::GetBaseWeaponSkillValue(WeaponAttackType attType) const
{
Item* item = GetWeaponForAttack(attType, true);
// unarmed only with base attack
if (attType != BASE_ATTACK && !item)
return 0;
// weapon skill or (unarmed for base attack)
uint32 skill = item ? item->GetSkill() : uint32(SKILL_UNARMED);
return GetBaseSkillValue(skill);
}
void Player::ResurrectUsingRequestData()
{
RemoveGhoul();
if (uint32 aura = _resurrectionData->Aura)
{
CastSpell(this, aura, _resurrectionData->GUID);
return;
}
// Teleport before resurrecting by player, otherwise the player might get attacked from creatures near his corpse
TeleportTo(_resurrectionData->Location);
if (IsBeingTeleported())
{
ScheduleDelayedOperation(DELAYED_RESURRECT_PLAYER);
return;
}
ResurrectUsingRequestDataImpl();
}
void Player::ResurrectUsingRequestDataImpl()
{
// save health and mana before resurrecting, _resurrectionData can be erased
uint32 resurrectHealth = _resurrectionData->Health;
uint32 resurrectMana = _resurrectionData->Mana;
ResurrectPlayer(0.0f, false);
SetHealth(resurrectHealth);
SetPower(POWER_MANA, resurrectMana);
SetPower(POWER_RAGE, 0);
SetFullPower(POWER_ENERGY);
SpawnCorpseBones();
}
void Player::SetClientControl(Unit* target, bool allowMove)
{
// a player can never client control nothing
ASSERT(target);
// don't allow possession to be overridden
if (target->HasUnitState(UNIT_STATE_CHARMED) && (GetGUID() != target->GetCharmerGUID()))
{
TC_LOG_ERROR("entities.player", "Player '{}' attempt to client control '{}', which is charmed by GUID {}",
GetName(), target->GetName(), target->GetCharmerGUID().ToString());
return;
}
// still affected by some aura that shouldn't allow control, only allow on last such aura to be removed
if (target->HasUnitState(UNIT_STATE_FLEEING | UNIT_STATE_CONFUSED))
allowMove = false;
WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
data << target->GetPackGUID();
data << uint8(allowMove ? 1 : 0);
SendDirectMessage(&data);
WorldObject* viewpoint = GetViewpoint();
if (!viewpoint)
viewpoint = this;
if (target != viewpoint)
{
if (viewpoint != this)
SetViewpoint(viewpoint, false);
if (target != this)
SetViewpoint(target, true);
}
GetGameClient()->SetMovedUnit(target, allowMove);
}
void Player::UpdateZoneDependentAuras(uint32 newZone)
{
// Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
SpellAreaForAreaMapBounds saBounds = sSpellMgr->GetSpellAreaForAreaMapBounds(newZone);
for (SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
if (itr->second->autocast && itr->second->IsFitToRequirements(this, newZone, 0))
if (!HasAura(itr->second->spellId))
CastSpell(this, itr->second->spellId, true);
}
void Player::UpdateAreaDependentAuras(uint32 newArea)
{
// remove auras from spells with area limitations
for (AuraMap::iterator iter = m_ownedAuras.begin(); iter != m_ownedAuras.end();)
{
// use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
if (iter->second->GetSpellInfo()->CheckLocation(GetMapId(), m_zoneUpdateId, newArea, this, false) != SPELL_CAST_OK)
RemoveOwnedAura(iter);
else
++iter;
}
// some auras applied at subzone enter
SpellAreaForAreaMapBounds saBounds = sSpellMgr->GetSpellAreaForAreaMapBounds(newArea);
for (SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
if (itr->second->autocast && itr->second->IsFitToRequirements(this, m_zoneUpdateId, newArea))
if (!HasAura(itr->second->spellId))
CastSpell(this, itr->second->spellId, true);
}
uint32 Player::GetCorpseReclaimDelay(bool pvp) const
{
if (pvp)
{
if (!sWorld->getBoolConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP))
return corpseReclaimDelay[0];
}
else if (!sWorld->getBoolConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE))
return 0;
time_t now = GameTime::GetGameTime();
// 0..2 full period
// should be ceil(x)-1 but not floor(x)
uint64 count = (now < m_deathExpireTime - 1) ? (m_deathExpireTime - 1 - now) / DEATH_EXPIRE_STEP : 0;
return corpseReclaimDelay[count];
}
void Player::UpdateCorpseReclaimDelay()
{
bool pvp = (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) != 0;
if ((pvp && !sWorld->getBoolConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
(!pvp && !sWorld->getBoolConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE)))
return;
time_t now = GameTime::GetGameTime();
if (now < m_deathExpireTime)
{
// full and partly periods 1..3
uint64 count = (m_deathExpireTime - now) / DEATH_EXPIRE_STEP + 1;
if (count < MAX_DEATH_COUNT)
m_deathExpireTime = now+(count + 1) * DEATH_EXPIRE_STEP;
else
m_deathExpireTime = now + MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
}
else
m_deathExpireTime = now + DEATH_EXPIRE_STEP;
}
int32 Player::CalculateCorpseReclaimDelay(bool load) const
{
Corpse* corpse = GetCorpse();
if (load && !corpse)
return -1;
bool pvp = corpse ? corpse->GetType() == CORPSE_RESURRECTABLE_PVP : (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) != 0;
uint32 delay;
if (load)
{
if (corpse->GetGhostTime() > m_deathExpireTime)
return -1;
uint64 count = 0;
if ((pvp && sWorld->getBoolConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
(!pvp && sWorld->getBoolConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE)))
{
count = (m_deathExpireTime - corpse->GetGhostTime()) / DEATH_EXPIRE_STEP;
if (count >= MAX_DEATH_COUNT)
count = MAX_DEATH_COUNT - 1;
}
time_t expected_time = corpse->GetGhostTime() + corpseReclaimDelay[count];
time_t now = GameTime::GetGameTime();
if (now >= expected_time)
return -1;
delay = expected_time - now;
}
else
delay = GetCorpseReclaimDelay(pvp);
return delay * IN_MILLISECONDS;
}
void Player::SendCorpseReclaimDelay(uint32 delay) const
{
WorldPackets::Misc::CorpseReclaimDelay packet;
packet.Remaining = delay;
GetSession()->SendPacket(packet.Write());
}
Player* Player::GetNextRandomRaidMember(float radius)
{
Group* group = GetGroup();
if (!group)
return nullptr;
std::vector<Player*> nearMembers;
nearMembers.reserve(group->GetMembersCount());
for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next())
{
Player* Target = itr->GetSource();
// IsHostileTo check duel and controlled by enemy
if (Target && Target != this && IsWithinDistInMap(Target, radius) &&
!Target->HasInvisibilityAura() && !IsHostileTo(Target))
nearMembers.push_back(Target);
}
if (nearMembers.empty())
return nullptr;
uint32 randTarget = urand(0, nearMembers.size()-1);
return nearMembers[randTarget];
}
PartyResult Player::CanUninviteFromGroup(ObjectGuid guidMember) const
{
Group const* grp = GetGroup();
if (!grp)
return ERR_NOT_IN_GROUP;
if (grp->isLFGGroup())
{
ObjectGuid gguid = grp->GetGUID();
if (!sLFGMgr->GetKicksLeft(gguid))
return ERR_PARTY_LFG_BOOT_LIMIT;
lfg::LfgState state = sLFGMgr->GetState(gguid);
if (sLFGMgr->IsVoteKickActive(gguid))
return ERR_PARTY_LFG_BOOT_IN_PROGRESS;
if (grp->GetMembersCount() <= lfg::LFG_GROUP_KICK_VOTES_NEEDED)
return ERR_PARTY_LFG_BOOT_TOO_FEW_PLAYERS;
if (state == lfg::LFG_STATE_FINISHED_DUNGEON)
return ERR_PARTY_LFG_BOOT_DUNGEON_COMPLETE;
if (grp->isRollLootActive())
return ERR_PARTY_LFG_BOOT_LOOT_ROLLS;
/// @todo Should also be sent when anyone has recently left combat, with an aprox ~5 seconds timer.
for (GroupReference const* itr = grp->GetFirstMember(); itr != nullptr; itr = itr->next())
if (itr->GetSource() && itr->GetSource()->IsInMap(this) && itr->GetSource()->IsInCombat())
return ERR_PARTY_LFG_BOOT_IN_COMBAT;
/* Missing support for these types
return ERR_PARTY_LFG_BOOT_COOLDOWN_S;
return ERR_PARTY_LFG_BOOT_NOT_ELIGIBLE_S;
*/
}
else
{
if (!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
return ERR_NOT_LEADER;
if (InBattleground())
return ERR_INVITE_RESTRICTED;
if (grp->IsLeader(guidMember))
return ERR_NOT_LEADER;
}
return ERR_PARTY_RESULT_OK;
}
bool Player::isUsingLfg() const
{
return sLFGMgr->GetState(GetGUID()) != lfg::LFG_STATE_NONE;
}
bool Player::inRandomLfgDungeon() const
{
if (sLFGMgr->selectedRandomLfgDungeon(GetGUID()))
{
Map const* map = GetMap();
return sLFGMgr->inLfgDungeonMap(GetGUID(), map->GetId(), map->GetDifficulty());
}
return false;
}
void Player::SetBattlegroundOrBattlefieldRaid(Group* group, int8 subgroup)
{
//we must move references from m_group to m_originalGroup
SetOriginalGroup(GetGroup(), GetSubGroup());
m_group.unlink();
m_group.link(group, this);
m_group.setSubGroup((uint8)subgroup);
}
void Player::RemoveFromBattlegroundOrBattlefieldRaid()
{
//remove existing reference
m_group.unlink();
if (Group* group = GetOriginalGroup())
{
m_group.link(group, this);
m_group.setSubGroup(GetOriginalSubGroup());
}
SetOriginalGroup(nullptr);
}
void Player::SetOriginalGroup(Group* group, int8 subgroup)
{
if (group == nullptr)
m_originalGroup.unlink();
else
{
// never use SetOriginalGroup without a subgroup unless you specify NULL for group
ASSERT(subgroup >= 0);
m_originalGroup.link(group, this);
m_originalGroup.setSubGroup((uint8)subgroup);
}
}
void Player::ProcessTerrainStatusUpdate(ZLiquidStatus oldLiquidStatus, Optional<LiquidData> const& newLiquidData)
{
// process liquid auras using generic unit code
Unit::ProcessTerrainStatusUpdate(oldLiquidStatus, newLiquidData);
// player specific logic for mirror timers
if (GetLiquidStatus() && newLiquidData)
{
// Breath bar state (under water in any liquid type)
if (newLiquidData->type_flags & MAP_ALL_LIQUIDS)
{
if (GetLiquidStatus() & LIQUID_MAP_UNDER_WATER)
m_MirrorTimerFlags |= UNDERWATER_INWATER;
else
m_MirrorTimerFlags &= ~UNDERWATER_INWATER;
}
// Fatigue bar state (if not on flight path or transport)
if ((newLiquidData->type_flags & MAP_LIQUID_TYPE_DARK_WATER) && !IsInFlight() && !GetTransport())
m_MirrorTimerFlags |= UNDERWATER_INDARKWATER;
else
m_MirrorTimerFlags &= ~UNDERWATER_INDARKWATER;
// Lava state (any contact)
if (newLiquidData->type_flags & MAP_LIQUID_TYPE_MAGMA)
{
if (GetLiquidStatus() & MAP_LIQUID_STATUS_IN_CONTACT)
m_MirrorTimerFlags |= UNDERWATER_INLAVA;
else
m_MirrorTimerFlags &= ~UNDERWATER_INLAVA;
}
// Slime state (any contact)
if (newLiquidData->type_flags & MAP_LIQUID_TYPE_SLIME)
{
if (GetLiquidStatus() & MAP_LIQUID_STATUS_IN_CONTACT)
m_MirrorTimerFlags |= UNDERWATER_INSLIME;
else
m_MirrorTimerFlags &= ~UNDERWATER_INSLIME;
}
}
else
m_MirrorTimerFlags &= ~(UNDERWATER_INWATER | UNDERWATER_INLAVA | UNDERWATER_INSLIME | UNDERWATER_INDARKWATER);
}
void Player::AtExitCombat()
{
Unit::AtExitCombat();
UpdatePotionCooldown();
if (GetClass() == CLASS_DEATH_KNIGHT)
for (uint8 i = 0; i < MAX_RUNES; ++i)
{
SetRuneTimer(i, 0xFFFFFFFF);
SetLastRuneGraceTimer(i, 0);
}
}
void Player::SetCanParry(bool value)
{
if (m_canParry == value)
return;
m_canParry = value;
UpdateParryPercentage();
}
void Player::SetCanBlock(bool value)
{
if (m_canBlock == value)
return;
m_canBlock = value;
UpdateBlockPercentage();
}
bool ItemPosCount::isContainedIn(std::vector<ItemPosCount> const& vec) const
{
for (ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end(); ++itr)
if (itr->pos == pos)
return true;
return false;
}
void Player::StopCastingBindSight() const
{
if (Unit* target = Object::ToUnit(GetViewpoint()))
{
target->RemoveAurasByType(SPELL_AURA_BIND_SIGHT, GetGUID());
target->RemoveAurasByType(SPELL_AURA_MOD_POSSESS, GetGUID());
target->RemoveAurasByType(SPELL_AURA_MOD_POSSESS_PET, GetGUID());
}
}
void Player::SetViewpoint(WorldObject* target, bool apply)
{
if (apply)
{
TC_LOG_DEBUG("maps", "Player::CreateViewpoint: Player '{}' ({}) creates seer (Entry: {}, TypeId: {}).",
GetName(), GetGUID().ToString(), target->GetEntry(), target->GetTypeId());
if (!AddGuidValue(PLAYER_FARSIGHT, target->GetGUID()))
{
TC_LOG_FATAL("entities.player", "Player::CreateViewpoint: Player '{}' ({}) cannot add new viewpoint!", GetName(), GetGUID().ToString());
return;
}
// farsight dynobj or puppet may be very far away
UpdateVisibilityOf(target);
if (Unit* targetUnit = target->ToUnit(); targetUnit && targetUnit != GetVehicleBase())
targetUnit->AddPlayerToVision(this);
SetSeer(target);
}
else
{
TC_LOG_DEBUG("maps", "Player::CreateViewpoint: Player {} removed seer", GetName());
if (!RemoveGuidValue(PLAYER_FARSIGHT, target->GetGUID()))
{
TC_LOG_FATAL("entities.player", "Player::CreateViewpoint: Player '{}' ({}) cannot remove current viewpoint!", GetName(), GetGUID().ToString());
return;
}
if (Unit* targetUnit = target->ToUnit(); targetUnit && targetUnit != GetVehicleBase())
targetUnit->RemovePlayerFromVision(this);
//must immediately set seer back otherwise may crash
SetSeer(this);
//WorldPacket data(SMSG_CLEAR_FAR_SIGHT_IMMEDIATE, 0);
//SendDirectMessage(&data);
}
// HACK: Make sure update for PLAYER_FARSIGHT is received before SMSG_PET_SPELLS to properly hide "Release spirit" dialog
if (target->GetTypeId() == TYPEID_UNIT && static_cast<Unit*>(target)->HasUnitTypeMask(UNIT_MASK_MINION) && static_cast<Minion*>(target)->IsRisenAlly())
{
if (apply)
{
UpdateDataMapType update_players;
BuildUpdate(update_players);
WorldPacket packet;
for (UpdateDataMapType::iterator iter = update_players.begin(); iter != update_players.end(); ++iter)
{
iter->second.BuildPacket(&packet);
iter->first->SendDirectMessage(&packet);
packet.clear();
}
}
else
{
m_deathTimer = 6 * MINUTE * IN_MILLISECONDS;
// Reset "Release spirit" timer clientside
WorldPacket data(SMSG_FORCED_DEATH_UPDATE);
SendDirectMessage(&data);
}
}
}
WorldObject* Player::GetViewpoint() const
{
ObjectGuid guid = GetGuidValue(PLAYER_FARSIGHT);
if (!guid.IsEmpty())
return static_cast<WorldObject*>(ObjectAccessor::GetObjectByTypeMask(*this, guid, TYPEMASK_SEER));
return nullptr;
}
bool Player::CanUseBattlegroundObject(GameObject* gameobject) const
{
// It is possible to call this method with a null pointer, only skipping faction check.
if (gameobject)
{
FactionTemplateEntry const* playerFaction = GetFactionTemplateEntry();
FactionTemplateEntry const* faction = sFactionTemplateStore.LookupEntry(gameobject->GetFaction());
if (playerFaction && faction && !playerFaction->IsFriendlyTo(*faction))
return false;
}
// BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
// Note: Mount, stealth and invisibility will be removed when used
return (!isTotalImmune() && // Damage immune
!HasAura(SPELL_RECENTLY_DROPPED_FLAG) && // Still has recently held flag debuff
IsAlive()); // Alive
}
bool Player::CanCaptureTowerPoint() const
{
return (!HasStealthAura() && // not stealthed
!HasInvisibilityAura() && // not invisible
IsAlive()); // live player
}
uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair, BarberShopStyleEntry const* newSkin) const
{
uint8 level = GetLevel();
if (level > GT_MAX_LEVEL)
level = GT_MAX_LEVEL; // max level in this dbc
uint8 hairstyle = GetHairStyleId();
uint8 haircolor = GetHairColorId();
uint8 facialhair = GetFacialStyle();
uint8 skincolor = GetSkinId();
if ((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair) && (!newSkin || (newSkin->Data == skincolor)))
return 0;
GtBarberShopCostBaseEntry const* bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
if (!bsc) // shouldn't happen
return 0xFFFFFFFF;
float cost = 0;
if (hairstyle != newhairstyle)
cost += bsc->Data; // full price
if ((haircolor != newhaircolor) && (hairstyle == newhairstyle))
cost += bsc->Data * 0.5f; // +1/2 of price
if (facialhair != newfacialhair)
cost += bsc->Data * 0.75f; // +3/4 of price
if (newSkin && skincolor != newSkin->Data)
cost += bsc->Data * 0.75f; // +5/6 of price
return uint32(cost);
}
void Player::InitGlyphsForLevel()
{
for (uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
if (GlyphSlotEntry const* gs = sGlyphSlotStore.LookupEntry(i))
if (gs->Tooltip)
SetGlyphSlot(gs->Tooltip - 1, gs->ID);
uint8 level = GetLevel();
uint32 value = 0;
// 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
if (level >= 15)
value |= (0x01 | 0x02);
if (level >= 30)
value |= 0x08;
if (level >= 50)
value |= 0x04;
if (level >= 70)
value |= 0x10;
if (level >= 80)
value |= 0x20;
SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
}
void Player::SetGlyph(uint8 slot, uint32 glyph)
{
_talentMgr->SpecInfo[GetActiveSpec()].Glyphs[slot] = glyph;
SetUInt32Value(PLAYER_FIELD_GLYPHS_1 + slot, glyph);
}
bool Player::isTotalImmune() const
{
AuraEffectList const& immune = GetAuraEffectsByType(SPELL_AURA_SCHOOL_IMMUNITY);
uint32 immuneMask = 0;
for (AuraEffectList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
{
immuneMask |= (*itr)->GetMiscValue();
if (immuneMask & SPELL_SCHOOL_MASK_ALL) // total immunity
return true;
}
return false;
}
bool Player::HasTitle(uint32 bitIndex) const
{
if (bitIndex > MAX_TITLE_INDEX)
return false;
uint32 fieldIndexOffset = bitIndex / 32;
uint32 flag = 1 << (bitIndex % 32);
return HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
}
bool Player::HasTitle(CharTitlesEntry const* title) const
{
return HasTitle(title->MaskID);
}
void Player::SetTitle(CharTitlesEntry const* title, bool lost)
{
uint32 fieldIndexOffset = title->MaskID / 32;
uint32 flag = 1 << (title->MaskID % 32);
if (lost)
{
if (!HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
return;
RemoveFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
}
else
{
if (HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
return;
SetFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
}
WorldPacket data(SMSG_TITLE_EARNED, 4 + 4);
data << uint32(title->MaskID);
data << uint32(lost ? 0 : 1); // 1 - earned, 0 - lost
SendDirectMessage(&data);
}
uint32 Player::GetRuneTypeBaseCooldown(RuneType runeType) const
{
float cooldown = RUNE_BASE_COOLDOWN;
AuraEffectList const& regenAura = GetAuraEffectsByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
for (AuraEffectList::const_iterator i = regenAura.begin();i != regenAura.end(); ++i)
if ((*i)->GetMiscValue() == POWER_RUNE && (*i)->GetMiscValueB() == runeType)
cooldown *= 1.0f - (*i)->GetAmount() / 100.0f;
return cooldown;
}
void Player::SetRuneCooldown(uint8 index, uint32 cooldown, bool casted /*= false*/)
{
uint32 gracePeriod = GetRuneTimer(index);
if (casted && IsInCombat())
{
if (gracePeriod < 0xFFFFFFFF && cooldown > 0)
{
uint32 lessCd = std::min(uint32(2500), gracePeriod);
cooldown = (cooldown > lessCd) ? (cooldown - lessCd) : 0;
SetLastRuneGraceTimer(index, lessCd);
}
SetRuneTimer(index, 0);
}
m_runes->runes[index].Cooldown = cooldown;
m_runes->SetRuneState(index, (cooldown == 0) ? true : false);
ResyncRunes();
}
void Player::SetRuneConvertAura(uint8 index, AuraEffect const* aura)
{
m_runes->runes[index].ConvertAuras.insert(aura);
}
void Player::RemoveRuneConvertAura(uint8 index, AuraEffect const* aura)
{
m_runes->runes[index].ConvertAuras.erase(aura);
}
void Player::AddRuneByAuraEffect(uint8 index, RuneType newType, AuraEffect const* aura)
{
SetRuneConvertAura(index, aura);
ConvertRune(index, newType);
}
void Player::RemoveRunesByAuraEffect(AuraEffect const* aura)
{
for (uint8 itr = 0; itr < MAX_RUNES; ++itr)
{
RemoveRuneConvertAura(itr, aura);
if (m_runes->runes[itr].ConvertAuras.empty())
ConvertRune(itr, GetBaseRune(itr));
}
}
void Player::RestoreBaseRune(uint8 index)
{
std::vector<AuraEffect const*> removeList;
std::unordered_set<AuraEffect const*>& auras = m_runes->runes[index].ConvertAuras;
auto criteria = [&removeList](AuraEffect const* storedAura) -> bool
{
// AuraEffect already gone
if (!storedAura)
return true;
if (storedAura->GetSpellInfo()->HasAttribute(SPELL_ATTR0_PASSIVE))
{
// Don't drop passive talents providing rune conversion
if (storedAura->GetAuraType() == SPELL_AURA_CONVERT_RUNE)
removeList.push_back(storedAura);
return true;
}
// If rune was converted by a non-passive aura that is still active we should keep it converted
return false;
};
Trinity::Containers::EraseIf(auras, criteria);
if (!auras.empty())
return;
ConvertRune(index, GetBaseRune(index));
if (removeList.empty())
return;
// Filter auras set to be removed if they are converting any other rune index
for (AuraEffect const* storedAura : removeList)
{
uint8 itr = 0;
for (; itr < MAX_RUNES; ++itr)
{
if (m_runes->runes[itr].ConvertAuras.find(storedAura) != m_runes->runes[itr].ConvertAuras.end())
break;
}
if (itr == MAX_RUNES)
storedAura->GetBase()->Remove();
}
}
void Player::ConvertRune(uint8 index, RuneType newType)
{
SetCurrentRune(index, newType);
WorldPacket data(SMSG_CONVERT_RUNE, 2);
data << uint8(index);
data << uint8(newType);
SendDirectMessage(&data);
}
void Player::ResyncRunes() const
{
if (GetClass() != CLASS_DEATH_KNIGHT)
return;
WorldPackets::Spells::ResyncRunes packet;
packet.Count = MAX_RUNES;
for (uint32 itr = 0; itr < MAX_RUNES; ++itr)
{
WorldPackets::Spells::ResyncRune resyncRune;
resyncRune.RuneType = GetCurrentRune(itr);
resyncRune.Cooldown = uint8(255) - uint8(GetRuneCooldown(itr) * uint32(255) / uint32(RUNE_BASE_COOLDOWN)); // cooldown time (0-255)
packet.Runes.emplace_back(resyncRune);
}
SendDirectMessage(packet.Write());
}
void Player::AddRunePower(uint8 index) const
{
WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
data << uint32(1 << index); // mask (0x00-0x3F probably)
SendDirectMessage(&data);
}
static RuneType runeSlotTypes[MAX_RUNES] =
{
/*0*/ RUNE_BLOOD,
/*1*/ RUNE_BLOOD,
/*2*/ RUNE_UNHOLY,
/*3*/ RUNE_UNHOLY,
/*4*/ RUNE_FROST,
/*5*/ RUNE_FROST
};
void Player::InitRunes()
{
if (GetClass() != CLASS_DEATH_KNIGHT)
return;
m_runes = new Runes;
m_runes->runeState = 0;
m_runes->lastUsedRune = RUNE_BLOOD;
for (uint8 i = 0; i < MAX_RUNES; ++i)
{
SetBaseRune(i, runeSlotTypes[i]); // init base types
SetCurrentRune(i, runeSlotTypes[i]); // init current types
SetRuneCooldown(i, 0); // reset cooldowns
SetRuneTimer(i, 0xFFFFFFFF); // Reset rune flags
SetLastRuneGraceTimer(i, 0);
SetRuneConvertAura(i, nullptr);
m_runes->SetRuneState(i);
}
for (uint8 i = 0; i < NUM_RUNE_TYPES; ++i)
SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);
}
bool Player::IsBaseRuneSlotsOnCooldown(RuneType runeType) const
{
for (uint8 i = 0; i < MAX_RUNES; ++i)
if (GetBaseRune(i) == runeType && GetRuneCooldown(i) == 0)
return false;
return true;
}
void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast, bool createdByPlayer)
{
Loot loot;
loot.FillLoot (loot_id, store, this, true);
uint32 max_slot = loot.GetMaxSlotInLootFor(this);
for (uint32 i = 0; i < max_slot; ++i)
{
LootItem* lootItem = loot.LootItemInSlot(i, this);
ItemPosCountVec dest;
InventoryResult msg = CanStoreNewItem(bag, slot, dest, lootItem->itemid, lootItem->count);
if (msg != EQUIP_ERR_OK && slot != NULL_SLOT)
msg = CanStoreNewItem(bag, NULL_SLOT, dest, lootItem->itemid, lootItem->count);
if (msg != EQUIP_ERR_OK && bag != NULL_BAG)
msg = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, lootItem->itemid, lootItem->count);
if (msg != EQUIP_ERR_OK)
{
SendEquipError(msg, nullptr, nullptr, lootItem->itemid);
continue;
}
Item* pItem = StoreNewItem(dest, lootItem->itemid, true, lootItem->randomPropertyId);
SendNewItem(pItem, lootItem->count, false, createdByPlayer, broadcast);
}
}
void Player::StoreLootItem(uint8 lootSlot, Loot* loot)
{
NotNormalLootItem* qitem = nullptr;
NotNormalLootItem* ffaitem = nullptr;
NotNormalLootItem* conditem = nullptr;
LootItem* item = loot->LootItemInSlot(lootSlot, this, &qitem, &ffaitem, &conditem);
if (!item || item->is_looted)
{
SendEquipError(EQUIP_ERR_LOOT_GONE, nullptr, nullptr);
return;
}
if (!item->AllowedForPlayer(this))
{
SendLootRelease(GetLootGUID());
return;
}
// questitems use the blocked field for other purposes
if (!qitem && item->is_blocked)
{
SendLootRelease(GetLootGUID());
return;
}
// dont allow protected item to be looted by someone else
if (!item->rollWinnerGUID.IsEmpty() && item->rollWinnerGUID != GetGUID())
{
SendLootRelease(GetLootGUID());
return;
}
ItemPosCountVec dest;
InventoryResult msg = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, item->itemid, item->count);
if (msg == EQUIP_ERR_OK)
{
Item* newitem = StoreNewItem(dest, item->itemid, true, item->randomPropertyId, item->GetAllowedLooters());
if (qitem)
{
qitem->is_looted = true;
//freeforall is 1 if everyone's supposed to get the quest item.
if (item->freeforall || loot->GetPlayerQuestItems().size() == 1)
SendNotifyLootItemRemoved(lootSlot);
else
loot->NotifyQuestItemRemoved(qitem->index);
}
else
{
if (ffaitem)
{
//freeforall case, notify only one player of the removal
ffaitem->is_looted = true;
SendNotifyLootItemRemoved(lootSlot);
}
else
{
//not freeforall, notify everyone
if (conditem)
conditem->is_looted = true;
loot->NotifyItemRemoved(lootSlot);
}
}
//if only one person is supposed to loot the item, then set it to looted
if (!item->freeforall)
item->is_looted = true;
--loot->unlootedCount;
SendNewItem(newitem, uint32(item->count), false, false, true);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM, item->itemid, item->count);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE, loot->loot_type, item->count);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOOT_EPIC_ITEM, item->itemid, item->count);
// LootItem is being removed (looted) from the container, delete it from the DB.
if (loot->containerID > 0)
sLootItemStorage->RemoveStoredLootItemForContainer(loot->containerID, item->itemid, item->count, item->itemIndex);
#ifdef ELUNA
if (Eluna* e = GetEluna())
e->OnLootItem(this, newitem, item->count, this->GetLootGUID());
#endif
}
else
SendEquipError(msg, nullptr, nullptr, item->itemid);
}
uint32 Player::CalculateTalentsPoints() const
{
uint32 baseForLevel = GetLevel() < 10 ? 0 : GetLevel() - 9;
if (GetClass() != CLASS_DEATH_KNIGHT || GetMapId() != 609)
return uint32(baseForLevel * sWorld->getRate(RATE_TALENT));
uint32 talentPointsForLevel = GetLevel() < 56 ? 0 : GetLevel() - 55;
talentPointsForLevel += GetQuestRewardedTalentCount();
if (talentPointsForLevel > baseForLevel)
talentPointsForLevel = baseForLevel;
return uint32(talentPointsForLevel * sWorld->getRate(RATE_TALENT));
}
bool Player::CanFlyInZone(uint32 mapid, uint32 zone, SpellInfo const* bySpell) const
{
// continent checked in SpellInfo::CheckLocation at cast and area update
uint32 v_map = GetVirtualMapForMapAndZone(mapid, zone);
if (v_map == 571 && !bySpell->HasAttribute(SPELL_ATTR7_IGNORE_COLD_WEATHER_FLYING))
if (!HasSpell(54197)) // 54197 = Cold Weather Flying
return false;
return true;
}
void Player::_LoadSkills(PreparedQueryResult result)
{
// 0 1 2
// SetPQuery(PLAYER_LOGIN_QUERY_LOADSKILLS, "SELECT skill, value, max FROM character_skills WHERE guid = '{}'", GUID_LOPART(m_guid));
uint32 count = 0;
std::unordered_map<uint32, uint32> loadedSkillValues;
if (result)
{
do
{
Field* fields = result->Fetch();
uint16 skill = fields[0].GetUInt16();
uint16 value = fields[1].GetUInt16();
uint16 max = fields[2].GetUInt16();
SkillRaceClassInfoEntry const* rcEntry = GetSkillRaceClassInfo(skill, GetRace(), GetClass());
if (!rcEntry)
{
TC_LOG_ERROR("entities.player", "Player::_LoadSkills: Player '{}' ({}, Race: {}, Class: {}) has forbidden skill {} for his race/class combination",
GetName(), GetGUID().ToString(), uint32(GetRace()), uint32(GetClass()), skill);
mSkillStatus.insert(SkillStatusMap::value_type(skill, SkillStatusData(0, SKILL_DELETED)));
continue;
}
// set fixed skill ranges
switch (GetSkillRangeType(rcEntry))
{
case SKILL_RANGE_LANGUAGE: // 300..300
value = max = 300;
break;
case SKILL_RANGE_MONO: // 1..1, grey monolite bar
value = max = 1;
break;
case SKILL_RANGE_LEVEL:
max = GetMaxSkillValueForLevel();
break;
default:
break;
}
if (value == 0)
{
TC_LOG_ERROR("entities.player", "Player::_LoadSkills: Player '{}' ({}) has skill {} with value 0, deleted.",
GetName(), GetGUID().ToString(), skill);
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHARACTER_SKILL);
stmt->setUInt32(0, GetGUID().GetCounter());
stmt->setUInt16(1, skill);
CharacterDatabase.Execute(stmt);
continue;
}
uint16 skillStep = 0;
if (SkillTiersEntry const* skillTier = sSkillTiersStore.LookupEntry(rcEntry->SkillTierID))
{
for (uint32 i = 0; i < MAX_SKILL_STEP; ++i)
{
if (skillTier->Value[skillStep] == max)
{
skillStep = i + 1;
break;
}
}
}
SetSkillLineId(count, skill);
SetSkillStep(count, skillStep);
SetSkillRank(count, value);
SetSkillMaxRank(count, max);
SetSkillTempBonus(count, 0);
SetSkillPermBonus(count, 0);
mSkillStatus.insert(SkillStatusMap::value_type(skill, SkillStatusData(count, SKILL_UNCHANGED)));
loadedSkillValues[skill] = value;
++count;
if (count >= PLAYER_MAX_SKILLS) // client limit
{
TC_LOG_ERROR("entities.player", "Player::_LoadSkills: Player '{}' ({}) has more than {} skills.",
GetName(), GetGUID().ToString(), PLAYER_MAX_SKILLS);
break;
}
}
while (result->NextRow());
}
// Learn skill rewarded spells after all skills have been loaded to prevent learning a skill from them before its loaded with proper value from DB
for (auto& skill : loadedSkillValues)
LearnSkillRewardedSpells(skill.first, skill.second);
if (HasSkill(SKILL_FIST_WEAPONS))
SetSkill(SKILL_FIST_WEAPONS, 0, GetSkillValue(SKILL_UNARMED), GetMaxSkillValueForLevel());
}
uint32 Player::GetPhaseMaskForSpawn() const
{
uint32 phase = PHASEMASK_NORMAL;
if (!IsGameMaster())
phase = GetPhaseMask();
else
{
AuraEffectList const& phases = GetAuraEffectsByType(SPELL_AURA_PHASE);
if (!phases.empty())
phase = phases.front()->GetMiscValue();
}
// some aura phases include 1 normal map in addition to phase itself
if (uint32 n_phase = phase & ~PHASEMASK_NORMAL)
return n_phase;
return PHASEMASK_NORMAL;
}
InventoryResult Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const
{
ItemTemplate const* pProto = pItem->GetTemplate();
// proto based limitations
if (InventoryResult res = CanEquipUniqueItem(pProto, eslot, limit_count))
return res;
// check unique-equipped on gems
for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
{
uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
if (!enchant_id)
continue;
SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if (!enchantEntry)
continue;
ItemTemplate const* pGem = sObjectMgr->GetItemTemplate(enchantEntry->SrcItemID);
if (!pGem)
continue;
// include for check equip another gems with same limit category for not equipped item (and then not counted)
uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;
if (InventoryResult res = CanEquipUniqueItem(pGem, eslot, gem_limit_count))
return res;
}
return EQUIP_ERR_OK;
}
InventoryResult Player::CanEquipUniqueItem(ItemTemplate const* itemProto, uint8 except_slot, uint32 limit_count) const
{
// check unique-equipped on item
if (itemProto->HasFlag(ITEM_FLAG_UNIQUE_EQUIPPABLE))
{
// there is an equip limit on this item
if (HasItemOrGemWithIdEquipped(itemProto->ItemId, 1, except_slot))
return EQUIP_ERR_ITEM_UNIQUE_EQUIPPABLE;
}
// check unique-equipped limit
if (itemProto->ItemLimitCategory)
{
ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory);
if (!limitEntry)
return EQUIP_ERR_NOT_EQUIPPABLE;
// NOTE: limitEntry->mode not checked because if item have have-limit then it applied and to equip case
if (limit_count > limitEntry->Quantity)
return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS;
// there is an equip limit on this item
if (HasItemWithLimitCategoryEquipped(itemProto->ItemLimitCategory, limitEntry->Quantity - limit_count + 1, except_slot))
return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS;
else if (HasGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory, limitEntry->Quantity - limit_count + 1, except_slot))
return EQUIP_ERR_ITEM_MAX_COUNT_EQUIPPED_SOCKETED;
}
return EQUIP_ERR_OK;
}
void Player::SetFallInformation(uint32 time, float z)
{
m_lastFallTime = time;
m_lastFallZ = z;
}
void Player::HandleFall(MovementInfo const& movementInfo)
{
// calculate total z distance of the fall
float z_diff = m_lastFallZ - movementInfo.pos.GetPositionZ();
//TC_LOG_DEBUG("zDiff = {}", z_diff);
//Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
// 14.57 can be calculated by resolving damageperc formula below to 0
if (z_diff >= 14.57f && !isDead() && !IsGameMaster() &&
!HasAuraType(SPELL_AURA_HOVER) && !HasAuraType(SPELL_AURA_FEATHER_FALL) &&
!HasAuraType(SPELL_AURA_FLY) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL))
{
//Safe fall, fall height reduction
int32 safe_fall = GetTotalAuraModifier(SPELL_AURA_SAFE_FALL);
float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f;
if (damageperc > 0)
{
uint32 damage = (uint32)(damageperc * GetMaxHealth()*sWorld->getRate(RATE_DAMAGE_FALL));
if (GetCommandStatus(CHEAT_GOD))
damage = 0;
float height = movementInfo.pos.m_positionZ;
UpdateGroundPositionZ(movementInfo.pos.m_positionX, movementInfo.pos.m_positionY, height);
if (damage > 0)
{
//Prevent fall damage from being more than the player maximum health
if (damage > GetMaxHealth())
damage = GetMaxHealth();
// Gust of Wind
if (HasAura(43621))
damage = GetMaxHealth()/2;
uint32 original_health = GetHealth();
uint32 final_damage = EnvironmentalDamage(DAMAGE_FALL, damage);
// recheck alive, might have died of EnvironmentalDamage, avoid cases when player die in fact like Spirit of Redemption case
if (IsAlive() && final_damage < original_health)
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100));
}
//Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
TC_LOG_DEBUG("entities.player.falldamage", "FALLDAMAGE z={} sz={} pZ={} FallTime={} mZ={} damage={} SF={}\nPlayer debug info:\n{}", movementInfo.pos.GetPositionZ(), height, GetPositionZ(), movementInfo.fallTime, height, damage, safe_fall, GetDebugInfo());
}
}
}
void Player::ResetAchievements()
{
m_achievementMgr->Reset();
}
void Player::SendRespondInspectAchievements(Player* player) const
{
m_achievementMgr->SendRespondInspectAchievements(player);
}
bool Player::HasAchieved(uint32 achievementId) const
{
return m_achievementMgr->HasAchieved(achievementId);
}
void Player::StartTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry, uint32 timeLost/* = 0*/)
{
m_achievementMgr->StartTimedAchievement(type, entry, timeLost);
}
void Player::RemoveTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry)
{
m_achievementMgr->RemoveTimedAchievement(type, entry);
}
void Player::ResetAchievementCriteria(AchievementCriteriaCondition condition, uint32 value, bool evenIfCriteriaComplete /* = false*/)
{
m_achievementMgr->ResetAchievementCriteria(condition, value, evenIfCriteriaComplete);
}
void Player::UpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 /*= 0*/, uint32 miscValue2 /*= 0*/, WorldObject* ref /*= nullptr*/)
{
m_achievementMgr->UpdateAchievementCriteria(type, miscValue1, miscValue2, ref);
}
void Player::CompletedAchievement(AchievementEntry const* entry)
{
m_achievementMgr->CompletedAchievement(entry);
}
bool Player::LearnTalent(uint32 talentId, uint32 talentRank)
{
uint32 CurTalentPoints = GetFreeTalentPoints();
if (CurTalentPoints == 0)
return false;
if (talentRank >= MAX_TALENT_RANK)
return false;
TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
if (!talentInfo)
return false;
TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TabID);
if (!talentTabInfo)
return false;
// prevent learn talent for different class (cheating)
if ((GetClassMask() & talentTabInfo->ClassMask) == 0)
return false;
// find current max talent rank (0~5)
uint8 curtalent_maxrank = 0; // 0 = not learned any rank
for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank)
{
if (talentInfo->SpellRank[rank] && HasSpell(talentInfo->SpellRank[rank]))
{
curtalent_maxrank = (rank + 1);
break;
}
}
// we already have same or higher talent rank learned
if (curtalent_maxrank >= (talentRank + 1))
return false;
// check if we have enough talent points
if (CurTalentPoints < (talentRank - curtalent_maxrank + 1))
return false;
// Check if it requires another talent
if (talentInfo->PrereqTalent > 0)
{
if (TalentEntry const* depTalentInfo = sTalentStore.LookupEntry(talentInfo->PrereqTalent))
{
bool hasEnoughRank = false;
for (uint8 rank = talentInfo->PrereqRank; rank < MAX_TALENT_RANK; rank++)
{
if (depTalentInfo->SpellRank[rank] != 0)
if (HasSpell(depTalentInfo->SpellRank[rank]))
hasEnoughRank = true;
}
if (!hasEnoughRank)
return false;
}
}
// Find out how many points we have in this field
uint32 spentPoints = 0;
uint32 tTab = talentInfo->TabID;
if (talentInfo->TierID > 0)
for (uint32 i = 0; i < sTalentStore.GetNumRows(); i++) // Loop through all talents.
if (TalentEntry const* tmpTalent = sTalentStore.LookupEntry(i)) // Someday, someone needs to revamp the way talents are tracked
if (tmpTalent->TabID == tTab)
for (uint8 rank = 0; rank < MAX_TALENT_RANK; rank++)
if (tmpTalent->SpellRank[rank] != 0)
if (HasSpell(tmpTalent->SpellRank[rank]))
spentPoints += (rank + 1);
// not have required min points spent in talent tree
if (spentPoints < (talentInfo->TierID * MAX_TALENT_RANK))
return false;
// spell not set in talent.dbc
uint32 spellid = talentInfo->SpellRank[talentRank];
if (spellid == 0)
{
TC_LOG_ERROR("entities.player", "Player::LearnTalent: Talent.dbc has no spellInfo for talent: {} (spell id = 0)", talentId);
return false;
}
// already known
if (HasSpell(spellid))
return false;
// learn! (other talent ranks will unlearned at learning)
LearnSpell(spellid, false);
AddTalent(spellid, GetActiveSpec(), true);
TC_LOG_DEBUG("misc", "Player::LearnTalent: TalentID: {} Spell: {} Group: {}\n", talentId, spellid, uint32(GetActiveSpec()));
// update free talent points
SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
#ifdef ELUNA
if (Eluna* e = GetEluna())
e->OnLearnTalents(this, talentId, talentRank, spellid);
#endif
return true;
}
void Player::LearnPetTalent(ObjectGuid petGuid, uint32 talentId, uint32 talentRank)
{
Pet* pet = GetPet();
if (!pet)
return;
if (petGuid != pet->GetGUID())
return;
uint32 CurTalentPoints = pet->GetFreeTalentPoints();
if (CurTalentPoints == 0)
return;
if (talentRank >= MAX_PET_TALENT_RANK)
return;
TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
if (!talentInfo)
return;
TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TabID);
if (!talentTabInfo)
return;
CreatureTemplate const* ci = pet->GetCreatureTemplate();
if (!ci)
return;
CreatureFamilyEntry const* pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
if (!pet_family)
return;
if (pet_family->PetTalentType < 0) // not hunter pet
return;
// prevent learn talent for different family (cheating)
if (!((1 << pet_family->PetTalentType) & talentTabInfo->PetTalentMask))
return;
// find current max talent rank (0~5)
uint8 curtalent_maxrank = 0; // 0 = not learned any rank
for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank)
{
if (talentInfo->SpellRank[rank] && pet->HasSpell(talentInfo->SpellRank[rank]))
{
curtalent_maxrank = (rank + 1);
break;
}
}
// we already have same or higher talent rank learned
if (curtalent_maxrank >= (talentRank + 1))
return;
// check if we have enough talent points
if (CurTalentPoints < (talentRank - curtalent_maxrank + 1))
return;
// Check if it requires another talent
if (talentInfo->PrereqTalent > 0)
{
if (TalentEntry const* depTalentInfo = sTalentStore.LookupEntry(talentInfo->PrereqTalent))
{
bool hasEnoughRank = false;
for (uint8 rank = talentInfo->PrereqRank; rank < MAX_TALENT_RANK; rank++)
{
if (depTalentInfo->SpellRank[rank] != 0)
if (pet->HasSpell(depTalentInfo->SpellRank[rank]))
hasEnoughRank = true;
}
if (!hasEnoughRank)
return;
}
}
// Find out how many points we have in this field
uint32 spentPoints = 0;
uint32 tTab = talentInfo->TabID;
if (talentInfo->TierID > 0)
{
uint32 numRows = sTalentStore.GetNumRows();
for (uint32 i = 0; i < numRows; ++i) // Loop through all talents.
{
// Someday, someone needs to revamp
TalentEntry const* tmpTalent = sTalentStore.LookupEntry(i);
if (tmpTalent) // the way talents are tracked
{
if (tmpTalent->TabID == tTab)
{
for (uint8 rank = 0; rank < MAX_TALENT_RANK; rank++)
{
if (tmpTalent->SpellRank[rank] != 0)
{
if (pet->HasSpell(tmpTalent->SpellRank[rank]))
{
spentPoints += (rank + 1);
}
}
}
}
}
}
}
// not have required min points spent in talent tree
if (spentPoints < (talentInfo->TierID * MAX_PET_TALENT_RANK))
return;
// spell not set in talent.dbc
uint32 spellid = talentInfo->SpellRank[talentRank];
if (spellid == 0)
{
TC_LOG_ERROR("entities.player", "Talent.dbc contains talent: {} Rank: {} spell id = 0", talentId, talentRank);
return;
}
// already known
if (pet->HasSpell(spellid))
return;
// learn! (other talent ranks will unlearned at learning)
pet->learnSpell(spellid);
TC_LOG_DEBUG("entities.player", "PetTalentID: {} Rank: {} Spell: {}\n", talentId, talentRank, spellid);
// update free talent points
pet->SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
}
void Player::AddKnownCurrency(uint32 itemId)
{
if (CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(itemId))
SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES, (1LL << (ctEntry->BitIndex-1)));
}
void Player::UpdateFallInformationIfNeed(MovementInfo const& minfo, uint16 opcode)
{
if (m_lastFallTime >= minfo.fallTime || m_lastFallZ <= minfo.pos.GetPositionZ() || opcode == MSG_MOVE_FALL_LAND)
SetFallInformation(minfo.fallTime, minfo.pos.GetPositionZ());
}
void Player::UnsummonPetTemporaryIfAny()
{
Pet* pet = GetPet();
if (!pet)
return;
if (!m_temporaryUnsummonedPetNumber && pet->isControlled() && !pet->isTemporarySummoned())
{
m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
m_oldpetspell = pet->GetUInt32Value(UNIT_CREATED_BY_SPELL);
}
RemovePet(pet, PET_SAVE_AS_CURRENT);
}
void Player::ResummonPetTemporaryUnSummonedIfAny()
{
if (!m_temporaryUnsummonedPetNumber)
return;
// not resummon in not appropriate state
if (IsPetNeedBeTemporaryUnsummoned())
return;
if (!GetPetGUID().IsEmpty())
return;
Pet* NewPet = new Pet(this);
if (!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
delete NewPet;
m_temporaryUnsummonedPetNumber = 0;
}
bool Player::IsPetNeedBeTemporaryUnsummoned() const
{
return !IsInWorld() || !IsAlive() || IsMounted() /*+in flight*/;
}
bool Player::CanSeeSpellClickOn(Creature const* c) const
{
if (!c->HasNpcFlag(UNIT_NPC_FLAG_SPELLCLICK))
return false;
auto clickBounds = sObjectMgr->GetSpellClickInfoMapBounds(c->GetEntry());
if (clickBounds.begin() == clickBounds.end())
return false;
for (auto const& clickPair : clickBounds)
{
if (!clickPair.second.IsFitToRequirements(this, c))
return false;
if (sConditionMgr->IsObjectMeetingSpellClickConditions(c->GetEntry(), clickPair.second.spellId, const_cast<Player*>(this), const_cast<Creature*>(c)))
return true;
}
return false;
}
void Player::BuildPlayerTalentsInfoData(WorldPacket* data)
{
*data << uint32(GetFreeTalentPoints()); // unspentTalentPoints
*data << uint8(GetSpecsCount()); // talent group count (0, 1 or 2)
*data << uint8(GetActiveSpec()); // talent group index (0 or 1)
if (GetSpecsCount())
{
if (GetSpecsCount() > MAX_TALENT_SPECS)
SetSpecsCount(MAX_TALENT_SPECS);
// loop through all specs (only 1 for now)
for (uint32 specIdx = 0; specIdx < GetSpecsCount(); ++specIdx)
{
uint8 talentIdCount = 0;
size_t pos = data->wpos();
*data << uint8(talentIdCount); // [PH], talentIdCount
// find class talent tabs (all players have 3 talent tabs)
uint32 const* talentTabIds = GetTalentTabPages(GetClass());
for (uint8 i = 0; i < MAX_TALENT_TABS; ++i)
{
uint32 talentTabId = talentTabIds[i];
for (uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
{
TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
if (!talentInfo)
continue;
// skip another tab talents
if (talentInfo->TabID != talentTabId)
continue;
// find max talent rank (0~4)
int8 curtalent_maxrank = -1;
for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank)
{
if (talentInfo->SpellRank[rank] && HasTalent(talentInfo->SpellRank[rank], specIdx))
{
curtalent_maxrank = rank;
break;
}
}
// not learned talent
if (curtalent_maxrank < 0)
continue;
*data << uint32(talentInfo->ID); // Talent.dbc
*data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
++talentIdCount;
}
}
data->put<uint8>(pos, talentIdCount); // put real count
*data << uint8(MAX_GLYPH_SLOT_INDEX); // glyphs count
for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
*data << uint16(GetGlyph(specIdx, i)); // GlyphProperties.dbc
}
}
}
void Player::BuildPetTalentsInfoData(WorldPacket* data)
{
uint32 unspentTalentPoints = 0;
size_t pointsPos = data->wpos();
*data << uint32(unspentTalentPoints); // [PH], unspentTalentPoints
uint8 talentIdCount = 0;
size_t countPos = data->wpos();
*data << uint8(talentIdCount); // [PH], talentIdCount
Pet* pet = GetPet();
if (!pet)
return;
unspentTalentPoints = pet->GetFreeTalentPoints();
data->put<uint32>(pointsPos, unspentTalentPoints); // put real points
CreatureTemplate const* ci = pet->GetCreatureTemplate();
if (!ci)
return;
CreatureFamilyEntry const* pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
if (!pet_family || pet_family->PetTalentType < 0)
return;
for (uint32 talentTabId = 1; talentTabId < sTalentTabStore.GetNumRows(); ++talentTabId)
{
TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentTabId);
if (!talentTabInfo)
continue;
if (!((1 << pet_family->PetTalentType) & talentTabInfo->PetTalentMask))
continue;
for (uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
{
TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
if (!talentInfo)
continue;
// skip another tab talents
if (talentInfo->TabID != talentTabId)
continue;
// find max talent rank (0~4)
int8 curtalent_maxrank = -1;
for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank)
{
if (talentInfo->SpellRank[rank] && pet->HasSpell(talentInfo->SpellRank[rank]))
{
curtalent_maxrank = rank;
break;
}
}
// not learned talent
if (curtalent_maxrank < 0)
continue;
*data << uint32(talentInfo->ID); // Talent.dbc
*data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
++talentIdCount;
}
data->put<uint8>(countPos, talentIdCount); // put real count
break;
}
}
void Player::SendTalentsInfoData(bool pet)
{
WorldPacket data(SMSG_TALENTS_INFO, 50);
data << uint8(pet ? 1 : 0);
if (pet)
BuildPetTalentsInfoData(&data);
else
BuildPlayerTalentsInfoData(&data);
SendDirectMessage(&data);
}
void Player::BuildEnchantmentsInfoData(WorldPacket* data)
{
uint32 slotUsedMask = 0;
size_t slotUsedMaskPos = data->wpos();
*data << uint32(slotUsedMask); // slotUsedMask < 0x80000
for (uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
{
Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
if (!item)
continue;
slotUsedMask |= (1 << i);
*data << uint32(item->GetEntry()); // item entry
uint16 enchantmentMask = 0;
size_t enchantmentMaskPos = data->wpos();
*data << uint16(enchantmentMask); // enchantmentMask < 0x1000
for (uint32 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
{
uint32 enchId = item->GetEnchantmentId(EnchantmentSlot(j));
if (!enchId)
continue;
enchantmentMask |= (1 << j);
*data << uint16(enchId); // enchantmentId?
}
data->put<uint16>(enchantmentMaskPos, enchantmentMask);
*data << int16(item->GetItemRandomPropertyId()); // Random item property id
*data << item->GetGuidValue(ITEM_FIELD_CREATOR).WriteAsPacked(); // item creator
*data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
}
data->put<uint32>(slotUsedMaskPos, slotUsedMask);
}
void Player::SendEquipmentSetList()
{
uint32 count = 0;
WorldPacket data(SMSG_EQUIPMENT_SET_LIST, 1000); // guess size
size_t count_pos = data.wpos();
data << uint32(count); // count placeholder
static ObjectGuid const IgnoredSlot = []
{
ObjectGuid guid;
guid.SetRawValue(1);
return guid;
}();
for (EquipmentSetContainer::value_type const& eqSet : _equipmentSets)
{
if (eqSet.second.State == EQUIPMENT_SET_DELETED)
continue;
data.appendPackGUID(eqSet.first);
data << uint32(eqSet.second.Data.SetID);
data << eqSet.second.Data.SetName;
data << eqSet.second.Data.SetIcon;
for (uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
{
// ignored slots stored in IgnoreMask, client wants "1" as raw GUID, so no HighGuid::Item
if (eqSet.second.Data.IgnoreMask & (1 << i))
data << IgnoredSlot.WriteAsPacked();
else
data << eqSet.second.Data.Pieces[i].WriteAsPacked();
}
++count; // client have limit but it checked at loading and set
}
data.put<uint32>(count_pos, count);
SendDirectMessage(&data);
}
void Player::SetEquipmentSet(EquipmentSetInfo::EquipmentSetData const& eqSet)
{
if (eqSet.Guid != 0)
{
// something wrong...
auto itr = _equipmentSets.find(eqSet.Guid);
if (itr == _equipmentSets.end() || itr->second.Data.Guid != eqSet.Guid)
{
TC_LOG_ERROR("entities.player", "Player::SetEquipmentSet: Player '{}' ({}) tried to save nonexistent equipment set {} (index: {})",
GetName(), GetGUID().ToString(), eqSet.Guid, eqSet.SetID);
return;
}
}
uint64 setGuid = (eqSet.Guid != 0) ? eqSet.Guid : sObjectMgr->GenerateEquipmentSetGuid();
EquipmentSetInfo& eqSlot = _equipmentSets[setGuid];
eqSlot.Data = eqSet;
if (eqSet.Guid == 0)
{
eqSlot.Data.Guid = setGuid;
WorldPacket data(SMSG_EQUIPMENT_SET_SAVED, 4 + 1);
data << uint32(eqSlot.Data.SetID);
data.appendPackGUID(eqSlot.Data.Guid);
SendDirectMessage(&data);
}
eqSlot.State = (eqSlot.State == EQUIPMENT_SET_NEW ? EQUIPMENT_SET_NEW : EQUIPMENT_SET_CHANGED);
}
void Player::_SaveEquipmentSets(CharacterDatabaseTransaction trans)
{
for (EquipmentSetContainer::iterator itr = _equipmentSets.begin(); itr != _equipmentSets.end();)
{
EquipmentSetInfo& eqSet = itr->second;
CharacterDatabasePreparedStatement* stmt;
uint8 j = 0;
switch (eqSet.State)
{
case EQUIPMENT_SET_UNCHANGED:
++itr;
break; // nothing do
case EQUIPMENT_SET_CHANGED:
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_EQUIP_SET);
stmt->setString(j++, eqSet.Data.SetName);
stmt->setString(j++, eqSet.Data.SetIcon);
stmt->setUInt32(j++, eqSet.Data.IgnoreMask);
for (uint8 i = 0; i < EQUIPMENT_SLOT_END; ++i)
stmt->setUInt32(j++, eqSet.Data.Pieces[i].GetCounter());
stmt->setUInt32(j++, GetGUID().GetCounter());
stmt->setUInt64(j++, eqSet.Data.Guid);
stmt->setUInt32(j, eqSet.Data.SetID);
trans->Append(stmt);
eqSet.State = EQUIPMENT_SET_UNCHANGED;
++itr;
break;
case EQUIPMENT_SET_NEW:
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_EQUIP_SET);
stmt->setUInt32(j++, GetGUID().GetCounter());
stmt->setUInt64(j++, eqSet.Data.Guid);
stmt->setUInt32(j++, eqSet.Data.SetID);
stmt->setString(j++, eqSet.Data.SetName);
stmt->setString(j++, eqSet.Data.SetIcon);
stmt->setUInt32(j++, eqSet.Data.IgnoreMask);
for (uint8 i = 0; i < EQUIPMENT_SLOT_END; ++i)
stmt->setUInt32(j++, eqSet.Data.Pieces[i].GetCounter());
trans->Append(stmt);
eqSet.State = EQUIPMENT_SET_UNCHANGED;
++itr;
break;
case EQUIPMENT_SET_DELETED:
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_EQUIP_SET);
stmt->setUInt64(0, eqSet.Data.Guid);
trans->Append(stmt);
itr = _equipmentSets.erase(itr);
break;
}
}
}
void Player::_SaveBGData(CharacterDatabaseTransaction trans)
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_BGDATA);
stmt->setUInt32(0, GetGUID().GetCounter());
trans->Append(stmt);
/* guid, bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_PLAYER_BGDATA);
stmt->setUInt32(0, GetGUID().GetCounter());
stmt->setUInt32(1, m_bgData.bgInstanceID);
stmt->setUInt16(2, m_bgData.bgTeam);
stmt->setFloat (3, m_bgData.joinPos.GetPositionX());
stmt->setFloat (4, m_bgData.joinPos.GetPositionY());
stmt->setFloat (5, m_bgData.joinPos.GetPositionZ());
stmt->setFloat (6, m_bgData.joinPos.GetOrientation());
stmt->setUInt16(7, m_bgData.joinPos.GetMapId());
stmt->setUInt32(8, m_bgData.taxiPath[0]);
stmt->setUInt32(9, m_bgData.taxiPath[1]);
stmt->setUInt32(10, m_bgData.mountSpell);
trans->Append(stmt);
}
void Player::DeleteEquipmentSet(uint64 setGuid)
{
for (EquipmentSetContainer::iterator itr = _equipmentSets.begin(); itr != _equipmentSets.end();)
{
if (itr->second.Data.Guid == setGuid)
{
if (itr->second.State == EQUIPMENT_SET_NEW)
itr = _equipmentSets.erase(itr);
else
itr->second.State = EQUIPMENT_SET_DELETED;
break;
}
++itr;
}
}
void Player::RemoveAtLoginFlag(AtLoginFlags flags, bool persist /*= false*/)
{
m_atLoginFlags &= ~flags;
if (persist)
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_REM_AT_LOGIN_FLAG);
stmt->setUInt16(0, uint16(flags));
stmt->setUInt32(1, GetGUID().GetCounter());
CharacterDatabase.Execute(stmt);
}
}
void Player::ResetMap()
{
// this may be called during Map::Update
// after decrement+unlink, ++m_mapRefIter will continue correctly
// when the first element of the list is being removed
// nocheck_prev will return the padding element of the RefManager
// instead of nullptr in the case of prev
GetMap()->UpdateIteratorBack(this);
Unit::ResetMap();
GetMapRef().unlink();
}
void Player::SetMap(Map* map)
{
Unit::SetMap(map);
m_mapRef.link(map, this);
}
void Player::_LoadGlyphs(PreparedQueryResult result)
{
// SELECT talentGroup, glyph1, glyph2, glyph3, glyph4, glyph5, glyph6 from character_glyphs WHERE guid = '%u'
if (!result)
return;
do
{
Field* fields = result->Fetch();
uint8 spec = fields[0].GetUInt8();
if (spec >= GetSpecsCount())
continue;
for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
_talentMgr->SpecInfo[spec].Glyphs[i] = fields[i + 1].GetUInt16();
}
while (result->NextRow());
}
void Player::_SaveGlyphs(CharacterDatabaseTransaction trans) const
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_GLYPHS);
stmt->setUInt32(0, GetGUID().GetCounter());
trans->Append(stmt);
for (uint8 spec = 0; spec < GetSpecsCount(); ++spec)
{
uint8 index = 0;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_GLYPHS);
stmt->setUInt32(index++, GetGUID().GetCounter());
stmt->setUInt8(index++, spec);
for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
stmt->setUInt16(index++, uint16(GetGlyph(spec, i)));
trans->Append(stmt);
}
}
void Player::_LoadTalents(PreparedQueryResult result)
{
// SetPQuery(PLAYER_LOGIN_QUERY_LOADTALENTS, "SELECT spell, talentGroup FROM character_talent WHERE guid = '{}'", GUID_LOPART(m_guid));
if (result)
{
do
AddTalent((*result)[0].GetUInt32(), (*result)[1].GetUInt8(), false);
while (result->NextRow());
}
}
void Player::_SaveTalents(CharacterDatabaseTransaction trans)
{
CharacterDatabasePreparedStatement* stmt = nullptr;
for (uint8 i = 0; i < MAX_TALENT_SPECS; ++i)
{
for (PlayerTalentMap::iterator itr = GetTalentMap(i)->begin(); itr != GetTalentMap(i)->end();)
{
if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_TALENT_BY_SPELL_SPEC);
stmt->setUInt32(0, GetGUID().GetCounter());
stmt->setUInt32(1, itr->first);
stmt->setUInt8(2, itr->second->spec);
trans->Append(stmt);
}
if (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED)
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_TALENT);
stmt->setUInt32(0, GetGUID().GetCounter());
stmt->setUInt32(1, itr->first);
stmt->setUInt8(2, itr->second->spec);
trans->Append(stmt);
}
if (itr->second->state == PLAYERSPELL_REMOVED)
{
delete itr->second;
GetTalentMap(i)->erase(itr++);
}
else
{
itr->second->state = PLAYERSPELL_UNCHANGED;
++itr;
}
}
}
}
void Player::UpdateSpecCount(uint8 count)
{
uint32 curCount = GetSpecsCount();
if (curCount == count)
return;
if (GetActiveSpec() >= count)
ActivateSpec(0);
CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction();
CharacterDatabasePreparedStatement* stmt;
// Copy spec data
if (count > curCount)
{
_SaveActions(trans); // make sure the button list is cleaned up
for (ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); ++itr)
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_ACTION);
stmt->setUInt32(0, GetGUID().GetCounter());
stmt->setUInt8(1, 1);
stmt->setUInt8(2, itr->first);
stmt->setUInt32(3, itr->second.GetAction());
stmt->setUInt8(4, uint8(itr->second.GetType()));
trans->Append(stmt);
}
}
// Delete spec data for removed spec.
else if (count < curCount)
{
_SaveActions(trans);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACTION_EXCEPT_SPEC);
stmt->setUInt8(0, GetActiveSpec());
stmt->setUInt32(1, GetGUID().GetCounter());
trans->Append(stmt);
SetActiveSpec(0);
}
CharacterDatabase.CommitTransaction(trans);
SetSpecsCount(count);
SendTalentsInfoData(false);
}
void Player::ActivateSpec(uint8 spec)
{
if (GetActiveSpec() == spec)
return;
if (spec > GetSpecsCount())
return;
if (IsNonMeleeSpellCast(false))
InterruptNonMeleeSpells(false);
CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction();
_SaveActions(trans);
CharacterDatabase.CommitTransaction(trans);
// TO-DO: We need more research to know what happens with warlock's reagent
if (Pet* pet = GetPet())
RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
ClearAllReactives();
UnsummonAllTotems();
ExitVehicle();
RemoveAllControlled();
// remove single target auras at other targets
AuraList& scAuras = GetSingleCastAuras();
for (AuraList::iterator iter = scAuras.begin(); iter != scAuras.end();)
{
Aura* aura = *iter;
if (aura->GetUnitOwner() != this)
{
aura->Remove();
iter = scAuras.begin();
}
else
++iter;
}
/*RemoveAllAurasOnDeath();
if (GetPet())
GetPet()->RemoveAllAurasOnDeath();*/
//RemoveAllAuras(GetGUID(), nullptr, false, true); // removes too many auras
//ExitVehicle(); // should be impossible to switch specs from inside a vehicle..
// Let client clear his current Actions
SendActionButtons(2);
// m_actionButtons.clear() is called in the next _LoadActionButtons
for (uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
{
TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
if (!talentInfo)
continue;
TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TabID);
if (!talentTabInfo)
continue;
// unlearn only talents for character class
// some spell learned by one class as normal spells or know at creation but another class learn it as talent,
// to prevent unexpected lost normal learned spell skip another class talents
if ((GetClassMask() & talentTabInfo->ClassMask) == 0)
continue;
for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank)
{
// skip non-existing talent ranks
if (talentInfo->SpellRank[rank] == 0)
continue;
RemoveSpell(talentInfo->SpellRank[rank], true); // removes the talent, and all dependant, learned, and chained spells..
if (SpellInfo const* _spellEntry = sSpellMgr->GetSpellInfo(talentInfo->SpellRank[rank]))
for (SpellEffectInfo const& spellEffectInfo : _spellEntry->GetEffects()) // search through the SpellInfo for valid trigger spells
if (spellEffectInfo.IsEffect(SPELL_EFFECT_LEARN_SPELL) && spellEffectInfo.TriggerSpell > 0)
RemoveSpell(spellEffectInfo.TriggerSpell, true); // and remove any spells that the talent teaches
// if this talent rank can be found in the PlayerTalentMap, mark the talent as removed so it gets deleted
//PlayerTalentMap::iterator plrTalent = m_talents[m_activeSpec]->find(talentInfo->RankID[rank]);
//if (plrTalent != m_talents[m_activeSpec]->end())
// plrTalent->second->state = PLAYERSPELL_REMOVED;
}
}
// set glyphs
for (uint8 slot = 0; slot < MAX_GLYPH_SLOT_INDEX; ++slot)
// remove secondary glyph
if (uint32 oldglyph = GetGlyph(GetActiveSpec(), slot))
if (GlyphPropertiesEntry const* old_gp = sGlyphPropertiesStore.LookupEntry(oldglyph))
RemoveAurasDueToSpell(old_gp->SpellID);
SetActiveSpec(spec);
uint32 spentTalents = 0;
for (uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
{
TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
if (!talentInfo)
continue;
TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TabID);
if (!talentTabInfo)
continue;
// learn only talents for character class
if ((GetClassMask() & talentTabInfo->ClassMask) == 0)
continue;
// learn highest talent rank that exists in newly activated spec
for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank)
{
// skip non-existing talent ranks
if (talentInfo->SpellRank[rank] == 0)
continue;
// if the talent can be found in the newly activated PlayerTalentMap
if (HasTalent(talentInfo->SpellRank[rank], GetActiveSpec()))
{
LearnSpell(talentInfo->SpellRank[rank], false); // add the talent to the PlayerSpellMap
spentTalents += (rank + 1); // increment the spentTalents count
}
}
}
// set glyphs
for (uint8 slot = 0; slot < MAX_GLYPH_SLOT_INDEX; ++slot)
{
uint32 glyph = GetGlyph(GetActiveSpec(), slot);
// apply primary glyph
if (glyph)
if (GlyphPropertiesEntry const* gp = sGlyphPropertiesStore.LookupEntry(glyph))
CastSpell(this, gp->SpellID, true);
SetGlyph(slot, glyph);
}
SetUsedTalentCount(spentTalents);
InitTalentForLevel();
// load them asynchronously
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_ACTIONS_SPEC);
stmt->setUInt32(0, GetGUID().GetCounter());
stmt->setUInt8(1, GetActiveSpec());
WorldSession* mySess = GetSession();
mySess->GetQueryProcessor().AddCallback(CharacterDatabase.AsyncQuery(stmt)
.WithPreparedCallback([mySess](PreparedQueryResult result)
{
// safe callback, we can't pass this pointer directly
// in case player logs out before db response (player would be deleted in that case)
if (Player* thisPlayer = mySess->GetPlayer())
thisPlayer->LoadActions(result);
}));
}
Powers pw = GetPowerType();
if (pw != POWER_MANA)
SetPower(POWER_MANA, 0); // Mana must be 0 even if it isn't the active power type.
SetPower(pw, 0);
Unit::AuraEffectList const& shapeshiftAuras = GetAuraEffectsByType(SPELL_AURA_MOD_SHAPESHIFT);
for (AuraEffect* aurEff : shapeshiftAuras)
{
aurEff->HandleShapeshiftBoosts(this, false);
aurEff->HandleShapeshiftBoosts(this, true);
}
}
void Player::LoadActions(PreparedQueryResult result)
{
if (result)
_LoadActions(result);
SendActionButtons(1);
}
void Player::SetReputation(uint32 factionentry, uint32 value)
{
GetReputationMgr().SetReputation(sFactionStore.LookupEntry(factionentry), value);
}
uint32 Player::GetReputation(uint32 factionentry) const
{
return GetReputationMgr().GetReputation(sFactionStore.LookupEntry(factionentry));
}
std::string Player::GetGuildName() const
{
return GetGuildId() ? sGuildMgr->GetGuildById(GetGuildId())->GetName() : "";
}
void Player::SendDuelCountdown(uint32 counter)
{
WorldPacket data(SMSG_DUEL_COUNTDOWN, 4);
data << uint32(counter); // seconds
SendDirectMessage(&data);
}
void Player::AddRefundReference(ObjectGuid it)
{
m_refundableItems.insert(it);
}
void Player::DeleteRefundReference(ObjectGuid it)
{
GuidSet::iterator itr = m_refundableItems.find(it);
if (itr != m_refundableItems.end())
m_refundableItems.erase(itr);
}
void Player::SendRefundInfo(Item* item)
{
// This function call unsets ITEM_FLAGS_REFUNDABLE if played time is over 2 hours.
item->UpdatePlayedTime(this);
if (!item->IsRefundable())
{
TC_LOG_DEBUG("entities.player.items", "Item refund: item not refundable!");
return;
}
if (GetGUID() != item->GetRefundRecipient()) // Formerly refundable item got traded
{
TC_LOG_DEBUG("entities.player.items", "Item refund: item was traded!");
item->SetNotRefundable(this);
return;
}
ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(item->GetPaidExtendedCost());
if (!iece)
{
TC_LOG_DEBUG("entities.player.items", "Item refund: cannot find extendedcost data.");
return;
}
WorldPacket data(SMSG_ITEM_REFUND_INFO_RESPONSE, 8+4+4+4+4*4+4*4+4+4);
data << item->GetGUID(); // item guid
data << uint32(item->GetPaidMoney()); // money cost
data << uint32(iece->HonorPoints); // honor point cost
data << uint32(iece->ArenaPoints); // arena point cost
for (uint8 i = 0; i < MAX_ITEM_EXTENDED_COST_REQUIREMENTS; ++i) // item cost data
{
data << uint32(iece->ItemID[i]);
data << uint32(iece->ItemCount[i]);
}
data << uint32(0);
data << uint32(GetTotalPlayedTime() - item->GetPlayedTime());
SendDirectMessage(&data);
}
bool Player::AddItem(uint32 itemId, uint32 count)
{
uint32 noSpaceForCount = 0;
ItemPosCountVec dest;
InventoryResult msg = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, itemId, count, &noSpaceForCount);
if (msg != EQUIP_ERR_OK)
count -= noSpaceForCount;
if (count == 0 || dest.empty())
{
/// @todo Send to mailbox if no space
ChatHandler(GetSession()).PSendSysMessage("You don't have any space in your bags.");
return false;
}
Item* item = StoreNewItem(dest, itemId, true, GenerateItemRandomPropertyId(itemId));
if (item)
SendNewItem(item, count, true, false);
else
return false;
return true;
}
PetStable& Player::GetOrInitPetStable()
{
if (!m_petStable)
m_petStable = std::make_unique<PetStable>();
return *m_petStable;
}
void Player::SendItemRefundResult(Item* item, ItemExtendedCostEntry const* iece, uint8 error) const
{
WorldPacket data(SMSG_ITEM_REFUND_RESULT, 8 + 4 + 4 + 4 + 4 + 4 * 4 + 4 * 4);
data << item->GetGUID(); // item guid
data << uint32(error); // 0, or error code
if (!error)
{
data << uint32(item->GetPaidMoney()); // money cost
data << uint32(iece->HonorPoints); // honor point cost
data << uint32(iece->ArenaPoints); // arena point cost
for (uint8 i = 0; i < MAX_ITEM_EXTENDED_COST_REQUIREMENTS; ++i) // item cost data
{
data << uint32(iece->ItemID[i]);
data << uint32(iece->ItemCount[i]);
}
}
SendDirectMessage(&data);
}
void Player::RefundItem(Item* item)
{
if (!item->IsRefundable())
{
TC_LOG_DEBUG("entities.player.items", "Item refund: item not refundable!");
return;
}
if (item->IsRefundExpired()) // item refund has expired
{
item->SetNotRefundable(this);
SendItemRefundResult(item, nullptr, 10);
return;
}
if (GetGUID() != item->GetRefundRecipient()) // Formerly refundable item got traded
{
TC_LOG_DEBUG("entities.player.items", "Item refund: item was traded!");
item->SetNotRefundable(this);
return;
}
ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(item->GetPaidExtendedCost());
if (!iece)
{
TC_LOG_DEBUG("entities.player.items", "Item refund: cannot find extendedcost data.");
return;
}
bool store_error = false;
for (uint8 i = 0; i < MAX_ITEM_EXTENDED_COST_REQUIREMENTS; ++i)
{
uint32 count = iece->ItemCount[i];
uint32 itemid = iece->ItemID[i];
if (count && itemid)
{
ItemPosCountVec dest;
InventoryResult msg = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, itemid, count);
if (msg != EQUIP_ERR_OK)
{
store_error = true;
break;
}
}
}
if (store_error)
{
SendItemRefundResult(item, iece, 10);
return;
}
SendItemRefundResult(item, iece, 0);
uint32 moneyRefund = item->GetPaidMoney(); // item-> will be invalidated in DestroyItem
// Save all relevant data to DB to prevent desynchronisation exploits
CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction();
// Delete any references to the refund data
item->SetNotRefundable(this, true, &trans);
// Destroy item
DestroyItem(item->GetBagSlot(), item->GetSlot(), true);
// Grant back extendedcost items
for (uint8 i = 0; i < MAX_ITEM_EXTENDED_COST_REQUIREMENTS; ++i)
{
uint32 count = iece->ItemCount[i];
uint32 itemid = iece->ItemID[i];
if (count && itemid)
{
ItemPosCountVec dest;
InventoryResult msg = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, itemid, count);
ASSERT(msg == EQUIP_ERR_OK); /// Already checked before
Item* it = StoreNewItem(dest, itemid, true);
SendNewItem(it, count, true, false, true);
}
}
// Grant back money
if (moneyRefund)
ModifyMoney(moneyRefund); // Saved in SaveInventoryAndGoldToDB
// Grant back Honor points
if (uint32 honorRefund = iece->HonorPoints)
ModifyHonorPoints(honorRefund, trans);
// Grant back Arena points
if (uint32 arenaRefund = iece->ArenaPoints)
ModifyArenaPoints(arenaRefund, trans);
SaveInventoryAndGoldToDB(trans);
CharacterDatabase.CommitTransaction(trans);
}
void Player::SendItemRetrievalMail(uint32 itemEntry, uint32 count)
{
MailSender sender(MAIL_CREATURE, 34337 /* The Postmaster */);
MailDraft draft("Recovered Item", "We recovered a lost item in the twisting nether and noted that it was yours.$B$BPlease find said object enclosed."); // This is the text used in Cataclysm, it probably wasn't changed.
CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction();
if (Item* item = Item::CreateItem(itemEntry, count, nullptr))
{
item->SaveToDB(trans);
draft.AddItem(item);
}
draft.SendMailTo(trans, MailReceiver(this, GetGUID().GetCounter()), sender);
CharacterDatabase.CommitTransaction(trans);
}
void Player::SetRandomWinner(bool isWinner)
{
m_IsBGRandomWinner = isWinner;
if (m_IsBGRandomWinner)
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_BATTLEGROUND_RANDOM);
stmt->setUInt32(0, GetGUID().GetCounter());
CharacterDatabase.Execute(stmt);
}
}
void Player::_LoadRandomBGStatus(PreparedQueryResult result)
{
//QueryResult result = CharacterDatabase.PQuery("SELECT guid FROM character_battleground_random WHERE guid = '{}'", GetGUID().GetCounter());
if (result)
m_IsBGRandomWinner = true;
}
float Player::GetAverageItemLevel() const
{
float sum = 0;
uint32 count = 0;
for (int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
{
// don't check tabard, ranged, offhand or shirt
if (i == EQUIPMENT_SLOT_TABARD || i == EQUIPMENT_SLOT_RANGED || i == EQUIPMENT_SLOT_OFFHAND || i == EQUIPMENT_SLOT_BODY)
continue;
if (m_items[i] && m_items[i]->GetTemplate())
sum += m_items[i]->GetTemplate()->GetItemLevelIncludingQuality();
++count;
}
return ((float)sum) / count;
}
void Player::_LoadPetStable(uint8 petStableSlots, PreparedQueryResult result)
{
if (!petStableSlots && !result)
return;
m_petStable = std::make_unique<PetStable>();
m_petStable->MaxStabledPets = petStableSlots;
if (m_petStable->MaxStabledPets > MAX_PET_STABLES)
{
TC_LOG_ERROR("entities.player", "Player::LoadFromDB: Player ({}) can't have more stable slots than {}, but has {} in DB",
GetGUID().ToString(), MAX_PET_STABLES, m_petStable->MaxStabledPets);
m_petStable->MaxStabledPets = MAX_PET_STABLES;
}
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// SELECT id, entry, modelid, level, exp, Reactstate, slot, name, renamed, curhealth, curmana, curhappiness, abdata, savetime, CreatedBySpell, PetType FROM character_pet WHERE owner = ?
if (result)
{
do
{
Field* fields = result->Fetch();
PetStable::PetInfo petInfo;
petInfo.PetNumber = fields[0].GetUInt32();
petInfo.CreatureId = fields[1].GetUInt32();
petInfo.DisplayId = fields[2].GetUInt32();
petInfo.Level = fields[3].GetUInt16();
petInfo.Experience = fields[4].GetUInt32();
petInfo.ReactState = ReactStates(fields[5].GetUInt8());
PetSaveMode slot = PetSaveMode(fields[6].GetUInt8());
petInfo.Name = fields[7].GetString();
petInfo.WasRenamed = fields[8].GetBool();
petInfo.Health = fields[9].GetUInt32();
petInfo.Mana = fields[10].GetUInt32();
petInfo.Happiness = fields[11].GetUInt32();
petInfo.ActionBar = fields[12].GetString();
petInfo.LastSaveTime = fields[13].GetUInt32();
petInfo.CreatedBySpellId = fields[14].GetUInt32();
petInfo.Type = PetType(fields[15].GetUInt8());
if (slot == PET_SAVE_AS_CURRENT)
m_petStable->CurrentPet = std::move(petInfo);
else if (slot >= PET_SAVE_FIRST_STABLE_SLOT && slot <= PET_SAVE_LAST_STABLE_SLOT)
m_petStable->StabledPets[slot - 1] = std::move(petInfo);
else if (slot == PET_SAVE_NOT_IN_SLOT)
m_petStable->UnslottedPets.push_back(std::move(petInfo));
} while (result->NextRow());
}
}
bool Player::IsInWhisperWhiteList(ObjectGuid guid)
{
for (GuidList::const_iterator itr = WhisperList.begin(); itr != WhisperList.end(); ++itr)
if (*itr == guid)
return true;
return false;
}
bool Player::SetDisableGravity(bool disable, bool packetOnly /*= false*/, bool updateAnimTier /*= true*/)
{
if (!packetOnly && !Unit::SetDisableGravity(disable, packetOnly, updateAnimTier))
return false;
WorldPacket data(disable ? SMSG_MOVE_GRAVITY_DISABLE : SMSG_MOVE_GRAVITY_ENABLE, 12);
data << GetPackGUID();
data << uint32(0); //! movement counter
SendDirectMessage(&data);
data.Initialize(MSG_MOVE_GRAVITY_CHNG, 64);
data << GetPackGUID();
BuildMovementPacket(&data);
SendMessageToSet(&data, false);
return true;
}
bool Player::SetCanFly(bool apply, bool packetOnly /*= false*/)
{
if (!apply)
SetFallInformation(0, GetPositionZ());
WorldPacket data(apply ? SMSG_MOVE_SET_CAN_FLY : SMSG_MOVE_UNSET_CAN_FLY, 12);
data << GetPackGUID();
data << uint32(0); //! movement counter
SendDirectMessage(&data);
if (packetOnly || Unit::SetCanFly(apply))
{
data.Initialize(MSG_MOVE_UPDATE_CAN_FLY, 64);
data << GetPackGUID();
BuildMovementPacket(&data);
SendMessageToSet(&data, false);
return true;
}
else
return false;
}
bool Player::SetHover(bool apply, bool packetOnly /*= false*/, bool updateAnimTier /*= true*/)
{
if (!packetOnly && !Unit::SetHover(apply, packetOnly, updateAnimTier))
return false;
WorldPacket data(apply ? SMSG_MOVE_SET_HOVER : SMSG_MOVE_UNSET_HOVER, 12);
data << GetPackGUID();
data << uint32(0); //! movement counter
SendDirectMessage(&data);
data.Initialize(MSG_MOVE_HOVER, 64);
data << GetPackGUID();
BuildMovementPacket(&data);
SendMessageToSet(&data, false);
return true;
}
bool Player::SetWaterWalking(bool apply, bool packetOnly /*= false*/)
{
if (!packetOnly && !Unit::SetWaterWalking(apply))
return false;
WorldPacket data(apply ? SMSG_MOVE_WATER_WALK : SMSG_MOVE_LAND_WALK, 12);
data << GetPackGUID();
data << uint32(0); //! movement counter
SendDirectMessage(&data);
data.Initialize(MSG_MOVE_WATER_WALK, 64);
data << GetPackGUID();
BuildMovementPacket(&data);
SendMessageToSet(&data, false);
return true;
}
bool Player::SetFeatherFall(bool apply, bool packetOnly /*= false*/)
{
if (!packetOnly && !Unit::SetFeatherFall(apply))
return false;
WorldPacket data(apply ? SMSG_MOVE_FEATHER_FALL : SMSG_MOVE_NORMAL_FALL, 12);
data << GetPackGUID();
data << uint32(0); //! movement counter
SendDirectMessage(&data);
data.Initialize(MSG_MOVE_FEATHER_FALL, 64);
data << GetPackGUID();
BuildMovementPacket(&data);
SendMessageToSet(&data, false);
return true;
}
void Player::SendMovementSetCollisionHeight(float height)
{
WorldPacket data(SMSG_MOVE_SET_COLLISION_HGT, GetPackGUID().size() + 4 + 4);
data << GetPackGUID();
data << uint32(GetMovementCounterAndInc());
data << height;
SendDirectMessage(&data);
}
std::string Player::GetMapAreaAndZoneString() const
{
uint32 areaId = GetAreaId();
std::string areaName = "Unknown";
std::string zoneName = "Unknown";
if (AreaTableEntry const* area = sAreaTableStore.LookupEntry(areaId))
{
int locale = GetSession()->GetSessionDbcLocale();
areaName = area->AreaName[locale];
if (AreaTableEntry const* zone = sAreaTableStore.LookupEntry(area->ParentAreaID))
zoneName = zone->AreaName[locale];
}
std::ostringstream str;
str << "Map: " << GetMapId() << " (" << (FindMap() ? FindMap()->GetMapName() : "Unknown") << ") Area: " << areaId << " (" << areaName.c_str() << ") Zone: " << zoneName.c_str();
return str.str();
}
std::string Player::GetCoordsMapAreaAndZoneString() const
{
std::ostringstream str;
str << Position::ToString() << " " << GetMapAreaAndZoneString();
return str.str();
}
void Player::SetInGuild(ObjectGuid::LowType guildId)
{
SetUInt32Value(PLAYER_GUILDID, guildId);
sCharacterCache->UpdateCharacterGuildId(GetGUID(), guildId);
}
Guild* Player::GetGuild()
{
ObjectGuid::LowType guildId = GetGuildId();
return guildId ? sGuildMgr->GetGuildById(guildId) : nullptr;
}
Pet* Player::SummonPet(uint32 entry, float x, float y, float z, float ang, PetType petType, uint32 duration)
{
PetStable& petStable = GetOrInitPetStable();
Pet* pet = new Pet(this, petType);
if (petType == SUMMON_PET && pet->LoadPetFromDB(this, entry, 0, false))
{
// Remove Demonic Sacrifice auras (known pet)
Unit::AuraEffectList const& auraClassScripts = GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
for (Unit::AuraEffectList::const_iterator itr = auraClassScripts.begin(); itr != auraClassScripts.end();)
{
if ((*itr)->GetMiscValue() == 2228)
{
RemoveAurasDueToSpell((*itr)->GetId());
itr = auraClassScripts.begin();
}
else
++itr;
}
if (duration > 0)
pet->SetDuration(duration);
// Generate a new name for the newly summoned ghoul
if (pet->IsPetGhoul())
{
std::string new_name = sObjectMgr->GeneratePetName(entry);
if (!new_name.empty())
pet->SetName(new_name);
}
return nullptr;
}
// petentry == 0 for hunter "call pet" (current pet summoned if any)
if (!entry)
{
delete pet;
return nullptr;
}
pet->Relocate(x, y, z, ang);
if (!pet->IsPositionValid())
{
TC_LOG_ERROR("misc", "Player::SummonPet: Pet ({}, Entry: {}) not summoned. Suggested coordinates aren't valid (X: {} Y: {})", pet->GetGUID().ToString(), pet->GetEntry(), pet->GetPositionX(), pet->GetPositionY());
delete pet;
return nullptr;
}
Map* map = GetMap();
uint32 pet_number = sObjectMgr->GeneratePetNumber();
if (!pet->Create(map->GenerateLowGuid<HighGuid::Pet>(), map, GetPhaseMask(), entry, pet_number))
{
TC_LOG_ERROR("misc", "Player::SummonPet: No such creature entry {}", entry);
delete pet;
return nullptr;
}
if (petType == SUMMON_PET && petStable.CurrentPet)
RemovePet(nullptr, PET_SAVE_NOT_IN_SLOT);
pet->SetCreatorGUID(GetGUID());
pet->SetFaction(GetFaction());
pet->ReplaceAllNpcFlags(UNIT_NPC_FLAG_NONE);
pet->InitStatsForLevel(GetLevel());
SetMinion(pet, true);
switch (petType)
{
case SUMMON_PET:
// this enables pet details window (Shift+P)
pet->GetCharmInfo()->SetPetNumber(pet_number, true);
pet->SetClass(CLASS_MAGE);
pet->SetPetExperience(0);
pet->SetPetNextLevelExperience(1000);
pet->SetFullHealth();
pet->SetPower(POWER_MANA, pet->GetMaxPower(POWER_MANA));
pet->SetPetNameTimestamp(uint32(GameTime::GetGameTime())); // cast can't be helped in this case
break;
default:
break;
}
map->AddToMap(pet->ToCreature());
ASSERT(!petStable.CurrentPet && (petType != HUNTER_PET || !petStable.GetUnslottedHunterPet()));
pet->FillPetInfo(&petStable.CurrentPet.emplace());
switch (petType)
{
case SUMMON_PET:
pet->InitPetCreateSpells();
pet->InitTalentForLevel();
pet->SavePetToDB(PET_SAVE_AS_CURRENT);
PetSpellInitialize();
break;
default:
break;
}
if (petType == SUMMON_PET)
{
// Remove Demonic Sacrifice auras (known pet)
Unit::AuraEffectList const& auraClassScripts = GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
for (Unit::AuraEffectList::const_iterator itr = auraClassScripts.begin(); itr != auraClassScripts.end();)
{
if ((*itr)->GetMiscValue() == 2228)
{
RemoveAurasDueToSpell((*itr)->GetId());
itr = auraClassScripts.begin();
}
else
++itr;
}
}
if (duration > 0)
pet->SetDuration(duration);
//ObjectAccessor::UpdateObjectVisibility(pet);
return pet;
}
void Player::SendSupercededSpell(uint32 oldSpell, uint32 newSpell) const
{
WorldPacket data(SMSG_SUPERCEDED_SPELL, 8);
data << uint32(oldSpell) << uint32(newSpell);
SendDirectMessage(&data);
}
bool Player::ValidateAppearance(uint8 race, uint8 class_, uint8 gender, uint8 hairID, uint8 hairColor, uint8 faceID, uint8 facialHair, uint8 skinColor, bool create /*=false*/)
{
auto validateCharSection = [class_, create](CharSectionsEntry const* entry) -> bool
{
if (!entry)
return false;
// Check Death Knight exclusive
if (class_ != CLASS_DEATH_KNIGHT && entry->HasFlag(SECTION_FLAG_DEATH_KNIGHT))
return false;
// Character creation/customize has some limited sections (as opposed to barbershop)
if (create && !entry->HasFlag(SECTION_FLAG_PLAYER))
return false;
return true;
};
// For Skin type is always 0
CharSectionsEntry const* skinEntry = GetCharSectionEntry(race, SECTION_TYPE_SKIN, gender, 0, skinColor);
if (!validateCharSection(skinEntry))
return false;
// Skin Color defined as Face color, too
CharSectionsEntry const* faceEntry = GetCharSectionEntry(race, SECTION_TYPE_FACE, gender, faceID, skinColor);
if (!validateCharSection(faceEntry))
return false;
// Check Hair
CharSectionsEntry const* hairEntry = GetCharSectionEntry(race, SECTION_TYPE_HAIR, gender, hairID, hairColor);
if (!validateCharSection(hairEntry))
return false;
// These combinations don't have an entry of Type SECTION_TYPE_FACIAL_HAIR, exclude them from that check
bool const excludeCheck = (race == RACE_TAUREN) || (race == RACE_DRAENEI) || (gender == GENDER_FEMALE && race != RACE_NIGHTELF && race != RACE_UNDEAD_PLAYER);
if (!excludeCheck)
{
CharSectionsEntry const* facialHairEntry = GetCharSectionEntry(race, SECTION_TYPE_FACIAL_HAIR, gender, facialHair, hairColor);
if (!validateCharSection(facialHairEntry))
return false;
}
CharacterFacialHairStylesEntry const* entry = GetCharFacialHairEntry(race, gender, facialHair);
if (!entry)
return false;
return true;
}
void Player::SetRestFlag(RestFlag restFlag, uint32 triggerId /*= 0*/)
{
uint32 oldRestMask = _restFlagMask;
_restFlagMask |= restFlag;
if (!oldRestMask && _restFlagMask) // only set flag/time on the first rest state
{
_restTime = GameTime::GetGameTime();
SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
}
if (triggerId)
inn_triggerId = triggerId;
}
void Player::RemoveRestFlag(RestFlag restFlag)
{
uint32 oldRestMask = _restFlagMask;
_restFlagMask &= ~restFlag;
if (oldRestMask && !_restFlagMask) // only remove flag/time on the last rest state remove
{
_restTime = 0;
RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
}
}
uint32 Player::DoRandomRoll(uint32 minimum, uint32 maximum)
{
ASSERT(maximum <= 10000);
uint32 roll = urand(minimum, maximum);
WorldPackets::Misc::RandomRoll randomRoll;
randomRoll.Min = minimum;
randomRoll.Max = maximum;
randomRoll.Result = roll;
randomRoll.Roller = GetGUID();
if (Group* group = GetGroup())
group->BroadcastPacket(randomRoll.Write(), false);
else
SendDirectMessage(randomRoll.Write());
return roll;
}
void Player::RemoveSocial()
{
sSocialMgr->RemovePlayerSocial(GetGUID());
m_social = nullptr;
}
std::string Player::GetDebugInfo() const
{
std::stringstream sstr;
sstr << Unit::GetDebugInfo();
return sstr.str();
}
GameClient* Player::GetGameClient() const
{
return GetSession()->GetGameClient();
}
| 412 | 0.996467 | 1 | 0.996467 | game-dev | MEDIA | 0.809636 | game-dev | 0.607769 | 1 | 0.607769 |
ExpressLRS/ExpressLRS | 29,727 | src/lua/elrsV3.lua | -- TNS|ExpressLRS|TNE
---- #########################################################################
---- # #
---- # Copyright (C) OpenTX, adapted for ExpressLRS #
-----# #
---- # License GPLv2: http://www.gnu.org/licenses/gpl-2.0.html #
---- # #
---- #########################################################################
local EXITVER = "-- EXIT (Lua r15) --"
local deviceId = 0xEE
local handsetId = 0xEF
local deviceName = "Loading..."
local lineIndex = 1
local pageOffset = 0
local edit = nil
local fieldPopup
local fieldTimeout = 0
local loadQ = {}
local fieldChunk = 0
local fieldData = nil
local fields = {}
local devices = {}
local goodBadPkt = ""
local elrsFlags = 0
local elrsFlagsInfo = ""
local fields_count = 0
local devicesRefreshTimeout = 50
local currentFolderId = nil
local commandRunningIndicator = 1
local expectChunksRemain = -1
local deviceIsELRS_TX = nil
local linkstatTimeout = 100
local titleShowWarn = nil
local titleShowWarnTimeout = 100
local exitscript = 0
local COL1
local COL2
local maxLineIndex
local textYoffset
local textSize
local barTextSpacing
local function allocateFields()
-- fields table is real fields, then the Other Devices item, then devices, then Exit/Back
fields = {}
for i=1, fields_count do
fields[i] = { }
end
fields[#fields+1] = {id=fields_count+1, name="Other Devices", parent=255, type=16}
fields[#fields+1] = {name=EXITVER, type=14}
end
local function createDeviceFields() -- put other devices in the field list
-- move back button to the end of the list, so it will always show up at the bottom.
fields[fields_count + #devices + 2] = fields[#fields]
for i=1, #devices do
local parent = (devices[i].id == deviceId) and 255 or (fields_count+1)
fields[fields_count + 1 + i] = {id=devices[i].id, name=devices[i].name, parent=parent, type=15}
end
end
local function reloadAllField()
fieldTimeout = 0
fieldChunk = 0
fieldData = nil
-- loadQ is actually a stack
loadQ = {}
for fieldId = fields_count, 1, -1 do
loadQ[#loadQ+1] = fieldId
end
end
local function getField(line)
local counter = 1
for i = 1, #fields do
local field = fields[i]
if currentFolderId == field.parent and not field.hidden then
if counter < line then
counter = counter + 1
else
return field
end
end
end
end
local function incrField(step)
local field = getField(lineIndex)
local min, max = 0, 0
if field.type <= 8 then
min = field.min or 0
max = field.max or 0
step = (field.step or 1) * step
elseif field.type == 9 then
min = 0
max = #field.values - 1
end
local newval = field.value
repeat
newval = newval + step
if newval < min then
newval = min
elseif newval > max then
newval = max
end
-- keep looping until a non-blank selection value is found
if field.values == nil or #field.values[newval+1] ~= 0 then
field.value = newval
return
end
until (newval == min or newval == max)
end
-- Select the next or previous editable field
local function selectField(step)
local newLineIndex = lineIndex
local field
repeat
newLineIndex = newLineIndex + step
if newLineIndex <= 0 then
newLineIndex = #fields
elseif newLineIndex == 1 + #fields then
newLineIndex = 1
pageOffset = 0
end
field = getField(newLineIndex)
until newLineIndex == lineIndex or (field and field.name)
lineIndex = newLineIndex
if lineIndex > maxLineIndex + pageOffset then
pageOffset = lineIndex - maxLineIndex
elseif lineIndex <= pageOffset then
pageOffset = lineIndex - 1
end
end
local function fieldGetStrOrOpts(data, offset, last, isOpts)
-- For isOpts: Split a table of byte values (string) with ; separator into a table
-- Else just read a string until the first null byte
local r = last or (isOpts and {})
local opt = ''
local vcnt = 0
repeat
local b = data[offset]
offset = offset + 1
if not last then
if r and (b == 59 or b == 0) then -- ';'
r[#r+1] = opt
if opt ~= '' then
vcnt = vcnt + 1
opt = ''
end
elseif b ~= 0 then
-- On firmwares that have constants defined for the arrow chars, use them in place of
-- the \xc0 \xc1 chars (which are OpenTX-en)
-- Use the table to convert the char, else use string.char if not in the table
opt = opt .. (({
[192] = CHAR_UP or (__opentx and __opentx.CHAR_UP),
[193] = CHAR_DOWN or (__opentx and __opentx.CHAR_DOWN)
})[b] or string.char(b))
end
end
until b == 0
return (r or opt), offset, vcnt, collectgarbage("collect")
end
local function getDevice(id)
for _, device in ipairs(devices) do
if device.id == id then
return device
end
end
end
local function fieldGetValue(data, offset, size)
local result = 0
for i=0, size-1 do
result = bit32.lshift(result, 8) + data[offset + i]
end
return result
end
local function reloadCurField()
local field = getField(lineIndex)
fieldTimeout = 0
fieldChunk = 0
fieldData = nil
loadQ[#loadQ+1] = field.id
end
-- UINT8/INT8/UINT16/INT16 + FLOAT + TEXTSELECT
local function fieldUnsignedLoad(field, data, offset, size, unitoffset)
field.value = fieldGetValue(data, offset, size)
field.min = fieldGetValue(data, offset+size, size)
field.max = fieldGetValue(data, offset+2*size, size)
--field.default = fieldGetValue(data, offset+3*size, size)
field.unit = fieldGetStrOrOpts(data, offset+(unitoffset or (4*size)), field.unit)
-- Only store the size if it isn't 1 (covers most fields / selection)
if size ~= 1 then
field.size = size
end
end
local function fieldUnsignedToSigned(field, size)
local bandval = bit32.lshift(0x80, (size-1)*8)
field.value = field.value - bit32.band(field.value, bandval) * 2
field.min = field.min - bit32.band(field.min, bandval) * 2
field.max = field.max - bit32.band(field.max, bandval) * 2
--field.default = field.default - bit32.band(field.default, bandval) * 2
end
local function fieldSignedLoad(field, data, offset, size, unitoffset)
fieldUnsignedLoad(field, data, offset, size, unitoffset)
fieldUnsignedToSigned(field, size)
-- signed ints are INTdicated by a negative size
field.size = -size
end
local function fieldIntLoad(field, data, offset)
-- Type is U8/I8/U16/I16, use that to determine the size and signedness
local loadFn = (field.type % 2 == 0) and fieldUnsignedLoad or fieldSignedLoad
loadFn(field, data, offset, math.floor(field.type / 2) + 1)
end
local function fieldIntSave(field)
local value = field.value
local size = field.size or 1
-- Convert signed to 2s complement
if size < 0 then
size = -size
if value < 0 then
value = bit32.lshift(0x100, (size-1)*8) + value
end
end
local frame = { deviceId, handsetId, field.id }
for i = size-1, 0, -1 do
frame[#frame + 1] = bit32.rshift(value, 8*i) % 256
end
crossfireTelemetryPush(0x2D, frame)
end
local function fieldIntDisplay(field, y, attr)
lcd.drawText(COL2, y, field.value .. field.unit, attr)
end
-- -- FLOAT
local function fieldFloatLoad(field, data, offset)
fieldSignedLoad(field, data, offset, 4, 21)
field.prec = data[offset+16]
if field.prec > 3 then
field.prec = 3
end
field.step = fieldGetValue(data, offset+17, 4)
-- precompute the format string to preserve the precision
field.fmt = "%." .. tostring(field.prec) .. "f" .. field.unit
-- Convert precision to a divider
field.prec = 10 ^ field.prec
end
local function fieldFloatDisplay(field, y, attr)
lcd.drawText(COL2, y, string.format(field.fmt, field.value / field.prec), attr)
end
-- TEXT SELECTION
local function fieldTextSelLoad(field, data, offset)
local vcnt
local cached = field.nc == nil and field.values
field.values, offset, vcnt = fieldGetStrOrOpts(data, offset, cached, true)
-- 'Disable' the line if values only has one option in the list
if not cached then
field.grey = vcnt <= 1
end
field.value = data[offset]
-- min max and default (offset+1 to 3) are not used on selections
-- units never uses cache
field.unit = fieldGetStrOrOpts(data, offset+4)
field.nc = nil -- use cache next time
end
local function fieldTextSelDisplay_color(field, y, attr, color)
local val = field.values[field.value+1] or "ERR"
lcd.drawText(COL2, y, val, attr + color)
local strPix = lcd.sizeText and lcd.sizeText(val) or (10 * #val)
lcd.drawText(COL2 + strPix, y, field.unit, color)
end
local function fieldTextSelDisplay_bw(field, y, attr)
lcd.drawText(COL2, y, field.values[field.value+1] or "ERR", attr)
lcd.drawText(lcd.getLastPos(), y, field.unit, 0)
end
-- STRING
local function fieldStringLoad(field, data, offset)
field.value, offset = fieldGetStrOrOpts(data, offset)
if #data >= offset then
field.maxlen = data[offset]
end
end
local function fieldStringDisplay(field, y, attr)
lcd.drawText(COL2, y, field.value, attr)
end
local function fieldFolderOpen(field)
currentFolderId = field.id
local backFld = fields[#fields]
backFld.name = "----BACK----"
-- Store the lineIndex and pageOffset to return to in the backFld
backFld.li = lineIndex
backFld.po = pageOffset
backFld.parent = currentFolderId
lineIndex = 1
pageOffset = 0
end
local function fieldFolderDeviceOpen(field)
-- crossfireTelemetryPush(0x28, { 0x00, 0xEA }) --broadcast with standard handset ID to get all node respond correctly
-- Make sure device fields are in the folder when it opens
createDeviceFields()
return fieldFolderOpen(field)
end
local function fieldFolderDisplay(field,y ,attr)
lcd.drawText(COL1, y, "> " .. field.name, attr + BOLD)
end
local function fieldCommandLoad(field, data, offset)
field.status = data[offset]
field.timeout = data[offset+1]
field.info = fieldGetStrOrOpts(data, offset+2)
if field.status == 0 then
fieldPopup = nil
end
end
local function fieldCommandSave(field)
reloadCurField()
if field.status ~= nil then
if field.status < 4 then
field.status = 1
crossfireTelemetryPush(0x2D, { deviceId, handsetId, field.id, field.status })
fieldPopup = field
fieldPopup.lastStatus = 0
fieldTimeout = getTime() + field.timeout
end
end
end
local function fieldCommandDisplay(field, y, attr)
lcd.drawText(10, y, "[" .. field.name .. "]", attr + BOLD)
end
local function fieldBackExec(field)
if field.parent then
lineIndex = field.li or 1
pageOffset = field.po or 0
field.name = EXITVER
field.parent = nil
field.li = nil
field.po = nil
currentFolderId = nil
else
exitscript = 1
end
end
local function changeDeviceId(devId) --change to selected device ID
local device = getDevice(devId)
if deviceId == devId and fields_count == device.fldcnt then return end
deviceId = devId
elrsFlags = 0
currentFolderId = nil
deviceName = device.name
fields_count = device.fldcnt
deviceIsELRS_TX = device.isElrs and devId == 0xEE or nil -- ELRS and ID is TX module
handsetId = deviceIsELRS_TX and 0xEF or 0xEA -- Address ELRS_LUA vs RADIO_TRANSMITTER
allocateFields()
reloadAllField()
end
local function fieldDeviceIdSelect(field)
return changeDeviceId(field.id)
end
local function parseDeviceInfoMessage(data)
local id = data[2]
local newName, offset = fieldGetStrOrOpts(data, 3)
local device = getDevice(id)
if device == nil then
device = { id = id }
devices[#devices + 1] = device
end
device.name = newName
device.fldcnt = data[offset + 12]
device.isElrs = fieldGetValue(data, offset, 4) == 0x454C5253 -- SerialNumber = 'E L R S'
if deviceId == id then
changeDeviceId(id)
end
-- DeviceList change while in Other Devices, refresh list
if currentFolderId == fields_count + 1 then
createDeviceFields()
end
end
local functions = {
{ load=fieldIntLoad, save=fieldIntSave, display=fieldIntDisplay }, --1 UINT8(0)
{ load=fieldIntLoad, save=fieldIntSave, display=fieldIntDisplay }, --2 INT8(1)
{ load=fieldIntLoad, save=fieldIntSave, display=fieldIntDisplay }, --3 UINT16(2)
{ load=fieldIntLoad, save=fieldIntSave, display=fieldIntDisplay }, --4 INT16(3)
nil,
nil,
nil,
nil,
{ load=fieldFloatLoad, save=fieldIntSave, display=fieldFloatDisplay }, --9 FLOAT(8)
{ load=fieldTextSelLoad, save=fieldIntSave, display=nil }, --10 SELECT(9)
{ load=fieldStringLoad, save=nil, display=fieldStringDisplay }, --11 STRING(10) editing NOTIMPL
{ load=nil, save=fieldFolderOpen, display=fieldFolderDisplay }, --12 FOLDER(11)
{ load=fieldStringLoad, save=nil, display=fieldStringDisplay }, --13 INFO(12)
{ load=fieldCommandLoad, save=fieldCommandSave, display=fieldCommandDisplay }, --14 COMMAND(13)
{ load=nil, save=fieldBackExec, display=fieldCommandDisplay }, --15 back/exit(14)
{ load=nil, save=fieldDeviceIdSelect, display=fieldCommandDisplay }, --16 device(15)
{ load=nil, save=fieldFolderDeviceOpen, display=fieldFolderDisplay }, --17 deviceFOLDER(16)
}
local function parseParameterInfoMessage(data)
local fieldId = (fieldPopup and fieldPopup.id) or loadQ[#loadQ]
if data[2] ~= deviceId or data[3] ~= fieldId then
fieldData = nil
fieldChunk = 0
return
end
local field = fields[fieldId]
local chunksRemain = data[4]
-- If no field or the chunksremain changed when we have data, don't continue
if not field or (fieldData and chunksRemain ~= expectChunksRemain) then
return
end
local offset
-- If data is chunked, copy it to persistent buffer
if chunksRemain > 0 or fieldChunk > 0 then
fieldData = fieldData or {}
for i=5, #data do
fieldData[#fieldData + 1] = data[i]
data[i] = nil
end
offset = 1
else
-- All data arrived in one chunk, operate directly on data
fieldData = data
offset = 5
end
if chunksRemain > 0 then
fieldChunk = fieldChunk + 1
expectChunksRemain = chunksRemain - 1
else
-- Field data stream is now complete, process into a field
loadQ[#loadQ] = nil
if #fieldData > (offset + 2) then
field.id = fieldId
field.parent = (fieldData[offset] ~= 0) and fieldData[offset] or nil
field.type = bit32.band(fieldData[offset+1], 0x7f)
field.hidden = bit32.btest(fieldData[offset+1], 0x80) or nil
field.name, offset = fieldGetStrOrOpts(fieldData, offset+2, field.name)
if functions[field.type+1].load then
functions[field.type+1].load(field, fieldData, offset)
end
if field.min == 0 then field.min = nil end
if field.max == 0 then field.max = nil end
end
fieldChunk = 0
fieldData = nil
-- Return value is if the screen should be updated
-- If deviceId is TX module, then the Bad/Good drives the update; for other
-- devices update each new item. and always update when the queue empties
return deviceId ~= 0xEE or #loadQ == 0
end
end
local function parseElrsInfoMessage(data)
if data[2] ~= deviceId then
fieldData = nil
fieldChunk = 0
return
end
local badPkt = data[3]
local goodPkt = (data[4]*256) + data[5]
local newFlags = data[6]
-- If flags are changing, reset the warning timeout to display/hide message immediately
if newFlags ~= elrsFlags then
elrsFlags = newFlags
titleShowWarnTimeout = 0
end
elrsFlagsInfo = fieldGetStrOrOpts(data, 7)
local state = (bit32.btest(elrsFlags, 1) and "C") or "-"
goodBadPkt = string.format("%u/%u %s", badPkt, goodPkt, state)
end
local function parseElrsV1Message(data)
if (data[1] ~= 0xEA) or (data[2] ~= 0xEE) then
return
end
-- local badPkt = data[9]
-- local goodPkt = (data[10]*256) + data[11]
-- goodBadPkt = string.format("%u/%u X", badPkt, goodPkt)
fieldPopup = {id = 0, status = 2, timeout = 0xFF, info = "ERROR: 1.x firmware"}
fieldTimeout = getTime() + 0xFFFF
end
local function refreshNext(skipPush)
local command, data, forceRedraw
repeat
command, data = crossfireTelemetryPop()
if command == 0x29 then
parseDeviceInfoMessage(data)
elseif command == 0x2B then
if parseParameterInfoMessage(data) then
forceRedraw = true
end
if #loadQ > 0 then
fieldTimeout = 0 -- request next chunk immediately
elseif fieldPopup then
fieldTimeout = getTime() + fieldPopup.timeout
end
elseif command == 0x2D then
parseElrsV1Message(data)
elseif command == 0x2E then
parseElrsInfoMessage(data)
forceRedraw = true
end
until command == nil
-- Don't even bother with return value, skipPush implies redraw
if skipPush then return end
local time = getTime()
if fieldPopup then
if time > fieldTimeout and fieldPopup.status ~= 3 then
crossfireTelemetryPush(0x2D, { deviceId, handsetId, fieldPopup.id, 6 }) -- lcsQuery
fieldTimeout = time + fieldPopup.timeout
end
elseif time > devicesRefreshTimeout and #devices == 0 then
forceRedraw = true -- handles initial screen draw
devicesRefreshTimeout = time + 100 -- 1s
crossfireTelemetryPush(0x28, { 0x00, 0xEA })
elseif time > linkstatTimeout then
if deviceIsELRS_TX then
crossfireTelemetryPush(0x2D, { deviceId, handsetId, 0x0, 0x0 }) --request linkstat
else
goodBadPkt = ""
end
linkstatTimeout = time + 100
elseif time > fieldTimeout and fields_count ~= 0 then
if #loadQ > 0 then
crossfireTelemetryPush(0x2C, { deviceId, handsetId, loadQ[#loadQ], fieldChunk })
fieldTimeout = time + 500 -- 5s
end
end
if time > titleShowWarnTimeout then
-- if elrsFlags bit set is bit higher than bit 0 and bit 1, it is warning flags
titleShowWarn = (elrsFlags > 3 and not titleShowWarn) or nil
titleShowWarnTimeout = time + 100
forceRedraw = true
end
return forceRedraw
end
local lcd_title -- holds function that is color/bw version
local function lcd_title_color()
lcd.clear()
local EBLUE = lcd.RGB(0x43, 0x61, 0xAA)
local EGREEN = lcd.RGB(0x9f, 0xc7, 0x6f)
local EGREY1 = lcd.RGB(0x91, 0xb2, 0xc9)
local EGREY2 = lcd.RGB(0x6f, 0x62, 0x7f)
-- Field display area (white w/ 2px green border)
lcd.setColor(CUSTOM_COLOR, EGREEN)
lcd.drawRectangle(0, 0, LCD_W, LCD_H, CUSTOM_COLOR)
lcd.drawRectangle(1, 0, LCD_W - 2, LCD_H - 1, CUSTOM_COLOR)
-- title bar
lcd.drawFilledRectangle(0, 0, LCD_W, barHeight, CUSTOM_COLOR)
lcd.setColor(CUSTOM_COLOR, EGREY1)
lcd.drawFilledRectangle(LCD_W - textSize, 0, textSize, barHeight, CUSTOM_COLOR)
lcd.setColor(CUSTOM_COLOR, EGREY2)
lcd.drawRectangle(LCD_W - textSize, 0, textSize, barHeight - 1, CUSTOM_COLOR)
lcd.drawRectangle(LCD_W - textSize, 1 , textSize - 1, barHeight - 2, CUSTOM_COLOR) -- left and bottom line only 1px, make it look bevelled
lcd.setColor(CUSTOM_COLOR, BLACK)
if titleShowWarn then
lcd.drawText(COL1 + 1, barTextSpacing, elrsFlagsInfo, CUSTOM_COLOR)
else
lcd.drawText(COL1 + 1, barTextSpacing, deviceName, CUSTOM_COLOR)
lcd.drawText(LCD_W - 5, barTextSpacing, goodBadPkt, RIGHT + BOLD + CUSTOM_COLOR)
end
-- progress bar
if #loadQ > 0 and fields_count > 0 then
local barW = (COL2-4) * (fields_count - #loadQ) / fields_count
lcd.setColor(CUSTOM_COLOR, EBLUE)
lcd.drawFilledRectangle(2, barTextSpacing/2+textSize, barW, barTextSpacing, CUSTOM_COLOR)
lcd.setColor(CUSTOM_COLOR, WHITE)
lcd.drawFilledRectangle(2+barW, barTextSpacing/2+textSize, COL2-2-barW, barTextSpacing, CUSTOM_COLOR)
end
end
local function lcd_title_bw()
lcd.clear()
-- B&W screen
local barHeight = 9
if not titleShowWarn then
lcd.drawText(LCD_W - 1, 1, goodBadPkt, RIGHT)
lcd.drawLine(LCD_W - 10, 0, LCD_W - 10, barHeight-1, SOLID, INVERS)
end
if #loadQ > 0 and fields_count > 0 then
lcd.drawFilledRectangle(COL2, 0, LCD_W, barHeight, GREY_DEFAULT)
lcd.drawGauge(0, 0, COL2, barHeight, fields_count - #loadQ, fields_count, 0)
else
lcd.drawFilledRectangle(0, 0, LCD_W, barHeight, GREY_DEFAULT)
if titleShowWarn then
lcd.drawText(COL1, 1, elrsFlagsInfo, INVERS)
else
lcd.drawText(COL1, 1, deviceName, INVERS)
end
end
end
local function lcd_warn()
lcd.drawText(COL1, textSize*2, "Error:")
lcd.drawText(COL1, textSize*3, elrsFlagsInfo)
lcd.drawText(LCD_W/2, textSize*5, "[OK]", BLINK + INVERS + CENTER)
end
local function reloadRelatedFields(field)
-- Reload the parent folder to update the description
if field.parent then
loadQ[#loadQ+1] = field.parent
fields[field.parent].name = nil
end
-- Reload all editable fields at the same level as well as the parent item
for fieldId = fields_count, 1, -1 do
-- Skip this field, will be added to end
local fldTest = fields[fieldId]
local fldType = fldTest.type or 99 -- type could be nil if still loading
if fieldId ~= field.id
and fldTest.parent == field.parent
and (fldType < 11 or fldType == 12) then -- ignores FOLDER/COMMAND/devices/EXIT
fldTest.nc = true -- "no cache" the options
loadQ[#loadQ+1] = fieldId
end
end
-- Reload this field
loadQ[#loadQ+1] = field.id
-- with a short delay to allow the module EEPROM to commit
fieldTimeout = getTime() + 20
-- Also push the next bad/good update further out
linkstatTimeout = fieldTimeout + 100
end
local function handleDevicePageEvent(event)
if #fields == 0 then --if there is no field yet
return
else
if fields[#fields].name == nil then --if back button is not assigned yet, means there is no field yet.
return
end
end
if event == EVT_VIRTUAL_EXIT then -- Cancel edit / go up a folder / reload all
if edit then
edit = nil
reloadCurField()
else
if currentFolderId == nil and #loadQ == 0 then -- only do reload if we're in the root folder and finished loading
if deviceId ~= 0xEE then
changeDeviceId(0xEE)
else
reloadAllField()
end
crossfireTelemetryPush(0x28, { 0x00, 0xEA })
else
fieldBackExec(fields[#fields])
end
end
elseif event == EVT_VIRTUAL_ENTER then -- toggle editing/selecting current field
if elrsFlags > 0x1F then
elrsFlags = 0
crossfireTelemetryPush(0x2D, { deviceId, handsetId, 0x2E, 0x00 })
else
local field = getField(lineIndex)
if field and field.name then
-- Editable fields
if not field.grey and field.type < 10 then
edit = not edit
if not edit then
reloadRelatedFields(field)
end
end
if not edit then
if functions[field.type+1].save then
functions[field.type+1].save(field)
end
end
end
end
elseif edit then
if event == EVT_VIRTUAL_NEXT then
incrField(1)
elseif event == EVT_VIRTUAL_PREV then
incrField(-1)
end
else
if event == EVT_VIRTUAL_NEXT then
selectField(1)
elseif event == EVT_VIRTUAL_PREV then
selectField(-1)
end
end
end
-- Main
local function runDevicePage(event)
handleDevicePageEvent(event)
lcd_title()
if #devices > 1 then -- show other device folder
fields[fields_count+1].parent = nil
end
if elrsFlags > 0x1F then
lcd_warn()
else
for y = 1, maxLineIndex+1 do
local field = getField(pageOffset+y)
if not field then
break
elseif field.name ~= nil then
local attr = lineIndex == (pageOffset+y)
and ((edit and BLINK or 0) + INVERS)
or 0
local color = field.grey and COLOR_THEME_DISABLED or 0
if field.type < 11 or field.type == 12 then -- if not folder, command, or back
lcd.drawText(COL1, y*textSize+textYoffset, field.name, color)
end
if functions[field.type+1].display then
functions[field.type+1].display(field, y*textSize+textYoffset, attr, color)
end
end
end
end
end
local function popupCompat(t, m, e)
-- Only use 2 of 3 arguments for older platforms
return popupConfirmation(t, e)
end
local function runPopupPage(event)
if event == EVT_VIRTUAL_EXIT then
crossfireTelemetryPush(0x2D, { deviceId, handsetId, fieldPopup.id, 5 }) -- lcsCancel
fieldTimeout = getTime() + 200 -- 2s
end
if fieldPopup.status == 0 and fieldPopup.lastStatus ~= 0 then -- stopped
popupCompat(fieldPopup.info, "Stopped!", event)
reloadAllField()
fieldPopup = nil
elseif fieldPopup.status == 3 then -- confirmation required
local result = popupCompat(fieldPopup.info, "PRESS [OK] to confirm", event)
fieldPopup.lastStatus = fieldPopup.status
if result == "OK" then
crossfireTelemetryPush(0x2D, { deviceId, handsetId, fieldPopup.id, 4 }) -- lcsConfirmed
fieldTimeout = getTime() + fieldPopup.timeout -- we are expecting an immediate response
fieldPopup.status = 4
elseif result == "CANCEL" then
fieldPopup = nil
end
elseif fieldPopup.status == 2 then -- running
if fieldChunk == 0 then
commandRunningIndicator = (commandRunningIndicator % 4) + 1
end
local result = popupCompat(fieldPopup.info .. " [" .. string.sub("|/-\\", commandRunningIndicator, commandRunningIndicator) .. "]", "Press [RTN] to exit", event)
fieldPopup.lastStatus = fieldPopup.status
if result == "CANCEL" then
crossfireTelemetryPush(0x2D, { deviceId, handsetId, fieldPopup.id, 5 }) -- lcsCancel
fieldTimeout = getTime() + fieldPopup.timeout -- we are expecting an immediate response
fieldPopup = nil
end
end
end
local function touch2evt(event, touchState)
-- Convert swipe events to normal events Left/Right/Up/Down -> EXIT/ENTER/PREV/NEXT
-- PREV/NEXT are swapped if editing
-- TAP is converted to ENTER
touchState = touchState or {}
return (touchState.swipeLeft and EVT_VIRTUAL_EXIT)
or (touchState.swipeRight and EVT_VIRTUAL_ENTER)
or (touchState.swipeUp and (edit and EVT_VIRTUAL_NEXT or EVT_VIRTUAL_PREV))
or (touchState.swipeDown and (edit and EVT_VIRTUAL_PREV or EVT_VIRTUAL_NEXT))
or (event == EVT_TOUCH_TAP and EVT_VIRTUAL_ENTER)
end
local function setLCDvar()
-- Set the title function depending on if LCD is color, and free the other function and
-- set textselection unit function, use GetLastPost or sizeText
if (lcd.RGB ~= nil) then
lcd_title = lcd_title_color
functions[10].display = fieldTextSelDisplay_color
else
lcd_title = lcd_title_bw
functions[10].display = fieldTextSelDisplay_bw
touch2evt = nil
end
lcd_title_color = nil
lcd_title_bw = nil
fieldTextSelDisplay_bw = nil
fieldTextSelDisplay_color = nil
-- Determine if popupConfirmation takes 3 arguments or 2
-- if pcall(popupConfirmation, "", "", EVT_VIRTUAL_EXIT) then
-- major 1 is assumed to be FreedomTX
local _, _, major = getVersion()
if major ~= 1 then
popupCompat = popupConfirmation
end
if (lcd.RGB ~= nil) then
local ver, radio, maj, minor, rev, osname = getVersion()
if osname ~= nil and osname == "EdgeTX" then
textWidth, textSize = lcd.sizeText("Qg") -- determine standard font height for EdgeTX
else
textSize = 21 -- use this for OpenTX
end
COL1 = 3
COL2 = LCD_W/2
barTextSpacing = 4
barHeight = textSize + barTextSpacing + barTextSpacing
textYoffset = 2 * barTextSpacing + 2
maxLineIndex = math.floor(((LCD_H - barHeight - textYoffset) / textSize)) - 1
else
if LCD_W == 212 then
COL2 = 110
else
COL2 = 70
end
if LCD_H == 96 then
maxLineIndex = 9
else
maxLineIndex = 6
end
COL1 = 0
textYoffset = 3
textSize = 8
end
end
local function setMock()
-- Setup fields to display if running in Simulator
local _, rv = getVersion()
if string.sub(rv, -5) ~= "-simu" then return end
local mock = loadScript("mockup/elrsmock.lua")
if mock == nil then return end
fields, goodBadPkt, deviceName = mock()
fields_count = #fields - 1
loadQ = { fields_count }
deviceIsELRS_TX = true
end
local function checkCrsfModule()
-- Loop through the modules and look for one set to CRSF (5)
for modIdx = 0, 1 do
local mod = model.getModule(modIdx)
if mod and (mod.Type == nil or mod.Type == 5) then
-- CRSF found
checkCrsfModule = nil
return 0
end
end
-- No CRSF module found, save an error message for run()
lcd.clear()
local y = 0
lcd.drawText(2, y, " No ExpressLRS", MIDSIZE)
y = y + (textSize * 2) - 2
local msgs = {
" Enable a CRSF Internal",
" or External module in",
" Model settings",
" If module is internal",
" also set Internal RF to",
" CRSF in SYS->Hardware",
}
for i, msg in ipairs(msgs) do
lcd.drawText(2, y, msg)
y = y + textSize
if i == 3 then
lcd.drawLine(0, y, LCD_W, y, SOLID, INVERS)
y = y + 2
end
end
return 0
end
-- Init
local function init()
setLCDvar()
setMock()
setLCDvar = nil
setMock = nil
end
-- Main
local function run(event, touchState)
if event == nil then return 2 end
if checkCrsfModule then return checkCrsfModule() end
event = (touch2evt and touch2evt(event, touchState)) or event
-- If ENTER pressed, skip any pushing this loop to reserve queue for the save command
local forceRedraw = refreshNext(event == EVT_VIRTUAL_ENTER)
if fieldPopup ~= nil then
runPopupPage(event)
elseif event ~= 0 or forceRedraw or edit then
runDevicePage(event)
end
return exitscript
end
return { init=init, run=run }
| 412 | 0.909677 | 1 | 0.909677 | game-dev | MEDIA | 0.340831 | game-dev | 0.795873 | 1 | 0.795873 |
sstsimulator/sst-elements | 3,476 | src/sst/elements/firefly/ctrlMsgFunctors.h | // Copyright 2009-2025 NTESS. Under the terms
// of Contract DE-NA0003525 with NTESS, the U.S.
// Government retains certain rights in this software.
//
// Copyright (c) 2009-2025, NTESS
// All rights reserved.
//
// Portions are copyright of other developers:
// See the file CONTRIBUTORS.TXT in the top level directory
// of the distribution for more information.
//
// This file is part of the SST software package. For license
// information, see the LICENSE file in the top level directory of the
// distribution.
#ifndef COMPONENTS_FIREFLY_CTRLMSGFUNCTORS_H
#define COMPONENTS_FIREFLY_CTRLMSGFUNCTORS_H
namespace SST {
namespace Firefly {
namespace CtrlMsg {
template< class TRetval = void >
class FunctorBase_0 {
public:
virtual TRetval operator()() = 0;
virtual ~FunctorBase_0() {}
};
template< class T1, class TRetval = void >
class FunctorBase_1 {
public:
virtual TRetval operator()(T1) = 0;
virtual ~FunctorBase_1() {}
};
template< class T1, class T2, class TRetval = void >
class FunctorBase_2 {
public:
virtual TRetval operator()(T1,T2) = 0;
virtual ~FunctorBase_2() {}
};
template< class T1, class T2, class T3, class TRetval = void >
class FunctorBase_3 {
public:
virtual TRetval operator()(T1,T2,T3) = 0;
virtual ~FunctorBase_3() {}
};
template <class T1, class TRetval = void >
class Functor_0 : public FunctorBase_0< TRetval >
{
private:
T1* m_obj;
TRetval ( T1::*m_fptr )();
public:
Functor_0( T1* obj, TRetval ( T1::*fptr )( ) ) :
m_obj( obj ),
m_fptr( fptr )
{ }
virtual TRetval operator()() {
return (*m_obj.*m_fptr)();
}
};
template <class T1, class T2, class TRetval = void >
class Functor_1 : public FunctorBase_1< T2, TRetval >
{
private:
T1* m_obj;
TRetval ( T1::*m_fptr )(T2);
public:
Functor_1( T1* obj, TRetval ( T1::*fptr )( T2 ) ) :
m_obj( obj ),
m_fptr( fptr )
{ }
virtual TRetval operator()( T2 arg ) {
return (*m_obj.*m_fptr)( arg );
}
};
template <class T1, class T2, class TRetval = void >
class FunctorStatic_0 : public FunctorBase_0< TRetval >
{
private:
T1* m_obj;
TRetval ( T1::*m_fptr )( T2 );
T2 m_arg;
public:
FunctorStatic_0( T1* obj, TRetval ( T1::*fptr )( T2 ), T2 arg ) :
m_obj( obj ),
m_fptr( fptr ),
m_arg( arg )
{ }
virtual TRetval operator()() {
return (*m_obj.*m_fptr)( m_arg );
}
};
template <class T1, class T2, class T3, class TRetval = void >
class FunctorStatic_1 : public FunctorBase_1< T3, TRetval >
{
private:
T1* m_obj;
TRetval ( T1::*m_fptr )( T2, T3 );
T2 m_arg;
public:
FunctorStatic_1( T1* obj, TRetval ( T1::*fptr )( T2, T3 ), T2 arg ) :
m_obj( obj ),
m_fptr( fptr ),
m_arg( arg )
{ }
virtual TRetval operator()( T3 arg ) {
return (*m_obj.*m_fptr)( m_arg, arg );
}
};
template <class T1, class T2, class T3, class T4, class T5, class TRetval = void >
class FunctorStatic_3 : public FunctorBase_3< T3, T4, T5, TRetval >
{
private:
T1* m_obj;
TRetval ( T1::*m_fptr )( T2, T3, T4, T5 );
T2 m_arg;
public:
FunctorStatic_3( T1* obj, TRetval ( T1::*fptr )( T2, T3, T4, T5), T2 arg ) :
m_obj( obj ),
m_fptr( fptr ),
m_arg( arg )
{ }
virtual TRetval operator()( T3 arg1, T4 arg2, T5 arg3) {
return (*m_obj.*m_fptr)( m_arg, arg1, arg2, arg3 );
}
};
}
}
}
#endif
| 412 | 0.850023 | 1 | 0.850023 | game-dev | MEDIA | 0.244241 | game-dev | 0.831053 | 1 | 0.831053 |
DirtPowered/DirtMultiversion | 2,695 | src/main/java/com/github/dirtpowered/dirtmv/data/protocol/types/PositionArrayDataType.java | /*
* Copyright (c) 2020-2022 Dirt Powered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.dirtpowered.dirtmv.data.protocol.types;
import com.github.dirtpowered.dirtmv.data.protocol.DataType;
import com.github.dirtpowered.dirtmv.data.protocol.Type;
import com.github.dirtpowered.dirtmv.data.protocol.TypeHolder;
import com.github.dirtpowered.dirtmv.data.protocol.io.model.PacketInput;
import com.github.dirtpowered.dirtmv.data.protocol.io.model.PacketOutput;
import com.github.dirtpowered.dirtmv.data.protocol.objects.BlockLocation;
public class PositionArrayDataType extends DataType<BlockLocation[]> {
public PositionArrayDataType() {
super(Type.POSITION_ARRAY);
}
@Override
public BlockLocation[] read(PacketInput packetInput) {
int blockAmount = packetInput.readInt();
BlockLocation[] blockLocations = new BlockLocation[blockAmount];
for (int i = 0; i < blockAmount; i++) {
int locX = packetInput.readByte();
int locY = packetInput.readByte();
int locZ = packetInput.readByte();
blockLocations[i] = new BlockLocation(locX, locY, locZ);
}
return blockLocations;
}
@Override
public void write(TypeHolder typeHolder, PacketOutput packetOutput) {
BlockLocation[] blockLocations = (BlockLocation[]) typeHolder.getObject();
packetOutput.writeInt(blockLocations.length);
for (BlockLocation record : blockLocations) {
packetOutput.writeByte(record.getX());
packetOutput.writeByte(record.getY());
packetOutput.writeByte(record.getZ());
}
}
}
| 412 | 0.638953 | 1 | 0.638953 | game-dev | MEDIA | 0.694819 | game-dev,networking | 0.629108 | 1 | 0.629108 |
pret/pokeplatinum | 2,482 | src/overlay094/screens/pokemon_summary.c | #include "overlay094/screens/pokemon_summary.h"
#include <dwc.h>
#include <nitro.h>
#include <string.h>
#include "applications/pokemon_summary_screen/main.h"
#include "overlay094/application.h"
#include "overlay094/gts_application_state.h"
#include "overlay094/screens/select_pokemon.h"
#include "overlay_manager.h"
#include "unk_0202D778.h"
#include "constdata/const_020F410C.h"
static const u8 sGTSPokemonSummaryPages[] = {
SUMMARY_PAGE_INFO,
SUMMARY_PAGE_MEMO,
SUMMARY_PAGE_SKILLS,
SUMMARY_PAGE_CONDITION,
SUMMARY_PAGE_BATTLE_MOVES,
SUMMARY_PAGE_CONTEST_MOVES,
SUMMARY_PAGE_RIBBONS,
SUMMARY_PAGE_EXIT,
SUMMARY_PAGE_MAX
};
int GTSApplication_PokemonSummary_Init(GTSApplicationState *appState, int unused1)
{
appState->pokemonSummary.monData = ov94_022411DC(appState->playerData->party, appState->playerData->pcBoxes, appState->selectedBoxId, appState->unk_112);
appState->pokemonSummary.dataType = SUMMARY_DATA_BOX_MON;
appState->pokemonSummary.monMax = 1;
appState->pokemonSummary.monIndex = 0;
appState->pokemonSummary.mode = SUMMARY_MODE_LOCK_MOVES;
appState->pokemonSummary.move = 0;
appState->pokemonSummary.showContest = PokemonSummaryScreen_ShowContestData(appState->playerData->saveData);
appState->pokemonSummary.dexMode = appState->playerData->dexMode;
appState->pokemonSummary.options = appState->playerData->options;
appState->pokemonSummary.specialRibbons = sub_0202D79C(appState->playerData->saveData);
PokemonSummaryScreen_FlagVisiblePages(&appState->pokemonSummary, sGTSPokemonSummaryPages);
PokemonSummaryScreen_SetPlayerProfile(&appState->pokemonSummary, appState->playerData->trainerInfo);
appState->appMan = ApplicationManager_New(&gPokemonSummaryScreenApp, &appState->pokemonSummary, HEAP_ID_62);
appState->hasTradedPokemon = TRUE;
return GTS_LOOP_STATE_WAIT_FADE;
}
int GTSApplication_PokemonSummary_Main(GTSApplicationState *appState, int unused1)
{
int loopState = GTS_LOOP_STATE_MAIN;
if (ApplicationManager_Exec(appState->appMan)) {
ApplicationManager_Free(appState->appMan);
GTSApplication_SetNextScreenWithArgument(appState, GTS_SCREEN_SELECT_POKEMON, appState->screenArgument);
loopState = GTS_LOOP_STATE_FINISH;
}
return loopState;
}
int GTSApplication_PokemonSummary_Exit(GTSApplicationState *appState, int unused1)
{
GTSApplication_MoveToNextScreen(appState);
return GTS_LOOP_STATE_INIT;
}
| 412 | 0.800434 | 1 | 0.800434 | game-dev | MEDIA | 0.538512 | game-dev | 0.934626 | 1 | 0.934626 |
DarkstarProject/darkstar | 1,297 | scripts/globals/weaponskills/raiden_thrust.lua | -----------------------------------
-- Raiden Thrust
-- Polearm weapon skill
-- Skill Level: 70
-- Deals lightning elemental damage to enemy. Damage varies with TP.
-- Aligned with the Light Gorget & Thunder Gorget.
-- Aligned with the Light Belt & Thunder Belt.
-- Element: Lightning
-- Modifiers: STR:40% INT:40%
-- 100%TP 200%TP 300%TP
-- 1.00 2.00 3.00
-----------------------------------
require("scripts/globals/magic")
require("scripts/globals/status")
require("scripts/globals/settings")
require("scripts/globals/weaponskills")
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {}
params.ftp100 = 1 params.ftp200 = 2 params.ftp300 = 3
params.str_wsc = 0.3 params.dex_wsc = 0.0 params.vit_wsc = 0.0 params.agi_wsc = 0.0 params.int_wsc = 0.3 params.mnd_wsc = 0.0 params.chr_wsc = 0.0
params.ele = dsp.magic.ele.LIGHTNING
params.skill = dsp.skill.POLEARM
params.includemab = true
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 0.4 params.int_wsc = 0.4
end
local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, wsID, params, tp, action, primary)
return tpHits, extraHits, criticalHit, damage
end
| 412 | 0.884643 | 1 | 0.884643 | game-dev | MEDIA | 0.970942 | game-dev | 0.824655 | 1 | 0.824655 |
It-Life/Deer_GameFramework_Wolong | 2,725 | Assets/GameFramework/Libraries/Resource/ResourceManager.ResourceLoader.LoadBinaryInfo.cs | //------------------------------------------------------------
// Game Framework
// Copyright © 2013-2021 Jiang Yin. All rights reserved.
// Homepage: https://gameframework.cn/
// Feedback: mailto:ellan@gameframework.cn
//------------------------------------------------------------
namespace GameFramework.Resource
{
internal sealed partial class ResourceManager : GameFrameworkModule, IResourceManager
{
private sealed partial class ResourceLoader
{
private sealed class LoadBinaryInfo : IReference
{
private string m_BinaryAssetName;
private ResourceInfo m_ResourceInfo;
private LoadBinaryCallbacks m_LoadBinaryCallbacks;
private object m_UserData;
public LoadBinaryInfo()
{
m_BinaryAssetName = null;
m_ResourceInfo = null;
m_LoadBinaryCallbacks = null;
m_UserData = null;
}
public string BinaryAssetName
{
get
{
return m_BinaryAssetName;
}
}
public ResourceInfo ResourceInfo
{
get
{
return m_ResourceInfo;
}
}
public LoadBinaryCallbacks LoadBinaryCallbacks
{
get
{
return m_LoadBinaryCallbacks;
}
}
public object UserData
{
get
{
return m_UserData;
}
}
public static LoadBinaryInfo Create(string binaryAssetName, ResourceInfo resourceInfo, LoadBinaryCallbacks loadBinaryCallbacks, object userData)
{
LoadBinaryInfo loadBinaryInfo = ReferencePool.Acquire<LoadBinaryInfo>();
loadBinaryInfo.m_BinaryAssetName = binaryAssetName;
loadBinaryInfo.m_ResourceInfo = resourceInfo;
loadBinaryInfo.m_LoadBinaryCallbacks = loadBinaryCallbacks;
loadBinaryInfo.m_UserData = userData;
return loadBinaryInfo;
}
public void Clear()
{
m_BinaryAssetName = null;
m_ResourceInfo = null;
m_LoadBinaryCallbacks = null;
m_UserData = null;
}
}
}
}
}
| 412 | 0.68989 | 1 | 0.68989 | game-dev | MEDIA | 0.459009 | game-dev | 0.712048 | 1 | 0.712048 |
annulusgames/MagicTween | 4,121 | MagicTween/Assets/MagicTween/Runtime/Core/Systems/StandardTweenSystemBase.cs | using MagicTween.Core.Components;
using Unity.Burst;
using Unity.Burst.Intrinsics;
using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
namespace MagicTween.Core.Systems
{
[BurstCompile]
[UpdateInGroup(typeof(MagicTweenUpdateSystemGroup))]
[RequireMatchingQueriesForUpdate]
public abstract partial class StandardTweenSystemBase<TValue, TOptions, TPlugin> : SystemBase
where TValue : unmanaged
where TOptions : unmanaged, ITweenOptions
where TPlugin : unmanaged, ICustomTweenPlugin<TValue, TOptions>
{
EntityQuery query;
[BurstCompile]
protected override void OnCreate()
{
query = SystemAPI.QueryBuilder()
.WithAspect<TweenAspect>()
.WithAll<TweenValue<TValue>, TweenStartValue<TValue>, TweenEndValue<TValue>, TweenOptions<TOptions>, TweenPluginTag<TPlugin>>()
.Build();
}
[BurstCompile]
protected override void OnUpdate()
{
var job = new SystemJob()
{
valueTypeHandle = SystemAPI.GetComponentTypeHandle<TweenValue<TValue>>(),
startValueTypeHandle = SystemAPI.GetComponentTypeHandle<TweenStartValue<TValue>>(true),
endValueTypeHandle = SystemAPI.GetComponentTypeHandle<TweenEndValue<TValue>>(true),
optionsTypeHandle = SystemAPI.GetComponentTypeHandle<TweenOptions<TOptions>>(true),
progressTypeHandle = SystemAPI.GetComponentTypeHandle<TweenProgress>(true),
isInvertedTypeHandle = SystemAPI.GetComponentTypeHandle<TweenInvertFlag>(true),
isRelativeTypeHandle = SystemAPI.GetComponentTypeHandle<TweenParameterIsRelative>(true),
};
Dependency = job.ScheduleParallel(query, Dependency);
}
[BurstCompile]
unsafe struct SystemJob : IJobChunk
{
readonly TPlugin plugin;
public ComponentTypeHandle<TweenValue<TValue>> valueTypeHandle;
[ReadOnly] public ComponentTypeHandle<TweenStartValue<TValue>> startValueTypeHandle;
[ReadOnly] public ComponentTypeHandle<TweenEndValue<TValue>> endValueTypeHandle;
[ReadOnly] public ComponentTypeHandle<TweenOptions<TOptions>> optionsTypeHandle;
[ReadOnly] public ComponentTypeHandle<TweenProgress> progressTypeHandle;
[ReadOnly] public ComponentTypeHandle<TweenInvertFlag> isInvertedTypeHandle;
[ReadOnly] public ComponentTypeHandle<TweenParameterIsRelative> isRelativeTypeHandle;
[BurstCompile]
public void Execute(in ArchetypeChunk chunk, int unfilteredChunkIndex, bool useEnabledMask, in v128 chunkEnabledMask)
{
var valueArrayPtr = chunk.GetComponentDataPtrRW(ref valueTypeHandle);
var startValueArrayPtr = chunk.GetComponentDataPtrRO(ref startValueTypeHandle);
var endValueArrayPtr = chunk.GetComponentDataPtrRO(ref endValueTypeHandle);
var optionsArrayPtr = chunk.GetComponentDataPtrRO(ref optionsTypeHandle);
var progressArrayPtr = chunk.GetComponentDataPtrRO(ref progressTypeHandle);
var isInvertedArrayPtr = chunk.GetComponentDataPtrRO(ref isInvertedTypeHandle);
var isRelativeArrayPtr = chunk.GetComponentDataPtrRO(ref isRelativeTypeHandle);
for (int i = 0; i < chunk.Count; i++)
{
var context = new TweenEvaluationContext(
(progressArrayPtr + i)->value,
(isRelativeArrayPtr + i)->value,
(isInvertedArrayPtr + i)->value
);
var currentValue = plugin.Evaluate(
(startValueArrayPtr + i)->value,
(endValueArrayPtr + i)->value,
(optionsArrayPtr + i)->value,
context
);
(valueArrayPtr + i)->value = currentValue;
}
}
}
}
} | 412 | 0.873758 | 1 | 0.873758 | game-dev | MEDIA | 0.823156 | game-dev | 0.917621 | 1 | 0.917621 |
dual-universe/mydu-server-mods | 4,115 | APIReference/Services/IScenegraph.cs | using NQ;
#nullable enable
namespace Backend.Scenegraph
{
public interface IScenegraph
{
/// <summary>
/// returns the position of the center of a construct (depends of the size)
/// </summary>
/// <param name="constructId"></param>
/// <param name="size"></param>
/// <returns>Center position</returns>
Task<Vec3> GetCenterWorldPosition(ConstructId constructId, long size);
/// <summary>
/// returns the position of the center of a construct when you don't know its size.
/// </summary>
/// <param name="constructId"></param>
/// <returns></returns>
Task<Vec3> GetConstructCenterWorldPosition(ConstructId constructId);
/// <summary>
/// Compute the world position from a relative location
/// NOTE : throws if the construct doesn't exists
/// </summary>
Task<RelativeLocation> ResolveWorldLocation(RelativeLocation loc);
/// <summary>
/// Compute the position of a position relative to a construct
/// NOTE : throws if a construct doesn't exists
/// </summary>
Task<RelativeLocation> ResolveRelativeLocation(RelativeLocation loc, ConstructId target);
/// <summary>
/// Batch Compute the world position from a relative location
/// NOTE : can return a null entry if the construct doesn't exists
/// </summary>
Task<RelativeLocation?[]> BatchResolveWorldLocations(RelativeLocation[] locs);
/// <summary>
/// Batch Compute the position of a position relative to a construct
/// NOTE : can return a null entry if a construct doesn't exists
/// </summary>
Task<RelativeLocation?[]> BatchResolveRelativeLocations(RelativeLocation[] locs, ConstructId target);
/// <summary>
/// Compute the distance² between p1 and p2
/// NOTE : throws if a construct doesn't exists
/// </summary>
Task<double> Distance2(RelativeLocation p1, RelativeLocation p2);
/// <summary>
/// Compute the distance² between a player and a position
/// NOTE : throws if a construct doesn't exists
/// </summary>
Task<double> PlayerDistance2(PlayerId player, RelativeLocation pos);
/// <summary>
/// Get a player local position (works even when the player is disconnected)
/// </summary>
Task<RelativeLocation> GetPlayerLocation(PlayerId playerId);
/// <summary>
/// Get a player local position (for a connected player)
/// </summary>
Task<RelativeLocation?> GetPlayerLocalPosition(PlayerId player);
/// <summary>
/// return the relative position of all players in list
/// </summary>
/// <param name="players">list of players</param>
/// <returns>list of relative location</returns>
Task<List<RelativeLocation?>> GetPlayerLocalPositionBatch(List<PlayerId> players);
/// <summary>
/// Get a player world position (works even when the player is disconnected)
/// NOTE : throws if the player is on a non-existant construct
/// </summary>
Task<(RelativeLocation local, RelativeLocation world)> GetPlayerWorldPosition(PlayerId playerId);
/// <summary>
/// Get the position of a player, should always be valid
/// </summary>
Task<RelativeLocation> GetPlayerSafeLocation(PlayerId playerId);
Task<RelativeLocation> GetDefaultSpawnPos(PlayerId playerId);
Task<List<ConstructRelativeData>> GetTree(ConstructId constructId, bool allowLeafDeleted = true);
/// <summary>
/// returns some construct data around the given position.
/// It can't return constructs that would be too far to be visible for a regular player.
/// </summary>
/// <param name="worldPosition"></param>
/// <param name="range"></param>
/// <returns></returns>
Task<NQ.Visibility.ConstructPositions> GetConstructsInRange(Vec3 worldPosition, double range);
}
}
| 412 | 0.808156 | 1 | 0.808156 | game-dev | MEDIA | 0.76599 | game-dev | 0.843905 | 1 | 0.843905 |
AionGermany/aion-germany | 12,957 | AL-Game/src/com/aionemu/gameserver/geoEngine/models/GeoMap.java | /**
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Aion-Lightning is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License
* along with Aion-Lightning.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.aionemu.gameserver.geoEngine.models;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.aionemu.gameserver.configs.main.GeoDataConfig;
import com.aionemu.gameserver.geoEngine.bounding.BoundingBox;
import com.aionemu.gameserver.geoEngine.collision.CollisionIntention;
import com.aionemu.gameserver.geoEngine.collision.CollisionResult;
import com.aionemu.gameserver.geoEngine.collision.CollisionResults;
import com.aionemu.gameserver.geoEngine.math.Ray;
import com.aionemu.gameserver.geoEngine.math.Triangle;
import com.aionemu.gameserver.geoEngine.math.Vector3f;
import com.aionemu.gameserver.geoEngine.scene.Node;
import com.aionemu.gameserver.geoEngine.scene.Spatial;
import com.aionemu.gameserver.geoEngine.scene.mesh.DoorGeometry;
import javolution.util.FastMap;
/**
* @author Mr. Poke
*/
public class GeoMap extends Node {
private short[] terrainData;
private List<BoundingBox> tmpBox = new ArrayList<BoundingBox>();
private Map<String, DoorGeometry> doors = new FastMap<String, DoorGeometry>();
/**
* @param name
*/
public GeoMap(String name, int worldSize) {
setCollisionFlags((short) (CollisionIntention.ALL.getId() << 8));
for (int x = 0; x < worldSize; x += 256) {
for (int y = 0; y < worldSize; y += 256) {
Node geoNode = new Node("");
geoNode.setCollisionFlags((short) (CollisionIntention.ALL.getId() << 8));
tmpBox.add(new BoundingBox(new Vector3f(x, y, 0), new Vector3f(x + 256, y + 256, 4000)));
super.attachChild(geoNode);
}
}
}
public String getDoorName(int worldId, String meshFile, float x, float y, float z) {
if (!GeoDataConfig.GEO_DOORS_ENABLE) {
return null;
}
String mesh = meshFile.toUpperCase();
Vector3f templatePoint = new Vector3f(x, y, z);
float distance = Float.MAX_VALUE;
DoorGeometry foundDoor = null;
for (Entry<String, DoorGeometry> door : doors.entrySet()) {
if (!(door.getKey().startsWith(Integer.toString(worldId)) && door.getKey().endsWith(mesh))) {
continue;
}
DoorGeometry checkDoor = doors.get(door.getKey());
float doorDistance = checkDoor.getWorldBound().distanceTo(templatePoint);
if (distance > doorDistance) {
distance = doorDistance;
foundDoor = checkDoor;
}
if (checkDoor.getWorldBound().intersects(templatePoint)) {
foundDoor = checkDoor;
break;
}
}
if (foundDoor == null) {
// log.warn("Could not find static door: " + worldId + " " + meshFile + " " + templatePoint);
return null;
}
foundDoor.setFoundTemplate(true);
// log.info("Static door " + worldId + " " + meshFile + " " + templatePoint + " matched " + foundDoor.getName() +
// "; distance: " + distance);
return foundDoor.getName();
}
public void setDoorState(int instanceId, String name, boolean isOpened) {
DoorGeometry door = doors.get(name);
if (door != null) {
door.setDoorState(instanceId, isOpened);
}
}
/*
* (non-Javadoc)
* @see aionjHungary.geoEngine.scene.Node#attachChild(aionjHungary.geoEngine.scene.Spatial)
*/
@Override
public int attachChild(Spatial child) {
int i = 0;
if (child instanceof DoorGeometry) {
doors.put(child.getName(), (DoorGeometry) child);
}
for (Spatial spatial : getChildren()) {
if (tmpBox.get(i).intersects(child.getWorldBound())) {
((Node) spatial).attachChild(child);
}
i++;
}
return 0;
}
/**
* @param terrainData
* The terrainData to set.
*/
public void setTerrainData(short[] terrainData) {
this.terrainData = terrainData;
}
public float getZ(float x, float y) {
CollisionResults results = new CollisionResults(CollisionIntention.PHYSICAL.getId(), false, 1);
Vector3f pos = new Vector3f(x, y, 4000);
Vector3f dir = new Vector3f(x, y, 0);
Float limit = pos.distance(dir);
dir.subtractLocal(pos).normalizeLocal();
Ray r = new Ray(pos, dir);
r.setLimit(limit);
collideWith(r, results);
Vector3f terrain = null;
if (terrainData.length == 1) {
terrain = new Vector3f(x, y, terrainData[0] / 32f);
}
else {
terrain = terraionCollision(x, y, r);
}
if (terrain != null) {
CollisionResult result = new CollisionResult(terrain, Math.max(0, Math.max(4000 - terrain.z, terrain.z)));
results.addCollision(result);
}
if (results.size() == 0) {
return 0;
}
return results.getClosestCollision().getContactPoint().z;
}
public float getZ(float x, float y, float z, int instanceId) {
CollisionResults results = new CollisionResults(CollisionIntention.PHYSICAL.getId(), false, instanceId);
Vector3f pos = new Vector3f(x, y, z + 2);
Vector3f dir = new Vector3f(x, y, z - 100);
Float limit = pos.distance(dir);
dir.subtractLocal(pos).normalizeLocal();
Ray r = new Ray(pos, dir);
r.setLimit(limit);
collideWith(r, results);
Vector3f terrain = null;
if (terrainData.length == 1) {
if (terrainData[0] != 0) {
terrain = new Vector3f(x, y, terrainData[0] / 32f);
}
}
else {
terrain = terraionCollision(x, y, r);
}
if (terrain != null && terrain.z > 0 && terrain.z < z + 2) {
CollisionResult result = new CollisionResult(terrain, Math.abs(z - terrain.z + 2));
results.addCollision(result);
}
if (results.size() == 0) {
return z;
}
return results.getClosestCollision().getContactPoint().z;
}
public Vector3f getClosestCollision(float x, float y, float z, float targetX, float targetY, float targetZ, boolean changeDirection, boolean fly, int instanceId, byte intentions) {
float zChecked1 = 0;
float zChecked2 = 0;
if (!fly && changeDirection) {
zChecked1 = z;
z = getZ(x, y, z + 2, instanceId);
}
z += 1f;
targetZ += 1f;
Vector3f start = new Vector3f(x, y, z);
Vector3f end = new Vector3f(targetX, targetY, targetZ);
Vector3f pos = new Vector3f(x, y, z);
Vector3f dir = new Vector3f(targetX, targetY, targetZ);
CollisionResults results = new CollisionResults(intentions, false, instanceId);
Float limit = pos.distance(dir);
dir.subtractLocal(pos).normalizeLocal();
Ray r = new Ray(pos, dir);
r.setLimit(limit);
Vector3f terrain = calculateTerrainCollision(start.x, start.y, start.z, end.x, end.y, end.z, r);
if (terrain != null) {
CollisionResult result = new CollisionResult(terrain, terrain.distance(pos));
results.addCollision(result);
}
collideWith(r, results);
float geoZ = 0;
if (results.size() == 0) {
if (fly) {
return end;
}
if (zChecked1 > 0 && targetX == x && targetY == y && targetZ - 1f == zChecked1) {
geoZ = z - 1f;
}
else {
zChecked2 = targetZ;
geoZ = getZ(targetX, targetY, targetZ + 2, instanceId);
}
if (Math.abs(geoZ - targetZ) < start.distance(end)) {
return end.setZ(geoZ);
}
return start;
}
Vector3f contactPoint = results.getClosestCollision().getContactPoint();
float distance = results.getClosestCollision().getDistance();
if (distance < 1) {
return start;
}
// -1m
contactPoint = contactPoint.subtract(dir);
if (!fly && changeDirection) {
if (zChecked1 > 0 && contactPoint.x == x && contactPoint.y == y && contactPoint.z == zChecked1) {
contactPoint.z = z - 1f;
}
else if (zChecked2 > 0 && contactPoint.x == targetX && contactPoint.y == targetY && contactPoint.z == zChecked2) {
contactPoint.z = geoZ;
}
else {
contactPoint.z = getZ(contactPoint.x, contactPoint.y, contactPoint.z + 2, instanceId);
}
}
if (!fly && Math.abs(start.z - contactPoint.z) > distance) {
return start;
}
return contactPoint;
}
public CollisionResults getCollisions(float x, float y, float z, float targetX, float targetY, float targetZ, boolean changeDirection, boolean fly, int instanceId, byte intentions) {
if (!fly && changeDirection) {
z = getZ(x, y, z + 2, instanceId);
}
z += 1f;
targetZ += 1f;
Vector3f start = new Vector3f(x, y, z);
Vector3f end = new Vector3f(targetX, targetY, targetZ);
Vector3f pos = new Vector3f(x, y, z);
Vector3f dir = new Vector3f(targetX, targetY, targetZ);
CollisionResults results = new CollisionResults(intentions, false, instanceId);
Float limit = pos.distance(dir);
dir.subtractLocal(pos).normalizeLocal();
Ray r = new Ray(pos, dir);
r.setLimit(limit);
Vector3f terrain = calculateTerrainCollision(start.x, start.y, start.z, end.x, end.y, end.z, r);
if (terrain != null) {
CollisionResult result = new CollisionResult(terrain, terrain.distance(pos));
results.addCollision(result);
}
collideWith(r, results);
return results;
}
/**
* @param z
* @param targetZ
*/
private Vector3f calculateTerrainCollision(float x, float y, float z, float targetX, float targetY, float targetZ, Ray ray) {
float x2 = targetX - x;
float y2 = targetY - y;
int intD = (int) Math.abs(ray.getLimit());
for (float s = 0; s < intD; s += 2) {
float tempX = x + (x2 * s / ray.getLimit());
float tempY = y + (y2 * s / ray.getLimit());
Vector3f result = terraionCollision(tempX, tempY, ray);
if (result != null) {
return result;
}
}
return null;
}
private Vector3f terraionCollision(float x, float y, Ray ray) {
y /= 2f;
x /= 2f;
int xInt = (int) x;
int yInt = (int) y;
// p1-----p2
// || ||
// || ||
// p3-----p4
float p1, p2, p3, p4;
if (terrainData.length == 1) {
p1 = p2 = p3 = p4 = terrainData[0] / 32f;
}
else {
int size = (int) Math.sqrt(terrainData.length);
try {
int index = yInt + (xInt * size);
p1 = terrainData[index] / 32f;
p2 = terrainData[index + 1] / 32f;
p3 = terrainData[index + size] / 32f;
p4 = terrainData[index + size+ 1] / 32f;
// check if the terrain quad is removed.
if (terrainCutoutData != null) {
if (Arrays.binarySearch(terrainCutoutData, index) >= 0) {
//return false;
}
}
}
catch (Exception e) {
return null;
}
}
Vector3f result = new Vector3f();
if (p1 >= 0 && p2 >= 0 && p3 >= 0) {
Triangle tringle1 = new Triangle(new Vector3f(xInt * 2, yInt * 2, p1), new Vector3f(xInt * 2, (yInt + 1) * 2, p2), new Vector3f((xInt + 1) * 2, yInt * 2, p3));
if (ray.intersectWhere(tringle1, result)) {
return result;
}
}
if (p4 >= 0 && p2 >= 0 && p3 >= 0) {
Triangle tringle2 = new Triangle(new Vector3f((xInt + 1) * 2, (yInt + 1) * 2, p4), new Vector3f(xInt * 2, (yInt + 1) * 2, p2), new Vector3f((xInt + 1) * 2, yInt * 2, p3));
if (ray.intersectWhere(tringle2, result)) {
return result;
}
}
return null;
}
public boolean canSee(float x, float y, float z, float targetX, float targetY, float targetZ, float limit, int instanceId) {
targetZ += 1;
z += 1;
// Another fix can see in instances
// if (getZ(targetX, targetY) > targetZ)
// return false;
float x2 = x - targetX;
float y2 = y - targetY;
float distance = (float) Math.sqrt(x2 * x2 + y2 * y2);
if (distance > 80f) {
return false;
}
int intD = (int) Math.abs(distance);
Vector3f pos = new Vector3f(x, y, z);
Vector3f dir = new Vector3f(targetX, targetY, targetZ);
dir.subtractLocal(pos).normalizeLocal();
Ray r = new Ray(pos, dir);
r.setLimit(limit);
for (float s = 2; s < intD; s += 2) {
float tempX = targetX + (x2 * s / distance);
float tempY = targetY + (y2 * s / distance);
Vector3f result = terraionCollision(tempX, tempY, r);
if (result != null) {
return false;
}
}
CollisionResults results = new CollisionResults((byte) (CollisionIntention.PHYSICAL.getId() | CollisionIntention.DOOR.getId()), false, instanceId);
int collisions = this.collideWith(r, results);
return (results.size() == 0 && collisions == 0);
}
/*
* (non-Javadoc)
* @see aionjHungary.geoEngine.scene.Spatial#updateModelBound()
*/
@Override
public void updateModelBound() {
if (getChildren() != null) {
Iterator<Spatial> i = getChildren().iterator();
while (i.hasNext()) {
Spatial s = i.next();
if (s instanceof Node && ((Node) s).getChildren().isEmpty()) {
i.remove();
}
}
}
super.updateModelBound();
}
private int[] terrainCutoutData;
public void setTerrainCutouts(int[] cutoutData) {
int[] arr = cutoutData.clone();
Arrays.sort(arr);
this.terrainCutoutData = arr;
}
}
| 412 | 0.90721 | 1 | 0.90721 | game-dev | MEDIA | 0.941679 | game-dev | 0.980866 | 1 | 0.980866 |
Dark-Basic-Software-Limited/Dark-Basic-Pro | 19,706 | Dark Basic Public Shared/Dark Basic Pro SDK/Shared/Text/CPositionC.cpp | #include "cpositionc.h"
#include ".\..\error\cerror.h"
tagObjectPos* m_pTextPos;
//tagObjectPos* m_pTextPos;
//extern tagObjectPos* m_pTextPos;
//extern bool UpdatePtr ( int iID );
extern LPDIRECT3DDEVICE9 m_pD3DMatrix;
static void TextInternalUpdate ( int iID );
void GetCullDataFromModel(int);
extern bool UpdateTextPtr ( int iID );
/*
#ifdef MATRIX_DLL
extern bool UpdateMatrixPtr ( int iID );
#define UpdatePtr( p ) UpdateMatrixPtr ( p )
extern void GetMatrixCullDataFromModel(int);
#define GetCullDataFromModel( p ) GetMatrixCullDataFromModel ( p )
#endif
*/
// internal
/*
static void GetCullDataFromModel(int)
{
}
*/
float TextGetXPosition ( int iID )
{
// update internal data
if ( iID < 1 || iID > MAXIMUMVALUE )
{
RunTimeError(RUNTIMEERROR_B3DMODELNUMBERILLEGAL);
return 0;
}
if ( !UpdateTextPtr ( iID ) )
{
RunTimeError(RUNTIMEERROR_B3DMODELNOTEXISTS);
return 0;
}
return m_pTextPos->vecPosition.x;
}
float TextGetYPosition ( int iID )
{
// update internal data
if ( iID < 1 || iID > MAXIMUMVALUE )
{
RunTimeError(RUNTIMEERROR_B3DMODELNUMBERILLEGAL);
return 0;
}
if ( !UpdateTextPtr ( iID ) )
{
RunTimeError(RUNTIMEERROR_B3DMODELNOTEXISTS);
return 0;
}
return m_pTextPos->vecPosition.y;
}
float TextGetZPosition ( int iID )
{
// update internal pointer
if ( !UpdateTextPtr ( iID ) )
return 0;
return m_pTextPos->vecPosition.z;
}
float TextGetXRotation ( int iID )
{
// update internal data
if ( iID < 1 || iID > MAXIMUMVALUE )
{
RunTimeError(RUNTIMEERROR_B3DMODELNUMBERILLEGAL);
return 0;
}
if ( !UpdateTextPtr ( iID ) )
{
RunTimeError(RUNTIMEERROR_B3DMODELNOTEXISTS);
return 0;
}
return m_pTextPos->vecRotate.x;
}
float TextGetYRotation ( int iID )
{
// update internal data
if ( iID < 1 || iID > MAXIMUMVALUE )
{
RunTimeError(RUNTIMEERROR_B3DMODELNUMBERILLEGAL);
return 0;
}
if ( !UpdateTextPtr ( iID ) )
{
RunTimeError(RUNTIMEERROR_B3DMODELNOTEXISTS);
return 0;
}
return m_pTextPos->vecRotate.y;
}
float TextGetZRotation ( int iID )
{
// update internal data
if ( iID < 1 || iID > MAXIMUMVALUE )
{
RunTimeError(RUNTIMEERROR_B3DMODELNUMBERILLEGAL);
return 0;
}
if ( !UpdateTextPtr ( iID ) )
{
RunTimeError(RUNTIMEERROR_B3DMODELNOTEXISTS);
return 0;
}
return m_pTextPos->vecRotate.z;
}
static float wrapangleoffset(float da)
{
int breakout=100;
while(da<0.0f || da>=360.0f)
{
if(da<0.0f) da=da+360.0f;
if(da>=360.0f) da=da-360.0f;
breakout--;
if(breakout==0) break;
}
if(breakout==0) da=0.0f;
return da;
}
static void GetAngleFromPoint(float x1, float y1, float z1, float x2, float y2, float z2, float* ax, float* ay, float* az)
{
D3DXVECTOR3 Vector;
Vector.x = x2-x1;
Vector.y = y2-y1;
Vector.z = z2-z1;
// Find Y and then X axis rotation
double yangle=atan2(Vector.x, Vector.z);
if(yangle<0.0) yangle+=D3DXToRadian(360.0);
if(yangle>=D3DXToRadian(360.0)) yangle-=D3DXToRadian(360.0);
D3DXMATRIX yrotate;
D3DXMatrixRotationY ( &yrotate, (float)-yangle );
D3DXVec3TransformCoord ( &Vector, &Vector, &yrotate );
double xangle=-atan2(Vector.y, Vector.z);
if(xangle<0.0) xangle+=D3DXToRadian(360.0);
if(xangle>=D3DXToRadian(360.0)) xangle-=D3DXToRadian(360.0);
*ax = wrapangleoffset(D3DXToDegree((float)xangle));
*ay = wrapangleoffset(D3DXToDegree((float)yangle));
*az = 0.0f;
}
// commands
void TextScale ( int iID, float fX, float fY, float fZ )
{
// update internal data
if ( iID < 1 || iID > MAXIMUMVALUE )
{
RunTimeError(RUNTIMEERROR_B3DMODELNUMBERILLEGAL);
return;
}
if ( !UpdateTextPtr ( iID ) )
{
RunTimeError(RUNTIMEERROR_B3DMODELNOTEXISTS);
return;
}
// scale an object by the specified scale values
// set the new values
m_pTextPos->vecScale = D3DXVECTOR3 ( fX/100.0f, fY/100.0f, fZ/100.0f );
// update for clipping
GetCullDataFromModel ( iID );
// apply the changes
TextInternalUpdate ( iID );
}
void TextPosition ( int iID, float fX, float fY, float fZ )
{
// set the position of an object
// update internal data
if ( !UpdateTextPtr ( iID ) )
return;
// set the new position
m_pTextPos->vecPosition = D3DXVECTOR3 ( fX, fY, fZ );
m_pTextPos->bHasBeenMovedForResponse=true;
// apply the changes
TextInternalUpdate ( iID );
}
void TextRotate ( int iID, float fX, float fY, float fZ )
{
// update internal data
if ( iID < 1 || iID > MAXIMUMVALUE )
{
RunTimeError(RUNTIMEERROR_B3DMODELNUMBERILLEGAL);
return;
}
if ( !UpdateTextPtr ( iID ) )
{
RunTimeError(RUNTIMEERROR_B3DMODELNOTEXISTS);
return;
}
// rotate an object around all 3 axes
// store the new rotation values
m_pTextPos->vecRotate = D3DXVECTOR3 ( fX, fY, fZ );
m_pTextPos->bFreeFlightRotation = false;
// apply the changes
TextInternalUpdate ( iID );
}
void TextXRotate ( int iID, float fX )
{
// update internal data
if ( iID < 1 || iID > MAXIMUMVALUE )
{
RunTimeError(RUNTIMEERROR_B3DMODELNUMBERILLEGAL);
return;
}
if ( !UpdateTextPtr ( iID ) )
{
RunTimeError(RUNTIMEERROR_B3DMODELNOTEXISTS);
return;
}
// rotate an object around it's x axis
// store the new rotation values
// m_pTextPos->vecRotate = D3DXVECTOR3 ( fX, D3DXToDegree ( m_pTextPos->vecRotate.y ), D3DXToDegree ( m_pTextPos->vecRotate.z ) );
m_pTextPos->vecRotate = D3DXVECTOR3 ( fX, m_pTextPos->vecRotate.y, m_pTextPos->vecRotate.z );
m_pTextPos->bFreeFlightRotation = false;
// apply the changes
TextInternalUpdate ( iID );
}
void TextYRotate ( int iID, float fY )
{
// update internal data
if ( iID < 1 || iID > MAXIMUMVALUE )
{
RunTimeError(RUNTIMEERROR_B3DMODELNUMBERILLEGAL);
return;
}
if ( !UpdateTextPtr ( iID ) )
{
RunTimeError(RUNTIMEERROR_B3DMODELNOTEXISTS);
return;
}
// rotate an object around it's y axis
// store the new rotation values
m_pTextPos->vecRotate = D3DXVECTOR3 ( m_pTextPos->vecRotate.x, fY, m_pTextPos->vecRotate.z );
m_pTextPos->bFreeFlightRotation = false;
// apply the changes
TextInternalUpdate ( iID );
}
void TextZRotate ( int iID, float fZ )
{
// update internal data
if ( iID < 1 || iID > MAXIMUMVALUE )
{
RunTimeError(RUNTIMEERROR_B3DMODELNUMBERILLEGAL);
return;
}
if ( !UpdateTextPtr ( iID ) )
{
RunTimeError(RUNTIMEERROR_B3DMODELNOTEXISTS);
return;
}
// rotate an object around it's z axis
// store the new rotation values
m_pTextPos->vecRotate = D3DXVECTOR3 ( m_pTextPos->vecRotate.x, m_pTextPos->vecRotate.y, fZ );
m_pTextPos->bFreeFlightRotation = false;
// apply the changes
TextInternalUpdate ( iID );
}
void TextPoint ( int iID, float fX, float fY, float fZ )
{
// update internal data
if ( iID < 1 || iID > MAXIMUMVALUE )
{
RunTimeError(RUNTIMEERROR_B3DMODELNUMBERILLEGAL);
return;
}
if ( !UpdateTextPtr ( iID ) )
{
RunTimeError(RUNTIMEERROR_B3DMODELNOTEXISTS);
return;
}
/* LEEFIX - 041002 - LOOK not tied to rotation of object
// point an object in a direction
m_pTextPos->vecLook.x = fX - m_pTextPos->vecPosition.x;
m_pTextPos->vecLook.y = fY - m_pTextPos->vecPosition.y;
m_pTextPos->vecLook.z = fZ - m_pTextPos->vecPosition.z;
D3DXVec3Normalize(&m_pTextPos->vecLook,&m_pTextPos->vecLook);
// set the new look direction
m_pTextPos->vecLook = D3DXVECTOR3 ( fX, fY, fZ );
*/
// rotation from xyz diff
GetAngleFromPoint ( m_pTextPos->vecPosition.x, m_pTextPos->vecPosition.y, m_pTextPos->vecPosition.z,
fX, fY, fZ, &m_pTextPos->vecRotate.x, &m_pTextPos->vecRotate.y, &m_pTextPos->vecRotate.z);
// apply the changes
TextInternalUpdate ( iID );
}
void TextSetLook ( int iID, float fX, float fY, float fZ )
{
// update internal data
if ( iID < 1 || iID > MAXIMUMVALUE )
{
RunTimeError(RUNTIMEERROR_B3DMODELNUMBERILLEGAL);
return;
}
if ( !UpdateTextPtr ( iID ) )
{
RunTimeError(RUNTIMEERROR_B3DMODELNOTEXISTS);
return;
}
m_pTextPos->vecLook.x = fX;
m_pTextPos->vecLook.y = fY;
m_pTextPos->vecLook.z = fZ;
}
void TextMove ( int iID, float fStep )
{
// update internal data
if ( iID < 1 || iID > MAXIMUMVALUE )
{
RunTimeError(RUNTIMEERROR_B3DMODELNUMBERILLEGAL);
return;
}
if ( !UpdateTextPtr ( iID ) )
{
RunTimeError(RUNTIMEERROR_B3DMODELNOTEXISTS);
return;
}
// moves an object forward in it's current direction
// update internal data
if ( !UpdateTextPtr ( iID ) )
return;
// update the position vector
// m_pTextPos->vecPosition -= ( fStep * m_pTextPos->vecLook );
// m_pTextPos->vecPosition -= ( 0.1f * m_pTextPos->vecLook );
// mike : Always move INTO the Z
m_pTextPos->vecPosition += ( fStep * m_pTextPos->vecLook );
m_pTextPos->bHasBeenMovedForResponse=true;
// apply changes
TextInternalUpdate ( iID );
}
void TextMoveLeft ( int iID, float fStep )
{
// update internal data
if ( iID < 1 || iID > MAXIMUMVALUE )
{
RunTimeError(RUNTIMEERROR_B3DMODELNUMBERILLEGAL);
return;
}
if ( !UpdateTextPtr ( iID ) )
{
RunTimeError(RUNTIMEERROR_B3DMODELNOTEXISTS);
return;
}
m_pTextPos->vecPosition -= fStep * m_pTextPos->vecRight;
m_pTextPos->bHasBeenMovedForResponse=true;
TextInternalUpdate ( iID );
}
void TextMoveRight ( int iID, float fStep )
{
// update internal data
if ( iID < 1 || iID > MAXIMUMVALUE )
{
RunTimeError(RUNTIMEERROR_B3DMODELNUMBERILLEGAL);
return;
}
if ( !UpdateTextPtr ( iID ) )
{
RunTimeError(RUNTIMEERROR_B3DMODELNOTEXISTS);
return;
}
m_pTextPos->vecPosition += fStep * m_pTextPos->vecRight;
m_pTextPos->bHasBeenMovedForResponse=true;
TextInternalUpdate ( iID );
}
void TextMoveUp ( int iID, float fStep )
{
// update internal data
if ( iID < 1 || iID > MAXIMUMVALUE )
{
RunTimeError(RUNTIMEERROR_B3DMODELNUMBERILLEGAL);
return;
}
if ( !UpdateTextPtr ( iID ) )
{
RunTimeError(RUNTIMEERROR_B3DMODELNOTEXISTS);
return;
}
m_pTextPos->vecPosition += ( fStep * m_pTextPos->vecUp );
m_pTextPos->bHasBeenMovedForResponse=true;
TextInternalUpdate ( iID );
}
void TextMoveDown ( int iID, float fStep )
{
// update internal data
if ( iID < 1 || iID > MAXIMUMVALUE )
{
RunTimeError(RUNTIMEERROR_B3DMODELNUMBERILLEGAL);
return;
}
if ( !UpdateTextPtr ( iID ) )
{
RunTimeError(RUNTIMEERROR_B3DMODELNOTEXISTS);
return;
}
m_pTextPos->vecPosition -= ( fStep * m_pTextPos->vecUp );
m_pTextPos->bHasBeenMovedForResponse=true;
TextInternalUpdate ( iID );
}
void TextTurnLeft ( int iID, float fAngle )
{
// update internal data
if ( iID < 1 || iID > MAXIMUMVALUE )
{
RunTimeError(RUNTIMEERROR_B3DMODELNUMBERILLEGAL);
return;
}
if ( !UpdateTextPtr ( iID ) )
{
RunTimeError(RUNTIMEERROR_B3DMODELNOTEXISTS);
return;
}
m_pTextPos->vecYawPitchRoll.x -= fAngle;
m_pTextPos->bFreeFlightRotation = true;
TextInternalUpdate ( iID );
}
void TextTurnRight ( int iID, float fAngle )
{
// update internal data
if ( iID < 1 || iID > MAXIMUMVALUE )
{
RunTimeError(RUNTIMEERROR_B3DMODELNUMBERILLEGAL);
return;
}
if ( !UpdateTextPtr ( iID ) )
{
RunTimeError(RUNTIMEERROR_B3DMODELNOTEXISTS);
return;
}
m_pTextPos->vecYawPitchRoll.x += fAngle;
m_pTextPos->bFreeFlightRotation = true;
TextInternalUpdate ( iID );
}
void TextPitchUp ( int iID, float fAngle )
{
// update internal data
if ( iID < 1 || iID > MAXIMUMVALUE )
{
RunTimeError(RUNTIMEERROR_B3DMODELNUMBERILLEGAL);
return;
}
if ( !UpdateTextPtr ( iID ) )
{
RunTimeError(RUNTIMEERROR_B3DMODELNOTEXISTS);
return;
}
m_pTextPos->vecYawPitchRoll.y += fAngle;
m_pTextPos->bFreeFlightRotation = true;
TextInternalUpdate ( iID );
}
void TextPitchDown ( int iID, float fAngle )
{
// update internal data
if ( iID < 1 || iID > MAXIMUMVALUE )
{
RunTimeError(RUNTIMEERROR_B3DMODELNUMBERILLEGAL);
return;
}
if ( !UpdateTextPtr ( iID ) )
{
RunTimeError(RUNTIMEERROR_B3DMODELNOTEXISTS);
return;
}
m_pTextPos->vecYawPitchRoll.y -= fAngle;
m_pTextPos->bFreeFlightRotation = true;
TextInternalUpdate ( iID );
}
void TextRollLeft ( int iID, float fAngle )
{
// update internal data
if ( iID < 1 || iID > MAXIMUMVALUE )
{
RunTimeError(RUNTIMEERROR_B3DMODELNUMBERILLEGAL);
return;
}
if ( !UpdateTextPtr ( iID ) )
{
RunTimeError(RUNTIMEERROR_B3DMODELNOTEXISTS);
return;
}
m_pTextPos->vecYawPitchRoll.z -= fAngle;
m_pTextPos->bFreeFlightRotation = true;
TextInternalUpdate ( iID );
}
void TextRollRight ( int iID, float fAngle )
{
// update internal data
if ( iID < 1 || iID > MAXIMUMVALUE )
{
RunTimeError(RUNTIMEERROR_B3DMODELNUMBERILLEGAL);
return;
}
if ( !UpdateTextPtr ( iID ) )
{
RunTimeError(RUNTIMEERROR_B3DMODELNOTEXISTS);
return;
}
m_pTextPos->vecYawPitchRoll.z += fAngle;
m_pTextPos->bFreeFlightRotation = true;
TextInternalUpdate ( iID );
}
void TextInternalUpdate ( int iID )
{
// apply any changes to the object e.g. position
// update internal pointer
if ( !UpdateTextPtr ( iID ) )
return;
// variable declarations
D3DXMATRIX matTranslation; // translation ( position )
D3DXMATRIX matRotation, matRotateX, matRotateY, matRotateZ; // rotation
D3DXMATRIX matScale; // scale
bool bUpdate = false; // used to update look, up and right vector
// apply scaling to the object
D3DXMatrixScaling ( &matScale, m_pTextPos->vecScale.x, m_pTextPos->vecScale.y, m_pTextPos->vecScale.z );
// apply translation to the object
D3DXMatrixTranslation ( &matTranslation, m_pTextPos->vecPosition.x, m_pTextPos->vecPosition.y, m_pTextPos->vecPosition.z );
// setup rotation matrices
if ( m_pTextPos->bFreeFlightRotation )
{
// LEEFIX - 0941002 - Should be converted to radians
// D3DXMatrixRotationYawPitchRoll ( &matRotation, m_pTextPos->vecYawPitchRoll.x, m_pTextPos->vecYawPitchRoll.y, m_pTextPos->vecYawPitchRoll.z );
D3DXMatrixRotationYawPitchRoll ( &matRotation, D3DXToRadian ( m_pTextPos->vecYawPitchRoll.x ),
D3DXToRadian ( m_pTextPos->vecYawPitchRoll.y ),
D3DXToRadian ( m_pTextPos->vecYawPitchRoll.z ) );
}
else
{
D3DXMatrixRotationX ( &matRotateX, D3DXToRadian ( m_pTextPos->vecRotate.x ) ); // x rotation
D3DXMatrixRotationY ( &matRotateY, D3DXToRadian ( m_pTextPos->vecRotate.y ) ); // y rotation
D3DXMatrixRotationZ ( &matRotateZ, D3DXToRadian ( m_pTextPos->vecRotate.z ) ); // z rotation
// build final rotation matrix
matRotation = matRotateX * matRotateY * matRotateZ;
}
// Apply pivot if any
if ( m_pTextPos->bApplyPivot )
{
D3DXMatrixRotationX ( &matRotateX, D3DXToRadian ( m_pTextPos->vecPivot.x ) ); // x rotation
D3DXMatrixRotationY ( &matRotateY, D3DXToRadian ( m_pTextPos->vecPivot.y ) ); // y rotation
D3DXMatrixRotationZ ( &matRotateZ, D3DXToRadian ( m_pTextPos->vecPivot.z ) ); // z rotation
// build final rotation matrix
D3DXMATRIX matPivotRotation = matRotateX * matRotateY * matRotateZ;
// modify current rotation
matRotation = matPivotRotation * matRotation;
}
// scale first, then rotation, then translation (notran is a quick way of stripping translation for colcenter calc)
m_pTextPos->matObjectNoTran = matScale * matRotation;
m_pTextPos->matObject = m_pTextPos->matObjectNoTran * matTranslation;
// now we have to update the look, up and right vector, we do this because
// when we want to move an object we move it using these vectors so we need
// to update them to reflect any changes setup by the rotations
// if any of the rotation values have changed then we must reset the look, up
// and right vectors to their original states
// LEEFIX - 171002 - Ensure free flight is seperate from euler
if( m_pTextPos->bFreeFlightRotation==false )
{
if ( m_pTextPos->vecLast != m_pTextPos->vecRotate )
{
// save the current rotation vector
m_pTextPos->vecLast = m_pTextPos->vecRotate;
// regenerate the look, up and right vectors
m_pTextPos->vecLook = D3DXVECTOR3 ( 0, 0, 1 ); // look vector
m_pTextPos->vecUp = D3DXVECTOR3 ( 0, 1, 0 ); // up vector
m_pTextPos->vecRight = D3DXVECTOR3 ( 1, 0, 0 ); // right vector
// signal that we need to update the vectors
bUpdate = true;
}
}
else
{
// free flight always applies rotation
bUpdate = true;
}
// only update if there has been a change in rotation
if ( bUpdate )
{
if ( m_pTextPos->bFreeFlightRotation )
{
// free flight modifies lookupright directly (uses current rotation matrix)
D3DXVec3TransformCoord ( &m_pTextPos->vecLook, &m_pTextPos->vecLook, &matRotation );
D3DXVec3TransformCoord ( &m_pTextPos->vecRight, &m_pTextPos->vecRight, &matRotation );
D3DXVec3TransformCoord ( &m_pTextPos->vecUp, &m_pTextPos->vecUp, &matRotation );
}
else
{
// x rotation
D3DXMatrixRotationAxis ( &matRotation, &m_pTextPos->vecRight, D3DXToRadian ( m_pTextPos->vecRotate.x ) );
D3DXVec3TransformCoord ( &m_pTextPos->vecLook, &m_pTextPos->vecLook, &matRotation );
D3DXVec3TransformCoord ( &m_pTextPos->vecUp, &m_pTextPos->vecUp, &matRotation );
D3DXMatrixRotationAxis ( &matRotation, &D3DXVECTOR3 ( 0.0f, 1.0f, 0.0f ), D3DXToRadian ( m_pTextPos->vecRotate.y ) );
D3DXVec3TransformCoord ( &m_pTextPos->vecLook, &m_pTextPos->vecLook, &matRotation );
// LEEFIX - 051002 - Y rotation changes right, not up which stays the same throughout a Y rotation
// D3DXVec3TransformCoord ( &m_pTextPos->vecUp, &m_pTextPos->vecUp, &matRotation );
D3DXVec3TransformCoord ( &m_pTextPos->vecRight, &m_pTextPos->vecRight, &matRotation );
D3DXMatrixRotationAxis ( &matRotation, &m_pTextPos->vecLook, D3DXToRadian ( m_pTextPos->vecRotate.z ) );
// LEEFIX - 051002 - Z rotation changes right, not look which stays the same throughout a Z rotation
// D3DXVec3TransformCoord ( &m_pTextPos->vecLook, &m_pTextPos->vecLook, &matRotation );
D3DXVec3TransformCoord ( &m_pTextPos->vecRight, &m_pTextPos->vecRight, &matRotation );
D3DXVec3TransformCoord ( &m_pTextPos->vecUp, &m_pTextPos->vecUp, &matRotation );
}
}
// May need to recalc colcenter if used later
m_pTextPos->bColCenterUpdated=false;
}
D3DXVECTOR3 TextGetPosVec ( int iID )
{
return m_pTextPos->vecPosition;
}
D3DXVECTOR3 TextGetRotVec ( int iID )
{
return m_pTextPos->vecRotate;
}
DWORD TextGetXPositionEx ( int iID )
{
// update internal data
if ( iID < 1 || iID > MAXIMUMVALUE )
{
RunTimeError(RUNTIMEERROR_B3DMODELNUMBERILLEGAL);
return 0;
}
if ( !UpdateTextPtr ( iID ) )
{
RunTimeError(RUNTIMEERROR_B3DMODELNOTEXISTS);
return 0;
}
return *(DWORD*)&m_pTextPos->vecPosition.x;
}
DWORD TextGetYPositionEx ( int iID )
{
// update internal data
if ( iID < 1 || iID > MAXIMUMVALUE )
{
RunTimeError(RUNTIMEERROR_B3DMODELNUMBERILLEGAL);
return 0;
}
if ( !UpdateTextPtr ( iID ) )
{
RunTimeError(RUNTIMEERROR_B3DMODELNOTEXISTS);
return 0;
}
return *(DWORD*)&m_pTextPos->vecPosition.y;
}
DWORD TextGetZPositionEx ( int iID )
{
// update internal pointer
if ( !UpdateTextPtr ( iID ) )
return 0;
return *(DWORD*)&m_pTextPos->vecPosition.z;
}
DWORD TextGetXRotationEx ( int iID )
{
// update internal data
if ( iID < 1 || iID > MAXIMUMVALUE )
{
RunTimeError(RUNTIMEERROR_B3DMODELNUMBERILLEGAL);
return 0;
}
if ( !UpdateTextPtr ( iID ) )
{
RunTimeError(RUNTIMEERROR_B3DMODELNOTEXISTS);
return 0;
}
return *(DWORD*)&m_pTextPos->vecRotate.x;
}
DWORD TextGetYRotationEx ( int iID )
{
// update internal data
if ( iID < 1 || iID > MAXIMUMVALUE )
{
RunTimeError(RUNTIMEERROR_B3DMODELNUMBERILLEGAL);
return 0;
}
if ( !UpdateTextPtr ( iID ) )
{
RunTimeError(RUNTIMEERROR_B3DMODELNOTEXISTS);
return 0;
}
return *(DWORD*)&m_pTextPos->vecRotate.y;
}
DWORD TextGetZRotationEx ( int iID )
{
// update internal data
if ( iID < 1 || iID > MAXIMUMVALUE )
{
RunTimeError(RUNTIMEERROR_B3DMODELNUMBERILLEGAL);
return 0;
}
if ( !UpdateTextPtr ( iID ) )
{
RunTimeError(RUNTIMEERROR_B3DMODELNOTEXISTS);
return 0;
}
return *(DWORD*)&m_pTextPos->vecRotate.z;
}
| 412 | 0.843711 | 1 | 0.843711 | game-dev | MEDIA | 0.51241 | game-dev,graphics-rendering | 0.88584 | 1 | 0.88584 |
janhohenheim/foxtrot | 2,028 | src/gameplay/animation.rs | //! Animation system boilerplate.
use std::iter;
use bevy::{prelude::*, scene::SceneInstanceReady};
pub(super) fn plugin(app: &mut App) {
app.add_observer(link_animation_player);
}
/// Entities with this component will receive an [`AnimationPlayers`] relationship so that they can easily find the animation player of their model.
#[derive(Component)]
pub(crate) struct AnimationPlayerAncestor;
/// Simple link to the animation player of a model that is buried deep in the hierarchy.
#[derive(Component, Reflect, Clone, Deref)]
#[reflect(Component)]
#[relationship_target(relationship = AnimationPlayerOf)]
pub(crate) struct AnimationPlayers(Vec<Entity>);
#[derive(Component, Reflect, Deref)]
#[reflect(Component)]
#[relationship(relationship_target = AnimationPlayers)]
pub(crate) struct AnimationPlayerOf(pub(crate) Entity);
/// Bevy likes to hide the [`AnimationPlayer`] component deep in the hierarchy of a model.
/// This system ensures that we can find the animation player easily by inserting an [`AnimationPlayers`] relationship
/// into the same entity that contains the [`AnimationPlayerAncestor`] component.
fn link_animation_player(
ready: On<SceneInstanceReady>,
mut commands: Commands,
q_parent: Query<&ChildOf>,
q_children: Query<&Children>,
q_animation_player: Query<Entity, With<AnimationPlayer>>,
q_ancestor: Query<Entity, With<AnimationPlayerAncestor>>,
) {
let scene_root = ready.entity;
let animation_player = q_children
.iter_descendants(scene_root)
.find(|child| q_animation_player.get(*child).is_ok());
let Some(animation_player) = animation_player else {
return;
};
let animation_ancestor = iter::once(animation_player)
.chain(q_parent.iter_ancestors(animation_player))
.find(|entity| q_ancestor.get(*entity).is_ok());
let Some(animation_ancestor) = animation_ancestor else {
return;
};
commands
.entity(animation_player)
.insert(AnimationPlayerOf(animation_ancestor));
}
| 412 | 0.837977 | 1 | 0.837977 | game-dev | MEDIA | 0.954489 | game-dev | 0.615869 | 1 | 0.615869 |
a1studmuffin/Cataclysm-DDA-Android | 20,731 | src/debug_menu.cpp | #include "debug_menu.h"
#include "action.h"
#include "coordinate_conversions.h"
#include "game.h"
#include "messages.h"
#include "overmap.h"
#include "player.h"
#include "ui.h"
#include "npc.h"
#include "npc_class.h"
#include "overmapbuffer.h"
#include "vitamin.h"
#include "mission.h"
#include <algorithm>
#include <vector>
namespace debug_menu
{
class mission_debug
{
private:
// Doesn't actually "destroy" the mission, just removes assignments
static void remove_mission( mission &m );
public:
static void edit_mission( mission &m );
static void edit( player &who );
static void edit_player();
static void edit_npc( npc &who );
static std::string describe( const mission &m );
};
void teleport_short()
{
const tripoint where( g->look_around() );
if( where == tripoint_min || where == g->u.pos() ) {
return;
}
g->place_player( where );
const tripoint new_pos( g->u.pos() );
add_msg( _( "You teleport to point (%d,%d,%d)." ), new_pos.x, new_pos.y, new_pos.z );
}
void teleport_long()
{
const tripoint where( overmap::draw_overmap() );
if( where == overmap::invalid_tripoint ) {
return;
}
g->place_player_overmap( where );
add_msg( _( "You teleport to submap (%d,%d,%d)." ), where.x, where.y, where.z );
}
void teleport_overmap()
{
tripoint dir;
if( !choose_direction( _( "Where is the desired overmap?" ), dir ) ) {
return;
}
const tripoint offset( OMAPX * dir.x, OMAPY * dir.y, dir.z );
const tripoint where( g->u.global_omt_location() + offset );
g->place_player_overmap( where );
const tripoint new_pos( omt_to_om_copy( g->u.global_omt_location() ) );
add_msg( _( "You teleport to overmap (%d,%d,%d)." ), new_pos.x, new_pos.y, new_pos.z );
}
void npc_edit_menu()
{
std::vector< tripoint > locations;
uimenu charmenu;
charmenu.return_invalid = true;
// Hack: uimenu doesn't like negative indices in entries
int charnum = 0;
charmenu.addentry( charnum++, true, MENU_AUTOASSIGN, "%s", _( "You" ) );
locations.emplace_back( g->u.pos() );
for( auto *npc_p : g->active_npc ) {
charmenu.addentry( charnum++, true, MENU_AUTOASSIGN, "%s", npc_p->name.c_str() );
locations.emplace_back( npc_p->pos() );
}
pointmenu_cb callback( locations );
charmenu.callback = &callback;
charmenu.w_y = 0;
charmenu.query();
// Part 2 of the index hack
int npcdex = charmenu.ret - 1;
if( npcdex < -1 || npcdex > charnum ) {
return;
}
player &p = npcdex != -1 ? *g->active_npc[npcdex] : g->u;
// The NPC is also required for "Add mission", so has to be in this scope
npc *np = npcdex != -1 ? g->active_npc[npcdex] : nullptr;
uimenu nmenu;
nmenu.return_invalid = true;
if( np != nullptr ) {
std::stringstream data;
data << np->name << " " << ( np->male ? _( "Male" ) : _( "Female" ) ) << std::endl;
data << np->myclass.obj().get_name() << "; " <<
npc_attitude_name( np->attitude ) << std::endl;
if( np->has_destination() ) {
data << string_format( _( "Destination: %d:%d:%d (%s)" ),
np->goal.x, np->goal.y, np->goal.z,
overmap_buffer.ter( np->goal )->get_name().c_str() ) << std::endl;
} else {
data << _( "No destination." ) << std::endl;
}
data << string_format( _( "Trust: %d" ), np->op_of_u.trust ) << " "
<< string_format( _( "Fear: %d" ), np->op_of_u.fear ) << " "
<< string_format( _( "Value: %d" ), np->op_of_u.value ) << " "
<< string_format( _( "Anger: %d" ), np->op_of_u.anger ) << " "
<< string_format( _( "Owed: %d" ), np->op_of_u.owed ) << std::endl;
data << string_format( _( "Aggression: %d" ), int( np->personality.aggression ) ) << " "
<< string_format( _( "Bravery: %d" ), int( np->personality.bravery ) ) << " "
<< string_format( _( "Collector: %d" ), int( np->personality.collector ) ) << " "
<< string_format( _( "Altruism: %d" ), int( np->personality.altruism ) ) << std::endl;
data << _( "Needs:" ) << std::endl;
for( const auto &need : np->needs ) {
data << need << std::endl;
}
nmenu.text = data.str();
} else {
nmenu.text = _( "Player" );
}
enum { D_SKILLS, D_STATS, D_ITEMS, D_DELETE_ITEMS, D_ITEM_WORN,
D_HP, D_PAIN, D_NEEDS, D_HEALTHY, D_STATUS, D_MISSION_ADD, D_MISSION_EDIT,
D_TELE, D_MUTATE, D_CLASS
};
nmenu.addentry( D_SKILLS, true, 's', "%s", _( "Edit [s]kills" ) );
nmenu.addentry( D_STATS, true, 't', "%s", _( "Edit s[t]ats" ) );
nmenu.addentry( D_ITEMS, true, 'i', "%s", _( "Grant [i]tems" ) );
nmenu.addentry( D_DELETE_ITEMS, true, 'd', "%s", _( "[d]elete (all) items" ) );
nmenu.addentry( D_ITEM_WORN, true, 'w', "%s",
_( "[w]ear/[w]ield an item from player's inventory" ) );
nmenu.addentry( D_HP, true, 'h', "%s", _( "Set [h]it points" ) );
nmenu.addentry( D_PAIN, true, 'p', "%s", _( "Cause [p]ain" ) );
nmenu.addentry( D_HEALTHY, true, 'a', "%s", _( "Set he[a]lth" ) );
nmenu.addentry( D_NEEDS, true, 'n', "%s", _( "Set [n]eeds" ) );
nmenu.addentry( D_MUTATE, true, 'u', "%s", _( "M[u]tate" ) );
nmenu.addentry( D_STATUS, true, '@', "%s", _( "Status Window [@]" ) );
nmenu.addentry( D_TELE, true, 'e', "%s", _( "t[e]leport" ) );
nmenu.addentry( D_MISSION_EDIT, true, 'M', "%s", _( "Edit [M]issions (WARNING: Unstable!)" ) );
if( p.is_npc() ) {
nmenu.addentry( D_MISSION_ADD, true, 'm', "%s", _( "Add [m]ission" ) );
nmenu.addentry( D_CLASS, true, 'c', "%s", _( "Randomize with [c]lass" ) );
}
nmenu.addentry( 999, true, 'q', "%s", _( "[q]uit" ) );
nmenu.selected = 0;
nmenu.query();
switch( nmenu.ret ) {
case D_SKILLS:
wishskill( &p );
break;
case D_STATS: {
uimenu smenu;
smenu.return_invalid = true;
smenu.addentry( 0, true, 'S', "%s: %d", _( "Maximum strength" ), p.str_max );
smenu.addentry( 1, true, 'D', "%s: %d", _( "Maximum dexterity" ), p.dex_max );
smenu.addentry( 2, true, 'I', "%s: %d", _( "Maximum intelligence" ), p.int_max );
smenu.addentry( 3, true, 'P', "%s: %d", _( "Maximum perception" ), p.per_max );
smenu.addentry( 999, true, 'q', "%s", _( "[q]uit" ) );
smenu.selected = 0;
smenu.query();
int *bp_ptr = nullptr;
switch( smenu.ret ) {
case 0:
bp_ptr = &p.str_max;
break;
case 1:
bp_ptr = &p.dex_max;
break;
case 2:
bp_ptr = &p.int_max;
break;
case 3:
bp_ptr = &p.per_max;
break;
default:
break;
}
if( bp_ptr != nullptr ) {
int value;
if( query_int( value, _( "Set the stat to? Currently: %d" ), *bp_ptr ) && value >= 0 ) {
*bp_ptr = value;
p.reset_stats();
}
}
}
break;
case D_ITEMS:
wishitem( &p );
break;
case D_DELETE_ITEMS:
if( !query_yn( _( "Delete all items from the target?" ) ) ) {
break;
}
for( auto &it : p.worn ) {
it.on_takeoff( p );
}
p.worn.clear();
p.inv.clear();
p.weapon = p.ret_null;
break;
case D_ITEM_WORN: {
int item_pos = g->inv_for_all( _( "Make target equip" ) );
item &to_wear = g->u.i_at( item_pos );
if( to_wear.is_armor() ) {
p.on_item_wear( to_wear );
p.worn.push_back( to_wear );
} else if( !to_wear.is_null() ) {
p.weapon = to_wear;
}
}
break;
case D_HP: {
uimenu smenu;
smenu.return_invalid = true;
smenu.addentry( 0, true, 'q', "%s: %d", _( "Torso" ), p.hp_cur[hp_torso] );
smenu.addentry( 1, true, 'w', "%s: %d", _( "Head" ), p.hp_cur[hp_head] );
smenu.addentry( 2, true, 'a', "%s: %d", _( "Left arm" ), p.hp_cur[hp_arm_l] );
smenu.addentry( 3, true, 's', "%s: %d", _( "Right arm" ), p.hp_cur[hp_arm_r] );
smenu.addentry( 4, true, 'z', "%s: %d", _( "Left leg" ), p.hp_cur[hp_leg_l] );
smenu.addentry( 5, true, 'x', "%s: %d", _( "Right leg" ), p.hp_cur[hp_leg_r] );
smenu.selected = 0;
smenu.query();
int *bp_ptr = nullptr;
switch( smenu.ret ) {
case 0:
bp_ptr = &p.hp_cur[hp_torso];
break;
case 1:
bp_ptr = &p.hp_cur[hp_head];
break;
case 2:
bp_ptr = &p.hp_cur[hp_arm_l];
break;
case 3:
bp_ptr = &p.hp_cur[hp_arm_r];
break;
case 4:
bp_ptr = &p.hp_cur[hp_leg_l];
break;
case 5:
bp_ptr = &p.hp_cur[hp_leg_r];
break;
default:
break;
}
if( bp_ptr != nullptr ) {
int value;
if( query_int( value, _( "Set the hitpoints to? Currently: %d" ), *bp_ptr ) && value >= 0 ) {
*bp_ptr = value;
p.reset_stats();
}
}
}
break;
case D_PAIN: {
int value;
if( query_int( value, _( "Cause how much pain? pain: %d" ), p.get_pain() ) ) {
p.mod_pain( value );
}
}
break;
case D_NEEDS: {
uimenu smenu;
smenu.return_invalid = true;
smenu.addentry( 0, true, 'h', "%s: %d", _( "Hunger" ), p.get_hunger() );
smenu.addentry( 1, true, 't', "%s: %d", _( "Thirst" ), p.get_thirst() );
smenu.addentry( 2, true, 'f', "%s: %d", _( "Fatigue" ), p.get_fatigue() );
const auto &vits = vitamin::all();
for( const auto &v : vits ) {
smenu.addentry( -1, true, 0, "%s: %d", v.second.name().c_str(), p.vitamin_get( v.first ) );
}
smenu.addentry( 999, true, 'q', "%s", _( "[q]uit" ) );
smenu.selected = 0;
smenu.query();
switch( smenu.ret ) {
int value;
case 0:
if( query_int( value, _( "Set hunger to? Currently: %d" ), p.get_hunger() ) ) {
p.set_hunger( value );
}
break;
case 1:
if( query_int( value, _( "Set thirst to? Currently: %d" ), p.get_thirst() ) ) {
p.set_thirst( value );
}
break;
case 2:
if( query_int( value, _( "Set fatigue to? Currently: %d" ), p.get_fatigue() ) ) {
p.set_fatigue( value );
}
break;
default:
if( smenu.ret > 2 && smenu.ret < static_cast<int>( vits.size() + 3 ) ) {
auto iter = std::next( vits.begin(), smenu.ret - 3 );
if( query_int( value, _( "Set %s to? Currently: %d" ),
iter->second.name().c_str(), p.vitamin_get( iter->first ) ) ) {
p.vitamin_set( iter->first, value );
}
}
}
}
break;
case D_MUTATE:
wishmutate( &p );
break;
case D_HEALTHY: {
uimenu smenu;
smenu.return_invalid = true;
smenu.addentry( 0, true, 'h', "%s: %d", _( "Health" ), p.get_healthy() );
smenu.addentry( 1, true, 'm', "%s: %d", _( "Health modifier" ), p.get_healthy_mod() );
smenu.addentry( 2, true, 'r', "%s: %d", _( "Radiation" ), p.radiation );
smenu.addentry( 999, true, 'q', "%s", _( "[q]uit" ) );
smenu.selected = 0;
smenu.query();
switch( smenu.ret ) {
int value;
case 0:
if( query_int( value, _( "Set the value to? Currently: %d" ), p.get_healthy() ) ) {
p.set_healthy( value );
}
break;
case 1:
if( query_int( value, _( "Set the value to? Currently: %d" ), p.get_healthy_mod() ) ) {
p.set_healthy_mod( value );
}
break;
case 2:
if( query_int( value, _( "Set the value to? Currently: %d" ), p.radiation ) ) {
p.radiation = value;
}
break;
default:
break;
}
}
break;
case D_STATUS:
p.disp_info();
break;
case D_MISSION_ADD: {
uimenu types;
types.return_invalid = true;
types.text = _( "Choose mission type" );
const auto all_missions = mission_type::get_all();
std::vector<const mission_type *> mts;
for( size_t i = 0; i < all_missions.size(); i++ ) {
types.addentry( i, true, -1, all_missions[ i ].name );
mts.push_back( &all_missions[ i ] );
}
types.addentry( INT_MAX, true, -1, _( "Cancel" ) );
types.query();
if( types.ret >= 0 && types.ret < ( int )mts.size() ) {
np->add_new_mission( mission::reserve_new( mts[ types.ret ]->id, np->getID() ) );
}
}
break;
case D_MISSION_EDIT:
mission_debug::edit( p );
break;
case D_TELE: {
tripoint newpos = g->look_around();
if( newpos != tripoint_min ) {
p.setpos( newpos );
if( p.is_player() ) {
g->update_map( g->u );
}
}
}
break;
case D_CLASS: {
uimenu classes;
classes.return_invalid = true;
classes.text = _( "Choose new class" );
std::vector<npc_class_id> ids;
size_t i = 0;
for( auto &cl : npc_class::get_all() ) {
ids.push_back( cl.id );
classes.addentry( i, true, -1, cl.get_name() );
i++;
}
classes.addentry( INT_MAX, true, -1, _( "Cancel" ) );
classes.query();
if( classes.ret < ( int )ids.size() && classes.ret >= 0 ) {
np->randomize( ids[ classes.ret ] );
}
}
}
}
const std::string &mission_status_string( mission::mission_status status )
{
static const std::map<mission::mission_status, std::string> desc {{
{ mission::mission_status::yet_to_start, _( "Yet to start" ) },
{ mission::mission_status::in_progress, _( "In progress" ) },
{ mission::mission_status::success, _( "Success" ) },
{ mission::mission_status::failure, _( "Failure" ) }
}
};
const auto &iter = desc.find( status );
if( iter != desc.end() ) {
return iter->second;
}
static const std::string errmsg = _( "Bugged" );
return errmsg;
}
std::string mission_debug::describe( const mission &m )
{
std::stringstream data;
data << _( "Type:" ) << m.type->id.str();
data << _( " Status:" ) << mission_status_string( m.status );
data << _( " ID:" ) << m.uid;
data << _( " NPC ID:" ) << m.npc_id;
data << _( " Target:" ) << m.target.x << "," << m.target.y << "," << m.target.z;
data << _( "Player ID:" ) << m.player_id;
return data.str();
}
void add_header( uimenu &mmenu, const std::string &str )
{
mmenu.addentry( -1, false, -1, "" );
uimenu_entry header( -1, false, -1, str, c_yellow, c_yellow );
header.force_color = true;
mmenu.entries.push_back( header );
}
void mission_debug::edit( player &who )
{
if( who.is_player() ) {
edit_player();
} else if( who.is_npc() ) {
edit_npc( dynamic_cast<npc &>( who ) );
}
}
void mission_debug::edit_npc( npc &who )
{
npc_chatbin &bin = who.chatbin;
std::vector<mission *> all_missions;
uimenu mmenu;
mmenu.return_invalid = true;
mmenu.text = _( "Select mission to edit" );
add_header( mmenu, _( "Currently assigned missions:" ) );
for( mission *m : bin.missions_assigned ) {
mmenu.addentry( all_missions.size(), true, MENU_AUTOASSIGN, "%s", m->type->id.c_str() );
all_missions.emplace_back( m );
}
add_header( mmenu, _( "Not assigned missions:" ) );
for( mission *m : bin.missions ) {
mmenu.addentry( all_missions.size(), true, MENU_AUTOASSIGN, "%s", m->type->id.c_str() );
all_missions.emplace_back( m );
}
mmenu.query();
if( mmenu.ret < 0 || mmenu.ret >= ( int )all_missions.size() ) {
return;
}
edit_mission( *all_missions[ mmenu.ret ] );
}
void mission_debug::edit_player()
{
std::vector<mission *> all_missions;
uimenu mmenu;
mmenu.return_invalid = true;
mmenu.text = _( "Select mission to edit" );
add_header( mmenu, _( "Active missions:" ) );
for( mission *m : g->u.active_missions ) {
mmenu.addentry( all_missions.size(), true, MENU_AUTOASSIGN, "%s", m->type->id.c_str() );
all_missions.emplace_back( m );
}
add_header( mmenu, _( "Completed missions:" ) );
for( mission *m : g->u.completed_missions ) {
mmenu.addentry( all_missions.size(), true, MENU_AUTOASSIGN, "%s", m->type->id.c_str() );
all_missions.emplace_back( m );
}
add_header( mmenu, _( "Failed missions:" ) );
for( mission *m : g->u.failed_missions ) {
mmenu.addentry( all_missions.size(), true, MENU_AUTOASSIGN, "%s", m->type->id.c_str() );
all_missions.emplace_back( m );
}
mmenu.query();
if( mmenu.ret < 0 || mmenu.ret >= ( int )all_missions.size() ) {
return;
}
edit_mission( *all_missions[ mmenu.ret ] );
}
bool remove_from_vec( std::vector<mission *> &vec, mission *m )
{
auto iter = std::remove( vec.begin(), vec.end(), m );
bool ret = iter != vec.end();
vec.erase( iter, vec.end() );
return ret;
}
void mission_debug::remove_mission( mission &m )
{
if( remove_from_vec( g->u.active_missions, &m ) ) {
add_msg( _( "Removing from active_missions" ) );
}
if( remove_from_vec( g->u.completed_missions, &m ) ) {
add_msg( _( "Removing from completed_missions" ) );
}
if( remove_from_vec( g->u.failed_missions, &m ) ) {
add_msg( _( "Removing from failed_missions" ) );
}
if( g->u.active_mission == &m ) {
g->u.active_mission = nullptr;
add_msg( _( "Unsetting active mission" ) );
}
const auto giver = g->find_npc( m.npc_id );
if( giver != nullptr ) {
if( remove_from_vec( giver->chatbin.missions_assigned, &m ) ) {
add_msg( _( "Removing from %s missions_assigned" ), giver->name.c_str() );
}
if( remove_from_vec( giver->chatbin.missions, &m ) ) {
add_msg( _( "Removing from %s missions" ), giver->name.c_str() );
}
}
}
void mission_debug::edit_mission( mission &m )
{
uimenu mmenu;
mmenu.return_invalid = true;
mmenu.text = describe( m );
enum { M_FAIL, M_SUCCEED, M_REMOVE
};
mmenu.addentry( M_FAIL, true, 'f', "%s", _( "Fail mission" ) );
mmenu.addentry( M_SUCCEED, true, 'c', "%s", _( "Mark as complete" ) );
mmenu.addentry( M_REMOVE, true, 'r', "%s", _( "Remove mission without proper cleanup" ) );
mmenu.query();
switch( mmenu.ret ) {
case M_FAIL:
m.fail();
break;
case M_SUCCEED:
m.status = mission::mission_status::success;
break;
case M_REMOVE:
remove_mission( m );
break;
}
}
}
| 412 | 0.954186 | 1 | 0.954186 | game-dev | MEDIA | 0.563591 | game-dev,networking | 0.964599 | 1 | 0.964599 |
PaperMC/Paper-archive | 2,240 | patches/server/0671-Buffer-OOB-setBlock-calls.patch | From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Shane Freeder <theboyetronic@gmail.com>
Date: Sat, 19 Mar 2022 12:12:22 +0000
Subject: [PATCH] Buffer OOB setBlock calls
lets debug mode throw a trace in order to potentially see where
such calls are cascading from easier, but, generally, if you see one setBlock
call, you're gonna see more, and this just potentially causes a flood of logs
which can cause issues for slower terminals, etc.
We can limit the flood by just allowing one for a single gen region,
we'll also only gen a trace for the first one, I see no real pressing need
to generate more, given that that would *massively* negate this patch otherwise
diff --git a/src/main/java/net/minecraft/server/level/WorldGenRegion.java b/src/main/java/net/minecraft/server/level/WorldGenRegion.java
index f1725ef766c35aa623ace58fe8bf31fc9b2bb6b3..5bf438bb58833c1df3620e82d3d2b90207366372 100644
--- a/src/main/java/net/minecraft/server/level/WorldGenRegion.java
+++ b/src/main/java/net/minecraft/server/level/WorldGenRegion.java
@@ -284,6 +284,7 @@ public class WorldGenRegion implements WorldGenLevel {
}
}
+ private boolean hasSetFarWarned = false; // Paper - Buffer OOB setBlock calls
@Override
public boolean ensureCanWrite(BlockPos pos) {
int i = SectionPos.blockToSectionCoord(pos.getX());
@@ -303,7 +304,15 @@ public class WorldGenRegion implements WorldGenLevel {
return true;
} else {
+ // Paper start - Buffer OOB setBlock calls
+ if (!hasSetFarWarned) {
Util.logAndPauseIfInIde("Detected setBlock in a far chunk [" + i + ", " + j + "], pos: " + String.valueOf(pos) + ", status: " + String.valueOf(this.generatingStep.targetStatus()) + (this.currentlyGenerating == null ? "" : ", currently generating: " + (String) this.currentlyGenerating.get()));
+ hasSetFarWarned = true;
+ if (this.getServer() != null && this.getServer().isDebugging()) {
+ io.papermc.paper.util.TraceUtil.dumpTraceForThread("far setBlock call");
+ }
+ }
+ // Paper end - Buffer OOB setBlock calls
return false;
}
}
| 412 | 0.850749 | 1 | 0.850749 | game-dev | MEDIA | 0.958027 | game-dev | 0.673038 | 1 | 0.673038 |
mattmatterson111/IS12-Warfare-Two | 20,334 | code/modules/reagents/Chemistry-Reagents/Chemistry-Reagents-Toxins.dm | /* Toxins, poisons, venoms */
/datum/reagent/toxin
name = "toxin"
description = "A toxic chemical."
taste_description = "bitterness"
taste_mult = 1.2
reagent_state = REAGENT_LIQUID
color = "#cf3600"
metabolism = REM * 0.25 // 0.05 by default. They last a while and slowly kill you.
var/target_organ
var/strength = 4 // How much damage it deals per unit
/datum/reagent/toxin/affect_blood(var/mob/living/carbon/M, var/alien, var/removed)
if(strength && alien != IS_DIONA)
M.add_chemical_effect(CE_TOXIN, strength)
var/dam = (strength * removed)
if(target_organ && ishuman(M))
var/mob/living/carbon/human/H = M
var/obj/item/organ/internal/I = H.internal_organs_by_name[target_organ]
if(I)
var/can_damage = I.max_damage - I.damage
if(can_damage > 0)
if(dam > can_damage)
I.take_damage(can_damage, silent=TRUE)
dam -= can_damage
else
I.take_damage(dam, silent=TRUE)
dam = 0
if(dam)
M.adjustToxLoss(target_organ ? (dam * 0.75) : dam)
/datum/reagent/toxin/plasticide
name = "Plasticide"
description = "Liquid plastic, do not eat."
taste_description = "plastic"
reagent_state = REAGENT_LIQUID
color = "#cf3600"
strength = 5
/datum/reagent/toxin/amatoxin
name = "Amatoxin"
description = "A powerful poison derived from certain species of mushroom."
taste_description = "mushroom"
reagent_state = REAGENT_LIQUID
color = "#792300"
strength = 10
/datum/reagent/toxin/blattedin
name = "Blattedin"
description = "A powerful toxin produced by those omnipresent roaches."
taste_description = "chicken"
reagent_state = REAGENT_LIQUID
color = "#0f4800"
strength = 5
/datum/reagent/toxin/blattedin/touch_mob(var/mob/living/L, var/amount)
if(istype(L, /mob/living/simple_animal/hostile/retaliate/roach))
if(L.health <= 0)
if(prob(70))//Roaches sometimes can come back to life from healing vapors
return
L.heal_organ_damage(amount * 0.5)
else
..()
/datum/reagent/toxin/carpotoxin
name = "Carpotoxin"
description = "A deadly neurotoxin produced by the dreaded space carp."
taste_description = "fish"
reagent_state = REAGENT_LIQUID
color = "#003333"
target_organ = BP_BRAIN
strength = 10
/datum/reagent/toxin/phoron
name = "Phoron"
description = "Phoron in its liquid form."
taste_mult = 1.5
reagent_state = REAGENT_LIQUID
color = "#ff3300"
strength = 30
touch_met = 5
var/fire_mult = 5
/datum/reagent/toxin/chlorine
name = "Chlorine"
description = "A highly poisonous liquid. Smells strongly of bleach."
reagent_state = REAGENT_LIQUID
taste_description = "bleach"
color = "#707C13"
strength = 15
metabolism = REM
/datum/reagent/toxin/phoron/touch_mob(var/mob/living/L, var/amount)
if(istype(L))
L.adjust_fire_stacks(amount / fire_mult)
/datum/reagent/toxin/phoron/affect_blood(var/mob/living/carbon/M, var/alien, var/removed)
if(alien == IS_NABBER)
return
..()
/datum/reagent/toxin/phoron/affect_touch(var/mob/living/carbon/M, var/alien, var/removed)
M.take_organ_damage(0, removed * 0.1) //being splashed directly with phoron causes minor chemical burns
if(prob(10 * fire_mult))
M.pl_effects()
/datum/reagent/toxin/phoron/touch_turf(var/turf/simulated/T)
if(!istype(T))
return
T.assume_gas("phoron", volume, T20C)
remove_self(volume)
// Produced during deuterium synthesis. Super poisonous, SUPER flammable (doesn't need oxygen to burn).
/datum/reagent/toxin/phoron/oxygen
name = "Oxyphoron"
description = "An exceptionally flammable molecule formed from deuterium synthesis."
strength = 15
fire_mult = 15
/datum/reagent/toxin/phoron/oxygen/touch_turf(var/turf/simulated/T)
if(!istype(T))
return
T.assume_gas("oxygen", ceil(volume/2), T20C)
T.assume_gas("phoron", ceil(volume/2), T20C)
remove_self(volume)
/datum/reagent/toxin/cyanide //Fast and Lethal
name = "Cyanide"
description = "A highly toxic chemical."
taste_mult = 0.6
reagent_state = REAGENT_LIQUID
color = "#cf3600"
strength = 20
metabolism = REM * 2
target_organ = BP_HEART
/datum/reagent/toxin/cyanide/affect_blood(var/mob/living/carbon/M, var/alien, var/removed)
..()
M.sleeping += 1
/datum/reagent/toxin/potassium_chloride
name = "Potassium Chloride"
description = "A delicious salt that stops the heart when injected into cardiac muscle."
taste_description = "salt"
reagent_state = REAGENT_SOLID
color = "#ffffff"
strength = 0
overdose = REAGENTS_OVERDOSE
/datum/reagent/toxin/potassium_chloride/overdose(var/mob/living/carbon/M, var/alien)
..()
if(ishuman(M))
var/mob/living/carbon/human/H = M
if(H.stat != 1)
if(H.losebreath >= 10)
H.losebreath = max(10, H.losebreath - 10)
H.adjustOxyLoss(2)
H.Weaken(10)
M.add_chemical_effect(CE_NOPULSE, 1)
/datum/reagent/toxin/potassium_chlorophoride
name = "Potassium Chlorophoride"
description = "A specific chemical based on Potassium Chloride to stop the heart for surgery. Not safe to eat!"
taste_description = "salt"
reagent_state = REAGENT_SOLID
color = "#ffffff"
strength = 10
overdose = 20
/datum/reagent/toxin/potassium_chlorophoride/affect_blood(var/mob/living/carbon/M, var/alien, var/removed)
..()
if(ishuman(M))
var/mob/living/carbon/human/H = M
if(H.stat != 1)
if(H.losebreath >= 10)
H.losebreath = max(10, M.losebreath-10)
H.adjustOxyLoss(2)
H.Weaken(10)
M.add_chemical_effect(CE_NOPULSE, 1)
/datum/reagent/toxin/zombiepowder
name = "Zombie Powder"
description = "A strong neurotoxin that puts the subject into a death-like state."
taste_description = "death"
reagent_state = REAGENT_SOLID
color = "#669900"
metabolism = REM
strength = 3
target_organ = BP_BRAIN
/datum/reagent/toxin/zombiepowder/affect_blood(var/mob/living/carbon/M, var/alien, var/removed)
..()
if(alien == IS_DIONA)
return
M.status_flags |= FAKEDEATH
M.adjustOxyLoss(3 * removed)
M.Weaken(10)
M.silent = max(M.silent, 10)
if(M.chem_doses[type] <= removed) //half-assed attempt to make timeofdeath update only at the onset
M.timeofdeath = world.time
M.add_chemical_effect(CE_NOPULSE, 1)
/datum/reagent/toxin/zombiepowder/Destroy()
if(holder && holder.my_atom && ismob(holder.my_atom))
var/mob/M = holder.my_atom
M.status_flags &= ~FAKEDEATH
. = ..()
/datum/reagent/toxin/fertilizer //Reagents used for plant fertilizers.
name = /datum/reagent/toxin/fertilizer
description = "A chemical mix good for growing plants with."
taste_description = "plant food"
taste_mult = 0.5
reagent_state = REAGENT_LIQUID
strength = 0.5 // It's not THAT poisonous.
color = "#664330"
/datum/reagent/toxin/fertilizer/eznutrient
name = "EZ Nutrient"
/datum/reagent/toxin/fertilizer/left4zed
name = "Left-4-Zed"
/datum/reagent/toxin/fertilizer/robustharvest
name = "Robust Harvest"
/datum/reagent/toxin/plantbgone
name = "Plant-B-Gone"
description = "A harmful toxic mixture to kill plantlife. Do not ingest!"
taste_mult = 1
reagent_state = REAGENT_LIQUID
color = "#49002e"
strength = 4
/datum/reagent/toxin/plantbgone/touch_turf(var/turf/T)
if(istype(T, /turf/simulated/wall))
var/turf/simulated/wall/W = T
if(locate(/obj/effect/overlay/wallrot) in W)
for(var/obj/effect/overlay/wallrot/E in W)
qdel(E)
W.visible_message("<span class='notice'>The fungi are completely dissolved by the solution!</span>")
/datum/reagent/toxin/plantbgone/touch_obj(var/obj/O, var/volume)
if(istype(O, /obj/effect/vine))
qdel(O)
/datum/reagent/toxin/plantbgone/affect_blood(var/mob/living/carbon/M, var/alien, var/removed)
..()
if(alien == IS_DIONA)
M.adjustToxLoss(50 * removed)
/datum/reagent/toxin/plantbgone/affect_touch(var/mob/living/carbon/M, var/alien, var/removed)
..()
if(alien == IS_DIONA)
M.adjustToxLoss(50 * removed)
/datum/reagent/acid/polyacid
name = "Polytrinic acid"
description = "Polytrinic acid is a an extremely corrosive chemical substance."
taste_description = "acid"
reagent_state = REAGENT_LIQUID
color = "#8e18a9"
power = 10
meltdose = 4
/datum/reagent/lexorin
name = "Lexorin"
description = "Lexorin temporarily stops respiration. Causes tissue damage."
taste_description = "acid"
reagent_state = REAGENT_LIQUID
color = "#c8a5dc"
overdose = REAGENTS_OVERDOSE
/datum/reagent/lexorin/affect_blood(var/mob/living/carbon/M, var/alien, var/removed)
if(alien == IS_DIONA)
return
if(alien == IS_SKRELL)
M.take_organ_damage(2.4 * removed, 0)
if(M.losebreath < 22.5)
M.losebreath++
else
M.take_organ_damage(3 * removed, 0)
if(M.losebreath < 15)
M.losebreath++
/datum/reagent/mutagen
name = "Unstable mutagen"
description = "Might cause unpredictable mutations. Keep away from children."
taste_description = "slime"
taste_mult = 0.9
reagent_state = REAGENT_LIQUID
color = "#13bc5e"
/datum/reagent/mutagen/affect_touch(var/mob/living/carbon/M, var/alien, var/removed)
if(prob(33))
affect_blood(M, alien, removed)
/datum/reagent/mutagen/affect_ingest(var/mob/living/carbon/M, var/alien, var/removed)
if(prob(67))
affect_blood(M, alien, removed)
/datum/reagent/mutagen/affect_blood(var/mob/living/carbon/M, var/alien, var/removed)
if(M.isSynthetic())
return
var/mob/living/carbon/human/H = M
if(istype(H) && (H.species.species_flags & SPECIES_FLAG_NO_SCAN))
return
if(M.dna)
if(prob(removed * 0.1)) // Approx. one mutation per 10 injected/20 ingested/30 touching units
randmuti(M)
if(prob(98))
randmutb(M)
else
randmutg(M)
domutcheck(M, null)
M.UpdateAppearance()
M.apply_effect(10 * removed, IRRADIATE, blocked = 0)
/datum/reagent/slimejelly
name = "Slime Jelly"
description = "A gooey semi-liquid produced from one of the deadliest lifeforms in existence. SO REAL."
taste_description = "slime"
taste_mult = 1.3
reagent_state = REAGENT_LIQUID
color = "#801e28"
/datum/reagent/slimejelly/affect_blood(var/mob/living/carbon/M, var/alien, var/removed)
if(alien == IS_DIONA)
return
if(prob(10))
to_chat(M, "<span class='danger'>Your insides are burning!</span>")
M.adjustToxLoss(rand(100, 300) * removed)
else if(prob(40))
M.heal_organ_damage(25 * removed, 0)
/datum/reagent/soporific
name = "Soporific"
description = "An effective hypnotic used to treat insomnia."
taste_description = "bitterness"
reagent_state = REAGENT_LIQUID
color = "#009ca8"
metabolism = REM * 0.5
overdose = REAGENTS_OVERDOSE
/datum/reagent/soporific/affect_blood(var/mob/living/carbon/M, var/alien, var/removed)
if(alien == IS_DIONA)
return
var/threshold = 1
if(alien == IS_SKRELL)
threshold = 1.2
if(M.chem_doses[type] < 1 * threshold)
if(M.chem_doses[type] == metabolism * 2 || prob(5))
M.emote("yawn")
else if(M.chem_doses[type] < 1.5 * threshold)
M.eye_blurry = max(M.eye_blurry, 10)
else if(M.chem_doses[type] < 5 * threshold)
if(prob(50))
M.Weaken(2)
M.drowsyness = max(M.drowsyness, 20)
else
M.sleeping = max(M.sleeping, 20)
M.drowsyness = max(M.drowsyness, 60)
M.add_chemical_effect(CE_PULSE, -1)
/datum/reagent/chloralhydrate
name = "Chloral Hydrate"
description = "A powerful sedative."
taste_description = "bitterness"
reagent_state = REAGENT_SOLID
color = "#000067"
metabolism = REM * 0.5
overdose = REAGENTS_OVERDOSE * 0.5
/datum/reagent/chloralhydrate/affect_blood(var/mob/living/carbon/M, var/alien, var/removed)
if(alien == IS_DIONA)
return
var/threshold = 1
if(alien == IS_SKRELL)
threshold = 1.2
if(M.chem_doses[type] == metabolism * threshold)
M.confused += 2
M.drowsyness += 2
else if(M.chem_doses[type] < 2 * threshold)
M.Weaken(30)
M.eye_blurry = max(M.eye_blurry, 10)
else
M.sleeping = max(M.sleeping, 30)
if(M.chem_doses[type] > 1 * threshold)
M.adjustToxLoss(removed)
/datum/reagent/chloralhydrate/beer2 //disguised as normal beer for use by emagged brobots
name = "Beer"
description = "An alcoholic beverage made from malted grains, hops, yeast, and water. The fermentation appears to be incomplete." //If the players manage to analyze this, they deserve to know something is wrong.
taste_description = "shitty piss water"
reagent_state = REAGENT_LIQUID
color = "#ffd300"
glass_name = "beer"
glass_desc = "A freezing pint of beer"
/* Drugs */
/datum/reagent/space_drugs
name = "Trench drugs"
description = "An illegal chemical compound used as drug."
taste_description = "bitterness"
taste_mult = 0.4
reagent_state = REAGENT_LIQUID
color = "#60a584"
metabolism = REM * 0.5
overdose = REAGENTS_OVERDOSE
/datum/reagent/space_drugs/affect_blood(var/mob/living/carbon/M, var/alien, var/removed)
if(alien == IS_DIONA)
return
var/drug_strength = 15
if(alien == IS_SKRELL)
drug_strength = drug_strength * 0.8
M.druggy = max(M.druggy, drug_strength)
if(prob(10) && isturf(M.loc) && !istype(M.loc, /turf/space) && M.canmove && !M.restrained())
step(M, pick(GLOB.cardinal))
if(prob(7))
M.emote(pick("twitch", "drool", "moan", "giggle"))
M.add_chemical_effect(CE_PULSE, -1)
M.add_event("high", /datum/happiness_event/high)
//SUGAR CRACK PIE, GET ME HIGH
/datum/reagent/serotrotium
name = "Serotrotium"
description = "A chemical compound that promotes concentrated production of the serotonin neurotransmitter in humans."
taste_description = "bitterness"
reagent_state = REAGENT_LIQUID
color = "#202040"
metabolism = REM * 0.25
overdose = REAGENTS_OVERDOSE
/datum/reagent/serotrotium/affect_blood(var/mob/living/carbon/M, var/alien, var/removed)
if(alien == IS_DIONA)
return
if(prob(7))
M.emote(pick("twitch", "drool", "moan", "gasp"))
return
/datum/reagent/cryptobiolin
name = "Cryptobiolin"
description = "Cryptobiolin causes confusion and dizzyness."
taste_description = "sourness"
reagent_state = REAGENT_LIQUID
color = "#000055"
metabolism = REM * 0.5
overdose = REAGENTS_OVERDOSE
/datum/reagent/cryptobiolin/affect_blood(var/mob/living/carbon/M, var/alien, var/removed)
if(alien == IS_DIONA)
return
var/drug_strength = 4
if(alien == IS_SKRELL)
drug_strength = drug_strength * 0.8
M.make_dizzy(drug_strength)
M.confused = max(M.confused, drug_strength * 5)
/datum/reagent/impedrezene
name = "Impedrezene"
description = "Impedrezene is a narcotic that impedes one's ability by slowing down the higher brain cell functions."
taste_description = "numbness"
reagent_state = REAGENT_LIQUID
color = "#c8a5dc"
overdose = REAGENTS_OVERDOSE
/datum/reagent/impedrezene/affect_blood(var/mob/living/carbon/M, var/alien, var/removed)
if(alien == IS_DIONA)
return
M.jitteriness = max(M.jitteriness - 5, 0)
if(prob(80))
M.adjustBrainLoss(0.1 * removed)
if(prob(50))
M.drowsyness = max(M.drowsyness, 3)
if(prob(10))
M.emote("drool")
M.add_event("high", /datum/happiness_event/high)
/datum/reagent/mindbreaker
name = "Mindbreaker Toxin"
description = "A powerful hallucinogen, it can cause fatal effects in users."
taste_description = "sourness"
reagent_state = REAGENT_LIQUID
color = "#b31008"
metabolism = REM * 0.25
overdose = REAGENTS_OVERDOSE
/datum/reagent/mindbreaker/affect_blood(var/mob/living/carbon/M, var/alien, var/removed)
if(alien == IS_DIONA)
return
M.add_chemical_effect(CE_MIND, -2)
if(alien == IS_SKRELL)
M.hallucination(25, 30)
else
M.hallucination(50, 50)
/datum/reagent/psilocybin
name = "Psilocybin"
description = "A strong psycotropic derived from certain species of mushroom."
taste_description = "mushroom"
color = "#e700e7"
overdose = REAGENTS_OVERDOSE
metabolism = REM * 0.5
/datum/reagent/psilocybin/affect_blood(var/mob/living/carbon/M, var/alien, var/removed)
if(alien == IS_DIONA)
return
var/threshold = 1
if(alien == IS_SKRELL)
threshold = 1.2
M.druggy = max(M.druggy, 30)
if(M.chem_doses[type] < 1 * threshold)
M.apply_effect(3, STUTTER)
M.make_dizzy(5)
if(prob(5))
M.emote(pick("twitch", "giggle"))
else if(M.chem_doses[type] < 2 * threshold)
M.apply_effect(3, STUTTER)
M.make_jittery(5)
M.make_dizzy(5)
M.druggy = max(M.druggy, 35)
if(prob(10))
M.emote(pick("twitch", "giggle"))
else
M.add_chemical_effect(CE_MIND, -1)
M.apply_effect(3, STUTTER)
M.make_jittery(10)
M.make_dizzy(10)
M.druggy = max(M.druggy, 40)
if(prob(15))
M.emote(pick("twitch", "giggle"))
M.add_event("high", /datum/happiness_event/high)
/* Transformations */
/datum/reagent/slimetoxin
name = "Mutation Toxin"
description = "A corruptive toxin produced by slimes."
taste_description = "sludge"
reagent_state = REAGENT_LIQUID
color = "#13bc5e"
metabolism = REM * 0.2
/datum/reagent/slimetoxin/affect_blood(var/mob/living/carbon/human/H, var/alien, var/removed)
if(!istype(H))
return
if(H.species.name == SPECIES_PROMETHEAN)
return
H.adjustToxLoss(40 * removed)
if(H.chem_doses[type] < 1 || prob(30))
return
H.chem_doses[type] = 0
var/list/meatchunks = list()
for(var/limb_tag in list(BP_R_ARM, BP_L_ARM, BP_R_LEG,BP_L_LEG))
var/obj/item/organ/external/E = H.get_organ(limb_tag)
if(!E.is_stump() && E.robotic < ORGAN_ROBOT && E.species.name != SPECIES_PROMETHEAN)
meatchunks += E
if(!meatchunks.len)
return
var/obj/item/organ/external/O = pick(meatchunks)
to_chat(H, "<span class='danger'>Your [O.name]'s flesh mutates rapidly!</span>")
meatchunks = list(O) | O.children
for(var/obj/item/organ/external/E in meatchunks)
E.species = all_species[SPECIES_PROMETHEAN]
E.s_tone = null
E.s_col = ReadRGB("#05ff9b")
E.s_col_blend = ICON_ADD
E.status &= ~ORGAN_BROKEN
E.status |= ORGAN_MUTATED
E.cannot_break = 1
E.dislocated = -1
E.nonsolid = 1
E.max_damage = 5
E.update_icon(1)
O.max_damage = 15
if(prob(10))
to_chat(H, "<span class='danger'>Your slimy [O.name]'s plops off!</span>")
O.droplimb()
H.update_body()
/datum/reagent/aslimetoxin
name = "Advanced Mutation Toxin"
description = "An advanced corruptive toxin produced by slimes."
taste_description = "sludge"
reagent_state = REAGENT_LIQUID
color = "#13bc5e"
/datum/reagent/aslimetoxin/affect_blood(var/mob/living/carbon/M, var/alien, var/removed) // TODO: check if there's similar code anywhere else
if(M.transforming)
return
to_chat(M, "<span class='danger'>Your flesh rapidly mutates!</span>")
M.transforming = 1
M.canmove = 0
M.icon = null
M.overlays.Cut()
M.set_invisibility(101)
for(var/obj/item/W in M)
if(istype(W, /obj/item/implant)) //TODO: Carn. give implants a dropped() or something
qdel(W)
continue
M.drop_from_inventory(W)
var/mob/living/carbon/slime/new_mob = new /mob/living/carbon/slime(M.loc)
new_mob.a_intent = "hurt"
new_mob.universal_speak = 1
if(M.mind)
M.mind.transfer_to(new_mob)
else
new_mob.key = M.key
qdel(M)
/datum/reagent/nanites
name = "Nanomachines"
description = "Microscopic construction robots."
taste_description = "slimey metal"
reagent_state = REAGENT_LIQUID
color = "#535e66"
/datum/reagent/xenomicrobes
name = "Xenomicrobes"
description = "Microbes with an entirely alien cellular structure."
taste_description = "sludge"
reagent_state = REAGENT_LIQUID
color = "#535e66"
/datum/reagent/toxin/hair_remover
name = "Hair Remover"
description = "An extremely effective chemical depilator. Do not ingest."
taste_description = "acid"
reagent_state = REAGENT_LIQUID
color = "#d9ffb3"
strength = 1
overdose = REAGENTS_OVERDOSE
/datum/reagent/toxin/hair_remover/affect_touch(var/mob/living/carbon/human/M, var/alien, var/removed)
if(alien == IS_SKRELL) //skrell can't have hair unless you hack it in, also to prevent tentacles from falling off
return
M.species.set_default_hair(M)
to_chat(M, "<span class='warning'>Your feel a chill, your skin feels lighter..</span>")
remove_self(volume)
/datum/reagent/toxin/corrupting
name = "Corruption"
description = "a loyalty changing liquid."
taste_description = "blood"
color = "#ffffff"
taste_mult = 5
strength = 10
metabolism = REM * 2
overdose = 30
/datum/reagent/toxin/corrupting/affect_touch(var/mob/living/carbon/M, var/alien, var/removed)
affect_blood(M,alien,removed*0.5)
/datum/reagent/toxin/corrupting/affect_blood(var/mob/living/carbon/M, var/alien, var/removed)
..()
if(prob(5))
if(M.chem_doses[type] < 15)
to_chat(M, "<span class='warning'>You feel funny...</span>")
else
to_chat(M, "<span class='danger'>You feel like you could die at any moment!</span>")
/datum/reagent/toxin/corrupting/overdose(var/mob/living/carbon/M, var/alien)
if(istype(M, /mob/living/carbon/human))
var/mob/living/carbon/human/H = M
H.zombieze()
remove_self(volume)
| 412 | 0.931654 | 1 | 0.931654 | game-dev | MEDIA | 0.999501 | game-dev | 0.852412 | 1 | 0.852412 |
BahamutDragon/pcgen | 2,835 | data/starwars_saga_edition/wizards_of_the_coast/star_wars_saga_edition_core_rulebook/cr_kits.lst | # CVS $Revision: $ $Author: $ -- Thu Jul 4 11:45:43 2013 -- reformated by prettylst.pl v1.50 (build 20400)
STARTPACK:Droid Default Gear VISIBLE:QUALIFY EQUIPBUY:0 PREMULT:1,[!PRERACE:1,%],[PRERACE:1,Droid%]
GEAR:Heuristic Processor SIZE:PC LOCATION:Equipped
STARTPACK:Droid Claw VISIBLE:QUALIFY EQUIPBUY:0 PREMULT:1,[!PRERACE:1,%],[PRERACE:1,Droid%]
GEAR:Claw SIZE:PC LOCATION:Equipped
STARTPACK:Droid Hand VISIBLE:QUALIFY EQUIPBUY:0 PREMULT:1,[!PRERACE:1,%],[PRERACE:1,Droid%]
GEAR:Hand SIZE:PC LOCATION:Equipped
STARTPACK:Droid Instrument VISIBLE:QUALIFY EQUIPBUY:0 PREMULT:1,[!PRERACE:1,%],[PRERACE:1,Droid%]
GEAR:Instrument SIZE:PC LOCATION:Equipped
STARTPACK:Droid Probe VISIBLE:QUALIFY EQUIPBUY:0 PREMULT:1,[!PRERACE:1,%],[PRERACE:1,Droid%]
GEAR:Probe SIZE:PC LOCATION:Equipped
STARTPACK:Droid Tool VISIBLE:QUALIFY EQUIPBUY:0 PREMULT:1,[!PRERACE:1,%],[PRERACE:1,Droid%]
GEAR:Tool SIZE:PC LOCATION:Equipped
STARTPACK:Acklay Default VISIBLE:QUALIFY EQUIPBUY:0 PREMULT:1,[!PRERACE:1,%],[PRERACE:1,Acklay]
STAT:STR=11|DEX=11|CON=11|INT=10|WIS=11|CHA=11
RACE:Acklay !PRERACE:1,%
ABILITY:CATEGORY=FEAT|Cleave
ABILITY:CATEGORY=FEAT|Power Attack
ABILITY:CATEGORY=FEAT|Skill Training (Initiative)
ABILITY:CATEGORY=FEAT|Skill Training (Perception)
STARTPACK:Dewback Default VISIBLE:QUALIFY EQUIPBUY:0 PREMULT:1,[!PRERACE:1,%],[PRERACE:1,Dewback]
STAT:STR=11|DEX=10|CON=10|INT=11|WIS=10|CHA=11
RACE:Dewback !PRERACE:1,%
ABILITY:CATEGORY=FEAT|Improved Damage Threshold
ABILITY:CATEGORY=FEAT|Toughness
STARTPACK:Nexu Default VISIBLE:QUALIFY EQUIPBUY:0 PREMULT:1,[!PRERACE:1,%],[PRERACE:1,Nexu]
STAT:STR=10|DEX=10|CON=11|INT=10|WIS=10|CHA=10
RACE:Nexu !PRERACE:1,%
ABILITY:CATEGORY=FEAT|Pin
ABILITY:CATEGORY=FEAT|Skill Training (Initiative)
ABILITY:CATEGORY=FEAT|Skill Training (Perception)
STARTPACK:Rancor Default VISIBLE:QUALIFY EQUIPBUY:0 PREMULT:1,[!PRERACE:1,%],[PRERACE:1,Rancor]
STAT:STR=10|DEX=11|CON=11|INT=10|WIS=11|CHA=11
RACE:Rancor !PRERACE:1,%
ABILITY:CATEGORY=FEAT|Cleave
ABILITY:CATEGORY=FEAT|Crush
ABILITY:CATEGORY=FEAT|Pin
ABILITY:CATEGORY=FEAT|Power Attack
ABILITY:CATEGORY=FEAT|Toughness
STARTPACK:Reek Default VISIBLE:QUALIFY EQUIPBUY:0 PREMULT:1,[!PRERACE:1,%],[PRERACE:1,Reek]
STAT:STR=11|DEX=10|CON=10|INT=10|WIS=10|CHA=10
RACE:Reek !PRERACE:1,%
ABILITY:CATEGORY=FEAT|Power Attack
ABILITY:CATEGORY=FEAT|Powerful Charge
ABILITY:CATEGORY=FEAT|Toughness
STARTPACK:Tauntaun Default VISIBLE:QUALIFY EQUIPBUY:0 PREMULT:1,[!PRERACE:1,%],[PRERACE:1,Tauntaun]
STAT:STR=10|DEX=10|CON=10|INT=10|WIS=10|CHA=10
RACE:Tauntaun !PRERACE:1,%
ABILITY:CATEGORY=FEAT|Toughness
STARTPACK:Wampa Default VISIBLE:QUALIFY EQUIPBUY:0 PREMULT:1,[!PRERACE:1,%],[PRERACE:1,Wampa]
STAT:STR=10|DEX=10|CON=10|INT=10|WIS=11|CHA=11
RACE:Wampa !PRERACE:1,%
ABILITY:CATEGORY=FEAT|Power Attack
ABILITY:CATEGORY=FEAT|Skill Training (Stealth)
| 412 | 0.575217 | 1 | 0.575217 | game-dev | MEDIA | 0.983186 | game-dev | 0.757287 | 1 | 0.757287 |
Filigrani/SkyCoop | 40,696 | ExpeditionEditor.cs | using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using static SkyCoop.DataStr;
using static SkyCoop.ExpeditionBuilder;
using static SkyCoop.ExpeditionManager;
using MelonLoader.TinyJSON;
using MelonLoader;
using System.Security.Policy;
using static SkyCoop.Comps;
using Harmony;
using Il2Cpp;
namespace SkyCoop
{
public class ExpeditionEditor
{
public static List<ExpeditionGearSpawner> m_Spawns = new List<ExpeditionGearSpawner>();
public static Vector3 m_Center = new Vector3(0, 0, 0);
public static List<string> m_Containers = new List<string>();
public static List<string> m_Plants = new List<string>();
public static List<string> m_Breakdowns = new List<string>();
public static List<UniversalSyncableObjectSpawner> m_Objects = new List<UniversalSyncableObjectSpawner>();
public static List<GameObject> m_VisualizeObjects = new List<GameObject>();
public static string m_LastSpawnerGUID = "";
public static string m_LastObjectGUID = "";
public static float m_LastChance = 0;
public static int m_LastType = 0;
public static float m_LastRadious = 0;
public static GameObject m_InnerSphere = null;
public static GameObject m_OutterSphere = null;
public static int LastSelectedRegion = 6;
#if (DEDICATED_LINUX)
public static string Seperator = @"/";
#else
public static string Seperator = @"\";
#endif
public static void DisableRadiousSpheres()
{
if (m_InnerSphere != null)
{
m_InnerSphere.SetActive(false);
}
if (m_OutterSphere != null)
{
m_OutterSphere.SetActive(false);
}
}
public static void SetRadiousSpheres()
{
if(m_LastType == (int) ExpeditionTaskType.ENTERSCENE)
{
if (m_InnerSphere != null)
{
m_InnerSphere.SetActive(false);
}
if (m_OutterSphere != null)
{
m_OutterSphere.SetActive(false);
}
return;
}
float Radious = MyMod.ExpeditionEditorUI.transform.GetChild(6).gameObject.GetComponent<UnityEngine.UI.Slider>().m_Value;
if (m_InnerSphere == null)
{
m_InnerSphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
m_OutterSphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
UnityEngine.Object.Destroy(m_InnerSphere.GetComponent<SphereCollider>());
UnityEngine.Object.Destroy(m_OutterSphere.GetComponent<SphereCollider>());
}
m_InnerSphere.transform.position = m_Center;
m_InnerSphere.transform.localScale = new Vector3(Radious * 2, Radious * 2, Radious * 2);
m_InnerSphere.SetActive(true);
m_OutterSphere.transform.position = m_Center;
m_OutterSphere.transform.localScale = new Vector3(-Radious * 2, -Radious * 2, -Radious * 2);
m_OutterSphere.SetActive(true);
}
public static void DisableAllPanels()
{
MyMod.ExpeditionEditorUI.transform.GetChild(13).gameObject.SetActive(false);
MyMod.ExpeditionEditorUI.transform.GetChild(14).gameObject.SetActive(false);
MyMod.ExpeditionEditorUI.transform.GetChild(14).GetChild(7).gameObject.SetActive(false);
MyMod.ExpeditionEditorUI.transform.GetChild(27).gameObject.SetActive(false);
MyMod.ExpeditionEditorUI.transform.GetChild(28).gameObject.SetActive(false);
MyMod.ExpeditionEditorUI.transform.GetChild(31).gameObject.SetActive(false);
MyMod.ExpeditionEditorUI.transform.GetChild(31).GetChild(4).gameObject.SetActive(false);
}
public static void BackToSelect(int Region)
{
RefreshExpeditionsList(Region);
DisableAllPanels();
MyMod.ExpeditionEditorUI.SetActive(false);
MyMod.ExpeditionEditorSelectUI.SetActive(true);
DisableRadiousSpheres();
DisableVisualizeObjects();
}
public static void ExpeditionTypeChanged()
{
MyMod.ExpeditionEditorUI.transform.GetChild(17).GetComponent<UnityEngine.UI.Toggle>().Set(m_LastType == (int)ExpeditionTaskType.ENTERSCENE);
SetRadiousSpheres();
}
public static void ExpeditionRadiousChanged()
{
SetRadiousSpheres();
}
public static void SetObjectiveGear()
{
MyMod.ExpeditionEditorUI.transform.GetChild(20).GetComponent<UnityEngine.UI.InputField>().SetText(m_LastSpawnerGUID);
}
public static void AutoSelectRegion()
{
if (GameManager.GetUniStorm() != null)
{
int Region = (int)MyMod.ConvertGameRegion(GameManager.GetUniStorm().m_CurrentRegion);
Region += Shared.GameRegionNegativeOffset;
MyMod.ExpeditionEditorUI.transform.GetChild(1).gameObject.GetComponent<UnityEngine.UI.Dropdown>().Set(Region);
}
}
public static void AutoSelectScene()
{
MyMod.ExpeditionEditorUI.transform.GetChild(4).gameObject.GetComponent<UnityEngine.UI.InputField>().SetText(MyMod.level_guid);
}
public static void ToggleContainersList()
{
bool OldState = MyMod.ExpeditionEditorUI.transform.GetChild(13).gameObject.activeSelf;
DisableAllPanels();
MyMod.ExpeditionEditorUI.transform.GetChild(13).gameObject.SetActive(!OldState);
}
public static void ToggleGearsList()
{
bool OldState = MyMod.ExpeditionEditorUI.transform.GetChild(14).gameObject.activeSelf;
DisableAllPanels();
MyMod.ExpeditionEditorUI.transform.GetChild(14).gameObject.SetActive(!OldState);
}
public static void ToggleHarvestablesList()
{
bool OldState = MyMod.ExpeditionEditorUI.transform.GetChild(27).gameObject.activeSelf;
DisableAllPanels();
MyMod.ExpeditionEditorUI.transform.GetChild(27).gameObject.SetActive(!OldState);
}
public static void ToggleBreakdownsList()
{
bool OldState = MyMod.ExpeditionEditorUI.transform.GetChild(28).gameObject.activeSelf;
DisableAllPanels();
MyMod.ExpeditionEditorUI.transform.GetChild(28).gameObject.SetActive(!OldState);
}
public static void ToggleExtraPanel()
{
MyMod.ExpeditionEditorUI.transform.GetChild(14).GetChild(7).gameObject.SetActive(!MyMod.ExpeditionEditorUI.transform.GetChild(14).GetChild(7).gameObject.activeSelf);
}
public static void ToggleObjectSettingsPanel()
{
MyMod.ExpeditionEditorUI.transform.GetChild(31).GetChild(4).gameObject.SetActive(!MyMod.ExpeditionEditorUI.transform.GetChild(31).GetChild(4).gameObject.activeSelf);
}
public static void ToggleObjectsList()
{
bool OldState = MyMod.ExpeditionEditorUI.transform.GetChild(31).gameObject.activeSelf;
DisableAllPanels();
MyMod.ExpeditionEditorUI.transform.GetChild(31).gameObject.SetActive(!OldState);
}
public static void AutoPositionSelect()
{
m_Center = GameManager.GetPlayerTransform().position;
SetRadiousSpheres();
}
public static void SetContainerContent()
{
if (!string.IsNullOrEmpty(m_LastObjectGUID))
{
string ContainerData = MPSaveManager.LoadContainer(MyMod.level_guid, m_LastObjectGUID);
if (!string.IsNullOrEmpty(ContainerData))
{
MyMod.ExpeditionEditorUI.transform.GetChild(31).GetChild(4).GetChild(1).gameObject.GetComponent<UnityEngine.UI.InputField>().SetText(ContainerData);
UpdateObjectSettings();
}
}
}
public static void SaveExpeditionTemplate()
{
int Type = MyMod.ExpeditionEditorUI.transform.GetChild(3).GetComponent<UnityEngine.UI.Dropdown>().m_Value;
MPSaveManager.CreateFolderIfNotExist("Mods");
MPSaveManager.CreateFolderIfNotExist(@"Mods\ExpeditionTemplates");
string Alias = MyMod.ExpeditionEditorUI.transform.GetChild(9).GetComponent<UnityEngine.UI.InputField>().text;
ExpeditionTaskTemplate Task = new ExpeditionTaskTemplate();
Task.m_TaskType = (ExpeditionTaskType)Type;
Task.m_Alias = Alias;
Task.m_RegionBelong = MyMod.ExpeditionEditorUI.transform.GetChild(1).GetComponent<UnityEngine.UI.Dropdown>().m_Value-Shared.GameRegionNegativeOffset;
Task.m_SceneName = MyMod.ExpeditionEditorUI.transform.GetChild(4).GetComponent<UnityEngine.UI.InputField>().text;
Task.m_TaskText = MyMod.ExpeditionEditorUI.transform.GetChild(10).GetComponent<UnityEngine.UI.InputField>().text;
Task.m_GearSpawners = m_Spawns;
Task.m_Containers = m_Containers;
Task.m_ZoneCenter = m_Center;
Task.m_ZoneRadius = MyMod.ExpeditionEditorUI.transform.GetChild(6).gameObject.GetComponent<UnityEngine.UI.Slider>().m_Value;
Task.m_RestockSceneContainers = MyMod.ExpeditionEditorUI.transform.GetChild(17).GetComponent<UnityEngine.UI.Toggle>().isOn;
Task.m_CanBeTaken = MyMod.ExpeditionEditorUI.transform.GetChild(18).GetComponent<UnityEngine.UI.Toggle>().isOn;
Task.m_NextTaskAlias = MyMod.ExpeditionEditorUI.transform.GetChild(19).GetComponent<UnityEngine.UI.InputField>().text;
Task.m_ObjectiveGearGUID = MyMod.ExpeditionEditorUI.transform.GetChild(20).GetComponent<UnityEngine.UI.InputField>().text;
Task.m_CompleatOrder = (ExpeditionCompleteOrder)MyMod.ExpeditionEditorUI.transform.GetChild(21).GetComponent<UnityEngine.UI.Dropdown>().m_Value;
Task.m_RandomTasksAmout = int.Parse(MyMod.ExpeditionEditorUI.transform.GetChild(22).GetComponent<UnityEngine.UI.InputField>().text);
Task.m_Time = int.Parse(MyMod.ExpeditionEditorUI.transform.GetChild(23).GetComponent<UnityEngine.UI.InputField>().text);
Task.m_TimeAdd = MyMod.ExpeditionEditorUI.transform.GetChild(24).GetComponent<UnityEngine.UI.Dropdown>().m_Value == 0;
Task.m_Plants = m_Plants;
Task.m_Breakdowns = m_Breakdowns;
Task.m_StaySeconds = int.Parse(MyMod.ExpeditionEditorUI.transform.GetChild(29).GetComponent<UnityEngine.UI.InputField>().text);
Task.m_Objects = m_Objects;
MPSaveManager.SaveData(Alias + ".json", JSON.Dump(Task), 0, @"Mods\ExpeditionTemplates\" + Alias + ".json");
}
public static void AddContainer(string GUID)
{
if (!m_Containers.Contains(GUID))
{
m_Containers.Add(GUID);
RecontructContainersList();
HUDMessage.AddMessage("Added Container " + GUID);
} else
{
HUDMessage.AddMessage("Container " + GUID + " is already added!");
}
}
public static void AddPlant(string GUID)
{
if (!m_Plants.Contains(GUID))
{
m_Plants.Add(GUID);
RecontructHarvestablesList();
HUDMessage.AddMessage("Added Harvestable " + GUID);
} else
{
HUDMessage.AddMessage("Harvestable " + GUID + " is already added!");
}
}
public static void AddBreakdown(string GUID)
{
if (!m_Breakdowns.Contains(GUID))
{
m_Breakdowns.Add(GUID);
RecontructBreakdownsList();
HUDMessage.AddMessage("Added Breakdown " + GUID);
} else
{
HUDMessage.AddMessage("Breakdown " + GUID + " is already added!");
}
}
public static void RemoveContainerFromList(GameObject Element)
{
m_Containers.Remove(Element.transform.GetChild(0).gameObject.GetComponent<UnityEngine.UI.Text>().text);
RecontructContainersList();
}
public static void RemoveHarvestableFromList(GameObject Element)
{
m_Plants.Remove(Element.transform.GetChild(0).gameObject.GetComponent<UnityEngine.UI.Text>().text);
RecontructHarvestablesList();
}
public static void RemoveBreakdownFromList(GameObject Element)
{
m_Breakdowns.Remove(Element.transform.GetChild(0).gameObject.GetComponent<UnityEngine.UI.Text>().text);
RecontructBreakdownsList();
}
public static void ClearSelectedGear()
{
MyMod.ExpeditionEditorUI.transform.GetChild(14).GetChild(2).gameObject.GetComponent<UnityEngine.UI.Text>().text = "GUID:";
MyMod.ExpeditionEditorUI.transform.GetChild(14).GetChild(3).gameObject.GetComponent<UnityEngine.UI.Slider>().Set(0, false);
MyMod.ExpeditionEditorUI.transform.GetChild(14).GetChild(4).gameObject.GetComponent<UnityEngine.UI.Dropdown>().ClearOptions();
}
public static void ClearSelectedObject()
{
MyMod.ExpeditionEditorUI.transform.GetChild(31).GetChild(2).gameObject.GetComponent<UnityEngine.UI.Text>().text = "GUID:";
}
public static void UpdateExtra()
{
for (int i = m_Spawns.Count - 1; i >= 0; i--)
{
if (m_Spawns[i].m_GUID == m_LastSpawnerGUID)
{
m_Spawns[i].m_Extra.m_Dropper = MyMod.ExpeditionEditorUI.transform.GetChild(14).GetChild(7).GetChild(1).GetComponent<UnityEngine.UI.InputField>().text;
m_Spawns[i].m_Extra.m_PhotoGUID = MyMod.ExpeditionEditorUI.transform.GetChild(14).GetChild(7).GetChild(2).GetComponent<UnityEngine.UI.InputField>().text;
m_Spawns[i].m_Extra.m_ExpeditionNote = MyMod.ExpeditionEditorUI.transform.GetChild(14).GetChild(7).GetChild(4).GetComponent<UnityEngine.UI.InputField>().text;
return;
}
}
}
public static void UpdateObjectSettings()
{
for (int i = m_Objects.Count - 1; i >= 0; i--)
{
if (m_Objects[i].m_GUID == m_LastObjectGUID)
{
m_Objects[i].m_Content = MyMod.ExpeditionEditorUI.transform.GetChild(31).GetChild(4).GetChild(1).gameObject.GetComponent<UnityEngine.UI.InputField>().text;
return;
}
}
}
public static void UpdateGear()
{
ClearSelectedGear();
if (!string.IsNullOrEmpty(m_LastSpawnerGUID))
{
for (int i = m_Spawns.Count - 1; i >= 0; i--)
{
if (m_Spawns[i].m_GUID == m_LastSpawnerGUID)
{
MyMod.ExpeditionEditorUI.transform.GetChild(14).GetChild(2).gameObject.GetComponent<UnityEngine.UI.Text>().text = "GUID: "+ m_Spawns[i].m_GUID;
MyMod.ExpeditionEditorUI.transform.GetChild(14).GetChild(3).gameObject.GetComponent<UnityEngine.UI.Slider>().Set(m_Spawns[i].m_Chance, false);
m_LastChance = m_Spawns[i].m_Chance;
UnityEngine.UI.Dropdown Drop = MyMod.ExpeditionEditorUI.transform.GetChild(14).GetChild(4).gameObject.GetComponent<UnityEngine.UI.Dropdown>();
for (int i2 = 0; i2 < m_Spawns[i].m_GearsVariant.Count; i2++)
{
Drop.options.Add(new UnityEngine.UI.Dropdown.OptionData(m_Spawns[i].m_GearsVariant[i2]));
}
if(m_Spawns[i].m_GearsVariant.Count == 1)
{
Drop.Set(1);
} else
{
Drop.Set(m_Spawns[i].m_GearsVariant.Count - 1);
}
MyMod.ExpeditionEditorUI.transform.GetChild(14).GetChild(7).GetChild(1).GetComponent<UnityEngine.UI.InputField>().SetText(m_Spawns[i].m_Extra.m_Dropper);
MyMod.ExpeditionEditorUI.transform.GetChild(14).GetChild(7).GetChild(2).GetComponent<UnityEngine.UI.InputField>().SetText(m_Spawns[i].m_Extra.m_PhotoGUID);
MyMod.ExpeditionEditorUI.transform.GetChild(14).GetChild(7).GetChild(4).GetComponent<UnityEngine.UI.InputField>().SetText(m_Spawns[i].m_Extra.m_ExpeditionNote);
return;
}
}
}
}
public static void UpdateObject()
{
ClearSelectedObject();
if (!string.IsNullOrEmpty(m_LastObjectGUID))
{
for (int i = m_Objects.Count - 1; i >= 0; i--)
{
if (m_Objects[i].m_GUID == m_LastObjectGUID)
{
MyMod.ExpeditionEditorUI.transform.GetChild(31).GetChild(2).gameObject.GetComponent<UnityEngine.UI.Text>().text = "GUID: " + m_LastObjectGUID;
MyMod.ExpeditionEditorUI.transform.GetChild(31).GetChild(4).GetChild(1).gameObject.GetComponent<UnityEngine.UI.InputField>().SetText(m_Objects[i].m_Content);
return;
}
}
}
}
public static void RemoveObjectFromList(GameObject Element)
{
string GUID = Element.GetComponent<LocalVariablesKit>().m_String;
for (int i = m_Objects.Count - 1; i >= 0; i--)
{
if (m_Objects[i].m_GUID == GUID)
{
if (m_LastObjectGUID == GUID)
{
ClearSelectedObject();
}
m_Objects.RemoveAt(i);
RecontructObjectsList();
VisualizeObjects();
return;
}
}
}
public static void SelectObjectFromList(GameObject Element)
{
string GUID = Element.GetComponent<LocalVariablesKit>().m_String;
for (int i = m_Objects.Count - 1; i >= 0; i--)
{
if (m_Objects[i].m_GUID == GUID)
{
UpdateObjectSettings();
m_LastObjectGUID = GUID;
UpdateObject();
return;
}
}
}
public static void RemoveGearFromList(GameObject Element)
{
string GUID = Element.GetComponent<LocalVariablesKit>().m_String;
DebugLog("RemoveGearFromList " + GUID);
for (int i = m_Spawns.Count - 1; i >= 0; i--)
{
if (m_Spawns[i].m_GUID == GUID)
{
if(m_LastSpawnerGUID == GUID)
{
ClearSelectedGear();
}
m_Spawns.RemoveAt(i);
RecontructGearsList();
return;
}
}
}
public static void SelectGearFromList(GameObject Element)
{
string GUID = Element.GetComponent<LocalVariablesKit>().m_String;
DebugLog("SelectGearFromList "+ GUID);
for (int i = m_Spawns.Count - 1; i >= 0; i--)
{
if (m_Spawns[i].m_GUID == GUID)
{
UpdateExtra();
m_LastSpawnerGUID = GUID;
UpdateGear();
return;
}
}
}
public static void RecontructContainersList()
{
GameObject Content = MyMod.ExpeditionEditorUI.transform.GetChild(13).GetChild(1).GetChild(0).GetChild(0).gameObject;
for (int i = Content.transform.childCount - 1; i >= 0; i--)
{
UnityEngine.Object.Destroy(Content.transform.GetChild(i).gameObject);
}
GameObject LoadedAssets = MyMod.LoadedBundle.LoadAsset<GameObject>("MP_ContainerElement");
foreach (string GUID in m_Containers)
{
GameObject Element = GameObject.Instantiate(LoadedAssets, Content.transform);
Element.transform.GetChild(0).gameObject.GetComponent<UnityEngine.UI.Text>().text = GUID;
Action act = new Action(() => RemoveContainerFromList(Element));
Element.transform.GetChild(1).gameObject.GetComponent<UnityEngine.UI.Button>().onClick.AddListener(act);
}
}
public static void RecontructHarvestablesList()
{
GameObject Content = MyMod.ExpeditionEditorUI.transform.GetChild(27).GetChild(1).GetChild(0).GetChild(0).gameObject;
for (int i = Content.transform.childCount - 1; i >= 0; i--)
{
UnityEngine.Object.Destroy(Content.transform.GetChild(i).gameObject);
}
GameObject LoadedAssets = MyMod.LoadedBundle.LoadAsset<GameObject>("MP_ContainerElement");
foreach (string GUID in m_Plants)
{
GameObject Element = GameObject.Instantiate(LoadedAssets, Content.transform);
Element.transform.GetChild(0).gameObject.GetComponent<UnityEngine.UI.Text>().text = GUID;
Action act = new Action(() => RemoveHarvestableFromList(Element));
Element.transform.GetChild(1).gameObject.GetComponent<UnityEngine.UI.Button>().onClick.AddListener(act);
}
}
public static void RecontructBreakdownsList()
{
GameObject Content = MyMod.ExpeditionEditorUI.transform.GetChild(28).GetChild(1).GetChild(0).GetChild(0).gameObject;
for (int i = Content.transform.childCount - 1; i >= 0; i--)
{
UnityEngine.Object.Destroy(Content.transform.GetChild(i).gameObject);
}
GameObject LoadedAssets = MyMod.LoadedBundle.LoadAsset<GameObject>("MP_ContainerElement");
foreach (string GUID in m_Breakdowns)
{
GameObject Element = GameObject.Instantiate(LoadedAssets, Content.transform);
Element.transform.GetChild(0).gameObject.GetComponent<UnityEngine.UI.Text>().text = GUID;
Action act = new Action(() => RemoveBreakdownFromList(Element));
Element.transform.GetChild(1).gameObject.GetComponent<UnityEngine.UI.Button>().onClick.AddListener(act);
}
}
public static void RecontructObjectsList()
{
GameObject Content = MyMod.ExpeditionEditorUI.transform.GetChild(31).GetChild(1).GetChild(0).GetChild(0).gameObject;
for (int i = Content.transform.childCount - 1; i >= 0; i--)
{
UnityEngine.Object.Destroy(Content.transform.GetChild(i).gameObject);
}
GameObject LoadedAssets = MyMod.LoadedBundle.LoadAsset<GameObject>("MP_GearElement");
foreach (UniversalSyncableObjectSpawner Object in m_Objects)
{
GameObject Element = GameObject.Instantiate(LoadedAssets, Content.transform);
Element.AddComponent<LocalVariablesKit>().m_String = Object.m_GUID;
Element.transform.GetChild(0).GetChild(0).gameObject.GetComponent<UnityEngine.UI.Text>().text = Object.m_Prefab;
Action act = new Action(() => RemoveObjectFromList(Element));
Element.transform.GetChild(1).gameObject.GetComponent<UnityEngine.UI.Button>().onClick.AddListener(act);
Action act2 = new Action(() => SelectObjectFromList(Element));
Element.transform.GetChild(0).gameObject.GetComponent<UnityEngine.UI.Button>().onClick.AddListener(act2);
}
}
public static void AddGear(string GearPrefab, Vector3 Pos, Quaternion Rot, string PHOTOGUID)
{
ExpeditionGearSpawner Spawner = new ExpeditionGearSpawner();
Spawner.m_GUID = Guid.NewGuid().ToString();
Spawner.m_Chance = 0.33f;
Spawner.m_GearsVariant.Add(GearPrefab);
Spawner.m_Possition = Pos;
Spawner.m_Rotation = Rot;
Spawner.m_Extra.m_PhotoGUID = PHOTOGUID;
m_Spawns.Add(Spawner);
if (!string.IsNullOrEmpty(PHOTOGUID))
{
MPSaveManager.CopyPhotoToExpeditionCache(PHOTOGUID);
}
HUDMessage.AddMessage("Added Gear " + Spawner.m_GUID);
RecontructGearsList();
UpdateExtra();
m_LastSpawnerGUID = Spawner.m_GUID;
UpdateGear();
}
public static void AddGearVariant(string GearPrefab)
{
if (!string.IsNullOrEmpty(m_LastSpawnerGUID))
{
for (int i = m_Spawns.Count - 1; i >= 0; i--)
{
if (m_Spawns[i].m_GUID == m_LastSpawnerGUID)
{
if (!m_Spawns[i].m_GearsVariant.Contains(GearPrefab))
{
m_Spawns[i].m_GearsVariant.Add(GearPrefab);
HUDMessage.AddMessage("Added" + GearPrefab + " Variant");
} else
{
HUDMessage.AddMessage(GearPrefab+" Already Added!");
}
UpdateGear();
return;
}
}
}
}
public static void RemoveGearVariant()
{
if (!string.IsNullOrEmpty(m_LastSpawnerGUID))
{
UnityEngine.UI.Dropdown Drop = MyMod.ExpeditionEditorUI.transform.GetChild(14).GetChild(4).gameObject.GetComponent<UnityEngine.UI.Dropdown>();
for (int i = m_Spawns.Count - 1; i >= 0; i--)
{
if (m_Spawns[i].m_GUID == m_LastSpawnerGUID)
{
if(m_Spawns[i].m_GearsVariant.Count > 1)
{
m_Spawns[i].m_GearsVariant.RemoveAt(Drop.m_Value);
}
UpdateGear();
return;
}
}
}
}
public static void ChangeChance()
{
if (!string.IsNullOrEmpty(m_LastSpawnerGUID))
{
for (int i = m_Spawns.Count - 1; i >= 0; i--)
{
if (m_Spawns[i].m_GUID == m_LastSpawnerGUID)
{
m_Spawns[i].m_Chance = MyMod.ExpeditionEditorUI.transform.GetChild(14).GetChild(3).gameObject.GetComponent<UnityEngine.UI.Slider>().value;
return;
}
}
}
}
public static void RecontructGearsList()
{
GameObject Content = MyMod.ExpeditionEditorUI.transform.GetChild(14).GetChild(1).GetChild(0).GetChild(0).gameObject;
for (int i = Content.transform.childCount-1; i >= 0; i--)
{
UnityEngine.Object.Destroy(Content.transform.GetChild(i).gameObject);
}
GameObject LoadedAssets = MyMod.LoadedBundle.LoadAsset<GameObject>("MP_GearElement");
foreach (ExpeditionGearSpawner Spawner in m_Spawns)
{
GameObject Element = GameObject.Instantiate(LoadedAssets, Content.transform);
Element.AddComponent<LocalVariablesKit>().m_String = Spawner.m_GUID;
Element.transform.GetChild(0).GetChild(0).gameObject.GetComponent<UnityEngine.UI.Text>().text = Spawner.m_GearsVariant[0];
Action act = new Action(() => RemoveGearFromList(Element));
Element.transform.GetChild(1).gameObject.GetComponent<UnityEngine.UI.Button>().onClick.AddListener(act);
Action act2 = new Action(() => SelectGearFromList(Element));
Element.transform.GetChild(0).gameObject.GetComponent<UnityEngine.UI.Button>().onClick.AddListener(act2);
}
}
public static void LoadExpedition(ExpeditionTaskTemplate Data)
{
MyMod.ExpeditionEditorUI.transform.GetChild(1).GetComponent<UnityEngine.UI.Dropdown>().Set(Data.m_RegionBelong+ Shared.GameRegionNegativeOffset);
MyMod.ExpeditionEditorUI.transform.GetChild(3).GetComponent<UnityEngine.UI.Dropdown>().Set((int)Data.m_TaskType);
MyMod.ExpeditionEditorUI.transform.GetChild(4).GetComponent<UnityEngine.UI.InputField>().SetText(Data.m_SceneName);
MyMod.ExpeditionEditorUI.transform.GetChild(6).GetComponent<UnityEngine.UI.Slider>().Set(Data.m_ZoneRadius);
m_Center = Data.m_ZoneCenter;
MyMod.ExpeditionEditorUI.transform.GetChild(9).GetComponent<UnityEngine.UI.InputField>().SetText(Data.m_Alias);
MyMod.ExpeditionEditorUI.transform.GetChild(10).GetComponent<UnityEngine.UI.InputField>().SetText(Data.m_TaskText);
MyMod.ExpeditionEditorUI.transform.GetChild(18).GetComponent<UnityEngine.UI.Toggle>().Set(Data.m_CanBeTaken);
m_Spawns = Data.m_GearSpawners;
m_Containers = Data.m_Containers;
MyMod.ExpeditionEditorUI.transform.GetChild(20).GetComponent<UnityEngine.UI.InputField>().SetText(Data.m_ObjectiveGearGUID);
MyMod.ExpeditionEditorUI.transform.GetChild(19).GetComponent<UnityEngine.UI.InputField>().SetText(Data.m_NextTaskAlias);
MyMod.ExpeditionEditorUI.transform.GetChild(21).GetComponent<UnityEngine.UI.Dropdown>().Set((int)Data.m_CompleatOrder);
MyMod.ExpeditionEditorUI.transform.GetChild(22).GetComponent<UnityEngine.UI.InputField>().SetText(Data.m_RandomTasksAmout.ToString());
MyMod.ExpeditionEditorUI.transform.GetChild(23).GetComponent<UnityEngine.UI.InputField>().SetText(Data.m_Time.ToString());
MyMod.ExpeditionEditorUI.transform.GetChild(29).GetComponent<UnityEngine.UI.InputField>().SetText(Data.m_StaySeconds.ToString());
int TimeType = 0;
if (!Data.m_TimeAdd)
{
TimeType = 1;
}
MyMod.ExpeditionEditorUI.transform.GetChild(24).GetComponent<UnityEngine.UI.Dropdown>().Set(TimeType);
m_Plants = Data.m_Plants;
m_Breakdowns = Data.m_Breakdowns;
m_Objects = Data.m_Objects;
RecontructContainersList();
RecontructGearsList();
RecontructHarvestablesList();
RecontructBreakdownsList();
RecontructObjectsList();
UpdateGear();
UpdateObject();
SetRadiousSpheres();
MyMod.ExpeditionEditorSelectUI.SetActive(false);
MyMod.ExpeditionEditorUI.SetActive(true);
}
public static void SelectExpedition(GameObject Element)
{
LocalVariablesKit Kit = Element.GetComponent<LocalVariablesKit>();
string Alias = Kit.m_String;
string JSONString = GetExpeditionJsonByAlias(Alias);
LoadExpedition(JSON.Load(JSONString).Make<ExpeditionTaskTemplate>());
}
public static void SelectRegion(GameObject Element)
{
LocalVariablesKit Kit = Element.GetComponent<LocalVariablesKit>();
int Region = Kit.m_Int;
LastSelectedRegion = Region;
RefreshExpeditionsList(Region);
}
public static void TestExpedition(GameObject Element)
{
string FileName = Element.transform.GetChild(0).gameObject.GetComponent<UnityEngine.UI.Text>().text;
string Alias = FileName.Replace(".json", "");
string MyMac = MPSaveManager.GetSubNetworkGUID();
for (int i = m_ActiveExpeditions.Count-1; i >= 0; i--)
{
if (m_ActiveExpeditions[i].m_Players.Contains(MyMac))
{
CompleteExpedition(m_ActiveExpeditions[i].m_GUID, 0);
}
}
StartNewExpedition(MyMac, 0, Alias);
DisableRadiousSpheres();
}
public static void DisableVisualizeObjects()
{
for (int i = m_VisualizeObjects.Count - 1; i >= 0; i--)
{
if(m_VisualizeObjects[i] != null && m_VisualizeObjects[i].GetComponent<ObjectGuid>())
{
bool Found = false;
for (int i2 = 0; i2 < m_Objects.Count; i2++)
{
if (m_Objects[i2].m_GUID == m_VisualizeObjects[i].GetComponent<ObjectGuid>().Get())
{
Found = true;
break;
}
}
if (!Found)
{
UnityEngine.Object.Destroy(m_VisualizeObjects[i]);
m_VisualizeObjects.RemoveAt(i);
}
}
}
}
public static void VisualizeObjects()
{
DisableVisualizeObjects();
foreach (UniversalSyncableObjectSpawner Spawner in m_Objects)
{
UniversalSyncableObject Obj = new UniversalSyncableObject();
Obj.m_Prefab = Spawner.m_Prefab;
Obj.m_GUID = Spawner.m_GUID;
Obj.m_Position = Spawner.m_Position;
Obj.m_Rotation = Spawner.m_Rotation;
MPSaveManager.RemoveContainer(MyMod.level_guid, Spawner.m_GUID);
if (!string.IsNullOrEmpty(Spawner.m_Content))
{
MPSaveManager.SaveContainer(MyMod.level_guid, Spawner.m_GUID, Spawner.m_Content);
MPSaveManager.SetConstainerState(MyMod.level_guid, Spawner.m_GUID, 1);
} else
{
MPSaveManager.SetConstainerState(MyMod.level_guid, Spawner.m_GUID, 2);
}
Obj.m_ExpeditionBelong = "";
Obj.m_Scene = MyMod.level_guid;
Obj.m_CreationTime = MyMod.MinutesFromStartServer;
GameObject newObject = MyMod.SpawnUniversalSyncableObject(Obj);
if (newObject)
{
m_VisualizeObjects.Add(newObject);
}
}
}
public static void ToggleColisionOfObject(GameObject obj, bool Status)
{
List<GameObject> list = new List<GameObject>();
list.Add(obj);
Transform Parent = obj.transform;
foreach (Transform child in Parent.GetComponentsInChildren<Transform>())
{
list.Add(child.gameObject);
}
foreach (GameObject obji in list)
{
foreach (BoxCollider Com in obji.GetComponents<BoxCollider>())
{
Com.enabled = Status;
}
foreach (SphereCollider Com in obji.GetComponents<SphereCollider>())
{
Com.enabled = Status;
}
foreach (MeshCollider Com in obji.GetComponents<MeshCollider>())
{
Com.enabled = Status;
}
foreach (Rigidbody Com in obji.GetComponents<Rigidbody>())
{
Com.isKinematic = true;
}
}
}
public static void PlaceVisualizedObject()
{
string GUID = m_LastObjectGUID;
GameObject Object = Il2CppTLD.PDID.PdidTable.GetGameObject(GUID);
if(Object)
{
GameManager.GetPlayerManagerComponent().StartPlaceMesh(Object, PlaceMeshFlags.None);
ToggleColisionOfObject(Object, false);
}
}
public static void AddObject()
{
string Prefab = MyMod.ExpeditionEditorUI.transform.GetChild(31).GetChild(5).GetComponent<UnityEngine.UI.InputField>().text;
UniversalSyncableObjectSpawner Spawner = new UniversalSyncableObjectSpawner();
Spawner.m_Prefab = Prefab;
Spawner.m_Position = GameManager.GetPlayerTransform().transform.position;
Spawner.m_Rotation = GameManager.GetPlayerTransform().transform.rotation;
Spawner.m_GUID = ObjectGuidManager.GenerateNewGuidString();
m_Objects.Add(Spawner);
m_LastObjectGUID = Spawner.m_GUID;
VisualizeObjects();
RecontructObjectsList();
UpdateObject();
UpdateObjectSettings();
}
public static bool LastOnlyShowFirstTasksState = false;
public static void RefreshExpeditionsList(int RegionMode = 6)
{
MPSaveManager.CreateFolderIfNotExist("Mods");
MPSaveManager.CreateFolderIfNotExist("Mods"+Seperator+ "ExpeditionTemplates");
DirectoryInfo d = new DirectoryInfo("Mods" + Seperator + "ExpeditionTemplates");
ExpeditionBuilder.Init(true);
List<string> Names = new List<string>();
List<int> RegionBelong = new List<int>();
foreach (var item in m_ExpeditionTasks)
{
int Region = item.Key;
if(RegionMode == 6)
{
Names.Add(GetRegionString(Region));
RegionBelong.Add(Region);
}else if(Region == RegionMode)
{
foreach (ExpeditionTaskTemplate task in item.Value)
{
if (!LastOnlyShowFirstTasksState || task.m_CanBeTaken)
{
Names.Add(task.m_Alias);
RegionBelong.Add(task.m_RegionBelong);
}
}
}
}
MyMod.ExpeditionEditorSelectUI.transform.GetChild(3).gameObject.SetActive(RegionMode == 6);
MyMod.ExpeditionEditorSelectUI.transform.GetChild(4).gameObject.SetActive(RegionMode != 6);
MyMod.ExpeditionEditorSelectUI.transform.GetChild(5).gameObject.SetActive(RegionMode != 6);
GameObject Content = MyMod.ExpeditionEditorSelectUI.transform.GetChild(1).GetChild(0).GetChild(0).gameObject;
for (int i = Content.transform.childCount - 1; i >= 0; i--)
{
UnityEngine.Object.Destroy(Content.transform.GetChild(i).gameObject);
}
GameObject LoadedAssets = MyMod.LoadedBundle.LoadAsset<GameObject>("MP_ExpeditionElement");
for (int i = 0; i < Names.Count; i++)
{
string Name = Names[i];
int Region = RegionBelong[i];
GameObject Element = GameObject.Instantiate(LoadedAssets, Content.transform);
LocalVariablesKit Kit = Element.AddComponent<LocalVariablesKit>();
Kit.m_Int = Region;
Kit.m_String = Name;
Element.transform.GetChild(0).gameObject.GetComponent<UnityEngine.UI.Text>().text = Name;
if(RegionMode != 6)
{
Action act = new Action(() => SelectExpedition(Element));
Element.transform.GetChild(1).gameObject.GetComponent<UnityEngine.UI.Button>().onClick.AddListener(act);
Action act2 = new Action(() => TestExpedition(Element));
Element.transform.GetChild(2).gameObject.GetComponent<UnityEngine.UI.Button>().onClick.AddListener(act2);
} else
{
Action act = new Action(() => SelectRegion(Element));
Element.transform.GetChild(2).gameObject.GetComponent<UnityEngine.UI.Button>().onClick.AddListener(act);
Element.transform.GetChild(1).gameObject.SetActive(false);
Element.transform.GetChild(2).GetChild(0).gameObject.GetComponent<UnityEngine.UI.Text>().text = "Open";
}
}
}
}
}
| 412 | 0.911067 | 1 | 0.911067 | game-dev | MEDIA | 0.987267 | game-dev | 0.968992 | 1 | 0.968992 |
shawwn/noh | 9,032 | src/sav_shared/i_triggerentity.cpp | // (C)2007 S2 Games
// i_triggerentity.cpp
//
//=============================================================================
//=============================================================================
// Headers
//=============================================================================
#include "game_shared_common.h"
#include "i_triggerentity.h"
#include "../k2/c_function.h"
//=============================================================================
//=============================================================================
// Definitions
//=============================================================================
vector<SDataField>* ITriggerEntity::s_pvFields;
//=============================================================================
/*====================
ITriggerEntity::CEntityConfig::CEntityConfig
====================*/
ITriggerEntity::CEntityConfig::CEntityConfig(const tstring &sName) :
IVisualEntity::CEntityConfig(sName)
{
}
/*====================
ITriggerEntity::ITriggerEntity
====================*/
ITriggerEntity::ITriggerEntity(CEntityConfig *pConfig) :
IVisualEntity(pConfig),
m_pEntityConfig(pConfig),
m_uiLinkedEntityIndex(INVALID_INDEX),
m_hEffect(INVALID_RESOURCE),
m_hTriggerEffect(INVALID_RESOURCE),
m_uiEventIndex(INVALID_INDEX),
m_uiTimedStatus(INVALID_TIME)
{
}
/*====================
ITriggerEntity::~ITriggerEntity
====================*/
ITriggerEntity::~ITriggerEntity()
{
StopEffect();
if (m_uiWorldIndex != INVALID_INDEX && Game.WorldEntityExists(m_uiWorldIndex))
{
Game.UnlinkEntity(m_uiWorldIndex);
Game.DeleteWorldEntity(m_uiWorldIndex);
}
}
/*====================
ITriggerEntity::Spawn
====================*/
void ITriggerEntity::Spawn()
{
IVisualEntity::Spawn();
SetStatus(ENTITY_STATUS_ACTIVE);
StartEffect();
}
/*====================
ITriggerEntity::Trigger
====================*/
void ITriggerEntity::Trigger(uint uiTriggeringEntIndex, const tstring &sTriggerName, bool bPlayEffect)
{
if (GetStatus() != ENTITY_STATUS_ACTIVE || !Game.IsServer())
return;
tstring sTrigger(sTriggerName);
if (sTrigger.empty())
sTrigger = _T("trigger");
if (bPlayEffect && m_hTriggerEffect != INVALID_RESOURCE)
{
CWorldEntity *pEnt(Game.GetWorldEntity(uiTriggeringEntIndex));
if (pEnt != NULL)
{
CGameEvent ev;
ev.SetSourceEntity(pEnt->GetGameIndex());
ev.SetEffect(m_hTriggerEffect);
ev.Spawn();
Game.AddEvent(ev);
}
}
IGameEntity *pLinkedEnt(Game.GetVisualEntity(m_uiLinkedEntityIndex));
Game.RegisterTriggerParam(_T("triggerindex"), XtoA(GetIndex()));
Game.RegisterTriggerParam(_T("index"), XtoA(uiTriggeringEntIndex));
if (pLinkedEnt != NULL)
Game.RegisterTriggerParam(_T("linkedindex"), XtoA(pLinkedEnt->GetIndex()));
else
Game.RegisterTriggerParam(_T("linkedindex"), _T("-1"));
Game.TriggerEntityScript(GetIndex(), sTrigger);
}
/*====================
ITriggerEntity::Baseline
====================*/
void ITriggerEntity::Baseline()
{
IVisualEntity::Baseline();
m_uiLinkedEntityIndex = INVALID_INDEX;
m_hEffect = INVALID_RESOURCE;
m_hTriggerEffect = INVALID_RESOURCE;
m_uiEventIndex = INVALID_INDEX;
m_uiTimedStatus = INVALID_TIME;
}
/*====================
ITriggerEntity::Kill
====================*/
void ITriggerEntity::Kill(IVisualEntity *pAttacker, ushort unKillingObjectID)
{
Disable();
tstring sMethod(_T("Unknown"));
if (unKillingObjectID != INVALID_ENT_TYPE)
{
ICvar *pCvar(EntityRegistry.GetGameSetting(unKillingObjectID, _T("Name")));
if (pCvar != NULL)
sMethod = pCvar->GetString();
}
Game.RegisterTriggerParam(_T("index"), XtoA(GetIndex()));
Game.RegisterTriggerParam(_T("attackingindex"), XtoA(pAttacker != NULL ? pAttacker->GetIndex() : INVALID_INDEX));
Game.RegisterTriggerParam(_T("method"), sMethod);
Game.TriggerEntityScript(GetIndex(), _T("death"));
}
/*====================
ITriggerEntity::Copy
====================*/
void ITriggerEntity::Copy(const IGameEntity &B)
{
IVisualEntity::Copy(B);
const ITriggerEntity *pB(B.GetAsTrigger());
if (!pB)
return;
const ITriggerEntity &C(*pB);
m_uiLinkedEntityIndex = C.m_uiLinkedEntityIndex;
m_hEffect = C.m_hEffect;
m_hTriggerEffect = C.m_hTriggerEffect;
m_uiEventIndex = C.m_uiEventIndex;
m_uiTimedStatus = C.m_uiTimedStatus;
}
/*====================
ITriggerEntity::ApplyWorldEntity
====================*/
void ITriggerEntity::ApplyWorldEntity(const CWorldEntity &ent)
{
IVisualEntity::ApplyWorldEntity(ent);
m_sLinkedEntityName = ent.GetProperty(_T("linkedentity"), _T(""));
m_hEffect = Game.RegisterEffect(ent.GetProperty(_T("effect")));
m_hTriggerEffect = Game.RegisterEffect(ent.GetProperty(_T("triggereffect")));
}
/*====================
ITriggerEntity::StopEffect
====================*/
void ITriggerEntity::StopEffect()
{
if (m_uiLinkedEntityIndex == INVALID_INDEX)
{
if (m_uiEventIndex != INVALID_INDEX)
{
Game.DeleteEvent(m_uiEventIndex);
m_uiEventIndex = INVALID_INDEX;
}
}
else
{
IVisualEntity *pEnt(Game.GetVisualEntity(m_uiLinkedEntityIndex));
if (pEnt != NULL)
{
if (pEnt->GetEffect(EFFECT_CHANNEL_TRIGGER) == m_hEffect)
{
pEnt->SetEffect(EFFECT_CHANNEL_TRIGGER, INVALID_RESOURCE);
pEnt->IncEffectSequence(EFFECT_CHANNEL_TRIGGER);
}
}
}
}
/*====================
ITriggerEntity::StartEffect
====================*/
void ITriggerEntity::StartEffect()
{
if (m_hEffect != INVALID_RESOURCE)
{
if (m_uiLinkedEntityIndex == INVALID_INDEX)
{
if (m_uiEventIndex != INVALID_INDEX)
Game.DeleteEvent(m_uiEventIndex);
CGameEvent ev;
ev.SetSourcePosition(GetPosition());
ev.SetSourceAngles(GetAngles());
ev.SetEffect(m_hEffect);
ev.Spawn();
m_uiEventIndex = Game.AddEvent(ev);
}
}
}
/*====================
ITriggerEntity::Enable
====================*/
void ITriggerEntity::Enable(uint uiTime)
{
SetStatus(ENTITY_STATUS_ACTIVE);
StartEffect();
if (uiTime != INVALID_TIME)
m_uiTimedStatus = Game.GetGameTime() + uiTime;
else
m_uiTimedStatus = INVALID_TIME;
}
/*====================
ITriggerEntity::Disable
====================*/
void ITriggerEntity::Disable(uint uiTime)
{
SetStatus(ENTITY_STATUS_DORMANT);
StopEffect();
if (uiTime != INVALID_TIME)
m_uiTimedStatus = Game.GetGameTime() + uiTime;
else
m_uiTimedStatus = INVALID_TIME;
}
/*====================
ITriggerEntity::ServerFrame
====================*/
bool ITriggerEntity::ServerFrame()
{
IVisualEntity::ServerFrame();
if (m_uiTimedStatus != INVALID_TIME && Game.GetGameTime() > m_uiTimedStatus)
{
if (GetStatus() == ENTITY_STATUS_ACTIVE)
Disable();
else
Enable();
m_uiTimedStatus = INVALID_TIME;
}
if (GetStatus() != ENTITY_STATUS_ACTIVE)
return true;
if (!m_sLinkedEntityName.empty())
{
if (m_uiLinkedEntityIndex == INVALID_INDEX)
{
WorldEntMap mapEnts(Game.GetWorldEntityMap());
for (WorldEntMap::iterator it(mapEnts.begin()); it != mapEnts.end(); it++)
{
CWorldEntity *pWorldEnt(Game.GetWorldEntity(it->first));
if (pWorldEnt != NULL && pWorldEnt->GetName() == m_sLinkedEntityName)
{
m_uiLinkedEntityIndex = pWorldEnt->GetGameIndex();
break;
}
}
}
IVisualEntity *pEnt(Game.GetVisualEntity(m_uiLinkedEntityIndex));
if (pEnt != NULL && pEnt->GetStatus() == ENTITY_STATUS_ACTIVE)
{
SetPosition(pEnt->GetPosition());
SetAngles(pEnt->GetAngles());
CWorldEntity *pWorldEnt(Game.GetWorldEntity(m_uiWorldIndex));
if (pWorldEnt != NULL)
{
pWorldEnt->SetPosition(GetPosition());
pWorldEnt->SetAngles(GetAngles());
}
if (m_hEffect != INVALID_RESOURCE && pEnt->GetEffect(EFFECT_CHANNEL_TRIGGER) != m_hEffect)
{
pEnt->SetEffect(EFFECT_CHANNEL_TRIGGER, m_hEffect);
pEnt->IncEffectSequence(EFFECT_CHANNEL_TRIGGER);
}
}
else if (m_uiLinkedEntityIndex != INVALID_INDEX)
{
Disable();
return false;
}
}
else if (m_hEffect != INVALID_RESOURCE && m_uiEventIndex == INVALID_INDEX)
StartEffect();
return true;
}
| 412 | 0.957824 | 1 | 0.957824 | game-dev | MEDIA | 0.912952 | game-dev | 0.988212 | 1 | 0.988212 |
mmatyas/pegasus-frontend | 1,657 | src/backend/model/gaming/Assets.cpp | // Pegasus Frontend
// Copyright (C) 2017-2019 Mátyás Mustoha
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include "Assets.h"
#include <QUrl>
namespace model {
Assets::Assets(QObject* parent)
: QObject(parent)
{}
const QStringList& Assets::get(AssetType key) const {
static const QStringList empty;
const auto it = m_asset_lists.find(key);
if (it != m_asset_lists.cend())
return it->second;
return empty;
}
const QString& Assets::getFirst(AssetType key) const {
static const QString empty;
const QStringList& list = get(key);
if (!list.isEmpty())
return list.constFirst();
return empty;
}
Assets& Assets::add_file(AssetType key, QString path)
{
QString uri = QUrl::fromLocalFile(std::move(path)).toString();
return add_uri(key, std::move(uri));
}
Assets& Assets::add_uri(AssetType key, QString url)
{
QStringList& target = m_asset_lists[key];
if (!url.isEmpty() && !target.contains(url))
target.append(std::move(url));
return *this;
}
} // namespace model
| 412 | 0.963035 | 1 | 0.963035 | game-dev | MEDIA | 0.533892 | game-dev | 0.872845 | 1 | 0.872845 |
langroodi/Adaptive-AUTOSAR | 1,266 | src/ara/sm/trigger.h | #ifndef TRIGGER_H
#define TRIGGER_H
#include <functional>
namespace ara
{
namespace sm
{
/// @brief Callback on trigger invocation
using TriggerHandler = std::function<void()>;
/// @brief State changing trigger wrapper
/// @tparam T State type
template <typename T>
class Trigger
{
private:
T &mState;
TriggerHandler mHandler;
public:
/// @brief Constructor
/// @param state State
/// @param handler Handler to be invoked after state change
Trigger(T &state, TriggerHandler handler) : mState{state},
mHandler{handler}
{
}
Trigger() = delete;
~Trigger() noexcept = default;
Trigger(const Trigger &) = delete;
Trigger(Trigger &&) = delete;
Trigger &operator=(const Trigger &) = delete;
Trigger &operator=(Trigger &&) = delete;
/// @brief Write into the trigger
/// @param state New state
void Write(T state)
{
mState = state;
mHandler();
}
};
}
}
#endif | 412 | 0.957856 | 1 | 0.957856 | game-dev | MEDIA | 0.244761 | game-dev | 0.675395 | 1 | 0.675395 |
paloamit/SwiftUI-Animations | 1,808 | HeartAnimation/HeartAnimation/HeartShape.swift | //
// HeartShape.swift
// HeartAnimation
//
// Created by Amit Palo on 15/09/22.
//
import Foundation
import SwiftUI
struct HeartShape: Shape {
func path(in rect: CGRect) -> Path {
HeartShape.createPath(in: rect)
}
static func createPath(in rect: CGRect) -> Path {
let size = min(rect.width, rect.height)
let xOffset = (rect.width > rect.height) ? (rect.width - rect.height) / 2.0 : 0.0
let yOffset = (rect.height > rect.width) ? (rect.height - rect.width) / 2.0 : 0.0
func offsetPoint(p: CGPoint) -> CGPoint {
return CGPoint(x: p.x + xOffset, y: p.y+yOffset)
}
var path = Path()
path.move(to: offsetPoint(p: (CGPoint(x: (size * 0.50), y: (size * 0.25)))))
path.addCurve(to: offsetPoint(p: CGPoint(x: 0, y: (size * 0.25))),
control1: offsetPoint(p: CGPoint(x: (size * 0.50), y: (-size * 0.10))),
control2: offsetPoint(p: CGPoint(x: 0, y: 0)))
path.addCurve(to: offsetPoint(p: CGPoint(x: (size * 0.50), y: size)),
control1: offsetPoint(p: CGPoint(x: 0, y: (size * 0.60))),
control2: offsetPoint(p: CGPoint(x: (size * 0.50), y: (size * 0.80))))
path.addCurve(to: offsetPoint(p: CGPoint(x: size, y: (size * 0.25))),
control1: offsetPoint(p: CGPoint(x: (size * 0.50), y: (size * 0.80))),
control2: offsetPoint(p: CGPoint(x: size, y: (size * 0.60))))
path.addCurve(to: offsetPoint(p: CGPoint(x: (size * 0.50), y: (size * 0.25))),
control1: offsetPoint(p: CGPoint(x: size, y: 0)),
control2: offsetPoint(p: CGPoint(x: (size * 0.50), y: (-size * 0.10))))
return path
}
}
| 412 | 0.796457 | 1 | 0.796457 | game-dev | MEDIA | 0.386301 | game-dev | 0.5637 | 1 | 0.5637 |
tadadosii/2DTopDownIsometricShooterStudy | 2,719 | Assets/Scripts/Environment/EnvironmentObject.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnvironmentObject : MonoBehaviour
{
// --------------------------------------
// ----- 2D Isometric Shooter Study -----
// ----------- by Tadadosi --------------
// --------------------------------------
// ---- Support my work by following ----
// ---- https://twitter.com/tadadosi ----
// --------------------------------------
public enum WhenPlayerIsOnPosition { Above, Left, Right, Below }
public WhenPlayerIsOnPosition startsOnPlayerPosition = WhenPlayerIsOnPosition.Right;
public GameObject whenPlayerIsAbove;
public GameObject whenPlayerIsOnLeft;
public GameObject whenPlayerIsOnRight;
public GameObject whenPlayerIsBelow;
private GameObject[] objects;
private SpriteRenderer spriteRenderer;
private readonly bool debug = false;
private void Awake()
{
StoreObjects();
SetActiveObject(startsOnPlayerPosition);
TryGetComponent(out spriteRenderer);
if (debug)
CheckIfMissingObjects();
}
public void SetActiveObject(WhenPlayerIsOnPosition position)
{
DisableSets();
switch (position)
{
case WhenPlayerIsOnPosition.Above:
if (whenPlayerIsAbove != null)
whenPlayerIsAbove.SetActive(true);
break;
case WhenPlayerIsOnPosition.Left:
if (whenPlayerIsOnLeft != null)
whenPlayerIsOnLeft.SetActive(true);
break;
case WhenPlayerIsOnPosition.Right:
if (whenPlayerIsOnRight != null)
whenPlayerIsOnRight.SetActive(true);
break;
case WhenPlayerIsOnPosition.Below:
if (whenPlayerIsBelow != null)
whenPlayerIsBelow.SetActive(true);
break;
default:
break;
}
}
private void DisableSets()
{
for (int i = 0; i < objects.Length; i++)
{
if (objects[i] != null)
objects[i].SetActive(false);
}
}
/// <summary>
/// Used as a debug method only.
/// </summary>
private void CheckIfMissingObjects()
{
if (whenPlayerIsAbove == null || whenPlayerIsOnLeft == null || whenPlayerIsOnRight == null || whenPlayerIsBelow == null)
{
Debug.LogWarning(gameObject.name + ": One or more objects missing!");
}
}
private void StoreObjects()
{
objects = new GameObject[] { whenPlayerIsAbove, whenPlayerIsOnLeft, whenPlayerIsOnRight, whenPlayerIsBelow };
}
}
| 412 | 0.839936 | 1 | 0.839936 | game-dev | MEDIA | 0.885561 | game-dev | 0.912078 | 1 | 0.912078 |
ixray-team/ixray-1.6-stcop | 3,116 | gamedata_cs/scripts/ph_hit.script | ----------------------------------------------------------------------------------------------------
-- Apply directional hit to the object
----------------------------------------------------------------------------------------------------
-- Исходный скрипт: Oleg Hryptul (Haron) haronk@ukr.net
----------------------------------------------------------------------------------------------------
class "action_hit"
----------------------------------------------------------------------------------------------------
-- Constructor
----------------------------------------------------------------------------------------------------
function action_hit:__init(obj, storage)
self.object = obj
self.st = storage
end
function action_hit:reset_scheme()
printf("_hr: action_hit:reset_scheme: self.object:name()='%s'", self.object:name())
local p1 = patrol(self.st.dir_path):point(0)
local p2 = self.object:position()
local h = hit()
h.power = self.st.power
h.impulse = self.st.impulse
h:bone(self.st.bone)
h.type = hit.strike
h.direction = utils.vector_copy_by_val(p1):sub(p2)
h.draftsman = self.object
self.object:hit(h)
--printf("_hr: action_hit:reset_scheme: p1=%f,%f,%f", p1.x, p1.y, p1.z)
--printf("_hr: action_hit:reset_scheme: p2=%f,%f,%f", p2.x, p2.y, p2.z)
--printf("_hr: action_hit:reset_scheme: bone = %d", h.bone)
printf("_hr: action_hit:reset_scheme: direction=%f,%f,%f", h.direction.x, h.direction.y, h.direction.z)
end
function action_hit:update(delta)
--printf("_hr: action_hit:update()")
--if not xr_logic.is_active(self.object, self.st) then
-- return
--end
local actor = level.actor()
if not actor then
return
end
if xr_logic.try_switch_to_another_section(self.object, self.st, actor) then
return
end
end
--[[
function action_hit:hit_callback(door, actor)
if self.st.locked then
if self.st.snd_open_start then
self:door_play_snd_from_set(self.st.snd_open_start)
end
return
end
local angle = self.joint:get_axis_angle(90)
if angle - self.low_limits > self.hi_limits - angle then
self:open_door()
else
self:close_door(false)
end
end
--]]
---------------------------------------------------------------------------------------------------------------------
function add_to_binder(npc, ini, scheme, section, storage)
printf("DEBUG: add_to_binder: scheme='%s', section='%s'", scheme, section)
local new_action = action_hit(npc, storage)
-- Зарегистрировать все actions, в которых должен быть вызван метод reset_scheme при изменении настроек схемы:
xr_logic.subscribe_action_for_events(npc, storage, new_action)
end
function set_scheme(npc, ini, scheme, section, gulag_name)
local st = xr_logic.assign_storage_and_bind(npc, ini, scheme, section)
st.logic = xr_logic.cfg_get_switch_conditions(ini, section, npc)
st.power = utils.cfg_get_number(ini, section, "power", npc, false, 0)
st.impulse = utils.cfg_get_number(ini, section, "impulse", npc, false, 1000)
st.bone = utils.cfg_get_string(ini, section, "bone", npc, true, "")
st.dir_path = utils.cfg_get_string(ini, section, "dir_path", npc, true, "")
end
| 412 | 0.870064 | 1 | 0.870064 | game-dev | MEDIA | 0.94584 | game-dev | 0.969785 | 1 | 0.969785 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.