blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fe8bce3e85b726de5bf621f3b859852ee78ac38d | 08b8cf38e1936e8cec27f84af0d3727321cec9c4 | /data/crawl/git/old_hunk_7998.cpp | ded81082d6b1d211590248476a8c238220419e53 | [] | no_license | ccdxc/logSurvey | eaf28e9c2d6307140b17986d5c05106d1fd8e943 | 6b80226e1667c1e0760ab39160893ee19b0e9fb1 | refs/heads/master | 2022-01-07T21:31:55.446839 | 2018-04-21T14:12:43 | 2018-04-21T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 664 | cpp | #include "cache.h"
#include "quote.h"
/* Stolen from "imap-send.c". */
int nfvasprintf(char **strp, const char *fmt, va_list ap)
{
int len;
char tmp[1024];
if ((len = vsnprintf(tmp, sizeof(tmp), fmt, ap)) < 0 ||
!(*strp = xmalloc(len + 1)))
die("Fatal: Out of memory\n");
if (len >= (int)sizeof(tmp))
vsprintf(*strp, fmt, ap);
else
memcpy(*strp, tmp, len + 1);
return len;
}
int nfasprintf(char **str, const char *fmt, ...)
{
int rc;
va_list args;
va_start(args, fmt);
rc = nfvasprintf(str, fmt, args);
va_end(args);
return rc;
}
/* Get a trace file descriptor from GIT_TRACE env variable. */
static int get_trace_fd(int *need_close)
{
| [
"993273596@qq.com"
] | 993273596@qq.com |
ef990054308064e33f6f8be12490882df7bba9a5 | 1e912cdedc9c864b624fc132ac64063e0d3ef49d | /Series of Crimes.cpp | 821044b7692a7e513032785c2ba3fc51af0b2e61 | [] | no_license | AkramRickon/100A_CodeForces_OkailsBlog_Solved | 11b6849ad8703d446ee819b7622807288e39de9f | 04439721eee1a67865db36b282825b642e2ca3f8 | refs/heads/main | 2023-07-13T10:40:29.157372 | 2021-08-09T17:14:56 | 2021-08-09T17:14:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 664 | cpp |
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,m;
cin>>n>>m;
string s[n];
for(int i=0 ;i<n ;i++) cin>> s[i];
int x,y,cnt;
for(int i=0 ;i<n ;i++)
{
cnt=0;
for(int j=0; j<m; j++)
{
if(s[i][j]=='*') cnt++;
}
if(cnt==1)
{
x=i;
break;
}
}
for(int i=0 ;i<m ;i++)
{
cnt=0;
for(int j=0; j<n; j++)
{
if(s[j][i]=='*') cnt++;
}
if(cnt==1)
{
y=i;
break;
}
}
cout<<x+1<<" "<<y+1<<endl;
}
| [
"akramhsin29@gmail.com"
] | akramhsin29@gmail.com |
b232bcc754c55b2b289b331a9d560aa30e4e8fa9 | d40cd8f8daff69950482d641f3343fc3361230fc | /server/系统模块/定制游戏/斗地主/机器人服务/AndroidUserItemSink.h | 9a3beb7c1abc034f8a495ec65d0e946aa61e40c0 | [] | no_license | scriptkitz/SiYangMJ | 3f47f389f55fb2854fbf3ab9ac26f3f1b25e2f0c | 6e899b7f7c22a6770722038dac3f05c17d4bffb3 | refs/heads/master | 2020-07-12T18:30:15.228243 | 2018-01-02T03:53:53 | 2018-01-02T03:53:53 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,062 | h | #ifndef ANDROID_USER_ITEM_SINK_HEAD_FILE
#define ANDROID_USER_ITEM_SINK_HEAD_FILE
#pragma once
#include "Stdafx.h"
#include "GameLogic.h"
//////////////////////////////////////////////////////////////////////////
//机器人类
class CAndroidUserItemSink : public IAndroidUserItemSink
{
//游戏变量
protected:
WORD m_wBankerUser; //庄家用户
BYTE m_cbCurrentLandScore; //已叫分数
WORD m_wOutCardUser; //出牌玩家
//扑克变量
protected:
BYTE m_cbTurnCardCount; //出牌数目
BYTE m_cbTurnCardData[MAX_COUNT]; //出牌列表
//手上扑克
protected:
BYTE m_cbHandCardData[MAX_COUNT]; //手上扑克
BYTE m_cbHandCardCount[GAME_PLAYER]; //扑克数目
//历史扑克
protected:
//控件变量
protected:
CGameLogic m_GameLogic; //游戏逻辑
IAndroidUserItem * m_pIAndroidUserItem; //用户接口
//函数定义
public:
//构造函数
CAndroidUserItemSink();
//析构函数
virtual ~CAndroidUserItemSink();
//基础接口
public:
//释放对象
virtual VOID Release()
{
delete this;
}
//接口查询
virtual VOID * QueryInterface(REFGUID Guid, DWORD dwQueryVer);
//控制接口
public:
//初始接口
virtual bool Initialization(IUnknownEx * pIUnknownEx);
//重置接口
virtual bool RepositionSink();
//游戏事件
public:
//时间消息
virtual bool OnEventTimer(UINT nTimerID);
//游戏消息
virtual bool OnEventGameMessage(WORD wSubCmdID, VOID * pData, WORD wDataSize);
//游戏消息
virtual bool OnEventFrameMessage(WORD wSubCmdID, VOID * pData, WORD wDataSize);
//场景消息
virtual bool OnEventSceneMessage(BYTE cbGameStatus, bool bLookonOther, VOID * pData, WORD wDataSize);
//用户事件
public:
//用户进入
virtual VOID OnEventUserEnter(IAndroidUserItem * pIAndroidUserItem, bool bLookonUser);
//用户离开
virtual VOID OnEventUserLeave(IAndroidUserItem * pIAndroidUserItem, bool bLookonUser);
//用户积分
virtual VOID OnEventUserScore(IAndroidUserItem * pIAndroidUserItem, bool bLookonUser);
//用户状态
virtual VOID OnEventUserStatus(IAndroidUserItem * pIAndroidUserItem, bool bLookonUser);
//用户段位
virtual VOID OnEventUserSegment(IAndroidUserItem * pIAndroidUserItem, bool bLookonUser);
//消息处理
protected:
//游戏开始
bool OnSubGameStart(VOID * pData, WORD wDataSize);
//用户叫分
bool OnSubCallScore(VOID * pData, WORD wDataSize);
//庄家信息
bool OnSubBankerInfo(VOID * pData, WORD wDataSize);
//用户出牌
bool OnSubOutCard(VOID * pData, WORD wDataSize);
//用户放弃
bool OnSubPassCard(VOID * pData, WORD wDataSize);
//游戏结束
bool OnSubGameEnd(VOID * pData, WORD wDataSize);
};
//////////////////////////////////////////////////////////////////////////
#endif | [
"jianan@ixianlai.com"
] | jianan@ixianlai.com |
b4270dd07df42a817e5bb9f5f24c9ac3e7f2ccbb | 279b08a0a1d60f56c05f70518a9c750ba6070ead | /Blast_Editor/Blast_Editor/ModuleBlast.cpp | 7d13112b26a82d2c35d02096e3387e25b89b8dda | [
"MIT"
] | permissive | Project-3-UPC-DDV-BCN/Blast_Editor | 6c62bc999b6e646fff401f2922e15576f1df14ca | 501782d3e8334627ce2dd3b69fed02df75df29fc | refs/heads/master | 2021-09-14T07:28:56.698431 | 2018-02-19T11:26:16 | 2018-02-19T11:26:16 | 119,430,076 | 0 | 0 | null | 2018-01-29T19:24:48 | 2018-01-29T19:24:48 | null | UTF-8 | C++ | false | false | 21,963 | cpp | #include "ModuleBlast.h"
#include "Nvidia/Blast/Include/extensions/authoring/Include/NvBlastExtAuthoring.h"
#include "Nvidia/Blast/Include/extensions/authoring/Include/NvBlastExtAuthoringFractureTool.h"
#include "Nvidia/Blast/Include/extensions/authoring/Include/NvBlastExtAuthoringMesh.h"
#include "Nvidia/Blast/Include/extensions/authoring/Include/NvBlastExtAuthoringCollisionBuilder.h"
#include "Nvidia/Blast/Include/extensions/authoring/Include/NvBlastExtAuthoringBondGenerator.h"
#include "Nvidia/Blast/Include/toolkit/Include/NvBlastTkFramework.h"
#include "Nvidia/Blast/Include/extensions/physx/Include/NvBlastExtPxAsset.h"
#include "Nvidia/Blast/Include/extensions/serialization/Include/NvBlastExtPxSerialization.h"
#include "Nvidia/Blast/Include/extensions/serialization/Include/NvBlastExtSerialization.h"
#include "Nvidia/Blast/Include/extensions/serialization/Include/NvBlastExtTkSerialization.h"
#include "Nvidia/Blast/Include/extensions/exporter/Include/NvBlastExtExporter.h"
#include "BlastMesh.h"
#include "Application.h"
#include "ModuleRenderer3D.h"
#include "ComponentTransform.h"
#include "Material.h"
#include "ComponentTransform.h"
#include <fstream>
#define WIN32_MEAN_AND_LEAN
#include "windows.h"
#if _DEBUG
#pragma comment (lib, "Nvidia/Blast/lib/lib_debug/NvBlastDEBUG_x86.lib")
#pragma comment (lib, "Nvidia/Blast/lib/lib_debug/NvBlastExtAuthoringDEBUG_x86.lib")
#pragma comment (lib, "Nvidia/Blast/lib/lib_debug/NvBlastExtPxSerializationDEBUG_x86.lib")
#pragma comment (lib, "Nvidia/Blast/lib/lib_debug/NvBlastExtSerializationDEBUG_x86.lib")
#pragma comment (lib, "Nvidia/Blast/lib/lib_debug/NvBlastTkDEBUG_x86.lib")
#pragma comment (lib, "Nvidia/Blast/lib/lib_debug/NvBlastGlobalsDEBUG_x86.lib")
#pragma comment (lib, "Nvidia/Blast/lib/lib_debug/NvBlastExtPhysXDEBUG_x86.lib")
#pragma comment (lib, "Nvidia/Blast/lib/lib_debug/NvBlastExtTkSerializationDEBUG_x86.lib")
#pragma comment (lib, "Nvidia/Blast/lib/lib_debug/NvBlastExtExporterDEBUG_x86.lib")
#pragma comment (lib, "Nvidia/PhysX/libx86/lib_debug/PhysX3DEBUG_x86.lib")
#pragma comment (lib, "Nvidia/PhysX/libx86/lib_debug/PhysX3CommonDEBUG_x86.lib")
#pragma comment (lib, "Nvidia/PhysX/libx86/lib_debug/PxFoundationDEBUG_x86.lib")
#pragma comment (lib, "Nvidia/PhysX/libx86/lib_debug/PhysX3CookingDEBUG_x86.lib")
#pragma comment (lib, "Nvidia/PhysX/libx86/lib_debug/PhysX3ExtensionsDEBUG_x86.lib")
#else
#pragma comment (lib, "Nvidia/Blast/lib/lib_release/NvBlast_x86.lib")
#pragma comment (lib, "Nvidia/Blast/lib/lib_release/NvBlastExtAuthoring_x86.lib")
#pragma comment (lib, "Nvidia/Blast/lib/lib_release/NvBlastExtPxSerialization_x86.lib")
#pragma comment (lib, "Nvidia/Blast/lib/lib_release/NvBlastExtSerialization_x86.lib")
#pragma comment (lib, "Nvidia/Blast/lib/lib_release/NvBlastTk_x86.lib")
#pragma comment (lib, "Nvidia/Blast/lib/lib_release/NvBlastGlobals_x86.lib")
#pragma comment (lib, "Nvidia/Blast/lib/lib_release/NvBlastExtPhysX_x86.lib")
#pragma comment (lib, "Nvidia/Blast/lib/lib_release/NvBlastExtTkSerialization_x86.lib")
#pragma comment (lib, "Nvidia/Blast/lib/lib_release/NvBlastExtExporter_x86.lib")
#pragma comment (lib, "Nvidia/PhysX/libx86/lib_release/PhysX3_x86.lib")
#pragma comment (lib, "Nvidia/PhysX/libx86/lib_release/PhysX3Common_x86.lib")
#pragma comment (lib, "Nvidia/PhysX/libx86/lib_release/PxFoundation_x86.lib")
#pragma comment (lib, "Nvidia/PhysX/libx86/lib_release/PhysX3Cooking_x86.lib")
#pragma comment (lib, "Nvidia/PhysX/libx86/lib_release/PhysX3Extensions_x86.lib")
#endif
ModuleBlast::ModuleBlast(Application* app) : Module(app)
{
name = "Blast";
fract_tool = nullptr;
voronoi_sites_generator = nullptr;
blast_random_generator = nullptr;
authoring_result = nullptr;
current_selected_mesh = nullptr;
explosion_amount = 0;
cell_counts = 10;
cluster_count = 5;
cluster_radius = 100;
radial_center = float3::zero;
radial_normal = float3::zero;
radial_radius = 100;
radial_angular_steps = 6;
radial_steps = 5;
radial_angle_offset = 0;
radial_variability = 0;
sphere_center = float3::zero;
sphere_radius = 20;
remove_sphere_center = float3::zero;
remove_sphere_radius = 20;
remove_sphere_eraser_probability = 1;
slicing_angle_variation = 0;
slicing_noise_amplitude = 0;
slicing_noise_frquency = 1;
slicing_noise_octave_number = 1;
slicing_offset_variations = 0;
slicing_surface_resolution = 1;
slicing_x_slices = 2;
slicing_y_slices = 2;
slicing_z_slices = 2;
replace_chunk = false;
remove_islands = true;
new_mesh = false;
interior_mesh_material = new Material();
interior_mesh_material->SetDiffuseColor(1,1,1);
}
ModuleBlast::~ModuleBlast()
{
}
bool ModuleBlast::Init()
{
bool ret = true;
physx_foundation = PxCreateFoundation(PX_FOUNDATION_VERSION, gDefaultAllocatorCallback, gDefaultErrorCallback);
if (!physx_foundation)
{
ret = false;
}
else
{
physx_physics = PxCreatePhysics(PX_PHYSICS_VERSION, *physx_foundation, physx::PxTolerancesScale(), true);
if (!physx_physics)
{
ret = false;
}
else
{
cooking = PxCreateCooking(PX_PHYSICS_VERSION, *physx_foundation, physx::PxCookingParams(physx::PxTolerancesScale()));
if (!cooking)
{
ret = false;
}
}
}
fract_tool = NvBlastExtAuthoringCreateFractureTool();
fract_tool->setInteriorMaterialId(MATERIAL_INTERIOR);
blast_random_generator = new RandomGenerator();
fract_tool->setRemoveIslands(remove_islands);
fracture_type = VoronoiUniform;
return ret;
}
bool ModuleBlast::CleanUp()
{
fract_tool->release();
if (voronoi_sites_generator)
{
voronoi_sites_generator->release();
}
delete blast_random_generator;
blast_random_generator = nullptr;
for (std::vector<BlastMesh*>::iterator it = blast_meshes.begin(); it != blast_meshes.end();)
{
(*it)->blast_mesh->release();
delete *it;
*it = nullptr;
it = blast_meshes.erase(it);
}
return true;
}
void ModuleBlast::CreateBlastMesh(float* vertices, uint num_vertices, float* normals, float* texture_coords, uint* indices, uint num_indices, std::string mesh_name,
float3 mesh_pos, float3 mesh_rot, float3 mesh_scale, ComponentTransform* parent_transform)
{
Nv::Blast::Mesh* mesh = NvBlastExtAuthoringCreateMesh((physx::PxVec3*)vertices, (physx::PxVec3*)normals, (physx::PxVec2*)texture_coords,
num_vertices, indices, num_indices);
SetCurrentMesh(mesh);
new_mesh = true;
UpdateMesh();
current_selected_mesh = blast_meshes[0];
SetCurrentMesh(blast_meshes[0]->blast_mesh);
blast_meshes.back()->name = mesh_name;
blast_meshes.back()->mesh_transform->SetParentTransform(parent_transform);
blast_meshes.back()->mesh_transform->SetPosition(mesh_pos);
blast_meshes.back()->mesh_transform->SetRotation(mesh_rot);
blast_meshes.back()->mesh_transform->SetScale({ 1,1,1 });
}
void ModuleBlast::UpdateMesh()
{
Nv::Blast::BlastBondGenerator* bond_generator = NvBlastExtAuthoringCreateBondGenerator(cooking, &physx_physics->getPhysicsInsertionCallback());
Nv::Blast::ConvexMeshBuilder* collision_builder = NvBlastExtAuthoringCreateConvexMeshBuilder(cooking, &physx_physics->getPhysicsInsertionCallback());
Nv::Blast::CollisionParams param;
param.maximumNumberOfHulls = 1;
param.voxelGridResolution = 0;
authoring_result = NvBlastExtAuthoringProcessFracture(*fract_tool, *bond_generator, *collision_builder, param);
bond_generator->release();
collision_builder->release();
for (int i = 0; i < authoring_result->chunkCount; i++)
{
if (!blast_meshes.empty() && !new_mesh && i == 0) continue;
BlastMesh* mesh = new BlastMesh();
Nv::Blast::Mesh* m = fract_tool->createChunkMesh(i);
mesh->blast_mesh = m;
mesh->chunk_depth = fract_tool->getChunkDepth(i);
mesh->chunk_id = i;
float* pos = authoring_result->chunkDescs[i].centroid;
float x = pos[0];
float y = pos[1];
float z = pos[2];
int triangle_count = authoring_result->geometryOffset[i + 1] - authoring_result->geometryOffset[i];
mesh->num_vertices = triangle_count * 3;
mesh->vertices_data = new float[mesh->num_vertices * 12];
mesh->num_indices = triangle_count * 3;
mesh->indices = new uint[mesh->num_indices];
int vertex_index = 0;
int indice_index = 0;
int start_triangle = authoring_result->geometryOffset[i];
int end_triangle = authoring_result->geometryOffset[i + 1];
int inter_mat = fract_tool->getInteriorMaterialId();
std::vector<int> inter_mat_indices;
for (int j = start_triangle; j < end_triangle; j++)
{
Nv::Blast::Triangle& tr = authoring_result->geometry[j];
for (int vi = 0; vi < 3; vi++, vertex_index++)
{
auto& vertex = (&tr.a)[vi];
mesh->vertices_data[vertex_index * 12 + 0] = vertex.p.x;
mesh->vertices_data[vertex_index * 12 + 1] = vertex.p.y;
mesh->vertices_data[vertex_index * 12 + 2] = vertex.p.z;
mesh->vertices_data[vertex_index * 12 + 3] = vertex.uv->x;
mesh->vertices_data[vertex_index * 12 + 4] = vertex.uv->y;
mesh->vertices_data[vertex_index * 12 + 5] = vertex.n.x;
mesh->vertices_data[vertex_index * 12 + 6] = vertex.n.y;
mesh->vertices_data[vertex_index * 12 + 7] = vertex.n.z;
mesh->vertices_data[vertex_index * 12 + 8] = 1;
mesh->vertices_data[vertex_index * 12 + 9] = 1;
mesh->vertices_data[vertex_index * 12 + 10] = 1;
mesh->vertices_data[vertex_index * 12 + 11] = 1;
if (tr.materialId != inter_mat)
{
mesh->indices[indice_index] = vertex_index;
indice_index++;
}
else
{
inter_mat_indices.push_back(vertex_index);
}
}
}
int tmp_indices = indice_index;
for (auto& index : inter_mat_indices)
{
mesh->indices[indice_index] = index;
indice_index++;
}
if (!new_mesh)
{
mesh->interior_material = new Material();
mesh->interior_material->SetDiffuseColor(1, 1, 1);
mesh->interior_material->indice_count = inter_mat_indices.size();
mesh->interior_material->first_indice = tmp_indices;
}
mesh->CreateVerticesFromData();
mesh->LoadToMemory();
//mesh->material = mesh_material;
mesh->material = new Material();
mesh->material->indice_count = tmp_indices;
mesh->material->first_indice = 0;
App->renderer3D->AddMeshToDraw(mesh);
if (i == 0)
{
blast_meshes.push_back(mesh);
}
if (current_selected_mesh && !new_mesh)
{
mesh->chunk_depth += current_selected_mesh->chunk_depth;
current_selected_mesh->childs.push_back(mesh);
mesh->base_displacement = float3(x, y, z);
mesh->mesh_transform->SetPosition(/*current_selected_mesh->mesh_transform->GetGlobalPosition()*/mesh->base_displacement * explosion_amount);
current_selected_mesh->is_root = true;
}
new_mesh = false;
}
}
void ModuleBlast::SetCurrentMesh(Nv::Blast::Mesh * current)
{
if (current_selected_mesh && current_selected_mesh->blast_mesh == current) return;
fract_tool->setSourceMesh(current);
}
void ModuleBlast::RemoveChildChunks(BlastMesh * mesh)
{
if (fract_tool->deleteAllChildrenOfChunk(0))
{
DeleteChilds(mesh);
mesh->is_root = false;
}
}
void ModuleBlast::ApplyFracture()
{
if (voronoi_sites_generator) voronoi_sites_generator->release();
voronoi_sites_generator = NvBlastExtAuthoringCreateVoronoiSitesGenerator(current_selected_mesh->blast_mesh, blast_random_generator);
bool fractured = false;
switch (fracture_type)
{
case ModuleBlast::VoronoiUniform:
fractured = ApplyVoronoiFracture();
break;
case ModuleBlast::VoronoiClustered:
fractured = ApplyVoronoiClusteredFracture();
break;
case ModuleBlast::VoronoiRadial:
fractured = ApplyVoronoiRadialFracture();
break;
case ModuleBlast::VoronoiInSphere:
fractured = ApplyVoronoiInSphereFracture();
break;
case ModuleBlast::VoronoiRemove:
fractured = RemoveInSphereFracture();
break;
case ModuleBlast::Slice:
fractured = ApplySliceFracture();
break;
default:
break;
}
if (fractured)
{
if (explosion_amount < 0.2)
{
explosion_amount += 0.2;
App->renderer3D->SetExplosionDisplacement(explosion_amount);
}
}
}
void ModuleBlast::ResetMesh()
{
fract_tool->reset();
DeleteChilds(blast_meshes.front());
blast_meshes.front()->is_root = false;
}
void ModuleBlast::OptimizeChunks()
{
//fract_tool->uniteChunks()
}
bool ModuleBlast::ApplyVoronoiFracture()
{
voronoi_sites_generator->uniformlyGenerateSitesInMesh(cell_counts);
const physx::PxVec3* sites = nullptr;
uint sites_count = voronoi_sites_generator->getVoronoiSites(sites);
if (fract_tool->voronoiFracturing(current_selected_mesh->chunk_id, sites_count, sites, replace_chunk) == 0)
{
UpdateMesh();
return true;
}
return false;
}
bool ModuleBlast::ApplyVoronoiClusteredFracture()
{
voronoi_sites_generator->clusteredSitesGeneration(cluster_count, cell_counts, cluster_radius);
const physx::PxVec3* sites = nullptr;
uint sites_count = voronoi_sites_generator->getVoronoiSites(sites);
if (fract_tool->voronoiFracturing(current_selected_mesh->chunk_id, sites_count, sites, replace_chunk) == 0)
{
UpdateMesh();
return true;
}
return false;
}
bool ModuleBlast::ApplyVoronoiRadialFracture()
{
physx::PxVec3 center(radial_center.x, radial_center.y, radial_center.z);
physx::PxVec3 normal(radial_normal.x, radial_normal.y, radial_normal.z);
voronoi_sites_generator->radialPattern(center, normal, radial_radius, radial_angular_steps, radial_steps, radial_angle_offset, radial_variability);
const physx::PxVec3* sites = nullptr;
uint sites_count = voronoi_sites_generator->getVoronoiSites(sites);
if (fract_tool->voronoiFracturing(current_selected_mesh->chunk_id, sites_count, sites, replace_chunk) == 0)
{
UpdateMesh();
return true;
}
return false;
}
bool ModuleBlast::ApplyVoronoiInSphereFracture()
{
physx::PxVec3 center(sphere_center.x, sphere_center.y, sphere_center.z);
voronoi_sites_generator->generateInSphere(cell_counts, sphere_radius, center);
const physx::PxVec3* sites = nullptr;
uint sites_count = voronoi_sites_generator->getVoronoiSites(sites);
if (fract_tool->voronoiFracturing(current_selected_mesh->chunk_id, sites_count, sites, replace_chunk) == 0)
{
UpdateMesh();
return true;
}
return false;
}
bool ModuleBlast::RemoveInSphereFracture()
{
physx::PxVec3 center(sphere_center.x, sphere_center.y, sphere_center.z);
voronoi_sites_generator->deleteInSphere(sphere_radius, center, remove_sphere_eraser_probability);
const physx::PxVec3* sites = nullptr;
uint sites_count = voronoi_sites_generator->getVoronoiSites(sites);
if (fract_tool->voronoiFracturing(current_selected_mesh->chunk_id, sites_count, sites, replace_chunk) == 0)
{
UpdateMesh();
return true;
}
return false;
}
bool ModuleBlast::ApplySliceFracture()
{
Nv::Blast::SlicingConfiguration config;
config.noise.amplitude = slicing_noise_amplitude;
config.noise.frequency = slicing_noise_frquency;
config.noise.octaveNumber = slicing_noise_octave_number;
config.noise.surfaceResolution = slicing_surface_resolution;
config.angle_variations = slicing_angle_variation;
config.offset_variations = slicing_offset_variations;
config.x_slices = slicing_x_slices;
config.y_slices = slicing_y_slices;
config.z_slices = slicing_z_slices;
if (fract_tool->slicing(current_selected_mesh->chunk_id, config, replace_chunk, blast_random_generator) == 0)
{
UpdateMesh();
return true;
}
return false;
}
void ModuleBlast::DeleteChilds(BlastMesh * mesh)
{
for (std::vector<BlastMesh*>::iterator it = mesh->childs.begin(); it != mesh->childs.end(); it = mesh->childs.erase(it))
{
DeleteChilds(*it);
App->renderer3D->RemoveMeshToDraw(*it);
delete *it;
*it = nullptr;
}
}
void ModuleBlast::SetFractureType(FractureType type)
{
fracture_type = type;
}
ModuleBlast::FractureType ModuleBlast::GetFractureType() const
{
return fracture_type;
}
void ModuleBlast::SetCellCounts(int counts)
{
cell_counts = counts;
}
int ModuleBlast::GetCellCounts() const
{
return cell_counts;
}
void ModuleBlast::SetReplaceChunk(bool replace)
{
replace_chunk = replace;
}
bool ModuleBlast::GetReplaceChunk() const
{
return replace_chunk;
}
void ModuleBlast::SetRemoveIslands(bool remove)
{
remove_islands = remove;
}
bool ModuleBlast::GetRemoveIslands() const
{
return remove_islands;
}
void ModuleBlast::SetClusterCount(int count)
{
cluster_count = count;
}
int ModuleBlast::GetClusterCount() const
{
return cluster_count;
}
void ModuleBlast::SetClusterRadius(float radius)
{
cluster_radius = radius;
}
float ModuleBlast::GetClusterRadius() const
{
return cluster_radius;
}
void ModuleBlast::SetRadialCenter(float3 center)
{
radial_center = center;
}
float3 ModuleBlast::GetRadialCenter() const
{
return radial_center;
}
void ModuleBlast::SetRadialNormal(float3 normal)
{
radial_normal = normal;
}
float3 ModuleBlast::GetRadialNormal() const
{
return radial_normal;
}
void ModuleBlast::SetRadialRadius(float radius)
{
radial_radius = radius;
}
float ModuleBlast::GetRadialRadius() const
{
return radial_radius;
}
void ModuleBlast::SetRadialAngularSteps(int steps)
{
radial_angular_steps = steps;
}
int ModuleBlast::GetRadialAngularSteps() const
{
return radial_angular_steps;
}
void ModuleBlast::SetRadialSteps(int steps)
{
radial_steps = steps;
}
int ModuleBlast::GetRadialSteps() const
{
return radial_steps;
}
void ModuleBlast::SetRadialAngleOffset(float offset)
{
radial_angle_offset = offset;
}
float ModuleBlast::GetRadialAngleOffset() const
{
return radial_angle_offset;
}
void ModuleBlast::SetRadialVariability(float variability)
{
radial_variability = variability;
}
float ModuleBlast::GetRadialVariability() const
{
return radial_variability;
}
void ModuleBlast::SetSphereCenter(float3 center)
{
sphere_center = center;
}
float3 ModuleBlast::GetSphereCenter() const
{
return sphere_center;
}
void ModuleBlast::SetSphereRadius(float radius)
{
sphere_radius = radius;
}
float ModuleBlast::GetSphereRadius() const
{
return sphere_radius;
}
void ModuleBlast::SetRemoveSphereCenter(float3 center)
{
remove_sphere_center = center;
}
float3 ModuleBlast::GetRemoveSphereCenter() const
{
return remove_sphere_center;
}
void ModuleBlast::SetRemoveSphereRadius(float radius)
{
remove_sphere_radius = radius;
}
float ModuleBlast::GetRemoveSphereRadius() const
{
return remove_sphere_radius;
}
void ModuleBlast::SetRemoveSphereEraserProbability(float probability)
{
remove_sphere_eraser_probability = probability;
}
float ModuleBlast::GetRemoveSphereEraserProbability() const
{
return remove_sphere_eraser_probability;
}
void ModuleBlast::SetSlicingAngleVariation(float variation)
{
slicing_angle_variation = variation;
}
float ModuleBlast::GetSlicingAngleVariation() const
{
return slicing_angle_variation;
}
void ModuleBlast::SetSlicingNoiseAmplitude(float amplitude)
{
slicing_noise_amplitude = amplitude;
}
float ModuleBlast::GetSlicingNoiseAmplitude() const
{
return slicing_noise_amplitude;
}
void ModuleBlast::SetSlicingNoiseFrequency(float frequency)
{
slicing_noise_frquency = frequency;
}
float ModuleBlast::GetSlicingNoiseFrequency() const
{
return slicing_noise_frquency;
}
void ModuleBlast::SetSlicingNoiseOctaveNumber(uint number)
{
slicing_noise_octave_number = number;
}
uint ModuleBlast::GetSlicingNoiseOctaveNumber() const
{
return slicing_noise_octave_number;
}
void ModuleBlast::SetSlicingOffsetVariations(float variations)
{
slicing_offset_variations = variations;
}
float ModuleBlast::GetSlicingOffsetVariations() const
{
return slicing_offset_variations;
}
void ModuleBlast::SetSlicingSurfaceResolution(uint resolution)
{
slicing_surface_resolution = resolution;
}
uint ModuleBlast::GetSlicingSurfaceResolution() const
{
return slicing_surface_resolution;
}
void ModuleBlast::SetSlicingX(int x)
{
slicing_x_slices = x;
}
int ModuleBlast::GetSlicingX() const
{
return slicing_x_slices;
}
void ModuleBlast::SetSlicingY(int y)
{
slicing_y_slices = y;
}
int ModuleBlast::GetSlicingY() const
{
return slicing_y_slices;
}
void ModuleBlast::SetSlicingZ(int z)
{
slicing_z_slices = z;
}
int ModuleBlast::GetSlicingZ() const
{
return slicing_z_slices;
}
void ModuleBlast::CreateBlastFile()
{
Nv::Blast::TkFramework* framework = NvBlastTkFrameworkCreate();
Nv::Blast::TkAssetDesc descriptor;
descriptor.bondCount = authoring_result->bondCount;
descriptor.bondDescs = authoring_result->bondDescs;
descriptor.bondFlags = nullptr;
descriptor.chunkCount = authoring_result->chunkCount;
descriptor.chunkDescs = authoring_result->chunkDescs;
Nv::Blast::ExtPxAsset* physicsAsset = Nv::Blast::ExtPxAsset::create(descriptor, authoring_result->physicsChunks, authoring_result->physicsSubchunks, *framework);
void* buffer;
Nv::Blast::ExtSerialization* serialization = NvBlastExtSerializationCreate();
if (serialization != nullptr && physx_physics != nullptr && cooking != nullptr && framework != nullptr)
{
NvBlastExtTkSerializerLoadSet(*framework, *serialization);
NvBlastExtPxSerializerLoadSet(*framework, *physx_physics, *cooking, *serialization);
serialization->setSerializationEncoding(NVBLAST_FOURCC('C', 'P', 'N', 'B'));
}
CreateDirectory("./Wall", NULL);
const uint64_t buffer_size = NvBlastExtSerializationSerializeExtPxAssetIntoBuffer(buffer, *serialization, physicsAsset);
if (buffer_size != 0)
{
std::ofstream outfile("./Wall/wall.bmesh", std::ofstream::binary);
outfile.write((char*)buffer, buffer_size);
outfile.close();
}
Nv::Blast::IMeshFileWriter* mesh_exporter = NvBlastExtExporterCreateFbxFileWriter();
if (mesh_exporter)
{
//mesh_exporter->setInteriorIndex(1);
mesh_exporter->appendMesh(*authoring_result, "wall");
mesh_exporter->saveToFile("wall_blast", "./Wall/");
mesh_exporter->release();
}
Nv::Blast::IMeshFileWriter* mesh_exporter2 = NvBlastExtExporterCreateObjFileWriter();
if (mesh_exporter2)
{
//mesh_exporter2->setInteriorIndex(1);
mesh_exporter2->appendMesh(*authoring_result, "wall");
mesh_exporter2->saveToFile("wall_blast", "./Wall/");
mesh_exporter2->release();
}
}
//Blast Random Generator
float RandomGenerator::getRandomValue()
{
return App->RandomNumber().Float();
}
void RandomGenerator::seed(int32_t seed)
{
App->RandomNumber().Seed(seed);
} | [
"elsuperchowchow@gmail.com"
] | elsuperchowchow@gmail.com |
4724475dfc1e2af6302a3392d4fbe478b916b497 | b1fed0cf607483a8c51df377d6278d186be95007 | /branches/REL_2_4/shibsp/attribute/NameIDAttributeDecoder.cpp | d220e6a52a74e50041e08dedc198de069cbdcd41 | [] | no_license | svn2github/cpp-sp | eab0e52ce521ae696ba02d815d7da02481c4e24d | 9c0bfdae80f3c60860b36f15698f241f1e3d933f | refs/heads/master | 2020-06-06T03:24:19.620256 | 2015-01-20T00:27:14 | 2015-01-20T00:27:14 | 19,316,247 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,861 | cpp | /**
* Licensed to the University Corporation for Advanced Internet
* Development, Inc. (UCAID) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* UCAID licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the
* License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
/**
* NameIDAttributeDecoder.cpp
*
* Decodes SAML into NameIDAttributes.
*/
#include "internal.h"
#include "attribute/AttributeDecoder.h"
#include "attribute/NameIDAttribute.h"
#include <saml/saml1/core/Assertions.h>
#include <saml/saml2/core/Assertions.h>
using namespace shibsp;
using namespace opensaml::saml1;
using namespace opensaml::saml2;
using namespace xmltooling;
using namespace std;
namespace shibsp {
static const XMLCh formatter[] = UNICODE_LITERAL_9(f,o,r,m,a,t,t,e,r);
static const XMLCh defaultQualifiers[] = UNICODE_LITERAL_17(d,e,f,a,u,l,t,Q,u,a,l,i,f,i,e,r,s);
class SHIBSP_DLLLOCAL NameIDAttributeDecoder : virtual public AttributeDecoder
{
public:
NameIDAttributeDecoder(const DOMElement* e)
: AttributeDecoder(e),
m_formatter(XMLHelper::getAttrString(e, nullptr, formatter)),
m_defaultQualifiers(XMLHelper::getAttrBool(e, false, defaultQualifiers)) {
}
~NameIDAttributeDecoder() {}
shibsp::Attribute* decode(
const vector<string>& ids, const XMLObject* xmlObject, const char* assertingParty=nullptr, const char* relyingParty=nullptr
) const;
private:
void extract(
const NameIDType* n, vector<NameIDAttribute::Value>& dest, const char* assertingParty, const char* relyingParty
) const;
void extract(
const NameIdentifier* n, vector<NameIDAttribute::Value>& dest, const char* assertingParty, const char* relyingParty
) const;
string m_formatter;
bool m_defaultQualifiers;
};
AttributeDecoder* SHIBSP_DLLLOCAL NameIDAttributeDecoderFactory(const DOMElement* const & e)
{
return new NameIDAttributeDecoder(e);
}
};
shibsp::Attribute* NameIDAttributeDecoder::decode(
const vector<string>& ids, const XMLObject* xmlObject, const char* assertingParty, const char* relyingParty
) const
{
auto_ptr<NameIDAttribute> nameid(
new NameIDAttribute(ids, (!m_formatter.empty()) ? m_formatter.c_str() : DEFAULT_NAMEID_FORMATTER)
);
vector<NameIDAttribute::Value>& dest = nameid->getValues();
vector<XMLObject*>::const_iterator v,stop;
Category& log = Category::getInstance(SHIBSP_LOGCAT".AttributeDecoder.NameID");
if (xmlObject && XMLString::equals(opensaml::saml1::Attribute::LOCAL_NAME,xmlObject->getElementQName().getLocalPart())) {
const opensaml::saml2::Attribute* saml2attr = dynamic_cast<const opensaml::saml2::Attribute*>(xmlObject);
if (saml2attr) {
const vector<XMLObject*>& values = saml2attr->getAttributeValues();
v = values.begin();
stop = values.end();
if (log.isDebugEnabled()) {
auto_ptr_char n(saml2attr->getName());
log.debug(
"decoding NameIDAttribute (%s) from SAML 2 Attribute (%s) with %lu value(s)",
ids.front().c_str(), n.get() ? n.get() : "unnamed", values.size()
);
}
}
else {
const opensaml::saml1::Attribute* saml1attr = dynamic_cast<const opensaml::saml1::Attribute*>(xmlObject);
if (saml1attr) {
const vector<XMLObject*>& values = saml1attr->getAttributeValues();
v = values.begin();
stop = values.end();
if (log.isDebugEnabled()) {
auto_ptr_char n(saml1attr->getAttributeName());
log.debug(
"decoding NameIDAttribute (%s) from SAML 1 Attribute (%s) with %lu value(s)",
ids.front().c_str(), n.get() ? n.get() : "unnamed", values.size()
);
}
}
else {
log.warn("XMLObject type not recognized by NameIDAttributeDecoder, no values returned");
return nullptr;
}
}
for (; v!=stop; ++v) {
const NameIDType* n2 = dynamic_cast<const NameIDType*>(*v);
if (n2) {
log.debug("decoding AttributeValue element of saml2:NameIDType type");
extract(n2, dest, assertingParty, relyingParty);
}
else {
const NameIdentifier* n1=dynamic_cast<const NameIdentifier*>(*v);
if (n1) {
log.debug("decoding AttributeValue element of saml1:NameIdentifier type");
extract(n1, dest, assertingParty, relyingParty);
}
else if ((*v)->hasChildren()) {
const list<XMLObject*>& values = (*v)->getOrderedChildren();
for (list<XMLObject*>::const_iterator vv = values.begin(); vv!=values.end(); ++vv) {
if (n2=dynamic_cast<const NameIDType*>(*vv)) {
log.debug("decoding saml2:NameID child element of AttributeValue");
extract(n2, dest, assertingParty, relyingParty);
}
else if (n1=dynamic_cast<const NameIdentifier*>(*vv)) {
log.debug("decoding saml1:NameIdentifier child element of AttributeValue");
extract(n1, dest, assertingParty, relyingParty);
}
else {
log.warn("skipping AttributeValue child element not recognizable as NameID/NameIdentifier");
}
}
}
else {
log.warn("AttributeValue was not of a supported type and contains no child elements");
}
}
}
return dest.empty() ? nullptr : _decode(nameid.release());
}
const NameIDType* saml2name = dynamic_cast<const NameIDType*>(xmlObject);
if (saml2name) {
if (log.isDebugEnabled()) {
auto_ptr_char f(saml2name->getFormat());
log.debug("decoding NameIDAttribute (%s) from SAML 2 NameID with Format (%s)", ids.front().c_str(), f.get() ? f.get() : "unspecified");
}
extract(saml2name, dest, assertingParty, relyingParty);
}
else {
const NameIdentifier* saml1name = dynamic_cast<const NameIdentifier*>(xmlObject);
if (saml1name) {
if (log.isDebugEnabled()) {
auto_ptr_char f(saml1name->getFormat());
log.debug(
"decoding NameIDAttribute (%s) from SAML 1 NameIdentifier with Format (%s)",
ids.front().c_str(), f.get() ? f.get() : "unspecified"
);
}
extract(saml1name, dest, assertingParty, relyingParty);
}
else {
log.warn("XMLObject type not recognized by NameIDAttributeDecoder, no values returned");
return nullptr;
}
}
return dest.empty() ? nullptr : _decode(nameid.release());
}
void NameIDAttributeDecoder::extract(
const NameIDType* n, vector<NameIDAttribute::Value>& dest, const char* assertingParty, const char* relyingParty
) const
{
auto_arrayptr<char> name(toUTF8(n->getName()));
if (name.get() && *name.get()) {
dest.push_back(NameIDAttribute::Value());
NameIDAttribute::Value& val = dest.back();
val.m_Name = name.get();
char* str = toUTF8(n->getFormat());
if (str) {
val.m_Format = str;
delete[] str;
}
str = toUTF8(n->getNameQualifier());
if (str && *str)
val.m_NameQualifier = str;
else if (m_defaultQualifiers && assertingParty)
val.m_NameQualifier = assertingParty;
delete[] str;
str = toUTF8(n->getSPNameQualifier());
if (str && *str)
val.m_SPNameQualifier = str;
else if (m_defaultQualifiers && relyingParty)
val.m_SPNameQualifier = relyingParty;
delete[] str;
str = toUTF8(n->getSPProvidedID());
if (str) {
val.m_SPProvidedID = str;
delete[] str;
}
}
}
void NameIDAttributeDecoder::extract(
const NameIdentifier* n, vector<NameIDAttribute::Value>& dest, const char* assertingParty, const char* relyingParty
) const
{
auto_arrayptr<char> name(toUTF8(n->getName()));
if (name.get() && *name.get()) {
dest.push_back(NameIDAttribute::Value());
NameIDAttribute::Value& val = dest.back();
val.m_Name = name.get();
char* str = toUTF8(n->getFormat());
if (str) {
val.m_Format = str;
delete[] str;
}
str = toUTF8(n->getNameQualifier());
if (str && *str)
val.m_NameQualifier = str;
else if (m_defaultQualifiers && assertingParty)
val.m_NameQualifier = assertingParty;
delete[] str;
if (m_defaultQualifiers && relyingParty)
val.m_SPNameQualifier = relyingParty;
}
}
| [
"scantor@cb58f699-b61c-0410-a6fe-9272a202ed29"
] | scantor@cb58f699-b61c-0410-a6fe-9272a202ed29 |
8ad952cc113bd5b46781683b3b4c4a7f7bfe7dd5 | 5426ed64246ea6d5133493aa8455bb260f7c1788 | /CxAODMaker/CxAODMaker/.svn/text-base/TruthEventHandler.h.svn-base | 44837e588a6c963e2e2aa2babec399fbd5bc4897 | [] | no_license | ytchoutw/CxAODFramework | d2267dee5b5506ad43a91087bfc47e0716ab5ffe | 3908e88fe60d952fa3142c2c9f53dd3212a4d7c9 | refs/heads/master | 2020-06-04T02:32:45.073068 | 2016-10-20T08:43:52 | 2016-10-20T08:43:52 | 30,071,233 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 940 | // Dear emacs, this is -*-c++-*-
#ifndef CxAODMaker_TruthEventHandler_H
#define CxAODMaker_TruthEventHandler_H
// STL includes
#include <string>
// Infra structure includes
#include "xAODRootAccess/TEvent.h"
#include "EventLoop/StatusCode.h"
// Forward declarations
class ConfigStore;
class EventInfoHandler;
namespace xAOD {
#ifndef XAODTRUTH_TRUTHPARTICLECONTAINER_H
class TruthEventContainer;
#endif
#ifndef XAODTRUTH_TRUTHPARTICLE_H
class TruthEvent;
#endif
}
class TruthEventHandler {
public:
TruthEventHandler(ConfigStore & config, xAOD::TEvent * event, EventInfoHandler & eventInfoHandler);
~TruthEventHandler();
EL::StatusCode setObjects();
EL::StatusCode select();
EL::StatusCode fillOutputContainer();
EL::StatusCode clearEvent();
private:
ConfigStore & m_config;
EventInfoHandler & m_eventInfoHandler;
xAOD::TEvent * m_event;
std::string m_containerName;
};
#endif
| [
"yuantangchou@hotmail.com"
] | yuantangchou@hotmail.com | |
cadcc36d59f6cd280cd7b221144bf9075aa1c65c | da4cc98ed821ec4c41a0a29c926c0a97df3c0bff | /demo/framework-gl/application.h | 14fb8a7193ff54974298df369f8cfaf8646e1674 | [
"MIT"
] | permissive | rokuz/GraphicsDemo | 514d308ad147214480b53e58c47cfccb558a9cbd | 41300287cc9d2f7e4e0656348809db5b3c939ced | refs/heads/master | 2023-04-06T20:15:11.159235 | 2023-03-31T21:32:13 | 2023-03-31T21:32:13 | 17,832,703 | 11 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 5,078 | h | /*
* Copyright (c) 2014 Roman Kuznetsov
*
* Thanks to Graham Sellers (and his book "OpenGL SuperBible, 6th Edition") for inspiration and some code
*
* 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 (including the next
* paragraph) 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.
*/
#ifndef __APPLICATION_H__
#define __APPLICATION_H__
namespace framework
{
class Application
{
friend class Destroyable;
public:
Application();
virtual ~Application(){}
virtual void init(const std::map<std::string, int>& params){}
virtual void startup(gui::WidgetPtr_T root){}
virtual void render(double elapsedTime){}
virtual void shutdown(){}
virtual void onResize(int width, int height){}
virtual void onKeyButton(int key, int scancode, bool pressed){}
virtual void onMouseButton(double xpos, double ypos, int button, bool pressed){}
virtual void onMouseMove(double xpos, double ypos){}
static Application* instance();
int run(Application* self, const std::string& commandLine);
void exit();
void resize();
bool isDebugEnabled() const;
vector2 getScreenSize();
protected:
struct AppInfo
{
std::string title;
int windowWidth;
int windowHeight;
int samples;
union
{
struct
{
unsigned int fullscreen : 1;
unsigned int vsync : 1;
unsigned int cursor : 1;
unsigned int debug : 1;
unsigned int useStencil : 1;
};
unsigned int all;
} flags;
AppInfo();
};
AppInfo m_info;
LightManager m_lightManager;
gui::LabelPtr_T m_fpsLabel;
gui::LabelPtr_T m_legendLabel;
void renderGui(double elapsedTime);
void renderAxes(const matrix44& viewProjection);
void renderSkybox(Camera& camera, std::shared_ptr<Texture> texture);
void useDefaultRenderTarget();
void clearDefaultRenderTarget(const vector4& color = vector4(0, 0, 0, 0), float depth = 1.0f);
void applyStandardParams(const std::map<std::string, int>& params);
void setLegend(const std::string& legend);
private:
static Application* m_self;
OpenGLContext m_context;
utils::Timer m_timer;
bool m_isRunning;
double m_lastTime;
std::string m_legend;
utils::FpsCounter m_fpsCounter;
std::list<std::weak_ptr<Destroyable> > m_destroyableList;
std::shared_ptr<Line3D> m_axisX;
std::shared_ptr<Line3D> m_axisY;
std::shared_ptr<Line3D> m_axisZ;
void registerDestroyable(std::weak_ptr<Destroyable> ptr);
void destroyAllDestroyable();
bool initGui();
void destroyGui();
void initAxes();
void initInput();
void mainLoop();
static void APIENTRY debugCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, GLvoid* userParam);
};
}
#if defined _WIN32
#define DECLARE_MAIN(A) \
int CALLBACK WinMain(HINSTANCE hInstance, \
HINSTANCE hPrevInstance, \
LPSTR lpCmdLine, \
int nCmdShow) \
{ \
utils::Utils::init(); \
utils::Logger::start(utils::Logger::IDE_OUTPUT |\
utils::Logger::FILE); \
A *app = new A(); \
int result = app->run(app, lpCmdLine); \
delete app; \
utils::Logger::finish(); \
return result; \
}
#elif defined __APPLE__
#define DECLARE_MAIN(a) \
int main(int argc, const char ** argv) \
{ \
utils::Utils::init(); \
utils::Logger::start(utils::Logger::IDE_OUTPUT |\
utils::Logger::FILE); \
A *app = new A(); \
int result = app->run(app); \
delete app; \
utils::Logger::finish(); \
return result; \
}
#else
#error Undefined platform!
#endif
#endif // __APPLICATION_H__ | [
"r.kuznetsow@gmail.com"
] | r.kuznetsow@gmail.com |
4b28d88c8b943aa99e2c6e1a28a450a19966d7c6 | 40feced5d15e19f0db73c00ff7000522a8598b5b | /segitiga/membuat segitiga.cpp | 908001b22d6090b233a5327757de07cfc8e1eb0e | [] | no_license | dedesaepulloh/Pemrograman-Dasar | c711a0f9059749fce611775d54bbd3269940998e | dc68196c56283e83fc368b81cd59b612a9d79b31 | refs/heads/master | 2020-07-21T18:22:31.222839 | 2019-09-07T09:09:14 | 2019-09-07T09:09:14 | 206,942,209 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 215 | cpp | #include <iostream.h>
#include <stdio.h>
#include <conio.h>
main(){
int i,j,n;
cout << "Masukan Panjang Segitiga : "; cin >>n;
for (i=1;i<=n;i++){
for(j=1;j<=i;j++){
cout << "*";
}
cout <<endl;
}
getch();
}
| [
"dedesaepulloh77@gmail.com"
] | dedesaepulloh77@gmail.com |
1245f38432d91fb98457e1d02f2e75597bcc6ee7 | b4e2870e505b3a576115fa9318aabfb971535aef | /zParserExtender/ZenGin/Gothic_I_Classic/API/zScanDir.h | 206bb370a6045175a6a09d9841bb4240737d3d82 | [] | no_license | Gratt-5r2/zParserExtender | 4289ba2e71748bbac0c929dd1941d151cdde46ff | ecf51966e4d8b4dc27e3bfaff06848fab69ec9f1 | refs/heads/master | 2023-01-07T07:35:15.720162 | 2022-10-08T15:58:41 | 2022-10-08T15:58:41 | 208,900,373 | 6 | 1 | null | 2023-01-02T21:53:03 | 2019-09-16T21:21:28 | C++ | UTF-8 | C++ | false | false | 2,318 | h | // Supported with union (c) 2018 Union team
#ifndef __ZSCAN_DIR_H__VER0__
#define __ZSCAN_DIR_H__VER0__
#include "zDisk.h"
namespace Gothic_I_Classic {
class zCScanDirFileHandler {
public:
zCArray<zSTRING> msgList;
zCArray<zSTRING> extList;
zSTRING name;
void zCScanDirFileHandler_OnInit() zCall( 0x00463500 );
zCScanDirFileHandler() zInit( zCScanDirFileHandler_OnInit() );
int CanHandleFile( zSTRING& ) zCall( 0x00463700 );
int GetNumMessages() zCall( 0x00463920 );
zSTRING GetMessageA( int ) zCall( 0x00463930 );
void RegisterFileType( zSTRING ) zCall( 0x00463AC0 );
void AddMessage( zSTRING ) zCall( 0x00463C30 );
void ClearMessages() zCall( 0x00463DA0 );
void SetName( zSTRING const& ) zCall( 0x00463DD0 );
zSTRING& GetName() zCall( 0x00463F10 );
virtual ~zCScanDirFileHandler() zCall( 0x00463630 );
virtual int HandleFile( zSTRING const&, char const*, _finddata_t ) zPureCall;
// user API
#include "zCScanDirFileHandler.inl"
};
class zCScanDir {
public:
zCList<zCScanDirFileHandler> cbList;
int statFoundFiles;
int statHandledFiles;
int statTouchedFiles;
void zCScanDir_OnInit() zCall( 0x00463F20 );
zCScanDir() zInit( zCScanDir_OnInit() );
void ScanX() zCall( 0x00464140 );
virtual ~zCScanDir() zCall( 0x00463F60 );
virtual void RegisterFileHandler( zCScanDirFileHandler*, zSTRING const& ) zCall( 0x00463FF0 );
virtual void Scan( zSTRING const& ) zCall( 0x00464900 );
// user API
#include "zCScanDir.inl"
};
} // namespace Gothic_I_Classic
#endif // __ZSCAN_DIR_H__VER0__ | [
"amax96@yandex.ru"
] | amax96@yandex.ru |
4f963624c3cc8820d5494873643b897e3a75e703 | 2591ae43a809173d223b78207c7638d80d839962 | /LEETCODE/TREE/7_513_findBottomLeftTreeValue.cpp | a1dfdaf3ceeb3e462b54c360ff9bd8619c8247e1 | [] | no_license | DeveshDutt2710/Competitive_Programming | 82fc97efcae65b23738d7f4e4ecc880e43bf975c | 78a6251e74c8b261c94ebf79408e7c36f9331838 | refs/heads/master | 2023-07-30T16:05:54.659186 | 2021-09-22T17:44:08 | 2021-09-22T17:44:08 | 300,497,546 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,991 | cpp |
/*
https://leetcode.com/problems/find-bottom-left-tree-value/
513. Find Bottom Left Tree Value
Given the root of a binary tree, return the leftmost value in the last row of the tree.
Example 1:
Input: root = [2,1,3]
Output: 1
Example 2:
Input: root = [1,2,3,4,null,5,6,null,null,7]
Output: 7
Constraints:
The number of nodes in the tree is in the range [1, 104].
-231 <= Node.val <= 231 - 1
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
queue<TreeNode*> q;
q.push(root);
while(!q.empty()) {
root=q.front();
q.pop();
if (root->right) {
q.push(root->right);
}
if(root->left) q.push(root->left);
}
return root->val;
}
};
class Solution {
public:
int ans=0;
int depth;
bool mila=false;
void dfs(TreeNode* root, int l)
{
if(root==NULL)
return;
dfs(root->left, l+1);
if(root->left == NULL and root->right==NULL and l>depth)
depth=l;
dfs(root->right, l+1);
}
void helper(TreeNode* root, int d)
{
if(root==NULL)
return;
helper(root->left, d+1);
if(root->left==NULL and root->right==NULL and depth == d and !mila)
{
ans = root->val;
mila= true;
}
helper(root->right, d+1);
}
int findBottomLeftValue(TreeNode* root) {
depth=0;
dfs(root, 0);
helper(root, 0);
return ans;
}
}; | [
"dd123.ues2017@gmail.com"
] | dd123.ues2017@gmail.com |
d81315ea3b11026e2029343d351a88ab25217557 | 920d7ac42212620e85202665329a9db7dd322710 | /Plugins/Wwise/Source/AudiokineticTools/Classes/WwisePicker/SWwisePicker.h | 9a395ecfee8a867d85f389f443c386e1bf93ea9f | [] | no_license | lavilate/WwiseDemoGame | 8bc10481dea3f7f811633a43fb03c4ec97c1d554 | 3fc41d1b3ebfdba3f97df945671212b1d23bbff0 | refs/heads/master | 2021-07-22T03:34:11.530433 | 2017-10-29T16:57:52 | 2017-10-29T16:57:52 | 108,670,028 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,557 | h | // Copyright (c) 2006-2012 Audiokinetic Inc. / All Rights Reserved
/*------------------------------------------------------------------------------------
SWwisePicker.h
------------------------------------------------------------------------------------*/
#pragma once
/*------------------------------------------------------------------------------------
SWwisePicker
------------------------------------------------------------------------------------*/
#include "WwiseTreeItem.h"
#include "TextFilter.h"
#include "Views/ITypedTableView.h"
#include "Views/STreeView.h"
#include "WwiseWwuParser.h"
class SWwisePicker : public SCompoundWidget
{
public:
SLATE_BEGIN_ARGS( SWwisePicker )
: _FocusSearchBoxWhenOpened(false)
, _ShowTreeTitle(true)
, _ShowSearchBar(true)
, _ShowSeparator(true)
, _AllowContextMenu(true)
, _SelectionMode( ESelectionMode::Multi )
{}
/** Content displayed to the left of the search bar */
SLATE_NAMED_SLOT( FArguments, SearchContent )
/** If true, the search box will be focus the frame after construction */
SLATE_ARGUMENT( bool, FocusSearchBoxWhenOpened )
/** If true, The tree title will be displayed */
SLATE_ARGUMENT( bool, ShowTreeTitle )
/** If true, The tree search bar will be displayed */
SLATE_ARGUMENT( bool, ShowSearchBar )
/** If true, The tree search bar separator be displayed */
SLATE_ARGUMENT( bool, ShowSeparator )
/** If false, the context menu will be suppressed */
SLATE_ARGUMENT( bool, AllowContextMenu )
/** The selection mode for the tree view */
SLATE_ARGUMENT( ESelectionMode::Type, SelectionMode )
SLATE_END_ARGS( )
AUDIOKINETICTOOLS_API void Construct(const FArguments& InArgs);
SWwisePicker(void);
~SWwisePicker();
AUDIOKINETICTOOLS_API static const FName WwisePickerTabName;
AUDIOKINETICTOOLS_API void ForceRefresh();
virtual void Tick( const FGeometry& AllottedGeometry, const double InCurrentTime, const float InDeltaTime ) override;
private:
/** The tree view widget */
TSharedPtr< STreeView< TSharedPtr<FWwiseTreeItem>> > TreeViewPtr;
/** Filter for the search box */
TSharedPtr<StringFilter> SearchBoxFilter;
/** Root items (only events for now). */
TArray< TSharedPtr<FWwiseTreeItem> > RootItems;
/** Bool to prevent the selection changed callback from running */
bool AllowTreeViewDelegates;
/** Remember the selected items. Useful when filtering to preserve selection status. */
TSet< FString > LastSelectedPaths;
/** Remember the expanded items. Useful when filtering to preserve expansion status. */
TSet< FString > LastExpandedPaths;
/** Ran when the Populate button is clicked. Parses the Wwise project (using the WwiseWwuParser) and populates the window. */
FReply OnPopulateClicked();
/** Populates the picker window only (does not parse the Wwise project) */
void ConstructTree();
/** Change the watched folder for the wwu parser */
void UpdateDirectoryWatcher();
/** Generate a row in the tree view */
TSharedRef<ITableRow> GenerateRow( TSharedPtr<FWwiseTreeItem> TreeItem, const TSharedRef<STableViewBase>& OwnerTable );
/** Get the children of a specific tree element */
void GetChildrenForTree( TSharedPtr< FWwiseTreeItem > TreeItem, TArray< TSharedPtr<FWwiseTreeItem> >& OutChildren );
/** Handle Drag & Drop */
FReply OnDragDetected(const FGeometry& Geometry, const FPointerEvent& MouseEvent);
void ExpandFirstLevel();
void ExpandParents(TSharedPtr<FWwiseTreeItem> Item);
FText GetProjectName() const;
/** Used by the search filter */
void PopulateSearchStrings( const FString& FolderName, OUT TArray< FString >& OutSearchStrings ) const;
void OnSearchBoxChanged( const FText& InSearchText );
FText GetHighlightText() const;
void FilterUpdated();
void SetItemVisibility(TSharedPtr<FWwiseTreeItem> Item, bool IsVisible);
void ApplyFilter(TSharedPtr<FWwiseTreeItem> ItemToFilter);
void RestoreTreeExpansion(const TArray< TSharedPtr<FWwiseTreeItem> >& Items);
/** Handler for tree view selection changes */
void TreeSelectionChanged( TSharedPtr< FWwiseTreeItem > TreeItem, ESelectInfo::Type SelectInfo );
/** Handler for tree view expansion changes */
void TreeExpansionChanged( TSharedPtr< FWwiseTreeItem > TreeItem, bool bIsExpanded );
void OnProjectDirectoryChanged(const TArray<struct FFileChangeData>& ChangedFiles);
FDelegateHandle ProjectDirectoryModifiedDelegateHandle;
FString ProjectFolder;
FString ProjectName;
}; | [
"lavilate@gmail.com"
] | lavilate@gmail.com |
502c9f2e414f7850c9a2d9c120ac74e00456f5c9 | 4263b2fa0eadb8576805c375e4500121b88f0173 | /hellomap3/Nuti.framework/Versions/A/Headers/renderers/components/BillboardSorter.h | cd8d946a457483227f7c5485414abcab8c5b820c | [
"BSD-2-Clause"
] | permissive | Navirize/hellomap3d-ios | d2b3a4506041d1dead38d1a1fb232db6b40b7741 | 3895e29705a97580e42bc7d9e8169e43317d2546 | refs/heads/master | 2021-01-17T11:56:20.311799 | 2015-11-08T12:31:11 | 2015-11-08T12:31:11 | 45,779,480 | 0 | 0 | null | 2015-11-08T12:28:00 | 2015-11-08T12:27:59 | null | UTF-8 | C++ | false | false | 994 | h | /*
* Copyright 2014 Nutiteq Llc. All rights reserved.
* Copying and using this code is allowed only according
* to license terms, as given in https://www.nutiteq.com/license/
*/
#ifndef _NUTI_BILLBOARDSORTER_H_
#define _NUTI_BILLBOARDSORTER_H_
#include <memory>
#include <vector>
namespace Nuti {
class Billboard;
class BillboardDrawData;
class ViewState;
class BillboardSorter {
public:
BillboardSorter();
virtual ~BillboardSorter();
void addBillboard(const std::shared_ptr<Billboard>& billboard);
void sort(const ViewState& viewState);
const std::vector<std::shared_ptr<Billboard> >& getSortedBillboards() const;
void clear();
private:
bool distanceComparator(const std::shared_ptr<Billboard>& billboard1, const std::shared_ptr<Billboard>& billboard2) const;
std::vector<std::shared_ptr<Billboard> > _billboards;
bool _sort3D;
};
}
#endif
| [
"jaak@nutiteq.com"
] | jaak@nutiteq.com |
eba180397ccec0bc273c55c37f0b316c072f7513 | 9824d607fab0a0a827abff255865f320e2a7a692 | /界面资源/[XTreme.Toolkit.9.6.MFC].Xtreme.Toolkit.Pro.v9.60/Include/ReportControl/XTPReportView.h | 6e96ee476c384ff8c4e24d79b2700f3fdc989d10 | [] | no_license | tuian/pcshare | 013b24af954b671aaf98604d6ab330def675a561 | 5d6455226d9720d65cfce841f8d00ef9eb09a5b8 | refs/heads/master | 2021-01-23T19:16:44.227266 | 2014-09-18T02:31:05 | 2014-09-18T02:31:05 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 7,941 | h | // XTPReportView.h: interface for the CXTPReportView class.
//
// This file is a part of the XTREME TOOLKIT PRO MFC class library.
// ©1998-2005 Codejock Software, All Rights Reserved.
//
// THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE
// RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN
// CONSENT OF CODEJOCK SOFTWARE.
//
// THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED
// IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO
// YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A
// SINGLE COMPUTER.
//
// CONTACT INFORMATION:
// support@codejock.com
// http://www.codejock.com
//
/////////////////////////////////////////////////////////////////////////////
//{{AFX_CODEJOCK_PRIVATE
#if !defined(__XTPREPORTVIEW_H__)
#define __XTPREPORTVIEW_H__
//}}AFX_CODEJOCK_PRIVATE
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
//===========================================================================
// Summary:
// Identifier of report control child window of CXTPReportView.
// Example:
// <code>
// int CXTPReportView::OnCreate(LPCREATESTRUCT lpCreateStruct)
// {
// if (CView::OnCreate(lpCreateStruct) == -1)
// return -1;
//
// if (!m_wndReport.Create(WS_CHILD|WS_TABSTOP|WS_VISIBLE|WM_VSCROLL,
// CRect(0, 0, 0, 0), this, XTP_ID_REPORT_CONTROL))
// {
// TRACE(_T("Failed to create tab control window\n"));
// return -1;
// }
// return 0;
// }
// </code>
// See Also:
// XTP_NM_REPORT_CHECKED, XTP_NM_REPORT_COLUMNORDERCHANGED, XTP_NM_REPORT_HEADER_RCLICK,
// XTP_NM_REPORT_HYPERLINK, XTP_NM_REPORT_INPLACEBUTTONDOWN, XTP_NM_REPORT_SELCHANGED
// XTP_NM_REPORT_SORTORDERCHANGED, XTP_NM_REPORT_VALUECHANGED
// CXTPReportView, CXTPReportControl, CXTPReportHeader
//===========================================================================
const UINT XTP_ID_REPORT_CONTROL = 100;
#include "XTPReportControl.h"
//===========================================================================
// Summary:
// The CXTPReportView class provides an implementation of
// the Report control as view class. Use GetReportCtrl method to access methods
// of CXTPReportControl
// See Also: CXTPReportControl
//===========================================================================
class _XTP_EXT_CLASS CXTPReportView : public CView
{
DECLARE_DYNCREATE(CXTPReportView)
protected:
//-------------------------------------------------------------------------
// Summary:
// Protected constructor used by dynamic creation
//-------------------------------------------------------------------------
CXTPReportView();
public:
//-----------------------------------------------------------------------
// Summary:
// Call this method to access Report control object.
// Returns:
// Reference to child CXTPReportControl window
//-----------------------------------------------------------------------
CXTPReportControl& GetReportCtrl();
//-----------------------------------------------------------------------
// Summary:
// Retrieved paint manager of the child report control.
// Returns:
// Pointer to paint manager of report control.
//-----------------------------------------------------------------------
CXTPReportPaintManager* GetPaintManager();
protected:
//-------------------------------------------------------------------------
// Summary:
// Destroys a CXTPReportView object, handles cleanup and deallocation.
//-------------------------------------------------------------------------
virtual ~CXTPReportView();
protected:
//-----------------------------------------------------------------------
// Summary:
// This method is called to print single page of report control.
// Parameters:
// pDC - Pointer to a device context for page output.
// pInfo - Points to a CPrintInfo structure that describes the current print job.
// rcPage - Page bounding rectangle
// nIndexStart - First row to print
// Remarks:
// This method call PrintHeader, PrintRows and PrintFooter methods.
// Returns:
// Index of last printed row
//-----------------------------------------------------------------------
virtual long PrintPage (CDC* pDC, CPrintInfo* pInfo, CRect rcPage, long nIndexStart);
//-----------------------------------------------------------------------
// Summary:
// This method is called to print header of each page.
// Parameters:
// pDC - Pointer to a device context for page output.
// rcHeader - Header bounding rectangle
//-----------------------------------------------------------------------
virtual void PrintHeader(CDC* pDC, CRect rcHeader);
//-----------------------------------------------------------------------
// Summary:
// This method is called to draw all rows inside bounding rectangle.
// Parameters:
// pDC - Pointer to a device context for page output.
// rcRows - Bounding rectangle of rows
// nIndexStart - First row to print
// Returns:
// Index of last printed row
//-----------------------------------------------------------------------
virtual int PrintRows(CDC* pDC, CRect rcRows, long nIndexStart);
//-----------------------------------------------------------------------
// Summary:
// This method is called by PrintRows to print single row.
// Parameters:
// pDC - Pointer to a device context for page output.
// pRow - Row to print.
// rcRow - Bounding rectangle of row
//-----------------------------------------------------------------------
virtual void PrintRow(CDC* pDC, CXTPReportRow* pRow, CRect rcRow);
//-----------------------------------------------------------------------
// Summary:
// This method is called to print footer information for each page.
// Parameters:
// pDC - Pointer to a device context for page output.
// pInfo - Points to a CPrintInfo structure that describes the current print job.
// rcFooter - Footer bounding rectangle
//-----------------------------------------------------------------------
virtual void PrintFooter(CDC* pDC, CPrintInfo* pInfo, CRect rcFooter);
//-----------------------------------------------------------------------
// Summary:
// This method calculates width of column need to print.
// Parameters:
// pColumn - Column need to print
// nTotalWidth - Total width of all columns.
// Returns:
// Width of column.
//-----------------------------------------------------------------------
int GetColumnWidth(CXTPReportColumn* pColumn, int nTotalWidth);
protected:
//{{AFX_CODEJOCK_PRIVATE
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
DECLARE_MESSAGE_MAP()
//{{AFX_VIRTUAL(CXTPReportView)
virtual BOOL PaginateTo(CDC* pDC, CPrintInfo* pInfo);
virtual void OnPrepareDC(CDC* pDC, CPrintInfo* pInfo);
virtual void OnDraw(CDC* pDC);
virtual BOOL OnPreparePrinting(CPrintInfo* pInfo);
virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo);
virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo);
virtual void OnPrint(CDC* pDC, CPrintInfo* pInfo);
//}}AFX_VIRTUAL
//{{AFX_MSG(CXTPReportView)
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnSetFocus(CWnd* pOldWnd);
afx_msg void OnPaint();
//}}AFX_MSG
//}}AFX_CODEJOCK_PRIVATE
protected:
CXTPReportControl m_wndReport; // Child report control window.
CUIntArray m_aPageStart; // Printed indexes.
};
/////////////////////////////////////////////////////////////////////////////
AFX_INLINE CXTPReportControl& CXTPReportView::GetReportCtrl() {
return m_wndReport;
}
#endif // !defined(__XTPREPORTVIEW_H__)
| [
"sincoder@vip.qq.com"
] | sincoder@vip.qq.com |
b6e46fca2418e671c9f1abff11baa47e34d3bfe5 | 47bc067058e4d45f8729670b1bfa19aceaadc156 | /facebook hackercup qual 2017/1.cpp | a60c9478f12067e0158ce541941895d52cb17c8a | [] | no_license | return19/All-C-Codes | 0bd0df357cd4bbc6552e1d943df792a1b4d806bb | b1c2269d2436a0cd65a5ef022595300c4827520f | refs/heads/master | 2021-09-09T16:13:53.464406 | 2018-03-17T17:02:55 | 2018-03-17T17:02:55 | 125,650,568 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,963 | cpp | #include<bits/stdc++.h>
using namespace std;
double pi = 3.14159265359;
double degree(double x){
return (x*pi)/180.0;
}
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
int i,j,k;
int test,t;
double p;
double x,y;
double prec = 0.0000001;
scanf("%d",&test);
for(t=0;t<test;t++){
//scanf("%lf%lf%lf",&p,&x,&y);
cin>>p>>x>>y;
x -=50;
y-=50;
double angle = 3.6*p;
if(p == 0 || (sqrt( x*x + y*y ) - 50.0 > prec )){
printf("Case #%d: white\n",t+1);
continue;
}
if(p==100){
printf("Case #%d: black\n",t+1);
continue;
}
if(x == 0 && y >=0){
printf("Case #%d: black\n",t+1);
} else if(x == 0 && y < 0 ){
if(p>=50)
printf("Case #%d: black\n",t+1);
else
printf("Case #%d: white\n",t+1);
} else if(y==0 && x>=0){
if(p>=25)
printf("Case #%d: black\n",t+1);
else
printf("Case #%d: white\n",t+1);
} else if(y == 0 && x < 0){
if(p>=75)
printf("Case #%d: black\n",t+1);
else
printf("Case #%d: white\n",t+1);
} else {
if(p==25){
if(x>=0 && y>=0)
printf("Case #%d: black\n",t+1);
else
printf("Case #%d: white\n",t+1);
continue;
}
if(p==50){
if(x>=0)
printf("Case #%d: black\n",t+1);
else
printf("Case #%d: white\n",t+1);
continue;
}
if(p==75){
if(x<0 && y>0)
printf("Case #%d: white\n",t+1);
else
printf("Case #%d: black\n",t+1);
continue;
}
double a = abs(x);
double b = abs(y);
if(p<25){
if( (a/b) - tan(degree(angle)) < prec )
printf("Case #%d: black\n",t+1);
else
printf("Case #%d: white\n",t+1);
} else if(p>25 && p<50){
if( (b/a) - tan(degree(angle-90)) < prec )
printf("Case #%d: black\n",t+1);
else
printf("Case #%d: white\n",t+1);
} else if(p>50 && p<75){
if( (a/b) - tan(degree(angle-180)) < prec )
printf("Case #%d: black\n",t+1);
else
printf("Case #%d: white\n",t+1);
} else {
if((b/a)- tan(degree(angle-270)) < prec)
printf("Case #%d: black\n",t+1);
else
printf("Case #%d: white\n",t+1);
}
}
}
return 0;
}
| [
"abhinandan1941996@gmail.com"
] | abhinandan1941996@gmail.com |
207288e1a9f5fd8105d78c48abe664a05fe11c17 | d1909a2cbed9505a10cb3a9991b3659a5ce1525d | /Grid.cpp | dac53897dc321db9dd5aa4b983b6672f17ca6a56 | [] | no_license | XKraft/Plants_Vs_Zombies2.0 | 3040e0bfb3c02807ac26c6df7f1550e354a3cc27 | 2bc0cc9d752d5bf1da1d5bdfcfbea7096261ea0a | refs/heads/main | 2023-04-23T23:23:28.013945 | 2021-05-17T02:22:31 | 2021-05-17T02:22:31 | 368,030,962 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 10,553 | cpp | #include"Grid.h"
using namespace std;
Grid::Grid()
{
_X = -1;
_Y = -1;
_state = BLANK;
}
void Grid::SetGridXY(int x, int y)
{
_X = x;
_Y = y;
}
void Grid::Draw(bool display_cursor)
{
for (int i = 1; i <= 4; ++i)
{
CursorSetXY(_X + 1, _Y + i);
cout << " ";
}
if (display_cursor)
{
SetPrintColor(b_yellow);
DrawGridEdge(_X, _Y);
SetPrintColor(reset);
}
if (_state == BLANK)
{
if (_zombies.size() == 1)
{
if (_zombies.front()->GetSnow())
SetPrintColor(f_blue);
CursorSetXY(_X + 3, _Y + 2);
cout << _zombies.front()->GetZombieName();
CursorSetXY(_X + 3, _Y + 3);
cout << "HP:" << _zombies.front()->GetZombieHP();
SetPrintColor(reset);
}
if (_zombies.size() > 1 && _zombies.size() <= 3)
{
for (int i = 0; i < _zombies.size(); ++i)
{
if (_zombies[i]->GetSnow())
SetPrintColor(f_blue);
CursorSetXY(_X + 3, _Y + i + 1);
cout << _zombies[i]->GetZombieName();
SetPrintColor(reset);
}
}
if (_zombies.size() > 3)
{
for (int i = 0; i < 3; ++i)
{
if (_zombies[i]->GetSnow())
SetPrintColor(f_blue);
CursorSetXY(_X + 3, _Y + i + 1);
cout << _zombies[i]->GetZombieName();
SetPrintColor(reset);
}
CursorSetXY(_X + 1, _Y + 4);
cout << "僵尸 ×" << _zombies.size();
}
}
else
{
if (_zombies.size())
{
if (_state == PLANT_PUMPKIN)
{
CursorSetXY(_X + 1, _Y + 1);
cout << _plants[0]->GetPlantName();
CursorSetXY(_X + 1, _Y + 2);
cout << _plants[1]->GetPlantName();
CursorSetXY(_X + 1, _Y + 3);
if (_zombies.front()->GetSnow())
SetPrintColor(f_blue);
cout << _zombies.front()->GetZombieName();
SetPrintColor(reset);
CursorSetXY(_X + 1, _Y + 4);
cout << "僵尸 ×" << _zombies.size();
}
else
{
CursorSetXY(_X + 1, _Y + 1);
cout << "HP:" << _plants[0]->GetPlantHP();
CursorSetXY(_X + 1, _Y + 2);
cout << _plants[0]->GetPlantName();
CursorSetXY(_X + 1, _Y + 3);
if (_zombies.front()->GetSnow())
SetPrintColor(f_blue);
cout << _zombies.front()->GetZombieName();
SetPrintColor(reset);
CursorSetXY(_X + 1, _Y + 4);
cout << "僵尸 ×" << _zombies.size();
}
}
else
{
if (_state == PLANT_PUMPKIN)
{
CursorSetXY(_X + 1, _Y + 1);
cout << "HP:" << _plants[0]->GetPlantHP();
CursorSetXY(_X + 1, _Y + 2);
cout << _plants[0]->GetPlantName();
CursorSetXY(_X + 1, _Y + 3);
cout << _plants[1]->GetPlantName();
CursorSetXY(_X + 1, _Y + 4);
cout << "HP:" << _plants[1]->GetPlantHP();
}
else
{
CursorSetXY(_X + 1, _Y + 2);
cout << _plants[0]->GetPlantName();
CursorSetXY(_X + 1, _Y + 3);
cout << "HP:" << _plants[0]->GetPlantHP();
}
}
}
}
bool Grid::GrowPlant(Plants* plant, int ID)
{
if (_state == BLANK)
{
_plants.push_back(plant);
if (ID != 10)
_state = PLANT;
else
_state = PUMPKIN;
return true;
}
if (_state == PLANT_PUMPKIN)
return false;
if (_state == PLANT)
{
if (ID == 10)
{
_plants.push_back(plant);
_state = PLANT_PUMPKIN;
return true;
}
else
return false;
}
if (_state == PUMPKIN)
{
if (ID != 10)
{
_plants.insert(_plants.begin(), plant);
_state = PLANT_PUMPKIN;
return true;
}
else
return false;
}
}
void Grid::AddZombie(int ID)
{
Zombies* zombie = NULL;
switch (ID)
{
case 1:
zombie = new Zombies; break;
case 2:
zombie = new ConheadZombie; break;
case 3:
zombie = new PoleVaultingZombie; break;
case 4:
zombie = new NewspaperZombie; break;
case 5:
zombie = new JackInTheBoxZombie; break;
case 6:
zombie = new CatapultZombie; break;
}
_zombies.push_back(zombie);
}
bool Grid::ExistZombie()
{
if (_zombies.size() != 0)
return true;
else
return false;
}
bool Grid::MoveZombie(Grid map[][7], int x, int y)
{
bool zstepover = true;
if (_plants.size() == 0)
zstepover = true;
else
zstepover = _plants[0]->GetStepOver();
for (unsigned int i = 0; i < _zombies.size(); )
{
if (_zombies[i]->ChangeRoad(false))
{
int dy = 0;
if (y == 0 )
dy = 1;
else if (y == 4 )
dy = -1;
else
{
int i = rand() % 2;
if (i == 0)
dy = 1;
else
dy = -1;
}
_zombies[i]->ChangeMove(true);
map[y + dy][x]._zombies.push_back(_zombies[i]);
_zombies.erase(_zombies.begin() + i);
}
else if ((_zombies[i])->JugdeMove(zstepover))
{
if (x == 0)
return true;
map[y][x - 1]._zombies.push_back(_zombies[i]);
_zombies.erase(_zombies.begin() + i);
}
else
++i;
}
return false;
}
void Grid::ZombieEatPlant()
{
if (_state != BLANK && _zombies.size() != 0)
for (unsigned int i = 0; i < _zombies.size(); ++i)
{
if (_zombies[i]->Attack(_plants.back()->GetPlantHP(), _plants.back()->GetInvincibility()))
{
_zombies[i]->ChangeRoad(_plants.back()->BeAte());
if (_plants.back()->GetPlantHP() == 0)
{
Plants* p = _plants.back();
_plants.pop_back();
delete p;
if (_plants.size() == 1)
{
_state = PLANT;
continue;
}
else
{
_state = BLANK;
for (int j = 0; j < _zombies.size(); ++j)
_zombies[j]->ChangeMove(true);
break;
}
}
}
}
}
void Grid::ZombieFunction(Grid map[][7], int x, int y, int lastplant, deque<Bullets*>& basketball)
{
ZombieAction za = NONE;
for (unsigned int i = 0; i < _zombies.size(); )
{
_zombies[i]->Function(za, x, lastplant);
if (za == BOMB)
{
SetPrintColor(b_red);
for (int k = -1; k <= 1; ++k)
for (int j = -1; j <= 1; ++j)
{
if (x + j < 7 && x + j >= 0 && y + k < 5 && y + k >= 0)
{
DrawGridEdge(map[y + k][x + j]._X, map[y + k][x + j]._Y);//绘制爆炸特效
map[y + k][x + j].ClearDead(3);
}
}
ClearDead(1);
SetPrintColor(reset);
}
if (za == SHOOT)
{
BasketballBullet* p = new BasketballBullet(_X, _Y + 1, lastplant);
basketball.push_back(p);
++i;
}
if (za == NONE)
++i;
}
}
bool Grid::BulletAttack(Bullets* b, Target t, int &score)
{
if (t == ZOMBIES)
{
if (_zombies.size() != 0)
{
auto max = _zombies.begin();
for (auto i = _zombies.begin(); i < _zombies.end(); ++i)
if ((*i)->GetGridMove() > (*max)->GetGridMove())
max = i;
if ((*max)->BeAttack(b->GetBulletAtk(), b->GetFreeze()))
{
score += (*max)->GetZombieScore();
delete (*max);
_zombies.erase(max);
}
return true;
}
return false;
}
if (t == PLANTS)
{
BasketballBullet* p = (BasketballBullet*)b;
if (p->GetDestination() == _X / 13)
{
if (_plants.size() == 0)
return true;
if (_plants[0]->BeAttack(p->GetBulletAtk()))
{
delete _plants[0];
_plants.erase(_plants.begin());
if (_plants.size() == 1)
_state = PUMPKIN;
else
_state = BLANK;
}
return true;
}
return false;
}
}
void Grid::ClearDead(int choice)
{
if (choice == 0 || choice == 2)//清除格子中HP为0的植物
for (unsigned int i = 0; i < _plants.size(); )
if (_plants[i]->GetPlantHP() <= 0)
{
delete _plants[i];
_plants.erase(_plants.begin() + i);
if (_plants.size() == 0)
_state = BLANK;
if (_plants.size() == 1 && i == 0)
_state = PUMPKIN;
if (_plants.size() == 1 && i == 1)
_state = PLANT;
}
else
++i;
if (choice == 1 || choice == 2)//清除格子中HP为0的僵尸
for (unsigned int i = 0; i < _zombies.size(); )
if (_zombies[i]->GetZombieHP() <= 0)
{
delete _zombies[i];
_zombies.erase(_zombies.begin() + i);
}
else
++i;
if (choice == 3 || choice == 5)//清除格子中所有植物
{
while (!_plants.empty())
{
delete _plants.front();
_plants.erase(_plants.begin());
}
_state = BLANK;
}
if (choice == 4 || choice == 5)//清除格子中所有僵尸
{
while (!_zombies.empty())
{
delete _zombies.front();
_zombies.erase(_zombies.begin());
}
}
}
void Grid::PlantFunction(Grid map[][7], int x, int y, bool exsitzombie, int& sunlight, deque<Bullets*> &bullet, int& score)
{
PlantAction pa = _NONE;
for (unsigned int i = 0; i < _plants.size(); )
{
unsigned int zombie_nums = 0;
for (int j = -1; j <= 1; ++j)
if (x + j >= 0 && x + j < 7)
zombie_nums += map[y][x + j]._zombies.size();
_plants[i]->Function(pa, exsitzombie, zombie_nums, sunlight);
if (pa == _SHOOT)
{
Bullets* p = new Bullets(_X + 13, _Y + 2);
bullet.push_back(p);
pa = _NONE;
}
if (pa == _SHOOT_SNOW)
{
Bullets* p = new SnowBullet(_X + 13, _Y + 2);
bullet.push_back(p);
pa = _NONE;
}
if (pa == _BOMP)
{
SetPrintColor(b_red);
for (int k = -1; k <= 1; ++k)
for (int j = -1; j <= 1; ++j)
{
if (x + j < 7 && x + j >= 0 && y + k < 5 && y + k >= 0)
{
DrawGridEdge(map[y + k][x + j]._X, map[y + k][x + j]._Y);//绘制爆炸特效
for (auto m = map[y + k][x + j]._zombies.begin(); m < map[y + k][x + j]._zombies.end(); ++m)
score += (*m)->GetZombieScore();
map[y + k][x + j].ClearDead(4);
}
}
ClearDead(0);
SetPrintColor(reset);
}
if (pa == _BOUCE)
{
int _x = x;
/*if (map[x][y]._zombies.size() == 0 && zombie_nums)
{
if (x - 1 < 0)
_x = x + 1;
else if (x + 1 >= 7)
_x = x - 1;
else if (map[x - 1][y]._zombies.size() == 0)
_x = x + 1;
else if (map[x + 1][y]._zombies.size() == 0)
_x = x - 1;
else
{
if (map[x - 1][y]._zombies.size() > map[x - 1][y]._zombies.size())
_x = x - 1;
else
_x = x + 1;
}
}*/
/*if (x - 1 >= 0)
{
if (map[x - 1][y]._zombies.size() != 0)
_x = x - 1;
}
else if (map[x][y]._zombies.size() != 0)
_x = x;
else if (x + 1 < 7)
{
if (map[x + 1][y]._zombies.size() != 0)
_x = x + 1;
}*/
if (x + 1 < 7)
if (!map[y][x + 1]._zombies.empty())
_x = x + 1;
if (!map[y][x]._zombies.empty())
_x = x;
if (x - 1 >= 0)
if (!map[y][x - 1]._zombies.empty())
_x = x - 1;
SetPrintColor(b_red);
DrawGridEdge(map[y][_x]._X, map[y][_x]._Y);//绘制特效
SetPrintColor(reset);
map[y][_x].ClearDead(4);
ClearDead(0);
}
if (pa == _NONE)
++i;
}
} | [
"noreply@github.com"
] | noreply@github.com |
06e8fac6f3eca2b8884cfe7ecd2ebf8a78932774 | 1af87cd959eb826ed2671545886d6ecc3f65b409 | /net/third_party/http2/hpack/varint/hpack_varint_decoder.cc | c001b52109fdcdab451f27b827adaf33c481ab7b | [
"BSD-3-Clause"
] | permissive | alisha/chromium | f427cd8ac3a38f141da320da33418a1f727a5658 | be615a8821d04fb4bf6d371be95bd323d2d4155c | refs/heads/master | 2023-03-09T04:19:23.854288 | 2018-12-07T18:00:38 | 2018-12-07T18:00:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,443 | cc | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/third_party/http2/hpack/varint/hpack_varint_decoder.h"
#include "net/third_party/http2/platform/api/http2_flag_utils.h"
#include "net/third_party/http2/platform/api/http2_string_utils.h"
namespace http2 {
DecodeStatus HpackVarintDecoder::Start(uint8_t prefix_value,
uint8_t prefix_length,
DecodeBuffer* db) {
DCHECK_LE(3u, prefix_length);
DCHECK_LE(prefix_length, 7u);
// |prefix_mask| defines the sequence of low-order bits of the first byte
// that encode the prefix of the value. It is also the marker in those bits
// of the first byte indicating that at least one extension byte is needed.
const uint8_t prefix_mask = (1 << prefix_length) - 1;
// Ignore the bits that aren't a part of the prefix of the varint.
value_ = prefix_value & prefix_mask;
if (value_ < prefix_mask) {
MarkDone();
return DecodeStatus::kDecodeDone;
}
offset_ = 0;
return Resume(db);
}
DecodeStatus HpackVarintDecoder::StartExtended(uint8_t prefix_length,
DecodeBuffer* db) {
DCHECK_LE(3u, prefix_length);
DCHECK_LE(prefix_length, 7u);
value_ = (1 << prefix_length) - 1;
offset_ = 0;
return Resume(db);
}
DecodeStatus HpackVarintDecoder::Resume(DecodeBuffer* db) {
if (decode_64_bits_) {
HTTP2_RELOADABLE_FLAG_COUNT(http2_varint_decode_64_bits);
// There can be at most 10 continuation bytes. Offset is zero for the
// first one and increases by 7 for each subsequent one.
const uint8_t kMaxOffset = 63;
CheckNotDone();
// Process most extension bytes without the need for overflow checking.
while (offset_ < kMaxOffset) {
if (db->Empty()) {
return DecodeStatus::kDecodeInProgress;
}
uint8_t byte = db->DecodeUInt8();
uint64_t summand = byte & 0x7f;
// Shifting a 7 bit value to the left by at most 56 places can never
// overflow on uint64_t.
DCHECK_LE(offset_, 56);
DCHECK_LE(summand, std::numeric_limits<uint64_t>::max() >> offset_);
summand <<= offset_;
// At this point,
// |value_| is at most (2^prefix_length - 1) + (2^49 - 1), and
// |summand| is at most 255 << 56 (which is smaller than 2^63),
// so adding them can never overflow on uint64_t.
DCHECK_LE(value_, std::numeric_limits<uint64_t>::max() - summand);
value_ += summand;
// Decoding ends if continuation flag is not set.
if ((byte & 0x80) == 0) {
MarkDone();
return DecodeStatus::kDecodeDone;
}
offset_ += 7;
}
if (db->Empty()) {
return DecodeStatus::kDecodeInProgress;
}
DCHECK_EQ(kMaxOffset, offset_);
uint8_t byte = db->DecodeUInt8();
// No more extension bytes are allowed after this.
if ((byte & 0x80) == 0) {
uint64_t summand = byte & 0x7f;
// Check for overflow in left shift.
if (summand <= std::numeric_limits<uint64_t>::max() >> offset_) {
summand <<= offset_;
// Check for overflow in addition.
if (value_ <= std::numeric_limits<uint64_t>::max() - summand) {
value_ += summand;
MarkDone();
return DecodeStatus::kDecodeDone;
}
}
}
// Signal error if value is too large or there are too many extension bytes.
DLOG(WARNING) << "Variable length int encoding is too large or too long. "
<< DebugString();
MarkDone();
return DecodeStatus::kDecodeError;
}
// Old code path. TODO(bnc): remove.
DCHECK(!decode_64_bits_);
const uint8_t kMaxOffset = 28;
CheckNotDone();
do {
if (db->Empty()) {
return DecodeStatus::kDecodeInProgress;
}
uint8_t byte = db->DecodeUInt8();
if (offset_ == kMaxOffset && byte != 0)
break;
DCHECK(offset_ <= kMaxOffset - 7 || byte == 0);
// Shifting a 7 bit value to the left by at most 21 places can never
// overflow on uint32_t. Shifting 0 to the left cannot overflow either.
value_ += (byte & 0x7f) << offset_;
if ((byte & 0x80) == 0) {
MarkDone();
return DecodeStatus::kDecodeDone;
}
offset_ += 7;
} while (offset_ <= kMaxOffset);
DLOG(WARNING) << "Variable length int encoding is too large or too long. "
<< DebugString();
MarkDone();
return DecodeStatus::kDecodeError;
}
uint64_t HpackVarintDecoder::value() const {
CheckDone();
return value_;
}
void HpackVarintDecoder::set_value(uint64_t v) {
MarkDone();
value_ = v;
}
Http2String HpackVarintDecoder::DebugString() const {
return Http2StrCat("HpackVarintDecoder(value=", value_, ", offset=", offset_,
")");
}
DecodeStatus HpackVarintDecoder::StartForTest(uint8_t prefix_value,
uint8_t prefix_length,
DecodeBuffer* db) {
return Start(prefix_value, prefix_length, db);
}
DecodeStatus HpackVarintDecoder::StartExtendedForTest(uint8_t prefix_length,
DecodeBuffer* db) {
return StartExtended(prefix_length, db);
}
DecodeStatus HpackVarintDecoder::ResumeForTest(DecodeBuffer* db) {
return Resume(db);
}
} // namespace http2
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
baae9e72418054bcd3137b357a5ccf67149a1530 | 20dd52e82277a726f1df75d986fcc5b7d19779f1 | /glwidget.h | ec26a1f3a58316dfe5fe4139d621b782f2791b56 | [] | no_license | Igor-kor/qt_opengl_snake | 22202bcd686d3aeb7299937bebb18f2bfcea3fdb | aac420e3282c2131163b1360ccc7ffa9e0f36c81 | refs/heads/master | 2023-03-30T05:39:26.404470 | 2020-07-02T09:01:05 | 2020-07-02T09:01:05 | 276,598,499 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 991 | h | #ifndef GLWIDGET_H
#define GLWIDGET_H
#include <QGLWidget>
#include <QTimer>
#include <QTime>
#include <QMediaPlayer>
#include "Zmeyka.h"
#include "globject.h"
class GLWidget : public QGLWidget
{
Q_OBJECT
public:
GLuint zmeykaTextureGL[2];
bool gameover;
int frames;
QTime time;
GLObject* zmeyaObj;
GLObject* headzmeyaObj;
GLObject* eatObj;
GLObject* backgroundObj;
GLObject* gameoverObj;
QMediaPlayer* eatmusic;
QMediaPlayer* scrimer;
QMediaPlayer* music;
ZMEYKA one;
ZMEYKAEL eat;
bool key_press;
explicit GLWidget(QWidget* parent = 0);
void initializeGL();
void paintGL();
void resizeGL(int nWidth, int nHeight);
void keyPressEvent(QKeyEvent *ke);
void generateTextures(GLuint* , char* ,int,bool);
void initializeObjects();
GLfloat zmeykaVertexArray[4][2];
GLfloat zmeykaColorArray[4][2];
GLubyte zmeykaIndexArray[1][4];
public slots:
void mainLoop();
};
#endif // GLWIDGET_H
| [
"igor_korenovsk@mail.ru"
] | igor_korenovsk@mail.ru |
a04f3b00d252c8234f622696136770b20226076b | 72cc2533a2100733cbf8fdd3481f9e19200cab48 | /library.cpp | 5d4d61c4d88a4e1bd4d3b848b67a23f5097d9aca | [] | no_license | fru-old/Autoencoder1 | 16fb4dd7a1d98c01d16f0bc02641d11a66faeb48 | e67255aa3f7754a0009ae184eb609f02918dba96 | refs/heads/master | 2021-03-27T08:28:39.556673 | 2016-04-23T13:13:10 | 2016-04-23T13:13:10 | 56,006,392 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 72 | cpp | extern "C"
{
__declspec(dllexport) double Test()
{
return 54.0;
}
} | [
"florian.rueberg@gmail.com"
] | florian.rueberg@gmail.com |
1d9695c12af5637fd2402695aa74143e413710bd | ee09f4c64c5b275cff5ffd8aaea4bd323fdba02f | /Source/SIMPLib/Math/ArrayHelpers.hpp | 6d9b5ecd0b91879dad860fcb4e64c82da1d3f07c | [
"BSD-3-Clause"
] | permissive | tplatt77/SIMPL | c4e1a4eafd77697a60e7be0ae0adc21da40ca2cc | b0ae871b14b24277bda91dbbb2a77b0f4688b7ee | refs/heads/develop | 2021-07-08T16:35:02.038457 | 2019-07-03T19:45:02 | 2019-07-03T19:45:02 | 158,443,139 | 0 | 0 | null | 2019-03-29T18:12:17 | 2018-11-20T19:49:28 | C++ | UTF-8 | C++ | false | false | 3,530 | hpp | #pragma once
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <limits>
#include <iomanip>
#include <SIMPLib/Math/SIMPLibMath.h>
/**
* @brief ArrayHelpers: Some quick methods that act on an "array" of POD values.
* The template parameters are:
* @param T The type such as std::vector, QVector or another type that implements
* the [] operators, size() functions.
* @param K The POD type such as float or double.
*/
template<typename T, typename K>
class ArrayHelpers
{
public:
virtual ~ArrayHelpers(){}
static void splat(T& a, const K val)
{
size_t size = a.size();
for(size_t i = 0; i < size; i++)
{
a[i] = val;
}
}
static T multiply(const T& a, const T& b)
{
T c(a.size());
for(size_t i = 0; i < c.size(); i++)
{
c[i] = a[i] * b[i];
}
return c;
}
static T multiply(const T& a, const T& b, size_t max)
{
T c(max);
for(size_t i = 0; i < max; i++)
{
c[i] = a[i] * b[i];
}
return c;
}
static void scalarMultiply(T& a, K b)
{
size_t size = a.size();
for(size_t i = 0; i < size; i++)
{
a[i] = a[i] * b;
}
}
static void scalarDivide(T& a, K b)
{
size_t size = a.size();
for(size_t i = 0; i < size; i++)
{
a[i] = a[i] / b;
}
}
static K sum(const T& a)
{
K s = static_cast<K>(0);
for(size_t i = 0; i < a.size(); i++)
{
s += a[i];
}
return s;
}
static K sum(const T& a, size_t max)
{
K s = static_cast<K>(0);
for(size_t i = 0; i < max; i++)
{
s += a[i];
}
return s;
}
static K sumofSquares(const T& a)
{
K s = static_cast<K>(0);
for(size_t i = 0; i < a.size(); i++)
{
s += a[i] * a[i];
}
return s;
}
static K maxval(const T& a)
{
K s = a[0];
for(size_t i = 1; i < a.size(); i++)
{
if (a[i] > s) { s = a[i]; }
}
return s;
}
static T absValue(const T& a)
{
T c(a.size());
for(size_t i = 0; i < c.size(); i++)
{
c[i] = (a[i] < 0.0 ? -a[i] : a[i]);
}
return c;
}
/* Auxiliary routine: printing eigenvectors */
static void print_eigenvectors( const char* desc, int n, float* wi, float* v, int ldv )
{
int i, j;
printf( "\n %s\n", desc );
for( i = 0; i < n; i++ )
{
j = 0;
while( j < n )
{
if( wi[j] == (float)0.0 )
{
printf( " %6.2f", v[i + j * ldv] );
j++;
}
else
{
printf( " (%6.2f,%6.2f)", v[i + j * ldv], v[i + (j + 1)*ldv] );
printf( " (%6.2f,%6.2f)", v[i + j * ldv], -v[i + (j + 1)*ldv] );
j += 2;
}
}
printf( "\n" );
}
}
/**
* @brief print
* @param c
* @param out
*/
static void print(const T& c, std::ostream &out)
{
out.width(16);
for(size_t i = 0; i < c.size(); i++)
{
out << std::fixed << std::setprecision( 16 ) << c[i];
if(i < c.size() - 1) { out << " "; }
if (i == c.size() - 1) { out << std::endl; }
}
}
protected:
ArrayHelpers(){}
private:
ArrayHelpers(const ArrayHelpers&); // Copy Constructor Not Implemented
void operator=(const ArrayHelpers&); // Move assignment Not Implemented
};
| [
"mike.jackson@bluequartz.net"
] | mike.jackson@bluequartz.net |
6a7a00afda1ed830397577bf9ed628e109df94ea | 60ec554a4dcd9fcd10e70e04d178d32569721ffe | /base.hpp | ff4d26425260a0160273a0d733585d94b1a49569 | [] | no_license | cthi001/Calculator-with-GUI | 724be413624217abddf80b8462c2d99503f42bc5 | e62e7f4b30ac7e034dddb3bf6a1f5ed37ce1fa2f | refs/heads/master | 2022-12-16T13:40:37.511865 | 2020-09-24T07:25:15 | 2020-09-24T07:25:15 | 298,198,634 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 297 | hpp | #ifndef __BASE_HPP__
#define __BASE_HPP__
#include <string>
#include <math.h>
class Base {
public:
/* Constructors */
Base() {};
/* Pure Virtual Functions */
virtual double evaluate() = 0;
virtual std::string stringify() = 0;
};
#endif //__BASE_HPP__
| [
"cthi001@ucr.edu"
] | cthi001@ucr.edu |
768cf6473d1ae4d691464d40981e7b6a30424456 | bee39d5e352e497d4c0bec686014dd689a1d6ff6 | /Geometry/point_location.cpp | 082ff7101f9f96e769cd300e675ccd71a2ea3e05 | [
"MIT"
] | permissive | su050300/CSES-Problemset-Solutions | 41ba1b4f292f5fe536d01b788628bd57f813df43 | 292281f9ac3c57c21c8208b30087386c29238d17 | refs/heads/master | 2023-03-03T10:46:39.337575 | 2021-02-12T04:55:01 | 2021-02-12T04:55:01 | 276,333,967 | 3 | 0 | null | 2021-02-04T04:52:08 | 2020-07-01T09:24:33 | C++ | UTF-8 | C++ | false | false | 772 | cpp | #include <bits/stdc++.h>
using namespace std;
#define ll long long int
struct P
{
ll x, y;
void read()
{
cin >> x >> y;
}
P operator-(P b)
{
return P{x - b.x, y - b.y};
}
P operator+(P b)
{
return P{x + b.x, y + b.y};
}
ll operator*(P b)
{
return b.y * x - b.x * y;
}
};
void solve()
{
P p1, p2, p3;
p1.read();
p2.read();
p3.read();
p3 = p3 - p1;
p2 = p2 - p1;
ll res = p2 * p3;
if (res > 0)
{
cout << "LEFT" << endl;
}
else if (res < 0)
{
cout << "RIGHT" << endl;
}
else
{
cout << "TOUCH" << endl;
}
}
int main()
{
ll t;
cin >> t;
while (t--)
{
solve();
}
return 0;
} | [
"ks99737@gmail.com"
] | ks99737@gmail.com |
b8a9e0a4a6b1f355418a42911e7a5d9c10c76072 | 3400e536711b24cdb658771bde4ca3d891d57045 | /src/server/game/Entities/Player/Player.cpp | 4602cff9d2011c9271a4543d1700271a34b7c517 | [] | no_license | Grimtonz1337/ikaroswow | 01a843e405fe0637527bbdd2f559c4198ea768c6 | c3bf9d960a3c3cc4e327f45632d93c7123eabd70 | refs/heads/master | 2021-01-21T13:41:41.536210 | 2013-08-27T21:31:36 | 2013-08-27T21:31:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 976,726 | cpp | /*
* Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Player.h"
#include "AccountMgr.h"
#include "AchievementMgr.h"
#include "ArenaTeam.h"
#include "ArenaTeamMgr.h"
#include "Battlefield.h"
#include "BattlefieldMgr.h"
#include "BattlefieldWG.h"
#include "Battleground.h"
#include "BattlegroundMgr.h"
#include "CellImpl.h"
#include "Channel.h"
#include "ChannelMgr.h"
#include "CharacterDatabaseCleaner.h"
#include "Chat.h"
#include "Common.h"
#include "ConditionMgr.h"
#include "CreatureAI.h"
#include "DatabaseEnv.h"
#include "DisableMgr.h"
#include "Formulas.h"
#include "GameEventMgr.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 "LFGMgr.h"
#include "Language.h"
#include "Log.h"
#include "MapInstanced.h"
#include "MapManager.h"
#include "ObjectAccessor.h"
#include "ObjectMgr.h"
#include "Opcodes.h"
#include "OutdoorPvP.h"
#include "OutdoorPvPMgr.h"
#include "Pet.h"
#include "QuestDef.h"
#include "ReputationMgr.h"
#include "SkillDiscovery.h"
#include "SocialMgr.h"
#include "Spell.h"
#include "SpellAuraEffects.h"
#include "SpellAuras.h"
#include "SpellMgr.h"
#include "Transport.h"
#include "UpdateData.h"
#include "UpdateFieldFlags.h"
#include "UpdateMask.h"
#include "Util.h"
#include "Vehicle.h"
#include "Weather.h"
#include "WeatherMgr.h"
#include "World.h"
#include "WorldPacket.h"
#include "WorldSession.h"
#include "HookMgr.h"
#define ZONE_UPDATE_INTERVAL (1*IN_MILLISECONDS)
#define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
#define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
#define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
#define SKILL_VALUE(x) PAIR32_LOPART(x)
#define SKILL_MAX(x) PAIR32_HIPART(x)
#define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v, m)
#define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
#define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
#define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t, p)
enum CharacterFlags
{
CHARACTER_FLAG_NONE = 0x00000000,
CHARACTER_FLAG_UNK1 = 0x00000001,
CHARACTER_FLAG_UNK2 = 0x00000002,
CHARACTER_LOCKED_FOR_TRANSFER = 0x00000004,
CHARACTER_FLAG_UNK4 = 0x00000008,
CHARACTER_FLAG_UNK5 = 0x00000010,
CHARACTER_FLAG_UNK6 = 0x00000020,
CHARACTER_FLAG_UNK7 = 0x00000040,
CHARACTER_FLAG_UNK8 = 0x00000080,
CHARACTER_FLAG_UNK9 = 0x00000100,
CHARACTER_FLAG_UNK10 = 0x00000200,
CHARACTER_FLAG_HIDE_HELM = 0x00000400,
CHARACTER_FLAG_HIDE_CLOAK = 0x00000800,
CHARACTER_FLAG_UNK13 = 0x00001000,
CHARACTER_FLAG_GHOST = 0x00002000,
CHARACTER_FLAG_RENAME = 0x00004000,
CHARACTER_FLAG_UNK16 = 0x00008000,
CHARACTER_FLAG_UNK17 = 0x00010000,
CHARACTER_FLAG_UNK18 = 0x00020000,
CHARACTER_FLAG_UNK19 = 0x00040000,
CHARACTER_FLAG_UNK20 = 0x00080000,
CHARACTER_FLAG_UNK21 = 0x00100000,
CHARACTER_FLAG_UNK22 = 0x00200000,
CHARACTER_FLAG_UNK23 = 0x00400000,
CHARACTER_FLAG_UNK24 = 0x00800000,
CHARACTER_FLAG_LOCKED_BY_BILLING = 0x01000000,
CHARACTER_FLAG_DECLINED = 0x02000000,
CHARACTER_FLAG_UNK27 = 0x04000000,
CHARACTER_FLAG_UNK28 = 0x08000000,
CHARACTER_FLAG_UNK29 = 0x10000000,
CHARACTER_FLAG_UNK30 = 0x20000000,
CHARACTER_FLAG_UNK31 = 0x40000000,
CHARACTER_FLAG_UNK32 = 0x80000000
};
enum CharacterCustomizeFlags
{
CHAR_CUSTOMIZE_FLAG_NONE = 0x00000000,
CHAR_CUSTOMIZE_FLAG_CUSTOMIZE = 0x00000001, // name, gender, etc...
CHAR_CUSTOMIZE_FLAG_FACTION = 0x00010000, // name, gender, faction, etc...
CHAR_CUSTOMIZE_FLAG_RACE = 0x00100000 // name, gender, race, etc...
};
// corpse reclaim times
#define DEATH_EXPIRE_STEP (5*MINUTE)
#define MAX_DEATH_COUNT 3
static uint32 copseReclaimDelay[MAX_DEATH_COUNT] = { 30, 60, 120 };
// == PlayerTaxi ================================================
PlayerTaxi::PlayerTaxi()
{
memset(m_taximask, 0, sizeof(m_taximask));
}
void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint8 level)
{
// class specific initial known nodes
switch (chrClass)
{
case CLASS_DEATH_KNIGHT:
{
for (uint8 i = 0; i < TaxiMaskSize; ++i)
m_taximask[i] |= sOldContinentsNodesMask[i];
break;
}
}
// race specific initial known nodes: capital and taxi hub masks
switch (race)
{
case RACE_HUMAN: SetTaximaskNode(2); break; // Human
case RACE_ORC: SetTaximaskNode(23); break; // Orc
case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf
case RACE_NIGHTELF: SetTaximaskNode(26);
SetTaximaskNode(27); break; // Night Elf
case RACE_UNDEAD_PLAYER: SetTaximaskNode(11); break;// Undead
case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren
case RACE_GNOME: SetTaximaskNode(6); break; // Gnome
case RACE_TROLL: SetTaximaskNode(23); break; // Troll
case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf
case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei
}
// new continent starting masks (It will be accessible only at new map)
switch (Player::TeamForRace(race))
{
case ALLIANCE: SetTaximaskNode(100); break;
case HORDE: SetTaximaskNode(99); break;
}
// level dependent taxi hubs
if (level >= 68)
SetTaximaskNode(213); //Shattered Sun Staging Area
}
void PlayerTaxi::LoadTaxiMask(std::string const &data)
{
Tokenizer tokens(data, ' ');
uint8 index = 0;
for (Tokenizer::const_iterator iter = tokens.begin(); index < TaxiMaskSize && iter != tokens.end(); ++iter, ++index)
{
// load and set bits only for existing taxi nodes
m_taximask[index] = sTaxiNodesMask[index] & uint32(atol(*iter));
}
}
void PlayerTaxi::AppendTaximaskTo(ByteBuffer& data, bool all)
{
if (all)
{
for (uint8 i = 0; i < TaxiMaskSize; ++i)
data << uint32(sTaxiNodesMask[i]); // all existed nodes
}
else
{
for (uint8 i = 0; i < TaxiMaskSize; ++i)
data << uint32(m_taximask[i]); // known nodes
}
}
bool PlayerTaxi::LoadTaxiDestinationsFromString(const std::string& values, uint32 team)
{
ClearTaxiDestinations();
Tokenizer Tokenizer(values, ' ');
for (Tokenizer::const_iterator iter = Tokenizer.begin(); iter != Tokenizer.end(); ++iter)
{
uint32 node = uint32(atol(*iter));
AddTaxiDestination(node);
}
if (m_TaxiDestinations.empty())
return true;
// Check integrity
if (m_TaxiDestinations.size() < 2)
return false;
for (size_t i = 1; i < m_TaxiDestinations.size(); ++i)
{
uint32 cost;
uint32 path;
sObjectMgr->GetTaxiPath(m_TaxiDestinations[i-1], m_TaxiDestinations[i], path, cost);
if (!path)
return false;
}
// can't load taxi path without mount set (quest taxi path?)
if (!sObjectMgr->GetTaxiMountDisplayId(GetTaxiSource(), team, true))
return false;
return true;
}
std::string PlayerTaxi::SaveTaxiDestinationsToString()
{
if (m_TaxiDestinations.empty())
return "";
std::ostringstream ss;
for (size_t i=0; i < m_TaxiDestinations.size(); ++i)
ss << m_TaxiDestinations[i] << ' ';
return ss.str();
}
uint32 PlayerTaxi::GetCurrentTaxiPath() const
{
if (m_TaxiDestinations.size() < 2)
return 0;
uint32 path;
uint32 cost;
sObjectMgr->GetTaxiPath(m_TaxiDestinations[0], m_TaxiDestinations[1], path, cost);
return path;
}
std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi)
{
for (uint8 i = 0; i < TaxiMaskSize; ++i)
ss << taxi.m_taximask[i] << ' ';
return ss;
}
//== TradeData =================================================
TradeData* TradeData::GetTraderData() const
{
return m_trader->GetTradeData();
}
Item* TradeData::GetItem(TradeSlots slot) const
{
return m_items[slot] ? m_player->GetItemByGuid(m_items[slot]) : NULL;
}
bool TradeData::HasItem(uint64 itemGuid) const
{
for (uint8 i = 0; i < TRADE_SLOT_COUNT; ++i)
if (m_items[i] == itemGuid)
return true;
return false;
}
TradeSlots TradeData::GetTradeSlotForItem(uint64 itemGuid) const
{
for (uint8 i = 0; i < TRADE_SLOT_COUNT; ++i)
if (m_items[i] == itemGuid)
return TradeSlots(i);
return TRADE_SLOT_INVALID;
}
Item* TradeData::GetSpellCastItem() const
{
return m_spellCastItem ? m_player->GetItemByGuid(m_spellCastItem) : NULL;
}
void TradeData::SetItem(TradeSlots slot, Item* item)
{
uint64 itemGuid = item ? item->GetGUID() : 0;
if (m_items[slot] == itemGuid)
return;
m_items[slot] = itemGuid;
SetAccepted(false);
GetTraderData()->SetAccepted(false);
Update();
// need remove possible trader spell applied to changed item
if (slot == TRADE_SLOT_NONTRADED)
GetTraderData()->SetSpell(0);
// need remove possible player spell applied (possible move reagent)
SetSpell(0);
}
void TradeData::SetSpell(uint32 spell_id, Item* castItem /*= NULL*/)
{
uint64 itemGuid = castItem ? castItem->GetGUID() : 0;
if (m_spell == spell_id && m_spellCastItem == itemGuid)
return;
m_spell = spell_id;
m_spellCastItem = itemGuid;
SetAccepted(false);
GetTraderData()->SetAccepted(false);
Update(true); // send spell info to item owner
Update(false); // send spell info to caster self
}
void TradeData::SetMoney(uint32 money)
{
if (m_money == money)
return;
m_money = money;
SetAccepted(false);
GetTraderData()->SetAccepted(false);
Update(true);
}
void TradeData::Update(bool forTarget /*= true*/)
{
if (forTarget)
m_trader->GetSession()->SendUpdateTrade(true); // player state for trader
else
m_player->GetSession()->SendUpdateTrade(false); // player state for player
}
void TradeData::SetAccepted(bool state, bool crosssend /*= false*/)
{
m_accepted = state;
if (!state)
{
if (crosssend)
m_trader->GetSession()->SendTradeStatus(TRADE_STATUS_BACK_TO_TRADE);
else
m_player->GetSession()->SendTradeStatus(TRADE_STATUS_BACK_TO_TRADE);
}
}
// == KillRewarder ====================================================
// KillRewarder incapsulates logic of rewarding player upon kill with:
// * XP;
// * honor;
// * reputation;
// * kill credit (for quest objectives).
// Rewarding is initiated in two cases: when player kills unit in Unit::Kill()
// and on battlegrounds in Battleground::RewardXPAtKill().
//
// Rewarding algorithm is:
// 1. Initialize internal variables to default values.
// 2. In case when player is in group, initialize variables necessary for group calculations:
// 2.1. _count - number of alive group members within reward distance;
// 2.2. _sumLevel - sum of levels of alive group members within reward distance;
// 2.3. _maxLevel - maximum level of alive group member within reward distance;
// 2.4. _maxNotGrayMember - maximum level of alive group member within reward distance,
// for whom victim is not gray;
// 2.5. _isFullXP - flag identifying that for all group members victim is not gray,
// so 100% XP will be rewarded (50% otherwise).
// 3. Reward killer (and group, if necessary).
// 3.1. If killer is in group, reward group.
// 3.1.1. Initialize initial XP amount based on maximum level of group member,
// for whom victim is not gray.
// 3.1.2. Alter group rate if group is in raid (not for battlegrounds).
// 3.1.3. Reward each group member (even dead) within reward distance (see 4. for more details).
// 3.2. Reward single killer (not group case).
// 3.2.1. Initialize initial XP amount based on killer's level.
// 3.2.2. Reward killer (see 4. for more details).
// 4. Reward player.
// 4.1. Give honor (player must be alive and not on BG).
// 4.2. Give XP.
// 4.2.1. If player is in group, adjust XP:
// * set to 0 if player's level is more than maximum level of not gray member;
// * cut XP in half if _isFullXP is false.
// 4.2.2. Apply auras modifying rewarded XP.
// 4.2.3. Give XP to player.
// 4.2.4. If player has pet, reward pet with XP (100% for single player, 50% for group case).
// 4.3. Give reputation (player must not be on BG).
// 4.4. Give kill credit (player must not be in group, or he must be alive or without corpse).
// 5. Credit instance encounter.
KillRewarder::KillRewarder(Player* killer, Unit* victim, bool isBattleGround) :
// 1. Initialize internal variables to default values.
_killer(killer), _victim(victim), _group(killer->GetGroup()),
_groupRate(1.0f), _maxNotGrayMember(NULL), _count(0), _sumLevel(0), _xp(0),
_isFullXP(false), _maxLevel(0), _isBattleGround(isBattleGround), _isPvP(false)
{
// mark the credit as pvp if victim is player
if (victim->GetTypeId() == TYPEID_PLAYER)
_isPvP = true;
// or if its owned by player and its not a vehicle
else if (IS_PLAYER_GUID(victim->GetCharmerOrOwnerGUID()))
_isPvP = !victim->IsVehicle();
_InitGroupData();
}
inline void KillRewarder::_InitGroupData()
{
if (_group)
{
// 2. In case when player is in group, initialize variables necessary for group calculations:
for (GroupReference* itr = _group->GetFirstMember(); itr != NULL; itr = itr->next())
if (Player* member = itr->GetSource())
if (member->IsAlive() && member->IsAtGroupRewardDistance(_victim))
{
const uint8 lvl = member->getLevel();
// 2.1. _count - number of alive group members within reward distance;
++_count;
// 2.2. _sumLevel - sum of levels of alive group members within reward distance;
_sumLevel += lvl;
// 2.3. _maxLevel - maximum level of alive group member within reward distance;
if (_maxLevel < lvl)
_maxLevel = lvl;
// 2.4. _maxNotGrayMember - maximum level of alive group member within reward distance,
// for whom victim is not gray;
uint32 grayLevel = Trinity::XP::GetGrayLevel(lvl);
if (_victim->getLevel() > grayLevel && (!_maxNotGrayMember || _maxNotGrayMember->getLevel() < lvl))
_maxNotGrayMember = member;
}
// 2.5. _isFullXP - flag identifying that for all group members victim is not gray,
// so 100% XP will be rewarded (50% otherwise).
_isFullXP = _maxNotGrayMember && (_maxLevel == _maxNotGrayMember->getLevel());
}
else
_count = 1;
}
inline void KillRewarder::_InitXP(Player* player)
{
// Get initial value of XP for kill.
// XP is given:
// * on battlegrounds;
// * otherwise, not in PvP;
// * not if killer is on vehicle.
if (_isBattleGround || (!_isPvP && !_killer->GetVehicle()))
_xp = Trinity::XP::Gain(player, _victim);
}
inline void KillRewarder::_RewardHonor(Player* player)
{
// Rewarded player must be alive.
if (player->IsAlive())
player->RewardHonor(_victim, _count, -1, true);
}
inline void KillRewarder::_RewardXP(Player* player, float rate)
{
uint32 xp(_xp);
if (_group)
{
// 4.2.1. If player is in group, adjust XP:
// * set to 0 if player's level is more than maximum level of not gray member;
// * cut XP in half if _isFullXP is false.
if (_maxNotGrayMember && player->IsAlive() &&
_maxNotGrayMember->getLevel() >= player->getLevel())
xp = _isFullXP ?
uint32(xp * rate) : // Reward FULL XP if all group members are not gray.
uint32(xp * rate / 2) + 1; // Reward only HALF of XP if some of group members are gray.
else
xp = 0;
}
if (xp)
{
// 4.2.2. Apply auras modifying rewarded XP (SPELL_AURA_MOD_XP_PCT).
Unit::AuraEffectList const& auras = player->GetAuraEffectsByType(SPELL_AURA_MOD_XP_PCT);
for (Unit::AuraEffectList::const_iterator i = auras.begin(); i != auras.end(); ++i)
AddPct(xp, (*i)->GetAmount());
// 4.2.3. Give XP to player.
player->GiveXP(xp, _victim, _groupRate);
if (Pet* pet = player->GetPet())
// 4.2.4. If player has pet, reward pet with XP (100% for single player, 50% for group case).
pet->GivePetXP(_group ? xp / 2 : xp);
}
}
inline void KillRewarder::_RewardReputation(Player* player, float rate)
{
// 4.3. Give reputation (player must not be on BG).
// Even dead players and corpses are rewarded.
player->RewardReputation(_victim, rate);
}
inline void KillRewarder::_RewardKillCredit(Player* player)
{
// 4.4. Give kill credit (player must not be in group, or he must be alive or without corpse).
if (!_group || player->IsAlive() || !player->GetCorpse())
if (_victim->GetTypeId() == TYPEID_UNIT)
player->KilledMonster(_victim->ToCreature()->GetCreatureTemplate(), _victim->GetGUID());
}
void KillRewarder::_RewardPlayer(Player* player, bool isDungeon)
{
// 4. Reward player.
if (!_isBattleGround)
{
// 4.1. Give honor (player must be alive and not on BG).
_RewardHonor(player);
// 4.1.1 Send player killcredit for quests with PlayerSlain
if (_victim->GetTypeId() == TYPEID_PLAYER)
player->KilledPlayerCredit();
}
// Give XP only in PvE or in battlegrounds.
// Give reputation and kill credit only in PvE.
if (!_isPvP || _isBattleGround)
{
const float rate = _group ?
_groupRate * float(player->getLevel()) / _sumLevel : // Group rate depends on summary level.
1.0f; // Personal rate is 100%.
if (_xp)
// 4.2. Give XP.
_RewardXP(player, rate);
if (!_isBattleGround)
{
// If killer is in dungeon then all members receive full reputation at kill.
_RewardReputation(player, isDungeon ? 1.0f : rate);
_RewardKillCredit(player);
}
}
}
void KillRewarder::_RewardGroup()
{
if (_maxLevel)
{
if (_maxNotGrayMember)
// 3.1.1. Initialize initial XP amount based on maximum level of group member,
// for whom victim is not gray.
_InitXP(_maxNotGrayMember);
// To avoid unnecessary calculations and calls,
// proceed only if XP is not ZERO or player is not on battleground
// (battleground rewards only XP, that's why).
if (!_isBattleGround || _xp)
{
const bool isDungeon = !_isPvP && sMapStore.LookupEntry(_killer->GetMapId())->IsDungeon();
if (!_isBattleGround)
{
// 3.1.2. Alter group rate if group is in raid (not for battlegrounds).
const bool isRaid = !_isPvP && sMapStore.LookupEntry(_killer->GetMapId())->IsRaid() && _group->isRaidGroup();
_groupRate = Trinity::XP::xp_in_group_rate(_count, isRaid);
}
// 3.1.3. Reward each group member (even dead or corpse) within reward distance.
for (GroupReference* itr = _group->GetFirstMember(); itr != NULL; itr = itr->next())
{
if (Player* member = itr->GetSource())
{
if (member->IsAtGroupRewardDistance(_victim))
{
_RewardPlayer(member, isDungeon);
member->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL, 1, 0, _victim);
}
}
}
}
}
}
void KillRewarder::Reward()
{
// 3. Reward killer (and group, if necessary).
if (_group)
// 3.1. If killer is in group, reward group.
_RewardGroup();
else
{
// 3.2. Reward single killer (not group case).
// 3.2.1. Initialize initial XP amount based on killer's level.
_InitXP(_killer);
// To avoid unnecessary calculations and calls,
// proceed only if XP is not ZERO or player is not on battleground
// (battleground rewards only XP, that's why).
if (!_isBattleGround || _xp)
// 3.2.2. Reward killer.
_RewardPlayer(_killer, false);
}
// 5. Credit instance encounter.
if (Creature* victim = _victim->ToCreature())
if (victim->IsDungeonBoss())
if (InstanceScript* instance = _victim->GetInstanceScript())
instance->UpdateEncounterState(ENCOUNTER_CREDIT_KILL_CREATURE, _victim->GetEntry(), _victim);
}
// == Player ====================================================
// we can disable this warning for this since it only
// causes undefined behavior when passed to the base class constructor
#ifdef _MSC_VER
#pragma warning(disable:4355)
#endif
Player::Player(WorldSession* session): Unit(true)
{
#ifdef _MSC_VER
#pragma warning(default:4355)
#endif
m_speakTime = 0;
m_speakCount = 0;
m_objectType |= TYPEMASK_PLAYER;
m_objectTypeId = TYPEID_PLAYER;
m_valuesCount = PLAYER_END;
m_session = session;
m_divider = 0;
m_ExtraFlags = 0;
m_spellModTakingSpell = NULL;
//m_pad = 0;
// players always accept
if (!GetSession()->HasPermission(RBAC_PERM_CAN_FILTER_WHISPERS))
SetAcceptWhispers(true);
m_curSelection = 0;
m_lootGuid = 0;
m_comboTarget = 0;
m_comboPoints = 0;
m_usedTalentCount = 0;
m_questRewardTalentCount = 0;
m_regenTimer = 0;
m_regenTimerCount = 0;
m_weaponChangeTimer = 0;
m_zoneUpdateId = 0;
m_zoneUpdateTimer = 0;
m_areaUpdateId = 0;
m_nextSave = sWorld->getIntConfig(CONFIG_INTERVAL_SAVE);
clearResurrectRequestData();
memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT);
m_social = NULL;
// group is initialized in the reference constructor
SetGroupInvite(NULL);
m_groupUpdateMask = 0;
m_auraRaidUpdateMask = 0;
m_bPassOnGroupLoot = false;
duel = NULL;
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 = NULL;
m_cinematic = 0;
PlayerTalkClass = new PlayerMenu(GetSession());
m_currentBuybackSlot = BUYBACK_SLOT_START;
m_DailyQuestChanged = false;
m_lastDailyQuestTime = 0;
for (uint8 i=0; i < MAX_TIMERS; i++)
m_MirrorTimer[i] = DISABLED_MIRROR_TIMER;
m_MirrorTimerFlags = UNDERWATER_NONE;
m_MirrorTimerFlagsLast = UNDERWATER_NONE;
m_isInWater = false;
m_drunkTimer = 0;
m_restTime = 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 = time(NULL);
m_Last_tick = m_logintime;
m_WeaponProficiency = 0;
m_ArmorProficiency = 0;
m_canParry = false;
m_canBlock = false;
m_canDualWield = false;
m_canTitanGrip = false;
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/////////////////////
time_inn_enter=0;
inn_pos_mapid=0;
inn_pos_x=0;
inn_pos_y=0;
inn_pos_z=0;
m_rest_bonus=0;
rest_type=REST_TYPE_NO;
////////////////////Rest System/////////////////////
m_mailsLoaded = false;
m_mailsUpdated = false;
unReadMails = 0;
m_nextMailDelivereTime = 0;
m_resetTalentsCost = 0;
m_resetTalentsTime = 0;
m_itemUpdateQueueBlocked = false;
for (uint8 i = 0; i < MAX_MOVE_TYPE; ++i)
m_forced_speed_changes[i] = 0;
m_stableSlots = 0;
/////////////////// Instance System /////////////////////
m_HomebindTimer = 0;
m_InstanceValid = true;
m_dungeonDifficulty = DUNGEON_DIFFICULTY_NORMAL;
m_raidDifficulty = RAID_DIFFICULTY_10MAN_NORMAL;
m_lastPotionId = 0;
m_activeSpec = 0;
m_specsCount = 1;
for (uint8 i = 0; i < MAX_TALENT_SPECS; ++i)
{
for (uint8 g = 0; g < MAX_GLYPH_SLOT_INDEX; ++g)
m_Glyphs[i][g] = 0;
m_talents[i] = new PlayerTalentMap();
}
for (uint8 i = 0; i < BASEMOD_END; ++i)
{
m_auraBaseMod[i][FLAT_MOD] = 0.0f;
m_auraBaseMod[i][PCT_MOD] = 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 = time(NULL);
m_IsBGRandomWinner = false;
// Player summoning
m_summon_expire = 0;
m_summon_mapid = 0;
m_summon_x = 0.0f;
m_summon_y = 0.0f;
m_summon_z = 0.0f;
m_mover = this;
m_movedPlayer = this;
m_seer = this;
m_contestedPvPTimer = 0;
m_declinedname = NULL;
m_isActive = true;
m_runes = NULL;
m_lastFallTime = 0;
m_lastFallZ = 0;
m_grantableLevels = 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_SeasonalQuestChanged = false;
SetPendingBind(0, 0);
_activeCheats = CHEAT_NONE;
m_achievementMgr = new AchievementMgr(this);
m_reputationMgr = new ReputationMgr(this);
}
Player::~Player()
{
// it must be unloaded already in PlayerLogout and accessed only for loggined player
//m_social = NULL;
// 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];
for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
delete itr->second;
for (uint8 i = 0; i < MAX_TALENT_SPECS; ++i)
{
for (PlayerTalentMap::const_iterator itr = m_talents[i]->begin(); itr != m_talents[i]->end(); ++itr)
delete itr->second;
delete m_talents[i];
}
//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;
sWorld->DecreasePlayerCount();
}
void Player::CleanupsBeforeDelete(bool finalCleanup)
{
TradeCancel(false);
DuelComplete(DUEL_INTERRUPTED);
Unit::CleanupsBeforeDelete(finalCleanup);
if (m_transport)
m_transport->RemovePassenger(this);
// 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(uint32 guidlow, CharacterCreateInfo* createInfo)
{
//FIXME: outfitId not used in player creating
/// @todo need more checks against packet modifications
// should check that skin, face, hair* are valid via DBC per race/class
// also do it in Player::BuildEnumData, Player::LoadFromDB
Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
m_name = createInfo->Name;
PlayerInfo const* info = sObjectMgr->GetPlayerInfo(createInfo->Race, createInfo->Class);
if (!info)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player::Create: Possible hacking-attempt: Account %u tried creating a character named '%s' with an invalid race/class pair (%u/%u) - refusing to do so.",
GetSession()->GetAccountId(), m_name.c_str(), createInfo->Race, createInfo->Class);
return false;
}
for (uint8 i = 0; i < PLAYER_SLOTS_COUNT; i++)
m_items[i] = NULL;
Relocate(info->positionX, info->positionY, info->positionZ, info->orientation);
ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(createInfo->Class);
if (!cEntry)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player::Create: Possible hacking-attempt: Account %u tried creating a character named '%s' with an invalid character class (%u) - refusing to do so (wrong DBC-files?)",
GetSession()->GetAccountId(), m_name.c_str(), createInfo->Class);
return false;
}
SetMap(sMapMgr->CreateMap(info->mapId, this));
uint8 powertype = cEntry->powerType;
SetObjectScale(1.0f);
setFactionForRace(createInfo->Race);
if (!IsValidGender(createInfo->Gender))
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player::Create: Possible hacking-attempt: Account %u tried creating a character named '%s' with an invalid gender (%hu) - refusing to do so",
GetSession()->GetAccountId(), m_name.c_str(), createInfo->Gender);
return false;
}
uint32 RaceClassGender = (createInfo->Race) | (createInfo->Class << 8) | (createInfo->Gender << 16);
SetUInt32Value(UNIT_FIELD_BYTES_0, (RaceClassGender | (powertype << 24)));
InitDisplayIds();
if (sWorld->getIntConfig(CONFIG_GAME_TYPE) == REALM_TYPE_PVP || sWorld->getIntConfig(CONFIG_GAME_TYPE) == REALM_TYPE_RPPVP)
{
SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP);
SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
}
SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3
SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1)); // -1 is default value
SetUInt32Value(PLAYER_BYTES, (createInfo->Skin | (createInfo->Face << 8) | (createInfo->HairStyle << 16) | (createInfo->HairColor << 24)));
SetUInt32Value(PLAYER_BYTES_2, (createInfo->FacialHair |
(0x00 << 8) |
(0x00 << 16) |
(((GetSession()->IsARecruiter() || GetSession()->GetRecruiterId() != 0) ? REST_STATE_RAF_LINKED : REST_STATE_NOT_RAF_LINKED) << 24)));
SetByteValue(PLAYER_BYTES_3, 0, createInfo->Gender);
SetByteValue(PLAYER_BYTES_3, 3, 0); // BattlefieldArenaFaction (0 or 1)
SetUInt32Value(PLAYER_GUILDID, 0);
SetUInt32Value(PLAYER_GUILDRANK, 0);
SetUInt32Value(PLAYER_GUILD_TIMESTAMP, 0);
for (int i = 0; i < KNOWN_TITLES_SIZE; ++i)
SetUInt64Value(PLAYER__FIELD_KNOWN_TITLES + i, 0); // 0=disabled
SetUInt32Value(PLAYER_CHOSEN_TITLE, 0);
SetUInt32Value(PLAYER_FIELD_KILLS, 0);
SetUInt32Value(PLAYER_FIELD_LIFETIME_HONORABLE_KILLS, 0);
SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
// set starting level
uint32 start_level = getClass() != CLASS_DEATH_KNIGHT
? sWorld->getIntConfig(CONFIG_START_PLAYER_LEVEL)
: sWorld->getIntConfig(CONFIG_START_HEROIC_PLAYER_LEVEL);
if (m_session->HasPermission(RBAC_PERM_USE_START_GM_LEVEL))
{
uint32 gm_level = sWorld->getIntConfig(CONFIG_START_GM_LEVEL);
if (gm_level > start_level)
start_level = gm_level;
}
SetUInt32Value(UNIT_FIELD_LEVEL, start_level);
InitRunes();
SetUInt32Value(PLAYER_FIELD_COINAGE, sWorld->getIntConfig(CONFIG_START_PLAYER_MONEY));
SetHonorPoints(sWorld->getIntConfig(CONFIG_START_HONOR_POINTS));
SetArenaPoints(sWorld->getIntConfig(CONFIG_START_ARENA_POINTS));
// start with every map explored
if (sWorld->getBoolConfig(CONFIG_START_ALL_EXPLORED))
{
for (uint8 i=0; i<PLAYER_EXPLORED_ZONES_SIZE; i++)
SetFlag(PLAYER_EXPLORED_ZONES_1+i, 0xFFFFFFFF);
}
//Reputations if "StartAllReputation" is enabled, -- @todo Fix this in a better way
if (sWorld->getBoolConfig(CONFIG_START_ALL_REP))
{
GetReputationMgr().SetReputation(sFactionStore.LookupEntry(942), 42999);
GetReputationMgr().SetReputation(sFactionStore.LookupEntry(935), 42999);
GetReputationMgr().SetReputation(sFactionStore.LookupEntry(936), 42999);
GetReputationMgr().SetReputation(sFactionStore.LookupEntry(1011), 42999);
GetReputationMgr().SetReputation(sFactionStore.LookupEntry(970), 42999);
GetReputationMgr().SetReputation(sFactionStore.LookupEntry(967), 42999);
GetReputationMgr().SetReputation(sFactionStore.LookupEntry(989), 42999);
GetReputationMgr().SetReputation(sFactionStore.LookupEntry(932), 42999);
GetReputationMgr().SetReputation(sFactionStore.LookupEntry(934), 42999);
GetReputationMgr().SetReputation(sFactionStore.LookupEntry(1038), 42999);
GetReputationMgr().SetReputation(sFactionStore.LookupEntry(1077), 42999);
// Factions depending on team, like cities and some more stuff
switch (GetTeam())
{
case ALLIANCE:
GetReputationMgr().SetReputation(sFactionStore.LookupEntry(72), 42999);
GetReputationMgr().SetReputation(sFactionStore.LookupEntry(47), 42999);
GetReputationMgr().SetReputation(sFactionStore.LookupEntry(69), 42999);
GetReputationMgr().SetReputation(sFactionStore.LookupEntry(930), 42999);
GetReputationMgr().SetReputation(sFactionStore.LookupEntry(730), 42999);
GetReputationMgr().SetReputation(sFactionStore.LookupEntry(978), 42999);
GetReputationMgr().SetReputation(sFactionStore.LookupEntry(54), 42999);
GetReputationMgr().SetReputation(sFactionStore.LookupEntry(946), 42999);
break;
case HORDE:
GetReputationMgr().SetReputation(sFactionStore.LookupEntry(76), 42999);
GetReputationMgr().SetReputation(sFactionStore.LookupEntry(68), 42999);
GetReputationMgr().SetReputation(sFactionStore.LookupEntry(81), 42999);
GetReputationMgr().SetReputation(sFactionStore.LookupEntry(911), 42999);
GetReputationMgr().SetReputation(sFactionStore.LookupEntry(729), 42999);
GetReputationMgr().SetReputation(sFactionStore.LookupEntry(941), 42999);
GetReputationMgr().SetReputation(sFactionStore.LookupEntry(530), 42999);
GetReputationMgr().SetReputation(sFactionStore.LookupEntry(947), 42999);
break;
default:
break;
}
}
// Played time
m_Last_tick = time(NULL);
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();
if (getPowerType() == POWER_MANA)
{
UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
}
if (getPowerType() == POWER_RUNIC_POWER)
{
SetPower(POWER_RUNE, 8);
SetMaxPower(POWER_RUNE, 8);
SetPower(POWER_RUNIC_POWER, 0);
SetMaxPower(POWER_RUNIC_POWER, 1000);
}
// original spells
learnDefaultSpells();
// 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)
{
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);
pItem = 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
return true;
}
bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
{
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "STORAGE: Creating initial item, itemId = %u, count = %u", 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;
Item* item = 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, Item::GenerateItemRandomPropertyId(titem_id));
return true; // stored
}
// item can't be added
TC_LOG_ERROR(LOG_FILTER_PLAYER_ITEMS, "STORAGE: Can't equip or store initial item %u for race %u class %u, error msg = %u", 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;
}
WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
data << (uint32)Type;
data << CurrentValue;
data << MaxValue;
data << Regen;
data << (uint8)0;
data << (uint32)0; // spell id
GetSession()->SendPacket(&data);
}
void Player::StopMirrorTimer(MirrorTimerType Type)
{
m_MirrorTimer[Type] = DISABLED_MIRROR_TIMER;
WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
data << (uint32)Type;
GetSession()->SendPacket(&data);
}
bool Player::IsImmuneToEnvironmentalDamage()
{
// 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;
if (type == DAMAGE_LAVA)
CalcAbsorbResist(this, SPELL_SCHOOL_MASK_FIRE, DIRECT_DAMAGE, damage, &absorb, &resist);
else if (type == DAMAGE_SLIME)
CalcAbsorbResist(this, SPELL_SCHOOL_MASK_NATURE, DIRECT_DAMAGE, damage, &absorb, &resist);
damage -= absorb + resist;
DealDamageMods(this, damage, &absorb);
WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
data << uint64(GetGUID());
data << uint8(type != DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
data << uint32(damage);
data << uint32(absorb);
data << uint32(resist);
SendMessageToSet(&data, true);
uint32 final_damage = DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
if (!IsAlive())
{
if (type == DAMAGE_FALL) // DealDamage not apply item durability loss at self damage
{
TC_LOG_DEBUG(LOG_FILTER_PLAYER, "We are fall to death, loosing 10 percents durability");
DurabilityLossAll(0.10f, false);
// durability lost message
WorldPacket data2(SMSG_DURABILITY_DAMAGE_DEATH, 0);
GetSession()->SendPacket(&data2);
}
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM, 1, type);
}
return final_damage;
}
int32 Player::getMaxTimer(MirrorTimerType timer)
{
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;
AuraEffectList const& mModWaterBreathing = GetAuraEffectsByType(SPELL_AURA_MOD_WATER_BREATHING);
for (AuraEffectList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
AddPct(UnderWaterTime, (*i)->GetAmount());
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)
{
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 & UNDERWARER_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 & UNDERWARER_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 & UNDERWARER_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);
}
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*/)
{
bool isSobering = newDrunkValue < GetDrunkValue();
uint32 oldDrunkenState = Player::GetDrunkenstateByValue(GetDrunkValue());
if (newDrunkValue > 100)
newDrunkValue = 100;
// select drunk percent or total SPELL_AURA_MOD_FAKE_INEBRIATE amount, whichever is higher for visibility updates
int32 drunkPercent = std::max<int32>(newDrunkValue, GetTotalAuraModifier(SPELL_AURA_MOD_FAKE_INEBRIATE));
if (drunkPercent)
{
m_invisibilityDetect.AddFlag(INVISIBILITY_DRUNK);
m_invisibilityDetect.SetValue(INVISIBILITY_DRUNK, drunkPercent);
}
else if (!HasAuraType(SPELL_AURA_MOD_FAKE_INEBRIATE) && !newDrunkValue)
m_invisibilityDetect.DelFlag(INVISIBILITY_DRUNK);
uint32 newDrunkenState = Player::GetDrunkenstateByValue(newDrunkValue);
SetByteValue(PLAYER_BYTES_3, 1, newDrunkValue);
UpdateObjectVisibility();
if (!isSobering)
m_drunkTimer = 0; // reset sobering timer
if (newDrunkenState == oldDrunkenState)
return;
WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
data << uint64(GetGUID());
data << uint32(newDrunkenState);
data << uint32(itemId);
SendMessageToSet(&data, true);
}
void Player::Update(uint32 p_time)
{
if (!IsInWorld())
return;
// undelivered mail
if (m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
{
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;
}
// If this is set during update SetSpellModTakingSpell call is missing somewhere in the code
// Having this would prevent more aura charges to be dropped, so let's crash
//ASSERT (!m_spellModTakingSpell);
if (m_spellModTakingSpell)
{
//TC_LOG_FATAL(LOG_FILTER_PLAYER, "Player has m_pad %u during update!", m_pad);
//if (m_spellModTakingSpell)
TC_LOG_FATAL(LOG_FILTER_SPELLS_AURAS, "Player has m_spellModTakingSpell %u during update!", m_spellModTakingSpell->m_spellInfo->Id);
m_spellModTakingSpell = NULL;
}
//used to implement delayed far teleports
SetCanDelayTeleport(true);
Unit::Update(p_time);
SetCanDelayTeleport(false);
time_t now = time(NULL);
UpdatePvPFlag(now);
UpdateContestedPvP(p_time);
UpdateDuelFlag(now);
CheckDuelDistance(now);
UpdateAfkReport(now);
if (IsCharmed())
if (Unit* charmer = GetCharmer())
if (charmer->GetTypeId() == TYPEID_UNIT && charmer->IsAlive())
UpdateCharmedAI();
// Update items that have just a limited lifetime
if (now > m_Last_tick)
UpdateItemDuration(uint32(now - m_Last_tick));
// check every second
if (now > m_Last_tick + 1)
UpdateSoulboundTradeItems();
// If mute expired, remove it from the DB
if (GetSession()->m_muteTime && GetSession()->m_muteTime < now)
{
GetSession()->m_muteTime = 0;
PreparedStatement* 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] = true;
++iter;
}
}
}
m_achievementMgr->UpdateTimedAchievements(p_time);
if (HasUnitState(UNIT_STATE_MELEE_ATTACKING) && !HasUnitState(UNIT_STATE_CASTING))
{
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*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*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) && GetTimeInnEnter() > 0) // freeze update
{
time_t time_inn = time(NULL)-GetTimeInnEnter();
if (time_inn >= 10) // freeze update
{
float bubble = 0.125f*sWorld->getRate(RATE_REST_INGAME);
// speed collect rest bonus (section/in hour)
SetRestBonus(GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
UpdateInnerTime(time(NULL));
}
}
}
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)
{
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 (m_timeSyncTimer > 0)
{
if (p_time >= m_timeSyncTimer)
SendTimeSync();
else
m_timeSyncTimer -= 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
sScriptMgr->OnPlayerSave(this);
SaveToDB();
TC_LOG_DEBUG(LOG_FILTER_PLAYER, "Player '%s' (GUID: %u) saved", GetName().c_str(), GetGUIDLow());
}
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
if (m_deathTimer > 0 && !GetBaseMap()->Instanceable() && !HasAuraType(SPELL_AURA_PREVENT_RESURRECTION))
{
if (p_time >= m_deathTimer)
{
m_deathTimer = 0;
BuildPlayerRepop();
RepopAtGraveyard();
}
else
m_deathTimer -= p_time;
}
UpdateEnchantTime(p_time);
UpdateHomebindTime(p_time);
if (!_instanceResetTimes.empty())
{
for (InstanceTimeMap::iterator itr = _instanceResetTimes.begin(); itr != _instanceResetTimes.end();)
{
if (itr->second < now)
_instanceResetTimes.erase(itr++);
else
++itr;
}
}
// group update
SendUpdateToOutOfRangeGroupMembers();
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);
//we should execute delayed teleports only for alive(!) players
//because we don't want player's ghost teleported from graveyard
if (IsHasDelayedTeleport() && IsAlive())
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(LOG_FILTER_PLAYER, "setDeathState: attempt to kill a dead player %s(%d)", GetName().c_str(), GetGUIDLow());
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 HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
RemovePet(NULL, 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);
ResetAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE, ACHIEVEMENT_CRITERIA_CONDITION_NO_DEATH);
ResetAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL, ACHIEVEMENT_CRITERIA_CONDITION_NO_DEATH);
ResetAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS, ACHIEVEMENT_CRITERIA_CONDITION_NO_DEATH);
}
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);
}
void Player::InnEnter(time_t time, uint32 mapid, float x, float y, float z)
{
inn_pos_mapid = mapid;
inn_pos_x = x;
inn_pos_y = y;
inn_pos_z = z;
time_inn_enter = time;
}
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.playerBytes, characters.playerBytes2, characters.level, "
// 8 9 10 11 12 13 14
// "characters.zone, characters.map, characters.position_x, characters.position_y, characters.position_z, guild_member.guildid, characters.playerFlags, "
// 15 16 17 18 19 20 21
// "characters.at_login, character_pet.entry, character_pet.modelid, character_pet.level, characters.data, character_banned.guid, character_declinedname.genitive "
Field* fields = result->Fetch();
uint32 guid = fields[0].GetUInt32();
uint8 plrRace = fields[2].GetUInt8();
uint8 plrClass = fields[3].GetUInt8();
uint8 gender = fields[4].GetUInt8();
PlayerInfo const* info = sObjectMgr->GetPlayerInfo(plrRace, plrClass);
if (!info)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER_LOADING, "Player %u has incorrect race/class pair. Don't build enum.", guid);
return false;
}
else if (!IsValidGender(gender))
{
TC_LOG_ERROR(LOG_FILTER_PLAYER_LOADING, "Player (%u) has incorrect gender (%hu), don't build enum.", guid, gender);
return false;
}
*data << uint64(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
*data << fields[1].GetString(); // name
*data << uint8(plrRace); // race
*data << uint8(plrClass); // class
*data << uint8(gender); // gender
uint32 playerBytes = fields[5].GetUInt32();
*data << uint8(playerBytes); // skin
*data << uint8(playerBytes >> 8); // face
*data << uint8(playerBytes >> 16); // hair style
*data << uint8(playerBytes >> 24); // hair color
uint32 playerBytes2 = fields[6].GetUInt32();
*data << uint8(playerBytes2 & 0xFF); // facial hair
*data << uint8(fields[7].GetUInt8()); // level
*data << uint32(fields[8].GetUInt16()); // zone
*data << uint32(fields[9].GetUInt16()); // map
*data << fields[10].GetFloat(); // x
*data << fields[11].GetFloat(); // y
*data << fields[12].GetFloat(); // z
*data << uint32(fields[13].GetUInt32()); // guild id
uint32 charFlags = 0;
uint32 playerFlags = fields[14].GetUInt32();
uint16 atLoginFlags = fields[15].GetUInt16();
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[20].GetUInt32())
charFlags |= CHARACTER_FLAG_LOCKED_BY_BILLING;
if (sWorld->getBoolConfig(CONFIG_DECLINED_NAMES_USED))
{
if (!fields[21].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;
uint32 petFamily = 0;
// show pet at selection character in character list only for non-ghost character
if (result && !(playerFlags & PLAYER_FLAGS_GHOST) && (plrClass == CLASS_WARLOCK || plrClass == CLASS_HUNTER || plrClass == CLASS_DEATH_KNIGHT))
{
uint32 entry = fields[16].GetUInt32();
CreatureTemplate const* creatureInfo = sObjectMgr->GetCreatureTemplate(entry);
if (creatureInfo)
{
petDisplayId = fields[17].GetUInt32();
petLevel = fields[18].GetUInt16();
petFamily = creatureInfo->family;
}
}
*data << uint32(petDisplayId);
*data << uint32(petLevel);
*data << uint32(petFamily);
Tokenizer equipment(fields[19].GetString(), ' ');
for (uint8 slot = 0; slot < INVENTORY_SLOT_BAG_END; ++slot)
{
uint32 visualBase = slot * 2;
uint32 itemId = GetUInt32ValueFromArray(equipment, visualBase);
ItemTemplate const* proto = sObjectMgr->GetItemTemplate(itemId);
if (!proto)
{
*data << uint32(0);
*data << uint8(0);
*data << uint32(0);
continue;
}
SpellItemEnchantmentEntry const* enchant = NULL;
uint32 enchants = GetUInt32ValueFromArray(equipment, visualBase + 1);
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->aura_id : 0);
}
return true;
}
void Player::ToggleAFK()
{
ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
// afk player not allowed in battleground
if (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 (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DEVELOPER))
tag |= CHAT_TAG_DEV;
return tag;
}
void Player::SendTeleportAckPacket()
{
WorldPacket data(MSG_MOVE_TELEPORT_ACK, 41);
data.append(GetPackGUID());
data << uint32(0); // this value increments every time
BuildMovementPacket(&data);
GetSession()->SendPacket(&data);
}
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(LOG_FILTER_MAPS, "TeleportTo: invalid map (%d) or invalid coordinates (X: %f, Y: %f, Z: %f, O: %f) given when teleporting player (GUID: %u, name: %s, map: %d, X: %f, Y: %f, Z: %f, O: %f).",
mapid, x, y, z, orientation, GetGUIDLow(), GetName().c_str(), GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
return false;
}
if (!GetSession()->HasPermission(RBAC_PERM_SKIP_CHECK_DISABLE_MAP) && DisableMgr::IsDisabledFor(DISABLE_TYPE_MAP, mapid, this))
{
TC_LOG_ERROR(LOG_FILTER_MAPS, "Player (GUID: %u, name: %s) tried to enter a forbidden map %u", GetGUIDLow(), GetName().c_str(), 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(LOG_FILTER_MAPS, "Player %s using client without required expansion tried teleport to non accessible map %u", GetName().c_str(), mapid);
if (GetTransport())
{
m_transport->RemovePassenger(this);
m_transport = NULL;
m_movementInfo.transport.Reset();
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(LOG_FILTER_MAPS, "Player %s is being teleported to map %u", GetName().c_str(), 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();
if (m_transport)
{
if (options & TELE_TO_NOT_LEAVE_TRANSPORT)
AddUnitMovementFlag(MOVEMENTFLAG_ONTRANSPORT);
else
{
m_transport->RemovePassenger(this);
m_transport = NULL;
m_movementInfo.transport.Reset();
}
}
// 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(GetUInt64Value(PLAYER_DUEL_ARBITER)))
DuelComplete(DUEL_FLED);
if (GetMapId() == mapid)
{
//lets reset far teleport flag if it wasn't reset during chained teleports
SetSemaphoreTeleportFar(false);
//setup delayed teleport flag
SetDelayedTeleportFlag(IsCanDelayTeleport());
//if teleport spell is casted 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 (!(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, z);
// 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())
{
Position oldPos;
GetPosition(&oldPos);
Relocate(x, y, z, orientation);
SendTeleportAckPacket();
SendTeleportPacket(oldPos); // this automatically relocates to oldPos in order to broadcast the packet in the right place
}
}
else
{
if (getClass() == CLASS_DEATH_KNIGHT && GetMapId() == 609 && !IsGameMaster() && !HasSpell(50977))
return false;
// far teleport to another map
Map* oldmap = IsInWorld() ? GetMap() : NULL;
// 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->CanPlayerEnter(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 casted 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(0);
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())
{
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 (IsNonMeleeSpellCasted(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 (m_transport)
data << m_transport->GetEntry() << GetMapId();
GetSession()->SendPacket(&data);
}
// remove from old map now
if (oldmap)
oldmap->RemovePlayerFromMap(this, false);
// new final coordinates
float final_x = x;
float final_y = y;
float final_z = z;
float final_o = orientation;
if (m_transport)
{
final_x += m_movementInfo.transport.pos.GetPositionX();
final_y += m_movementInfo.transport.pos.GetPositionY();
final_z += m_movementInfo.transport.pos.GetPositionZ();
final_o += m_movementInfo.transport.pos.GetOrientation();
}
m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
SetFallInformation(0, final_z);
// 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 (m_transport)
data << m_movementInfo.transport.pos.PositionXYZOStream();
else
data << m_teleport_dest.PositionXYZOStream();
GetSession()->SendPacket(&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);
ScheduleDelayedOperation(DELAYED_BG_GROUP_RESTORE);
return TeleportTo(m_bgData.joinPos);
}
void Player::ProcessDelayedOperations()
{
if (m_DelayedOperations == 0)
return;
if (m_DelayedOperations & DELAYED_RESURRECT_PLAYER)
{
ResurrectPlayer(0.0f, false);
if (GetMaxHealth() > m_resurrectHealth)
SetHealth(m_resurrectHealth);
else
SetFullHealth();
if (GetMaxPower(POWER_MANA) > m_resurrectMana)
SetPower(POWER_MANA, m_resurrectMana);
else
SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
SetPower(POWER_RAGE, 0);
SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
SpawnCorpseBones();
}
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();
}
}
if (m_DelayedOperations & DELAYED_BG_GROUP_RESTORE)
{
if (Group* g = GetGroup())
g->SendUpdateToPlayer(GetGUID());
}
//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();
sOutdoorPvPMgr->HandlePlayerLeaveZone(this, m_zoneUpdateId);
sBattlefieldMgr->HandlePlayerLeaveZone(this, m_zoneUpdateId);
}
///- 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 (uint8 i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
{
if (m_items[i])
m_items[i]->RemoveFromWorld();
}
for (ItemMap::iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
iter->second->RemoveFromWorld();
if (m_uint32Values)
{
if (WorldObject* viewpoint = GetViewpoint())
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player %s has viewpoint %u %u when removed from world",
GetName().c_str(), viewpoint->GetEntry(), viewpoint->GetTypeId());
SetViewpoint(viewpoint, false);
}
}
}
void Player::RegenerateAll()
{
//if (m_regenTimer <= 500)
// return;
m_regenTimerCount += m_regenTimer;
Regenerate(POWER_ENERGY);
Regenerate(POWER_MANA);
// 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();
}
Regenerate(POWER_RAGE);
if (getClass() == CLASS_DEATH_KNIGHT)
Regenerate(POWER_RUNIC_POWER);
m_regenTimerCount -= 2000;
}
m_regenTimer = 0;
}
void Player::Regenerate(Powers power)
{
uint32 maxValue = GetMaxPower(power);
if (!maxValue)
return;
uint32 curValue = GetPower(power);
/// @todo possible use of miscvalueb instead of amount
if (HasAuraTypeWithValue(SPELL_AURA_PREVENT_REGENERATE_POWER, power))
return;
float addvalue = 0.0f;
switch (power)
{
case POWER_MANA:
{
bool recentCast = IsUnderLastManaUseEffect();
float ManaIncreaseRate = sWorld->getRate(RATE_POWER_MANA);
if (getLevel() < 15)
ManaIncreaseRate = sWorld->getRate(RATE_POWER_MANA) * (2.066f - (getLevel() * 0.066f));
if (recentCast) // Trinity Updates Mana in intervals of 2s, which is correct
addvalue += GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 0.001f * m_regenTimer;
else
addvalue += GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 0.001f * m_regenTimer;
} break;
case POWER_RAGE: // Regenerate rage
{
if (!IsInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
{
float RageDecreaseRate = sWorld->getRate(RATE_POWER_RAGE_LOSS);
addvalue += -20 * RageDecreaseRate; // 2 rage by tick (= 2 seconds => 1 rage/sec)
}
} break;
case POWER_ENERGY: // Regenerate energy (rogue)
addvalue += 0.01f * m_regenTimer * sWorld->getRate(RATE_POWER_ENERGY);
break;
case POWER_RUNIC_POWER:
{
if (!IsInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
{
float RunicPowerDecreaseRate = sWorld->getRate(RATE_POWER_RUNICPOWER_LOSS);
addvalue += -30 * RunicPowerDecreaseRate; // 3 RunicPower by tick
}
} break;
case POWER_RUNE:
case POWER_FOCUS:
case POWER_HAPPINESS:
break;
case POWER_HEALTH:
return;
default:
break;
}
// Mana regen calculated in Player::UpdateManaRegen()
if (power != POWER_MANA)
{
AuraEffectList const& ModPowerRegenPCTAuras = GetAuraEffectsByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
for (AuraEffectList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
if (Powers((*i)->GetMiscValue()) == power)
AddPct(addvalue, (*i)->GetAmount());
// Butchery requires combat for this effect
if (power != POWER_RUNIC_POWER || IsInCombat())
addvalue += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_POWER_REGEN, power) * ((power != POWER_ENERGY) ? m_regenTimerCount : m_regenTimer) / (5 * IN_MILLISECONDS);
}
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(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)
SetPower(power, curValue);
else
UpdateUInt32Value(UNIT_FIELD_POWER1 + 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;
// normal regen case (maybe partly in combat case)
else if (!IsInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
{
addvalue = OCTRegenHPPerSpirit() * HealthIncreaseRate;
if (!IsInCombat())
{
AuraEffectList const& mModHealthRegenPct = GetAuraEffectsByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
for (AuraEffectList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
AddPct(addvalue, (*i)->GetAmount());
addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_REGEN) * 2 * IN_MILLISECONDS / (5 * IN_MILLISECONDS);
}
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)
addvalue = 0;
ModifyHealth(int32(addvalue));
}
void Player::ResetAllPowers()
{
SetHealth(GetMaxHealth());
switch (getPowerType())
{
case POWER_MANA:
SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
break;
case POWER_RAGE:
SetPower(POWER_RAGE, 0);
break;
case POWER_ENERGY:
SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
break;
case POWER_RUNIC_POWER:
SetPower(POWER_RUNIC_POWER, 0);
break;
default:
break;
}
}
bool Player::CanInteractWithQuestGiver(Object* questGiver)
{
switch (questGiver->GetTypeId())
{
case TYPEID_UNIT:
return GetNPCIfCanInteractWith(questGiver->GetGUID(), UNIT_NPC_FLAG_QUESTGIVER) != NULL;
case TYPEID_GAMEOBJECT:
return GetGameObjectIfCanInteractWith(questGiver->GetGUID(), GAMEOBJECT_TYPE_QUESTGIVER) != NULL;
case TYPEID_PLAYER:
return IsAlive() && questGiver->ToPlayer()->IsAlive();
case TYPEID_ITEM:
return IsAlive();
default:
break;
}
return false;
}
Creature* Player::GetNPCIfCanInteractWith(uint64 guid, uint32 npcflagmask)
{
// unit checks
if (!guid)
return NULL;
if (!IsInWorld())
return NULL;
if (IsInFlight())
return NULL;
// exist (we need look pets also for some interaction (quest/etc)
Creature* creature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, guid);
if (!creature)
return NULL;
// Deathstate checks
if (!IsAlive() && !(creature->GetCreatureTemplate()->type_flags & CREATURE_TYPEFLAGS_GHOST))
return NULL;
// alive or spirit healer
if (!creature->IsAlive() && !(creature->GetCreatureTemplate()->type_flags & CREATURE_TYPEFLAGS_DEAD_INTERACT))
return NULL;
// appropriate npc type
if (npcflagmask && !creature->HasFlag(UNIT_NPC_FLAGS, npcflagmask))
return NULL;
// not allow interaction under control, but allow with own pets
if (creature->GetCharmerGUID())
return NULL;
// not enemy
if (creature->IsHostileTo(this))
return NULL;
// not unfriendly
if (FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(creature->getFaction()))
if (factionTemplate->faction)
if (FactionEntry const* faction = sFactionStore.LookupEntry(factionTemplate->faction))
if (faction->reputationListID >= 0 && GetReputationMgr().GetRank(faction) <= REP_UNFRIENDLY)
return NULL;
// not too far
if (!creature->IsWithinDistInMap(this, INTERACTION_DISTANCE))
return NULL;
return creature;
}
GameObject* Player::GetGameObjectIfCanInteractWith(uint64 guid, GameobjectTypes type) const
{
if (GameObject* go = GetMap()->GetGameObject(guid))
{
if (go->GetGoType() == type)
{
float maxdist;
switch (type)
{
/// @todo find out how the client calculates the maximal usage distance to spellless working
// gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number
case GAMEOBJECT_TYPE_GUILD_BANK:
case GAMEOBJECT_TYPE_MAILBOX:
maxdist = 10.0f;
break;
case GAMEOBJECT_TYPE_FISHINGHOLE:
maxdist = 20.0f+CONTACT_DISTANCE; // max spell range
break;
default:
maxdist = INTERACTION_DISTANCE;
break;
}
if (go->IsWithinDistInMap(this, maxdist))
return go;
TC_LOG_DEBUG(LOG_FILTER_MAPS, "IsGameObjectOfTypeInRange: GameObject '%s' [GUID: %u] is too far away from player %s [GUID: %u] to be used by him (distance=%f, maximal 10 is allowed)", go->GetGOInfo()->name.c_str(),
go->GetGUIDLow(), GetName().c_str(), GetGUIDLow(), go->GetDistance(this));
}
}
return NULL;
}
bool Player::IsUnderWater() const
{
return IsInWater() &&
GetPositionZ() < (GetBaseMap()->GetWaterLevel(GetPositionX(), GetPositionY())-2);
}
void Player::SetInWater(bool apply)
{
if (m_isInWater == apply)
return;
//define player in water by opcodes
//move player's guid into HateOfflineList of those mobs
//which can't swim and move guid back into ThreatList when
//on surface.
/// @todo exist also swimming mobs, and function must be symmetric to enter/leave water
m_isInWater = apply;
// remove auras that need water/land
RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
getHostileRefManager().updateThreatTables();
}
void Player::SetGameMaster(bool on)
{
if (on)
{
m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
setFaction(35);
SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_ALLOW_CHEAT_SPELLS);
if (Pet* pet = GetPet())
{
pet->setFaction(35);
pet->getHostileRefManager().setOnlineOfflineState(false);
}
RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
ResetContestedPvP();
getHostileRefManager().setOnlineOfflineState(false);
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);
RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_ALLOW_CHEAT_SPELLS);
if (Pet* pet = GetPet())
{
pet->setFaction(getFaction());
pet->getHostileRefManager().setOnlineOfflineState(true);
}
// restore FFA PvP Server state
if (sWorld->IsFFAPvPRealm())
SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
// restore FFA PvP area state, remove not allowed for GM mounts
UpdateArea(m_areaUpdateId);
getHostileRefManager().setOnlineOfflineState(true);
m_serverSideVisibilityDetect.SetValue(SERVERSIDE_VISIBILITY_GM, SEC_PLAYER);
}
UpdateObjectVisibility();
}
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());
}
}
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();
}
}
bool Player::IsInSameGroupWith(Player const* p) const
{
return p == this || (GetGroup() != NULL &&
GetGroup() == p->GetGroup() &&
GetGroup()->SameSubGroup(this, p));
}
bool Player::IsInSameRaidWith(Player const* p) const
{
return p == this || (GetGroup() != NULL && GetGroup() == p->GetGroup());
}
///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
/// @todo Shouldn't we also check if there is no other invitees before disbanding the group?
void Player::UninviteFromGroup()
{
Group* group = GetGroupInvite();
if (!group)
return;
group->RemoveInvite(this);
if (group->GetMembersCount() <= 1) // group has just 1 member => disband
{
if (group->IsCreated())
{
group->Disband(true);
}
else
{
group->RemoveAllInvites();
delete group;
}
}
}
void Player::RemoveFromGroup(Group* group, uint64 guid, RemoveMethod method /* = GROUP_REMOVEMETHOD_DEFAULT*/, uint64 kicker /* = 0 */, const char* reason /* = NULL */)
{
if (group)
{
group->RemoveMember(guid, method, kicker, reason);
group = NULL;
}
}
void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 BonusXP, bool recruitAFriend, float /*group_rate*/)
{
WorldPacket data(SMSG_LOG_XPGAIN, 21); // guess size?
data << uint64(victim ? victim->GetGUID() : 0); // guid
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?
GetSession()->SendPacket(&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);
// Favored experience increase START
uint32 zone = GetZoneId();
float favored_exp_mult = 0;
if ((HasAura(32096) || HasAura(32098)) && (zone == 3483 || zone == 3562 || zone == 3836 || zone == 3713 || zone == 3714))
favored_exp_mult = 0.05f; // Thrallmar's Favor and Honor Hold's Favor
xp = uint32(xp * (1 + favored_exp_mult));
// Favored experience increase END
// XP to money conversion processed in Player::RewardQuest
if (level >= sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL))
return;
uint32 bonus_xp = 0;
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 curXP = GetUInt32Value(PLAYER_XP);
uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
uint32 newXP = curXP + xp + bonus_xp;
while (newXP >= nextLvlXP && level < sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL))
{
newXP -= nextLvlXP;
if (level < sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL))
GiveLevel(level + 1);
level = getLevel();
nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
}
SetUInt32Value(PLAYER_XP, 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);
// send levelup info to client
WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
data << uint32(level);
data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
// for (int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
data << uint32(0);
data << uint32(0);
data << uint32(0);
data << uint32(0);
data << uint32(0);
data << uint32(0);
// end for
for (uint8 i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
GetSession()->SendPacket(&data);
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
UpdateSkillsToMaxSkillsForLevel();
// set current level health and mana/energy to maximum after applying all mods.
SetFullHealth();
SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
if (GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
SetPower(POWER_FOCUS, 0);
SetPower(POWER_HAPPINESS, 0);
_ApplyAllLevelScaleItemMods(true);
// 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
SQLTransaction 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, 1, 0x01))
SetByteFlag(PLAYER_FIELD_BYTES, 1, 0x01);
}
sScriptMgr->OnPlayerLevelChanged(this, oldLevel);
}
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 (m_usedTalentCount > 0) // Free any used talents
{
resetTalents(true); /// @todo: Has to (collectively) be renamed to ResetTalents
SetFreeTalentPoints(0);
}
}
else
{
if (level < sWorld->getIntConfig(CONFIG_MIN_DUALSPEC_LEVEL) || m_specsCount == 0)
{
m_specsCount = 1;
m_activeSpec = 0;
}
uint32 talentPointsForLevel = CalculateTalentsPoints();
// if used more that have then reset
if (m_usedTalentCount > talentPointsForLevel)
{
if (!GetSession()->HasPermission(RBAC_PERM_SKIP_CHECK_MORE_TALENTS_THAN_ALLOWED))
resetTalents(true);
else
SetFreeTalentPoints(0);
}
// else update amount of free points
else
SetFreeTalentPoints(talentPointsForLevel - m_usedTalentCount);
}
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);
SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL));
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
SetFloatValue(UNIT_MOD_CAST_SPEED, 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 = 0; i < 7; ++i)
{
SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
}
//reset attack power, damage and attack speed fields
SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f);
SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f); // offhand attack time
SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f);
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);
SetInt32Value(UNIT_FIELD_ATTACK_POWER, 0);
SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0);
SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER, 0.0f);
SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0);
SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS, 0);
SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER, 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));
SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
// set other resistance to original value (0)
for (uint8 i = 1; i < MAX_SPELL_SCHOOL; ++i)
{
SetResistance(SpellSchools(i), 0);
SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
}
SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE, 0);
SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE, 0);
for (uint8 i = 0; 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(GetCreatePowers(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.
SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
// cleanup unit flags (will be re-applied if need at aura load).
RemoveFlag(UNIT_FIELD_FLAGS,
UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | 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_NOT_SELECTABLE |
UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE); // must be set
SetFlag(UNIT_FIELD_FLAGS_2, 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);
RemoveStandFlags(UNIT_STAND_FLAGS_ALL); // one form stealth modified bytes
RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, 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();
SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
if (GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
SetPower(POWER_FOCUS, 0);
SetPower(POWER_HAPPINESS, 0);
SetPower(POWER_RUNIC_POWER, 0);
// update level to hunter/summon pet
if (Pet* pet = GetPet())
pet->SynchronizeLevelWithOwner();
}
void Player::SendInitialSpells()
{
time_t curTime = time(NULL);
time_t infTime = curTime + infinityCooldownDelayCheck;
uint16 spellCount = 0;
WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(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 +=1;
}
data.put<uint16>(countPos, spellCount); // write real count value
uint16 spellCooldowns = m_spellCooldowns.size();
data << uint16(spellCooldowns);
for (SpellCooldowns::const_iterator itr = m_spellCooldowns.begin(); itr != m_spellCooldowns.end(); ++itr)
{
SpellInfo const* sEntry = sSpellMgr->GetSpellInfo(itr->first);
if (!sEntry)
continue;
data << uint32(itr->first);
data << uint16(itr->second.itemid); // cast item id
data << uint16(sEntry->Category); // spell category
// send infinity cooldown in special format
if (itr->second.end >= infTime)
{
data << uint32(1); // cooldown
data << uint32(0x80000000); // category cooldown
continue;
}
time_t cooldown = itr->second.end > curTime ? (itr->second.end-curTime)*IN_MILLISECONDS : 0;
if (sEntry->Category) // may be wrong, but anyway better than nothing...
{
data << uint32(0); // cooldown
data << uint32(cooldown); // category cooldown
}
else
{
data << uint32(cooldown); // cooldown
data << uint32(0); // category cooldown
}
}
GetSession()->SendPacket(&data);
TC_LOG_DEBUG(LOG_FILTER_NETWORKIO, "CHARACTER: Sent Initial Spells");
}
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, uint32 item_guid, uint32 item_count)
{
WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_EQUIP_ERROR?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
data << (uint32) mailId;
data << (uint32) mailAction;
data << (uint32) mailError;
if (mailError == MAIL_ERR_EQUIP_ERROR)
data << (uint32) equipError;
else if (mailAction == MAIL_ITEM_TAKEN)
{
data << (uint32) item_guid; // item guid low?
data << (uint32) item_count; // item count?
}
GetSession()->SendPacket(&data);
}
void Player::SendNewMail()
{
// deliver undelivered mail
WorldPacket data(SMSG_RECEIVED_MAIL, 4);
data << (uint32) 0;
GetSession()->SendPacket(&data);
}
void Player::UpdateNextMailTimeAndUnreads()
{
// calculate next delivery time (min. from non-delivered mails
// and recalculate unReadMail
time_t cTime = time(NULL);
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 <= time(NULL)) // 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++)
{
PreparedStatement* 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(LOG_FILTER_SPELLS_AURAS, "Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.", spellId);
DeleteSpellFromAllPlayers(spellId);
}
else
TC_LOG_ERROR(LOG_FILTER_SPELLS_AURAS, "Player::addSpell: Non-existed in SpellStore spell #%u request.", 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(LOG_FILTER_SPELLS_AURAS, "Player::addTalent: Broken spell #%u learning not allowed, deleting for all characters in `character_talent`.", spellId);
DeleteSpellFromAllPlayers(spellId);
}
else
TC_LOG_ERROR(LOG_FILTER_SPELLS_AURAS, "Player::addTalent: Broken spell #%u learning not allowed.", spellId);
return false;
}
PlayerTalentMap::iterator itr = m_talents[spec]->find(spellId);
if (itr != m_talents[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->RankID[rank];
if (!rankSpellId || rankSpellId == spellId)
continue;
itr = m_talents[spec]->find(rankSpellId);
if (itr != m_talents[spec]->end())
itr->second->state = PLAYERSPELL_REMOVED;
}
}
PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
PlayerTalent* newtalent = new PlayerTalent();
newtalent->state = state;
newtalent->spec = spec;
(*m_talents[spec])[spellId] = newtalent;
return true;
}
return false;
}
bool Player::addSpell(uint32 spellId, bool active, bool learning, bool dependent, bool disabled, bool loading /*= false*/)
{
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId);
if (!spellInfo)
{
// do character spell book cleanup (all characters)
if (!IsInWorld() && !learning) // spell load case
{
TC_LOG_ERROR(LOG_FILTER_SPELLS_AURAS, "Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.", spellId);
DeleteSpellFromAllPlayers(spellId);
}
else
TC_LOG_ERROR(LOG_FILTER_SPELLS_AURAS, "Player::addSpell: Non-existed in SpellStore spell #%u request.", 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(LOG_FILTER_SPELLS_AURAS, "Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.", spellId);
DeleteSpellFromAllPlayers(spellId);
}
else
TC_LOG_ERROR(LOG_FILTER_SPELLS_AURAS, "Player::addSpell: Broken spell #%u learning not allowed.", 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() && IsNeedCastPassiveSpellAtLearn(spellInfo))
CastSpell (this, spellId, true);
}
else if (IsInWorld())
{
if (next_active_spell_id)
{
// update spell ranks in spellbook and action bar
WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
data << uint32(spellId);
data << uint32(next_active_spell_id);
GetSession()->SendPacket(&data);
}
else
{
WorldPacket data(SMSG_REMOVED_SPELL, 4);
data << uint32(spellId);
GetSession()->SendPacket(&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
{
delete itr->second;
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->RankID[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);
else // at normal learning
learnSpell(prev_spell, true);
}
PlayerSpell* newspell = new PlayerSpell;
newspell->state = state;
newspell->active = active;
newspell->dependent = dependent;
newspell->disabled = disabled;
// 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() != 0)
{
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
{
WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
data << uint32(itr2->first);
data << uint32(spellId);
GetSession()->SendPacket(&data);
}
// 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
{
WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
data << uint32(spellId);
data << uint32(itr2->first);
GetSession()->SendPacket(&data);
}
// 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;
}
}
}
}
}
m_spells[spellId] = newspell;
// 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 (IsNeedCastPassiveSpellAtLearn(spellInfo))
CastSpell(this, spellId, true);
}
else if (spellInfo->HasEffect(SPELL_EFFECT_SKILL_STEP))
{
CastSpell(this, spellId, true);
return false;
}
// update used talent points count
m_usedTalentCount += 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);
}
// add dependent skills
uint16 maxskill = GetMaxSkillValueForLevel();
SpellLearnSkillNode const* spellLearnSkill = sSpellMgr->GetSpellLearnSkill(spellId);
SkillLineAbilityMapBounds skill_bounds = sSpellMgr->GetSkillLineAbilityMapBounds(spellId);
if (spellLearnSkill)
{
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 ? maxskill : spellLearnSkill->maxvalue;
if (skill_max_value < new_skill_max_value)
skill_max_value = new_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->skillId);
if (!pSkill)
continue;
if (!Has310Flyer(false) && pSkill->id == SKILL_MOUNTS)
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
if (spellInfo->Effects[i].ApplyAuraName == SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED &&
spellInfo->Effects[i].CalcValue() == 310)
SetHas310Flyer(true);
if (HasSkill(pSkill->id))
continue;
if (_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
// lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
((pSkill->id == SKILL_LOCKPICKING || pSkill->id == SKILL_RUNEFORGING) && _spell_idx->second->max_value == 0))
{
switch (GetSkillRangeType(pSkill, _spell_idx->second->racemask != 0))
{
case SKILL_RANGE_LANGUAGE:
SetSkill(pSkill->id, GetSkillStep(pSkill->id), 300, 300);
break;
case SKILL_RANGE_LEVEL:
SetSkill(pSkill->id, GetSkillStep(pSkill->id), 1, GetMaxSkillValueForLevel());
break;
case SKILL_RANGE_MONO:
SetSkill(pSkill->id, GetSkillStep(pSkill->id), 1, 1);
break;
default:
break;
}
}
}
}
// 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->skillId);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS, _spell_idx->second->skillId);
}
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 = new PlayerSpell;
newspell->state = PLAYERSPELL_TEMPORARY;
newspell->active = true;
newspell->dependent = false;
newspell->disabled = false;
m_spells[spellId] = newspell;
}
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;
delete itr->second;
m_spells.erase(itr);
}
bool Player::IsNeedCastPassiveSpellAtLearn(SpellInfo const* spellInfo) const
{
// 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 & (1 << (form - 1)))) ||
(!form && (spellInfo->AttributesEx2 & SPELL_ATTR2_NOT_NEED_SHAPESHIFT)));
//Check CasterAuraStates
return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraStateType(spellInfo->CasterAuraState)));
}
void Player::learnSpell(uint32 spell_id, bool dependent)
{
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);
// 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);
GetSession()->SendPacket(&data);
}
// 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);
}
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);
}
}
}
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)
{
delete itr->second;
m_spells.erase(itr);
}
else
itr->second->state = PLAYERSPELL_REMOVED;
}
RemoveAurasDueToSpell(spell_id);
// 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 < m_usedTalentCount)
m_usedTalentCount -= talentCosts;
else
m_usedTalentCount = 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);
for (SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
{
SkillLineEntry const* pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
if (!pSkill)
continue;
if ((_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL &&
pSkill->categoryId != SKILL_CATEGORY_CLASS) ||// not unlearn class skills (spellbook/talent pages)
// lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
((pSkill->id == SKILL_LOCKPICKING || pSkill->id == SKILL_RUNEFORGING) && _spell_idx->second->max_value == 0))
{
// not reset skills for professions and racial abilities
if ((pSkill->categoryId == SKILL_CATEGORY_SECONDARY || pSkill->categoryId == SKILL_CATEGORY_PROFESSION) &&
(IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask != 0))
continue;
SetSkill(pSkill->id, GetSkillStep(pSkill->id), 0, 0);
}
// most likely will never be used, haven't heard of cases where players unlearn a mount
if (Has310Flyer(false) && _spell_idx->second->skillId == SKILL_MOUNTS)
{
if (spellInfo)
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
if (spellInfo->Effects[i].ApplyAuraName == SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED &&
spellInfo->Effects[i].CalcValue() == 310)
Has310Flyer(true, spell_id); // with true as first argument its also used to set/remove the flag
}
}
}
// 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;
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 != NULL 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 (cur_active && !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
WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
data << uint32(spell_id);
data << uint32(prev_id);
GetSession()->SendPacket(&data);
prev_activate = true;
}
}
}
}
}
if (spell_id == 46917 && m_canTitanGrip)
SetCanTitanGrip(false);
if (spell_id == 674 && m_canDualWield)
SetCanDualWield(false);
if (sWorld->getBoolConfig(CONFIG_OFFHAND_CHECK_AT_SPELL_UNLEARN))
AutoUnequipOffhandIfNeed();
// remove from spell book if not replaced by lesser rank
if (!prev_activate)
{
WorldPacket data(SMSG_REMOVED_SPELL, 4);
data << uint32(spell_id);
GetSession()->SendPacket(&data);
}
}
bool Player::Has310Flyer(bool checkAllSpells, uint32 excludeSpellId)
{
if (!checkAllSpells)
return m_ExtraFlags & PLAYER_EXTRA_HAS_310_FLYER;
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->skillId != SKILL_MOUNTS)
break; // We can break because mount spells belong only to one skillline (at least 310 flyers do)
spellInfo = sSpellMgr->GetSpellInfo(itr->first);
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
if (spellInfo->Effects[i].ApplyAuraName == SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED &&
spellInfo->Effects[i].CalcValue() == 310)
{
SetHas310Flyer(true);
return true;
}
}
}
}
return false;
}
void Player::RemoveSpellCooldown(uint32 spell_id, bool update /* = false */)
{
m_spellCooldowns.erase(spell_id);
if (update)
SendClearCooldown(spell_id, this);
}
// I am not sure which one is more efficient
void Player::RemoveCategoryCooldown(uint32 cat)
{
SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
if (i_scstore != sSpellCategoryStore.end())
for (SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
RemoveSpellCooldown(*i_scset, true);
}
void Player::RemoveSpellCategoryCooldown(uint32 cat, bool update /* = false */)
{
SpellCategoryStore::const_iterator ct = sSpellCategoryStore.find(cat);
if (ct == sSpellCategoryStore.end())
return;
const SpellCategorySet& ct_set = ct->second;
for (SpellCooldowns::const_iterator i = m_spellCooldowns.begin(); i != m_spellCooldowns.end();)
{
if (ct_set.find(i->first) != ct_set.end())
RemoveSpellCooldown((i++)->first, update);
else
++i;
}
}
void Player::RemoveArenaSpellCooldowns(bool removeActivePetCooldowns)
{
// remove cooldowns on spells that have <= 10 min CD
SpellCooldowns::iterator itr, next;
for (itr = m_spellCooldowns.begin(); itr != m_spellCooldowns.end(); itr = next)
{
next = itr;
++next;
SpellInfo const* entry = sSpellMgr->GetSpellInfo(itr->first);
// check if spellentry is present and if the cooldown is less or equal to 10 min
if (entry &&
entry->RecoveryTime <= 10 * MINUTE * IN_MILLISECONDS &&
entry->CategoryRecoveryTime <= 10 * MINUTE * IN_MILLISECONDS)
{
// remove & notify
RemoveSpellCooldown(itr->first, true);
}
}
// pet cooldowns
if (removeActivePetCooldowns)
if (Pet* pet = GetPet())
{
// notify player
for (CreatureSpellCooldowns::const_iterator itr2 = pet->m_CreatureSpellCooldowns.begin(); itr2 != pet->m_CreatureSpellCooldowns.end(); ++itr2)
SendClearCooldown(itr2->first, pet);
// actually clear cooldowns
pet->m_CreatureSpellCooldowns.clear();
}
}
void Player::RemoveAllSpellCooldown()
{
if (!m_spellCooldowns.empty())
{
for (SpellCooldowns::const_iterator itr = m_spellCooldowns.begin(); itr != m_spellCooldowns.end(); ++itr)
SendClearCooldown(itr->first, this);
m_spellCooldowns.clear();
}
}
void Player::_LoadSpellCooldowns(PreparedQueryResult result)
{
// some cooldowns can be already set at aura loading...
//QueryResult* result = CharacterDatabase.PQuery("SELECT spell, item, time FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
if (result)
{
time_t curTime = time(NULL);
do
{
Field* fields = result->Fetch();
uint32 spell_id = fields[0].GetUInt32();
uint32 item_id = fields[1].GetUInt32();
time_t db_time = time_t(fields[2].GetUInt32());
if (!sSpellMgr->GetSpellInfo(spell_id))
{
TC_LOG_ERROR(LOG_FILTER_PLAYER_LOADING, "Player %u has unknown spell %u in `character_spell_cooldown`, skipping.", GetGUIDLow(), spell_id);
continue;
}
// skip outdated cooldown
if (db_time <= curTime)
continue;
AddSpellCooldown(spell_id, item_id, db_time);
TC_LOG_DEBUG(LOG_FILTER_PLAYER_LOADING, "Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
}
while (result->NextRow());
}
}
void Player::_SaveSpellCooldowns(SQLTransaction& trans)
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SPELL_COOLDOWN);
stmt->setUInt32(0, GetGUIDLow());
trans->Append(stmt);
time_t curTime = time(NULL);
time_t infTime = curTime + infinityCooldownDelayCheck;
bool first_round = true;
std::ostringstream ss;
// remove outdated and save active
for (SpellCooldowns::iterator itr = m_spellCooldowns.begin(); itr != m_spellCooldowns.end();)
{
if (itr->second.end <= curTime)
m_spellCooldowns.erase(itr++);
else if (itr->second.end <= infTime) // not save locked cooldowns, it will be reset or set at reload
{
if (first_round)
{
ss << "INSERT INTO character_spell_cooldown (guid, spell, item, time) VALUES ";
first_round = false;
}
// next new/changed record prefix
else
ss << ',';
ss << '(' << GetGUIDLow() << ',' << itr->first << ',' << itr->second.itemid << ',' << uint64(itr->second.end) << ')';
++itr;
}
else
++itr;
}
// if something changed execute
if (!first_round)
trans->Append(ss.str().c_str());
}
uint32 Player::resetTalentsCost() const
{
// The first time reset costs 1 gold
if (m_resetTalentsCost < 1*GOLD)
return 1*GOLD;
// then 5 gold
else if (m_resetTalentsCost < 5*GOLD)
return 5*GOLD;
// After that it increases in increments of 5 gold
else if (m_resetTalentsCost < 10*GOLD)
return 10*GOLD;
else
{
uint64 months = (sWorld->GetGameTime() - m_resetTalentsTime)/MONTH;
if (months > 0)
{
// This cost will be reduced by a rate of 5 gold per month
int32 new_cost = int32(m_resetTalentsCost - 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 = m_resetTalentsCost + 5*GOLD;
// until it hits a cap of 50 gold.
if (new_cost > 50*GOLD)
new_cost = 50*GOLD;
return new_cost;
}
}
}
bool Player::resetTalents(bool no_cost)
{
sScriptMgr->OnPlayerTalentsReset(this, no_cost);
// not need after this call
if (HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
RemoveAtLoginFlag(AT_LOGIN_RESET_TALENTS, true);
uint32 talentPointsForLevel = CalculateTalentsPoints();
if (m_usedTalentCount == 0)
{
SetFreeTalentPoints(talentPointsForLevel);
return false;
}
uint32 cost = 0;
if (!no_cost && !sWorld->getBoolConfig(CONFIG_NO_RESET_TALENT_COST))
{
cost = resetTalentsCost();
if (!HasEnoughMoney(cost))
{
SendBuyError(BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
return false;
}
}
RemovePet(NULL, 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->TalentTab);
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-existant talent ranks
if (talentInfo->RankID[rank] == 0)
continue;
const SpellInfo* _spellEntry = sSpellMgr->GetSpellInfo(talentInfo->RankID[rank]);
if (!_spellEntry)
continue;
removeSpell(talentInfo->RankID[rank], true);
// search for spells that the talent teaches and unlearn them
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
if (_spellEntry->Effects[i].TriggerSpell > 0 && _spellEntry->Effects[i].Effect == SPELL_EFFECT_LEARN_SPELL)
removeSpell(_spellEntry->Effects[i].TriggerSpell, true);
// 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;
}
}
SQLTransaction trans = CharacterDatabase.BeginTransaction();
_SaveTalents(trans);
_SaveSpells(trans);
CharacterDatabase.CommitTransaction(trans);
SetFreeTalentPoints(talentPointsForLevel);
if (!no_cost)
{
ModifyMoney(-(int32)cost);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS, cost);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS, 1);
m_resetTalentsCost = cost;
m_resetTalentsTime = time(NULL);
}
/* when prev line will dropped use next line
if (Pet* pet = GetPet())
{
if (pet->getPetType() == HUNTER_PET && !pet->GetCreatureTemplate()->IsTameable(CanTameExoticPets()))
RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
}
*/
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 NULL;
}
void Player::BuildCreateUpdateBlockForPlayer(UpdateData* data, Player* target) const
{
if (target == this)
{
for (uint8 i = 0; i < EQUIPMENT_SLOT_END; ++i)
{
if (m_items[i] == NULL)
continue;
m_items[i]->BuildCreateUpdateBlockForPlayer(data, target);
}
for (uint8 i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
{
if (m_items[i] == NULL)
continue;
m_items[i]->BuildCreateUpdateBlockForPlayer(data, target);
}
for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
{
if (m_items[i] == NULL)
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 < INVENTORY_SLOT_BAG_END; ++i)
{
if (m_items[i] == NULL)
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] == NULL)
continue;
m_items[i]->DestroyForPlayer(target);
}
for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
{
if (m_items[i] == NULL)
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 = m_talents[spec]->find(spell);
return (itr != m_talents[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);
}
TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
{
if (!trainer_spell)
return TRAINER_SPELL_RED;
bool hasSpell = true;
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (!trainer_spell->learnedSpell[i])
continue;
if (!HasSpell(trainer_spell->learnedSpell[i]))
{
hasSpell = false;
break;
}
}
// known spell
if (hasSpell)
return TRAINER_SPELL_GRAY;
// check skill requirement
if (trainer_spell->reqSkill && GetBaseSkillValue(trainer_spell->reqSkill) < trainer_spell->reqSkillValue)
return TRAINER_SPELL_RED;
// check level requirement
if (getLevel() < trainer_spell->reqLevel)
return TRAINER_SPELL_RED;
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (!trainer_spell->learnedSpell[i])
continue;
// check race/class requirement
if (!IsSpellFitByClassAndRace(trainer_spell->learnedSpell[i]))
return TRAINER_SPELL_RED;
if (uint32 prevSpell = sSpellMgr->GetPrevSpellInChain(trainer_spell->learnedSpell[i]))
{
// check prev.rank requirement
if (prevSpell && !HasSpell(prevSpell))
return TRAINER_SPELL_RED;
}
SpellsRequiringSpellMapBounds spellsRequired = sSpellMgr->GetSpellsRequiredForSpellBounds(trainer_spell->learnedSpell[i]);
for (SpellsRequiringSpellMap::const_iterator itr = spellsRequired.first; itr != spellsRequired.second; ++itr)
{
// check additional spell requirement
if (!HasSpell(itr->second))
return TRAINER_SPELL_RED;
}
}
// check primary prof. limit
// first rank of primary profession spell when there are no proffesions avalible is disabled
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (!trainer_spell->learnedSpell[i])
continue;
SpellInfo const* learnedSpellInfo = sSpellMgr->GetSpellInfo(trainer_spell->learnedSpell[i]);
if (learnedSpellInfo && learnedSpellInfo->IsPrimaryProfessionFirstRank() && (GetFreePrimaryProfessionPoints() == 0))
return TRAINER_SPELL_GREEN_DISABLED;
}
return TRAINER_SPELL_GREEN;
}
/**
* 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(uint64 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
uint32 guid = GUID_LOPART(playerguid);
uint32 charDelete_method = sWorld->getIntConfig(CONFIG_CHARDELETE_METHOD);
if (deleteFinally)
charDelete_method = CHAR_DELETE_REMOVE;
else if (CharacterNameData const* nameData = sWorld->GetCharacterNameData(guid)) // To avoid a query, we select loaded data. If it doesn't exist, return.
{
// Define the required variables
uint32 charDelete_minLvl = sWorld->getIntConfig(nameData->m_class != CLASS_DEATH_KNIGHT ? CONFIG_CHARDELETE_MIN_LEVEL : CONFIG_CHARDELETE_HEROIC_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 (nameData->m_level < charDelete_minLvl)
charDelete_method = CHAR_DELETE_REMOVE;
}
// convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
// bones will be deleted by corpse/bones deleting thread shortly
sObjectAccessor->ConvertCorpseForPlayer(playerguid);
if (uint32 guildId = GetGuildIdFromDB(playerguid))
if (Guild* guild = sGuildMgr->GetGuildById(guildId))
guild->DeleteMember(guid);
// remove from arena teams
LeaveAllArenaTeams(playerguid);
// the player was uninvited already on logout so just remove from group
PreparedStatement* 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, 10);
switch (charDelete_method)
{
// Completely remove from the database
case CHAR_DELETE_REMOVE:
{
SQLTransaction trans = CharacterDatabase.BeginTransaction();
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_COD_ITEM_MAIL);
stmt->setUInt32(0, guid);
PreparedQueryResult resultMail = CharacterDatabase.Query(stmt);
if (resultMail)
{
do
{
Field* mailFields = resultMail->Fetch();
uint32 mail_id = mailFields[0].GetUInt32();
uint8 mailType = mailFields[1].GetUInt8();
uint16 mailTemplateId= mailFields[2].GetUInt16();
uint32 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
if (has_items)
{
// Data needs to be at first place for Item::LoadFromDB
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_MAILITEMS);
stmt->setUInt32(0, mail_id);
PreparedQueryResult resultItems = CharacterDatabase.Query(stmt);
if (resultItems)
{
do
{
Field* itemFields = resultItems->Fetch();
uint32 item_guidlow = itemFields[11].GetUInt32();
uint32 item_template = itemFields[12].GetUInt32();
ItemTemplate const* itemProto = sObjectMgr->GetItemTemplate(item_template);
if (!itemProto)
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_INSTANCE);
stmt->setUInt32(0, item_guidlow);
trans->Append(stmt);
continue;
}
Item* pItem = NewItemOrBag(itemProto);
if (!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER), itemFields, item_template))
{
pItem->FSetState(ITEM_REMOVED);
pItem->SaveToDB(trans); // it also deletes item object!
continue;
}
draft.AddItem(pItem);
}
while (resultItems->NextRow());
}
}
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_ITEM_BY_ID);
stmt->setUInt32(0, mail_id);
trans->Append(stmt);
uint32 pl_account = sObjectMgr->GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
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_PETS);
stmt->setUInt32(0, guid);
PreparedQueryResult resultPets = CharacterDatabase.Query(stmt);
if (resultPets)
{
do
{
uint32 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);
PreparedQueryResult resultFriends = CharacterDatabase.Query(stmt);
if (resultFriends)
{
do
{
if (Player* pFriend = ObjectAccessor::FindPlayer(MAKE_NEW_GUID((*resultFriends)[0].GetUInt32(), 0, HIGHGUID_PLAYER)))
{
if (pFriend->IsInWorld())
{
pFriend->GetSocial()->RemoveFromSocialList(guid, false);
sSocialMgr->SendFriendStatus(pFriend, FRIEND_REMOVED, guid, false);
}
}
} 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_CHAR_AURA);
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_COOLDOWN);
stmt->setUInt32(0, guid);
trans->Append(stmt);
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_PLAYER_BGDATA);
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_CHAR_QUESTSTATUS_DAILY);
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);
CharacterDatabase.CommitTransaction(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);
CharacterDatabase.Execute(stmt);
break;
}
default:
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player::DeleteFromDB: Unsupported delete method: %u.", charDelete_method);
return;
}
if (updateRealmChars)
sWorld->UpdateRealmCharCount(accountId);
sWorld->DeleteCharacterNameData(guid);
}
/**
* 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 overrite the config option by another amount of days
*/
void Player::DeleteOldCharacters(uint32 keepDays)
{
TC_LOG_INFO(LOG_FILTER_PLAYER, "Player::DeleteOldChars: Deleting all characters which have been deleted %u days before...", keepDays);
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_OLD_CHARS);
stmt->setUInt32(0, uint32(time(NULL) - time_t(keepDays * DAY)));
PreparedQueryResult result = CharacterDatabase.Query(stmt);
if (result)
{
TC_LOG_DEBUG(LOG_FILTER_PLAYER, "Player::DeleteOldChars: Found " UI64FMTD " character(s) to delete", result->GetRowCount());
do
{
Field* fields = result->Fetch();
Player::DeleteFromDB(fields[0].GetUInt32(), fields[1].GetUInt32(), true, true);
}
while (result->NextRow());
}
}
void Player::SetMovement(PlayerMovementType pType)
{
WorldPacket data;
switch (pType)
{
case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
default:
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player::SetMovement: Unsupported move type (%d), data not sent to client.", pType);
return;
}
data.append(GetPackGUID());
data << uint32(0);
GetSession()->SendPacket(&data);
}
/* Preconditions:
- a resurrectable corpse must not be loaded for the player (only bones)
- the player must be in world
*/
void Player::BuildPlayerRepop()
{
WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
data.append(GetPackGUID());
GetSession()->SendPacket(&data);
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
// there we must send 888 opcode
// the player cannot have a corpse already, only bones which are not returned by GetCorpse
if (GetCorpse())
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "BuildPlayerRepop: player %s(%d) already has a corpse", GetName().c_str(), GetGUIDLow());
return;
}
// create a corpse and place it at the player's location
CreateCorpse();
Corpse* corpse = GetCorpse();
if (!corpse)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Error creating corpse for Player %s [%u]", GetName().c_str(), GetGUIDLow());
return;
}
GetMap()->AddToMap(corpse);
// convert player body to ghost
SetHealth(1);
SetMovement(MOVE_WATER_WALK);
if (!GetSession()->isLogingOut())
SetMovement(MOVE_UNROOT);
// BG - remove insignia related
RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
// SendCorpseReclaimDelay();
// to prevent cheating
corpse->ResetGhostTime();
StopMirrorTimers(); //disable timers(bars)
// set and clear other
SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND);
}
void Player::ResurrectPlayer(float restore_percent, bool applySickness)
{
WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
data << uint32(-1);
data << float(0);
data << float(0);
data << float(0);
GetSession()->SendPacket(&data);
// speed change, land walk
// remove death flag + set aura
SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
if (getRace() == RACE_NIGHTELF)
RemoveAurasDueToSpell(20584); // speed bonuses
RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
if (GetSession()->IsARecruiter() || (GetSession()->GetRecruiterId() != 0))
SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_REFER_A_FRIEND);
setDeathState(ALIVE);
SetMovement(MOVE_LAND_WALK);
SetMovement(MOVE_UNROOT);
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();
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);
if (int32(getLevel()) >= startLevel)
{
// set resurrection sickness
CastSpell(this, 15007, true);
// not full duration
if (int32(getLevel()) < startLevel+9)
{
int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
if (Aura* aur = GetAura(15007, GetGUID()))
{
aur->SetDuration(delta*IN_MILLISECONDS);
}
}
}
}
void Player::KillPlayer()
{
if (IsFlying() && !GetTransport())
i_motionMaster.MoveFall();
SetMovement(MOVE_ROOT);
StopMirrorTimers(); //disable timers(bars)
setDeathState(CORPSE);
//SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP);
SetUInt32Value(UNIT_DYNAMIC_FLAGS, 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
SendCorpseReclaimDelay();
// don't create corpse at this moment, player might be falling
// update visibility
UpdateObjectVisibility();
}
void Player::CreateCorpse()
{
// prevent existence 2 corpse for player
SpawnCorpseBones();
uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
Corpse* corpse = new Corpse((m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE);
SetPvPDeath(false);
if (!corpse->Create(sObjectMgr->GenerateLowGuid(HIGHGUID_CORPSE), this))
{
delete corpse;
return;
}
_uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
_pb = GetUInt32Value(PLAYER_BYTES);
_pb2 = GetUInt32Value(PLAYER_BYTES_2);
uint8 race = (uint8)(_uf);
uint8 skin = (uint8)(_pb);
uint8 face = (uint8)(_pb >> 8);
uint8 hairstyle = (uint8)(_pb >> 16);
uint8 haircolor = (uint8)(_pb >> 24);
uint8 facialhair = (uint8)(_pb2);
_cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
_cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 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);
}
}
// we do not need to save corpses for BG/arenas
if (!GetMap()->IsBattlegroundOrArena())
corpse->SaveToDB();
// register for player, but not show
sObjectAccessor->AddCorpse(corpse);
}
void Player::SpawnCorpseBones()
{
if (sObjectAccessor->ConvertCorpseForPlayer(GetGUID()))
if (!GetSession()->PlayerLogoutWithSave()) // at logout we will already store the player
SaveToDB(); // prevent loading as ghost without corpse
}
Corpse* Player::GetCorpse() const
{
return sObjectAccessor->GetCorpseForPlayerGUID(GetGUID());
}
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 = (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)
{
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);
}
uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
{
uint32 TotalCost = 0;
// equipped, backpack, bags itself
for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
TotalCost += DurabilityRepair(((INVENTORY_SLOT_BAG_0 << 8) | i), cost, discountMod, guildBank);
// 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++)
TotalCost += DurabilityRepair(((j << 8) | i), cost, discountMod, guildBank);
return TotalCost;
}
uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
{
Item* item = GetItemByPos(pos);
uint32 TotalCost = 0;
if (!item)
return TotalCost;
uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
if (!maxDurability)
return TotalCost;
uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
if (cost)
{
uint32 LostDurability = maxDurability - curDurability;
if (LostDurability>0)
{
ItemTemplate const* ditemProto = item->GetTemplate();
DurabilityCostsEntry const* dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
if (!dcost)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER_ITEMS, "RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
return TotalCost;
}
uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
DurabilityQualityEntry const* dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
if (!dQualitymodEntry)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER_ITEMS, "RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
return TotalCost;
}
uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class, ditemProto->SubClass)];
uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
costs = uint32(costs * discountMod * sWorld->getRate(RATE_REPAIRCOST));
if (costs == 0) //fix for ITEM_QUALITY_ARTIFACT
costs = 1;
if (guildBank)
{
if (GetGuildId() == 0)
{
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "You are not member of a guild");
return TotalCost;
}
Guild* guild = sGuildMgr->GetGuildById(GetGuildId());
if (!guild)
return TotalCost;
if (!guild->HandleMemberWithdrawMoney(GetSession(), costs, true))
return TotalCost;
TotalCost = costs;
}
else if (!HasEnoughMoney(costs))
{
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "You do not have enough money");
return TotalCost;
}
else
ModifyMoney(-int32(costs));
}
}
item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
item->SetState(ITEM_CHANGED, this);
// reapply mods for total broken and repaired item if equipped
if (IsEquipmentPos(pos) && !curDurability)
_ApplyItemMods(item, pos & 255, true);
return TotalCost;
}
void Player::RepopAtGraveyard()
{
// note: this can be called also when the player is alive
// for example from WorldSession::HandleMovementOpcodes
AreaTableEntry const* zone = GetAreaEntryByAreaID(GetAreaId());
// 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() < -500.0f)
{
ResurrectPlayer(0.5f);
SpawnCorpseBones();
}
WorldSafeLocsEntry const* ClosestGrave = NULL;
// 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());
}
// 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->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
if (isDead()) // not send if alive, because it used in TeleportTo()
{
WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
data << ClosestGrave->map_id;
data << ClosestGrave->x;
data << ClosestGrave->y;
data << ClosestGrave->z;
GetSession()->SendPacket(&data);
}
}
else if (GetPositionZ() < -500.0f)
TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation());
}
bool Player::CanJoinConstantChannelInZone(ChatChannelsEntry const* channel, AreaTableEntry const* zone)
{
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
if (ChannelMgr* cMgr = ChannelMgr::forTeam(GetTeam()))
cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
}
TC_LOG_DEBUG(LOG_FILTER_CHATSYS, "Player %s: channels cleaned up!", GetName().c_str());
}
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 = GetAreaEntryByAreaID(newZone);
if (!current_zone)
return;
ChannelMgr* cMgr = ChannelMgr::forTeam(GetTeam());
if (!cMgr)
return;
std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
for (uint32 i = 0; i < sChatChannelsStore.GetNumRows(); ++i)
{
if (ChatChannelsEntry const* channel = sChatChannelsStore.LookupEntry(i))
{
Channel* usedChannel = NULL;
for (JoinedChannelsList::iterator itr = m_channels.begin(); itr != m_channels.end(); ++itr)
{
if ((*itr)->GetChannelId() == i)
{
usedChannel = *itr;
break;
}
}
Channel* removeChannel = NULL;
Channel* joinChannel = NULL;
bool sendRemove = true;
if (CanJoinConstantChannelInZone(channel, current_zone))
{
if (!(channel->flags & CHANNEL_DBC_FLAG_GLOBAL))
{
if (channel->flags & CHANNEL_DBC_FLAG_CITY_ONLY && usedChannel)
continue; // Already on the channel, as city channel names are not changing
char new_channel_name_buf[100];
char const* currentNameExt;
if (channel->flags & CHANNEL_DBC_FLAG_CITY_ONLY)
currentNameExt = sObjectMgr->GetTrinityStringForDBCLocale(LANG_CHANNEL_CITY);
else
currentNameExt = current_zone_name.c_str();
snprintf(new_channel_name_buf, 100, channel->pattern[m_session->GetSessionDbcLocale()], currentNameExt);
joinChannel = cMgr->GetJoinChannel(new_channel_name_buf, channel->ChannelID);
if (usedChannel)
{
if (joinChannel != usedChannel)
{
removeChannel = usedChannel;
sendRemove = false; // Do not send leave channel, it already replaced at client
}
else
joinChannel = NULL;
}
}
else
joinChannel = cMgr->GetJoinChannel(channel->pattern[m_session->GetSessionDbcLocale()], channel->ChannelID);
}
else
removeChannel = usedChannel;
if (joinChannel)
joinChannel->JoinChannel(this, ""); // Changed Channel: ... or Joined Channel: ...
if (removeChannel)
{
removeChannel->LeaveChannel(this, sendRemove); // Leave old channel
std::string name = removeChannel->GetName(); // Store name, (*i)erase in LeftChannel
LeftChannel(removeChannel); // Remove from player's channel list
cMgr->LeftChannel(name); // 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::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
{
if (modGroup >= BASEMOD_END || modType >= MOD_END)
{
TC_LOG_ERROR(LOG_FILTER_SPELLS_AURAS, "ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
return;
}
switch (modType)
{
case FLAT_MOD:
m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
break;
case PCT_MOD:
ApplyPercentModFloatVar(m_auraBaseMod[modGroup][modType], amount, apply);
break;
}
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(LOG_FILTER_SPELLS_AURAS, "trial to access non existed BaseModGroup or wrong BaseModType!");
return 0.0f;
}
if (modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
return 0.0f;
return m_auraBaseMod[modGroup][modType];
}
float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
{
if (modGroup >= BASEMOD_END)
{
TC_LOG_ERROR(LOG_FILTER_SPELLS_AURAS, "wrong BaseModGroup in GetTotalBaseModValue()!");
return 0.0f;
}
if (m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
return 0.0f;
return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
}
uint32 Player::GetShieldBlockValue() const
{
float value = (m_auraBaseMod[SHIELD_BLOCK_VALUE][FLAT_MOD] + GetStat(STAT_STRENGTH) * 0.5f - 10)*m_auraBaseMod[SHIELD_BLOCK_VALUE][PCT_MOD];
value = (value < 0) ? 0 : value;
return uint32(value);
}
float Player::GetMeleeCritFromAgility()
{
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 == NULL || critRatio == NULL)
return 0.0f;
float crit = critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
return crit*100.0f;
}
void Player::GetDodgeFromAgility(float &diminishing, float &nondiminishing)
{
// 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 == NULL || 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) * m_auraModifiersGroup[UNIT_MOD_STAT_START + 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->ratio * crit_to_dodge[pclass-1];
nondiminishing = 100.0f * (dodge_base[pclass-1] + base_agility * dodgeRatio->ratio * crit_to_dodge[pclass-1]);
}
float Player::GetSpellCritFromIntellect()
{
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 == NULL || critRatio == NULL)
return 0.0f;
float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
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->ratio / Rating->ratio;
}
float Player::GetRatingBonusValue(CombatRating cr) const
{
return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + 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()
{
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 == NULL || moreRatio == NULL)
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->ratio + moreSpirit * moreRatio->ratio;
return regen;
}
float Player::OCTRegenMPPerSpirit()
{
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 == NULL)
return 0.0f;
// Formula get from PaperDollFrame script
float spirit = GetStat(STAT_SPIRIT);
float regen = spirit * moreRatio->ratio;
return regen;
}
void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
{
m_baseRatingValue[cr]+=(apply ? value : -value);
// explicit affected values
switch (cr)
{
case CR_HASTE_MELEE:
{
float RatingChange = value * GetRatingMultiplier(cr);
ApplyAttackTimePercentMod(BASE_ATTACK, RatingChange, apply);
ApplyAttackTimePercentMod(OFF_ATTACK, RatingChange, apply);
break;
}
case CR_HASTE_RANGED:
{
float RatingChange = value * GetRatingMultiplier(cr);
ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
break;
}
case CR_HASTE_SPELL:
{
float RatingChange = value * GetRatingMultiplier(cr);
ApplyCastTimePercentMod(RatingChange, apply);
break;
}
default:
break;
}
UpdateRating(cr);
}
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 (AuraEffectList::const_iterator i = modRatingFromStat.begin(); i != modRatingFromStat.end(); ++i)
if ((*i)->GetMiscValue() & (1<<cr))
amount += int32(CalculatePct(GetStat(Stats((*i)->GetMiscValueB())), (*i)->GetAmount()));
if (amount < 0)
amount = 0;
SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + 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 (int 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)
}
}
//skill+step, checking for max value
bool Player::UpdateSkill(uint32 skill_id, uint32 step)
{
if (!skill_id)
return false;
if (skill_id == SKILL_FIST_WEAPONS)
skill_id = SKILL_UNARMED;
SkillStatusMap::iterator itr = mSkillStatus.find(skill_id);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return false;
uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
uint32 data = GetUInt32Value(valueIndex);
uint32 value = SKILL_VALUE(data);
uint32 max = SKILL_MAX(data);
if ((!max) || (!value) || (value >= max))
return false;
if (value < max)
{
uint32 new_value = value+step;
if (new_value > max)
new_value = max;
SetUInt32Value(valueIndex, MAKE_SKILL_VALUE(new_value, max));
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(LOG_FILTER_PLAYER_SKILLS, "UpdateCraftSkill spellid %d", spellid);
SkillLineAbilityMapBounds bounds = sSpellMgr->GetSkillLineAbilityMapBounds(spellid);
for (SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
{
if (_spell_idx->second->skillId)
{
uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
// Alchemy Discoveries here
SpellInfo const* spellEntry = sSpellMgr->GetSpellInfo(spellid);
if (spellEntry && spellEntry->Mechanic == MECHANIC_DISCOVERY)
{
if (uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
learnSpell(discoveredSpell, false);
}
uint32 craft_skill_gain = sWorld->getIntConfig(CONFIG_SKILL_GAIN_CRAFTING);
return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
_spell_idx->second->max_value,
(_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
_spell_idx->second->min_value),
craft_skill_gain);
}
}
return false;
}
bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator)
{
TC_LOG_DEBUG(LOG_FILTER_PLAYER_SKILLS, "UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", 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;
}
bool Player::UpdateFishingSkill()
{
TC_LOG_DEBUG(LOG_FILTER_PLAYER_SKILLS, "UpdateFishingSkill");
uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
uint32 gathering_skill_gain = sWorld->getIntConfig(CONFIG_SKILL_GAIN_GATHERING);
return UpdateSkillPro(SKILL_FISHING, chance*10, gathering_skill_gain);
}
// levels sync. with spell requirement for skill levels to learn
// bonus abilities in sSkillLineAbilityStore
// Used only to avoid scan DBC at each skill grow
static uint32 bonusSkillLevels[] = {75, 150, 225, 300, 375, 450};
static const size_t bonusSkillLevelsSize = sizeof(bonusSkillLevels) / sizeof(uint32);
bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
{
TC_LOG_DEBUG(LOG_FILTER_PLAYER_SKILLS, "UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance / 10.0f);
if (!SkillId)
return false;
if (Chance <= 0) // speedup in 0 chance case
{
TC_LOG_DEBUG(LOG_FILTER_PLAYER_SKILLS, "Player::UpdateSkillPro Chance=%3.1f%% missed", Chance / 10.0f);
return false;
}
SkillStatusMap::iterator itr = mSkillStatus.find(SkillId);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return false;
uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
uint32 data = GetUInt32Value(valueIndex);
uint16 SkillValue = SKILL_VALUE(data);
uint16 MaxValue = SKILL_MAX(data);
if (!MaxValue || !SkillValue || SkillValue >= MaxValue)
return false;
int32 Roll = irand(1, 1000);
if (Roll <= Chance)
{
uint32 new_value = SkillValue+step;
if (new_value > MaxValue)
new_value = MaxValue;
SetUInt32Value(valueIndex, MAKE_SKILL_VALUE(new_value, MaxValue));
if (itr->second.uState != SKILL_NEW)
itr->second.uState = SKILL_CHANGED;
for (size_t i = 0; i < bonusSkillLevelsSize; ++i)
{
uint32 bsl = bonusSkillLevels[i];
if (SkillValue < bsl && new_value >= bsl)
{
learnSkillRewardedSpells(SkillId, new_value);
break;
}
}
UpdateSkillEnchantments(SkillId, SkillValue, new_value);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL, SkillId);
TC_LOG_DEBUG(LOG_FILTER_PLAYER_SKILLS, "Player::UpdateSkillPro Chance=%3.1f%% taken", Chance / 10.0f);
return true;
}
TC_LOG_DEBUG(LOG_FILTER_PLAYER_SKILLS, "Player::UpdateSkillPro Chance=%3.1f%% missed", Chance / 10.0f);
return false;
}
void Player::UpdateWeaponSkill(WeaponAttackType attType)
{
// no skill gain in pvp
Unit* victim = GetVictim();
if (victim && victim->GetTypeId() == TYPEID_PLAYER)
return;
if (IsInFeralForm())
return; // always maximized SKILL_FERAL_COMBAT in fact
if (GetShapeshiftForm() == FORM_TREE)
return; // use weapon but not skill up
if (victim && victim->GetTypeId() == TYPEID_UNIT && (victim->ToCreature()->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_NO_SKILLGAIN))
return;
uint32 weapon_skill_gain = sWorld->getIntConfig(CONFIG_SKILL_GAIN_WEAPON);
Item* tmpitem = GetWeaponForAttack(attType, true);
if (!tmpitem && attType == BASE_ATTACK)
UpdateSkill(SKILL_UNARMED, weapon_skill_gain);
else if (tmpitem && tmpitem->GetTemplate()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
UpdateSkill(tmpitem->GetSkill(), weapon_skill_gain);
UpdateAllCritPercentages();
}
void Player::UpdateCombatSkills(Unit* victim, WeaponAttackType attType, bool defence)
{
uint8 plevel = getLevel(); // if defense than victim == attacker
uint8 greylevel = Trinity::XP::GetGrayLevel(plevel);
uint8 moblevel = victim->getLevelForTarget(this);
if (moblevel < greylevel)
return;
if (moblevel > plevel + 5)
moblevel = plevel + 5;
uint8 lvldif = moblevel - greylevel;
if (lvldif < 3)
lvldif = 3;
uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
if (skilldif <= 0)
return;
float chance = float(3 * lvldif * skilldif) / plevel;
if (!defence)
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 (defence)
UpdateDefense();
else
UpdateWeaponSkill(attType);
}
else
return;
}
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;
uint32 bonusIndex = PLAYER_SKILL_BONUS_INDEX(itr->second.pos);
uint32 bonus_val = GetUInt32Value(bonusIndex);
int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
if (talent) // permanent bonus stored in high part
SetUInt32Value(bonusIndex, MAKE_SKILL_BONUS(temp_bonus, perm_bonus+val));
else // temporary/item bonus stored in low part
SetUInt32Value(bonusIndex, MAKE_SKILL_BONUS(temp_bonus+val, perm_bonus));
}
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;
SkillLineEntry const* pSkill = sSkillLineStore.LookupEntry(pskill);
if (!pSkill)
continue;
if (GetSkillRangeType(pSkill, false) != SKILL_RANGE_LEVEL)
continue;
uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
uint32 data = GetUInt32Value(valueIndex);
uint32 max = SKILL_MAX(data);
uint32 val = SKILL_VALUE(data);
/// update only level dependent max skill values
if (max != 1)
{
/// maximize skill always
if (alwaysMaxSkill)
{
SetUInt32Value(valueIndex, MAKE_SKILL_VALUE(maxSkill, 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
{
SetUInt32Value(valueIndex, MAKE_SKILL_VALUE(val, maxSkill));
if (itr->second.uState != SKILL_NEW)
itr->second.uState = SKILL_CHANGED;
}
}
}
}
void Player::UpdateSkillsToMaxSkillsForLevel()
{
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;
uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
uint32 data = GetUInt32Value(valueIndex);
uint32 max = SKILL_MAX(data);
if (max > 1)
{
SetUInt32Value(valueIndex, MAKE_SKILL_VALUE(max, 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(uint16 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 = SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(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
SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos), MAKE_PAIR32(id, step));
// update value
SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos), MAKE_SKILL_VALUE(newVal, 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
SetUInt32Value(PLAYER_SKILL_INDEX(itr->second.pos), 0);
SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos), 0);
SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(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
for (uint32 j = 0; j < sSkillLineAbilityStore.GetNumRows(); ++j)
if (SkillLineAbilityEntry const* pAbility = sSkillLineAbilityStore.LookupEntry(j))
if (pAbility->skillId == id)
removeSpell(sSpellMgr->GetFirstSpellInChain(pAbility->spellId));
}
}
else if (newVal) //add
{
currVal = 0;
for (int i=0; i < PLAYER_MAX_SKILLS; ++i)
if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
{
SkillLineEntry const* pSkill = sSkillLineStore.LookupEntry(id);
if (!pSkill)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER_SKILLS, "Skill not found in SkillLineStore: skill #%u", id);
return;
}
SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id, step));
SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i), MAKE_SKILL_VALUE(newVal, maxVal));
UpdateSkillEnchantments(id, currVal, newVal);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL, id);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL, id);
// 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
SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(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);
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(uint16 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 PAIR32_HIPART(GetUInt32Value(PLAYER_SKILL_INDEX(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;
uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos));
int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
result += SKILL_TEMP_BONUS(bonus);
result += SKILL_PERM_BONUS(bonus);
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;
uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos));
int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
result += SKILL_TEMP_BONUS(bonus);
result += SKILL_PERM_BONUS(bonus);
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 SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(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(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(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 SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(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 SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(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 SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(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 - Looks to be sent when initial action buttons get sent, however on Trinity we use 1 since 0 had some difficulties
1 - Used in any SMSG_ACTION_BUTTONS packet with button data on Trinity. Only used after spec swaps on retail.
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);
}
}
GetSession()->SendPacket(&data);
TC_LOG_INFO(LOG_FILTER_NETWORKIO, "SMSG_ACTION_BUTTONS sent '%u' spec '%u' Sent", GetGUIDLow(), m_activeSpec);
}
bool Player::IsActionButtonDataValid(uint8 button, uint32 action, uint8 type)
{
if (button >= MAX_ACTION_BUTTONS)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Action %u not added into button %u for player %s (GUID: %u): button must be < %u", action, button, GetName().c_str(), GUID_LOPART(GetGUID()), MAX_ACTION_BUTTONS );
return false;
}
if (action >= MAX_ACTION_BUTTON_ACTION_VALUE)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Action %u not added into button %u for player %s (GUID: %u): action must be < %u", action, button, GetName().c_str(), GUID_LOPART(GetGUID()), MAX_ACTION_BUTTON_ACTION_VALUE);
return false;
}
switch (type)
{
case ACTION_BUTTON_SPELL:
if (!sSpellMgr->GetSpellInfo(action))
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Spell action %u not added into button %u for player %s (GUID: %u): spell not exist", action, button, GetName().c_str(), GUID_LOPART(GetGUID()));
return false;
}
if (!HasSpell(action))
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Spell action %u not added into button %u for player %s (GUID: %u): player don't known this spell", action, button, GetName().c_str(), GUID_LOPART(GetGUID()));
return false;
}
break;
case ACTION_BUTTON_ITEM:
if (!sObjectMgr->GetItemTemplate(action))
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Item action %u not added into button %u for player %s (GUID: %u): item not exist", action, button, GetName().c_str(), GUID_LOPART(GetGUID()));
return false;
}
break;
case ACTION_BUTTON_C:
case ACTION_BUTTON_CMACRO:
case ACTION_BUTTON_MACRO:
case ACTION_BUTTON_EQSET:
break;
default:
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Unknown action type %u", 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 NULL;
// it create new button (NEW state) if need or return existed
ActionButton& ab = m_actionButtons[button];
// set data and update to CHANGED if not NEW
ab.SetActionAndType(action, ActionButtonType(type));
TC_LOG_DEBUG(LOG_FILTER_PLAYER, "Player '%u' Added Action '%u' (type %u) to Button '%u'", GetGUIDLow(), 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(LOG_FILTER_PLAYER, "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow());
}
ActionButton const* Player::GetActionButton(uint8 button)
{
ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
if (buttonItr == m_actionButtons.end() || buttonItr->second.uState == ACTIONBUTTON_DELETED)
return NULL;
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
// group update
if (GetGroup())
SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
if (GetTrader() && !IsWithinDistInMap(GetTrader(), INTERACTION_DISTANCE))
GetSession()->SendCancelTrade();
CheckAreaExploreAndOutdoor();
return true;
}
void Player::SaveRecallPosition()
{
m_recallMap = GetMapId();
m_recallX = GetPositionX();
m_recallY = GetPositionY();
m_recallZ = GetPositionZ();
m_recallO = GetOrientation();
}
void Player::SendMessageToSetInRange(WorldPacket* data, float dist, bool self)
{
if (self)
GetSession()->SendPacket(data);
Trinity::MessageDistDeliverer notifier(this, data, dist);
VisitNearbyWorldObject(dist, notifier);
}
void Player::SendMessageToSetInRange(WorldPacket* data, float dist, bool self, bool own_team_only)
{
if (self)
GetSession()->SendPacket(data);
Trinity::MessageDistDeliverer notifier(this, data, dist, own_team_only);
VisitNearbyWorldObject(dist, notifier);
}
void Player::SendMessageToSet(WorldPacket* data, Player const* skipped_rcvr)
{
if (skipped_rcvr != this)
GetSession()->SendPacket(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);
VisitNearbyWorldObject(GetVisibilityRange(), notifier);
}
void Player::SendDirectMessage(WorldPacket* data)
{
m_session->SendPacket(data);
}
void Player::SendCinematicStart(uint32 CinematicSequenceId)
{
WorldPacket data(SMSG_TRIGGER_CINEMATIC, 4);
data << uint32(CinematicSequenceId);
SendDirectMessage(&data);
}
void Player::SendMovieStart(uint32 MovieId)
{
WorldPacket data(SMSG_TRIGGER_MOVIE, 4);
data << uint32(MovieId);
SendDirectMessage(&data);
}
void Player::CheckAreaExploreAndOutdoor()
{
if (!IsAlive())
return;
if (IsInFlight())
return;
bool isOutdoor;
uint16 areaFlag = GetBaseMap()->GetAreaFlag(GetPositionX(), GetPositionY(), GetPositionZ(), &isOutdoor);
if (sWorld->getBoolConfig(CONFIG_VMAP_INDOOR_CHECK) && !isOutdoor)
RemoveAurasWithAttribute(SPELL_ATTR0_OUTDOORS_ONLY);
if (areaFlag == 0xffff)
return;
int offset = areaFlag / 32;
if (offset >= PLAYER_EXPLORED_ZONES_SIZE)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Wrong area flag %u in map data for (X: %f Y: %f) point to field PLAYER_EXPLORED_ZONES_1 + %u ( %u must be < %u ).", areaFlag, GetPositionX(), GetPositionY(), offset, offset, PLAYER_EXPLORED_ZONES_SIZE);
return;
}
uint32 val = (uint32)(1 << (areaFlag % 32));
uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
if (!(currFields & val))
{
SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
AreaTableEntry const* areaEntry = GetAreaEntryByAreaFlagAndMap(areaFlag, GetMapId());
if (!areaEntry)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player %u discovered unknown area (x: %f y: %f z: %f map: %u", GetGUIDLow(), GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId());
return;
}
if (areaEntry->area_level > 0)
{
uint32 area = areaEntry->ID;
if (getLevel() >= sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL))
{
SendExplorationExperience(area, 0);
}
else
{
int32 diff = int32(getLevel()) - areaEntry->area_level;
uint32 XP = 0;
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 > 100)
exploration_percent = 100;
else if (exploration_percent < 0)
exploration_percent = 0;
XP = uint32(sObjectMgr->GetBaseXP(areaEntry->area_level)*exploration_percent/100*sWorld->getRate(RATE_XP_EXPLORE));
}
else
{
XP = uint32(sObjectMgr->GetBaseXP(areaEntry->area_level)*sWorld->getRate(RATE_XP_EXPLORE));
}
GiveXP(XP, NULL);
SendExplorationExperience(area, XP);
}
TC_LOG_INFO(LOG_FILTER_PLAYER, "Player %u discovered a new area: %u", GetGUIDLow(), area);
}
}
}
uint32 Player::TeamForRace(uint8 race)
{
if (ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race))
{
switch (rEntry->TeamID)
{
case 1: return HORDE;
case 7: return ALLIANCE;
}
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Race (%u) has wrong teamid (%u) in DBC: wrong DBC files?", uint32(race), rEntry->TeamID);
}
else
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Race (%u) 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:
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_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 && map->IsNonRaidDungeon())
if (LFGDungeonEntry const* dungeon = GetLFGDungeon(map->GetId(), map->GetDifficulty()))
if (dungeon->reclevel == 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 && current_reputation_rank1 <= Rep->ReputationMaxCap1)
GetReputationMgr().ModifyReputation(factionEntry1, donerep1);
}
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 && current_reputation_rank2 <= Rep->ReputationMaxCap2)
GetReputationMgr().ModifyReputation(factionEntry2, donerep2);
}
}
// 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)
{
if (!quest->RewardFactionId[i])
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->QuestRewFactionValue[field];
}
}
if (!rep)
continue;
if (quest->IsDaily())
rep = CalculateReputationGain(REPUTATION_SOURCE_DAILY_QUEST, GetQuestLevel(quest), rep, quest->RewardFactionId[i], noQuestBonus);
else if (quest->IsWeekly())
rep = CalculateReputationGain(REPUTATION_SOURCE_WEEKLY_QUEST, GetQuestLevel(quest), rep, quest->RewardFactionId[i], noQuestBonus);
else if (quest->IsMonthly())
rep = CalculateReputationGain(REPUTATION_SOURCE_MONTHLY_QUEST, GetQuestLevel(quest), rep, quest->RewardFactionId[i], noQuestBonus);
else
rep = CalculateReputationGain(REPUTATION_SOURCE_QUEST, GetQuestLevel(quest), rep, quest->RewardFactionId[i], noQuestBonus);
if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(quest->RewardFactionId[i]))
GetReputationMgr().ModifyReputation(factionEntry, rep);
}
}
void Player::UpdateHonorFields()
{
/// called when rewarding honor and at each save
time_t now = time_t(time(NULL));
time_t today = time_t(time(NULL) / 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 Tokenizer
if (HasAura(SPELL_AURA_PLAYER_INACTIVE))
return false;
uint64 victim_guid = 0;
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::bit_index
// Ranks:
// title[1..14] -> rank[5..18]
// title[15..28] -> rank[5..18]
// title[other] -> 0
if (victim_title == 0)
victim_guid = 0; // 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 = 0; // Don't show HK: <rank> message, only log.
honor_f = 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);
}
else
{
if (!victim->ToCreature()->IsRacialLeader())
return false;
honor_f = 100.0f; // ??? need more info
victim_rank = 19; // HK: Leader
}
}
if (victim != NULL)
{
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 << uint64(victim_guid);
data << uint32(victim_rank);
GetSession()->SendPacket(&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() && !HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP))
|| (MapType == 2 && !HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP))
|| (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, SQLTransaction* trans /*=NULL*/)
{
int32 newValue = int32(GetHonorPoints()) + value;
if (newValue < 0)
newValue = 0;
SetHonorPoints(uint32(newValue));
if (trans && !trans->null())
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UDP_CHAR_HONOR_POINTS);
stmt->setUInt32(0, newValue);
stmt->setUInt32(1, GetGUIDLow());
(*trans)->Append(stmt);
}
}
void Player::ModifyArenaPoints(int32 value, SQLTransaction* trans /*=NULL*/)
{
int32 newValue = int32(GetArenaPoints()) + value;
if (newValue < 0)
newValue = 0;
SetArenaPoints(uint32(newValue));
if (trans && !trans->null())
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UDP_CHAR_ARENA_POINTS);
stmt->setUInt32(0, newValue);
stmt->setUInt32(1, GetGUIDLow());
(*trans)->Append(stmt);
}
}
uint32 Player::GetGuildIdFromDB(uint64 guid)
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_GUILD_MEMBER);
stmt->setUInt32(0, GUID_LOPART(guid));
PreparedQueryResult result = CharacterDatabase.Query(stmt);
if (!result)
return 0;
uint32 id = result->Fetch()[0].GetUInt32();
return id;
}
uint8 Player::GetRankFromDB(uint64 guid)
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_GUILD_MEMBER);
stmt->setUInt32(0, GUID_LOPART(guid));
PreparedQueryResult result = CharacterDatabase.Query(stmt);
if (result)
{
uint32 v = result->Fetch()[1].GetUInt8();
return v;
}
else
return 0;
}
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::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_ARENA_TEAM_ID_BY_PLAYER_GUID);
stmt->setUInt32(0, GUID_LOPART(guid));
stmt->setUInt8(1, type);
PreparedQueryResult result = CharacterDatabase.Query(stmt);
if (!result)
return 0;
uint32 id = (*result)[0].GetUInt32();
return id;
}
uint32 Player::GetZoneIdFromDB(uint64 guid)
{
uint32 guidLow = GUID_LOPART(guid);
PreparedStatement* 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);
PreparedQueryResult 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(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;
}
uint32 Player::GetLevelFromDB(uint64 guid)
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_LEVEL);
stmt->setUInt32(0, GUID_LOPART(guid));
PreparedQueryResult result = CharacterDatabase.Query(stmt);
if (!result)
return 0;
Field* fields = result->Fetch();
uint8 level = fields[0].GetUInt8();
return level;
}
void Player::UpdateArea(uint32 newArea)
{
// FFA_PVP flags are area and not zone id dependent
// so apply them accordingly
m_areaUpdateId = newArea;
AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
pvpInfo.IsInFFAPvPArea = area && (area->flags & AREA_FLAG_ARENA);
UpdatePvPState(true);
UpdateAreaDependentAuras(newArea);
// previously this was in UpdateZone (but after UpdateArea) so nothing will break
pvpInfo.IsInNoPvPArea = false;
if (area && area->IsSanctuary()) // in sanctuary
{
SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
pvpInfo.IsInNoPvPArea = true;
CombatStopWithPets();
}
else
RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
}
void Player::UpdateZone(uint32 newZone, uint32 newArea)
{
if (m_zoneUpdateId != newZone)
{
sOutdoorPvPMgr->HandlePlayerLeaveZone(this, m_zoneUpdateId);
sOutdoorPvPMgr->HandlePlayerEnterZone(this, newZone);
sBattlefieldMgr->HandlePlayerLeaveZone(this, m_zoneUpdateId);
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);
}
// group update
if (GetGroup())
SetGroupUpdateFlag(GROUP_UPDATE_FULL);
m_zoneUpdateId = newZone;
m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
// zone changed, so area changed as well, update it
UpdateArea(newArea);
AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
if (!zone)
return;
if (sWorld->getBoolConfig(CONFIG_WEATHER))
{
if (Weather* weather = WeatherMgr::FindWeather(zone->ID))
weather->SendWeatherUpdateToPlayer(this);
else
{
if (!WeatherMgr::AddWeather(zone->ID))
{
// send fine weather packet to remove old zone's weather
WeatherMgr::SendFineWeatherUpdateToPlayer(this);
}
}
}
sScriptMgr->OnPlayerUpdateZone(this, newZone, newArea);
// in PvP, any not controlled zone (except zone->team == 6, default case)
// in PvE, only opposition team capital
switch (zone->team)
{
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())
{
SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
SetRestType(REST_TYPE_IN_CITY);
InnEnter(time(0), GetMapId(), 0, 0, 0);
}
pvpInfo.IsInNoPvPArea = true;
}
else
{
if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
{
if (GetRestType() == REST_TYPE_IN_TAVERN) // Still inside a tavern or has recently left
{
// Remove rest state if we have recently left a tavern.
if (GetMapId() != GetInnPosMapId() || GetExactDist(GetInnPosX(), GetInnPosY(), GetInnPosZ()) > 1.0f)
{
RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
SetRestType(REST_TYPE_NO);
}
}
else // Recently left a capital city
{
RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
SetRestType(REST_TYPE_NO);
}
}
}
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);
}
//If players are too far away from the duel flag... they lose the duel
void Player::CheckDuelDistance(time_t currTime)
{
if (!duel)
return;
uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
GameObject* obj = GetMap()->GetGameObject(duelFlagGUID);
if (!obj)
return;
if (duel->outOfBound == 0)
{
if (!IsWithinDistInMap(obj, 50))
{
duel->outOfBound = currTime;
WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
GetSession()->SendPacket(&data);
}
}
else
{
if (IsWithinDistInMap(obj, 40))
{
duel->outOfBound = 0;
WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
GetSession()->SendPacket(&data);
}
else if (currTime >= (duel->outOfBound+10))
DuelComplete(DUEL_FLED);
}
}
bool Player::IsOutdoorPvPActive()
{
return IsAlive() && !HasInvisibilityAura() && !HasStealthAura() && IsPvP() && !HasUnitMovementFlag(MOVEMENTFLAG_FLYING) && !IsInFlight();
}
void Player::DuelComplete(DuelCompleteType type)
{
// duel not requested
if (!duel)
return;
TC_LOG_DEBUG(LOG_FILTER_UNITS, "Duel Complete %s %s", GetName().c_str(), duel->opponent->GetName().c_str());
WorldPacket data(SMSG_DUEL_COMPLETE, (1));
data << (uint8)((type != DUEL_INTERRUPTED) ? 1 : 0);
GetSession()->SendPacket(&data);
if (duel->opponent->GetSession())
duel->opponent->GetSession()->SendPacket(&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 << duel->opponent->GetName();
data << GetName();
SendMessageToSet(&data, true);
}
sScriptMgr->OnPlayerDuelEnd(duel->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 (duel->initiator->GetTeam() == duel->opponent->GetTeam())
{
duel->initiator->AttackStop();
duel->opponent->AttackStop();
}
else
{
if (!duel->initiator->IsPvP())
duel->initiator->AttackStop();
if (!duel->opponent->IsPvP())
duel->opponent->AttackStop();
}
break;
case DUEL_WON:
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL, 1);
duel->opponent->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL, 1);
// Credit for quest Death's Challenge
if (getClass() == CLASS_DEATH_KNIGHT && duel->opponent->GetQuestStatus(12733) == QUEST_STATUS_INCOMPLETE)
duel->opponent->CastSpell(duel->opponent, 52994, true);
// Honor points after duel (the winner) - ImpConfig
if (uint32 amount = sWorld->getIntConfig(CONFIG_HONOR_AFTER_DUEL))
duel->opponent->RewardHonor(NULL, 1, amount);
break;
default:
break;
}
// Victory emote spell
if (type != DUEL_INTERRUPTED)
duel->opponent->CastSpell(duel->opponent, 52852, true);
//Remove Duel Flag object
GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
if (obj)
duel->initiator->RemoveGameObject(obj, true);
/* remove auras */
AuraApplicationMap &itsAuras = duel->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)
duel->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() == duel->opponent->GetGUID() && aura->GetApplyTime() >= duel->startTime)
RemoveAura(i);
else
++i;
}
// cleanup combo points
if (GetComboTarget() == duel->opponent->GetGUID())
ClearComboPoints();
else if (GetComboTarget() == duel->opponent->GetPetGUID())
ClearComboPoints();
if (duel->opponent->GetComboTarget() == GetGUID())
duel->opponent->ClearComboPoints();
else if (duel->opponent->GetComboTarget() == GetPetGUID())
duel->opponent->ClearComboPoints();
//cleanups
SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
SetUInt32Value(PLAYER_DUEL_TEAM, 0);
duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
delete duel->opponent->duel;
duel->opponent->duel = NULL;
delete duel;
duel = NULL;
}
//---------------------------------------------------------//
void Player::_ApplyItemMods(Item* item, uint8 slot, bool apply)
{
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_INFO(LOG_FILTER_PLAYER_ITEMS, "applying mods for item %u ", item->GetGUIDLow());
uint8 attacktype = Player::GetAttackBySlot(slot);
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);
if (attacktype < MAX_ATTACK)
_ApplyWeaponDependentAuraMods(item, WeaponAttackType(attacktype), apply);
_ApplyItemBonuses(proto, slot, apply);
if (slot == EQUIPMENT_SLOT_RANGED)
_ApplyAmmoBonuses();
ApplyItemEquipSpell(item, apply);
ApplyEnchantment(item, apply);
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "_ApplyItemMods complete.");
}
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 = proto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution) : NULL;
if (only_level_scale && !ssd)
return;
// req. check at equip, but allow use for extended range if range limit max level, set proper level
uint32 ssd_level = getLevel();
if (ssd && ssd_level > ssd->MaxLevel)
ssd_level = ssd->MaxLevel;
ScalingStatValuesEntry const* ssv = proto->ScalingStatValue ? sScalingStatValuesStore.LookupEntry(ssd_level) : NULL;
if (only_level_scale && !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->StatMod[i] < 0)
continue;
statType = ssd->StatMod[i];
val = (ssv->getssdMultiplier(proto->ScalingStatValue) * ssd->Modifier[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:
HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
break;
case ITEM_MOD_HEALTH: // modify HP
HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
break;
case ITEM_MOD_AGILITY: // modify agility
HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
break;
case ITEM_MOD_STRENGTH: //modify strength
HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
break;
case ITEM_MOD_INTELLECT: //modify intellect
HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
break;
case ITEM_MOD_SPIRIT: //modify spirit
HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
break;
case ITEM_MOD_STAMINA: //modify stamina
HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
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:
HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), apply);
HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
break;
case ITEM_MOD_RANGED_ATTACK_POWER:
HandleStatModifier(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:
HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, 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)
{
UnitModifierType 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;
}
}
HandleStatModifier(UNIT_MOD_ARMOR, modType, float(armor), apply);
}
// Add armor bonus from ArmorDamageModifier if > 0
if (proto->ArmorDamageModifier > 0)
HandleStatModifier(UNIT_MOD_ARMOR, TOTAL_VALUE, float(proto->ArmorDamageModifier), apply);
if (proto->Block)
HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
if (proto->HolyRes)
HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
if (proto->FireRes)
HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
if (proto->NatureRes)
HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
if (proto->FrostRes)
HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
if (proto->ShadowRes)
HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
if (proto->ArcaneRes)
HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
WeaponAttackType attType = BASE_ATTACK;
if (slot == EQUIPMENT_SLOT_RANGED && (
proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
proto->InventoryType == INVTYPE_RANGEDRIGHT))
{
attType = RANGED_ATTACK;
}
else if (slot == EQUIPMENT_SLOT_OFFHAND)
{
attType = OFF_ATTACK;
}
if (CanUseAttackType(attType))
_ApplyWeaponDamage(slot, proto, ssv, 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, ScalingStatValuesEntry const* ssv, bool apply)
{
WeaponAttackType attType = BASE_ATTACK;
float damage = 0.0f;
if (slot == EQUIPMENT_SLOT_RANGED && (
proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
proto->InventoryType == INVTYPE_RANGEDRIGHT))
{
attType = RANGED_ATTACK;
}
else if (slot == EQUIPMENT_SLOT_OFFHAND)
{
attType = OFF_ATTACK;
}
float minDamage = proto->Damage[0].DamageMin;
float maxDamage = proto->Damage[0].DamageMax;
// If set dpsMod in ScalingStatValue use it for min (70% from average), max (130% from average) damage
if (ssv)
{
int32 extraDPS = ssv->getDPSMod(proto->ScalingStatValue);
if (extraDPS)
{
float average = extraDPS * proto->Delay / 1000.0f;
minDamage = 0.7f * average;
maxDamage = 1.3f * average;
}
}
if (minDamage > 0)
{
damage = apply ? minDamage : BASE_MINDAMAGE;
SetBaseWeaponDamage(attType, MINDAMAGE, damage);
}
if (maxDamage > 0)
{
damage = apply ? maxDamage : BASE_MAXDAMAGE;
SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
}
if (proto->Delay && !IsInFeralForm())
{
if (slot == EQUIPMENT_SLOT_RANGED)
SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
else if (slot == EQUIPMENT_SLOT_MAINHAND)
SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
else if (slot == EQUIPMENT_SLOT_OFFHAND)
SetAttackTime(OFF_ATTACK, 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() && (damage || proto->Delay))
UpdateDamagePhysical(attType);
}
void Player::_ApplyWeaponDependentAuraMods(Item* item, WeaponAttackType attackType, bool apply)
{
AuraEffectList const& auraCritList = GetAuraEffectsByType(SPELL_AURA_MOD_WEAPON_CRIT_PERCENT);
for (AuraEffectList::const_iterator itr = auraCritList.begin(); itr != auraCritList.end(); ++itr)
_ApplyWeaponDependentAuraCritMod(item, attackType, *itr, apply);
AuraEffectList const& auraDamageFlatList = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE);
for (AuraEffectList::const_iterator itr = auraDamageFlatList.begin(); itr != auraDamageFlatList.end(); ++itr)
_ApplyWeaponDependentAuraDamageMod(item, attackType, *itr, apply);
AuraEffectList const& auraDamagePctList = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
for (AuraEffectList::const_iterator itr = auraDamagePctList.begin(); itr != auraDamagePctList.end(); ++itr)
_ApplyWeaponDependentAuraDamageMod(item, attackType, *itr, apply);
}
void Player::_ApplyWeaponDependentAuraCritMod(Item* item, WeaponAttackType attackType, AuraEffect const* aura, bool apply)
{
// don't apply mod if item is broken or cannot be used
if (item->IsBroken() || !CanUseAttackType(attackType))
return;
// generic not weapon specific case processes in aura code
if (aura->GetSpellInfo()->EquippedItemClass == -1)
return;
BaseModGroup mod = BASEMOD_END;
switch (attackType)
{
case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
default: return;
}
if (item->IsFitToSpellRequirements(aura->GetSpellInfo()))
HandleBaseModValue(mod, FLAT_MOD, float (aura->GetAmount()), apply);
}
void Player::_ApplyWeaponDependentAuraDamageMod(Item* item, WeaponAttackType attackType, AuraEffect const* aura, bool apply)
{
// don't apply mod if item is broken or cannot be used
if (item->IsBroken() || !CanUseAttackType(attackType))
return;
// ignore spell mods for not wands
if ((aura->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL) == 0 && (getClassMask() & CLASSMASK_WAND_USERS) == 0)
return;
// generic not weapon specific case processes in aura code
if (aura->GetSpellInfo()->EquippedItemClass == -1)
return;
UnitMods unitMod = UNIT_MOD_END;
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: return;
}
UnitModifierType unitModType = TOTAL_VALUE;
switch (aura->GetAuraType())
{
case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
default: return;
}
if (item->IsFitToSpellRequirements(aura->GetSpellInfo()))
{
HandleStatModifier(unitMod, unitModType, float(aura->GetAmount()), apply);
if (unitModType == TOTAL_VALUE)
ApplyModUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS, aura->GetAmount(), apply);
}
}
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)
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(LOG_FILTER_PLAYER, "WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
CastSpell(this, spellInfo, true, 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, NULL, false, true); // remove spells that not fit to form
ApplyEquipSpell(spellInfo, NULL, true, true); // add spells that fit form but not active
}
}
}
void Player::CastItemCombatSpell(Unit* target, WeaponAttackType attType, uint32 procVictim, uint32 procEx)
{
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(attType))
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 (attType)
{
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 (attType == BASE_ATTACK)
if (!IsUseEquipedWeapon(true) && !IsInFeralForm())
continue;
}
CastItemCombatSpell(target, attType, procVictim, procEx, item, proto);
}
}
}
void Player::CastItemCombatSpell(Unit* target, WeaponAttackType attType, uint32 procVictim, uint32 procEx, Item* item, ItemTemplate const* proto)
{
// Can do effect if any damage done to target
if (procVictim & PROC_FLAG_TAKEN_DAMAGE)
//if (damageInfo->procVictim & PROC_FLAG_TAKEN_ANY_DAMAGE)
{
for (uint8 i = 0; i < MAX_ITEM_SPELLS; ++i)
{
_Spell const& spellData = proto->Spells[i];
// no spell
if (!spellData.SpellId)
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(LOG_FILTER_PLAYER_ITEMS, "WORLD: unknown Item spellid %i", spellData.SpellId);
continue;
}
// not allow proc extra attack spell at extra attack
if (m_extraAttacks && spellInfo->HasEffect(SPELL_EFFECT_ADD_EXTRA_ATTACKS))
return;
float chance = (float)spellInfo->ProcChance;
if (spellData.SpellPPMRate)
{
uint32 WeaponSpeed = GetAttackTime(attType);
chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate, spellInfo);
}
else if (chance > 100.0f)
chance = GetWeaponProcChance();
if (roll_chance_f(chance))
CastSpell(target, spellInfo->Id, true, 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->type[s] != ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
continue;
SpellEnchantProcEntry const* entry = sSpellMgr->GetSpellEnchantProcEvent(enchant_id);
if (entry && entry->procEx)
{
// Check hit/crit/dodge/parry requirement
if ((entry->procEx & procEx) == 0)
continue;
}
else
{
// Can do effect if any damage done to target
if (!(procVictim & PROC_FLAG_TAKEN_DAMAGE))
//if (!(damageInfo->procVictim & PROC_FLAG_TAKEN_ANY_DAMAGE))
continue;
}
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(pEnchant->spellid[s]);
if (!spellInfo)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER_ITEMS, "Player::CastItemCombatSpell(GUID: %u, name: %s, enchant: %i): unknown spell %i is casted, ignoring...",
GetGUIDLow(), GetName().c_str(), pEnchant->ID, pEnchant->spellid[s]);
continue;
}
float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
if (entry)
{
if (entry->PPMChance)
chance = GetPPMProcChance(proto->Delay, entry->PPMChance, spellInfo);
else if (entry->customChance)
chance = (float)entry->customChance;
}
// Apply spell mods
ApplySpellMod(pEnchant->spellid[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))
{
if (spellInfo->IsPositive())
CastSpell(this, spellInfo, true, item);
else
CastSpell(target, spellInfo, true, item);
}
}
}
}
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(LOG_FILTER_PLAYER, "Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ", proto->ItemId, learn_spell_id);
SendEquipError(EQUIP_ERR_NONE, item, NULL);
return;
}
Spell* spell = new Spell(this, spellInfo, TRIGGERED_NONE);
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;
}
// use triggered flag only for items with many spell casts and for not first cast
uint8 count = 0;
// item spells casted at use
for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
{
_Spell const& spellData = proto->Spells[i];
// no spell
if (!spellData.SpellId)
continue;
// wrong triggering type
if (spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
continue;
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellData.SpellId);
if (!spellInfo)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring", proto->ItemId, spellData.SpellId);
continue;
}
Spell* spell = new Spell(this, spellInfo, (count > 0) ? TRIGGERED_FULL_MASK : TRIGGERED_NONE);
spell->m_CastItem = item;
spell->m_cast_count = cast_count; // set count of casts
spell->m_glyphIndex = glyphIndex; // glyph index
spell->prepare(&targets);
++count;
}
// Item enchantments spells casted 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->type[s] != ITEM_ENCHANTMENT_TYPE_USE_SPELL)
continue;
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(pEnchant->spellid[s]);
if (!spellInfo)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
continue;
}
Spell* spell = new Spell(this, spellInfo, (count > 0) ? TRIGGERED_FULL_MASK : TRIGGERED_NONE);
spell->m_CastItem = item;
spell->m_cast_count = cast_count; // set count of casts
spell->m_glyphIndex = glyphIndex; // glyph index
spell->prepare(&targets);
++count;
}
}
}
void Player::_RemoveAllItemMods()
{
TC_LOG_DEBUG(LOG_FILTER_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;
uint32 attacktype = Player::GetAttackBySlot(i);
if (attacktype < MAX_ATTACK)
_ApplyWeaponDependentAuraMods(m_items[i], WeaponAttackType(attacktype), false);
_ApplyItemBonuses(proto, i, false);
if (i == EQUIPMENT_SLOT_RANGED)
_ApplyAmmoBonuses();
}
}
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "_RemoveAllItemMods complete.");
}
void Player::_ApplyAllItemMods()
{
TC_LOG_DEBUG(LOG_FILTER_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;
uint32 attacktype = Player::GetAttackBySlot(i);
if (attacktype < MAX_ATTACK)
_ApplyWeaponDependentAuraMods(m_items[i], WeaponAttackType(attacktype), true);
_ApplyItemBonuses(proto, i, true);
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(LOG_FILTER_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(const ItemTemplate* 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 (!GetBattlegroundId())
return;
// If not released spirit, do it !
if (m_deathTimer > 0)
{
m_deathTimer = 0;
BuildPlayerRepop();
RepopAtGraveyard();
}
// 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 = sObjectAccessor->ConvertCorpseForPlayer(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(uint64 guid)
{
WorldPacket data(SMSG_LOOT_RELEASE_RESPONSE, (8+1));
data << uint64(guid) << uint8(1);
SendDirectMessage(&data);
}
void Player::SendLoot(uint64 guid, LootType loot_type)
{
if (uint64 lguid = GetLootGUID())
m_session->DoLootRelease(lguid);
Loot* loot = 0;
PermissionTypes permission = ALL_PERMISSION;
TC_LOG_DEBUG(LOG_FILTER_LOOT, "Player::SendLoot");
if (IS_GAMEOBJECT_GUID(guid))
{
TC_LOG_DEBUG(LOG_FILTER_LOOT, "IS_GAMEOBJECT_GUID(guid)");
GameObject* go = GetMap()->GetGameObject(guid);
// 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 || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this, INTERACTION_DISTANCE)) || (loot_type == LOOT_CORPSE && go->GetRespawnTime() && go->isSpawnedByDefault()))
{
SendLootRelease(guid);
return;
}
loot = &go->loot;
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());
// get next RR player (for next loot)
if (groupRules)
group->UpdateLooterGuid(go);
}
if (loot_type == LOOT_FISHING)
go->getFishLoot(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 = MASTER_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 (IS_ITEM_GUID(guid))
{
Item* item = GetItemByGuid(guid);
if (!item)
{
SendLootRelease(guid);
return;
}
permission = OWNER_PERMISSION;
loot = &item->loot;
// 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 && !item->ItemContainerLoadLootFromDB())
{
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)
item->ItemContainerSaveLootToDB();
break;
}
}
}
else if (IS_CORPSE_GUID(guid)) // 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 (!bones->lootForBody)
{
bones->lootForBody = true;
uint32 pLevel = bones->loot.gold;
bones->loot.clear();
if (Battleground* bg = GetBattleground())
if (bg->GetTypeID(true) == BATTLEGROUND_AV)
loot->FillLoot(1, 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 * 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 (!creature->lootForPickPocketed)
{
creature->lootForPickPocketed = true;
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
{
// the player whose group may loot the corpse
Player* recipient = creature->GetLootRecipient();
if (!recipient)
return;
if (!creature->lootForBody)
{
creature->lootForBody = true;
// for creature, loot is filled when creature is killed.
if (Group* group = recipient->GetGroup())
{
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;
}
}
}
// possible only if creature->lootForBody && loot->empty() at spell cast check
if (loot_type == LOOT_SKINNING)
{
loot->clear();
loot->FillLoot(creature->GetCreatureTemplate()->SkinLootId, LootTemplates_Skinning, this, true);
permission = OWNER_PERMISSION;
}
// set group rights only for loot_type != LOOT_SKINNING
else
{
if (Group* group = GetGroup())
{
if (group == recipient->GetGroup())
{
switch (group->GetLootMethod())
{
case MASTER_LOOT:
permission = MASTER_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 (recipient == this)
permission = OWNER_PERMISSION;
else
permission = NONE_PERMISSION;
}
}
}
SetLootGUID(guid);
// 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;
default: break;
}
// need know merged fishing/corpse loot type for achievements
loot->loot_type = loot_type;
WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
data << uint64(guid);
data << uint8(loot_type);
data << LootView(*loot, this, permission);
SendDirectMessage(&data);
// add 'this' player as one of the players that are looting 'loot'
if (permission != NONE_PERMISSION)
loot->AddLooter(GetGUID());
if (loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid))
SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
}
void Player::SendNotifyLootMoneyRemoved()
{
WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
GetSession()->SendPacket(&data);
}
void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
{
WorldPacket data(SMSG_LOOT_REMOVED, 1);
data << uint8(lootSlot);
GetSession()->SendPacket(&data);
}
void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
{
WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
data << Field;
data << Value;
GetSession()->SendPacket(&data);
}
void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid)
{
// data depends on zoneid/mapid...
Battleground* bg = GetBattleground();
uint32 mapid = GetMapId();
OutdoorPvP* pvp = sOutdoorPvPMgr->GetOutdoorPvPToZoneId(zoneid);
InstanceScript* instance = GetInstanceScript();
Battlefield* bf = sBattlefieldMgr->GetBattlefieldToZoneId(zoneid);
TC_LOG_DEBUG(LOG_FILTER_NETWORKIO, "Sending SMSG_INIT_WORLD_STATES to Map: %u, Zone: %u", mapid, zoneid);
WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(12*8)));
data << uint32(mapid); // mapid
data << uint32(zoneid); // zone id
data << uint32(areaid); // area id, new 2.1.0
size_t countPos = data.wpos();
data << uint16(0); // count of uint64 blocks
data << uint32(0x8d8) << uint32(0x0); // 1
data << uint32(0x8d7) << uint32(0x0); // 2
data << uint32(0x8d6) << uint32(0x0); // 3
data << uint32(0x8d5) << uint32(0x0); // 4
data << uint32(0x8d4) << uint32(0x0); // 5
data << uint32(0x8d3) << uint32(0x0); // 6
// 7 1 - Arena season in progress, 0 - end of season
data << uint32(0xC77) << uint32(sWorld->getBoolConfig(CONFIG_ARENA_SEASON_IN_PROGRESS));
// 8 Arena season id
data << uint32(0xF3D) << uint32(sWorld->getIntConfig(CONFIG_ARENA_SEASON_ID));
if (mapid == 530) // Outland
{
data << uint32(0x9bf) << uint32(0x0); // 7
data << uint32(0x9bd) << uint32(0xF); // 8
data << uint32(0x9bb) << uint32(0xF); // 9
}
// insert <field> <value>
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 (pvp && pvp->GetTypeId() == OUTDOOR_PVP_EP)
pvp->FillInitialWorldStates(data);
else
{
data << uint32(0x97a) << uint32(0x0); // 10 2426
data << uint32(0x917) << uint32(0x0); // 11 2327
data << uint32(0x918) << uint32(0x0); // 12 2328
data << uint32(0x97b) << uint32(0x32); // 13 2427
data << uint32(0x97c) << uint32(0x32); // 14 2428
data << uint32(0x933) << uint32(0x1); // 15 2355
data << uint32(0x946) << uint32(0x0); // 16 2374
data << uint32(0x947) << uint32(0x0); // 17 2375
data << uint32(0x948) << uint32(0x0); // 18 2376
data << uint32(0x949) << uint32(0x0); // 19 2377
data << uint32(0x94a) << uint32(0x0); // 20 2378
data << uint32(0x94b) << uint32(0x0); // 21 2379
data << uint32(0x932) << uint32(0x0); // 22 2354
data << uint32(0x934) << uint32(0x0); // 23 2356
data << uint32(0x935) << uint32(0x0); // 24 2357
data << uint32(0x936) << uint32(0x0); // 25 2358
data << uint32(0x937) << uint32(0x0); // 26 2359
data << uint32(0x938) << uint32(0x0); // 27 2360
data << uint32(0x939) << uint32(0x1); // 28 2361
data << uint32(0x930) << uint32(0x1); // 29 2352
data << uint32(0x93a) << uint32(0x0); // 30 2362
data << uint32(0x93b) << uint32(0x0); // 31 2363
data << uint32(0x93c) << uint32(0x0); // 32 2364
data << uint32(0x93d) << uint32(0x0); // 33 2365
data << uint32(0x944) << uint32(0x0); // 34 2372
data << uint32(0x945) << uint32(0x0); // 35 2373
data << uint32(0x931) << uint32(0x1); // 36 2353
data << uint32(0x93e) << uint32(0x0); // 37 2366
data << uint32(0x931) << uint32(0x1); // 38 2367 ?? grey horde not in dbc! send for consistency's sake, and to match field count
data << uint32(0x940) << uint32(0x0); // 39 2368
data << uint32(0x941) << uint32(0x0); // 7 2369
data << uint32(0x942) << uint32(0x0); // 8 2370
data << uint32(0x943) << uint32(0x0); // 9 2371
}
break;
case 1377: // Silithus
if (pvp && pvp->GetTypeId() == OUTDOOR_PVP_SI)
pvp->FillInitialWorldStates(data);
else
{
// states are always shown
data << uint32(2313) << uint32(0x0); // 7 ally silityst gathered
data << uint32(2314) << uint32(0x0); // 8 horde silityst gathered
data << uint32(2317) << uint32(0x0); // 9 max silithyst
}
// dunno about these... aq opening event maybe?
data << uint32(2322) << uint32(0x0); // 10 sandworm N
data << uint32(2323) << uint32(0x0); // 11 sandworm S
data << uint32(2324) << uint32(0x0); // 12 sandworm SW
data << uint32(2325) << uint32(0x0); // 13 sandworm E
break;
case 2597: // Alterac Valley
if (bg && bg->GetTypeID(true) == BATTLEGROUND_AV)
bg->FillInitialWorldStates(data);
else
{
data << uint32(0x7ae) << uint32(0x1); // 7 snowfall n
data << uint32(0x532) << uint32(0x1); // 8 frostwolfhut hc
data << uint32(0x531) << uint32(0x0); // 9 frostwolfhut ac
data << uint32(0x52e) << uint32(0x0); // 10 stormpike firstaid a_a
data << uint32(0x571) << uint32(0x0); // 11 east frostwolf tower horde assaulted -unused
data << uint32(0x570) << uint32(0x0); // 12 west frostwolf tower horde assaulted - unused
data << uint32(0x567) << uint32(0x1); // 13 frostwolfe c
data << uint32(0x566) << uint32(0x1); // 14 frostwolfw c
data << uint32(0x550) << uint32(0x1); // 15 irondeep (N) ally
data << uint32(0x544) << uint32(0x0); // 16 ice grave a_a
data << uint32(0x536) << uint32(0x0); // 17 stormpike grave h_c
data << uint32(0x535) << uint32(0x1); // 18 stormpike grave a_c
data << uint32(0x518) << uint32(0x0); // 19 stoneheart grave a_a
data << uint32(0x517) << uint32(0x0); // 20 stoneheart grave h_a
data << uint32(0x574) << uint32(0x0); // 21 1396 unk
data << uint32(0x573) << uint32(0x0); // 22 iceblood tower horde assaulted -unused
data << uint32(0x572) << uint32(0x0); // 23 towerpoint horde assaulted - unused
data << uint32(0x56f) << uint32(0x0); // 24 1391 unk
data << uint32(0x56e) << uint32(0x0); // 25 iceblood a
data << uint32(0x56d) << uint32(0x0); // 26 towerp a
data << uint32(0x56c) << uint32(0x0); // 27 frostwolfe a
data << uint32(0x56b) << uint32(0x0); // 28 froswolfw a
data << uint32(0x56a) << uint32(0x1); // 29 1386 unk
data << uint32(0x569) << uint32(0x1); // 30 iceblood c
data << uint32(0x568) << uint32(0x1); // 31 towerp c
data << uint32(0x565) << uint32(0x0); // 32 stoneh tower a
data << uint32(0x564) << uint32(0x0); // 33 icewing tower a
data << uint32(0x563) << uint32(0x0); // 34 dunn a
data << uint32(0x562) << uint32(0x0); // 35 duns a
data << uint32(0x561) << uint32(0x0); // 36 stoneheart bunker alliance assaulted - unused
data << uint32(0x560) << uint32(0x0); // 37 icewing bunker alliance assaulted - unused
data << uint32(0x55f) << uint32(0x0); // 38 dunbaldar south alliance assaulted - unused
data << uint32(0x55e) << uint32(0x0); // 39 dunbaldar north alliance assaulted - unused
data << uint32(0x55d) << uint32(0x0); // 40 stone tower d
data << uint32(0x3c6) << uint32(0x0); // 41 966 unk
data << uint32(0x3c4) << uint32(0x0); // 42 964 unk
data << uint32(0x3c2) << uint32(0x0); // 43 962 unk
data << uint32(0x516) << uint32(0x1); // 44 stoneheart grave a_c
data << uint32(0x515) << uint32(0x0); // 45 stonheart grave h_c
data << uint32(0x3b6) << uint32(0x0); // 46 950 unk
data << uint32(0x55c) << uint32(0x0); // 47 icewing tower d
data << uint32(0x55b) << uint32(0x0); // 48 dunn d
data << uint32(0x55a) << uint32(0x0); // 49 duns d
data << uint32(0x559) << uint32(0x0); // 50 1369 unk
data << uint32(0x558) << uint32(0x0); // 51 iceblood d
data << uint32(0x557) << uint32(0x0); // 52 towerp d
data << uint32(0x556) << uint32(0x0); // 53 frostwolfe d
data << uint32(0x555) << uint32(0x0); // 54 frostwolfw d
data << uint32(0x554) << uint32(0x1); // 55 stoneh tower c
data << uint32(0x553) << uint32(0x1); // 56 icewing tower c
data << uint32(0x552) << uint32(0x1); // 57 dunn c
data << uint32(0x551) << uint32(0x1); // 58 duns c
data << uint32(0x54f) << uint32(0x0); // 59 irondeep (N) horde
data << uint32(0x54e) << uint32(0x0); // 60 irondeep (N) ally
data << uint32(0x54d) << uint32(0x1); // 61 mine (S) neutral
data << uint32(0x54c) << uint32(0x0); // 62 mine (S) horde
data << uint32(0x54b) << uint32(0x0); // 63 mine (S) ally
data << uint32(0x545) << uint32(0x0); // 64 iceblood h_a
data << uint32(0x543) << uint32(0x1); // 65 iceblod h_c
data << uint32(0x542) << uint32(0x0); // 66 iceblood a_c
data << uint32(0x540) << uint32(0x0); // 67 snowfall h_a
data << uint32(0x53f) << uint32(0x0); // 68 snowfall a_a
data << uint32(0x53e) << uint32(0x0); // 69 snowfall h_c
data << uint32(0x53d) << uint32(0x0); // 70 snowfall a_c
data << uint32(0x53c) << uint32(0x0); // 71 frostwolf g h_a
data << uint32(0x53b) << uint32(0x0); // 72 frostwolf g a_a
data << uint32(0x53a) << uint32(0x1); // 73 frostwolf g h_c
data << uint32(0x539) << uint32(0x0); // 74 frostwolf g a_c
data << uint32(0x538) << uint32(0x0); // 75 stormpike grave h_a
data << uint32(0x537) << uint32(0x0); // 76 stormpike grave a_a
data << uint32(0x534) << uint32(0x0); // 77 frostwolf hut h_a
data << uint32(0x533) << uint32(0x0); // 78 frostwolf hut a_a
data << uint32(0x530) << uint32(0x0); // 79 stormpike first aid h_a
data << uint32(0x52f) << uint32(0x0); // 80 stormpike first aid h_c
data << uint32(0x52d) << uint32(0x1); // 81 stormpike first aid a_c
}
break;
case 3277: // Warsong Gulch
if (bg && bg->GetTypeID(true) == BATTLEGROUND_WS)
bg->FillInitialWorldStates(data);
else
{
data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
}
break;
case 3358: // Arathi Basin
if (bg && bg->GetTypeID(true) == BATTLEGROUND_AB)
bg->FillInitialWorldStates(data);
else
{
data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
data << uint32(0x745) << uint32(0x2); // 37 1861 unk
data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
}
break;
case 3820: // Eye of the Storm
if (bg && bg->GetTypeID(true) == BATTLEGROUND_EY)
bg->FillInitialWorldStates(data);
else
{
data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
// and some more ... unknown
}
break;
// any of these needs change! the client remembers the prev setting!
// ON EVERY ZONE LEAVE, RESET THE OLD ZONE'S WORLD STATE, BUT AT LEAST THE UI STUFF!
case 3483: // Hellfire Peninsula
if (pvp && pvp->GetTypeId() == OUTDOOR_PVP_HP)
pvp->FillInitialWorldStates(data);
else
{
data << uint32(0x9ba) << uint32(0x1); // 10 // add ally tower main gui icon // maybe should be sent only on login?
data << uint32(0x9b9) << uint32(0x1); // 11 // add horde tower main gui icon // maybe should be sent only on login?
data << uint32(0x9b5) << uint32(0x0); // 12 // show neutral broken hill icon // 2485
data << uint32(0x9b4) << uint32(0x1); // 13 // show icon above broken hill // 2484
data << uint32(0x9b3) << uint32(0x0); // 14 // show ally broken hill icon // 2483
data << uint32(0x9b2) << uint32(0x0); // 15 // show neutral overlook icon // 2482
data << uint32(0x9b1) << uint32(0x1); // 16 // show the overlook arrow // 2481
data << uint32(0x9b0) << uint32(0x0); // 17 // show ally overlook icon // 2480
data << uint32(0x9ae) << uint32(0x0); // 18 // horde pvp objectives captured // 2478
data << uint32(0x9ac) << uint32(0x0); // 19 // ally pvp objectives captured // 2476
data << uint32(2475) << uint32(100); //: ally / horde slider grey area // show only in direct vicinity!
data << uint32(2474) << uint32(50); //: ally / horde slider percentage, 100 for ally, 0 for horde // show only in direct vicinity!
data << uint32(2473) << uint32(0); //: ally / horde slider display // show only in direct vicinity!
data << uint32(0x9a8) << uint32(0x0); // 20 // show the neutral stadium icon // 2472
data << uint32(0x9a7) << uint32(0x0); // 21 // show the ally stadium icon // 2471
data << uint32(0x9a6) << uint32(0x1); // 22 // show the horde stadium icon // 2470
}
break;
case 3518: // Nagrand
if (pvp && pvp->GetTypeId() == OUTDOOR_PVP_NA)
pvp->FillInitialWorldStates(data);
else
{
data << uint32(2503) << uint32(0x0); // 10
data << uint32(2502) << uint32(0x0); // 11
data << uint32(2493) << uint32(0x0); // 12
data << uint32(2491) << uint32(0x0); // 13
data << uint32(2495) << uint32(0x0); // 14
data << uint32(2494) << uint32(0x0); // 15
data << uint32(2497) << uint32(0x0); // 16
data << uint32(2762) << uint32(0x0); // 17
data << uint32(2662) << uint32(0x0); // 18
data << uint32(2663) << uint32(0x0); // 19
data << uint32(2664) << uint32(0x0); // 20
data << uint32(2760) << uint32(0x0); // 21
data << uint32(2670) << uint32(0x0); // 22
data << uint32(2668) << uint32(0x0); // 23
data << uint32(2669) << uint32(0x0); // 24
data << uint32(2761) << uint32(0x0); // 25
data << uint32(2667) << uint32(0x0); // 26
data << uint32(2665) << uint32(0x0); // 27
data << uint32(2666) << uint32(0x0); // 28
data << uint32(2763) << uint32(0x0); // 29
data << uint32(2659) << uint32(0x0); // 30
data << uint32(2660) << uint32(0x0); // 31
data << uint32(2661) << uint32(0x0); // 32
data << uint32(2671) << uint32(0x0); // 33
data << uint32(2676) << uint32(0x0); // 34
data << uint32(2677) << uint32(0x0); // 35
data << uint32(2672) << uint32(0x0); // 36
data << uint32(2673) << uint32(0x0); // 37
}
break;
case 3519: // Terokkar Forest
if (pvp && pvp->GetTypeId() == OUTDOOR_PVP_TF)
pvp->FillInitialWorldStates(data);
else
{
data << uint32(0xa41) << uint32(0x0); // 10 // 2625 capture bar pos
data << uint32(0xa40) << uint32(0x14); // 11 // 2624 capture bar neutral
data << uint32(0xa3f) << uint32(0x0); // 12 // 2623 show capture bar
data << uint32(0xa3e) << uint32(0x0); // 13 // 2622 horde towers controlled
data << uint32(0xa3d) << uint32(0x5); // 14 // 2621 ally towers controlled
data << uint32(0xa3c) << uint32(0x0); // 15 // 2620 show towers controlled
data << uint32(0xa88) << uint32(0x0); // 16 // 2696 SE Neu
data << uint32(0xa87) << uint32(0x0); // 17 // SE Horde
data << uint32(0xa86) << uint32(0x0); // 18 // SE Ally
data << uint32(0xa85) << uint32(0x0); // 19 //S Neu
data << uint32(0xa84) << uint32(0x0); // 20 S Horde
data << uint32(0xa83) << uint32(0x0); // 21 S Ally
data << uint32(0xa82) << uint32(0x0); // 22 NE Neu
data << uint32(0xa81) << uint32(0x0); // 23 NE Horde
data << uint32(0xa80) << uint32(0x0); // 24 NE Ally
data << uint32(0xa7e) << uint32(0x0); // 25 // 2686 N Neu
data << uint32(0xa7d) << uint32(0x0); // 26 N Horde
data << uint32(0xa7c) << uint32(0x0); // 27 N Ally
data << uint32(0xa7b) << uint32(0x0); // 28 NW Ally
data << uint32(0xa7a) << uint32(0x0); // 29 NW Horde
data << uint32(0xa79) << uint32(0x0); // 30 NW Neutral
data << uint32(0x9d0) << uint32(0x5); // 31 // 2512 locked time remaining seconds first digit
data << uint32(0x9ce) << uint32(0x0); // 32 // 2510 locked time remaining seconds second digit
data << uint32(0x9cd) << uint32(0x0); // 33 // 2509 locked time remaining minutes
data << uint32(0x9cc) << uint32(0x0); // 34 // 2508 neutral locked time show
data << uint32(0xad0) << uint32(0x0); // 35 // 2768 horde locked time show
data << uint32(0xacf) << uint32(0x1); // 36 // 2767 ally locked time show
}
break;
case 3521: // Zangarmarsh
if (pvp && pvp->GetTypeId() == OUTDOOR_PVP_ZM)
pvp->FillInitialWorldStates(data);
else
{
data << uint32(0x9e1) << uint32(0x0); // 10 //2529
data << uint32(0x9e0) << uint32(0x0); // 11
data << uint32(0x9df) << uint32(0x0); // 12
data << uint32(0xa5d) << uint32(0x1); // 13 //2653
data << uint32(0xa5c) << uint32(0x0); // 14 //2652 east beacon neutral
data << uint32(0xa5b) << uint32(0x1); // 15 horde
data << uint32(0xa5a) << uint32(0x0); // 16 ally
data << uint32(0xa59) << uint32(0x1); // 17 // 2649 Twin spire graveyard horde 12???
data << uint32(0xa58) << uint32(0x0); // 18 ally 14 ???
data << uint32(0xa57) << uint32(0x0); // 19 neutral 7???
data << uint32(0xa56) << uint32(0x0); // 20 // 2646 west beacon neutral
data << uint32(0xa55) << uint32(0x1); // 21 horde
data << uint32(0xa54) << uint32(0x0); // 22 ally
data << uint32(0x9e7) << uint32(0x0); // 23 // 2535
data << uint32(0x9e6) << uint32(0x0); // 24
data << uint32(0x9e5) << uint32(0x0); // 25
data << uint32(0xa00) << uint32(0x0); // 26 // 2560
data << uint32(0x9ff) << uint32(0x1); // 27
data << uint32(0x9fe) << uint32(0x0); // 28
data << uint32(0x9fd) << uint32(0x0); // 29
data << uint32(0x9fc) << uint32(0x1); // 30
data << uint32(0x9fb) << uint32(0x0); // 31
data << uint32(0xa62) << uint32(0x0); // 32 // 2658
data << uint32(0xa61) << uint32(0x1); // 33
data << uint32(0xa60) << uint32(0x1); // 34
data << uint32(0xa5f) << uint32(0x0); // 35
}
break;
case 3698: // Nagrand Arena
if (bg && bg->GetTypeID(true) == BATTLEGROUND_NA)
bg->FillInitialWorldStates(data);
else
{
data << uint32(0xa0f) << uint32(0x0); // 7
data << uint32(0xa10) << uint32(0x0); // 8
data << uint32(0xa11) << uint32(0x0); // 9 show
}
break;
case 3702: // Blade's Edge Arena
if (bg && bg->GetTypeID(true) == BATTLEGROUND_BE)
bg->FillInitialWorldStates(data);
else
{
data << uint32(0x9f0) << uint32(0x0); // 7 gold
data << uint32(0x9f1) << uint32(0x0); // 8 green
data << uint32(0x9f3) << uint32(0x0); // 9 show
}
break;
case 3968: // Ruins of Lordaeron
if (bg && bg->GetTypeID(true) == BATTLEGROUND_RL)
bg->FillInitialWorldStates(data);
else
{
data << uint32(0xbb8) << uint32(0x0); // 7 gold
data << uint32(0xbb9) << uint32(0x0); // 8 green
data << uint32(0xbba) << uint32(0x0); // 9 show
}
break;
case 4378: // Dalaran Sewers
if (bg && bg->GetTypeID(true) == BATTLEGROUND_DS)
bg->FillInitialWorldStates(data);
else
{
data << uint32(3601) << uint32(0x0); // 7 gold
data << uint32(3600) << uint32(0x0); // 8 green
data << uint32(3610) << uint32(0x0); // 9 show
}
break;
case 4384: // Strand of the Ancients
if (bg && bg->GetTypeID(true) == BATTLEGROUND_SA)
bg->FillInitialWorldStates(data);
else
{
// 1-3 A defend, 4-6 H defend, 7-9 unk defend, 1 - ok, 2 - half destroyed, 3 - destroyed
data << uint32(0xf09) << uint32(0x0); // 7 3849 Gate of Temple
data << uint32(0xe36) << uint32(0x0); // 8 3638 Gate of Yellow Moon
data << uint32(0xe27) << uint32(0x0); // 9 3623 Gate of Green Emerald
data << uint32(0xe24) << uint32(0x0); // 10 3620 Gate of Blue Sapphire
data << uint32(0xe21) << uint32(0x0); // 11 3617 Gate of Red Sun
data << uint32(0xe1e) << uint32(0x0); // 12 3614 Gate of Purple Ametyst
data << uint32(0xdf3) << uint32(0x0); // 13 3571 bonus timer (1 - on, 0 - off)
data << uint32(0xded) << uint32(0x0); // 14 3565 Horde Attacker
data << uint32(0xdec) << uint32(0x0); // 15 3564 Alliance Attacker
// End Round (timer), better explain this by example, eg. ends in 19:59 -> A:BC
data << uint32(0xde9) << uint32(0x0); // 16 3561 C
data << uint32(0xde8) << uint32(0x0); // 17 3560 B
data << uint32(0xde7) << uint32(0x0); // 18 3559 A
data << uint32(0xe35) << uint32(0x0); // 19 3637 East g - Horde control
data << uint32(0xe34) << uint32(0x0); // 20 3636 West g - Horde control
data << uint32(0xe33) << uint32(0x0); // 21 3635 South g - Horde control
data << uint32(0xe32) << uint32(0x0); // 22 3634 East g - Alliance control
data << uint32(0xe31) << uint32(0x0); // 23 3633 West g - Alliance control
data << uint32(0xe30) << uint32(0x0); // 24 3632 South g - Alliance control
data << uint32(0xe2f) << uint32(0x0); // 25 3631 Chamber of Ancients - Horde control
data << uint32(0xe2e) << uint32(0x0); // 26 3630 Chamber of Ancients - Alliance control
data << uint32(0xe2d) << uint32(0x0); // 27 3629 Beach1 - Horde control
data << uint32(0xe2c) << uint32(0x0); // 28 3628 Beach2 - Horde control
data << uint32(0xe2b) << uint32(0x0); // 29 3627 Beach1 - Alliance control
data << uint32(0xe2a) << uint32(0x0); // 30 3626 Beach2 - Alliance control
// and many unks...
}
break;
case 4406: // Ring of Valor
if (bg && bg->GetTypeID(true) == BATTLEGROUND_RV)
bg->FillInitialWorldStates(data);
else
{
data << uint32(0xe10) << uint32(0x0); // 7 gold
data << uint32(0xe11) << uint32(0x0); // 8 green
data << uint32(0xe1a) << uint32(0x0); // 9 show
}
break;
case 4710:
if (bg && bg->GetTypeID(true) == BATTLEGROUND_IC)
bg->FillInitialWorldStates(data);
else
{
data << uint32(4221) << uint32(1); // 7 BG_IC_ALLIANCE_RENFORT_SET
data << uint32(4222) << uint32(1); // 8 BG_IC_HORDE_RENFORT_SET
data << uint32(4226) << uint32(300); // 9 BG_IC_ALLIANCE_RENFORT
data << uint32(4227) << uint32(300); // 10 BG_IC_HORDE_RENFORT
data << uint32(4322) << uint32(1); // 11 BG_IC_GATE_FRONT_H_WS_OPEN
data << uint32(4321) << uint32(1); // 12 BG_IC_GATE_WEST_H_WS_OPEN
data << uint32(4320) << uint32(1); // 13 BG_IC_GATE_EAST_H_WS_OPEN
data << uint32(4323) << uint32(1); // 14 BG_IC_GATE_FRONT_A_WS_OPEN
data << uint32(4324) << uint32(1); // 15 BG_IC_GATE_WEST_A_WS_OPEN
data << uint32(4325) << uint32(1); // 16 BG_IC_GATE_EAST_A_WS_OPEN
data << uint32(4317) << uint32(1); // 17 unknown
data << uint32(4301) << uint32(1); // 18 BG_IC_DOCKS_UNCONTROLLED
data << uint32(4296) << uint32(1); // 19 BG_IC_HANGAR_UNCONTROLLED
data << uint32(4306) << uint32(1); // 20 BG_IC_QUARRY_UNCONTROLLED
data << uint32(4311) << uint32(1); // 21 BG_IC_REFINERY_UNCONTROLLED
data << uint32(4294) << uint32(1); // 22 BG_IC_WORKSHOP_UNCONTROLLED
data << uint32(4243) << uint32(1); // 23 unknown
data << uint32(4345) << uint32(1); // 24 unknown
}
break;
// The Ruby Sanctum
case 4987:
if (instance && mapid == 724)
instance->FillInitialWorldStates(data);
else
{
data << uint32(5049) << uint32(50); // 9 WORLDSTATE_CORPOREALITY_MATERIAL
data << uint32(5050) << uint32(50); // 10 WORLDSTATE_CORPOREALITY_TWILIGHT
data << uint32(5051) << uint32(0); // 11 WORLDSTATE_CORPOREALITY_TOGGLE
}
break;
// Icecrown Citadel
case 4812:
if (instance && mapid == 631)
instance->FillInitialWorldStates(data);
else
{
data << uint32(4903) << uint32(0); // 9 WORLDSTATE_SHOW_TIMER (Blood Quickening weekly)
data << uint32(4904) << uint32(30); // 10 WORLDSTATE_EXECUTION_TIME
data << uint32(4940) << uint32(0); // 11 WORLDSTATE_SHOW_ATTEMPTS
data << uint32(4941) << uint32(50); // 12 WORLDSTATE_ATTEMPTS_REMAINING
data << uint32(4942) << uint32(50); // 13 WORLDSTATE_ATTEMPTS_MAX
}
break;
// The Culling of Stratholme
case 4100:
if (instance && mapid == 595)
instance->FillInitialWorldStates(data);
else
{
data << uint32(3479) << uint32(0); // 9 WORLDSTATE_SHOW_CRATES
data << uint32(3480) << uint32(0); // 10 WORLDSTATE_CRATES_REVEALED
data << uint32(3504) << uint32(0); // 11 WORLDSTATE_WAVE_COUNT
data << uint32(3931) << uint32(25); // 12 WORLDSTATE_TIME_GUARDIAN
data << uint32(3932) << uint32(0); // 13 WORLDSTATE_TIME_GUARDIAN_SHOW
}
break;
// Ulduar
case 4273:
if (instance && mapid == 603)
instance->FillInitialWorldStates(data);
else
{
data << uint32(4132) << uint32(0); // 9 WORLDSTATE_ALGALON_TIMER_ENABLED
data << uint32(4131) << uint32(0); // 10 WORLDSTATE_ALGALON_DESPAWN_TIMER
}
break;
// Wintergrasp
case 4197:
if (bf && bf->GetTypeId() == BATTLEFIELD_WG)
{
bf->FillInitialWorldStates(data);
break;
}
case 4820:
if (instance && mapid == 668)
instance->FillInitialWorldStates(data);
else
{
data << uint32(4884) << uint32(0); // 9 WORLD_STATE_HOR_WAVES_ENABLED
data << uint32(4882) << uint32(0); // 10 WORLD_STATE_HOR_WAVE_COUNT
}
break;
// No break here, intended.
default:
data << uint32(0x914) << uint32(0x0); // 7
data << uint32(0x913) << uint32(0x0); // 8
data << uint32(0x912) << uint32(0x0); // 9
data << uint32(0x915) << uint32(0x0); // 10
break;
}
uint16 length = (data.wpos() - countPos) / 8;
data.put<uint16>(countPos, length);
GetSession()->SendPacket(&data);
SendBGWeekendWorldStates();
SendBattlefieldWorldStates();
}
void Player::SendBGWeekendWorldStates()
{
for (uint32 i = 1; i < sBattlemasterListStore.GetNumRows(); ++i)
{
BattlemasterListEntry const* bl = sBattlemasterListStore.LookupEntry(i);
if (bl && bl->HolidayWorldStateId)
{
if (BattlegroundMgr::IsBGWeekend((BattlegroundTypeId)bl->id))
SendUpdateWorldState(bl->HolidayWorldStateId, 1);
else
SendUpdateWorldState(bl->HolidayWorldStateId, 0);
}
}
}
void Player::SendBattlefieldWorldStates()
{
/// Send misc stuff that needs to be sent on every login, like the battle timers.
if (sWorld->getBoolConfig(CONFIG_WINTERGRASP_ENABLE))
{
if (BattlefieldWG* wg = (BattlefieldWG*)sBattlefieldMgr->GetBattlefieldByBattleId(BATTLEFIELD_BATTLEID_WG))
{
if (wg->IsWarTime())
SendUpdateWorldState(ClockWorldState[1], uint32(time(NULL)));
else // Time to next battle
{
uint32 timer = wg->GetTimer() / 1000;
SendUpdateWorldState(ClockWorldState[1], time(NULL) + 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_INFO(LOG_FILTER_PLAYER, "Player gain %u xp (+ %u Rested Bonus). Rested points=%f", xp+rested_bonus, rested_bonus, GetRestBonus());
return rested_bonus;
}
void Player::SetBindPoint(uint64 guid)
{
WorldPacket data(SMSG_BINDER_CONFIRM, 8);
data << uint64(guid);
GetSession()->SendPacket(&data);
}
void Player::SendTalentWipeConfirm(uint64 guid)
{
WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
data << uint64(guid);
uint32 cost = sWorld->getBoolConfig(CONFIG_NO_RESET_TALENT_COST) ? 0 : resetTalentsCost();
data << cost;
GetSession()->SendPacket(&data);
}
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(LOG_FILTER_PLAYER, "Object (GUID: %u TypeId: %u) is considered pet-like but doesn't have a charminfo!", pet->GetGUIDLow(), pet->GetTypeId());
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 if (charges <= 1)
{
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, NULL);
SetVirtualItemSlot(1, NULL);
SetVirtualItemSlot(2, NULL);
break;
case SHEATH_STATE_MELEE: // prepared melee weapon
SetVirtualItemSlot(0, GetWeaponForAttack(BASE_ATTACK, true));
SetVirtualItemSlot(1, GetWeaponForAttack(OFF_ATTACK, true));
SetVirtualItemSlot(2, NULL);
break;
case SHEATH_STATE_RANGED: // prepared ranged weapon
SetVirtualItemSlot(0, NULL);
SetVirtualItemSlot(1, NULL);
SetVirtualItemSlot(2, GetWeaponForAttack(RANGED_ATTACK, true));
break;
default:
SetVirtualItemSlot(0, NULL);
SetVirtualItemSlot(1, NULL);
SetVirtualItemSlot(2, NULL);
break;
}
Unit::SetSheath(sheathed); // this must visualize Sheath changing for other players...
}
uint8 Player::FindEquipSlot(ItemTemplate const* proto, uint32 slot, bool swap) const
{
uint8 playerClass = getClass();
uint8 slots[4];
slots[0] = NULL_SLOT;
slots[1] = NULL_SLOT;
slots[2] = NULL_SLOT;
slots[3] = NULL_SLOT;
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 (Item* mhWeapon = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND))
{
if (ItemTemplate const* mhWeaponProto = mhWeapon->GetTemplate())
{
if (mhWeaponProto->SubClass == ITEM_SUBCLASS_WEAPON_POLEARM || mhWeaponProto->SubClass == ITEM_SUBCLASS_WEAPON_STAFF)
{
const_cast<Player*>(this)->AutoUnequipOffhandIfNeed(true);
break;
}
}
}
if (GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
{
if (proto->SubClass == ITEM_SUBCLASS_WEAPON_POLEARM || proto->SubClass == ITEM_SUBCLASS_WEAPON_STAFF)
{
const_cast<Player*>(this)->AutoUnequipOffhandIfNeed(true);
break;
}
}
if (CanDualWield() && CanTitanGrip() && proto->SubClass != ITEM_SUBCLASS_WEAPON_POLEARM && proto->SubClass != ITEM_SUBCLASS_WEAPON_STAFF)
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[0] = INVENTORY_SLOT_BAG_START + 0;
slots[1] = INVENTORY_SLOT_BAG_START + 1;
slots[2] = INVENTORY_SLOT_BAG_START + 2;
slots[3] = INVENTORY_SLOT_BAG_START + 3;
break;
case INVTYPE_RELIC:
{
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_MISC:
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(uint64 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 NULL;
}
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];
else if (Bag* pBag = GetBagByPos(bag))
return pBag->GetItemByPos(slot);
return NULL;
}
//Does additional check for disarmed weapons
Item* Player::GetUseableItemByPos(uint8 bag, uint8 slot) const
{
if (!CanUseAttackType(GetAttackBySlot(slot)))
return NULL;
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 NULL;
}
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 NULL;
}
Item* item = NULL;
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 NULL;
if (!useable)
return item;
if (item->IsBroken() || IsInFeralForm())
return NULL;
return item;
}
Item* Player::GetShield(bool useable) const
{
Item* item = NULL;
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 NULL;
if (!useable)
return item;
if (item->IsBroken())
return NULL;
return item;
}
uint8 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)
{
// 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::HasItemOrGemWithLimitCategoryEquipped(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;
}
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) const
{
ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(entry);
if (!pProto)
{
if (no_space_count)
*no_space_count = count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
if (pItem && pItem->m_lootGenerated)
return EQUIP_ERR_ALREADY_LOOTED;
// 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_CANT_CARRY_MORE_OF_THIS;
}
}
// 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_ITEM_CANT_BE_EQUIPPED;
}
if (limitEntry->mode == ITEM_LIMIT_CATEGORY_MODE_HAVE)
{
uint32 curcount = GetItemCountWithLimitCategory(pProto->ItemLimitCategory, pItem);
if (curcount + count > uint32(limitEntry->maxCount))
{
if (no_space_count)
*no_space_count = count + curcount - limitEntry->maxCount;
return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED;
}
}
}
return EQUIP_ERR_OK;
}
InventoryResult Player::CanStoreNewItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, uint32 item, uint32 count, uint32* no_space_count /*= NULL*/) const
{
return CanStoreItem(bag, slot, dest, item, count, NULL, 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, NULL);
}
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 = NULL;
uint32 need_space;
if (pSrcItem && pSrcItem->IsNotEmptyBag() && !IsBagPos(uint16(bag) << 8 | slot))
return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
// 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_ITEM_DOESNT_GO_INTO_BAG;
// currencytoken case
if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->IsCurrencyToken()))
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
// prevent cheating
if ((slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END) || slot >= PLAYER_SLOT_END)
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
}
else
{
Bag* pBag = GetBagByPos(bag);
if (!pBag)
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
ItemTemplate const* pBagProto = pBag->GetTemplate();
if (!pBagProto)
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
if (slot >= pBagProto->ContainerSlots)
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
if (!ItemCanGoIntoBag(pProto, pBagProto))
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
}
// 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_ITEM_DOESNT_GO_INTO_BAG;
// skip not existed bag or self targeted bag
Bag* pBag = GetBagByPos(bag);
if (!pBag || pBag == pSrcItem)
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
if (pSrcItem && pSrcItem->IsNotEmptyBag())
return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
ItemTemplate const* pBagProto = pBag->GetTemplate();
if (!pBagProto)
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
// specialized bag mode or non-specilized
if (non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER))
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
if (!ItemCanGoIntoBag(pProto, pBagProto))
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
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 = NULL;
// if merge skip empty, if !merge skip non-empty
if ((pItem2 != NULL) != merge)
continue;
uint32 need_space = pProto->GetMaxStackSize();
if (pItem2)
{
// can be merged at least partly
uint8 res = pItem2->CanBeMergedPartlyWith(pProto);
if (res != 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_CAN_ONLY_DO_WITH_EMPTY_BAGS;
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 = NULL;
// if merge skip empty, if !merge skip non-empty
if ((pItem2 != NULL) != merge)
continue;
uint32 need_space = pProto->GetMaxStackSize();
if (pItem2)
{
// can be merged at least partly
uint8 res = pItem2->CanBeMergedPartlyWith(pProto);
if (res != 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(LOG_FILTER_PLAYER_ITEMS, "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(entry);
if (!pProto)
{
if (no_space_count)
*no_space_count = count;
return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
}
if (pItem)
{
// item used
if (pItem->m_lootGenerated)
{
if (no_space_count)
*no_space_count = count;
return EQUIP_ERR_ALREADY_LOOTED;
}
if (pItem->IsBindedNotWith(this))
{
if (no_space_count)
*no_space_count = count;
return EQUIP_ERR_DONT_OWN_THAT_ITEM;
}
}
// 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_CANT_CARRY_MORE_OF_THIS;
}
}
// 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_CANT_CARRY_MORE_OF_THIS;
}
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_CANT_CARRY_MORE_OF_THIS;
}
}
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_CANT_CARRY_MORE_OF_THIS;
}
}
}
// 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_CANT_CARRY_MORE_OF_THIS;
}
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_CANT_CARRY_MORE_OF_THIS;
}
}
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_CANT_CARRY_MORE_OF_THIS;
}
}
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_CANT_CARRY_MORE_OF_THIS;
}
}
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_CANT_CARRY_MORE_OF_THIS;
}
}
}
// 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_CANT_CARRY_MORE_OF_THIS;
}
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_CANT_CARRY_MORE_OF_THIS;
}
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_CANT_CARRY_MORE_OF_THIS;
}
}
}
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_CANT_CARRY_MORE_OF_THIS;
}
}
}
// 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_CANT_CARRY_MORE_OF_THIS;
}
}
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_CANT_CARRY_MORE_OF_THIS;
}
}
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_CANT_CARRY_MORE_OF_THIS;
}
}
}
if (pItem && pItem->IsNotEmptyBag())
return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_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_CANT_CARRY_MORE_OF_THIS;
}
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_CANT_CARRY_MORE_OF_THIS;
}
}
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_INVENTORY_FULL;
}
//////////////////////////////////////////////////////////////////////////
InventoryResult Player::CanStoreItems(Item** pItems, int count) const
{
Item* pItem2;
// fill space table
int inv_slot_items[INVENTORY_SLOT_ITEM_END - INVENTORY_SLOT_ITEM_START];
int inv_bags[INVENTORY_SLOT_BAG_END - INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
int inv_keys[KEYRING_SLOT_END - KEYRING_SLOT_START];
int inv_tokens[CURRENCYTOKEN_SLOT_END - CURRENCYTOKEN_SLOT_START];
memset(inv_slot_items, 0, sizeof(int) * (INVENTORY_SLOT_ITEM_END - INVENTORY_SLOT_ITEM_START));
memset(inv_bags, 0, sizeof(int) * (INVENTORY_SLOT_BAG_END - INVENTORY_SLOT_BAG_START) * MAX_BAG_SIZE);
memset(inv_keys, 0, sizeof(int) * (KEYRING_SLOT_END - KEYRING_SLOT_START));
memset(inv_tokens, 0, sizeof(int) * (CURRENCYTOKEN_SLOT_END - CURRENCYTOKEN_SLOT_START));
for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
{
pItem2 = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
if (pItem2 && !pItem2->IsInTrade())
inv_slot_items[i - INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
}
for (uint8 i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
{
pItem2 = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
if (pItem2 && !pItem2->IsInTrade())
inv_keys[i - KEYRING_SLOT_START] = pItem2->GetCount();
}
for (uint8 i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; i++)
{
pItem2 = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
if (pItem2 && !pItem2->IsInTrade())
inv_tokens[i - CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
}
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++)
{
pItem2 = GetItemByPos(i, j);
if (pItem2 && !pItem2->IsInTrade())
inv_bags[i - INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
}
// check free space for all items
for (int k = 0; k < count; ++k)
{
Item* pItem = pItems[k];
// no item
if (!pItem)
continue;
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "STORAGE: CanStoreItems %i. item = %u, count = %u", k + 1, pItem->GetEntry(), pItem->GetCount());
ItemTemplate const* pProto = pItem->GetTemplate();
// strange item
if (!pProto)
return EQUIP_ERR_ITEM_NOT_FOUND;
// item used
if (pItem->m_lootGenerated)
return EQUIP_ERR_ALREADY_LOOTED;
// item it 'bind'
if (pItem->IsBindedNotWith(this))
return EQUIP_ERR_DONT_OWN_THAT_ITEM;
ItemTemplate const* pBagProto;
// item is 'one item only'
InventoryResult res = CanTakeMoreSimilarItems(pItem);
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)
{
pItem2 = GetItemByPos(INVENTORY_SLOT_BAG_0, t);
if (pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
{
inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
b_found = true;
break;
}
}
if (b_found)
continue;
for (int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
{
pItem2 = GetItemByPos(INVENTORY_SLOT_BAG_0, t);
if (pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
{
inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
b_found = true;
break;
}
}
if (b_found)
continue;
for (int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
{
pItem2 = GetItemByPos(INVENTORY_SLOT_BAG_0, t);
if (pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
{
inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
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))
{
if (ItemCanGoIntoBag(pItem->GetTemplate(), bag->GetTemplate()))
{
for (uint32 j = 0; j < bag->GetBagSize(); j++)
{
pItem2 = GetItemByPos(t, j);
if (pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
{
inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
b_found = true;
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 (inv_keys[t-KEYRING_SLOT_START] == 0)
{
inv_keys[t-KEYRING_SLOT_START] = 1;
b_found = true;
break;
}
}
}
if (b_found)
continue;
if (pProto->IsCurrencyToken())
{
for (uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
{
if (inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0)
{
inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
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 (inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0)
{
inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
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 (inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0)
{
inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
b_found = true;
break;
}
}
if (b_found)
continue;
// search free slot in bags
for (int 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 (inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0)
{
inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
b_found = true;
break;
}
}
}
}
// no free slot found?
if (!b_found)
return EQUIP_ERR_INVENTORY_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(LOG_FILTER_PLAYER_ITEMS, "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
ItemTemplate const* pProto = pItem->GetTemplate();
if (pProto)
{
// item used
if (pItem->m_lootGenerated)
return EQUIP_ERR_ALREADY_LOOTED;
if (pItem->IsBindedNotWith(this))
return EQUIP_ERR_DONT_OWN_THAT_ITEM;
// 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_YOU_ARE_STUNNED;
// 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_CANT_DO_RIGHT_NOW; // maybe exist better err
if (IsNonMeleeSpellCasted(false))
return EQUIP_ERR_CANT_DO_RIGHT_NOW;
}
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_ITEM_CANT_BE_EQUIPPED;
uint8 eslot = FindEquipSlot(pProto, slot, swap);
if (eslot == NULL_SLOT)
return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
res = CanUseItem(pItem, not_loading);
if (res != EQUIP_ERR_OK)
return res;
if (!swap && GetItemByPos(INVENTORY_SLOT_BAG_0, eslot))
return EQUIP_ERR_NO_EQUIPMENT_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_CAN_EQUIP_ONLY1_AMMOPOUCH
: EQUIP_ERR_CAN_EQUIP_ONLY1_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_ITEM_DOESNT_GO_TO_SLOT;
else if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
{
if (!CanDualWield())
return EQUIP_ERR_CANT_DUAL_WIELD;
}
else if (type == INVTYPE_2HWEAPON)
{
if (!CanDualWield() || !CanTitanGrip())
return EQUIP_ERR_CANT_DUAL_WIELD;
}
if (IsTwoHandUsed())
return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
}
// equip two-hand weapon case (with possible unequip 2 items)
if (type == INVTYPE_2HWEAPON)
{
if (eslot == EQUIPMENT_SLOT_OFFHAND)
{
if (!CanTitanGrip())
return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
}
else if (eslot != EQUIPMENT_SLOT_MAINHAND)
return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
if (!CanTitanGrip())
{
// 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_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
}
}
dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
return EQUIP_ERR_OK;
}
}
return !swap ? EQUIP_ERR_ITEM_NOT_FOUND : EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
}
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 existed equipped item
if (!pItem)
return EQUIP_ERR_OK;
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
ItemTemplate const* pProto = pItem->GetTemplate();
if (!pProto)
return EQUIP_ERR_ITEM_NOT_FOUND;
// item used
if (pItem->m_lootGenerated)
return EQUIP_ERR_ALREADY_LOOTED;
// 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_CAN_ONLY_DO_WITH_EMPTY_BAGS;
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_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
uint32 count = pItem->GetCount();
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
ItemTemplate const* pProto = pItem->GetTemplate();
if (!pProto)
return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
// item used
if (pItem->m_lootGenerated)
return EQUIP_ERR_ALREADY_LOOTED;
if (pItem->IsBindedNotWith(this))
return EQUIP_ERR_DONT_OWN_THAT_ITEM;
// 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(LOG_FILTER_PLAYER, "Possible hacking attempt: Player %s [guid: %u] tried to move token [guid: %u, entry: %u] out of the currency bag!",
GetName().c_str(), GetGUIDLow(), pItem->GetGUIDLow(), pProto->ItemId);
return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
}
// 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_ITEM_DOESNT_GO_TO_SLOT;
if (slot - BANK_SLOT_BAG_START >= GetBankBagSlotCount())
return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_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_NONEMPTY_BAG_OVER_OTHER_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(LOG_FILTER_PLAYER_ITEMS, "STORAGE: CanUseItem item = %u", pItem->GetEntry());
if (!IsAlive() && not_loading)
return EQUIP_ERR_YOU_ARE_DEAD;
//if (isStunned())
// return EQUIP_ERR_YOU_ARE_STUNNED;
ItemTemplate const* pProto = pItem->GetTemplate();
if (pProto)
{
if (pItem->IsBindedNotWith(this))
return EQUIP_ERR_DONT_OWN_THAT_ITEM;
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_NO_REQUIRED_PROFICIENCY.
// 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_NO_REQUIRED_PROFICIENCY;
}
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)
{
if ((proto->Flags2 & ITEM_FLAGS_EXTRA_HORDE_ONLY) && GetTeam() != HORDE)
return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
if ((proto->Flags2 & ITEM_FLAGS_EXTRA_ALLIANCE_ONLY) && GetTeam() != ALLIANCE)
return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
if ((proto->AllowableClass & getClassMask()) == 0 || (proto->AllowableRace & getRaceMask()) == 0)
return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
if (proto->RequiredSkill != 0)
{
if (GetSkillValue(proto->RequiredSkill) == 0)
return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
else if (GetSkillValue(proto->RequiredSkill) < proto->RequiredSkillRank)
return EQUIP_ERR_CANT_EQUIP_SKILL;
}
if (proto->RequiredSpell != 0 && !HasSpell(proto->RequiredSpell))
return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
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_CANT_DO_RIGHT_NOW;
#ifdef ELUNA
return sHookMgr->OnCanUseItem(this, proto->ItemId);
#else
return EQUIP_ERR_OK;
#endif
}
return EQUIP_ERR_ITEM_NOT_FOUND;
}
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_YOU_CAN_NEVER_USE_THAT_ITEM;
if (proto->RequiredSpell != 0 && !HasSpell(proto->RequiredSpell))
return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
if (proto->RequiredSkill != 0)
{
if (!GetSkillValue(proto->RequiredSkill))
return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
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_NO_REQUIRED_PROFICIENCY;
if (proto->Class == ITEM_CLASS_ARMOR && proto->SubClass > ITEM_SUBCLASS_ARMOR_MISC && 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_CANT_DO_RIGHT_NOW;
}
else if (proto->SubClass != ITEM_SUBCLASS_ARMOR_PLATE)
return EQUIP_ERR_CANT_DO_RIGHT_NOW;
}
else if (_class == CLASS_HUNTER || _class == CLASS_SHAMAN)
{
if (getLevel() < 40)
{
if (proto->SubClass != ITEM_SUBCLASS_ARMOR_LEATHER)
return EQUIP_ERR_CANT_DO_RIGHT_NOW;
}
else if (proto->SubClass != ITEM_SUBCLASS_ARMOR_MAIL)
return EQUIP_ERR_CANT_DO_RIGHT_NOW;
}
if (_class == CLASS_ROGUE || _class == CLASS_DRUID)
if (proto->SubClass != ITEM_SUBCLASS_ARMOR_LEATHER)
return EQUIP_ERR_CANT_DO_RIGHT_NOW;
if (_class == CLASS_MAGE || _class == CLASS_PRIEST || _class == CLASS_WARLOCK)
if (proto->SubClass != ITEM_SUBCLASS_ARMOR_CLOTH)
return EQUIP_ERR_CANT_DO_RIGHT_NOW;
}
return EQUIP_ERR_OK;
}
InventoryResult Player::CanUseAmmo(uint32 item) const
{
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "STORAGE: CanUseAmmo item = %u", item);
if (!IsAlive())
return EQUIP_ERR_YOU_ARE_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_ONLY_AMMO_CAN_GO_HERE;
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_FULL6;
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
if (item)
{
InventoryResult msg = CanUseAmmo(item);
if (msg != EQUIP_ERR_OK)
{
SendEquipError(msg, NULL, NULL, 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, AllowedLooterSet 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)
{
ItemAddedQuestCheck(item, count);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM, item, count);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, item, 1);
if (randomPropertyId)
pItem->SetItemRandomProperties(randomPropertyId);
pItem = StoreItem(dest, pItem, update);
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;
AllowedLooterSet::const_iterator itr = allowedLooters.begin();
ss << *itr;
for (++itr; itr != allowedLooters.end(); ++itr)
ss << ' ' << *itr;
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_ITEM_BOP_TRADE);
stmt->setUInt32(0, pItem->GetGUIDLow());
stmt->setString(1, ss.str());
CharacterDatabase.Execute(stmt);
}
}
return pItem;
}
Item* Player::StoreItem(ItemPosCountVec const& dest, Item* pItem, bool update)
{
if (!pItem)
return NULL;
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 NULL;
uint8 bag = pos >> 8;
uint8 slot = pos & 255;
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u, guid = %u", bag, slot, pItem->GetEntry(), count, pItem->GetGUIDLow());
Item* pItem2 = GetItemByPos(bag, slot);
if (!pItem2)
{
if (clone)
pItem = pItem->CloneItem(count, this);
else
pItem->SetCount(count);
if (!pItem)
return NULL;
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) ? NULL : GetBagByPos(bag);
if (!pBag)
{
m_items[slot] = pItem;
SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID());
pItem->SetUInt64Value(ITEM_FIELD_CONTAINED, GetGUID());
pItem->SetUInt64Value(ITEM_FIELD_OWNER, GetGUID());
pItem->SetSlot(slot);
pItem->SetContainer(NULL);
// 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);
const ItemTemplate* proto = pItem->GetTemplate();
for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
if (proto->Spells[i].SpellTrigger == ITEM_SPELLTRIGGER_ON_NO_DELAY_USE && proto->Spells[i].SpellId > 0) // On obtain trigger
if (bag == INVENTORY_SLOT_BAG_0 || (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END))
if (!HasAura(proto->Spells[i].SpellId))
CastSpell(this, proto->Spells[i].SpellId, true, pItem);
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);
const ItemTemplate* proto = pItem2->GetTemplate();
for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
if (proto->Spells[i].SpellTrigger == ITEM_SPELLTRIGGER_ON_NO_DELAY_USE && proto->Spells[i].SpellId > 0) // On obtain trigger
if (bag == INVENTORY_SLOT_BAG_0 || (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END))
if (!HasAura(proto->Spells[i].SpellId))
CastSpell(this, proto->Spells[i].SpellId, true, pItem2);
return pItem2;
}
}
Item* Player::EquipNewItem(uint16 pos, uint32 item, bool update)
{
if (Item* pItem = Item::CreateItem(item, 1, this))
{
ItemAddedQuestCheck(item, 1);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM, item, 1);
return EquipItem(pos, pItem, update);
}
return NULL;
}
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(LOG_FILTER_PLAYER, "Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
else
{
m_weaponChangeTimer = spellProto->StartRecoveryTime;
GetGlobalCooldownMgr().AddGlobalCooldown(spellProto, m_weaponChangeTimer);
WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
data << uint64(GetGUID());
data << uint8(1);
data << uint32(cooldownSpell);
data << uint32(0);
GetSession()->SendPacket(&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);
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
sHookMgr->OnEquip(this, pItem2, bag, slot);
#endif
return pItem2;
}
// only for full equip instead adding to stack
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM, pItem->GetEntry(), slot);
#ifdef ELUNA
sHookMgr->OnEquip(this, pItem, bag, 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);
}
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM, pItem->GetEntry(), slot);
}
}
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(LOG_FILTER_PLAYER_ITEMS, "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
m_items[slot] = pItem;
SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID());
pItem->SetUInt64Value(ITEM_FIELD_CONTAINED, GetGUID());
pItem->SetUInt64Value(ITEM_FIELD_OWNER, GetGUID());
pItem->SetSlot(slot);
pItem->SetContainer(NULL);
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(LOG_FILTER_PLAYER_ITEMS, "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
RemoveEnchantmentDurations(pItem);
RemoveItemDurations(pItem);
RemoveTradeableItem(pItem);
if (bag == INVENTORY_SLOT_BAG_0)
{
if (slot < INVENTORY_SLOT_BAG_END)
{
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)
RemoveItemsSetItem(this, pProto);
_ApplyItemMods(pItem, slot, false);
// remove item dependent auras and casts (only weapon and armor slots)
if (slot < EQUIPMENT_SLOT_END)
{
RemoveItemDependentAurasAndCasts(pItem);
// 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);
default:
break;
}
}
}
m_items[slot] = NULL;
SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
if (slot < EQUIPMENT_SLOT_END)
SetVisibleItemSlot(slot, NULL);
}
else if (Bag* pBag = GetBagByPos(bag))
pBag->RemoveItem(slot, update);
pItem->SetUInt64Value(ITEM_FIELD_CONTAINED, 0);
// 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))
{
ItemRemovedQuestCheck(it->GetEntry(), it->GetCount());
RemoveItem(bag, slot, update);
it->SetNotRefundable(this, false);
it->RemoveFromUpdateQueueOf(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)
{
// update quest counters
ItemAddedQuestCheck(pItem->GetEntry(), pItem->GetCount());
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM, pItem->GetEntry(), pItem->GetCount());
// store item
Item* pLastItem = StoreItem(dest, pItem, update);
// only set if not merged to existed 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->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_BOP_TRADEABLE))
AddTradeableItem(pLastItem);
}
}
void Player::DestroyItem(uint8 bag, uint8 slot, bool update)
{
Item* pItem = GetItemByPos(bag, slot);
if (pItem)
{
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", 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->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_WRAPPED))
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GIFT);
stmt->setUInt32(0, pItem->GetGUIDLow());
CharacterDatabase.Execute(stmt);
}
RemoveEnchantmentDurations(pItem);
RemoveItemDurations(pItem);
pItem->SetNotRefundable(this);
pItem->ClearSoulboundTradeable(this);
RemoveTradeableItem(pItem);
const ItemTemplate* proto = pItem->GetTemplate();
for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
if (proto->Spells[i].SpellTrigger == ITEM_SPELLTRIGGER_ON_NO_DELAY_USE && proto->Spells[i].SpellId > 0) // On obtain trigger
RemoveAurasDueToSpell(proto->Spells[i].SpellId);
ItemRemovedQuestCheck(pItem->GetEntry(), pItem->GetCount());
if (bag == INVENTORY_SLOT_BAG_0)
{
SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
// equipment and equipped bags can have applied bonuses
if (slot < INVENTORY_SLOT_BAG_END)
{
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)
RemoveItemsSetItem(this, pProto);
_ApplyItemMods(pItem, slot, false);
}
if (slot < EQUIPMENT_SLOT_END)
{
// remove item dependent auras and casts (only weapon and armor slots)
RemoveItemDependentAurasAndCasts(pItem);
// 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);
default:
break;
}
if (slot == EQUIPMENT_SLOT_MAINHAND)
UpdateExpertise(BASE_ATTACK);
else if (slot == EQUIPMENT_SLOT_OFFHAND)
UpdateExpertise(OFF_ATTACK);
// equipment visual show
SetVisibleItemSlot(slot, NULL);
}
m_items[slot] = NULL;
}
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 (ItemTemplate const* pTmp = pItem->GetTemplate())
if (pTmp->Flags & ITEM_PROTO_FLAG_OPENABLE)
pItem->ItemContainerDeleteLootMoneyAndLootItemsFromDB();
if (IsInWorld() && update)
{
pItem->RemoveFromWorld();
pItem->DestroyForPlayer(this);
}
//pItem->SetOwnerGUID(0);
pItem->SetUInt64Value(ITEM_FIELD_CONTAINED, 0);
pItem->SetSlot(NULL_SLOT);
pItem->SetState(ITEM_REMOVED, this);
}
}
void Player::DestroyItemCount(uint32 itemEntry, uint32 count, bool update, bool unequip_check)
{
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "STORAGE: DestroyItemCount item = %u, count = %u", 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;
}
else
{
ItemRemovedQuestCheck(item->GetEntry(), count - remcount);
item->SetCount(item->GetCount() - count + remcount);
if (IsInWorld() && update)
item->SendUpdateToPlayer(this);
item->SetState(ITEM_CHANGED, this);
return;
}
}
}
}
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;
}
else
{
ItemRemovedQuestCheck(item->GetEntry(), count - remcount);
item->SetCount(item->GetCount() - count + remcount);
if (IsInWorld() && update)
item->SendUpdateToPlayer(this);
item->SetState(ITEM_CHANGED, this);
return;
}
}
}
}
// 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;
}
else
{
ItemRemovedQuestCheck(item->GetEntry(), count - remcount);
item->SetCount(item->GetCount() - count + remcount);
if (IsInWorld() && update)
item->SendUpdateToPlayer(this);
item->SetState(ITEM_CHANGED, this);
return;
}
}
}
}
}
}
// 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 && 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;
}
}
else
{
ItemRemovedQuestCheck(item->GetEntry(), count - remcount);
item->SetCount(item->GetCount() - count + remcount);
if (IsInWorld() && update)
item->SendUpdateToPlayer(this);
item->SetState(ITEM_CHANGED, this);
return;
}
}
}
}
// 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;
}
else
{
ItemRemovedQuestCheck(item->GetEntry(), count - remcount);
item->SetCount(item->GetCount() - count + remcount);
if (IsInWorld() && update)
item->SendUpdateToPlayer(this);
item->SetState(ITEM_CHANGED, this);
return;
}
}
}
}
// 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;
}
else
{
ItemRemovedQuestCheck(item->GetEntry(), count - remcount);
item->SetCount(item->GetCount() - count + remcount);
if (IsInWorld() && update)
item->SendUpdateToPlayer(this);
item->SetState(ITEM_CHANGED, this);
return;
}
}
}
}
}
}
}
void Player::DestroyZoneLimitedItem(bool update, uint32 new_zone)
{
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone);
// 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(LOG_FILTER_PLAYER_ITEMS, "STORAGE: DestroyConjuredItems");
// 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 (int 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 (int 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 (int 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 NULL;
}
void Player::DestroyItemCount(Item* pItem, uint32 &count, bool update)
{
if (!pItem)
return;
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(), pItem->GetEntry(), count);
if (pItem->GetCount() <= count)
{
count -= pItem->GetCount();
DestroyItem(pItem->GetBagSlot(), pItem->GetSlot(), update);
}
else
{
ItemRemovedQuestCheck(pItem->GetEntry(), count);
pItem->SetCount(pItem->GetCount() - 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, NULL);
return;
}
if (pSrcItem->m_lootGenerated) // prevent split looting item (item
{
//best error message found for attempting to split while looting
SendEquipError(EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL);
return;
}
// not let split all items (can be only at cheating)
if (pSrcItem->GetCount() == count)
{
SendEquipError(EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL);
return;
}
// not let split more existed items (can be only at cheating)
if (pSrcItem->GetCount() < count)
{
SendEquipError(EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL);
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(LOG_FILTER_PLAYER_ITEMS, "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
Item* pNewItem = pSrcItem->CloneItem(count, this);
if (!pNewItem)
{
SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL);
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, NULL);
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, NULL);
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, NULL);
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(LOG_FILTER_PLAYER_ITEMS, "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
if (!IsAlive())
{
SendEquipError(EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem);
return;
}
// SRC checks
if (pSrcItem->m_lootGenerated) // prevent swap looting item
{
//best error message found for attempting to swap while looting
SendEquipError(EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL);
return;
}
// 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_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem);
return;
}
// prevent equipping bag in the same slot from its inside
if (IsBagPos(dst) && srcbag == dstslot)
{
SendEquipError(EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem);
return;
}
// DST checks
if (pDstItem)
{
if (pDstItem->m_lootGenerated) // prevent swap looting item
{
//best error message found for attempting to swap while looting
SendEquipError(EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL);
return;
}
// 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, NULL);
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, NULL);
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, NULL);
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 = NULL;
Bag* fullBag = NULL;
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_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem);
return;
}
++count;
}
if (count > emptyBag->GetBagSize())
{
// too small targeted bag
SendEquipError(EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, 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 player is moving bags and is looting an item inside this bag
// release the loot
if (GetLootGUID())
{
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->m_lootGenerated)
{
m_session->DoLootRelease(GetLootGUID());
released = true; // so we don't need to look at dstBag
break;
}
}
}
}
if (!released && IsBagPos(dst) && pDstItem)
{
Bag* bag = pDstItem->ToBag();
for (uint32 i = 0; i < bag->GetBagSize(); ++i)
{
if (Item* bagItem = bag->GetItemByPos(i))
{
if (bagItem->m_lootGenerated)
{
m_session->DoLootRelease(GetLootGUID());
released = true; // not realy needed here
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])
{
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(LOG_FILTER_PLAYER_ITEMS, "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
m_items[slot] = pItem;
time_t base = time(NULL);
uint32 etime = uint32(base - m_logintime + (30 * 3600));
uint32 eslot = slot - BUYBACK_SLOT_START;
SetUInt64Value(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(LOG_FILTER_PLAYER_ITEMS, "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
return m_items[slot];
return NULL;
}
void Player::RemoveItemFromBuyBackSlot(uint32 slot, bool del)
{
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
{
Item* pItem = m_items[slot];
if (pItem)
{
pItem->RemoveFromWorld();
if (del)
pItem->SetState(ITEM_REMOVED, this);
}
m_items[slot] = NULL;
uint32 eslot = slot - BUYBACK_SLOT_START;
SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), 0);
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)
{
TC_LOG_DEBUG(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)", msg);
WorldPacket data(SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18));
data << uint8(msg);
if (msg != EQUIP_ERR_OK)
{
data << uint64(pItem ? pItem->GetGUID() : 0);
data << uint64(pItem2 ? pItem2->GetGUID() : 0);
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:
case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_SOCKETED_EXCEEDED:
case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED:
{
ItemTemplate const* proto = pItem ? pItem->GetTemplate() : sObjectMgr->GetItemTemplate(itemid);
data << uint32(proto ? proto->ItemLimitCategory : 0);
break;
}
default:
break;
}
}
GetSession()->SendPacket(&data);
}
void Player::SendBuyError(BuyResult msg, Creature* creature, uint32 item, uint32 param)
{
TC_LOG_DEBUG(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_BUY_FAILED");
WorldPacket data(SMSG_BUY_FAILED, (8+4+4+1));
data << uint64(creature ? creature->GetGUID() : 0);
data << uint32(item);
if (param > 0)
data << uint32(param);
data << uint8(msg);
GetSession()->SendPacket(&data);
}
void Player::SendSellError(SellResult msg, Creature* creature, uint64 guid, uint32 param)
{
TC_LOG_DEBUG(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_SELL_ITEM");
WorldPacket data(SMSG_SELL_ITEM, (8+8+(param?4:0)+1)); // last check 2.0.10
data << uint64(creature ? creature->GetGUID() : 0);
data << uint64(guid);
if (param > 0)
data << uint32(param);
data << uint8(msg);
GetSession()->SendPacket(&data);
}
bool Player::IsUseEquipedWeapon(bool mainhand) const
{
// disarm applied only to mainhand weapon
return !IsInFeralForm() && (!mainhand || !HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISARMED));
}
bool Player::IsTwoHandUsed() const
{
Item* mainItem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
return mainItem && mainItem->GetTemplate()->InventoryType == INVTYPE_2HWEAPON && !CanTitanGrip();
}
void Player::TradeCancel(bool sendback)
{
if (m_trade)
{
Player* trader = m_trade->GetTrader();
// send yellow "Trade canceled" message to both traders
if (sendback)
GetSession()->SendCancelTrade();
trader->GetSession()->SendCancelTrade();
// cleanup
delete m_trade;
m_trade = NULL;
delete trader->m_trade;
trader->m_trade = NULL;
}
}
void Player::UpdateSoulboundTradeItems()
{
if (m_itemSoulboundTradeable.empty())
return;
// also checks for garbage data
for (ItemDurationList::iterator itr = m_itemSoulboundTradeable.begin(); itr != m_itemSoulboundTradeable.end();)
{
ASSERT(*itr);
if ((*itr)->GetOwnerGUID() != GetGUID())
{
m_itemSoulboundTradeable.erase(itr++);
continue;
}
if ((*itr)->CheckSoulboundTradeExpire())
{
m_itemSoulboundTradeable.erase(itr++);
continue;
}
++itr;
}
}
void Player::AddTradeableItem(Item* item)
{
m_itemSoulboundTradeable.push_back(item);
}
/// @todo should never allow an item to be added to m_itemSoulboundTradeable twice
void Player::RemoveTradeableItem(Item* item)
{
m_itemSoulboundTradeable.remove(item);
}
void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
{
if (m_itemDuration.empty())
return;
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "Player::UpdateItemDuration(%u, %u)", 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()->FlagsCu & 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::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 (item && 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->EnchantmentCondition && !EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
return;
if (pEnchant->requiredLevel > getLevel())
return;
if (pEnchant->requiredSkill > 0 && pEnchant->requiredSkillValue > GetSkillValue(pEnchant->requiredSkill))
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->requiredSkill > 0 && pPrismaticEnchant->requiredSkillValue > GetSkillValue(pPrismaticEnchant->requiredSkill)))
return;
}
if (!item->IsBroken())
{
for (int s = 0; s < MAX_ITEM_ENCHANTMENT_EFFECTS; ++s)
{
uint32 enchant_display_type = pEnchant->type[s];
uint32 enchant_amount = pEnchant->amount[s];
uint32 enchant_spell_id = pEnchant->spellid[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:
if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
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->enchant_id[k] == enchant_id)
{
basepoints = int32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000);
break;
}
}
}
}
// Cast custom spell vs all equal basepoints got from enchant_amount
if (basepoints)
CastCustomSpell(this, enchant_spell_id, &basepoints, &basepoints, &basepoints, true, item);
else
CastSpell(this, enchant_spell_id, true, item);
}
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->enchant_id[k] == enchant_id)
{
enchant_amount = uint32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000);
break;
}
}
}
}
HandleStatModifier(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->enchant_id[k] == enchant_id)
{
enchant_amount = uint32((item_rand_suffix->prefix[k] * item->GetItemSuffixFactor()) / 10000);
break;
}
}
}
}
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "Adding %u to stat nb %u", enchant_amount, enchant_spell_id);
switch (enchant_spell_id)
{
case ITEM_MOD_MANA:
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "+ %u MANA", enchant_amount);
HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(enchant_amount), apply);
break;
case ITEM_MOD_HEALTH:
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "+ %u HEALTH", enchant_amount);
HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(enchant_amount), apply);
break;
case ITEM_MOD_AGILITY:
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "+ %u AGILITY", enchant_amount);
HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
ApplyStatBuffMod(STAT_AGILITY, (float)enchant_amount, apply);
break;
case ITEM_MOD_STRENGTH:
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "+ %u STRENGTH", enchant_amount);
HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
ApplyStatBuffMod(STAT_STRENGTH, (float)enchant_amount, apply);
break;
case ITEM_MOD_INTELLECT:
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "+ %u INTELLECT", enchant_amount);
HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
ApplyStatBuffMod(STAT_INTELLECT, (float)enchant_amount, apply);
break;
case ITEM_MOD_SPIRIT:
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "+ %u SPIRIT", enchant_amount);
HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
ApplyStatBuffMod(STAT_SPIRIT, (float)enchant_amount, apply);
break;
case ITEM_MOD_STAMINA:
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "+ %u STAMINA", enchant_amount);
HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
ApplyStatBuffMod(STAT_STAMINA, (float)enchant_amount, apply);
break;
case ITEM_MOD_DEFENSE_SKILL_RATING:
ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "+ %u DEFENCE", enchant_amount);
break;
case ITEM_MOD_DODGE_RATING:
ApplyRatingMod(CR_DODGE, enchant_amount, apply);
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "+ %u DODGE", enchant_amount);
break;
case ITEM_MOD_PARRY_RATING:
ApplyRatingMod(CR_PARRY, enchant_amount, apply);
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "+ %u PARRY", enchant_amount);
break;
case ITEM_MOD_BLOCK_RATING:
ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "+ %u SHIELD_BLOCK", enchant_amount);
break;
case ITEM_MOD_HIT_MELEE_RATING:
ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "+ %u MELEE_HIT", enchant_amount);
break;
case ITEM_MOD_HIT_RANGED_RATING:
ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "+ %u RANGED_HIT", enchant_amount);
break;
case ITEM_MOD_HIT_SPELL_RATING:
ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "+ %u SPELL_HIT", enchant_amount);
break;
case ITEM_MOD_CRIT_MELEE_RATING:
ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "+ %u MELEE_CRIT", enchant_amount);
break;
case ITEM_MOD_CRIT_RANGED_RATING:
ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "+ %u RANGED_CRIT", enchant_amount);
break;
case ITEM_MOD_CRIT_SPELL_RATING:
ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "+ %u 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(LOG_FILTER_PLAYER_ITEMS, "+ %u 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(LOG_FILTER_PLAYER_ITEMS, "+ %u 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(LOG_FILTER_PLAYER_ITEMS, "+ %u 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(LOG_FILTER_PLAYER_ITEMS, "+ %u HASTE", enchant_amount);
break;
case ITEM_MOD_EXPERTISE_RATING:
ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "+ %u EXPERTISE", enchant_amount);
break;
case ITEM_MOD_ATTACK_POWER:
HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "+ %u ATTACK_POWER", enchant_amount);
break;
case ITEM_MOD_RANGED_ATTACK_POWER:
HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "+ %u RANGED_ATTACK_POWER", enchant_amount);
break;
// case ITEM_MOD_FERAL_ATTACK_POWER:
// ApplyFeralAPBonus(enchant_amount, apply);
// TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "+ %u FERAL_ATTACK_POWER", enchant_amount);
// break;
case ITEM_MOD_MANA_REGENERATION:
ApplyManaRegenBonus(enchant_amount, apply);
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "+ %u MANA_REGENERATION", enchant_amount);
break;
case ITEM_MOD_ARMOR_PENETRATION_RATING:
ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "+ %u ARMOR PENETRATION", enchant_amount);
break;
case ITEM_MOD_SPELL_POWER:
ApplySpellPowerBonus(enchant_amount, apply);
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "+ %u SPELL_POWER", enchant_amount);
break;
case ITEM_MOD_HEALTH_REGEN:
ApplyHealthRegenBonus(enchant_amount, apply);
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "+ %u HEALTH_REGENERATION", enchant_amount);
break;
case ITEM_MOD_SPELL_PENETRATION:
ApplySpellPenetrationBonus(enchant_amount, apply);
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "+ %u SPELL_PENETRATION", enchant_amount);
break;
case ITEM_MOD_BLOCK_VALUE:
HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(enchant_amount), apply);
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "+ %u 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
{
if (getClass() == CLASS_SHAMAN)
{
float addValue = 0.0f;
if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
{
addValue = float(enchant_amount * item->GetTemplate()->Delay / 1000.0f);
HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
}
else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
{
addValue = float(enchant_amount * item->GetTemplate()->Delay / 1000.0f);
HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
}
}
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(LOG_FILTER_PLAYER, "Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type);
break;
} /*switch (enchant_display_type)*/
} /*for*/
}
// 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->requiredSkill == skill_id)
{
// Checks if the enchantment needs to be applied or removed
if (curr_value < Enchant->requiredSkillValue && new_value >= Enchant->requiredSkillValue)
ApplyEnchantment(m_items[i], EnchantmentSlot(slot), true);
else if (new_value < Enchant->requiredSkillValue && curr_value >= Enchant->requiredSkillValue)
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->requiredSkill == skill_id)
{
if (curr_value < pPrismaticEnchant->requiredSkillValue && new_value >= pPrismaticEnchant->requiredSkillValue)
ApplyEnchantment(m_items[i], EnchantmentSlot(slot), true);
else if (new_value < pPrismaticEnchant->requiredSkillValue && curr_value >= pPrismaticEnchant->requiredSkillValue)
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)
{
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 << uint64(GetGUID()); // player GUID
data << uint32(received); // 0=looted, 1=from npc
data << uint32(created); // 0=received, 1=created
data << uint32(1); // bool print error 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
GetSession()->SendPacket(&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(LOG_FILTER_SQL, "Creature %s (Entry: %u GUID: %u DB GUID: %u) has UNIT_NPC_FLAG_VENDOR set but has an empty trading item list.", creature->GetName().c_str(), creature->GetEntry(), creature->GetGUIDLow(), creature->GetDBTableGUIDLow());
canTalk = false;
}
break;
}
case GOSSIP_OPTION_LEARNDUALSPEC:
if (!(GetSpecsCount() == 1 && creature->isCanTrainingAndResetTalentsOf(this) && !(getLevel() < sWorld->getIntConfig(CONFIG_MIN_DUALSPEC_LEVEL))))
canTalk = false;
break;
case GOSSIP_OPTION_UNLEARNTALENTS:
if (!creature->isCanTrainingAndResetTalentsOf(this))
canTalk = false;
break;
case GOSSIP_OPTION_UNLEARNPETTALENTS:
if (!GetPet() || GetPet()->getPetType() != HUNTER_PET || GetPet()->m_spells.size() <= 1 || creature->GetCreatureTemplate()->trainer_type != TRAINER_TYPE_PETS || creature->GetCreatureTemplate()->trainer_class != CLASS_HUNTER)
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:
if (getClass() != creature->GetCreatureTemplate()->trainer_class && creature->GetCreatureTemplate()->trainer_type == TRAINER_TYPE_CLASS)
TC_LOG_ERROR(LOG_FILTER_SQL, "GOSSIP_OPTION_TRAINER:: Player %s (GUID: %u) request wrong gossip menu: %u with wrong class: %u at Creature: %s (Entry: %u, Trainer Class: %u)",
GetName().c_str(), GetGUIDLow(), menu->GetGossipMenu().GetMenuId(), getClass(), creature->GetName().c_str(), creature->GetEntry(), creature->GetCreatureTemplate()->trainer_class);
// no break;
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(LOG_FILTER_SQL, "Creature entry %u has unknown gossip option %u for menu %u", 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 = itr->second.OptionText;
std::string strBoxText = itr->second.BoxText;
int32 locale = GetSession()->GetSessionDbLocaleIndex();
if (locale >= 0)
{
uint32 idxEntry = MAKE_PAIR32(menuId, itr->second.OptionIndex);
if (GossipMenuItemsLocale const* no = sObjectMgr->GetGossipMenuItemsLocale(idxEntry))
{
ObjectMgr::GetLocaleString(no->OptionText, locale, strOptionText);
ObjectMgr::GetLocaleString(no->BoxText, locale, strBoxText);
}
}
menu->GetGossipMenu().AddMenuItem(itr->second.OptionIndex, itr->second.OptionIcon, strOptionText, 0, itr->second.OptionType, strBoxText, itr->second.BoxMoney, itr->second.BoxCoded);
menu->GetGossipMenu().AddGossipMenuItemData(itr->second.OptionIndex, 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()->HasFlag(UNIT_NPC_FLAGS, 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;
uint64 guid = source->GetGUID();
if (source->GetTypeId() == TYPEID_GAMEOBJECT)
{
if (gossipOptionId > GOSSIP_OPTION_QUESTGIVER)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player guid %u request invalid gossip option for GameObject entry %u", GetGUIDLow(), 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, 0, 0, 0);
PlayerTalkClass->SendCloseGossip();
return;
}
switch (gossipOptionId)
{
case GOSSIP_OPTION_GOSSIP:
{
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->GetGUID(), gossipListId);
break;
case GOSSIP_OPTION_SPIRITHEALER:
if (isDead())
source->ToCreature()->CastSpell(source->ToCreature(), 17251, true, NULL, NULL, 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(guid);
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, true, NULL, NULL, GetGUID());
CastSpell(this, 63624, true, NULL, NULL, GetGUID());
// Should show another Gossip text with "Congratulations..."
PlayerTalkClass->SendCloseGossip();
}
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(LOG_FILTER_PLAYER, "a user (guid %u) requested battlegroundlist from a npc who is no battlemaster", GetGUIDLow());
return;
}
GetSession()->SendBattleGroundList(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.text_id;
}
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(uint64 guid)
{
QuestRelationBounds objectQR;
QuestRelationBounds objectQIR;
// pets also can have quests
Creature* creature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, guid);
if (creature)
{
objectQR = sObjectMgr->GetCreatureQuestRelationBounds(creature->GetEntry());
objectQIR = sObjectMgr->GetCreatureQuestInvolvedRelationBounds(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* pGameObject = _map->GetGameObject(guid);
if (pGameObject)
{
objectQR = sObjectMgr->GetGOQuestRelationBounds(pGameObject->GetEntry());
objectQIR = sObjectMgr->GetGOQuestInvolvedRelationBounds(pGameObject->GetEntry());
}
else
return;
}
QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
qm.ClearMenu();
for (QuestRelations::const_iterator i = objectQIR.first; i != objectQIR.second; ++i)
{
uint32 quest_id = i->second;
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 (QuestRelations::const_iterator i = objectQR.first; i != objectQR.second; ++i)
{
uint32 quest_id = i->second;
Quest const* quest = sObjectMgr->GetQuestTemplate(quest_id);
if (!quest)
continue;
if (!CanTakeQuest(quest, false))
continue;
if (quest->IsAutoComplete())
qm.AddMenuItem(quest_id, 4);
else if (GetQuestStatus(quest_id) == QUEST_STATUS_NONE)
qm.AddMenuItem(quest_id, 2);
}
}
void Player::SendPreparedQuest(uint64 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))
{
AddQuest(quest, object);
if (CanCompleteQuest(questId))
CompleteQuest(questId);
}
if ((quest->IsAutoComplete() && quest->IsRepeatable() && !quest->IsDailyOrWeekly()) || quest->HasFlag(QUEST_FLAGS_AUTOCOMPLETE))
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._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
title = "";
}
else
{
qe = gossiptext->Options[0].Emotes[0];
if (!gossiptext->Options[0].Text_0.empty())
{
title = gossiptext->Options[0].Text_0;
int loc_idx = GetSession()->GetSessionDbLocaleIndex();
if (loc_idx >= 0)
if (NpcTextLocale const* nl = sObjectMgr->GetNpcTextLocale(textid))
ObjectMgr::GetLocaleString(nl->Text_0[0], loc_idx, title);
}
else
{
title = gossiptext->Options[0].Text_1;
int loc_idx = GetSession()->GetSessionDbLocaleIndex();
if (loc_idx >= 0)
if (NpcTextLocale const* nl = sObjectMgr->GetNpcTextLocale(textid))
ObjectMgr::GetLocaleString(nl->Text_1[0], loc_idx, 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(uint64 guid, Quest const* quest)
{
QuestRelationBounds objectQR;
Creature* creature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, guid);
if (creature)
objectQR = sObjectMgr->GetCreatureQuestRelationBounds(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* pGameObject = _map->GetGameObject(guid);
if (pGameObject)
objectQR = sObjectMgr->GetGOQuestRelationBounds(pGameObject->GetEntry());
else
return NULL;
}
uint32 nextQuestID = quest->GetNextQuestInChain();
for (QuestRelations::const_iterator itr = objectQR.first; itr != objectQR.second; ++itr)
{
if (itr->second == nextQuestID)
return sObjectMgr->GetQuestTemplate(nextQuestID);
}
return NULL;
}
bool Player::CanSeeStartQuest(Quest const* quest)
{
if (!DisableMgr::IsDisabledFor(DISABLE_TYPE_QUEST, quest->GetQuestId(), this) && SatisfyQuestClass(quest, false) && SatisfyQuestRace(quest, false) &&
SatisfyQuestSkill(quest, false) && SatisfyQuestExclusiveGroup(quest, false) && SatisfyQuestReputation(quest, false) &&
SatisfyQuestPreviousQuest(quest, false) && SatisfyQuestNextChain(quest, false) &&
SatisfyQuestPrevChain(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)
{
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)
&& SatisfyQuestPreviousQuest(quest, msg) && SatisfyQuestTimed(quest, msg)
&& SatisfyQuestNextChain(quest, msg) && SatisfyQuestPrevChain(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)
{
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_CANT_CARRY_MORE_OF_THIS)
return true;
else if (msg2 != EQUIP_ERR_OK)
{
SendEquipError(msg2, NULL, NULL, 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() && m_RewardedQuests.find(quest_id) != m_RewardedQuests.end())
return false; // not allow re-complete quest
// auto complete quest
if ((qInfo->IsAutoComplete() || qInfo->GetFlags() & QUEST_FLAGS_AUTOCOMPLETE) && 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->HasFlag(QUEST_TRINITY_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->HasFlag(QUEST_TRINITY_FLAGS_KILL_OR_CAST | QUEST_TRINITY_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->HasFlag(QUEST_TRINITY_FLAGS_PLAYER_KILL))
if (qInfo->GetPlayersSlain() != 0 && q_status.PlayerCount < qInfo->GetPlayersSlain())
return false;
if (qInfo->HasFlag(QUEST_TRINITY_FLAGS_EXPLORATION_OR_EVENT) && !q_status.Explored)
return false;
if (qInfo->HasFlag(QUEST_TRINITY_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->HasFlag(QUEST_TRINITY_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)
{
// not auto complete quest and not completed quest (only cheating case, then ignore without message)
if (!quest->IsDFQuest() && !quest->IsAutoComplete() && !(quest->GetFlags() & QUEST_FLAGS_AUTOCOMPLETE) && GetQuestStatus(quest->GetQuestId()) != QUEST_STATUS_COMPLETE)
return false;
// daily quest can't be rewarded (25 daily quest already completed)
if (!SatisfyQuestDay(quest, true) || !SatisfyQuestWeek(quest, true) || !SatisfyQuestMonth(quest, true) || !SatisfyQuestSeasonal(quest, true))
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->HasFlag(QUEST_TRINITY_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, NULL, NULL, 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;
}
bool Player::CanRewardQuest(Quest const* quest, uint32 reward, bool msg)
{
// prevent receive reward with quest items in bank or for not completed quest
if (!CanRewardQuest(quest, msg))
return false;
if (quest->GetRewChoiceItemsCount() > 0)
{
if (quest->RewardChoiceItemId[reward])
{
ItemPosCountVec dest;
InventoryResult res = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, quest->RewardChoiceItemId[reward], quest->RewardChoiceItemCount[reward]);
if (res != EQUIP_ERR_OK)
{
SendEquipError(res, NULL, NULL, quest->RewardChoiceItemId[reward]);
return false;
}
}
}
if (quest->GetRewItemsCount() > 0)
{
for (uint32 i = 0; i < quest->GetRewItemsCount(); ++i)
{
if (quest->RewardItemId[i])
{
ItemPosCountVec dest;
InventoryResult res = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, quest->RewardItemId[i], quest->RewardItemIdCount[i]);
if (res != EQUIP_ERR_OK)
{
SendEquipError(res, NULL, NULL, quest->RewardItemId[i]);
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->HasFlag(QUEST_TRINITY_FLAGS_DELIVER))
{
for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
questStatusData.ItemCount[i] = 0;
}
if (quest->HasFlag(QUEST_TRINITY_FLAGS_KILL_OR_CAST | QUEST_TRINITY_FLAGS_SPEAKTO))
{
for (uint8 i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
questStatusData.CreatureOrGOCount[i] = 0;
}
if (quest->HasFlag(QUEST_TRINITY_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->HasFlag(QUEST_TRINITY_FLAGS_TIMED))
{
uint32 limittime = quest->GetLimitTime();
// shared timed quest
if (questGiver && questGiver->GetTypeId() == TYPEID_PLAYER)
limittime = questGiver->ToPlayer()->getQuestStatusMap()[quest_id].Timer / IN_MILLISECONDS;
AddTimedQuest(quest_id);
questStatusData.Timer = limittime * IN_MILLISECONDS;
qtime = static_cast<uint32>(time(NULL)) + limittime;
}
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] = true;
StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_QUEST, quest_id);
UpdateForQuestWorldObjects();
}
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);
else
SendQuestComplete(quest_id);
}
}
}
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 (quest->RequiredItemId[i])
DestroyItemCount(quest->RequiredItemId[i], quest->RequiredItemCount[i], true);
for (uint8 i = 0; i < QUEST_SOURCE_ITEM_IDS_COUNT; ++i)
{
if (quest->RequiredSourceItemId[i])
{
uint32 count = quest->RequiredSourceItemCount[i];
DestroyItemCount(quest->RequiredSourceItemId[i], count ? count : 9999, true);
}
}
RemoveTimedQuest(quest_id);
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, Item::GenerateItemRandomPropertyId(itemId));
SendNewItem(item, quest->RewardChoiceItemCount[reward], true, false);
}
}
}
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, Item::GenerateItemRandomPropertyId(itemId));
SendNewItem(item, quest->RewardItemIdCount[i], true, false);
}
}
}
}
RewardReputation(quest);
uint16 log_slot = FindQuestSlot(quest_id);
if (log_slot < MAX_QUEST_LOG_SIZE)
SetQuestSlot(log_slot, 0);
bool rewarded = (m_RewardedQuests.find(quest_id) != m_RewardedQuests.end());
// Not give XP in case already completed once repeatable quest
uint32 XP = rewarded ? 0 : uint32(quest->XPValue(this)*sWorld->getRate(RATE_XP_QUEST));
// handle SPELL_AURA_MOD_XP_QUEST_PCT auras
Unit::AuraEffectList const& ModXPPctAuras = GetAuraEffectsByType(SPELL_AURA_MOD_XP_QUEST_PCT);
for (Unit::AuraEffectList::const_iterator i = ModXPPctAuras.begin(); i != ModXPPctAuras.end(); ++i)
AddPct(XP, (*i)->GetAmount());
int32 moneyRew = 0;
if (getLevel() < sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL))
GiveXP(XP, NULL);
else
moneyRew = int32(quest->GetRewMoneyMaxLevel() * sWorld->getRate(RATE_DROP_MONEY));
// Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
if (quest->GetRewOrReqMoney())
moneyRew += quest->GetRewOrReqMoney();
if (moneyRew)
{
ModifyMoney(moneyRew);
if (moneyRew > 0)
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, uint32(moneyRew));
}
// honor reward
if (uint32 honor = quest->CalculateHonorGain(getLevel()))
RewardHonor(NULL, 0, honor);
// title reward
if (quest->GetCharTitleId())
{
if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(quest->GetCharTitleId()))
SetTitle(titleEntry);
}
if (quest->GetBonusTalents())
{
m_questRewardTalentCount+=quest->GetBonusTalents();
InitTalentForLevel();
}
if (quest->GetRewArenaPoints())
ModifyArenaPoints(quest->GetRewArenaPoints());
// Send reward mail
if (uint32 mail_template_id = quest->GetRewMailTemplateId())
{
/// @todo Poor design of mail system
SQLTransaction trans = CharacterDatabase.BeginTransaction();
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);
m_RewardedQuests.insert(quest_id);
m_RewardedQuestsSave[quest_id] = true;
// StoreNewItem, mail reward, etc. save data directly to the database
// to prevent exploitable data desynchronisation we save the quest status to the database too
// (to prevent rewarding this quest another time while rewards were already given out)
SQLTransaction trans = SQLTransaction(NULL);
_SaveQuestStatus(trans);
if (announce)
SendQuestReward(quest, XP);
// cast spells after mark quest complete (some spells have quest completed state requirements in spell_area data)
if (quest->GetRewSpellCast() > 0)
CastSpell(this, quest->GetRewSpellCast(), true);
else if (quest->GetRewSpell() > 0)
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());
if (quest->HasFlag(QUEST_FLAGS_FLAGS_PVP))
{
pvpInfo.IsHostile = pvpInfo.IsInHostileArea || HasPvPForcingQuest();
UpdatePvPState();
}
//lets remove flag for delayed teleports
SetCanDelayTeleport(false);
}
void Player::FailQuest(uint32 questId)
{
if (Quest const* quest = sObjectMgr->GetQuestTemplate(questId))
{
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->HasFlag(QUEST_TRINITY_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_OBJECTIVES_COUNT; ++i)
if (quest->RequiredItemId[i] > 0 && quest->RequiredItemCount[i] > 0)
// Destroy items received on starting the quest.
DestroyItemCount(quest->RequiredItemId[i], quest->RequiredItemCount[i], true, true);
for (uint8 i = 0; i < QUEST_SOURCE_ITEM_IDS_COUNT; ++i)
if (quest->RequiredSourceItemId[i] > 0 && quest->RequiredSourceItemCount[i] > 0)
// Destroy items received during the quest.
DestroyItemCount(quest->RequiredSourceItemId[i], quest->RequiredSourceItemCount[i], true, 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(LOG_FILTER_GENERAL, "SatisfyQuestSkill: Sent INVALIDREASON_DONT_HAVE_REQ (questId: %u) because player does not have required skill value.", qInfo->GetQuestId());
}
return false;
}
return true;
}
bool Player::SatisfyQuestLevel(Quest const* qInfo, bool msg)
{
if (getLevel() < qInfo->GetMinLevel())
{
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_QUEST_FAILED_LOW_LEVEL);
TC_LOG_DEBUG(LOG_FILTER_GENERAL, "SatisfyQuestLevel: Sent INVALIDREASON_QUEST_FAILED_LOW_LEVEL (questId: %u) because player does not have required (min) level.", qInfo->GetQuestId());
}
return false;
}
else 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(LOG_FILTER_GENERAL, "SatisfyQuestLevel: Sent INVALIDREASON_QUEST_FAILED_LOW_LEVEL (questId: %u) because player does not have required (max) level.", qInfo->GetQuestId());
}
return false;
}
return true;
}
bool Player::SatisfyQuestLog(bool msg)
{
// exist free slot
if (FindQuestSlot(0) < MAX_QUEST_LOG_SIZE)
return true;
if (msg)
{
WorldPacket data(SMSG_QUESTLOG_FULL, 0);
GetSession()->SendPacket(&data);
TC_LOG_DEBUG(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_QUESTLOG_FULL");
}
return false;
}
bool Player::SatisfyQuestPreviousQuest(Quest const* qInfo, bool msg)
{
// No previous quest (might be first quest in a series)
if (qInfo->prevQuests.empty())
return true;
for (Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter)
{
uint32 prevId = abs(*iter);
Quest const* qPrevInfo = sObjectMgr->GetQuestTemplate(prevId);
if (qPrevInfo)
{
// If any of the positive previous quests completed, return true
if (*iter > 0 && m_RewardedQuests.find(prevId) != m_RewardedQuests.end())
{
// skip one-from-all exclusive group
if (qPrevInfo->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
ObjectMgr::ExclusiveQuestGroupsBounds range(sObjectMgr->mExclusiveQuestGroups.equal_range(qPrevInfo->GetExclusiveGroup()));
// always must be found if qPrevInfo->ExclusiveGroup != 0
ASSERT(range.first != range.second);
for (; range.first != range.second; ++range.first)
{
uint32 exclude_Id = range.first->second;
// skip checked quest id, only state of other quests in group is interesting
if (exclude_Id == prevId)
continue;
// alternative quest from group also must be completed and rewarded (reported)
if (m_RewardedQuests.find(exclude_Id) == m_RewardedQuests.end())
{
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
TC_LOG_DEBUG(LOG_FILTER_GENERAL, "SatisfyQuestPreviousQuest: Sent INVALIDREASON_DONT_HAVE_REQ (questId: %u) because player does not have required quest (1).", qInfo->GetQuestId());
}
return false;
}
}
return true;
}
// If any of the negative previous quests active, return true
if (*iter < 0 && GetQuestStatus(prevId) != QUEST_STATUS_NONE)
{
// skip one-from-all exclusive group
if (qPrevInfo->GetExclusiveGroup() >= 0)
return true;
// each-from-all exclusive group (< 0)
// can be start if only all quests in prev quest exclusive group active
ObjectMgr::ExclusiveQuestGroupsBounds range(sObjectMgr->mExclusiveQuestGroups.equal_range(qPrevInfo->GetExclusiveGroup()));
// always must be found if qPrevInfo->ExclusiveGroup != 0
ASSERT(range.first != range.second);
for (; range.first != range.second; ++range.first)
{
uint32 exclude_Id = range.first->second;
// skip checked quest id, only state of other quests in group is interesting
if (exclude_Id == prevId)
continue;
// alternative quest from group also must be active
if (GetQuestStatus(exclude_Id) != QUEST_STATUS_NONE)
{
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
TC_LOG_DEBUG(LOG_FILTER_GENERAL, "SatisfyQuestPreviousQuest: Sent INVALIDREASON_DONT_HAVE_REQ (questId: %u) because player does not have required quest (2).", qInfo->GetQuestId());
}
return false;
}
}
return true;
}
}
}
// Has only positive prev. quests in non-rewarded state
// and negative prev. quests in non-active state
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
TC_LOG_DEBUG(LOG_FILTER_GENERAL, "SatisfyQuestPreviousQuest: Sent INVALIDREASON_DONT_HAVE_REQ (questId: %u) because player does not have required quest (3).", qInfo->GetQuestId());
}
return false;
}
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(LOG_FILTER_GENERAL, "SatisfyQuestClass: Sent INVALIDREASON_DONT_HAVE_REQ (questId: %u) because player does not have required class.", qInfo->GetQuestId());
}
return false;
}
return true;
}
bool Player::SatisfyQuestRace(Quest const* qInfo, bool msg)
{
uint32 reqraces = qInfo->GetRequiredRaces();
if (reqraces == 0)
return true;
if ((reqraces & getRaceMask()) == 0)
{
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_QUEST_FAILED_WRONG_RACE);
TC_LOG_DEBUG(LOG_FILTER_GENERAL, "SatisfyQuestRace: Sent INVALIDREASON_QUEST_FAILED_WRONG_RACE (questId: %u) because player does not have required race.", qInfo->GetQuestId());
}
return false;
}
return true;
}
bool Player::SatisfyQuestReputation(Quest const* qInfo, bool msg)
{
uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
if (fIdMin && GetReputationMgr().GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
{
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
TC_LOG_DEBUG(LOG_FILTER_GENERAL, "SatisfyQuestReputation: Sent INVALIDREASON_DONT_HAVE_REQ (questId: %u) because player does not have required reputation (min).", qInfo->GetQuestId());
}
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(LOG_FILTER_GENERAL, "SatisfyQuestReputation: Sent INVALIDREASON_DONT_HAVE_REQ (questId: %u) because player does not have required reputation (max).", qInfo->GetQuestId());
}
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(LOG_FILTER_GENERAL, "SatisfyQuestReputation: Sent INVALIDREASON_DONT_HAVE_REQ (questId: %u) because player does not have required reputation (ReputationObjective2).", qInfo->GetQuestId());
}
return false;
}
return true;
}
bool Player::SatisfyQuestStatus(Quest const* qInfo, bool msg)
{
if (GetQuestStatus(qInfo->GetQuestId()) != QUEST_STATUS_NONE)
{
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_QUEST_ALREADY_ON);
TC_LOG_DEBUG(LOG_FILTER_GENERAL, "SatisfyQuestStatus: Sent INVALIDREASON_QUEST_ALREADY_ON (questId: %u) because player quest status is not NONE.", qInfo->GetQuestId());
}
return false;
}
return true;
}
bool Player::SatisfyQuestConditions(Quest const* qInfo, bool msg)
{
ConditionList conditions = sConditionMgr->GetConditionsForNotGroupedEntry(CONDITION_SOURCE_TYPE_QUEST_ACCEPT, qInfo->GetQuestId());
if (!sConditionMgr->IsObjectMeetToConditions(this, conditions))
{
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
TC_LOG_DEBUG(LOG_FILTER_GENERAL, "SatisfyQuestConditions: Sent INVALIDREASON_DONT_HAVE_REQ (questId: %u) because player does not meet conditions.", qInfo->GetQuestId());
}
TC_LOG_DEBUG(LOG_FILTER_CONDITIONSYS, "Player::SatisfyQuestConditions: conditions not met for quest %u", qInfo->GetQuestId());
return false;
}
return true;
}
bool Player::SatisfyQuestTimed(Quest const* qInfo, bool msg)
{
if (!m_timedquests.empty() && qInfo->HasFlag(QUEST_TRINITY_FLAGS_TIMED))
{
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_QUEST_ONLY_ONE_TIMED);
TC_LOG_DEBUG(LOG_FILTER_GENERAL, "SatisfyQuestTimed: Sent INVALIDREASON_QUEST_ONLY_ONE_TIMED (questId: %u) because player is already on a timed quest.", qInfo->GetQuestId());
}
return false;
}
return true;
}
bool Player::SatisfyQuestExclusiveGroup(Quest const* qInfo, bool msg)
{
// 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;
ObjectMgr::ExclusiveQuestGroupsBounds range(sObjectMgr->mExclusiveQuestGroups.equal_range(qInfo->GetExclusiveGroup()));
// always must be found if qInfo->ExclusiveGroup != 0
ASSERT(range.first != range.second);
for (; range.first != range.second; ++range.first)
{
uint32 exclude_Id = range.first->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);
if (!SatisfyQuestDay(Nquest, false) || !SatisfyQuestWeek(Nquest, false) || !SatisfyQuestSeasonal(Nquest, false))
{
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
TC_LOG_DEBUG(LOG_FILTER_GENERAL, "SatisfyQuestExclusiveGroup: Sent INVALIDREASON_DONT_HAVE_REQ (questId: %u) because player already did daily quests in exclusive group.", qInfo->GetQuestId());
}
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()) && (m_RewardedQuests.find(exclude_Id) != m_RewardedQuests.end())))
{
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
TC_LOG_DEBUG(LOG_FILTER_GENERAL, "SatisfyQuestExclusiveGroup: Sent INVALIDREASON_DONT_HAVE_REQ (questId: %u) because player already did quest in exclusive group.", qInfo->GetQuestId());
}
return false;
}
}
return true;
}
bool Player::SatisfyQuestNextChain(Quest const* qInfo, bool msg)
{
uint32 nextQuest = qInfo->GetNextQuestInChain();
if (!nextQuest)
return true;
// next quest in chain already started or completed
if (GetQuestStatus(nextQuest) != QUEST_STATUS_NONE) // GetQuestStatus returns QUEST_STATUS_COMPLETED for rewarded quests
{
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
TC_LOG_DEBUG(LOG_FILTER_GENERAL, "SatisfyQuestNextChain: Sent INVALIDREASON_DONT_HAVE_REQ (questId: %u) because player already did or started next quest in chain.", qInfo->GetQuestId());
}
return false;
}
// check for all quests further up the chain
// only necessary if there are quest chains with more than one quest that can be skipped
//return SatisfyQuestNextChain(qInfo->GetNextQuestInChain(), msg);
return true;
}
bool Player::SatisfyQuestPrevChain(Quest const* qInfo, bool msg)
{
// No previous quest in chain
if (qInfo->prevChainQuests.empty())
return true;
for (Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter)
{
QuestStatusMap::const_iterator itr = m_QuestStatus.find(*iter);
// If any of the previous quests in chain active, return false
if (itr != m_QuestStatus.end() && itr->second.Status != QUEST_STATUS_NONE)
{
if (msg)
{
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
TC_LOG_DEBUG(LOG_FILTER_GENERAL, "SatisfyQuestNextChain: Sent INVALIDREASON_DONT_HAVE_REQ (questId: %u) because player already did or started next quest in chain.", qInfo->GetQuestId());
}
return false;
}
// check for all quests further down the chain
// only necessary if there are quest chains with more than one quest that can be skipped
//if (!SatisfyQuestPrevChain(prevId, msg))
// return false;
}
// No previous quest in chain active
return true;
}
bool Player::SatisfyQuestDay(Quest const* qInfo, bool msg)
{
if (!qInfo->IsDaily() && !qInfo->IsDFQuest())
return true;
if (qInfo->IsDFQuest())
{
if (!m_DFQuests.empty())
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(LOG_FILTER_GENERAL, "SatisfyQuestDay: Sent INVALIDREASON_DAILY_QUESTS_REMAINING (questId: %u) because player already did all possible quests today.", qInfo->GetQuestId());
}
return false;
}
return true;
}
bool Player::SatisfyQuestWeek(Quest const* qInfo, bool /*msg*/)
{
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*/)
{
if (!qInfo->IsSeasonal() || m_seasonalquests.empty())
return true;
uint16 eventId = sGameEventMgr->GetEventIdForQuest(qInfo);
if (m_seasonalquests.find(eventId) == m_seasonalquests.end() || m_seasonalquests[eventId].empty())
return true;
// if not found in cooldown list
return m_seasonalquests[eventId].find(qInfo->GetQuestId()) == m_seasonalquests[eventId].end();
}
bool Player::SatisfyQuestMonth(Quest const* qInfo, bool /*msg*/)
{
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)
{
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_CANT_CARRY_MORE_OF_THIS)
return true;
else
SendEquipError(msg, NULL, NULL, 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;
// exist two cases when destroy source quest item not possible:
// a) non un-equippable item (equipped non-empty bag, for example)
// b) when quest is started from an item and item also is needed in
// the end as RequiredItemId
InventoryResult res = CanUnequipItems(srcItemId, count);
if (res != EQUIP_ERR_OK)
{
if (msg)
SendEquipError(res, NULL, NULL, srcItemId);
return false;
}
bool destroyItem = true;
for (uint8 n = 0; n < QUEST_ITEM_OBJECTIVES_COUNT; ++n)
if (item->StartQuest == questId && srcItemId == quest->RequiredItemId[n])
destroyItem = false;
if (destroyItem)
DestroyItemCount(srcItemId, count, true, true);
}
}
return true;
}
bool Player::GetQuestRewardStatus(uint32 quest_id) const
{
Quest const* qInfo = sObjectMgr->GetQuestTemplate(quest_id);
if (qInfo)
{
// for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
if (!qInfo->IsRepeatable())
return m_RewardedQuests.find(quest_id) != m_RewardedQuests.end();
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 (Quest const* qInfo = sObjectMgr->GetQuestTemplate(quest_id))
if (!qInfo->IsRepeatable() && m_RewardedQuests.find(quest_id) != m_RewardedQuests.end())
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())
return itr->second.Status == QUEST_STATUS_INCOMPLETE;
}
return false;
}
void Player::SetQuestStatus(uint32 quest_id, QuestStatus status)
{
if (sObjectMgr->GetQuestTemplate(quest_id))
{
m_QuestStatus[quest_id].Status = status;
m_QuestStatusSave[quest_id] = true;
}
uint32 zone = 0, area = 0;
SpellAreaForQuestMapBounds saBounds = sSpellMgr->GetSpellAreaForQuestMapBounds(quest_id);
if (saBounds.first != saBounds.second)
{
GetZoneAndAreaId(zone, area);
for (SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
if (itr->second->autocast && itr->second->IsFitToRequirements(this, zone, area))
if (!HasAura(itr->second->spellId))
CastSpell(this, itr->second->spellId, true);
}
saBounds = sSpellMgr->GetSpellAreaForQuestEndMapBounds(quest_id);
if (saBounds.first != saBounds.second)
{
if (!zone || !area)
GetZoneAndAreaId(zone, area);
for (SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
if (!itr->second->IsFitToRequirements(this, zone, area))
RemoveAurasDueToSpell(itr->second->spellId);
}
UpdateForQuestWorldObjects();
}
void Player::RemoveActiveQuest(uint32 quest_id)
{
QuestStatusMap::iterator itr = m_QuestStatus.find(quest_id);
if (itr != m_QuestStatus.end())
{
m_QuestStatus.erase(itr);
m_QuestStatusSave[quest_id] = false;
return;
}
}
void Player::RemoveRewardedQuest(uint32 quest_id)
{
RewardedQuestSet::iterator rewItr = m_RewardedQuests.find(quest_id);
if (rewItr != m_RewardedQuests.end())
{
m_RewardedQuests.erase(rewItr);
m_RewardedQuestsSave[quest_id] = false;
}
}
// not used in Trinity, but used in scripting code
uint16 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
{
Quest const* qInfo = sObjectMgr->GetQuestTemplate(quest_id);
if (!qInfo)
return 0;
for (uint8 j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
if (qInfo->RequiredNpcOrGo[j] == entry)
return m_QuestStatus[quest_id].CreatureOrGOCount[j];
return 0;
}
void Player::AdjustQuestReqItemCount(Quest const* quest, QuestStatusData& questStatusData)
{
if (quest->HasFlag(QUEST_TRINITY_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()] = true;
}
}
}
}
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];
if (!q_status.Explored)
{
q_status.Explored = true;
m_QuestStatusSave[questId] = true;
}
}
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 != NULL; 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->HasFlag(QUEST_TRINITY_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)
{
uint16 additemcount = curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount;
q_status.ItemCount[j] += additemcount;
m_QuestStatusSave[questid] = true;
SendQuestUpdateAddItem(qInfo, j, additemcount);
}
if (CanCompleteQuest(questid))
CompleteQuest(questid);
return;
}
}
}
UpdateForQuestWorldObjects();
}
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->HasFlag(QUEST_TRINITY_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 curitemcount;
if (q_status.Status != QUEST_STATUS_COMPLETE)
curitemcount = q_status.ItemCount[j];
else
curitemcount = GetItemCount(entry, true);
if (curitemcount < reqitemcount + count)
{
uint16 remitemcount = curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount;
q_status.ItemCount[j] = (curitemcount <= remitemcount) ? 0 : curitemcount - remitemcount;
m_QuestStatusSave[questid] = true;
IncompleteQuest(questid);
}
return;
}
}
}
UpdateForQuestWorldObjects();
}
void Player::KilledMonster(CreatureTemplate const* cInfo, uint64 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], 0);
}
void Player::KilledMonsterCredit(uint32 entry, uint64 guid /*= 0*/)
{
uint16 addkillcount = 1;
uint32 real_entry = entry;
Creature* killed = NULL;
if (guid)
{
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->HasFlag(QUEST_TRINITY_FLAGS_KILL_OR_CAST))
{
for (uint8 j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
{
// skip GO activate objective or none
if (qInfo->RequiredNpcOrGo[j] <= 0)
continue;
// skip Cast at creature objective
if (qInfo->RequiredSpellCast[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] = true;
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 addkillcount = 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;
// 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->HasFlag(QUEST_TRINITY_FLAGS_PLAYER_KILL))
{
uint32 reqkill = qInfo->GetPlayersSlain();
uint16 curkill = q_status.PlayerCount;
if (curkill < reqkill)
{
q_status.PlayerCount = curkill + addkillcount;
m_QuestStatusSave[questid] = true;
SendQuestUpdateAddPlayer(qInfo, curkill, addkillcount);
}
if (CanCompleteQuest(questid))
CompleteQuest(questid);
break;
}
}
}
}
void Player::CastedCreatureOrGO(uint32 entry, uint64 guid, uint32 spell_id)
{
bool isCreature = IS_CRE_OR_VEH_GUID(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->HasFlag(QUEST_TRINITY_FLAGS_KILL_OR_CAST))
{
for (uint8 j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
{
// skip kill creature objective (0) or wrong spell casts
if (qInfo->RequiredSpellCast[j] != spell_id)
continue;
uint32 reqTarget = 0;
if (isCreature)
{
// creature activate objectives
if (qInfo->RequiredNpcOrGo[j] > 0)
{
// checked at quest_template loading
reqTarget = qInfo->RequiredNpcOrGo[j];
if (reqTarget != entry) // if entry doesn't match, check for killcredits referenced in template
{
CreatureTemplate const* cinfo = sObjectMgr->GetCreatureTemplate(entry);
if (!cinfo)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player::CastedCreatureOrGO: GetCreatureTemplate failed for entry %u. Skipping.", entry);
continue;
}
for (uint8 k = 0; k < MAX_KILL_CREDIT; ++k)
if (cinfo->KillCredit[k] == reqTarget)
entry = cinfo->KillCredit[k];
}
}
}
else
{
// 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] = true;
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, uint64 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->HasFlag(QUEST_TRINITY_FLAGS_KILL_OR_CAST | QUEST_TRINITY_FLAGS_SPEAKTO))
{
for (uint8 j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
{
// skip spell casts and Gameobject objectives
if (qInfo->RequiredSpellCast[j] > 0 || 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] = true;
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) 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& q_status = qs_itr->second;
if (q_status.Status == QUEST_STATUS_INCOMPLETE)
{
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])
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->RequiredSourceItemId[j] == itemid)
{
ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(itemid);
// 'unique' item
if (pProto->MaxCount && int32(GetItemCount(itemid, true)) < pProto->MaxCount)
return true;
// allows custom amount drop when not 0
if (qinfo->RequiredSourceItemCount[j])
{
if (GetItemCount(itemid, true) < qinfo->RequiredSourceItemCount[j])
return true;
} else if (GetItemCount(itemid, true) < pProto->GetMaxStackSize())
return true;
}
}
}
}
return false;
}
void Player::SendQuestComplete(uint32 quest_id)
{
if (quest_id)
{
WorldPacket data(SMSG_QUESTUPDATE_COMPLETE, 4);
data << uint32(quest_id);
GetSession()->SendPacket(&data);
TC_LOG_DEBUG(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id);
}
}
void Player::SendQuestReward(Quest const* quest, uint32 XP)
{
uint32 questid = quest->GetQuestId();
TC_LOG_DEBUG(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid);
sGameEventMgr->HandleQuestComplete(questid);
WorldPacket data(SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4));
data << uint32(questid);
if (getLevel() < sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL))
{
data << uint32(XP);
data << uint32(quest->GetRewOrReqMoney());
}
else
{
data << uint32(0);
data << uint32(quest->GetRewOrReqMoney() + int32(quest->GetRewMoneyMaxLevel() * sWorld->getRate(RATE_DROP_MONEY)));
}
data << uint32(10 * quest->CalculateHonorGain(GetQuestLevel(quest)));
data << uint32(quest->GetBonusTalents()); // bonus talents
data << uint32(quest->GetRewArenaPoints());
GetSession()->SendPacket(&data);
}
void Player::SendQuestFailed(uint32 questId, InventoryResult reason)
{
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)
GetSession()->SendPacket(&data);
TC_LOG_DEBUG(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
}
}
void Player::SendQuestTimerFailed(uint32 quest_id)
{
if (quest_id)
{
WorldPacket data(SMSG_QUESTUPDATE_FAILEDTIMER, 4);
data << uint32(quest_id);
GetSession()->SendPacket(&data);
TC_LOG_DEBUG(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
}
}
void Player::SendCanTakeQuestResponse(QuestFailedReason msg) const
{
WorldPacket data(SMSG_QUESTGIVER_QUEST_INVALID, 4);
data << uint32(msg);
GetSession()->SendPacket(&data);
TC_LOG_DEBUG(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
}
void Player::SendQuestConfirmAccept(const Quest* quest, Player* pReceiver)
{
if (pReceiver)
{
std::string strTitle = quest->GetTitle();
int loc_idx = pReceiver->GetSession()->GetSessionDbLocaleIndex();
if (loc_idx >= 0)
if (const QuestLocale* pLocale = sObjectMgr->GetQuestLocale(quest->GetQuestId()))
ObjectMgr::GetLocaleString(pLocale->Title, loc_idx, strTitle);
WorldPacket data(SMSG_QUEST_CONFIRM_ACCEPT, (4 + strTitle.size() + 8));
data << uint32(quest->GetQuestId());
data << strTitle;
data << uint64(GetGUID());
pReceiver->GetSession()->SendPacket(&data);
TC_LOG_DEBUG(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_QUEST_CONFIRM_ACCEPT");
}
}
void Player::SendPushToPartyResponse(Player* player, uint8 msg)
{
if (player)
{
WorldPacket data(MSG_QUEST_PUSH_RESULT, 8 + 1);
data << uint64(player->GetGUID());
data << uint8(msg); // valid values: 0-8
GetSession()->SendPacket(&data);
TC_LOG_DEBUG(LOG_FILTER_NETWORKIO, "WORLD: Sent MSG_QUEST_PUSH_RESULT");
}
}
void Player::SendQuestUpdateAddItem(Quest const* /*quest*/, uint32 /*item_idx*/, uint16 /*count*/)
{
WorldPacket data(SMSG_QUESTUPDATE_ADD_ITEM, 0);
TC_LOG_DEBUG(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM");
//data << quest->RequiredItemId[item_idx];
//data << count;
GetSession()->SendPacket(&data);
}
void Player::SendQuestUpdateAddCreatureOrGo(Quest const* quest, uint64 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(LOG_FILTER_NETWORKIO, "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 << uint64(guid);
GetSession()->SendPacket(&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);
}
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));
TC_LOG_DEBUG(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_QUESTUPDATE_ADD_PVP_KILL");
data << uint32(quest->GetQuestId());
data << uint32(old_count + add_count);
data << uint32(quest->GetPlayersSlain());
GetSession()->SendPacket(&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);
}
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::Initialize(uint32 guid)
{
Object::_Create(guid, 0, HIGHGUID_PLAYER);
}
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(LOG_FILTER_PLAYER, "Player::_LoadArenaTeamInfo: couldn't load arenateam %u", arenaTeamId);
continue;
}
uint8 arenaSlot = arenaTeam->GetSlot();
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 = '%u' ORDER BY setindex", GUID_LOPART(m_guid));
if (!result)
return;
uint32 count = 0;
do
{
Field* fields = result->Fetch();
EquipmentSet eqSet;
eqSet.Guid = fields[0].GetUInt64();
uint8 index = fields[1].GetUInt8();
eqSet.Name = fields[2].GetString();
eqSet.IconName = fields[3].GetString();
eqSet.IgnoreMask = fields[4].GetUInt32();
eqSet.state = EQUIPMENT_SET_UNCHANGED;
for (uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
eqSet.Items[i] = fields[5+i].GetUInt32();
m_EquipmentSets[index] = eqSet;
++count;
if (count >= MAX_EQUIPMENT_SET_INDEX) // client limit
break;
}
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, uint64 guid)
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_POSITION);
stmt->setUInt32(0, GUID_LOPART(guid));
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
PreparedStatement* 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, GetGUIDLow());
CharacterDatabase.Execute(stmt);
}
uint32 Player::GetUInt32ValueFromArray(Tokenizer const& data, uint16 index)
{
if (index >= data.size())
return 0;
return (uint32)atoi(data[index]);
}
float Player::GetFloatValueFromArray(Tokenizer const& data, uint16 index)
{
float result;
uint32 temp = Player::GetUInt32ValueFromArray(data, index);
memcpy(&result, &temp, sizeof(result));
return result;
}
bool Player::isBeingLoaded() const
{
return GetSession()->PlayerLoading();
}
bool Player::LoadFromDB(uint32 guid, SQLQueryHolder *holder)
{
//// 0 1 2 3 4 5 6 7 8 9 10 11
//QueryResult* result = CharacterDatabase.PQuery("SELECT guid, account, name, race, class, gender, level, xp, money, playerBytes, playerBytes2, playerFlags, "
// 12 13 14 15 16 17 18 19 20 21 22 23 24
//"position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, "
// 25 26 27 28 29 30 31 32 33 34 35 36 37 38
//"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, "
// 39 40 41 42 43 44 45 46 47 48 49
//"arenaPoints, totalHonorPoints, todayHonorPoints, yesterdayHonorPoints, totalKills, todayKills, yesterdayKills, chosenTitle, knownCurrencies, watchedFaction, drunk, "
// 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
//"health, power1, power2, power3, power4, power5, power6, power7, instance_id, speccount, activespec, exploredZones, equipmentCache, ammoId, knownTitles, actionBars, grantableLevels FROM characters WHERE guid = '%u'", guid);
PreparedQueryResult result = holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_FROM);
if (!result)
{
std::string name = "<unknown>";
sObjectMgr->GetPlayerNameByGUID(guid, name);
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player %s (GUID: %u) not found in table `characters`, can't load. ", name.c_str(), guid);
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(LOG_FILTER_PLAYER, "Player (GUID: %u) loading from wrong account (is: %u, should be: %u)", guid, GetSession()->GetAccountId(), dbAccountId);
return false;
}
if (holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_BANNED))
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player (GUID: %u) is banned, can't load.", guid);
return false;
}
Object::_Create(guid, 0, HIGHGUID_PLAYER);
m_name = fields[2].GetString();
// check name limitations
if (ObjectMgr::CheckPlayerName(m_name) != CHAR_NAME_SUCCESS ||
(!GetSession()->HasPermission(RBAC_PERM_SKIP_CHECK_CHARACTER_CREATION_RESERVEDNAME) &&
sObjectMgr->IsReservedName(m_name)))
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ADD_AT_LOGIN_FLAG);
stmt->setUInt16(0, uint16(AT_LOGIN_RENAME));
stmt->setUInt32(1, guid);
CharacterDatabase.Execute(stmt);
return false;
}
// overwrite possible wrong/corrupted guid
SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
uint8 Gender = fields[5].GetUInt8();
if (!IsValidGender(Gender))
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player (GUID: %u) has wrong gender (%hu), can't be loaded.", guid, Gender);
return false;
}
// overwrite some data fields
uint32 bytes0 = 0;
bytes0 |= fields[3].GetUInt8(); // race
bytes0 |= fields[4].GetUInt8() << 8; // class
bytes0 |= Gender << 16; // gender
SetUInt32Value(UNIT_FIELD_BYTES_0, bytes0);
SetUInt32Value(UNIT_FIELD_LEVEL, fields[6].GetUInt8());
SetUInt32Value(PLAYER_XP, fields[7].GetUInt32());
_LoadIntoDataField(fields[61].GetCString(), PLAYER_EXPLORED_ZONES_1, PLAYER_EXPLORED_ZONES_SIZE);
_LoadIntoDataField(fields[64].GetCString(), PLAYER__FIELD_KNOWN_TITLES, KNOWN_TITLES_SIZE*2);
SetObjectScale(1.0f);
SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 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);
SetUInt32Value(PLAYER_BYTES, fields[9].GetUInt32());
SetUInt32Value(PLAYER_BYTES_2, fields[10].GetUInt32());
SetByteValue(PLAYER_BYTES_3, 0, fields[5].GetUInt8());
SetByteValue(PLAYER_BYTES_3, 1, fields[49].GetUInt8());
SetUInt32Value(PLAYER_FLAGS, fields[11].GetUInt32());
SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, fields[48].GetUInt32());
SetUInt64Value(PLAYER_FIELD_KNOWN_CURRENCIES, fields[47].GetUInt64());
SetUInt32Value(PLAYER_AMMO_ID, fields[63].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, 2, fields[65].GetUInt8());
InitDisplayIds();
// cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
for (uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
{
SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
SetVisibleItemSlot(slot, NULL);
delete m_items[slot];
m_items[slot] = NULL;
}
TC_LOG_DEBUG(LOG_FILTER_PLAYER_LOADING, "Load Basic value of player %s is: ", m_name.c_str());
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
uint32 transGUID = fields[30].GetUInt32();
Relocate(fields[12].GetFloat(), fields[13].GetFloat(), fields[14].GetFloat(), fields[16].GetFloat());
uint32 mapId = fields[15].GetUInt16();
uint32 instanceId = fields[58].GetUInt32();
uint32 dungeonDiff = fields[38].GetUInt8() & 0x0F;
if (dungeonDiff >= MAX_DUNGEON_DIFFICULTY)
dungeonDiff = DUNGEON_DIFFICULTY_NORMAL;
uint32 raidDiff = (fields[38].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[37].GetString();
#define RelocateToHomebind(){ 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[39].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[40].GetUInt32());
SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, fields[41].GetUInt32());
SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, fields[42].GetUInt32());
SetUInt32Value(PLAYER_FIELD_LIFETIME_HONORABLE_KILLS, fields[43].GetUInt32());
SetUInt16Value(PLAYER_FIELD_KILLS, 0, fields[44].GetUInt16());
SetUInt16Value(PLAYER_FIELD_KILLS, 1, fields[45].GetUInt16());
_LoadBoundInstances(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_BOUND_INSTANCES));
_LoadInstanceTimeRestrictions(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_INSTANCE_LOCK_TIMES));
_LoadBGData(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_BG_DATA));
GetSession()->SetPlayer(this);
MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
if (!mapEntry || !IsPositionValid())
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player (guidlow %d) have invalid coordinates (MapId: %u X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.", guid, mapId, GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
RelocateToHomebind();
}
// Player was saved in Arena or Bg
else if (mapEntry && mapEntry->IsBattlegroundOrArena())
{
Battleground* currentBg = NULL;
if (m_bgData.bgInstanceID) //saved in Battleground
currentBg = sBattlegroundMgr->GetBattleground(m_bgData.bgInstanceID, BATTLEGROUND_TYPE_NONE);
bool player_at_bg = currentBg && currentBg->IsPlayerInBattleground(GetGUID());
if (player_at_bg && currentBg->GetStatus() != STATUS_WAIT_LEAVE)
{
BattlegroundQueueTypeId bgQueueTypeId = sBattlegroundMgr->BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType());
AddBattlegroundQueueId(bgQueueTypeId);
m_bgData.bgTypeID = currentBg->GetTypeID();
//join player to battleground group
currentBg->EventPlayerLoggedIn(this);
currentBg->AddOrSetPlayerToCorrectBgGroup(this, m_bgData.bgTeam);
SetInviteForBattlegroundQueueType(bgQueueTypeId, currentBg->GetInstanceID());
}
// Bg was not found - go to Entry Point
else
{
// leave bg
if (player_at_bg)
currentBg->RemovePlayerAtLeave(GetGUID(), false, true);
// Do not look for instance if bg not found
const WorldLocation& _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(LOG_FILTER_PLAYER, "Player (guidlow %d) was in BG in database, but BG was not found, and entry point was invalid! Teleport to default race/class locations.", guid);
RelocateToHomebind();
}
else
Relocate(&_loc);
// We are not in BG anymore
m_bgData.bgInstanceID = 0;
}
}
// currently we do not support transport in bg
else if (transGUID)
{
m_movementInfo.transport.guid = MAKE_NEW_GUID(transGUID, 0, HIGHGUID_MO_TRANSPORT);
m_movementInfo.transport.pos.Relocate(fields[26].GetFloat(), fields[27].GetFloat(), fields[28].GetFloat(), fields[29].GetFloat());
if (!Trinity::IsValidMapCoord(
GetPositionX()+m_movementInfo.transport.pos.m_positionX, GetPositionY()+m_movementInfo.transport.pos.m_positionY,
GetPositionZ()+m_movementInfo.transport.pos.m_positionZ, GetOrientation()+m_movementInfo.transport.pos.m_orientation) ||
// transport size limited
m_movementInfo.transport.pos.m_positionX > 250 || m_movementInfo.transport.pos.m_positionY > 250 || m_movementInfo.transport.pos.m_positionZ > 250)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to bind location.",
guid, GetPositionX()+m_movementInfo.transport.pos.m_positionX, GetPositionY()+m_movementInfo.transport.pos.m_positionY,
GetPositionZ()+m_movementInfo.transport.pos.m_positionZ, GetOrientation()+m_movementInfo.transport.pos.m_orientation);
RelocateToHomebind();
}
else
{
for (MapManager::TransportSet::iterator iter = sMapMgr->m_Transports.begin(); iter != sMapMgr->m_Transports.end(); ++iter)
{
if ((*iter)->GetGUIDLow() == transGUID)
{
m_transport = *iter;
m_transport->AddPassenger(this);
mapId = (m_transport->GetMapId());
break;
}
}
if (!m_transport)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player (guidlow %d) have problems with transport guid (%u). Teleport to bind location.",
guid, transGUID);
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 = NULL;
if (uint32 node_id = m_taxi.GetTaxiSource())
nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
if (!nodeEntry) // don't know taxi start node, to homebind
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Character %u have wrong data in taxi destination list, teleport to homebind.", GetGUIDLow());
RelocateToHomebind();
}
else // have start node, to it
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Character %u have too short taxi destination list, teleport to original node.", GetGUIDLow());
mapId = nodeEntry->map_id;
Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->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->map_id == GetMapId())
{
ASSERT(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
mapId = nodeEntry->map_id;
Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->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(LOG_FILTER_PLAYER_LOADING, "Player %s using client without required expansion tried login at non accessible map %u", GetName().c_str(), 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
Map* map = sMapMgr->CreateMap(mapId, this);
if (!map)
{
instanceId = 0;
AreaTrigger const* at = sObjectMgr->GetGoBackTrigger(mapId);
if (at)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player (guidlow %d) is teleported to gobacktrigger (Map: %u X: %f Y: %f Z: %f O: %f).", guid, mapId, GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
Relocate(at->target_X, at->target_Y, at->target_Z, GetOrientation());
mapId = at->target_mapId;
}
else
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player (guidlow %d) is teleported to home (Map: %u X: %f Y: %f Z: %f O: %f).", guid, mapId, GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
RelocateToHomebind();
}
map = sMapMgr->CreateMap(mapId, this);
if (!map)
{
PlayerInfo const* info = sObjectMgr->GetPlayerInfo(getRace(), getClass());
mapId = info->mapId;
Relocate(info->positionX, info->positionY, info->positionZ, 0.0f);
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player (guidlow %d) have invalid coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.", guid, GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
map = sMapMgr->CreateMap(mapId, this);
if (!map)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player (guidlow %d) has invalid default map coordinates (X: %f Y: %f Z: %f O: %f). or instance couldn't be created", guid, GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
return false;
}
}
}
// if the player is in an instance and it has been reset in the meantime teleport him to the entrance
if (instanceId && !sInstanceSaveMgr->GetInstanceSave(instanceId) && !map->IsBattlegroundOrArena())
{
AreaTrigger const* at = sObjectMgr->GetMapEntranceTrigger(mapId);
if (at)
Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
else
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player %s(GUID: %u) logged in to a reset instance (map: %u) and there is no area-trigger leading to this map. Thus he can't be ported back to the entrance. This _might_ be an exploit attempt.", GetName().c_str(), GetGUIDLow(), mapId);
RelocateToHomebind();
}
}
SetMap(map);
StoreRaidMapDifficulty();
// 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 = time(NULL);
time_t logoutTime = time_t(fields[22].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
uint8 newDrunkValue = 0;
if (time_diff < uint32(GetDrunkValue()) * 9)
newDrunkValue = GetDrunkValue() - time_diff / 9;
SetDrunkValue(newDrunkValue);
m_cinematic = fields[18].GetUInt8();
m_Played_time[PLAYED_TIME_TOTAL]= fields[19].GetUInt32();
m_Played_time[PLAYED_TIME_LEVEL]= fields[20].GetUInt32();
m_resetTalentsCost = fields[24].GetUInt32();
m_resetTalentsTime = time_t(fields[25].GetUInt32());
m_taxi.LoadTaxiMask(fields[17].GetString()); // must be before InitTaxiNodesForLevel
uint32 extraflags = fields[31].GetUInt16();
m_stableSlots = fields[32].GetUInt8();
if (m_stableSlots > MAX_PET_STABLES)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player can have not more %u stable slots, but have in DB %u", MAX_PET_STABLES, uint32(m_stableSlots));
m_stableSlots = MAX_PET_STABLES;
}
m_atLoginFlags = fields[33].GetUInt16();
// Honor system
// Update Honor kills data
m_lastHonorUpdateTime = logoutTime;
UpdateHonorFields();
m_deathExpireTime = time_t(fields[36].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)
SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
SetUInt32Value(UNIT_CHANNEL_SPELL, 0);
// clear charm/summon related fields
SetOwnerGUID(0);
SetUInt64Value(UNIT_FIELD_CHARMEDBY, 0);
SetUInt64Value(UNIT_FIELD_CHARM, 0);
SetUInt64Value(UNIT_FIELD_SUMMON, 0);
SetUInt64Value(PLAYER_FARSIGHT, 0);
SetCreatorGUID(0);
RemoveFlag(UNIT_FIELD_FLAGS_2, 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
SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
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[21].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[23].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();
m_specsCount = fields[59].GetUInt8();
m_activeSpec = fields[60].GetUInt8();
// sanity check
if (m_specsCount > MAX_TALENT_SPECS || m_activeSpec > MAX_TALENT_SPEC || m_specsCount < MIN_TALENT_SPECS)
{
m_activeSpec = 0;
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player %s(GUID: %u) has SpecCount = %u and ActiveSpec = %u.", GetName().c_str(), GetGUIDLow(), m_specsCount, m_activeSpec);
}
_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();
learnDefaultSpells();
// 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
_LoadMailInit(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_MAIL_COUNT), holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_MAIL_DATE));
m_social = sSocialMgr->LoadFromDB(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_SOCIAL_LIST), GetGUIDLow());
// check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
// note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
uint32 curTitle = fields[46].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());
_LoadSpellCooldowns(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_SPELL_COOLDOWNS));
// 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)
uint32 savedHealth = fields[50].GetUInt32();
SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
for (uint8 i = 0; i < MAX_POWERS; ++i)
{
uint32 savedPower = fields[51+i].GetUInt32();
SetPower(Powers(i), savedPower > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower);
}
TC_LOG_DEBUG(LOG_FILTER_PLAYER_LOADING, "The value of player %s after load item and aura is: ", m_name.c_str());
outDebugValues();
// GM state
if (GetSession()->HasPermission(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;
}
}
// RaF stuff.
m_grantableLevels = fields[66].GetUInt8();
if (GetSession()->IsARecruiter() || (GetSession()->GetRecruiterId() != 0))
SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_REFER_A_FRIEND);
if (m_grantableLevels > 0)
SetByteValue(PLAYER_FIELD_BYTES, 1, 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(const Creature* creature)
{
if (!creature->isDead() || !creature->IsDamageEnoughForLootingAndReward())
return false;
if (HasPendingBind())
return false;
const Loot* loot = &creature->loot;
if (loot->isLooted()) // nothing to loot or everything looted.
return false;
Group* thisGroup = GetGroup();
if (!thisGroup)
return this == creature->GetLootRecipient();
else if (thisGroup != creature->GetLootRecipientGroup())
return false;
switch (thisGroup->GetLootMethod())
{
case FREE_FOR_ALL:
return true;
case ROUND_ROBIN:
case MASTER_LOOT:
// 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 == 0 || 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 == 0 || 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_ERROR(LOG_FILTER_PLAYER, " ...at loading, and will deleted in DB also");
// Will 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(LOG_FILTER_PLAYER_LOADING, "Loading auras for player %u", GetGUIDLow());
/* 0 1 2 3 4 5 6 7 8 9 10
QueryResult* result = CharacterDatabase.PQuery("SELECT caster_guid, spell, effect_mask, recalculate_mask, stackcount, amount0, amount1, amount2, base_amount0, base_amount1, base_amount2,
11 12 13
maxduration, remaintime, remaincharges FROM character_aura WHERE guid = '%u'", GetGUIDLow());
*/
if (result)
{
do
{
Field* fields = result->Fetch();
int32 damage[3];
int32 baseDamage[3];
uint64 caster_guid = fields[0].GetUInt64();
uint32 spellid = fields[1].GetUInt32();
uint8 effmask = fields[2].GetUInt8();
uint8 recalculatemask = fields[3].GetUInt8();
uint8 stackcount = fields[4].GetUInt8();
damage[0] = fields[5].GetInt32();
damage[1] = fields[6].GetInt32();
damage[2] = fields[7].GetInt32();
baseDamage[0] = fields[8].GetInt32();
baseDamage[1] = fields[9].GetInt32();
baseDamage[2] = fields[10].GetInt32();
int32 maxduration = fields[11].GetInt32();
int32 remaintime = fields[12].GetInt32();
uint8 remaincharges = fields[13].GetUInt8();
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellid);
if (!spellInfo)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Unknown aura (spellid %u), ignore.", spellid);
continue;
}
// negative effects should continue counting down after logout
if (remaintime != -1 && !spellInfo->IsPositive())
{
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;
if (Aura* aura = Aura::TryCreate(spellInfo, effmask, this, NULL, &baseDamage[0], NULL, caster_guid))
{
if (!aura->CanBeSaved())
{
aura->Remove();
continue;
}
aura->SetLoadedState(maxduration, remaintime, remaincharges, stackcount, recalculatemask, &damage[0]);
aura->ApplyForTargets();
TC_LOG_INFO(LOG_FILTER_PLAYER, "Added aura spellid %u, effectmask %u", spellInfo->Id, effmask);
}
}
while (result->NextRow());
}
}
void Player::_LoadGlyphAuras()
{
for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
{
if (uint32 glyph = GetGlyph(i))
{
if (GlyphPropertiesEntry const* gp = sGlyphPropertiesStore.LookupEntry(glyph))
{
if (GlyphSlotEntry const* gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(i)))
{
if (gp->TypeFlags == gs->TypeFlags)
{
CastSpell(this, gp->SpellId, true);
continue;
}
else
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
}
else
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player %s has not existing glyph slot entry %u on index %u", m_name.c_str(), GetGlyphSlot(i), i);
}
else
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player %s has not existing glyph entry %u on index %u", m_name.c_str(), glyph, i);
// On any error remove glyph
SetGlyph(i, 0);
}
}
}
void Player::LoadCorpse()
{
if (IsAlive())
sObjectAccessor->ConvertCorpseForPlayer(GetGUID());
else
{
if (Corpse* corpse = GetCorpse())
ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable());
else
//Prevent Dead Player login without corpse
ResurrectPlayer(0.5f);
}
}
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 = '%u' ORDER BY bag, slot", GetGUIDLow());
//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<uint32, Bag*> bagMap; // fast guid lookup for bags
std::map<uint32, Item*> invalidBagMap; // fast guid lookup for bags
std::list<Item*> problematicItems;
SQLTransaction 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))
{
uint32 bagGuid = fields[11].GetUInt32();
uint8 slot = fields[12].GetUInt8();
uint8 err = EQUIP_ERR_OK;
// Item is not in bag
if (!bagGuid)
{
item->SetContainer(NULL);
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->GetGUIDLow()] = pBag;
}
else
if (IsBagPos(item->GetPos()))
if (item->IsBag())
invalidBagMap[item->GetGUIDLow()] = item;
}
else
{
item->SetSlot(NULL_SLOT);
// Item is in the bag, find the bag
std::map<uint32, 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<uint32, Item*>::iterator itr = invalidBagMap.find(bagGuid);
if (std::find(problematicItems.begin(), problematicItems.end(), itr->second) != problematicItems.end())
err = EQUIP_ERR_INT_BAG_ERROR;
}
else
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player::_LoadInventory: player (GUID: %u, name: '%s') has item (GUID: %u, entry: %u) which doesnt have a valid bag (Bag GUID: %u, slot: %u). Possible cheat?",
GetGUIDLow(), GetName().c_str(), item->GetGUIDLow(), 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(LOG_FILTER_PLAYER, "Player::_LoadInventory: player (GUID: %u, name: '%s') has item (GUID: %u, entry: %u) which can't be loaded into inventory (Bag GUID: %u, slot: %u) by reason %u. Item will be sent by mail.",
GetGUIDLow(), GetName().c_str(), item->GetGUIDLow(), item->GetEntry(), bagGuid, slot, 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(SQLTransaction& trans, uint32 zoneId, uint32 timeDiff, Field* fields)
{
Item* item = NULL;
uint32 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))
{
PreparedStatement* stmt = NULL;
// Do not allow to have item limited to another map/zone in alive state
if (IsAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(), zoneId))
{
TC_LOG_DEBUG(LOG_FILTER_PLAYER_LOADING, "Player::_LoadInventory: player (GUID: %u, name: '%s', map: %u) has item (GUID: %u, entry: %u) limited to another map (%u). Deleting item.",
GetGUIDLow(), GetName().c_str(), GetMapId(), item->GetGUIDLow(), item->GetEntry(), zoneId);
remove = true;
}
// "Conjured items disappear if you are logged out for more than 15 minutes"
else if (timeDiff > 15 * MINUTE && proto->Flags & ITEM_PROTO_FLAG_CONJURED)
{
TC_LOG_DEBUG(LOG_FILTER_PLAYER_LOADING, "Player::_LoadInventory: player (GUID: %u, name: '%s', diff: %u) has conjured item (GUID: %u, entry: %u) with expired lifetime (15 minutes). Deleting item.",
GetGUIDLow(), GetName().c_str(), timeDiff, item->GetGUIDLow(), item->GetEntry());
remove = true;
}
else if (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_REFUNDABLE))
{
if (item->GetPlayedTime() > (2 * HOUR))
{
TC_LOG_DEBUG(LOG_FILTER_PLAYER_LOADING, "Player::_LoadInventory: player (GUID: %u, name: '%s') has item (GUID: %u, entry: %u) with expired refund time (%u). Deleting refund data and removing refundable flag.",
GetGUIDLow(), GetName().c_str(), item->GetGUIDLow(), item->GetEntry(), item->GetPlayedTime());
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_REFUND_INSTANCE);
stmt->setUInt32(0, item->GetGUIDLow());
trans->Append(stmt);
item->RemoveFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_REFUNDABLE);
}
else
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_ITEM_REFUNDS);
stmt->setUInt32(0, item->GetGUIDLow());
stmt->setUInt32(1, GetGUIDLow());
if (PreparedQueryResult result = CharacterDatabase.Query(stmt))
{
item->SetRefundRecipient((*result)[0].GetUInt32());
item->SetPaidMoney((*result)[1].GetUInt32());
item->SetPaidExtendedCost((*result)[2].GetUInt16());
AddRefundReference(item->GetGUIDLow());
}
else
{
TC_LOG_DEBUG(LOG_FILTER_PLAYER_LOADING, "Player::_LoadInventory: player (GUID: %u, name: '%s') has item (GUID: %u, entry: %u) with refundable flags, but without data in item_refund_instance. Removing flag.",
GetGUIDLow(), GetName().c_str(), item->GetGUIDLow(), item->GetEntry());
item->RemoveFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_REFUNDABLE);
}
}
}
else if (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_BOP_TRADEABLE))
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_ITEM_BOP_TRADE);
stmt->setUInt32(0, item->GetGUIDLow());
if (PreparedQueryResult result = CharacterDatabase.Query(stmt))
{
std::string strGUID = (*result)[0].GetString();
Tokenizer GUIDlist(strGUID, ' ');
AllowedLooterSet looters;
for (Tokenizer::const_iterator itr = GUIDlist.begin(); itr != GUIDlist.end(); ++itr)
looters.insert(atol(*itr));
if (looters.size() > 1 && item->GetTemplate()->GetMaxStackSize() == 1 && item->IsSoulBound())
{
item->SetSoulboundTradeable(looters);
AddTradeableItem(item);
}
else
item->ClearSoulboundTradeable(this);
}
else
{
TC_LOG_DEBUG(LOG_FILTER_PLAYER_LOADING, "Player::_LoadInventory: player (GUID: %u, name: '%s') has item (GUID: %u, entry: %u) with ITEM_FLAG_BOP_TRADEABLE flag, but without data in item_soulbound_trade_data. Removing flag.",
GetGUIDLow(), GetName().c_str(), item->GetGUIDLow(), item->GetEntry());
item->RemoveFlag(ITEM_FIELD_FLAGS, ITEM_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(LOG_FILTER_PLAYER, "Player::_LoadInventory: player (GUID: %u, name: '%s') has broken item (GUID: %u, entry: %u) in inventory. Deleting item.",
GetGUIDLow(), GetName().c_str(), 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 = NULL;
}
}
else
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player::_LoadInventory: player (GUID: %u, name: '%s') has unknown item (entry: %u) in inventory. Deleting item.",
GetGUIDLow(), GetName().c_str(), itemEntry);
Item::DeleteFromInventoryDB(trans, itemGuid);
Item::DeleteFromDB(trans, itemGuid);
}
return item;
}
// load mailed item which should receive current player
void Player::_LoadMailedItems(Mail* mail)
{
// data needs to be at first place for Item::LoadFromDB
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_MAILITEMS);
stmt->setUInt32(0, mail->messageID);
PreparedQueryResult result = CharacterDatabase.Query(stmt);
if (!result)
return;
do
{
Field* fields = result->Fetch();
uint32 itemGuid = fields[11].GetUInt32();
uint32 itemTemplate = fields[12].GetUInt32();
mail->AddItem(itemGuid, itemTemplate);
ItemTemplate const* proto = sObjectMgr->GetItemTemplate(itemTemplate);
if (!proto)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player %u has unknown item_template (ProtoType) in mailed items(GUID: %u template: %u) in mail (%u), deleted.", GetGUIDLow(), itemGuid, itemTemplate, mail->messageID);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INVALID_MAIL_ITEM);
stmt->setUInt32(0, itemGuid);
CharacterDatabase.Execute(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_INSTANCE);
stmt->setUInt32(0, itemGuid);
CharacterDatabase.Execute(stmt);
continue;
}
Item* item = NewItemOrBag(proto);
if (!item->LoadFromDB(itemGuid, MAKE_NEW_GUID(fields[13].GetUInt32(), 0, HIGHGUID_PLAYER), fields, itemTemplate))
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, itemGuid);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_ITEM);
stmt->setUInt32(0, itemGuid);
CharacterDatabase.Execute(stmt);
item->FSetState(ITEM_REMOVED);
SQLTransaction temp = SQLTransaction(NULL);
item->SaveToDB(temp); // it also deletes item object !
continue;
}
AddMItem(item);
}
while (result->NextRow());
}
void Player::_LoadMailInit(PreparedQueryResult resultUnread, PreparedQueryResult resultDelivery)
{
//set a count of unread mails
//QueryResult* resultMails = CharacterDatabase.PQuery("SELECT COUNT(id) FROM mail WHERE receiver = '%u' AND (checked & 1)=0 AND deliver_time <= '" UI64FMTD "'", GUID_LOPART(playerGuid), (uint64)cTime);
if (resultUnread)
unReadMails = uint8((*resultUnread)[0].GetUInt64());
// store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
//resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
if (resultDelivery)
m_nextMailDelivereTime = time_t((*resultDelivery)[0].GetUInt32());
}
void Player::_LoadMail()
{
m_mail.clear();
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_MAIL);
stmt->setUInt32(0, GetGUIDLow());
PreparedQueryResult result = CharacterDatabase.Query(stmt);
if (result)
{
do
{
Field* fields = result->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();
bool has_items = fields[6].GetBool();
m->expire_time = time_t(fields[7].GetUInt32());
m->deliver_time = time_t(fields[8].GetUInt32());
m->money = fields[9].GetUInt32();
m->COD = fields[10].GetUInt32();
m->checked = fields[11].GetUInt8();
m->stationery = fields[12].GetUInt8();
m->mailTemplateId = fields[13].GetInt16();
if (m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
m->mailTemplateId = 0;
}
m->state = MAIL_STATE_UNCHANGED;
if (has_items)
_LoadMailedItems(m);
m_mail.push_back(m);
}
while (result->NextRow());
}
m_mailsLoaded = true;
}
void Player::LoadPet()
{
//fixme: the pet should still be loaded if the player is not in world
// just not added to the map
if (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
// itemcount4, playercount FROM character_queststatus WHERE guid = '%u'", GetGUIDLow());
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(LOG_FILTER_PLAYER, "Player %s (GUID: %u) has invalid quest %d status (%u), replaced by QUEST_STATUS_INCOMPLETE(3).",
GetName().c_str(), GetGUIDLow(), quest_id, qstatus);
}
questStatusData.Explored = (fields[2].GetUInt8() > 0);
time_t quest_time = time_t(fields[3].GetUInt32());
if (quest->HasFlag(QUEST_TRINITY_FLAGS_TIMED) && !GetQuestRewardStatus(quest_id))
{
AddTimedQuest(quest_id);
if (quest_time <= sWorld->GetGameTime())
questStatusData.Timer = 1;
else
questStatusData.Timer = uint32((quest_time - sWorld->GetGameTime()) * IN_MILLISECONDS);
}
else
quest_time = 0;
questStatusData.CreatureOrGOCount[0] = fields[4].GetUInt16();
questStatusData.CreatureOrGOCount[1] = fields[5].GetUInt16();
questStatusData.CreatureOrGOCount[2] = fields[6].GetUInt16();
questStatusData.CreatureOrGOCount[3] = fields[7].GetUInt16();
questStatusData.ItemCount[0] = fields[8].GetUInt16();
questStatusData.ItemCount[1] = fields[9].GetUInt16();
questStatusData.ItemCount[2] = fields[10].GetUInt16();
questStatusData.ItemCount[3] = fields[11].GetUInt16();
questStatusData.PlayerCount = fields[12].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(LOG_FILTER_PLAYER_LOADING, "Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.Status, quest_id, GetGUIDLow());
}
}
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 (quest->GetBonusTalents())
m_questRewardTalentCount += quest->GetBonusTalents();
}
m_RewardedQuests.insert(quest_id);
}
while (result->NextRow());
}
}
void Player::_LoadDailyQuestStatus(PreparedQueryResult result)
{
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();
//QueryResult* result = CharacterDatabase.PQuery("SELECT quest, time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
if (result)
{
uint32 quest_daily_idx = 0;
do
{
Field* fields = result->Fetch();
if (Quest const* qQuest = sObjectMgr->GetQuestTemplate(fields[0].GetUInt32()))
{
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(LOG_FILTER_PLAYER, "Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`", GetGUIDLow());
break;
}
uint32 quest_id = fields[0].GetUInt32();
// 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(LOG_FILTER_PLAYER_LOADING, "Daily quest (%u) cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
}
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(LOG_FILTER_PLAYER_LOADING, "Weekly quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
}
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();
Quest const* quest = sObjectMgr->GetQuestTemplate(quest_id);
if (!quest)
continue;
m_seasonalquests[event_id].insert(quest_id);
TC_LOG_DEBUG(LOG_FILTER_PLAYER_LOADING, "Seasonal quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
}
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(LOG_FILTER_PLAYER_LOADING, "Monthly quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
}
while (result->NextRow());
}
m_MonthlyQuestChanged = false;
}
void Player::_LoadSpells(PreparedQueryResult result)
{
//QueryResult* result = CharacterDatabase.PQuery("SELECT spell, active, disabled FROM character_spell WHERE guid = '%u'", GetGUIDLow());
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=%u", GetGUIDLow());
if (result)
{
if (Group* group = sGroupMgr->GetGroupByDbStoreId((*result)[0].GetUInt32()))
{
uint8 subgroup = group->GetMemberGroup(GetGUID());
SetGroup(group, subgroup);
if (getLevel() >= LEVELREQUIREMENT_HEROIC)
{
// the group leader may change the instance difficulty while the player is offline
SetDungeonDifficulty(group->GetDungeonDifficulty());
SetRaidDifficulty(group->GetRaidDifficulty());
}
}
}
}
void Player::_LoadBoundInstances(PreparedQueryResult result)
{
for (uint8 i = 0; i < MAX_DIFFICULTY; ++i)
m_boundInstances[i].clear();
Group* group = GetGroup();
//QueryResult* result = CharacterDatabase.PQuery("SELECT id, permanent, map, difficulty, resettime FROM character_instance LEFT JOIN instance ON instance = id WHERE guid = '%u'", GUID_LOPART(m_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();
time_t resetTime = time_t(fields[4].GetUInt32());
// 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->name[sWorld->GetDefaultDbcLocale()] : "Unknown";
if (!mapEntry || !mapEntry->IsDungeon())
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d (%s)", GetName().c_str(), GetGUIDLow(), mapId, mapname.c_str());
deleteInstance = true;
}
else if (difficulty >= MAX_DIFFICULTY)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u (%s)", GetName().c_str(), GetGUIDLow(), difficulty, mapId, mapname.c_str());
deleteInstance = true;
}
else
{
MapDifficulty const* mapDiff = GetMapDifficultyData(mapId, Difficulty(difficulty));
if (!mapDiff)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u (%s)", GetName().c_str(), GetGUIDLow(), difficulty, mapId, mapname.c_str());
deleteInstance = true;
}
else if (!perm && group)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "_LoadBoundInstances: player %s(%d) is in group %d but has a non-permanent character bind to map %d (%s), %d, %d", GetName().c_str(), GetGUIDLow(), GUID_LOPART(group->GetGUID()), mapId, mapname.c_str(), instanceId, difficulty);
deleteInstance = true;
}
}
if (deleteInstance)
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE_GUID);
stmt->setUInt32(0, GetGUIDLow());
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, true);
}
while (result->NextRow());
}
}
InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, Difficulty difficulty)
{
// some instances only have one difficulty
MapDifficulty const* mapDiff = GetDownscaledMapDifficultyData(mapid, difficulty);
if (!mapDiff)
return NULL;
BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
if (itr != m_boundInstances[difficulty].end())
return &itr->second;
else
return NULL;
}
InstanceSave* Player::GetInstanceSave(uint32 mapid, bool raid)
{
InstancePlayerBind* pBind = GetBoundInstance(mapid, GetDifficulty(raid));
InstanceSave* pSave = pBind ? pBind->save : NULL;
if (!pBind || !pBind->perm)
if (Group* group = GetGroup())
if (InstanceGroupBind* groupBind = group->GetBoundInstance(this))
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)
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE_GUID);
stmt->setUInt32(0, GetGUIDLow());
stmt->setUInt32(1, itr->second.save->GetInstanceId());
CharacterDatabase.Execute(stmt);
}
if (itr->second.perm)
GetSession()->SendCalendarRaidLockout(itr->second.save, false);
itr->second.save->RemovePlayer(this); // save can become invalid
m_boundInstances[difficulty].erase(itr++);
}
}
InstancePlayerBind* Player::BindToInstance(InstanceSave* save, bool permanent, bool load)
{
if (save)
{
InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
if (!load)
{
if (bind.save)
{
// update the save when the group kills a boss
if (permanent != bind.perm || save != bind.save)
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_INSTANCE);
stmt->setUInt32(0, save->GetInstanceId());
stmt->setBool(1, permanent);
stmt->setUInt32(2, GetGUIDLow());
stmt->setUInt32(3, bind.save->GetInstanceId());
CharacterDatabase.Execute(stmt);
}
}
else
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_INSTANCE);
stmt->setUInt32(0, GetGUIDLow());
stmt->setUInt32(1, save->GetInstanceId());
stmt->setBool(2, permanent);
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;
if (!load)
TC_LOG_DEBUG(LOG_FILTER_MAPS, "Player::BindToInstance: %s(%d) is now bound to map %d, instance %d, difficulty %d", GetName().c_str(), GetGUIDLow(), save->GetMapId(), save->GetInstanceId(), save->GetDifficulty());
sScriptMgr->OnPlayerBindToInstance(this, save->GetDifficulty(), save->GetMapId(), permanent);
return &bind;
}
return NULL;
}
void Player::BindToInstance()
{
InstanceSave* mapSave = sInstanceSaveMgr->GetInstanceSave(_pendingBindId);
if (!mapSave) //it seems sometimes mapSave is NULL, but I did not check why
return;
WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
data << uint32(0);
GetSession()->SendPacket(&data);
BindToInstance(mapSave, true);
GetSession()->SendCalendarRaidLockout(mapSave, true);
}
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 = time(NULL);
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)
{
InstanceSave* save = itr->second.save;
data << uint32(save->GetMapId()); // map id
data << uint32(save->GetDifficulty()); // difficulty
data << uint64(save->GetInstanceId()); // instance id
data << uint8(1); // expired = 0
data << uint8(0); // extended = 1
data << uint32(save->GetResetTime() - now); // reset time
++counter;
}
}
}
data.put<uint32>(p_counter, counter);
GetSession()->SendPacket(&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 811. true or false means, whether you have current raid/heroic instances
data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
data << uint32(hasBeenSaved);
GetSession()->SendPacket(&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);
data << uint32(itr->second.save->GetMapId());
GetSession()->SendPacket(&data);
}
}
}
}
/// convert the player's binds to the group
void Player::ConvertInstancesToGroup(Player* player, Group* group, bool switchLeader)
{
// copy all binds to the group, when changing leader it's assumed the character
// will not have any solo binds
for (uint8 i = 0; i < MAX_DIFFICULTY; ++i)
{
for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
{
if (!switchLeader || !group->GetBoundInstance(itr->second.save->GetDifficulty(), itr->first))
group->BindToInstance(itr->second.save, itr->second.perm, false);
// permanent binds are not removed
if (switchLeader && !itr->second.perm)
{
// increments itr in call
player->UnbindInstance(itr, Difficulty(i), false);
}
else
++itr;
}
}
}
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;
uint64 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, sObjectMgr->GetItemTemplate(missingItem)->Name1.c_str());
else if (LevelMin)
GetSession()->SendAreaTriggerMessage(GetSession()->GetTrinityString(LANG_LEVEL_MINREQUIRED), LevelMin);
}
return false;
}
}
return true;
}
bool Player::CheckInstanceLoginValid()
{
if (!FindMap())
return false;
if (!GetMap()->IsDungeon() || IsGameMaster())
return true;
if (GetMap()->IsRaid())
{
// cannot be in raid instance without a group
if (!GetGroup())
return false;
}
else
{
// cannot be in normal instance without a group and more players than 1 in instance
if (!GetGroup() && GetMap()->GetPlayersCountExceptGMs() > 1)
return false;
}
// do checks for satisfy accessreqs, instance full, encounter in progress (raid), perm bind group != perm bind player
return sMapMgr->CanPlayerEnter(GetMap()->GetId(), this, true);
}
bool Player::CheckInstanceCount(uint32 instanceId) const
{
if (_instanceResetTimes.size() < sWorld->getIntConfig(CONFIG_MAX_INSTANCES_PER_HOUR))
return true;
return _instanceResetTimes.find(instanceId) != _instanceResetTimes.end();
}
void Player::AddInstanceEnterTime(uint32 instanceId, time_t enterTime)
{
if (_instanceResetTimes.find(instanceId) == _instanceResetTimes.end())
_instanceResetTimes.insert(InstanceTimeMap::value_type(instanceId, enterTime + HOUR));
}
bool Player::_LoadHomeBind(PreparedQueryResult result)
{
PlayerInfo const* info = sObjectMgr->GetPlayerInfo(getRace(), getClass());
if (!info)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player (Name %s) has incorrect race/class pair. Can't be loaded.", GetName().c_str());
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
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_HOMEBIND);
stmt->setUInt32(0, GetGUIDLow());
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;
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_PLAYER_HOMEBIND);
stmt->setUInt32(0, GetGUIDLow());
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(LOG_FILTER_PLAYER, "Setting player home position - mapid: %u, areaid: %u, X: %f, Y: %f, Z: %f",
m_homebindMapId, m_homebindAreaId, m_homebindX, m_homebindY, m_homebindZ);
return true;
}
/*********************************************************/
/*** SAVE SYSTEM ***/
/*********************************************************/
void Player::SaveToDB(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(LOG_FILTER_UNITS, "The value of player %s at save: ", m_name.c_str());
outDebugValues();
PreparedStatement* stmt = NULL;
uint8 index = 0;
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++, GetGUIDLow());
stmt->setUInt32(index++, GetSession()->GetAccountId());
stmt->setString(index++, GetName());
stmt->setUInt8(index++, getRace());
stmt->setUInt8(index++, getClass());
stmt->setUInt8(index++, getGender());
stmt->setUInt8(index++, getLevel());
stmt->setUInt32(index++, GetUInt32Value(PLAYER_XP));
stmt->setUInt32(index++, GetMoney());
stmt->setUInt32(index++, GetUInt32Value(PLAYER_BYTES));
stmt->setUInt32(index++, GetUInt32Value(PLAYER_BYTES_2));
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()));
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(time(NULL)));
stmt->setUInt8(index++, (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0));
//save, far from tavern/city
//save, but in tavern/city
stmt->setUInt32(index++, m_resetTalentsCost);
stmt->setUInt32(index++, uint32(m_resetTalentsTime));
stmt->setUInt16(index++, (uint16)m_ExtraFlags);
stmt->setUInt8(index++, m_stableSlots);
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++, m_specsCount);
stmt->setUInt8(index++, m_activeSpec);
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, 2));
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++, getGender());
stmt->setUInt8(index++, getLevel());
stmt->setUInt32(index++, GetUInt32Value(PLAYER_XP));
stmt->setUInt32(index++, GetMoney());
stmt->setUInt32(index++, GetUInt32Value(PLAYER_BYTES));
stmt->setUInt32(index++, GetUInt32Value(PLAYER_BYTES_2));
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()));
}
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(time(NULL)));
stmt->setUInt8(index++, (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0));
//save, far from tavern/city
//save, but in tavern/city
stmt->setUInt32(index++, m_resetTalentsCost);
stmt->setUInt32(index++, uint32(m_resetTalentsTime));
stmt->setUInt16(index++, (uint16)m_ExtraFlags);
stmt->setUInt8(index++, m_stableSlots);
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++, m_specsCount);
stmt->setUInt8(index++, m_activeSpec);
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, 2));
stmt->setUInt32(index++, m_grantableLevels);
stmt->setUInt8(index++, IsInWorld() && !GetSession()->PlayerLogout() ? 1 : 0);
// Index
stmt->setUInt32(index++, GetGUIDLow());
}
SQLTransaction trans = CharacterDatabase.BeginTransaction();
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);
_SaveSpellCooldowns(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);
_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);
CharacterDatabase.CommitTransaction(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(SQLTransaction& trans)
{
_SaveInventory(trans);
SaveGoldToDB(trans);
}
void Player::SaveGoldToDB(SQLTransaction& trans)
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UDP_CHAR_MONEY);
stmt->setUInt32(0, GetMoney());
stmt->setUInt32(1, GetGUIDLow());
trans->Append(stmt);
}
void Player::_SaveActions(SQLTransaction& trans)
{
PreparedStatement* stmt = NULL;
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, GetGUIDLow());
stmt->setUInt8(1, m_activeSpec);
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, GetGUIDLow());
stmt->setUInt8(3, itr->first);
stmt->setUInt8(4, m_activeSpec);
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, GetGUIDLow());
stmt->setUInt8(1, itr->first);
stmt->setUInt8(2, m_activeSpec);
trans->Append(stmt);
m_actionButtons.erase(itr++);
break;
default:
++itr;
break;
}
}
}
void Player::_SaveAuras(SQLTransaction& trans)
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_AURA);
stmt->setUInt32(0, GetGUIDLow());
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++, GetGUIDLow());
stmt->setUInt64(index++, itr->second->GetCasterGUID());
stmt->setUInt64(index++, itr->second->GetCastItemGUID());
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());
trans->Append(stmt);
}
}
void Player::_SaveInventory(SQLTransaction& trans)
{
PreparedStatement* stmt = NULL;
// 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 || item->GetState() == ITEM_NEW)
continue;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INVENTORY_BY_ITEM);
stmt->setUInt32(0, item->GetGUIDLow());
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_INSTANCE);
stmt->setUInt32(0, item->GetGUIDLow());
trans->Append(stmt);
m_items[i]->FSetState(ITEM_NEW);
}
// 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.
std::set<uint32>::iterator i_next;
for (std::set<uint32>::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(MAKE_NEW_GUID(*itr, 0, HIGHGUID_ITEM));
if (iPtr)
{
iPtr->UpdatePlayedTime(this);
continue;
}
else
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Can't find item guid %u but is in refundable storage for player %u ! Removing.", *itr, GetGUIDLow());
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;
uint32 lowGuid = GetGUIDLow();
for (size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
{
Item* item = m_itemUpdateQueue[i];
if (!item)
continue;
Bag* container = item->GetContainer();
uint32 bag_guid = container ? container->GetGUIDLow() : 0;
if (item->GetState() != ITEM_REMOVED)
{
Item* test = GetItemByPos(item->GetBagSlot(), item->GetSlot());
if (test == NULL)
{
uint32 bagTestGUID = 0;
if (Item* test2 = GetItemByPos(INVENTORY_SLOT_BAG_0, item->GetBagSlot()))
bagTestGUID = test2->GetGUIDLow();
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player(GUID: %u Name: %s)::_SaveInventory - the bag(%u) and slot(%u) values for the item with guid %u (state %d) are incorrect, the player doesn't have an item at that position!", lowGuid, GetName().c_str(), item->GetBagSlot(), item->GetSlot(), item->GetGUIDLow(), (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, lowGuid);
trans->Append(stmt);
// 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->GetGUIDLow());
// don't skip, let the switch delete it
//continue;
}
else if (test != item)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player(GUID: %u Name: %s)::_SaveInventory - the bag(%u) and slot(%u) values for the item with guid %u are incorrect, the item with guid %u is there instead!", lowGuid, GetName().c_str(), item->GetBagSlot(), item->GetSlot(), item->GetGUIDLow(), test->GetGUIDLow());
// save all changes to the item...
if (item->GetState() != ITEM_NEW) // only for existing items, no dupes
item->SaveToDB(trans);
// ...but do not save position in invntory
continue;
}
}
switch (item->GetState())
{
case ITEM_NEW:
case ITEM_CHANGED:
stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_INVENTORY_ITEM);
stmt->setUInt32(0, lowGuid);
stmt->setUInt32(1, bag_guid);
stmt->setUInt8 (2, item->GetSlot());
stmt->setUInt32(3, item->GetGUIDLow());
trans->Append(stmt);
break;
case ITEM_REMOVED:
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INVENTORY_BY_ITEM);
stmt->setUInt32(0, item->GetGUIDLow());
trans->Append(stmt);
case ITEM_UNCHANGED:
break;
}
item->SaveToDB(trans); // item have unchanged inventory record and can be save standalone
}
m_itemUpdateQueue.clear();
}
void Player::_SaveMail(SQLTransaction& trans)
{
if (!m_mailsLoaded)
return;
PreparedStatement* stmt = NULL;
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<uint32>::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(SQLTransaction& trans)
{
bool isTransaction = !trans.null();
if (!isTransaction)
trans = CharacterDatabase.BeginTransaction();
QuestStatusSaveMap::iterator saveItr;
QuestStatusMap::iterator statusItr;
PreparedStatement* stmt = NULL;
bool keepAbandoned = !(sWorld->GetCleaningFlags() & CharacterDatabaseCleaner::CLEANING_FLAG_QUESTSTATUS);
for (saveItr = m_QuestStatusSave.begin(); saveItr != m_QuestStatusSave.end(); ++saveItr)
{
if (saveItr->second)
{
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++, GetGUIDLow());
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+ sWorld->GetGameTime()));
for (uint8 i = 0; i < 4; i++)
stmt->setUInt16(index++, statusItr->second.CreatureOrGOCount[i]);
for (uint8 i = 0; i < 4; 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, GetGUIDLow());
stmt->setUInt32(1, saveItr->first);
trans->Append(stmt);
}
}
m_QuestStatusSave.clear();
for (saveItr = m_RewardedQuestsSave.begin(); saveItr != m_RewardedQuestsSave.end(); ++saveItr)
{
if (saveItr->second)
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_QUESTSTATUS_REWARDED);
stmt->setUInt32(0, GetGUIDLow());
stmt->setUInt32(1, saveItr->first);
trans->Append(stmt);
}
else if (!keepAbandoned)
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_QUESTSTATUS_REWARDED_BY_QUEST);
stmt->setUInt32(0, GetGUIDLow());
stmt->setUInt32(1, saveItr->first);
trans->Append(stmt);
}
}
m_RewardedQuestsSave.clear();
if (!isTransaction)
CharacterDatabase.CommitTransaction(trans);
}
void Player::_SaveDailyQuestStatus(SQLTransaction& 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.
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_DAILY_CHAR);
stmt->setUInt32(0, GetGUIDLow());
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_DAILYQUESTSTATUS);
stmt->setUInt32(0, GetGUIDLow());
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_DAILYQUESTSTATUS);
stmt->setUInt32(0, GetGUIDLow());
stmt->setUInt32(1, (*itr));
stmt->setUInt64(2, uint64(m_lastDailyQuestTime));
trans->Append(stmt);
}
}
}
void Player::_SaveWeeklyQuestStatus(SQLTransaction& trans)
{
if (!m_WeeklyQuestChanged || m_weeklyquests.empty())
return;
// we don't need transactions here.
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_WEEKLY_CHAR);
stmt->setUInt32(0, GetGUIDLow());
trans->Append(stmt);
for (QuestSet::const_iterator iter = m_weeklyquests.begin(); iter != m_weeklyquests.end(); ++iter)
{
uint32 quest_id = *iter;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARACTER_WEEKLYQUESTSTATUS);
stmt->setUInt32(0, GetGUIDLow());
stmt->setUInt32(1, quest_id);
trans->Append(stmt);
}
m_WeeklyQuestChanged = false;
}
void Player::_SaveSeasonalQuestStatus(SQLTransaction& trans)
{
if (!m_SeasonalQuestChanged || m_seasonalquests.empty())
return;
// we don't need transactions here.
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_SEASONAL_CHAR);
stmt->setUInt32(0, GetGUIDLow());
trans->Append(stmt);
for (SeasonalEventQuestMap::const_iterator iter = m_seasonalquests.begin(); iter != m_seasonalquests.end(); ++iter)
{
uint16 event_id = iter->first;
for (SeasonalQuestSet::const_iterator itr = iter->second.begin(); itr != iter->second.end(); ++itr)
{
uint32 quest_id = (*itr);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARACTER_SEASONALQUESTSTATUS);
stmt->setUInt32(0, GetGUIDLow());
stmt->setUInt32(1, quest_id);
stmt->setUInt32(2, event_id);
trans->Append(stmt);
}
}
m_SeasonalQuestChanged = false;
}
void Player::_SaveMonthlyQuestStatus(SQLTransaction& trans)
{
if (!m_MonthlyQuestChanged || m_monthlyquests.empty())
return;
// we don't need transactions here.
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_MONTHLY_CHAR);
stmt->setUInt32(0, GetGUIDLow());
trans->Append(stmt);
for (QuestSet::const_iterator iter = m_monthlyquests.begin(); iter != m_monthlyquests.end(); ++iter)
{
uint32 quest_id = *iter;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARACTER_MONTHLYQUESTSTATUS);
stmt->setUInt32(0, GetGUIDLow());
stmt->setUInt32(1, quest_id);
trans->Append(stmt);
}
m_MonthlyQuestChanged = false;
}
void Player::_SaveSkills(SQLTransaction& trans)
{
PreparedStatement* stmt = NULL;
// 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, GetGUIDLow());
stmt->setUInt32(1, itr->first);
trans->Append(stmt);
mSkillStatus.erase(itr++);
continue;
}
uint32 valueData = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos));
uint16 value = SKILL_VALUE(valueData);
uint16 max = SKILL_MAX(valueData);
switch (itr->second.uState)
{
case SKILL_NEW:
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_SKILLS);
stmt->setUInt32(0, GetGUIDLow());
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_UDP_CHAR_SKILLS);
stmt->setUInt16(0, value);
stmt->setUInt16(1, max);
stmt->setUInt32(2, GetGUIDLow());
stmt->setUInt16(3, uint16(itr->first));
trans->Append(stmt);
break;
default:
break;
}
itr->second.uState = SKILL_UNCHANGED;
++itr;
}
}
void Player::_SaveSpells(SQLTransaction& trans)
{
PreparedStatement* stmt = NULL;
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, GetGUIDLow());
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, GetGUIDLow());
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)
{
delete itr->second;
m_spells.erase(itr++);
}
else
{
itr->second->state = PLAYERSPELL_UNCHANGED;
++itr;
}
}
}
// save player stats -- only for external usage
// real stats will be recalculated on player login
void Player::_SaveStats(SQLTransaction& trans)
{
// 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;
PreparedStatement* stmt = NULL;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_STATS);
stmt->setUInt32(0, GetGUIDLow());
trans->Append(stmt);
uint8 index = 0;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_STATS);
stmt->setUInt32(index++, GetGUIDLow());
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));
stmt->setFloat(index++, GetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1));
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 + CR_CRIT_TAKEN_SPELL));
trans->Append(stmt);
}
void Player::outDebugValues() const
{
if (!sLog->ShouldLog(LOG_FILTER_UNITS, LOG_LEVEL_DEBUG))
return;
TC_LOG_DEBUG(LOG_FILTER_UNITS, "HP is: \t\t\t%u\t\tMP is: \t\t\t%u", GetMaxHealth(), GetMaxPower(POWER_MANA));
TC_LOG_DEBUG(LOG_FILTER_UNITS, "AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f", GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
TC_LOG_DEBUG(LOG_FILTER_UNITS, "INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f", GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
TC_LOG_DEBUG(LOG_FILTER_UNITS, "STAMINA is: \t\t%f", GetStat(STAT_STAMINA));
TC_LOG_DEBUG(LOG_FILTER_UNITS, "Armor is: \t\t%u\t\tBlock is: \t\t%f", GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
TC_LOG_DEBUG(LOG_FILTER_UNITS, "HolyRes is: \t\t%u\t\tFireRes is: \t\t%u", GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
TC_LOG_DEBUG(LOG_FILTER_UNITS, "NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u", GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
TC_LOG_DEBUG(LOG_FILTER_UNITS, "ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u", GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
TC_LOG_DEBUG(LOG_FILTER_UNITS, "MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f", GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
TC_LOG_DEBUG(LOG_FILTER_UNITS, "MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f", GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
TC_LOG_DEBUG(LOG_FILTER_UNITS, "MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f", GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
TC_LOG_DEBUG(LOG_FILTER_UNITS, "ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u", GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
}
/*********************************************************/
/*** FLOOD FILTER SYSTEM ***/
/*********************************************************/
void Player::UpdateSpeakTime()
{
// ignore chat spam protection for GMs in any mode
if (GetSession()->HasPermission(RBAC_PERM_SKIP_CHECK_CHAT_SPAM))
return;
time_t current = time (NULL);
if (m_speakTime > current)
{
uint32 max_count = sWorld->getIntConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
if (!max_count)
return;
++m_speakCount;
if (m_speakCount >= max_count)
{
// 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_speakCount = 0;
}
}
else
m_speakCount = 0;
m_speakTime = current + sWorld->getIntConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
}
bool Player::CanSpeak() const
{
return GetSession()->m_muteTime <= time (NULL);
}
/*********************************************************/
/*** LOW LEVEL FUNCTIONS:Notifiers ***/
/*********************************************************/
void Player::SendAttackSwingNotInRange()
{
WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
GetSession()->SendPacket(&data);
}
void Player::SavePositionInDB(uint32 mapid, float x, float y, float z, float o, uint32 zone, uint64 guid)
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHARACTER_POSITION);
stmt->setFloat(0, x);
stmt->setFloat(1, y);
stmt->setFloat(2, z);
stmt->setFloat(3, o);
stmt->setUInt16(4, uint16(mapid));
stmt->setUInt16(5, uint16(zone));
stmt->setUInt32(6, GUID_LOPART(guid));
CharacterDatabase.Execute(stmt);
}
void Player::SetUInt32ValueInArray(Tokenizer& tokens, uint16 index, uint32 value)
{
char buf[11];
snprintf(buf, 11, "%u", value);
if (index >= tokens.size())
return;
tokens[index] = buf;
}
void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_PLAYERBYTES2);
stmt->setUInt32(0, GUID_LOPART(guid));
PreparedQueryResult result = CharacterDatabase.Query(stmt);
if (!result)
return;
Field* fields = result->Fetch();
uint32 playerBytes2 = fields[0].GetUInt32();
playerBytes2 &= ~0xFF;
playerBytes2 |= facialHair;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GENDER_PLAYERBYTES);
stmt->setUInt8(0, gender);
stmt->setUInt32(1, skin | (face << 8) | (hairStyle << 16) | (hairColor << 24));
stmt->setUInt32(2, playerBytes2);
stmt->setUInt32(3, GUID_LOPART(guid));
CharacterDatabase.Execute(stmt);
}
void Player::SendAttackSwingDeadTarget()
{
WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
GetSession()->SendPacket(&data);
}
void Player::SendAttackSwingCantAttack()
{
WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
GetSession()->SendPacket(&data);
}
void Player::SendAttackSwingCancelAttack()
{
WorldPacket data(SMSG_CANCEL_COMBAT, 0);
GetSession()->SendPacket(&data);
}
void Player::SendAttackSwingBadFacingAttack()
{
WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
GetSession()->SendPacket(&data);
}
void Player::SendAutoRepeatCancel(Unit* target)
{
WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, target->GetPackGUID().size());
data.append(target->GetPackGUID()); // may be it's target guid
GetSession()->SendPacket(&data);
}
void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
{
WorldPacket data(SMSG_EXPLORATION_EXPERIENCE, 8);
data << uint32(Area);
data << uint32(Experience);
GetSession()->SendPacket(&data);
}
void Player::SendDungeonDifficulty(bool IsInGroup)
{
uint8 val = 0x00000001;
WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
data << (uint32)GetDungeonDifficulty();
data << uint32(val);
data << uint32(IsInGroup);
GetSession()->SendPacket(&data);
}
void Player::SendRaidDifficulty(bool IsInGroup, int32 forcedDifficulty)
{
uint8 val = 0x00000001;
WorldPacket data(MSG_SET_RAID_DIFFICULTY, 12);
data << uint32(forcedDifficulty == -1 ? GetRaidDifficulty() : forcedDifficulty);
data << uint32(val);
data << uint32(IsInGroup);
GetSession()->SendPacket(&data);
}
void Player::SendResetFailedNotify(uint32 mapid)
{
WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
data << uint32(mapid);
GetSession()->SendPacket(&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;
const MapEntry* 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->map_type == 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 (!((InstanceMap*)map)->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)
{
WorldPacket data(SMSG_INSTANCE_RESET, 4);
data << uint32(MapId);
GetSession()->SendPacket(&data);
}
void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
{
/*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, 4);
data << uint32(reason);
data << uint32(MapId);
GetSession()->SendPacket(&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::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;
UpdatePvP(false);
}
void Player::UpdateDuelFlag(time_t currTime)
{
if (!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
return;
sScriptMgr->OnPlayerDuelStart(this, duel->opponent);
SetUInt32Value(PLAYER_DUEL_TEAM, 1);
duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
duel->startTimer = 0;
duel->startTime = currTime;
duel->opponent->duel->startTimer = 0;
duel->opponent->duel->startTime = currTime;
}
Pet* Player::GetPet() const
{
if (uint64 pet_guid = GetPetGUID())
{
if (!IS_PET_GUID(pet_guid))
return NULL;
Pet* pet = ObjectAccessor::GetPet(*this, pet_guid);
if (!pet)
return NULL;
if (IsInWorld() && pet)
return pet;
//there may be a guardian in slot
//TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player::GetPet: Pet %u not exist.", GUID_LOPART(pet_guid));
//const_cast<Player*>(this)->SetPetGUID(0);
}
return NULL;
}
void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
{
if (!pet)
pet = GetPet();
if (pet)
{
TC_LOG_DEBUG(LOG_FILTER_PETS, "RemovePet %u, %u, %u", 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 || pet->GetOwnerGUID() != GetGUID())
return;
pet->CombatStop();
if (returnreagent)
{
switch (pet->GetEntry())
{
//warlock pets except imp are removed(?) when logging out
case 1860:
case 1863:
case 417:
case 17252:
mode = PET_SAVE_NOT_IN_SLOT;
break;
}
}
// only if current pet in slot
pet->SavePetToDB(mode);
SetMinion(pet, false);
pet->AddObjectToRemoveList();
pet->m_removed = true;
if (pet->isControlled())
{
WorldPacket data(SMSG_PET_SPELLS, 8);
data << uint64(0);
GetSession()->SendPacket(&data);
if (GetGroup())
SetGroupUpdateFlag(GROUP_UPDATE_PET);
}
}
void Player::StopCastingCharm()
{
Unit* charm = GetCharm();
if (!charm)
return;
if (charm->GetTypeId() == TYPEID_UNIT)
{
if (charm->ToCreature()->HasUnitTypeMask(UNIT_MASK_PUPPET))
((Puppet*)charm)->UnSummon();
else if (charm->IsVehicle())
ExitVehicle();
}
if (GetCharmGUID())
charm->RemoveCharmAuras();
if (GetCharmGUID())
{
TC_LOG_FATAL(LOG_FILTER_PLAYER, "Player %s (GUID: " UI64FMTD " is not able to uncharm unit (GUID: " UI64FMTD " Entry: %u, Type: %u)", GetName().c_str(), GetGUID(), GetCharmGUID(), charm->GetEntry(), charm->GetTypeId());
if (charm->GetCharmerGUID())
{
TC_LOG_FATAL(LOG_FILTER_PLAYER, "Charmed unit has charmer guid " UI64FMTD, charm->GetCharmerGUID());
ASSERT(false);
}
else
SetCharm(charm, false);
}
}
inline void Player::BuildPlayerChat(WorldPacket* data, uint8 msgtype, const std::string& text, uint32 language) const
{
*data << uint8(msgtype);
*data << uint32(language);
*data << uint64(GetGUID());
*data << uint32(0); // constant unknown time
*data << uint64(GetGUID());
*data << uint32(text.length() + 1);
*data << text;
*data << uint8(GetChatTag());
}
void Player::Say(const std::string& text, const uint32 language)
{
std::string _text(text);
sScriptMgr->OnPlayerChat(this, CHAT_MSG_SAY, language, _text);
WorldPacket data(SMSG_MESSAGECHAT, 200);
BuildPlayerChat(&data, CHAT_MSG_SAY, _text, language);
SendMessageToSetInRange(&data, sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_SAY), true);
}
void Player::Yell(const std::string& text, const uint32 language)
{
std::string _text(text);
sScriptMgr->OnPlayerChat(this, CHAT_MSG_YELL, language, _text);
WorldPacket data(SMSG_MESSAGECHAT, 200);
BuildPlayerChat(&data, CHAT_MSG_YELL, _text, language);
SendMessageToSetInRange(&data, sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_YELL), true);
}
void Player::TextEmote(const std::string& text)
{
std::string _text(text);
sScriptMgr->OnPlayerChat(this, CHAT_MSG_EMOTE, LANG_UNIVERSAL, _text);
WorldPacket data(SMSG_MESSAGECHAT, 200);
BuildPlayerChat(&data, CHAT_MSG_EMOTE, _text, LANG_UNIVERSAL);
SendMessageToSetInRange(&data, sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE), true, !GetSession()->HasPermission(RBAC_PERM_TWO_SIDE_INTERACTION_CHAT));
}
void Player::Whisper(const std::string& text, uint32 language, uint64 receiver)
{
bool isAddonMessage = language == LANG_ADDON;
if (!isAddonMessage) // if not addon data
language = LANG_UNIVERSAL; // whispers should always be readable
Player* rPlayer = ObjectAccessor::FindPlayer(receiver);
std::string _text(text);
sScriptMgr->OnPlayerChat(this, CHAT_MSG_WHISPER, language, _text, rPlayer);
WorldPacket data(SMSG_MESSAGECHAT, 200);
BuildPlayerChat(&data, CHAT_MSG_WHISPER, _text, language);
rPlayer->GetSession()->SendPacket(&data);
// rest stuff shouldn't happen in case of addon message
if (isAddonMessage)
return;
data.Initialize(SMSG_MESSAGECHAT, 200);
rPlayer->BuildPlayerChat(&data, CHAT_MSG_WHISPER_INFORM, _text, language);
GetSession()->SendPacket(&data);
if (!isAcceptWhispers() && !IsGameMaster() && !rPlayer->IsGameMaster())
{
SetAcceptWhispers(true);
ChatHandler(GetSession()).SendSysMessage(LANG_COMMAND_WHISPERON);
}
// announce afk or dnd message
if (rPlayer->isAFK())
ChatHandler(GetSession()).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName().c_str(), rPlayer->autoReplyMsg.c_str());
else if (rPlayer->isDND())
ChatHandler(GetSession()).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName().c_str(), rPlayer->autoReplyMsg.c_str());
}
Item* Player::GetMItem(uint32 id)
{
ItemMap::const_iterator itr = mMitems.find(id);
return itr != mMitems.end() ? itr->second : NULL;
}
void Player::AddMItem(Item* it)
{
ASSERT(it);
//ASSERT deleted, because items can be added before loading
mMitems[it->GetGUIDLow()] = it;
}
bool Player::RemoveMItem(uint32 id)
{
return mMitems.erase(id) ? true : false;
}
void Player::SendOnCancelExpectedVehicleRideAura()
{
WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
GetSession()->SendPacket(&data);
}
void Player::PetSpellInitialize()
{
Pet* pet = GetPet();
if (!pet)
return;
TC_LOG_DEBUG(LOG_FILTER_PETS, "Pet Spells Groups");
CharmInfo* charmInfo = pet->GetCharmInfo();
WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
data << uint64(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
// 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);
uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
data << uint8(cooldownsCount);
time_t curTime = time(NULL);
for (CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
{
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(itr->first);
if (!spellInfo)
{
data << uint32(0);
data << uint16(0);
data << uint32(0);
data << uint32(0);
continue;
}
time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILLISECONDS : 0;
data << uint32(itr->first); // spell ID
CreatureSpellCooldowns::const_iterator categoryitr = pet->m_CreatureCategoryCooldowns.find(spellInfo->Category);
if (categoryitr != pet->m_CreatureCategoryCooldowns.end())
{
time_t categoryCooldown = (categoryitr->second > curTime) ? (categoryitr->second - curTime) * IN_MILLISECONDS : 0;
data << uint16(spellInfo->Category); // spell category
data << uint32(cooldown); // spell cooldown
data << uint32(categoryCooldown); // category cooldown
}
else
{
data << uint16(0);
data << uint32(cooldown);
data << uint32(0);
}
}
GetSession()->SendPacket(&data);
}
void Player::PossessSpellInitialize()
{
Unit* charm = GetCharm();
if (!charm)
return;
CharmInfo* charmInfo = charm->GetCharmInfo();
if (!charmInfo)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player::PossessSpellInitialize(): charm ("UI64FMTD") has no charminfo!", charm->GetGUID());
return;
}
WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
data << uint64(charm->GetGUID());
data << uint16(0);
data << uint32(0);
data << uint32(0);
charmInfo->BuildActionBar(&data);
data << uint8(0); // spells count
data << uint8(0); // cooldowns count
GetSession()->SendPacket(&data);
}
void Player::VehicleSpellInitialize()
{
Creature* vehicle = GetVehicleCreatureBase();
if (!vehicle)
return;
uint8 cooldownCount = vehicle->m_CreatureSpellCooldowns.size();
WorldPacket data(SMSG_PET_SPELLS, 8 + 2 + 4 + 4 + 4 * 10 + 1 + 1 + cooldownCount * (4 + 2 + 4 + 4));
data << uint64(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 < CREATURE_MAX_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;
}
ConditionList conditions = sConditionMgr->GetConditionsForVehicleSpell(vehicle->GetEntry(), spellId);
if (!sConditionMgr->IsObjectMeetToConditions(this, vehicle, conditions))
{
TC_LOG_DEBUG(LOG_FILTER_CONDITIONSYS, "VehicleSpellInitialize: conditions not met for Vehicle entry %u spell %u", 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 = CREATURE_MAX_SPELLS; i < MAX_SPELL_CONTROL_BAR; ++i)
data << uint32(0);
data << uint8(0); // Auras?
// Cooldowns
data << uint8(cooldownCount);
time_t now = sWorld->GetGameTime();
for (CreatureSpellCooldowns::const_iterator itr = vehicle->m_CreatureSpellCooldowns.begin(); itr != vehicle->m_CreatureSpellCooldowns.end(); ++itr)
{
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(itr->first);
if (!spellInfo)
{
data << uint32(0);
data << uint16(0);
data << uint32(0);
data << uint32(0);
continue;
}
time_t cooldown = (itr->second > now) ? (itr->second - now) * IN_MILLISECONDS : 0;
data << uint32(itr->first); // spell ID
CreatureSpellCooldowns::const_iterator categoryitr = vehicle->m_CreatureCategoryCooldowns.find(spellInfo->Category);
if (categoryitr != vehicle->m_CreatureCategoryCooldowns.end())
{
time_t categoryCooldown = (categoryitr->second > now) ? (categoryitr->second - now) * IN_MILLISECONDS : 0;
data << uint16(spellInfo->Category); // spell category
data << uint32(cooldown); // spell cooldown
data << uint32(categoryCooldown); // category cooldown
}
else
{
data << uint16(0);
data << uint32(cooldown);
data << uint32(0);
}
}
GetSession()->SendPacket(&data);
}
void Player::CharmSpellInitialize()
{
Unit* charm = GetFirstControlled();
if (!charm)
return;
CharmInfo* charmInfo = charm->GetCharmInfo();
if (!charmInfo)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player::CharmSpellInitialize(): the player's charm ("UI64FMTD") has no charminfo!", charm->GetGUID());
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 << uint64(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
GetSession()->SendPacket(&data);
}
void Player::SendRemoveControlBar()
{
WorldPacket data(SMSG_PET_SPELLS, 8);
data << uint64(0);
GetSession()->SendPacket(&data);
}
bool Player::IsAffectedBySpellmod(SpellInfo const* spellInfo, SpellModifier* mod, Spell* spell)
{
if (!mod || !spellInfo)
return false;
// Mod out of charges
if (spell && mod->charges == -1 && spell->m_appliedMods.find(mod->ownerAura) == spell->m_appliedMods.end())
return false;
// +duration to infinite duration spells making them limited
if (mod->op == SPELLMOD_DURATION && spellInfo->GetDuration() == -1)
return false;
return spellInfo->IsAffectedBySpellMod(mod);
}
void Player::AddSpellMod(SpellModifier* mod, bool apply)
{
TC_LOG_DEBUG(LOG_FILTER_SPELLS_AURAS, "Player::AddSpellMod %d", mod->spellId);
uint16 Opcode = (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
int i = 0;
flag96 _mask = 0;
for (int eff = 0; eff < 96; ++eff)
{
if (eff != 0 && eff%32 == 0)
_mask[i++] = 0;
_mask[i] = uint32(1) << (eff-(32*i));
if (mod->mask & _mask)
{
int32 val = 0;
for (SpellModList::iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
{
if ((*itr)->type == mod->type && (*itr)->mask & _mask)
val += (*itr)->value;
}
val += apply ? mod->value : -(mod->value);
WorldPacket data(Opcode, (1+1+4));
data << uint8(eff);
data << uint8(mod->op);
data << int32(val);
SendDirectMessage(&data);
}
}
if (apply)
m_spellMods[mod->op].push_back(mod);
else
{
m_spellMods[mod->op].remove(mod);
// mods bound to aura will be removed in AuraEffect::~AuraEffect
if (!mod->ownerAura)
delete mod;
}
}
// Restore spellmods in case of failed cast
void Player::RestoreSpellMods(Spell* spell, uint32 ownerAuraId, Aura* aura)
{
if (!spell || spell->m_appliedMods.empty())
return;
for (uint8 i=0; i<MAX_SPELLMOD; ++i)
{
for (SpellModList::iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end(); ++itr)
{
SpellModifier* mod = *itr;
// spellmods without aura set cannot be charged
if (!mod->ownerAura || !mod->ownerAura->IsUsingCharges())
continue;
// Restore only specific owner aura mods
if (ownerAuraId && (ownerAuraId != mod->ownerAura->GetSpellInfo()->Id))
continue;
if (aura && mod->ownerAura != aura)
continue;
// check if mod affected this spell
// first, check if the mod aura applied at least one spellmod to this spell
Spell::UsedSpellMods::iterator iterMod = spell->m_appliedMods.find(mod->ownerAura);
if (iterMod == spell->m_appliedMods.end())
continue;
// secondly, check if the current mod is one of the spellmods applied by the mod aura
if (!(mod->mask & spell->m_spellInfo->SpellFamilyFlags))
continue;
// remove from list
spell->m_appliedMods.erase(iterMod);
// add mod charges back to mod
if (mod->charges == -1)
mod->charges = 1;
else
mod->charges++;
// Do not set more spellmods than avalible
if (mod->ownerAura->GetCharges() < mod->charges)
mod->charges = mod->ownerAura->GetCharges();
// Skip this check for now - aura charges may change due to various reason
/// @todo trac these changes correctly
//ASSERT (mod->ownerAura->GetCharges() <= mod->charges);
}
}
}
void Player::RestoreAllSpellMods(uint32 ownerAuraId, Aura* aura)
{
for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
if (m_currentSpells[i])
RestoreSpellMods(m_currentSpells[i], ownerAuraId, aura);
}
void Player::RemoveSpellMods(Spell* spell)
{
if (!spell)
return;
if (spell->m_appliedMods.empty())
return;
for (uint8 i=0; i<MAX_SPELLMOD; ++i)
{
for (SpellModList::const_iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
{
SpellModifier* mod = *itr;
++itr;
// spellmods without aura set cannot be charged
if (!mod->ownerAura || !mod->ownerAura->IsUsingCharges())
continue;
// check if mod affected this spell
Spell::UsedSpellMods::iterator iterMod = spell->m_appliedMods.find(mod->ownerAura);
if (iterMod == spell->m_appliedMods.end())
continue;
// remove from list
spell->m_appliedMods.erase(iterMod);
if (mod->ownerAura->DropCharge(AURA_REMOVE_BY_EXPIRE))
itr = m_spellMods[i].begin();
}
}
}
void Player::DropModCharge(SpellModifier* mod, Spell* spell)
{
// don't handle spells with proc_event entry defined
// this is a temporary workaround, because all spellmods should be handled like that
if (sSpellMgr->GetSpellProcEvent(mod->spellId))
return;
if (spell && mod->ownerAura && mod->charges > 0)
{
if (--mod->charges == 0)
mod->charges = -1;
spell->m_appliedMods.insert(mod->ownerAura);
}
}
void Player::SetSpellModTakingSpell(Spell* spell, bool apply)
{
if (!spell || (m_spellModTakingSpell && m_spellModTakingSpell != spell))
return;
if (apply && spell->getState() == SPELL_STATE_FINISHED)
return;
m_spellModTakingSpell = apply ? spell : NULL;
}
// send Proficiency
void Player::SendProficiency(ItemClass itemClass, uint32 itemSubclassMask)
{
WorldPacket data(SMSG_SET_PROFICIENCY, 1 + 4);
data << uint8(itemClass) << uint32(itemSubclassMask);
GetSession()->SendPacket(&data);
}
void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
{
PreparedStatement* stmt;
if (type == 10)
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_PETITION_SIG_BY_GUID);
else
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_PETITION_SIG_BY_GUID_TYPE);
stmt->setUInt8(1, uint8(type));
}
stmt->setUInt32(0, GUID_LOPART(guid));
PreparedQueryResult result = CharacterDatabase.Query(stmt);
if (result)
{
do // this part effectively does nothing, since the deletion / modification only takes place _after_ the PetitionQuery. Though I don't know if the result remains intact if I execute the delete query beforehand.
{ // and SendPetitionQueryOpcode reads data from the DB
Field* fields = result->Fetch();
uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
// send update if charter owner in game
Player* owner = ObjectAccessor::FindPlayer(ownerguid);
if (owner)
owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
} while (result->NextRow());
if (type == 10)
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ALL_PETITION_SIGNATURES);
stmt->setUInt32(0, GUID_LOPART(guid));
CharacterDatabase.Execute(stmt);
}
else
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PETITION_SIGNATURE);
stmt->setUInt32(0, GUID_LOPART(guid));
stmt->setUInt8(1, uint8(type));
CharacterDatabase.Execute(stmt);
}
}
SQLTransaction trans = CharacterDatabase.BeginTransaction();
if (type == 10)
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PETITION_BY_OWNER);
stmt->setUInt32(0, GUID_LOPART(guid));
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PETITION_SIGNATURE_BY_OWNER);
stmt->setUInt32(0, GUID_LOPART(guid));
trans->Append(stmt);
}
else
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PETITION_BY_OWNER_AND_TYPE);
stmt->setUInt32(0, GUID_LOPART(guid));
stmt->setUInt8(1, uint8(type));
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PETITION_SIGNATURE_BY_OWNER_AND_TYPE);
stmt->setUInt32(0, GUID_LOPART(guid));
stmt->setUInt8(1, uint8(type));
trans->Append(stmt);
}
CharacterDatabase.CommitTransaction(trans);
}
void Player::LeaveAllArenaTeams(uint64 guid)
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_PLAYER_ARENA_TEAMS);
stmt->setUInt32(0, GUID_LOPART(guid));
PreparedQueryResult result = CharacterDatabase.Query(stmt);
if (!result)
return;
do
{
Field* fields = result->Fetch();
uint32 arenaTeamId = fields[0].GetUInt32();
if (arenaTeamId != 0)
{
ArenaTeam* arenaTeam = sArenaTeamMgr->GetArenaTeamById(arenaTeamId);
if (arenaTeam)
arenaTeam->DelMember(guid, true);
}
}
while (result->NextRow());
}
void Player::SetRestBonus(float rest_bonus_new)
{
// Prevent resting on max level
if (getLevel() >= sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL))
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 (GetSession()->IsARecruiter() || (GetSession()->GetRecruiterId() != 0))
SetByteValue(PLAYER_BYTES_2, 3, REST_STATE_RAF_LINKED);
else if (m_rest_bonus > 10)
SetByteValue(PLAYER_BYTES_2, 3, REST_STATE_RESTED); // Set Reststate = Rested
else if (m_rest_bonus <= 1)
SetByteValue(PLAYER_BYTES_2, 3, REST_STATE_NOT_RAF_LINKED); // Set Reststate = Normal
//RestTickUpdate
SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
}
bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc /*= NULL*/, 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 (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
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 (IsNonMeleeSpellCasted(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;
}
// check node starting pos data set case if provided
if (node->x != 0.0f || node->y != 0.0f || node->z != 0.0f)
{
if (node->map_id != GetMapId() ||
(node->x - GetPositionX())*(node->x - GetPositionX())+
(node->y - GetPositionY())*(node->y - GetPositionY())+
(node->z - GetPositionZ())*(node->z - GetPositionZ()) >
(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE))
{
GetSession()->SendActivateTaxiReply(ERR_TAXITOOFARAWAY);
return false;
}
}
// node must have pos if taxi master case (npc != NULL)
else if (npc)
{
GetSession()->SendActivateTaxiReply(ERR_TAXIUNSPECIFIEDSERVERERROR);
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 prevnode = sourcenode;
uint32 lastnode = 0;
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 (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 == NULL || (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)
totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
if (money < totalcost)
{
GetSession()->SendActivateTaxiReply(ERR_TAXINOTENOUGHMONEY);
m_taxi.ClearTaxiDestinations();
return false;
}
//Checks and preparations done, DO FLIGHT
ModifyMoney(-(int32)totalcost);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, totalcost);
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]);
m_taxi.ClearTaxiDestinations();
TeleportTo(lastPathNode->map_id, lastPathNode->x, lastPathNode->y, lastPathNode->z, GetOrientation());
return false;
}
else
{
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->from;
nodes[1] = entry->to;
return ActivateTaxiPathTo(nodes, NULL, spellid);
}
void Player::CleanupAfterTaxiFlight()
{
m_taxi.ClearTaxiDestinations(); // not destinations, clear source node
Dismount();
RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_TAXI_FLIGHT);
getHostileRefManager().setOnlineOfflineState(true);
}
void Player::ContinueTaxiFlight()
{
uint32 sourceNode = m_taxi.GetTaxiSource();
if (!sourceNode)
return;
TC_LOG_DEBUG(LOG_FILTER_UNITS, "WORLD: Restart character %u taxi flight", GetGUIDLow());
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 = MAP_SIZE*MAP_SIZE;
float distNext =
(nodeList[0].x-GetPositionX())*(nodeList[0].x-GetPositionX())+
(nodeList[0].y-GetPositionY())*(nodeList[0].y-GetPositionY())+
(nodeList[0].z-GetPositionZ())*(nodeList[0].z-GetPositionZ());
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.mapid != GetMapId())
continue;
distPrev = distNext;
distNext =
(node.x-GetPositionX())*(node.x-GetPositionX())+
(node.y-GetPositionY())*(node.y-GetPositionY())+
(node.z-GetPositionZ())*(node.z-GetPositionZ());
float distNodes =
(node.x-prevNode.x)*(node.x-prevNode.x)+
(node.y-prevNode.y)*(node.y-prevNode.y)+
(node.z-prevNode.z)*(node.z-prevNode.z);
if (distNext + distPrev < distNodes)
{
startNode = i;
break;
}
}
GetSession()->SendDoFlight(mountDisplayId, path, startNode);
}
void Player::ProhibitSpellSchool(SpellSchoolMask idSchoolMask, uint32 unTimeMs)
{
// last check 2.0.10
WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
data << uint64(GetGUID());
data << uint8(0x0); // flags (0x1, 0x2)
time_t curTime = time(NULL);
for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
{
if (itr->second->state == PLAYERSPELL_REMOVED)
continue;
uint32 unSpellId = itr->first;
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(unSpellId);
if (!spellInfo)
{
ASSERT(spellInfo);
continue;
}
// Not send cooldown for this spells
if (spellInfo->Attributes & SPELL_ATTR0_DISABLED_WHILE_ACTIVE)
continue;
if (spellInfo->PreventionType != SPELL_PREVENTION_TYPE_SILENCE)
continue;
if ((idSchoolMask & spellInfo->GetSchoolMask()) && GetSpellCooldownDelay(unSpellId) < unTimeMs)
{
data << uint32(unSpellId);
data << uint32(unTimeMs); // in m.secs
AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/IN_MILLISECONDS);
}
}
GetSession()->SendPacket(&data);
}
void Player::InitDataForForm(bool reapplyMods)
{
ShapeshiftForm form = GetShapeshiftForm();
SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(form);
if (ssEntry && ssEntry->attackSpeed)
{
SetAttackTime(BASE_ATTACK, ssEntry->attackSpeed);
SetAttackTime(OFF_ATTACK, ssEntry->attackSpeed);
SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
}
else
SetRegularAttackTime();
switch (form)
{
case FORM_GHOUL:
case FORM_CAT:
{
if (getPowerType() != POWER_ENERGY)
setPowerType(POWER_ENERGY);
break;
}
case FORM_BEAR:
case FORM_DIREBEAR:
{
if (getPowerType() != POWER_RAGE)
setPowerType(POWER_RAGE);
break;
}
default: // 0, for example
{
ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
if (cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
setPowerType(Powers(cEntry->powerType));
break;
}
}
// 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(LOG_FILTER_PLAYER, "Player %u has incorrect race/class pair. Can't init display ids.", GetGUIDLow());
return;
}
uint8 gender = getGender();
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(LOG_FILTER_PLAYER, "Invalid gender %u for player", gender);
return;
}
}
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)
{
ItemPosCountVec vDest;
uint16 uiDest = 0;
InventoryResult msg = bStore ?
CanStoreNewItem(bag, slot, vDest, item, pProto->BuyCount * count) :
CanEquipNewItem(slot, uiDest, item, false);
if (msg != EQUIP_ERR_OK)
{
SendEquipError(msg, NULL, NULL, item);
return false;
}
ModifyMoney(-price);
if (crItem->ExtendedCost) // case for new honor system
{
ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
if (iece->reqhonorpoints)
ModifyHonorPoints(- int32(iece->reqhonorpoints * count));
if (iece->reqarenapoints)
ModifyArenaPoints(- int32(iece->reqarenapoints * count));
for (uint8 i = 0; i < MAX_ITEM_EXTENDED_COST_REQUIREMENTS; ++i)
{
if (iece->reqitem[i])
DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
}
}
Item* it = bStore ?
StoreNewItem(vDest, item, true) :
EquipNewItem(uiDest, item, true);
if (it)
{
uint32 new_count = pVendor->UpdateVendorItemCurrentCount(crItem, pProto->BuyCount * count);
WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
data << uint64(pVendor->GetGUID());
data << uint32(vendorslot + 1); // numbered from 1 at client
data << int32(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
data << uint32(count);
GetSession()->SendPacket(&data);
SendNewItem(it, pProto->BuyCount * count, true, false, false);
if (!bStore)
AutoUnequipOffhandIfNeed();
if (pProto->Flags & ITEM_PROTO_FLAG_REFUNDABLE && crItem->ExtendedCost && pProto->GetMaxStackSize() == 1)
{
it->SetFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_REFUNDABLE);
it->SetRefundRecipient(GetGUIDLow());
it->SetPaidMoney(price);
it->SetPaidExtendedCost(crItem->ExtendedCost);
it->SaveRefundDataToDB();
AddRefundReference(it->GetGUIDLow());
}
}
return true;
}
// Return true is the bought item has a max count to force refresh of window by caller
bool Player::BuyItemFromVendorSlot(uint64 vendorguid, uint32 vendorslot, uint32 item, uint8 count, uint8 bag, uint8 slot)
{
// cheating attempt
if (count < 1) count = 1;
// cheating attempt
if (slot > MAX_BAG_SIZE && slot != NULL_SLOT)
return false;
if (!IsAlive())
return false;
ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(item);
if (!pProto)
{
SendBuyError(BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
return false;
}
Creature* creature = GetNPCIfCanInteractWith(vendorguid, UNIT_NPC_FLAG_VENDOR);
if (!creature)
{
TC_LOG_DEBUG(LOG_FILTER_NETWORKIO, "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)));
SendBuyError(BUY_ERR_DISTANCE_TOO_FAR, NULL, 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)
{
ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
if (!iece)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
return false;
}
// honor points price
if (GetHonorPoints() < (iece->reqhonorpoints * count))
{
SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
return false;
}
// arena points price
if (GetArenaPoints() < (iece->reqarenapoints * count))
{
SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
return false;
}
// item base price
for (uint8 i = 0; i < MAX_ITEM_EXTENDED_COST_REQUIREMENTS; ++i)
{
if (iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
{
SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
return false;
}
}
// check for personal arena rating requirement
if (GetMaxPersonalArenaRatingRequirement(iece->reqarenaslot) < iece->reqpersonalarenarating)
{
// probably not the proper equip err
SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK, NULL, NULL);
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(LOG_FILTER_PLAYER, "Player %s tried to buy %u item id %u, causing overflow", GetName().c_str(), (uint32)count, pProto->ItemId);
count = (uint8)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_ITEM_CANT_BE_EQUIPPED, NULL, NULL);
return false;
}
if (!_StoreOrEquipNewItem(vendorslot, item, count, bag, slot, price, pProto, creature, crItem, false))
return false;
}
else
{
SendEquipError(EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL);
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);
GetSession()->SendPacket(&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);
GetSession()->SendPacket(&data);
TC_LOG_DEBUG(LOG_FILTER_MAPS, "PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName().c_str(), GetGUIDLow());
}
}
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 (!HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP))
{
SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
for (ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
(*itr)->SetByteValue(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
}
}
else if (HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP))
{
RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
for (ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
(*itr)->RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, 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 = time(NULL); // 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 = time(NULL);
SetPvP(state);
}
}
bool Player::HasSpellCooldown(uint32 spell_id) const
{
SpellCooldowns::const_iterator itr = m_spellCooldowns.find(spell_id);
return itr != m_spellCooldowns.end() && itr->second.end > time(NULL);
}
uint32 Player::GetSpellCooldownDelay(uint32 spell_id) const
{
SpellCooldowns::const_iterator itr = m_spellCooldowns.find(spell_id);
time_t t = time(NULL);
return uint32(itr != m_spellCooldowns.end() && itr->second.end > t ? itr->second.end - t : 0);
}
void Player::AddSpellAndCategoryCooldowns(SpellInfo const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown)
{
// init cooldown values
uint32 cat = 0;
int32 rec = -1;
int32 catrec = -1;
// some special item spells without correct cooldown in SpellInfo
// cooldown information stored in item prototype
// This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
if (itemId)
{
if (ItemTemplate const* proto = sObjectMgr->GetItemTemplate(itemId))
{
for (uint8 idx = 0; idx < MAX_ITEM_SPELLS; ++idx)
{
if (uint32(proto->Spells[idx].SpellId) == spellInfo->Id)
{
cat = proto->Spells[idx].SpellCategory;
rec = proto->Spells[idx].SpellCooldown;
catrec = proto->Spells[idx].SpellCategoryCooldown;
break;
}
}
}
}
// if no cooldown found above then base at DBC data
if (rec < 0 && catrec < 0)
{
cat = spellInfo->Category;
rec = spellInfo->RecoveryTime;
catrec = spellInfo->CategoryRecoveryTime;
}
time_t curTime = time(NULL);
time_t catrecTime;
time_t recTime;
// overwrite time for selected category
if (infinityCooldown)
{
// use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
// but not allow ignore until reset or re-login
catrecTime = catrec > 0 ? curTime+infinityCooldownDelay : 0;
recTime = rec > 0 ? curTime+infinityCooldownDelay : catrecTime;
}
else
{
// shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
// prevent 0 cooldowns set by another way
if (rec <= 0 && catrec <= 0 && (cat == 76 || (spellInfo->IsAutoRepeatRangedSpell() && spellInfo->Id != 75)))
rec = GetAttackTime(RANGED_ATTACK);
// Now we have cooldown data (if found any), time to apply mods
if (rec > 0)
ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell);
if (catrec > 0 && !(spellInfo->AttributesEx6 & SPELL_ATTR6_IGNORE_CATEGORY_COOLDOWN_MODS))
ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell);
// replace negative cooldowns by 0
if (rec < 0) rec = 0;
if (catrec < 0) catrec = 0;
// no cooldown after applying spell mods
if (rec == 0 && catrec == 0)
return;
catrecTime = catrec ? curTime+catrec/IN_MILLISECONDS : 0;
recTime = rec ? curTime+rec/IN_MILLISECONDS : catrecTime;
}
// self spell cooldown
if (recTime > 0)
AddSpellCooldown(spellInfo->Id, itemId, recTime);
// category spells
if (cat && catrec > 0)
{
SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
if (i_scstore != sSpellCategoryStore.end())
{
for (SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
{
if (*i_scset == spellInfo->Id) // skip main spell, already handled above
continue;
AddSpellCooldown(*i_scset, itemId, catrecTime);
}
}
}
}
void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
{
SpellCooldown sc;
sc.end = end_time;
sc.itemid = itemid;
m_spellCooldowns[spellid] = sc;
}
void Player::SendCooldownEvent(SpellInfo const* spellInfo, uint32 itemId /*= 0*/, Spell* spell /*= NULL*/, bool setCooldown /*= true*/)
{
// start cooldowns at server side, if any
if (setCooldown)
AddSpellAndCategoryCooldowns(spellInfo, itemId, spell);
// Send activate cooldown timer (possible 0) at client side
WorldPacket data(SMSG_COOLDOWN_EVENT, 4 + 8);
data << uint32(spellInfo->Id);
data << uint64(GetGUID());
SendDirectMessage(&data);
}
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 not existed charged spell cooldown spellmods for potions)
if (ItemTemplate const* proto = sObjectMgr->GetItemTemplate(m_lastPotionId))
for (uint8 idx = 0; idx < MAX_ITEM_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))
SendCooldownEvent(spellInfo, m_lastPotionId);
}
// from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
else
SendCooldownEvent(spell->m_spellInfo, m_lastPotionId, spell);
m_lastPotionId = 0;
}
void Player::setResurrectRequestData(uint64 guid, uint32 mapId, float X, float Y, float Z, uint32 health, uint32 mana)
{
m_resurrectGUID = guid;
m_resurrectMap = mapId;
m_resurrectX = X;
m_resurrectY = Y;
m_resurrectZ = Z;
m_resurrectHealth = health;
m_resurrectMana = mana;
}
//slot to be excluded while counting
bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
{
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->GemID;
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->color;
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->Color[i])
continue;
uint32 _cur_gem = curcount[Condition->Color[i] - 1];
// if have <CompareColor> use them as count, else use <value> from Condition
uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
switch (Condition->Comparator[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(LOG_FILTER_PLAYER_ITEMS, "Checking Condition %u, there are %u Meta Gems, %u Red Gems, %u Yellow Gems and %u Blue Gems, Activate:%s", 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->EnchantmentCondition;
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->EnchantmentCondition;
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 (const WorldSafeLocsEntry* entry = sObjectMgr->GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam()))
m_bgData.joinPos = WorldLocation(entry->map_id, entry->x, entry->y, entry->z, 0.0f);
else
TC_LOG_ERROR(LOG_FILTER_PLAYER, "SetBattlegroundEntryPoint: Dungeon map %u 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;
SetByteValue(PLAYER_BYTES_3, 3, uint8(team == ALLIANCE ? 1 : 0));
}
uint32 Player::GetBGTeam() const
{
return m_bgData.bgTeam ? m_bgData.bgTeam : GetTeam();
}
void Player::LeaveBattleground(bool teleportToEntryPoint)
{
if (Battleground* bg = GetBattleground())
{
bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
// call after remove to be sure that player resurrected for correct cast
if (bg->isBattleground() && !IsGameMaster() && sWorld->getBoolConfig(CONFIG_BATTLEGROUND_CAST_DESERTER))
{
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
}
}
}
}
bool Player::CanJoinToBattleground(Battleground const* bg) const
{
// check Deserter debuff
if (HasAura(26013))
return false;
if (bg->isArena() && !GetSession()->HasPermission(RBAC_PERM_JOIN_ARENAS))
return false;
if (bg->IsRandom() && !GetSession()->HasPermission(RBAC_PERM_JOIN_RANDOM_BG))
return false;
if (!GetSession()->HasPermission(RBAC_PERM_JOIN_NORMAL_BG))
return false;
return true;
}
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)
{
Battleground* bg = GetBattleground();
// Battleground also must be in progress!
if (!bg || bg != reporter->GetBattleground() || GetTeam() != reporter->GetTeam() || bg->GetStatus() != STATUS_IN_PROGRESS)
return;
// check if player has 'Idle' or 'Inactive' debuff
if (m_bgData.bgAfkReporter.find(reporter->GetGUIDLow()) == m_bgData.bgAfkReporter.end() && !HasAura(43680) && !HasAura(43681) && reporter->CanReportAfkDueToLimit())
{
m_bgData.bgAfkReporter.insert(reporter->GetGUIDLow());
// 3 players have to complain to apply debuff
if (m_bgData.bgAfkReporter.size() >= 3)
{
// cast 'Idle' spell
CastSpell(this, 43680, true);
m_bgData.bgAfkReporter.clear();
}
}
}
WorldLocation Player::GetStartPosition() const
{
PlayerInfo const* info = sObjectMgr->GetPlayerInfo(getRace(), getClass());
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(WorldObject const* u) const
{
return u == this || m_clientGUIDs.find(u->GetGUID()) != m_clientGUIDs.end();
}
bool Player::IsNeverVisible() const
{
if (Unit::IsNeverVisible())
return true;
if (GetSession()->PlayerLogout() || GetSession()->PlayerLoading())
return true;
return false;
}
bool Player::CanAlwaysSee(WorldObject const* obj) const
{
// Always can see self
if (m_mover == obj)
return true;
if (uint64 guid = GetUInt64Value(PLAYER_FARSIGHT))
if (obj->GetGUID() == guid)
return true;
return false;
}
bool Player::IsAlwaysDetectableFor(WorldObject const* seer) const
{
if (Unit::IsAlwaysDetectableFor(seer))
return true;
if (const Player* seerPlayer = seer->ToPlayer())
if (IsGroupVisibleFor(seerPlayer))
return !(seerPlayer->duel && seerPlayer->duel->startTime != 0 && seerPlayer->duel->opponent == this);
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
if (!IsVisible())
return false;
// non-gm stealth/invisibility not hide from global player lists
return true;
}
template<class T>
inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target, std::set<Unit*>& /*v*/)
{
s64.insert(target->GetGUID());
}
template<>
inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target, std::set<Unit*>& /*v*/)
{
// Don't update only GAMEOBJECT_TYPE_TRANSPORT (or all transports and destructible buildings?)
if ((target->GetGOInfo()->type != GAMEOBJECT_TYPE_TRANSPORT))
s64.insert(target->GetGUID());
}
template<>
inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, Creature* target, std::set<Unit*>& v)
{
s64.insert(target->GetGUID());
v.insert(target);
}
template<>
inline void UpdateVisibilityOf_helper(std::set<uint64>& 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->ToCreature()->IsPet())
((Pet*)t)->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(LOG_FILTER_MAPS, "Object %u (Type: %u) out of range for player %u. Distance = %f", target->GetGUIDLow(), target->GetTypeId(), GetGUIDLow(), GetDistance(target));
#endif
}
}
else
{
if (CanSeeOrDetect(target, false, true))
{
//if (target->isType(TYPEMASK_UNIT) && ((Unit*)target)->m_Vehicle)
// UpdateVisibilityOf(((Unit*)target)->m_Vehicle);
target->SendUpdateToPlayer(this);
m_clientGUIDs.insert(target->GetGUID());
#ifdef TRINITY_DEBUG
TC_LOG_DEBUG(LOG_FILTER_MAPS, "Object %u (Type: %u) is visible now for player %u. Distance = %f", target->GetGUIDLow(), target->GetTypeId(), GetGUIDLow(), 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->isType(TYPEMASK_UNIT))
SendInitialVisiblePackets((Unit*)target);
}
}
}
void Player::UpdateTriggerVisibility()
{
if (m_clientGUIDs.empty())
return;
if (!IsInWorld())
return;
UpdateData udata;
WorldPacket packet;
for (ClientGUIDs::iterator itr = m_clientGUIDs.begin(); itr != m_clientGUIDs.end(); ++itr)
{
if (IS_CREATURE_GUID(*itr))
{
Creature* creature = GetMap()->GetCreature(*itr);
// Update fields of triggers, transformed units or unselectable units (values dependent on GM state)
if (!creature || (!creature->IsTrigger() && !creature->HasAuraType(SPELL_AURA_TRANSFORM) && !creature->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE)))
continue;
creature->SetFieldNotifyFlag(UF_FLAG_PUBLIC);
creature->BuildValuesUpdateBlockForPlayer(&udata, this);
creature->RemoveFieldNotifyFlag(UF_FLAG_PUBLIC);
}
else if (IS_GAMEOBJECT_GUID((*itr)))
{
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);
GetSession()->SendPacket(&packet);
}
void Player::SendInitialVisiblePackets(Unit* target)
{
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(LOG_FILTER_MAPS, "Object %u (Type: %u, Entry: %u) is out of range for player %u. Distance = %f", target->GetGUIDLow(), target->GetTypeId(), target->GetEntry(), GetGUIDLow(), GetDistance(target));
#endif
}
}
else //if (visibleNow.size() < 30 || target->GetTypeId() == TYPEID_UNIT && target->ToCreature()->IsVehicle())
{
if (CanSeeOrDetect(target, false, true))
{
//if (target->isType(TYPEMASK_UNIT) && ((Unit*)target)->m_Vehicle)
// UpdateVisibilityOf(((Unit*)target)->m_Vehicle, data, visibleNow);
target->BuildCreateUpdateBlockForPlayer(&data, this);
UpdateVisibilityOf_helper(m_clientGUIDs, target, visibleNow);
#ifdef TRINITY_DEBUG
TC_LOG_DEBUG(LOG_FILTER_MAPS, "Object %u (Type: %u, Entry: %u) is visible now for player %u. Distance = %f", target->GetGUIDLow(), target->GetTypeId(), target->GetEntry(), GetGUIDLow(), 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)
{
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);
m_seer->VisitNearbyObject(GetSightRange(), notifier);
notifier.SendToSelf(); // send gathered data
}
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() < uint32(MAX_MONEY_AMOUNT - amount))
SetMoney(GetMoney() + amount);
else
{
if (sendError)
SendEquipError(EQUIP_ERR_TOO_MUCH_GOLD, NULL, NULL);
return false;
}
}
return true;
}
bool Player::HasEnoughMoney(int32 amount) const
{
if (amount > 0)
return (GetMoney() >= (uint32) amount);
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
{
if (m_curSelection)
return ObjectAccessor::GetUnit(*this, m_curSelection);
return NULL;
}
Player* Player::GetSelectedPlayer() const
{
if (m_curSelection)
return ObjectAccessor::GetPlayer(*this, m_curSelection);
return NULL;
}
void Player::SendComboPoints()
{
Unit* combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
if (combotarget)
{
WorldPacket data;
if (m_mover != this)
{
data.Initialize(SMSG_PET_UPDATE_COMBO_POINTS, m_mover->GetPackGUID().size()+combotarget->GetPackGUID().size()+1);
data.append(m_mover->GetPackGUID());
}
else
data.Initialize(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
data.append(combotarget->GetPackGUID());
data << uint8(m_comboPoints);
GetSession()->SendPacket(&data);
}
}
void Player::AddComboPoints(Unit* target, int8 count, Spell* spell)
{
if (!count)
return;
int8 * comboPoints = spell ? &spell->m_comboPointGain : &m_comboPoints;
// without combo points lost (duration checked in aura)
RemoveAurasByType(SPELL_AURA_RETAIN_COMBO_POINTS);
if (target->GetGUID() == m_comboTarget)
*comboPoints += count;
else
{
if (m_comboTarget)
if (Unit* target2 = ObjectAccessor::GetUnit(*this, m_comboTarget))
target2->RemoveComboPointHolder(GetGUIDLow());
// Spells will always add value to m_comboPoints eventualy, so it must be cleared first
if (spell)
m_comboPoints = 0;
m_comboTarget = target->GetGUID();
*comboPoints = count;
target->AddComboPointHolder(GetGUIDLow());
}
if (*comboPoints > 5)
*comboPoints = 5;
else if (*comboPoints < 0)
*comboPoints = 0;
if (!spell)
SendComboPoints();
}
void Player::GainSpellComboPoints(int8 count)
{
if (!count)
return;
m_comboPoints += count;
if (m_comboPoints > 5) m_comboPoints = 5;
else if (m_comboPoints < 0) m_comboPoints = 0;
SendComboPoints();
}
void Player::ClearComboPoints()
{
if (!m_comboTarget)
return;
// without combopoints lost (duration checked in aura)
RemoveAurasByType(SPELL_AURA_RETAIN_COMBO_POINTS);
m_comboPoints = 0;
SendComboPoints();
if (Unit* target = ObjectAccessor::GetUnit(*this, m_comboTarget))
target->RemoveComboPointHolder(GetGUIDLow());
m_comboTarget = 0;
}
void Player::SetGroup(Group* group, int8 subgroup)
{
if (group == NULL)
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
GetSocial()->SendSocialList(this);
// guild bank list wtf?
// Homebind
WorldPacket data(SMSG_BINDPOINTUPDATE, 5*4);
data << m_homebindX << m_homebindY << m_homebindZ;
data << (uint32) m_homebindMapId;
data << (uint32) m_homebindAreaId;
GetSession()->SendPacket(&data);
// SMSG_SET_PROFICIENCY
// SMSG_SET_PCT_SPELL_MODIFIER
// SMSG_SET_FLAT_SPELL_MODIFIER
// SMSG_UPDATE_AURA_DURATION
SendTalentsInfoData(false);
// SMSG_INSTANCE_DIFFICULTY
data.Initialize(SMSG_INSTANCE_DIFFICULTY, 4+4);
data << uint32(GetMap()->GetDifficulty());
data << uint32(0);
GetSession()->SendPacket(&data);
SendInitialSpells();
data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
data << uint32(0); // count, for (count) uint32;
GetSession()->SendPacket(&data);
SendInitialActionButtons();
m_reputationMgr->SendInitialReputations();
m_achievementMgr->SendAllAchievementData();
SendEquipmentSetList();
data.Initialize(SMSG_LOGIN_SETTIMESPEED, 4 + 4 + 4);
data.AppendPackedTime(sWorld->GetGameTime());
data << float(0.01666667f); // game speed
data << uint32(0); // added in 3.1.2
GetSession()->SendPacket(&data);
GetReputationMgr().SendForceReactions(); // SMSG_SET_FORCED_REACTIONS
// SMSG_TALENTS_INFO x 2 for pet (unspent points and talents in separate packets...)
// SMSG_PET_GUIDS
// SMSG_UPDATE_WORLD_STATE
// SMSG_POWER_UPDATE
SetMover(this);
}
void Player::SendInitialPacketsAfterAddToMap()
{
UpdateVisibilityForPlayer();
// update zone
uint32 newzone, newarea;
GetZoneAndAreaId(newzone, newarea);
UpdateZone(newzone, newarea); // also call SendInitWorldStates();
ResetTimeSync();
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))
SetMovement(MOVE_ROOT);
// 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))
{
WorldPacket data2(SMSG_FORCE_MOVE_ROOT, 10);
data2.append(GetPackGUID());
data2 << (uint32)2;
SendMessageToSet(&data2, true);
}
SendAurasForTarget(this);
SendEnchantmentDurations(); // must be after add to map
SendItemDurations(); // must be after add to map
// raid downscaling - send difficulty to player
if (GetMap()->IsRaid())
{
if (GetMap()->GetDifficulty() != GetRaidDifficulty())
{
StoreRaidMapDifficulty();
SendRaidDifficulty(GetGroup() != NULL, GetStoredRaidDifficulty());
}
}
else if (GetRaidDifficulty() != GetStoredRaidDifficulty())
SendRaidDifficulty(GetGroup() != NULL);
}
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)
{
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;
}
GetSession()->SendPacket(&data);
}
void Player::SendInstanceResetWarning(uint32 mapid, Difficulty difficulty, uint32 time)
{
// type of warning, based on the time remaining until reset
uint32 type;
if (time > 3600)
type = RAID_INSTANCE_WELCOME;
else if (time > 900 && time <= 3600)
type = RAID_INSTANCE_WARNING_HOURS;
else if (time > 300 && time <= 900)
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
}
GetSession()->SendPacket(&data);
}
void Player::ApplyEquipCooldown(Item* pItem)
{
if (pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_PROTO_FLAG_NO_EQUIP_COOLDOWN))
return;
for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
{
_Spell const& spellData = pItem->GetTemplate()->Spells[i];
// no spell
if (!spellData.SpellId)
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.
SpellCooldowns::iterator itr = m_spellCooldowns.find(spellData.SpellId);
if (itr != m_spellCooldowns.end() && itr->second.itemid == pItem->GetEntry() && itr->second.end > time(NULL) + 30)
continue;
AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
data << pItem->GetGUID();
data << uint32(spellData.SpellId);
GetSession()->SendPacket(&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->spellfamily;
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
learnDefaultSpells();
learnQuestRewardedSpells();
}
void Player::learnDefaultSpells()
{
// learn default race/class spells
PlayerInfo const* info = sObjectMgr->GetPlayerInfo(getRace(), getClass());
for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr != info->spell.end(); ++itr)
{
uint32 tspell = *itr;
TC_LOG_DEBUG(LOG_FILTER_PLAYER_LOADING, "PLAYER (Class: %u Race: %u): Adding initial spell, id = %u", 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::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 (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (spellInfo->Effects[i].Effect == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->Effects[i].TriggerSpell))
{
found = true;
break;
}
}
// skip quests with not teaching spell or already known spell
if (!found)
return;
// prevent learn non first rank unknown profession and second specialization for same profession)
uint32 learned_0 = spellInfo->Effects[0].TriggerSpell;
if (sSpellMgr->GetSpellRank(learned_0) > 1 && !HasSpell(learned_0))
{
SpellInfo const* learnedInfo = sSpellMgr->GetSpellInfo(learned_0);
if (!learnedInfo)
return;
// not have first rank learned (unlearned prof?)
if (!HasSpell(learnedInfo->GetFirstRankSpell()->Id))
return;
SpellsRequiringSpellMapBounds spellsRequired = sSpellMgr->GetSpellsRequiredForSpellBounds(learned_0);
for (SpellsRequiringSpellMap::const_iterator itr2 = spellsRequired.first; itr2 != spellsRequired.second; ++itr2)
{
uint32 profSpell = itr2->second;
// specialization
if (learnedInfo->Effects[0].Effect == SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effects[1].Effect == 0 && profSpell)
{
// search other specialization for same prof
for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
{
if (itr->second->state == PLAYERSPELL_REMOVED || itr->first == learned_0)
continue;
SpellInfo const* itrInfo = sSpellMgr->GetSpellInfo(itr->first);
if (!itrInfo)
return;
// compare only specializations
if (itrInfo->Effects[0].Effect != SPELL_EFFECT_TRADE_SKILL || itrInfo->Effects[1].Effect != 0)
continue;
// compare same chain spells
if (sSpellMgr->IsSpellRequiringSpell(itr->first, profSpell))
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 skill_id, uint32 skill_value)
{
uint32 raceMask = getRaceMask();
uint32 classMask = getClassMask();
for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
{
SkillLineAbilityEntry const* pAbility = sSkillLineAbilityStore.LookupEntry(j);
if (!pAbility || pAbility->skillId != skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
continue;
// Check race if set
if (pAbility->racemask && !(pAbility->racemask & raceMask))
continue;
// Check class if set
if (pAbility->classmask && !(pAbility->classmask & classMask))
continue;
if (sSpellMgr->GetSpellInfo(pAbility->spellId))
{
// need unlearn spell
if (skill_value < pAbility->req_skill_value)
removeSpell(pAbility->spellId);
// need learn
else if (!IsInWorld())
addSpell(pAbility->spellId, true, true, true, false);
else
learnSpell(pAbility->spellId, true);
}
}
}
void Player::SendAurasForTarget(Unit* target)
{
if (!target || target->GetVisibleAuras()->empty()) // speedup things
return;
/*! Blizz sends certain movement packets sometimes even before CreateObject
These movement packets are usually found in SMSG_COMPRESSED_MOVES
*/
if (target->HasAuraType(SPELL_AURA_FEATHER_FALL))
target->SetFeatherFall(true, true);
if (target->HasAuraType(SPELL_AURA_WATER_WALK))
target->SetWaterWalking(true, true);
if (target->HasAuraType(SPELL_AURA_HOVER))
target->SetHover(true, true);
WorldPacket data(SMSG_AURA_UPDATE_ALL);
data.append(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);
}
GetSession()->SendPacket(&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 = time(NULL); // last daily quest time
m_DailyQuestChanged = true;
break;
}
}
} else
{
m_DFQuests.insert(quest_id);
m_lastDailyQuestTime = time(NULL);
m_DailyQuestChanged = true;
}
}
}
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[sGameEventMgr->GetEventIdForQuest(quest)].insert(quest_id);
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)
{
if (m_seasonalquests.empty() || m_seasonalquests[event_id].empty())
return;
m_seasonalquests.erase(event_id);
// DB data deleted in caller
m_SeasonalQuestChanged = false;
}
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 NULL;
return sBattlegroundMgr->GetBattleground(GetBattlegroundId(), m_bgData.bgTypeID);
}
bool Player::InBattlegroundQueue() const
{
for (uint8 i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
if (m_bgBattlegroundQueueID[i].bgQueueTypeId != BATTLEGROUND_QUEUE_NONE)
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()
{
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
{
FactionTemplateEntry const* vendor_faction = creature->GetFactionTemplateEntry();
if (!vendor_faction || !vendor_faction->faction)
return 1.0f;
ReputationRank rank = GetReputationRank(vendor_faction->faction);
if (rank <= REP_NEUTRAL)
return 1.0f;
return 1.0f - 0.05f* (rank - REP_NEUTRAL);
}
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;
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::UpdateForQuestWorldObjects()
{
if (m_clientGUIDs.empty())
return;
UpdateData udata;
WorldPacket packet;
for (ClientGUIDs::iterator itr=m_clientGUIDs.begin(); itr != m_clientGUIDs.end(); ++itr)
{
if (IS_GAMEOBJECT_GUID(*itr))
{
if (GameObject* obj = HashMapHolder<GameObject>::Find(*itr))
obj->BuildValuesUpdateBlockForPlayer(&udata, this);
}
else if (IS_CRE_OR_VEH_GUID(*itr))
{
Creature* obj = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, *itr);
if (!obj)
continue;
// check if this unit requires quest specific flags
if (!obj->HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK))
continue;
SpellClickInfoMapBounds clickPair = sObjectMgr->GetSpellClickInfoMapBounds(obj->GetEntry());
for (SpellClickInfoContainer::const_iterator _itr = clickPair.first; _itr != clickPair.second; ++_itr)
{
//! This code doesn't look right, but it was logically converted to condition system to do the exact
//! same thing it did before. It definitely needs to be overlooked for intended functionality.
ConditionList conds = sConditionMgr->GetConditionsForSpellClickEvent(obj->GetEntry(), _itr->second.spellId);
bool buildUpdateBlock = false;
for (ConditionList::const_iterator jtr = conds.begin(); jtr != conds.end() && !buildUpdateBlock; ++jtr)
if ((*jtr)->ConditionType == CONDITION_QUESTREWARDED || (*jtr)->ConditionType == CONDITION_QUESTTAKEN)
buildUpdateBlock = true;
if (buildUpdateBlock)
{
obj->BuildValuesUpdateBlockForPlayer(&udata, this);
break;
}
}
}
}
udata.BuildPacket(&packet);
GetSession()->SendPacket(&packet);
}
void Player::SetSummonPoint(uint32 mapid, float x, float y, float z)
{
m_summon_expire = time(NULL) + MAX_PLAYER_SUMMON_DELAY;
m_summon_mapid = mapid;
m_summon_x = x;
m_summon_y = y;
m_summon_z = z;
}
void Player::SummonIfPossible(bool agree)
{
if (!agree)
{
m_summon_expire = 0;
return;
}
// expire and auto declined
if (m_summon_expire < time(NULL))
return;
// stop taxi flight at summon
if (IsInFlight())
{
GetMotionMaster()->MovementExpired();
CleanupAfterTaxiFlight();
}
// 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_mapid, m_summon_x, m_summon_y, m_summon_z, GetOrientation());
}
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;
// unequip offhand weapon if player doesn't have dual wield anymore
if (!CanDualWield() && (offItem->GetTemplate()->InventoryType == INVTYPE_WEAPONOFFHAND || offItem->GetTemplate()->InventoryType == INVTYPE_WEAPON))
force = true;
// need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
if (!force && (CanTitanGrip() || (offItem->GetTemplate()->InventoryType != INVTYPE_2HWEAPON && !IsTwoHandUsed())))
return;
ItemPosCountVec off_dest;
uint8 off_msg = CanStoreItem(NULL_BAG, NULL_SLOT, off_dest, offItem, false);
if (off_msg == 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);
SQLTransaction 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:
{
// 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;
// shields can be equipped to offhand slot
if (Item* item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
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(LOG_FILTER_PLAYER, "HasItemFitToSpellRequirements: Not handled spell requirement for item class %u", 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->AttributesEx5 & SPELL_ATTR5_NO_REAGENT_WHILE_PREP &&
HasFlag(UNIT_FIELD_FLAGS, 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 passive (passive item dependent spells work in another way) and not self applied auras
SpellInfo const* spellInfo = aura->GetSpellInfo();
if (aura->IsPassive() || 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 casted 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(LOG_FILTER_PLAYER, "Unhandled spell %u: 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) && !HasSpellCooldown(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* victim)
{
uint8 v_level = victim->getLevel();
uint8 k_grey = Trinity::XP::GetGrayLevel(getLevel());
// Victim level less gray level
if (v_level <= k_grey)
return false;
if (victim->GetTypeId() == TYPEID_UNIT)
{
if (victim->ToCreature()->IsTotem() ||
victim->ToCreature()->IsPet() ||
victim->ToCreature()->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
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 = this->GetGroup())
{
for (GroupReference* itr = group->GetFirstMember(); itr != NULL; 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;
uint64 creature_guid = (pRewardSource->GetTypeId() == TYPEID_UNIT) ? pRewardSource->GetGUID() : uint64(0);
// prepare data for near group iteration
if (Group* group = GetGroup())
{
for (GroupReference* itr = group->GetFirstMember(); itr != NULL; 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)
return false;
const WorldObject* player = GetCorpse();
if (!player || IsAlive())
player = this;
if (player->GetMapId() != pRewardSource->GetMapId() || player->GetInstanceId() != pRewardSource->GetInstanceId())
return false;
return pRewardSource->GetDistance(player) <= sWorld->getFloatConfig(CONFIG_GROUP_XP_DISTANCE);
}
bool Player::IsAtRecruitAFriendDistance(WorldObject const* pOther) const
{
if (!pOther)
return false;
const WorldObject* player = GetCorpse();
if (!player || IsAlive())
player = this;
if (player->GetMapId() != pOther->GetMapId() || player->GetInstanceId() != pOther->GetInstanceId())
return false;
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 and for fist weapons)
uint32 skill = (item && item->GetSkill() != SKILL_FIST_WEAPONS) ? item->GetSkill() : uint32(SKILL_UNARMED);
return GetBaseSkillValue(skill);
}
void Player::ResurectUsingRequestData()
{
/// Teleport before resurrecting by player, otherwise the player might get attacked from creatures near his corpse
TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
if (IsBeingTeleported())
{
ScheduleDelayedOperation(DELAYED_RESURRECT_PLAYER);
return;
}
ResurrectPlayer(0.0f, false);
if (GetMaxHealth() > m_resurrectHealth)
SetHealth(m_resurrectHealth);
else
SetFullHealth();
if (GetMaxPower(POWER_MANA) > m_resurrectMana)
SetPower(POWER_MANA, m_resurrectMana);
else
SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
SetPower(POWER_RAGE, 0);
SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
SpawnCorpseBones();
}
void Player::SetClientControl(Unit* target, uint8 allowMove)
{
WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
data.append(target->GetPackGUID());
data << uint8(allowMove);
GetSession()->SendPacket(&data);
if (target == this)
SetMover(this);
}
void Player::SetMover(Unit* target)
{
m_mover->m_movedPlayer = NULL;
m_mover = target;
m_mover->m_movedPlayer = this;
}
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) != 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);
if (newArea == 4273 && GetVehicleCreatureBase() && GetPositionX() > 400) // Ulduar
{
switch (GetVehicleBase()->GetEntry())
{
case 33062:
case 33109:
case 33060:
GetVehicleCreatureBase()->DespawnOrUnsummon();
break;
}
}
}
uint32 Player::GetCorpseReclaimDelay(bool pvp) const
{
if (pvp)
{
if (!sWorld->getBoolConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP))
return copseReclaimDelay[0];
}
else if (!sWorld->getBoolConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE))
return 0;
time_t now = time(NULL);
// 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 copseReclaimDelay[count];
}
void Player::UpdateCorpseReclaimDelay()
{
bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
if ((pvp && !sWorld->getBoolConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
(!pvp && !sWorld->getBoolConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE)))
return;
time_t now = time(NULL);
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;
}
void Player::SendCorpseReclaimDelay(bool load)
{
Corpse* corpse = GetCorpse();
if (load && !corpse)
return;
bool pvp;
if (corpse)
pvp = (corpse->GetType() == CORPSE_RESURRECTABLE_PVP);
else
pvp = (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH);
time_t delay;
if (load)
{
if (corpse->GetGhostTime() > m_deathExpireTime)
return;
uint64 count;
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;
}
else
count=0;
time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
time_t now = time(NULL);
if (now >= expected_time)
return;
delay = expected_time-now;
}
else
delay = GetCorpseReclaimDelay(pvp);
if (!delay)
return;
//! corpse reclaim delay 30 * 1000ms or longer at often deaths
WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
data << uint32(delay*IN_MILLISECONDS);
GetSession()->SendPacket(&data);
}
Player* Player::GetNextRandomRaidMember(float radius)
{
Group* group = GetGroup();
if (!group)
return NULL;
std::vector<Player*> nearMembers;
nearMembers.reserve(group->GetMembersCount());
for (GroupReference* itr = group->GetFirstMember(); itr != NULL; 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 NULL;
uint32 randTarget = urand(0, nearMembers.size()-1);
return nearMembers[randTarget];
}
PartyResult Player::CanUninviteFromGroup() const
{
Group const* grp = GetGroup();
if (!grp)
return ERR_NOT_IN_GROUP;
if (grp->isLFGGroup())
{
uint64 gguid = grp->GetGUID();
if (!sLFGMgr->GetKicksLeft(gguid))
return ERR_PARTY_LFG_BOOT_LIMIT;
lfg::LfgState state = sLFGMgr->GetState(gguid);
if (state == lfg::LFG_STATE_BOOT)
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 != NULL; itr = itr->next())
if (itr->GetSource() && 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;
}
return ERR_PARTY_RESULT_OK;
}
bool Player::isUsingLfg()
{
return sLFGMgr->GetState(GetGUID()) != lfg::LFG_STATE_NONE;
}
bool Player::inRandomLfgDungeon()
{
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(NULL);
}
void Player::SetOriginalGroup(Group* group, int8 subgroup)
{
if (group == NULL)
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::UpdateUnderwaterState(Map* m, float x, float y, float z)
{
LiquidData liquid_status;
ZLiquidStatus res = m->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquid_status);
if (!res)
{
m_MirrorTimerFlags &= ~(UNDERWATER_INWATER | UNDERWATER_INLAVA | UNDERWATER_INSLIME | UNDERWARER_INDARKWATER);
if (_lastLiquid && _lastLiquid->SpellId)
RemoveAurasDueToSpell(_lastLiquid->SpellId);
_lastLiquid = NULL;
return;
}
if (uint32 liqEntry = liquid_status.entry)
{
LiquidTypeEntry const* liquid = sLiquidTypeStore.LookupEntry(liqEntry);
if (_lastLiquid && _lastLiquid->SpellId && _lastLiquid->Id != liqEntry)
RemoveAurasDueToSpell(_lastLiquid->SpellId);
if (liquid && liquid->SpellId)
{
if (res & (LIQUID_MAP_UNDER_WATER | LIQUID_MAP_IN_WATER))
{
if (!HasAura(liquid->SpellId))
CastSpell(this, liquid->SpellId, true);
}
else
RemoveAurasDueToSpell(liquid->SpellId);
}
_lastLiquid = liquid;
}
else if (_lastLiquid && _lastLiquid->SpellId)
{
RemoveAurasDueToSpell(_lastLiquid->SpellId);
_lastLiquid = NULL;
}
// All liquids type - check under water position
if (liquid_status.type_flags & (MAP_LIQUID_TYPE_WATER | MAP_LIQUID_TYPE_OCEAN | MAP_LIQUID_TYPE_MAGMA | MAP_LIQUID_TYPE_SLIME))
{
if (res & LIQUID_MAP_UNDER_WATER)
m_MirrorTimerFlags |= UNDERWATER_INWATER;
else
m_MirrorTimerFlags &= ~UNDERWATER_INWATER;
}
// Allow travel in dark water on taxi or transport
if ((liquid_status.type_flags & MAP_LIQUID_TYPE_DARK_WATER) && !IsInFlight() && !GetTransport())
m_MirrorTimerFlags |= UNDERWARER_INDARKWATER;
else
m_MirrorTimerFlags &= ~UNDERWARER_INDARKWATER;
// in lava check, anywhere in lava level
if (liquid_status.type_flags & MAP_LIQUID_TYPE_MAGMA)
{
if (res & (LIQUID_MAP_UNDER_WATER | LIQUID_MAP_IN_WATER | LIQUID_MAP_WATER_WALK))
m_MirrorTimerFlags |= UNDERWATER_INLAVA;
else
m_MirrorTimerFlags &= ~UNDERWATER_INLAVA;
}
// in slime check, anywhere in slime level
if (liquid_status.type_flags & MAP_LIQUID_TYPE_SLIME)
{
if (res & (LIQUID_MAP_UNDER_WATER | LIQUID_MAP_IN_WATER | LIQUID_MAP_WATER_WALK))
m_MirrorTimerFlags |= UNDERWATER_INSLIME;
else
m_MirrorTimerFlags &= ~UNDERWATER_INSLIME;
}
}
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(ItemPosCountVec 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()
{
if (WorldObject* target = GetViewpoint())
{
if (target->isType(TYPEMASK_UNIT))
{
((Unit*)target)->RemoveAurasByType(SPELL_AURA_BIND_SIGHT, GetGUID());
((Unit*)target)->RemoveAurasByType(SPELL_AURA_MOD_POSSESS, GetGUID());
((Unit*)target)->RemoveAurasByType(SPELL_AURA_MOD_POSSESS_PET, GetGUID());
}
}
}
void Player::SetViewpoint(WorldObject* target, bool apply)
{
if (apply)
{
TC_LOG_DEBUG(LOG_FILTER_MAPS, "Player::CreateViewpoint: Player %s create seer %u (TypeId: %u).", GetName().c_str(), target->GetEntry(), target->GetTypeId());
if (!AddUInt64Value(PLAYER_FARSIGHT, target->GetGUID()))
{
TC_LOG_FATAL(LOG_FILTER_PLAYER, "Player::CreateViewpoint: Player %s cannot add new viewpoint!", GetName().c_str());
return;
}
// farsight dynobj or puppet may be very far away
UpdateVisibilityOf(target);
if (target->isType(TYPEMASK_UNIT) && !GetVehicle())
((Unit*)target)->AddPlayerToVision(this);
}
else
{
TC_LOG_DEBUG(LOG_FILTER_MAPS, "Player::CreateViewpoint: Player %s remove seer", GetName().c_str());
if (!RemoveUInt64Value(PLAYER_FARSIGHT, target->GetGUID()))
{
TC_LOG_FATAL(LOG_FILTER_PLAYER, "Player::CreateViewpoint: Player %s cannot remove current viewpoint!", GetName().c_str());
return;
}
if (target->isType(TYPEMASK_UNIT) && !GetVehicle())
((Unit*)target)->RemovePlayerFromVision(this);
//must immediately set seer back otherwise may crash
m_seer = this;
//WorldPacket data(SMSG_CLEAR_FAR_SIGHT_IMMEDIATE, 0);
//GetSession()->SendPacket(&data);
}
}
WorldObject* Player::GetViewpoint() const
{
if (uint64 guid = GetUInt64Value(PLAYER_FARSIGHT))
return (WorldObject*)ObjectAccessor::GetObjectByTypeMask(*this, guid, TYPEMASK_SEER);
return NULL;
}
bool Player::CanUseBattlegroundObject(GameObject* gameobject)
{
// 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->GetUInt32Value(GAMEOBJECT_FACTION));
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()
{
return (!HasStealthAura() && // not stealthed
!HasInvisibilityAura() && // not invisible
IsAlive()); // live player
}
uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair, BarberShopStyleEntry const* newSkin)
{
uint8 level = getLevel();
if (level > GT_MAX_LEVEL)
level = GT_MAX_LEVEL; // max level in this dbc
uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
uint8 skincolor = GetByteValue(PLAYER_BYTES, 0);
if ((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair) && (!newSkin || (newSkin->hair_id == 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->cost; // full price
if ((haircolor != newhaircolor) && (hairstyle == newhairstyle))
cost += bsc->cost * 0.5f; // +1/2 of price
if (facialhair != newfacialhair)
cost += bsc->cost * 0.75f; // +3/4 of price
if (newSkin && skincolor != newSkin->hair_id)
cost += bsc->cost * 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->Order)
SetGlyphSlot(gs->Order - 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)
{
m_Glyphs[m_activeSpec][slot] = glyph;
SetUInt32Value(PLAYER_FIELD_GLYPHS_1 + slot, glyph);
}
bool Player::isTotalImmune()
{
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)
{
if (bitIndex > MAX_TITLE_INDEX)
return false;
uint32 fieldIndexOffset = bitIndex / 32;
uint32 flag = 1 << (bitIndex % 32);
return HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
}
void Player::SetTitle(CharTitlesEntry const* title, bool lost)
{
uint32 fieldIndexOffset = title->bit_index / 32;
uint32 flag = 1 << (title->bit_index % 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->bit_index);
data << uint32(lost ? 0 : 1); // 1 - earned, 0 - lost
GetSession()->SendPacket(&data);
}
bool Player::isTotalImmunity()
{
AuraEffectList const& immune = GetAuraEffectsByType(SPELL_AURA_SCHOOL_IMMUNITY);
for (AuraEffectList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
{
if (((*itr)->GetMiscValue() & SPELL_SCHOOL_MASK_ALL) !=0) // total immunity
{
return true;
}
if (((*itr)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL) !=0) // physical damage immunity
{
for (AuraEffectList::const_iterator i = immune.begin(); i != immune.end(); ++i)
{
if (((*i)->GetMiscValue() & SPELL_SCHOOL_MASK_MAGIC) !=0) // magic immunity
{
return true;
}
}
}
}
return false;
}
void Player::UpdateCharmedAI()
{
//This should only called in Player::Update
Creature* charmer = GetCharmer()->ToCreature();
//kill self if charm aura has infinite duration
if (charmer->IsInEvadeMode())
{
AuraEffectList const& auras = GetAuraEffectsByType(SPELL_AURA_MOD_CHARM);
for (AuraEffectList::const_iterator iter = auras.begin(); iter != auras.end(); ++iter)
if ((*iter)->GetCasterGUID() == charmer->GetGUID() && (*iter)->GetBase()->IsPermanent())
{
charmer->DealDamage(this, GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
return;
}
}
if (!charmer->IsInCombat())
GetMotionMaster()->MoveFollow(charmer, PET_FOLLOW_DIST, PET_FOLLOW_ANGLE);
Unit* target = GetVictim();
if (!target || !charmer->IsValidAttackTarget(target))
{
target = charmer->SelectNearestTarget();
if (!target)
return;
GetMotionMaster()->MoveChase(target);
Attack(target, true);
}
}
uint32 Player::GetRuneBaseCooldown(uint8 index)
{
uint8 rune = GetBaseRune(index);
uint32 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() == rune)
cooldown = cooldown*(100-(*i)->GetAmount())/100;
}
return cooldown;
}
void Player::SetRuneCooldown(uint8 index, uint32 cooldown)
{
m_runes->runes[index].Cooldown = cooldown;
m_runes->SetRuneState(index, (cooldown == 0) ? true : false);
}
void Player::SetRuneConvertAura(uint8 index, AuraEffect const* aura)
{
m_runes->runes[index].ConvertAura = 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 i = 0; i < MAX_RUNES; ++i)
{
if (m_runes->runes[i].ConvertAura == aura)
{
ConvertRune(i, GetBaseRune(i));
SetRuneConvertAura(i, NULL);
}
}
}
void Player::RestoreBaseRune(uint8 index)
{
AuraEffect const* aura = m_runes->runes[index].ConvertAura;
// If rune was converted by a non-pasive aura that still active we should keep it converted
if (aura && !(aura->GetSpellInfo()->Attributes & SPELL_ATTR0_PASSIVE))
return;
ConvertRune(index, GetBaseRune(index));
SetRuneConvertAura(index, NULL);
// Don't drop passive talents providing rune convertion
if (!aura || aura->GetAuraType() != SPELL_AURA_CONVERT_RUNE)
return;
for (uint8 i = 0; i < MAX_RUNES; ++i)
{
if (aura == m_runes->runes[i].ConvertAura)
return;
}
aura->GetBase()->Remove();
}
void Player::ConvertRune(uint8 index, RuneType newType)
{
SetCurrentRune(index, newType);
WorldPacket data(SMSG_CONVERT_RUNE, 2);
data << uint8(index);
data << uint8(newType);
GetSession()->SendPacket(&data);
}
void Player::ResyncRunes(uint8 count)
{
WorldPacket data(SMSG_RESYNC_RUNES, 4 + count * 2);
data << uint32(count);
for (uint32 i = 0; i < count; ++i)
{
data << uint8(GetCurrentRune(i)); // rune type
data << uint8(255 - (GetRuneCooldown(i) * 51)); // passed cooldown time (0-255)
}
GetSession()->SendPacket(&data);
}
void Player::AddRunePower(uint8 index)
{
WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
data << uint32(1 << index); // mask (0x00-0x3F probably)
GetSession()->SendPacket(&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
SetRuneConvertAura(i, NULL);
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)
{
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, NULL, NULL, lootItem->itemid);
continue;
}
Item* pItem = StoreNewItem(dest, lootItem->itemid, true, lootItem->randomPropertyId);
SendNewItem(pItem, lootItem->count, false, false, broadcast);
}
}
void Player::StoreLootItem(uint8 lootSlot, Loot* loot)
{
QuestItem* qitem = NULL;
QuestItem* ffaitem = NULL;
QuestItem* conditem = NULL;
LootItem* item = loot->LootItemInSlot(lootSlot, this, &qitem, &ffaitem, &conditem);
if (!item)
{
SendEquipError(EQUIP_ERR_ALREADY_LOOTED, NULL, NULL);
return;
}
// questitems use the blocked field for other purposes
if (!qitem && item->is_blocked)
{
SendLootRelease(GetLootGUID());
return;
}
ItemPosCountVec dest;
InventoryResult msg = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, item->itemid, item->count);
if (msg == EQUIP_ERR_OK)
{
AllowedLooterSet looters = item->GetAllowedLooters();
Item* newitem = StoreNewItem(dest, item->itemid, true, item->randomPropertyId, looters);
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)
loot->DeleteLootItemFromContainerItemDB(item->itemid);
#ifdef ELUNA
sHookMgr->OnLootItem(this, newitem, item->count, this->GetLootGUID());
#endif
}
else
SendEquipError(msg, NULL, NULL, item->itemid);
}
uint32 Player::CalculateTalentsPoints() const
{
uint32 base_talent = getLevel() < 10 ? 0 : getLevel()-9;
if (getClass() != CLASS_DEATH_KNIGHT || GetMapId() != 609)
return uint32(base_talent * sWorld->getRate(RATE_TALENT));
uint32 talentPointsForLevel = getLevel() < 56 ? 0 : getLevel() - 55;
talentPointsForLevel += m_questRewardTalentCount;
if (talentPointsForLevel > base_talent)
talentPointsForLevel = base_talent;
return uint32(talentPointsForLevel * sWorld->getRate(RATE_TALENT));
}
bool Player::IsKnowHowFlyIn(uint32 mapid, uint32 zone) const
{
// continent checked in SpellInfo::CheckLocation at cast and area update
uint32 v_map = GetVirtualMapForMapAndZone(mapid, zone);
return v_map != 571 || HasSpell(54197); // Cold Weather Flying
}
void Player::learnSpellHighRank(uint32 spellid)
{
learnSpell(spellid, false);
if (uint32 next = sSpellMgr->GetNextSpellInChain(spellid))
learnSpellHighRank(next);
}
void Player::_LoadSkills(PreparedQueryResult result)
{
// 0 1 2
// SetPQuery(PLAYER_LOGIN_QUERY_LOADSKILLS, "SELECT skill, value, max FROM character_skills WHERE guid = '%u'", GUID_LOPART(m_guid));
uint32 count = 0;
if (result)
{
do
{
Field* fields = result->Fetch();
uint16 skill = fields[0].GetUInt16();
uint16 value = fields[1].GetUInt16();
uint16 max = fields[2].GetUInt16();
SkillLineEntry const* pSkill = sSkillLineStore.LookupEntry(skill);
if (!pSkill)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Character %u has skill %u that does not exist.", GetGUIDLow(), skill);
continue;
}
// set fixed skill ranges
switch (GetSkillRangeType(pSkill, false))
{
case SKILL_RANGE_LANGUAGE: // 300..300
value = max = 300;
break;
case SKILL_RANGE_MONO: // 1..1, grey monolite bar
value = max = 1;
break;
default:
break;
}
if (value == 0)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Character %u has skill %u with value 0. Will be deleted.", GetGUIDLow(), skill);
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHARACTER_SKILL);
stmt->setUInt32(0, GetGUIDLow());
stmt->setUInt16(1, skill);
CharacterDatabase.Execute(stmt);
continue;
}
// enable unlearn button for primary professions only
if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
SetUInt32Value(PLAYER_SKILL_INDEX(count), MAKE_PAIR32(skill, 1));
else
SetUInt32Value(PLAYER_SKILL_INDEX(count), MAKE_PAIR32(skill, 0));
SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count), MAKE_SKILL_VALUE(value, max));
SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count), 0);
mSkillStatus.insert(SkillStatusMap::value_type(skill, SkillStatusData(count, SKILL_UNCHANGED)));
learnSkillRewardedSpells(skill, value);
++count;
if (count >= PLAYER_MAX_SKILLS) // client limit
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Character %u has more than %u skills.", GetGUIDLow(), PLAYER_MAX_SKILLS);
break;
}
}
while (result->NextRow());
}
for (; count < PLAYER_MAX_SKILLS; ++count)
{
SetUInt32Value(PLAYER_SKILL_INDEX(count), 0);
SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count), 0);
SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count), 0);
}
// special settings
if (getClass() == CLASS_DEATH_KNIGHT)
{
uint8 base_level = std::min(getLevel(), uint8(sWorld->getIntConfig(CONFIG_START_HEROIC_PLAYER_LEVEL)));
if (base_level < 1)
base_level = 1;
uint16 base_skill = (base_level-1)*5; // 270 at starting level 55
if (base_skill < 1)
base_skill = 1; // skill mast be known and then > 0 in any case
if (GetPureSkillValue(SKILL_FIRST_AID) < base_skill)
SetSkill(SKILL_FIRST_AID, 0, base_skill, base_skill);
if (GetPureSkillValue(SKILL_AXES) < base_skill)
SetSkill(SKILL_AXES, 0, base_skill, base_skill);
if (GetPureSkillValue(SKILL_DEFENSE) < base_skill)
SetSkill(SKILL_DEFENSE, 0, base_skill, base_skill);
if (GetPureSkillValue(SKILL_POLEARMS) < base_skill)
SetSkill(SKILL_POLEARMS, 0, base_skill, base_skill);
if (GetPureSkillValue(SKILL_SWORDS) < base_skill)
SetSkill(SKILL_SWORDS, 0, base_skill, base_skill);
if (GetPureSkillValue(SKILL_2H_AXES) < base_skill)
SetSkill(SKILL_2H_AXES, 0, base_skill, base_skill);
if (GetPureSkillValue(SKILL_2H_SWORDS) < base_skill)
SetSkill(SKILL_2H_SWORDS, 0, base_skill, base_skill);
if (GetPureSkillValue(SKILL_UNARMED) < base_skill)
SetSkill(SKILL_UNARMED, 0, base_skill, base_skill);
}
}
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->GemID);
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->Flags & ITEM_PROTO_FLAG_UNIQUE_EQUIPPED)
{
// there is an equip limit on this item
if (HasItemOrGemWithIdEquipped(itemProto->ItemId, 1, except_slot))
return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
}
// check unique-equipped limit
if (itemProto->ItemLimitCategory)
{
ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory);
if (!limitEntry)
return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
// NOTE: limitEntry->mode not checked because if item have have-limit then it applied and to equip case
if (limit_count > limitEntry->maxCount)
return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED;
// there is an equip limit on this item
if (HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory, limitEntry->maxCount - 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 = %f", 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));
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(LOG_FILTER_PLAYER, "FALLDAMAGE z=%f sz=%f pZ=%f FallTime=%d mZ=%f damage=%d SF=%d", movementInfo.pos.GetPositionZ(), height, GetPositionZ(), movementInfo.fallTime, height, damage, safe_fall);
}
}
RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_LANDING); // No fly zone - Parachute
}
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(AchievementCriteriaTypes type, uint32 miscValue1 /*= 0*/, uint32 miscValue2 /*= 0*/, bool evenIfCriteriaComplete /* = false*/)
{
m_achievementMgr->ResetAchievementCriteria(type, miscValue1, miscValue2, evenIfCriteriaComplete);
}
void Player::UpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 /*= 0*/, uint32 miscValue2 /*= 0*/, Unit* unit /*= NULL*/)
{
m_achievementMgr->UpdateAchievementCriteria(type, miscValue1, miscValue2, unit);
}
void Player::CompletedAchievement(AchievementEntry const* entry)
{
m_achievementMgr->CompletedAchievement(entry);
}
void Player::LearnTalent(uint32 talentId, uint32 talentRank)
{
uint32 CurTalentPoints = GetFreeTalentPoints();
if (CurTalentPoints == 0)
return;
if (talentRank >= MAX_TALENT_RANK)
return;
TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
if (!talentInfo)
return;
TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
if (!talentTabInfo)
return;
// prevent learn talent for different class (cheating)
if ((getClassMask() & talentTabInfo->ClassMask) == 0)
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->RankID[rank] && HasSpell(talentInfo->RankID[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->DependsOn > 0)
{
if (TalentEntry const* depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
{
bool hasEnoughRank = false;
for (uint8 rank = talentInfo->DependsOnRank; rank < MAX_TALENT_RANK; rank++)
{
if (depTalentInfo->RankID[rank] != 0)
if (HasSpell(depTalentInfo->RankID[rank]))
hasEnoughRank = true;
}
if (!hasEnoughRank)
return;
}
}
// Find out how many points we have in this field
uint32 spentPoints = 0;
uint32 tTab = talentInfo->TalentTab;
if (talentInfo->Row > 0)
{
uint32 numRows = sTalentStore.GetNumRows();
for (uint32 i = 0; i < numRows; i++) // Loop through all talents.
{
// Someday, someone needs to revamp
const TalentEntry* tmpTalent = sTalentStore.LookupEntry(i);
if (tmpTalent) // the way talents are tracked
{
if (tmpTalent->TalentTab == tTab)
{
for (uint8 rank = 0; rank < MAX_TALENT_RANK; rank++)
{
if (tmpTalent->RankID[rank] != 0)
{
if (HasSpell(tmpTalent->RankID[rank]))
{
spentPoints += (rank + 1);
}
}
}
}
}
}
}
// not have required min points spent in talent tree
if (spentPoints < (talentInfo->Row * MAX_TALENT_RANK))
return;
// spell not set in talent.dbc
uint32 spellid = talentInfo->RankID[talentRank];
if (spellid == 0)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
return;
}
// already known
if (HasSpell(spellid))
return;
// learn! (other talent ranks will unlearned at learning)
learnSpell(spellid, false);
AddTalent(spellid, m_activeSpec, true);
TC_LOG_INFO(LOG_FILTER_PLAYER, "TalentID: %u Rank: %u Spell: %u Spec: %u\n", talentId, talentRank, spellid, m_activeSpec);
// update free talent points
SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
}
void Player::LearnPetTalent(uint64 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->TalentTab);
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->RankID[rank] && pet->HasSpell(talentInfo->RankID[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->DependsOn > 0)
{
if (TalentEntry const* depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
{
bool hasEnoughRank = false;
for (uint8 rank = talentInfo->DependsOnRank; rank < MAX_TALENT_RANK; rank++)
{
if (depTalentInfo->RankID[rank] != 0)
if (pet->HasSpell(depTalentInfo->RankID[rank]))
hasEnoughRank = true;
}
if (!hasEnoughRank)
return;
}
}
// Find out how many points we have in this field
uint32 spentPoints = 0;
uint32 tTab = talentInfo->TalentTab;
if (talentInfo->Row > 0)
{
uint32 numRows = sTalentStore.GetNumRows();
for (uint32 i = 0; i < numRows; ++i) // Loop through all talents.
{
// Someday, someone needs to revamp
const TalentEntry* tmpTalent = sTalentStore.LookupEntry(i);
if (tmpTalent) // the way talents are tracked
{
if (tmpTalent->TalentTab == tTab)
{
for (uint8 rank = 0; rank < MAX_TALENT_RANK; rank++)
{
if (tmpTalent->RankID[rank] != 0)
{
if (pet->HasSpell(tmpTalent->RankID[rank]))
{
spentPoints += (rank + 1);
}
}
}
}
}
}
}
// not have required min points spent in talent tree
if (spentPoints < (talentInfo->Row * MAX_PET_TALENT_RANK))
return;
// spell not set in talent.dbc
uint32 spellid = talentInfo->RankID[talentRank];
if (spellid == 0)
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Talent.dbc have for talent: %u Rank: %u 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_INFO(LOG_FILTER_PLAYER, "PetTalentID: %u Rank: %u Spell: %u\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())
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->HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK))
return false;
SpellClickInfoMapBounds clickPair = sObjectMgr->GetSpellClickInfoMapBounds(c->GetEntry());
if (clickPair.first == clickPair.second)
return true;
for (SpellClickInfoContainer::const_iterator itr = clickPair.first; itr != clickPair.second; ++itr)
{
if (!itr->second.IsFitToRequirements(this, c))
return false;
ConditionList conds = sConditionMgr->GetConditionsForSpellClickEvent(c->GetEntry(), itr->second.spellId);
ConditionSourceInfo info = ConditionSourceInfo(const_cast<Player*>(this), const_cast<Creature*>(c));
if (sConditionMgr->IsObjectMeetToConditions(info, conds))
return true;
}
return false;
}
void Player::BuildPlayerTalentsInfoData(WorldPacket* data)
{
*data << uint32(GetFreeTalentPoints()); // unspentTalentPoints
*data << uint8(m_specsCount); // talent group count (0, 1 or 2)
*data << uint8(m_activeSpec); // talent group index (0 or 1)
if (m_specsCount)
{
if (m_specsCount > MAX_TALENT_SPECS)
m_specsCount = MAX_TALENT_SPECS;
// loop through all specs (only 1 for now)
for (uint32 specIdx = 0; specIdx < m_specsCount; ++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->TalentTab != talentTabId)
continue;
// find max talent rank (0~4)
int8 curtalent_maxrank = -1;
for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank)
{
if (talentInfo->RankID[rank] && HasTalent(talentInfo->RankID[rank], specIdx))
{
curtalent_maxrank = rank;
break;
}
}
// not learned talent
if (curtalent_maxrank < 0)
continue;
*data << uint32(talentInfo->TalentID); // 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(m_Glyphs[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->TalentTab != talentTabId)
continue;
// find max talent rank (0~4)
int8 curtalent_maxrank = -1;
for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank)
{
if (talentInfo->RankID[rank] && pet->HasSpell(talentInfo->RankID[rank]))
{
curtalent_maxrank = rank;
break;
}
}
// not learned talent
if (curtalent_maxrank < 0)
continue;
*data << uint32(talentInfo->TalentID); // 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);
GetSession()->SendPacket(&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 << uint16(0); // unknown
data->appendPackGUID(item->GetUInt64Value(ITEM_FIELD_CREATOR)); // item creator
*data << uint32(0); // seed?
}
data->put<uint32>(slotUsedMaskPos, slotUsedMask);
}
void Player::SendEquipmentSetList()
{
uint32 count = 0;
WorldPacket data(SMSG_EQUIPMENT_SET_LIST, 4);
size_t count_pos = data.wpos();
data << uint32(count); // count placeholder
for (EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
{
if (itr->second.state == EQUIPMENT_SET_DELETED)
continue;
data.appendPackGUID(itr->second.Guid);
data << uint32(itr->first);
data << itr->second.Name;
data << itr->second.IconName;
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 (itr->second.IgnoreMask & (1 << i))
data.appendPackGUID(uint64(1));
else
data.appendPackGUID(MAKE_NEW_GUID(itr->second.Items[i], 0, HIGHGUID_ITEM));
}
++count; // client have limit but it checked at loading and set
}
data.put<uint32>(count_pos, count);
GetSession()->SendPacket(&data);
}
void Player::SetEquipmentSet(uint32 index, EquipmentSet eqset)
{
if (eqset.Guid != 0)
{
bool found = false;
for (EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
{
if ((itr->second.Guid == eqset.Guid) && (itr->first == index))
{
found = true;
break;
}
}
if (!found) // something wrong...
{
TC_LOG_ERROR(LOG_FILTER_PLAYER, "Player %s tried to save equipment set "UI64FMTD" (index %u), but that equipment set not found!", GetName().c_str(), eqset.Guid, index);
return;
}
}
EquipmentSet& eqslot = m_EquipmentSets[index];
EquipmentSetUpdateState old_state = eqslot.state;
eqslot = eqset;
if (eqset.Guid == 0)
{
eqslot.Guid = sObjectMgr->GenerateEquipmentSetGuid();
WorldPacket data(SMSG_EQUIPMENT_SET_SAVED, 4 + 1);
data << uint32(index);
data.appendPackGUID(eqslot.Guid);
GetSession()->SendPacket(&data);
}
eqslot.state = old_state == EQUIPMENT_SET_NEW ? EQUIPMENT_SET_NEW : EQUIPMENT_SET_CHANGED;
}
void Player::_SaveEquipmentSets(SQLTransaction& trans)
{
for (EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end();)
{
uint32 index = itr->first;
EquipmentSet& eqset = itr->second;
PreparedStatement* stmt = NULL;
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.Name.c_str());
stmt->setString(j++, eqset.IconName.c_str());
stmt->setUInt32(j++, eqset.IgnoreMask);
for (uint8 i=0; i<EQUIPMENT_SLOT_END; ++i)
stmt->setUInt32(j++, eqset.Items[i]);
stmt->setUInt32(j++, GetGUIDLow());
stmt->setUInt64(j++, eqset.Guid);
stmt->setUInt32(j, index);
trans->Append(stmt);
eqset.state = EQUIPMENT_SET_UNCHANGED;
++itr;
break;
case EQUIPMENT_SET_NEW:
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_EQUIP_SET);
stmt->setUInt32(j++, GetGUIDLow());
stmt->setUInt64(j++, eqset.Guid);
stmt->setUInt32(j++, index);
stmt->setString(j++, eqset.Name.c_str());
stmt->setString(j++, eqset.IconName.c_str());
stmt->setUInt32(j++, eqset.IgnoreMask);
for (uint8 i=0; i<EQUIPMENT_SLOT_END; ++i)
stmt->setUInt32(j++, eqset.Items[i]);
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.Guid);
trans->Append(stmt);
m_EquipmentSets.erase(itr++);
break;
}
}
}
void Player::_SaveBGData(SQLTransaction& trans)
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_BGDATA);
stmt->setUInt32(0, GetGUIDLow());
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, GetGUIDLow());
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->setUInt16(8, m_bgData.taxiPath[0]);
stmt->setUInt16(9, m_bgData.taxiPath[1]);
stmt->setUInt16(10, m_bgData.mountSpell);
trans->Append(stmt);
}
void Player::DeleteEquipmentSet(uint64 setGuid)
{
for (EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
{
if (itr->second.Guid == setGuid)
{
if (itr->second.state == EQUIPMENT_SET_NEW)
m_EquipmentSets.erase(itr);
else
itr->second.state = EQUIPMENT_SET_DELETED;
break;
}
}
}
void Player::RemoveAtLoginFlag(AtLoginFlags flags, bool persist /*= false*/)
{
m_atLoginFlags &= ~flags;
if (persist)
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_REM_AT_LOGIN_FLAG);
stmt->setUInt16(0, uint16(flags));
stmt->setUInt32(1, GetGUIDLow());
CharacterDatabase.Execute(stmt);
}
}
void Player::SendClearCooldown(uint32 spell_id, Unit* target)
{
WorldPacket data(SMSG_CLEAR_COOLDOWN, 4+8);
data << uint32(spell_id);
data << uint64(target->GetGUID());
SendDirectMessage(&data);
}
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 NULL 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 spec, 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 >= m_specsCount)
continue;
m_Glyphs[spec][0] = fields[1].GetUInt16();
m_Glyphs[spec][1] = fields[2].GetUInt16();
m_Glyphs[spec][2] = fields[3].GetUInt16();
m_Glyphs[spec][3] = fields[4].GetUInt16();
m_Glyphs[spec][4] = fields[5].GetUInt16();
m_Glyphs[spec][5] = fields[6].GetUInt16();
}
while (result->NextRow());
}
void Player::_SaveGlyphs(SQLTransaction& trans)
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_GLYPHS);
stmt->setUInt32(0, GetGUIDLow());
trans->Append(stmt);
for (uint8 spec = 0; spec < m_specsCount; ++spec)
{
uint8 index = 0;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_GLYPHS);
stmt->setUInt32(index++, GetGUIDLow());
stmt->setUInt8(index++, spec);
for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
stmt->setUInt16(index++, uint16(m_Glyphs[spec][i]));
trans->Append(stmt);
}
}
void Player::_LoadTalents(PreparedQueryResult result)
{
// SetPQuery(PLAYER_LOGIN_QUERY_LOADTALENTS, "SELECT spell, spec FROM character_talent WHERE guid = '%u'", GUID_LOPART(m_guid));
if (result)
{
do
AddTalent((*result)[0].GetUInt32(), (*result)[1].GetUInt8(), false);
while (result->NextRow());
}
}
void Player::_SaveTalents(SQLTransaction& trans)
{
PreparedStatement* stmt = NULL;
for (uint8 i = 0; i < MAX_TALENT_SPECS; ++i)
{
for (PlayerTalentMap::iterator itr = m_talents[i]->begin(); itr != m_talents[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, GetGUIDLow());
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, GetGUIDLow());
stmt->setUInt32(1, itr->first);
stmt->setUInt8(2, itr->second->spec);
trans->Append(stmt);
}
if (itr->second->state == PLAYERSPELL_REMOVED)
{
delete itr->second;
m_talents[i]->erase(itr++);
}
else
{
itr->second->state = PLAYERSPELL_UNCHANGED;
++itr;
}
}
}
}
void Player::UpdateSpecCount(uint8 count)
{
uint32 curCount = GetSpecsCount();
if (curCount == count)
return;
if (m_activeSpec >= count)
ActivateSpec(0);
SQLTransaction trans = CharacterDatabase.BeginTransaction();
PreparedStatement* stmt = NULL;
// 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, GetGUIDLow());
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, m_activeSpec);
stmt->setUInt32(1, GetGUIDLow());
trans->Append(stmt);
m_activeSpec = 0;
}
CharacterDatabase.CommitTransaction(trans);
SetSpecsCount(count);
SendTalentsInfoData(false);
}
void Player::ActivateSpec(uint8 spec)
{
if (GetActiveSpec() == spec)
return;
if (spec > GetSpecsCount())
return;
if (IsNonMeleeSpellCasted(false))
InterruptNonMeleeSpells(false);
SQLTransaction 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);
ClearComboPointHolders();
ClearAllReactives();
UnsummonAllTotems();
ExitVehicle();
RemoveAllControlled();
/*RemoveAllAurasOnDeath();
if (GetPet())
GetPet()->RemoveAllAurasOnDeath();*/
//RemoveAllAuras(GetGUID(), NULL, 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->TalentTab);
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-existant talent ranks
if (talentInfo->RankID[rank] == 0)
continue;
removeSpell(talentInfo->RankID[rank], true); // removes the talent, and all dependant, learned, and chained spells..
if (const SpellInfo* _spellEntry = sSpellMgr->GetSpellInfo(talentInfo->RankID[rank]))
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) // search through the SpellInfo for valid trigger spells
if (_spellEntry->Effects[i].TriggerSpell > 0 && _spellEntry->Effects[i].Effect == SPELL_EFFECT_LEARN_SPELL)
removeSpell(_spellEntry->Effects[i].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 = m_Glyphs[m_activeSpec][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->TalentTab);
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-existant talent ranks
if (talentInfo->RankID[rank] == 0)
continue;
// if the talent can be found in the newly activated PlayerTalentMap
if (HasTalent(talentInfo->RankID[rank], m_activeSpec))
{
learnSpell(talentInfo->RankID[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 = m_Glyphs[m_activeSpec][slot];
// apply primary glyph
if (glyph)
if (GlyphPropertiesEntry const* gp = sGlyphPropertiesStore.LookupEntry(glyph))
CastSpell(this, gp->SpellId, true);
SetGlyph(slot, glyph);
}
m_usedTalentCount = spentTalents;
InitTalentForLevel();
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_ACTIONS_SPEC);
stmt->setUInt32(0, GetGUIDLow());
stmt->setUInt8(1, m_activeSpec);
if (PreparedQueryResult result = CharacterDatabase.Query(stmt))
_LoadActions(result);
}
SendActionButtons(1);
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);
}
void Player::ResetTimeSync()
{
m_timeSyncCounter = 0;
m_timeSyncTimer = 0;
m_timeSyncClient = 0;
m_timeSyncServer = getMSTime();
}
void Player::SendTimeSync()
{
WorldPacket data(SMSG_TIME_SYNC_REQ, 4);
data << uint32(m_timeSyncCounter++);
GetSession()->SendPacket(&data);
// Schedule next sync in 10 sec
m_timeSyncTimer = 10000;
m_timeSyncServer = getMSTime();
}
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 const& Player::GetGuildName()
{
return sGuildMgr->GetGuildById(GetGuildId())->GetName();
}
void Player::SendDuelCountdown(uint32 counter)
{
WorldPacket data(SMSG_DUEL_COUNTDOWN, 4);
data << uint32(counter); // seconds
GetSession()->SendPacket(&data);
}
void Player::AddRefundReference(uint32 it)
{
m_refundableItems.insert(it);
}
void Player::DeleteRefundReference(uint32 it)
{
std::set<uint32>::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->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_REFUNDABLE))
{
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "Item refund: item not refundable!");
return;
}
if (GetGUIDLow() != item->GetRefundRecipient()) // Formerly refundable item got traded
{
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "Item refund: item was traded!");
item->SetNotRefundable(this);
return;
}
ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(item->GetPaidExtendedCost());
if (!iece)
{
TC_LOG_DEBUG(LOG_FILTER_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 << uint64(item->GetGUID()); // item guid
data << uint32(item->GetPaidMoney()); // money cost
data << uint32(iece->reqhonorpoints); // honor point cost
data << uint32(iece->reqarenapoints); // arena point cost
for (uint8 i = 0; i < MAX_ITEM_EXTENDED_COST_REQUIREMENTS; ++i) // item cost data
{
data << uint32(iece->reqitem[i]);
data << uint32(iece->reqitemcount[i]);
}
data << uint32(0);
data << uint32(GetTotalPlayedTime() - item->GetPlayedTime());
GetSession()->SendPacket(&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, Item::GenerateItemRandomPropertyId(itemId));
if (item)
SendNewItem(item, count, true, false);
else
return false;
return true;
}
void Player::RefundItem(Item* item)
{
if (!item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_REFUNDABLE))
{
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "Item refund: item not refundable!");
return;
}
if (item->IsRefundExpired()) // item refund has expired
{
item->SetNotRefundable(this);
WorldPacket data(SMSG_ITEM_REFUND_RESULT, 8+4);
data << uint64(item->GetGUID()); // Guid
data << uint32(10); // Error!
GetSession()->SendPacket(&data);
return;
}
if (GetGUIDLow() != item->GetRefundRecipient()) // Formerly refundable item got traded
{
TC_LOG_DEBUG(LOG_FILTER_PLAYER_ITEMS, "Item refund: item was traded!");
item->SetNotRefundable(this);
return;
}
ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(item->GetPaidExtendedCost());
if (!iece)
{
TC_LOG_DEBUG(LOG_FILTER_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->reqitemcount[i];
uint32 itemid = iece->reqitem[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)
{
WorldPacket data(SMSG_ITEM_REFUND_RESULT, 8+4);
data << uint64(item->GetGUID()); // Guid
data << uint32(10); // Error!
GetSession()->SendPacket(&data);
return;
}
WorldPacket data(SMSG_ITEM_REFUND_RESULT, 8+4+4+4+4+4*4+4*4);
data << uint64(item->GetGUID()); // item guid
data << uint32(0); // 0, or error code
data << uint32(item->GetPaidMoney()); // money cost
data << uint32(iece->reqhonorpoints); // honor point cost
data << uint32(iece->reqarenapoints); // arena point cost
for (uint8 i = 0; i < MAX_ITEM_EXTENDED_COST_REQUIREMENTS; ++i) // item cost data
{
data << uint32(iece->reqitem[i]);
data << uint32(iece->reqitemcount[i]);
}
GetSession()->SendPacket(&data);
uint32 moneyRefund = item->GetPaidMoney(); // item-> will be invalidated in DestroyItem
// Save all relevant data to DB to prevent desynchronisation exploits
SQLTransaction 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->reqitemcount[i];
uint32 itemid = iece->reqitem[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->reqhonorpoints)
ModifyHonorPoints(honorRefund, &trans);
// Grant back Arena points
if (uint32 arenaRefund = iece->reqarenapoints)
ModifyArenaPoints(arenaRefund, &trans);
SaveInventoryAndGoldToDB(trans);
CharacterDatabase.CommitTransaction(trans);
}
void Player::SetRandomWinner(bool isWinner)
{
m_IsBGRandomWinner = isWinner;
if (m_IsBGRandomWinner)
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_BATTLEGROUND_RANDOM);
stmt->setUInt32(0, GetGUIDLow());
CharacterDatabase.Execute(stmt);
}
}
void Player::_LoadRandomBGStatus(PreparedQueryResult result)
{
//QueryResult result = CharacterDatabase.PQuery("SELECT guid FROM character_battleground_random WHERE guid = '%u'", GetGUIDLow());
if (result)
m_IsBGRandomWinner = true;
}
float Player::GetAverageItemLevel()
{
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::_LoadInstanceTimeRestrictions(PreparedQueryResult result)
{
if (!result)
return;
do
{
Field* fields = result->Fetch();
_instanceResetTimes.insert(InstanceTimeMap::value_type(fields[0].GetUInt32(), fields[1].GetUInt64()));
} while (result->NextRow());
}
void Player::_SaveInstanceTimeRestrictions(SQLTransaction& trans)
{
if (_instanceResetTimes.empty())
return;
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ACCOUNT_INSTANCE_LOCK_TIMES);
stmt->setUInt32(0, GetSession()->GetAccountId());
trans->Append(stmt);
for (InstanceTimeMap::const_iterator itr = _instanceResetTimes.begin(); itr != _instanceResetTimes.end(); ++itr)
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_ACCOUNT_INSTANCE_LOCK_TIMES);
stmt->setUInt32(0, GetSession()->GetAccountId());
stmt->setUInt32(1, itr->first);
stmt->setUInt64(2, itr->second);
trans->Append(stmt);
}
}
bool Player::IsInWhisperWhiteList(uint64 guid)
{
for (WhisperListContainer::const_iterator itr = WhisperList.begin(); itr != WhisperList.end(); ++itr)
if (*itr == guid)
return true;
return false;
}
bool Player::SetDisableGravity(bool disable, bool packetOnly /*= false*/)
{
if (!packetOnly && !Unit::SetDisableGravity(disable))
return false;
WorldPacket data(disable ? SMSG_MOVE_GRAVITY_DISABLE : SMSG_MOVE_GRAVITY_ENABLE, 12);
data.append(GetPackGUID());
data << uint32(0); //! movement counter
SendDirectMessage(&data);
data.Initialize(MSG_MOVE_GRAVITY_CHNG, 64);
data.append(GetPackGUID());
BuildMovementPacket(&data);
SendMessageToSet(&data, false);
return true;
}
bool Player::SetCanFly(bool apply)
{
if (!Unit::SetCanFly(apply))
return false;
WorldPacket data(apply ? SMSG_MOVE_SET_CAN_FLY : SMSG_MOVE_UNSET_CAN_FLY, 12);
data.append(GetPackGUID());
data << uint32(0); //! movement counter
SendDirectMessage(&data);
data.Initialize(MSG_MOVE_UPDATE_CAN_FLY, 64);
data.append(GetPackGUID());
BuildMovementPacket(&data);
SendMessageToSet(&data, false);
return true;
}
bool Player::SetHover(bool apply, bool packetOnly /*= false*/)
{
if (!packetOnly && !Unit::SetHover(apply))
return false;
WorldPacket data(apply ? SMSG_MOVE_SET_HOVER : SMSG_MOVE_UNSET_HOVER, 12);
data.append(GetPackGUID());
data << uint32(0); //! movement counter
SendDirectMessage(&data);
data.Initialize(MSG_MOVE_HOVER, 64);
data.append(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.append(GetPackGUID());
data << uint32(0); //! movement counter
SendDirectMessage(&data);
data.Initialize(MSG_MOVE_WATER_WALK, 64);
data.append(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.append(GetPackGUID());
data << uint32(0); //! movement counter
SendDirectMessage(&data);
data.Initialize(MSG_MOVE_FEATHER_FALL, 64);
data.append(GetPackGUID());
BuildMovementPacket(&data);
SendMessageToSet(&data, false);
return true;
}
float Player::GetCollisionHeight(bool mounted) const
{
if (mounted)
{
CreatureDisplayInfoEntry const* mountDisplayInfo = sCreatureDisplayInfoStore.LookupEntry(GetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID));
if (!mountDisplayInfo)
return GetCollisionHeight(false);
CreatureModelDataEntry const* mountModelData = sCreatureModelDataStore.LookupEntry(mountDisplayInfo->ModelId);
if (!mountModelData)
return GetCollisionHeight(false);
CreatureDisplayInfoEntry const* displayInfo = sCreatureDisplayInfoStore.LookupEntry(GetNativeDisplayId());
ASSERT(displayInfo);
CreatureModelDataEntry const* modelData = sCreatureModelDataStore.LookupEntry(displayInfo->ModelId);
ASSERT(modelData);
float scaleMod = GetObjectScale(); // 99% sure about this
return scaleMod * mountModelData->MountHeight + modelData->CollisionHeight * 0.5f;
}
else
{
//! Dismounting case - use basic default model data
CreatureDisplayInfoEntry const* displayInfo = sCreatureDisplayInfoStore.LookupEntry(GetNativeDisplayId());
ASSERT(displayInfo);
CreatureModelDataEntry const* modelData = sCreatureModelDataStore.LookupEntry(displayInfo->ModelId);
ASSERT(modelData);
return modelData->CollisionHeight;
}
}
std::string Player::GetMapAreaAndZoneString()
{
uint32 areaId = GetAreaId();
std::string areaName = "Unknown";
std::string zoneName = "Unknown";
if (AreaTableEntry const* area = GetAreaEntryByAreaID(areaId))
{
int locale = GetSession()->GetSessionDbcLocale();
areaName = area->area_name[locale];
if (AreaTableEntry const* zone = GetAreaEntryByAreaID(area->zone))
zoneName = zone->area_name[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()
{
std::ostringstream str;
str << Position::ToString() << " " << GetMapAreaAndZoneString();
return str.str();
}
Guild* Player::GetGuild()
{
uint32 guildId = GetGuildId();
return guildId ? sGuildMgr->GetGuildById(guildId) : NULL;
}
Pet* Player::SummonPet(uint32 entry, float x, float y, float z, float ang, PetType petType, uint32 duration)
{
Pet* pet = new Pet(this, petType);
if (petType == SUMMON_PET && pet->LoadPetFromDB(this, entry))
{
// 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);
return NULL;
}
// petentry == 0 for hunter "call pet" (current pet summoned if any)
if (!entry)
{
delete pet;
return NULL;
}
pet->Relocate(x, y, z, ang);
if (!pet->IsPositionValid())
{
TC_LOG_ERROR(LOG_FILTER_GENERAL, "Pet (guidlow %d, entry %d) not summoned. Suggested coordinates isn't valid (X: %f Y: %f)", pet->GetGUIDLow(), pet->GetEntry(), pet->GetPositionX(), pet->GetPositionY());
delete pet;
return NULL;
}
Map* map = GetMap();
uint32 pet_number = sObjectMgr->GeneratePetNumber();
if (!pet->Create(sObjectMgr->GenerateLowGuid(HIGHGUID_PET), map, GetPhaseMask(), entry, pet_number))
{
TC_LOG_ERROR(LOG_FILTER_GENERAL, "no such creature entry %u", entry);
delete pet;
return NULL;
}
pet->SetCreatorGUID(GetGUID());
pet->SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, getFaction());
pet->setPowerType(POWER_MANA);
pet->SetUInt32Value(UNIT_NPC_FLAGS, 0);
pet->SetUInt32Value(UNIT_FIELD_BYTES_1, 0);
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->SetUInt32Value(UNIT_FIELD_BYTES_0, 2048);
pet->SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, 0);
pet->SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, 1000);
pet->SetFullHealth();
pet->SetPower(POWER_MANA, pet->GetMaxPower(POWER_MANA));
pet->SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, uint32(time(NULL))); // cast can't be helped in this case
break;
default:
break;
}
map->AddToMap(pet->ToCreature());
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;
}
| [
"jespergmteam@gmail.com"
] | jespergmteam@gmail.com |
1958da5e8252fa963fb5942f29d75275a37d1f97 | 9dc52dd89f622258926731b371552597ad6af3b7 | /src/base58.h | 8191650af14b3000297881dc754c50b4c173a9d4 | [
"MIT"
] | permissive | ctlcoin/ctlcoin-source | e655219d0b43f3245d2dede282b85be4bb3b2359 | 44315165b3795b74001c5c71b2c61f5e87ae5569 | refs/heads/master | 2021-01-09T06:14:58.588471 | 2016-07-08T14:39:12 | 2016-07-08T14:39:12 | 62,895,501 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,012 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//
// Why base-58 instead of standard base-64 encoding?
// - Don't want 0OIl characters that look the same in some fonts and
// could be used to create visually identical looking account numbers.
// - A string with non-alphanumeric characters is not as easily accepted as an account number.
// - E-mail usually won't line-break if there's no punctuation to break at.
// - Double-clicking selects the whole number as one word if it's all alphanumeric.
//
#ifndef BITCOIN_BASE58_H
#define BITCOIN_BASE58_H
#include <string>
#include <vector>
#include "bignum.h"
#include "key.h"
#include "script.h"
#include "allocators.h"
static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
// Encode a byte sequence as a base58-encoded string
inline std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)
{
CAutoBN_CTX pctx;
CBigNum bn58 = 58;
CBigNum bn0 = 0;
// Convert big endian data to little endian
// Extra zero at the end make sure bignum will interpret as a positive number
std::vector<unsigned char> vchTmp(pend-pbegin+1, 0);
reverse_copy(pbegin, pend, vchTmp.begin());
// Convert little endian data to bignum
CBigNum bn;
bn.setvch(vchTmp);
// Convert bignum to std::string
std::string str;
// Expected size increase from base58 conversion is approximately 137%
// use 138% to be safe
str.reserve((pend - pbegin) * 138 / 100 + 1);
CBigNum dv;
CBigNum rem;
while (bn > bn0)
{
if (!BN_div(&dv, &rem, &bn, &bn58, pctx))
throw bignum_error("EncodeBase58 : BN_div failed");
bn = dv;
unsigned int c = rem.getulong();
str += pszBase58[c];
}
// Leading zeroes encoded as base58 zeros
for (const unsigned char* p = pbegin; p < pend && *p == 0; p++)
str += pszBase58[0];
// Convert little endian std::string to big endian
reverse(str.begin(), str.end());
return str;
}
// Encode a byte vector as a base58-encoded string
inline std::string EncodeBase58(const std::vector<unsigned char>& vch)
{
return EncodeBase58(&vch[0], &vch[0] + vch.size());
}
// Decode a base58-encoded string psz into byte vector vchRet
// returns true if decoding is successful
inline bool DecodeBase58(const char* psz, std::vector<unsigned char>& vchRet)
{
CAutoBN_CTX pctx;
vchRet.clear();
CBigNum bn58 = 58;
CBigNum bn = 0;
CBigNum bnChar;
while (isspace(*psz))
psz++;
// Convert big endian string to bignum
for (const char* p = psz; *p; p++)
{
const char* p1 = strchr(pszBase58, *p);
if (p1 == NULL)
{
while (isspace(*p))
p++;
if (*p != '\0')
return false;
break;
}
bnChar.setulong(p1 - pszBase58);
if (!BN_mul(&bn, &bn, &bn58, pctx))
throw bignum_error("DecodeBase58 : BN_mul failed");
bn += bnChar;
}
// Get bignum as little endian data
std::vector<unsigned char> vchTmp = bn.getvch();
// Trim off sign byte if present
if (vchTmp.size() >= 2 && vchTmp.end()[-1] == 0 && vchTmp.end()[-2] >= 0x80)
vchTmp.erase(vchTmp.end()-1);
// Restore leading zeros
int nLeadingZeros = 0;
for (const char* p = psz; *p == pszBase58[0]; p++)
nLeadingZeros++;
vchRet.assign(nLeadingZeros + vchTmp.size(), 0);
// Convert little endian data to big endian
reverse_copy(vchTmp.begin(), vchTmp.end(), vchRet.end() - vchTmp.size());
return true;
}
// Decode a base58-encoded string str into byte vector vchRet
// returns true if decoding is successful
inline bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58(str.c_str(), vchRet);
}
// Encode a byte vector to a base58-encoded string, including checksum
inline std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)
{
// add 4-byte hash check to the end
std::vector<unsigned char> vch(vchIn);
uint256 hash = Hash(vch.begin(), vch.end());
vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);
return EncodeBase58(vch);
}
// Decode a base58-encoded string psz that includes a checksum, into byte vector vchRet
// returns true if decoding is successful
inline bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)
{
if (!DecodeBase58(psz, vchRet))
return false;
if (vchRet.size() < 4)
{
vchRet.clear();
return false;
}
uint256 hash = Hash(vchRet.begin(), vchRet.end()-4);
if (memcmp(&hash, &vchRet.end()[-4], 4) != 0)
{
vchRet.clear();
return false;
}
vchRet.resize(vchRet.size()-4);
return true;
}
// Decode a base58-encoded string str that includes a checksum, into byte vector vchRet
// returns true if decoding is successful
inline bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58Check(str.c_str(), vchRet);
}
/** Base class for all base58-encoded data */
class CBase58Data
{
protected:
// the version byte
unsigned char nVersion;
// the actually encoded data
typedef std::vector<unsigned char, zero_after_free_allocator<unsigned char> > vector_uchar;
vector_uchar vchData;
CBase58Data()
{
nVersion = 0;
vchData.clear();
}
void SetData(int nVersionIn, const void* pdata, size_t nSize)
{
nVersion = nVersionIn;
vchData.resize(nSize);
if (!vchData.empty())
memcpy(&vchData[0], pdata, nSize);
}
void SetData(int nVersionIn, const unsigned char *pbegin, const unsigned char *pend)
{
SetData(nVersionIn, (void*)pbegin, pend - pbegin);
}
public:
bool SetString(const char* psz)
{
std::vector<unsigned char> vchTemp;
DecodeBase58Check(psz, vchTemp);
if (vchTemp.empty())
{
vchData.clear();
nVersion = 0;
return false;
}
nVersion = vchTemp[0];
vchData.resize(vchTemp.size() - 1);
if (!vchData.empty())
memcpy(&vchData[0], &vchTemp[1], vchData.size());
OPENSSL_cleanse(&vchTemp[0], vchData.size());
return true;
}
bool SetString(const std::string& str)
{
return SetString(str.c_str());
}
std::string ToString() const
{
std::vector<unsigned char> vch(1, nVersion);
vch.insert(vch.end(), vchData.begin(), vchData.end());
return EncodeBase58Check(vch);
}
int CompareTo(const CBase58Data& b58) const
{
if (nVersion < b58.nVersion) return -1;
if (nVersion > b58.nVersion) return 1;
if (vchData < b58.vchData) return -1;
if (vchData > b58.vchData) return 1;
return 0;
}
bool operator==(const CBase58Data& b58) const { return CompareTo(b58) == 0; }
bool operator<=(const CBase58Data& b58) const { return CompareTo(b58) <= 0; }
bool operator>=(const CBase58Data& b58) const { return CompareTo(b58) >= 0; }
bool operator< (const CBase58Data& b58) const { return CompareTo(b58) < 0; }
bool operator> (const CBase58Data& b58) const { return CompareTo(b58) > 0; }
};
/** base58-encoded Bitcoin addresses.
* Public-key-hash-addresses have version 0 (or 111 testnet).
* The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key.
* Script-hash-addresses have version 5 (or 196 testnet).
* The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script.
*/
class CBitcoinAddress;
class CBitcoinAddressVisitor : public boost::static_visitor<bool>
{
private:
CBitcoinAddress *addr;
public:
CBitcoinAddressVisitor(CBitcoinAddress *addrIn) : addr(addrIn) { }
bool operator()(const CKeyID &id) const;
bool operator()(const CScriptID &id) const;
bool operator()(const CNoDestination &no) const;
};
class CBitcoinAddress : public CBase58Data
{
public:
enum
{
PUBKEY_ADDRESS = 28, // ctlcoin addresses start with L
SCRIPT_ADDRESS = 5,
PUBKEY_ADDRESS_TEST = 111,
SCRIPT_ADDRESS_TEST = 196,
};
bool Set(const CKeyID &id) {
SetData(fTestNet ? PUBKEY_ADDRESS_TEST : PUBKEY_ADDRESS, &id, 20);
return true;
}
bool Set(const CScriptID &id) {
SetData(fTestNet ? SCRIPT_ADDRESS_TEST : SCRIPT_ADDRESS, &id, 20);
return true;
}
bool Set(const CTxDestination &dest)
{
return boost::apply_visitor(CBitcoinAddressVisitor(this), dest);
}
bool IsValid() const
{
unsigned int nExpectedSize = 20;
bool fExpectTestNet = false;
switch(nVersion)
{
case PUBKEY_ADDRESS:
nExpectedSize = 20; // Hash of public key
fExpectTestNet = false;
break;
case SCRIPT_ADDRESS:
nExpectedSize = 20; // Hash of CScript
fExpectTestNet = false;
break;
case PUBKEY_ADDRESS_TEST:
nExpectedSize = 20;
fExpectTestNet = true;
break;
case SCRIPT_ADDRESS_TEST:
nExpectedSize = 20;
fExpectTestNet = true;
break;
default:
return false;
}
return fExpectTestNet == fTestNet && vchData.size() == nExpectedSize;
}
CBitcoinAddress()
{
}
CBitcoinAddress(const CTxDestination &dest)
{
Set(dest);
}
CBitcoinAddress(const std::string& strAddress)
{
SetString(strAddress);
}
CBitcoinAddress(const char* pszAddress)
{
SetString(pszAddress);
}
CTxDestination Get() const {
if (!IsValid())
return CNoDestination();
switch (nVersion) {
case PUBKEY_ADDRESS:
case PUBKEY_ADDRESS_TEST: {
uint160 id;
memcpy(&id, &vchData[0], 20);
return CKeyID(id);
}
case SCRIPT_ADDRESS:
case SCRIPT_ADDRESS_TEST: {
uint160 id;
memcpy(&id, &vchData[0], 20);
return CScriptID(id);
}
}
return CNoDestination();
}
bool GetKeyID(CKeyID &keyID) const {
if (!IsValid())
return false;
switch (nVersion) {
case PUBKEY_ADDRESS:
case PUBKEY_ADDRESS_TEST: {
uint160 id;
memcpy(&id, &vchData[0], 20);
keyID = CKeyID(id);
return true;
}
default: return false;
}
}
bool IsScript() const {
if (!IsValid())
return false;
switch (nVersion) {
case SCRIPT_ADDRESS:
case SCRIPT_ADDRESS_TEST: {
return true;
}
default: return false;
}
}
};
bool inline CBitcoinAddressVisitor::operator()(const CKeyID &id) const { return addr->Set(id); }
bool inline CBitcoinAddressVisitor::operator()(const CScriptID &id) const { return addr->Set(id); }
bool inline CBitcoinAddressVisitor::operator()(const CNoDestination &id) const { return false; }
/** A base58-encoded secret key */
class CBitcoinSecret : public CBase58Data
{
public:
enum
{
PRIVKEY_ADDRESS = CBitcoinAddress::PUBKEY_ADDRESS + 128,
PRIVKEY_ADDRESS_TEST = CBitcoinAddress::PUBKEY_ADDRESS_TEST + 128,
};
void SetKey(const CKey& vchSecret)
{
assert(vchSecret.IsValid());
SetData(fTestNet ? PRIVKEY_ADDRESS_TEST : PRIVKEY_ADDRESS, vchSecret.begin(), vchSecret.size());
if (vchSecret.IsCompressed())
vchData.push_back(1);
}
CKey GetKey()
{
CKey ret;
ret.Set(&vchData[0], &vchData[32], vchData.size() > 32 && vchData[32] == 1);
return ret;
}
bool IsValid() const
{
bool fExpectTestNet = false;
switch(nVersion)
{
case PRIVKEY_ADDRESS:
break;
case PRIVKEY_ADDRESS_TEST:
fExpectTestNet = true;
break;
default:
return false;
}
return fExpectTestNet == fTestNet && (vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1));
}
bool SetString(const char* pszSecret)
{
return CBase58Data::SetString(pszSecret) && IsValid();
}
bool SetString(const std::string& strSecret)
{
return SetString(strSecret.c_str());
}
CBitcoinSecret(const CKey& vchSecret)
{
SetKey(vchSecret);
}
CBitcoinSecret()
{
}
};
#endif // BITCOIN_BASE58_H
| [
"abel808080@gmail.com"
] | abel808080@gmail.com |
87f4ea52660bcefa4c133738e54dd3340e90a21e | 5838cf8f133a62df151ed12a5f928a43c11772ed | /NT/multimedia/directx/dplay/dvoice/dxvoice/vnametbl.h | b92aff370acbb0d22de46da31246ddf4f54d6094 | [] | no_license | proaholic/Win2K3 | e5e17b2262f8a2e9590d3fd7a201da19771eb132 | 572f0250d5825e7b80920b6610c22c5b9baaa3aa | refs/heads/master | 2023-07-09T06:15:54.474432 | 2021-08-11T09:09:14 | 2021-08-11T09:09:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,143 | h | /*==========================================================================
*
* Copyright (C) 1999 - 1999 Microsoft Corporation. All Rights Reserved.
*
* File: vnametbl.h
* Content: Voice Name Table Routines
*
* History:
* Date By Reason
* ==== == ======
* 03/26/00 rodtoll Created
* 06/02/00 rodtoll Updated so host migration algorithm returns ID as well as order ID
* 06/21/2000 rodtoll Fixed bug in error handling (not yet encountered -- but good to fix).
* 07/01/2000 rodtoll Bug #38280 - DVMSGID_DELETEVOICEPLAYER messages are being sent in non-peer to peer sessions
* Nametable will now only unravel with messages if session is peer to peer.
* 07/09/2000 rodtoll Added signature bytes
* 08/28/2000 masonb Voice Merge: Changed classhash.h to classhashvc.h
* 04/09/2001 rodtoll WINBUG #364126 - DPVoice : Memory leak when Initializing 2 Voice Servers with same DPlay transport
* 02/28/2002 rodtoll WINBUG #549943 - SECURITY: DPVOICE: Possible corruption of voice server state
* - Addition of single operation return and delete operation to allow for protection against second
* spoofed delete player message from crashing the server.
*
***************************************************************************/
#ifndef __NAMETABLE_H
#define __NAMETABLE_H
#undef DPF_SUBCOMP
#define DPF_SUBCOMP DN_SUBCOMP_VOICE
#define VSIG_VOICENAMETABLE 'BTNV'
#define VSIG_VOICENAMETABLE_FREE 'BTN_'
#undef DPF_MODNAME
#define DPF_MODNAME "ClassHash_Hash"
inline DWORD_PTR ClassHash_Hash( const DVID &dvidKey, UINT_PTR HashBitCount )
{
DWORD_PTR hashResult;
hashResult = dvidKey;
// Clear upper bits
hashResult <<= ((sizeof(DWORD_PTR)*8)-HashBitCount);
// Restore value
hashResult >>= ((sizeof(DWORD_PTR)*8)-HashBitCount);
return hashResult;
}
#define VOICE_NAMETABLE_START_BITDEPTH 6
#define VOICE_NAMETABLE_GROW_BITDEPTH 2
volatile class CVoiceNameTable
{
public:
#undef DPF_MODNAME
#define DPF_MODNAME "CVoiceNameTable::CVoiceNameTable"
CVoiceNameTable( )
{
m_dwSignature = VSIG_VOICENAMETABLE;
m_fInitialized = FALSE;
};
#undef DPF_MODNAME
#define DPF_MODNAME "CVoiceNameTable::~CVoiceNameTable"
~CVoiceNameTable()
{
DeInitialize(FALSE, NULL, NULL);
m_dwSignature = VSIG_VOICENAMETABLE_FREE;
}
HRESULT DeInitialize(BOOL fUnRavel, PVOID pvContext, LPDVMESSAGEHANDLER pvMessageHandler);
#undef DPF_MODNAME
#define DPF_MODNAME "CVoiceNameTable::Initialize"
inline HRESULT Initialize()
{
BOOL fResult;
if (!DNInitializeCriticalSection( &m_csTableLock ))
{
return DVERR_OUTOFMEMORY;
}
fResult = m_nameTable.Initialize( VOICE_NAMETABLE_START_BITDEPTH, VOICE_NAMETABLE_GROW_BITDEPTH );
if( !fResult )
{
DPFX(DPFPREP, 0, "Failed to initialize hash table" );
DNDeleteCriticalSection( &m_csTableLock );
return DVERR_GENERIC;
}
m_fInitialized = TRUE;
return DV_OK;
};
DWORD GetLowestHostOrderID(DVID *pdvidHost);
#undef DPF_MODNAME
#define DPF_MODNAME "CVoiceNameTable::IsEntry"
BOOL IsEntry( const DVID dvidID )
{
BOOL fResult;
CVoicePlayer *pEntry;
Lock();
fResult = m_nameTable.Find( dvidID, &pEntry );
UnLock();
return fResult;
}
#undef DPF_MODNAME
#define DPF_MODNAME "CVoiceNameTable::GetEntry"
inline HRESULT GetEntry( const DVID dvidID, CVoicePlayer **ppEntry, BOOL fAddReference )
{
BOOL fFound;
Lock();
fFound = m_nameTable.Find( dvidID, ppEntry );
if( !fFound )
{
*ppEntry = NULL;
UnLock();
return DVERR_INVALIDPLAYER;
}
DNASSERT( *ppEntry != NULL );
if( fAddReference )
{
(*ppEntry)->AddRef();
}
UnLock();
return DV_OK;
}
#undef DPF_MODNAME
#define DPF_MODNAME "CVoiceNameTable::AddEntry"
inline HRESULT AddEntry( const DVID dvidID, CVoicePlayer *pEntry )
{
BOOL fFound;
CVoicePlayer *pTmpEntry;
Lock();
fFound = m_nameTable.Find( dvidID, &pTmpEntry );
if( fFound )
{
UnLock();
return DVERR_GENERIC;
}
pEntry->AddRef();
fFound = m_nameTable.Insert( dvidID, pEntry );
if( !fFound )
{
pEntry->Release();
UnLock();
return DVERR_GENERIC;
}
UnLock();
return DV_OK;
}
#undef DPF_MODNAME
#define DPF_MODNAME "CVoiceNameTable::DeleteAndReturnEntry"
//
// This function removes and returns a record from the nametable, if one exists.
// The player object returned will have the nametable's reference on the player
// so the calling function MUST call release on the object to see it destroyed.
//
// After this function returns the player will no longer be available.
//
inline HRESULT DeleteAndReturnEntry( const DVID dvidID, CVoicePlayer **pTarget )
{
BOOL fFound;
CVoicePlayer *pTmpEntry;
Lock();
fFound = m_nameTable.Find( dvidID, &pTmpEntry );
if( !fFound )
{
UnLock();
return DVERR_GENERIC;
}
if( pTmpEntry == NULL )
{
DNASSERT( FALSE );
UnLock();
return DVERR_GENERIC;
}
m_nameTable.Remove( dvidID );
// Returning the object from the table, no release
// called therefore giving the reference to the caller.
*pTarget = pTmpEntry;
UnLock();
return DV_OK;
}
#undef DPF_MODNAME
#define DPF_MODNAME "CVoiceNameTable::DeleteEntry"
inline HRESULT DeleteEntry( const DVID dvidID )
{
BOOL fFound;
CVoicePlayer *pTmpEntry;
Lock();
fFound = m_nameTable.Find( dvidID, &pTmpEntry );
if( !fFound )
{
UnLock();
return DVERR_GENERIC;
}
m_nameTable.Remove( dvidID );
DNASSERT( pTmpEntry != NULL );
// Regardless of if it was found..
// Drop the reference count
pTmpEntry->Release();
if( !fFound )
{
UnLock();
return DVERR_GENERIC;
}
UnLock();
return DV_OK;
}
#undef DPF_MODNAME
#define DPF_MODNAME "CVoiceNameTable::Lock"
inline void Lock()
{
DNEnterCriticalSection( &m_csTableLock );
}
#undef DPF_MODNAME
#define DPF_MODNAME "CVoiceNameTable::UnLock"
inline void UnLock()
{
DNLeaveCriticalSection( &m_csTableLock );
}
protected:
DWORD m_dwSignature;
CClassHash<CVoicePlayer,DVID> m_nameTable;
DNCRITICAL_SECTION m_csTableLock;
BOOL m_fInitialized;
};
#undef DPF_MODNAME
#endif
| [
"blindtiger@foxmail.com"
] | blindtiger@foxmail.com |
3c04e7d2321110e44d7cfb5075d79ff5cd4151d8 | dd80a584130ef1a0333429ba76c1cee0eb40df73 | /external/chromium_org/skia/ext/lazy_pixel_ref.cc | ef74089f3e7b847a242af6178f3217e68dc50530 | [
"MIT",
"BSD-3-Clause"
] | permissive | karunmatharu/Android-4.4-Pay-by-Data | 466f4e169ede13c5835424c78e8c30ce58f885c1 | fcb778e92d4aad525ef7a995660580f948d40bc9 | refs/heads/master | 2021-03-24T13:33:01.721868 | 2017-02-18T17:48:49 | 2017-02-18T17:48:49 | 81,847,777 | 0 | 2 | MIT | 2020-03-09T00:02:12 | 2017-02-13T16:47:00 | null | UTF-8 | C++ | false | false | 507 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "skia/ext/lazy_pixel_ref.h"
namespace skia {
#ifdef SK_SUPPORT_LEGACY_PIXELREF_CONSTRUCTOR
// DEPRECATED -- will remove after blink updates to pass info
LazyPixelRef::LazyPixelRef() {
}
#endif
LazyPixelRef::LazyPixelRef(const SkImageInfo& info) : SkPixelRef(info) {
}
LazyPixelRef::~LazyPixelRef() {
}
} // namespace skia
| [
"karun.matharu@gmail.com"
] | karun.matharu@gmail.com |
f622e562eacd1e61382633c6e11cae42f4d3310a | 25ce2121f847c95ffaa89ae0e36ab4dadabceef2 | /Lab1/Lab1/Shape.h | ce8770a6cc48e76eb7f6c81998778f8b1fa91e3d | [] | no_license | JokerSSmile/KPO | 325ec87c25f1325513aeba7d73a766595b8ce022 | af7b9beb118892e634b68cf165ca23fb82e8019b | refs/heads/master | 2021-01-22T03:49:22.375348 | 2017-05-25T20:55:51 | 2017-05-25T20:55:51 | 81,463,574 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 171 | h | #pragma once
class IShape
{
public:
IShape() = default;
virtual ~IShape() = default;
virtual double GetPerimeter() const = 0;
virtual double GetArea() const = 0;
};
| [
"patrushev1996@gmail.com"
] | patrushev1996@gmail.com |
f364791b9683ea97a30d0bcafb041452b7942b21 | f1b8411098ee7932cc52aaaf190b93e8e2799741 | /source/scene/nckCamera.cpp | 18a11f2b748242180f6de41161ce70b8ccbba6db | [
"MIT"
] | permissive | jae686/nctoolkit | 19f66d5560449e36bf077dcf27465a50ce5ebdc0 | 88509e1b9dd26999c6cf44eb316aa033ae3e7af8 | refs/heads/master | 2021-01-16T22:14:48.744101 | 2016-01-26T22:49:15 | 2016-01-26T22:49:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,702 | cpp |
/**
* NCtoolKit © 2007-2015 Luís F.Loureiro, under zlib software license.
* https://github.com/nczeroshift/nctoolkit
*/
#include "nckCamera.h"
#include "nckUtils.h"
_SCENE_BEGIN
Camera::Camera(Graph::Device *dev) : Datablock(dev){
m_Object = NULL;
m_Aspect = 4.0f/3.0f;
m_Start = 1.0f;
m_End = 100.0f;
m_Fov = 36.0f;
}
Camera::~Camera(){
}
float Camera::GetFov(){
return m_Fov;
}
void Camera::SetFov(float fFov){
m_Fov = fFov;
}
void Camera::SetStart(float value){
m_Start = value;
}
float Camera::GetStart(){
return m_Start;
}
void Camera::SetEnd(float value){
m_End = value;
}
float Camera::GetEnd(){
return m_End;
}
void Camera::SetAspect(float value){
m_Aspect = value;
}
float Camera::GetAspect(){
return m_Aspect;
}
void Camera::Enable(Graph::MatrixType mat)
{
if(mat == Graph::MATRIX_PROJECTION)
{
m_Device->Perspective(m_Aspect,m_Fov,m_Start,m_End);
}
else if(mat == Graph::MATRIX_VIEW && m_Object)
{
Math::Quat q = -m_Object->GetRotation();
m_Device->Quaternion(q.GetX(),q.GetY(),q.GetZ(),q.GetW());
m_Device->Translate(-m_Object->GetPosition().GetX(),
-m_Object->GetPosition().GetY(),
-m_Object->GetPosition().GetZ());
}
}
Math::Mat44 Camera::GetMatrix()
{
Math::Mat44 mat = Math::Rotate( -m_Object->GetRotation() ) *
Math::Translate(-m_Object->GetPosition());
return mat;
}
void Camera::SetObject(Object *obj)
{
m_Object = obj;
}
Object *Camera::GetObject()
{
return m_Object;
}
void Camera::Read(Core::DataReader *f)
{
f->Read(&m_Name);
f->Read(&m_Fov,sizeof(float));
f->Read(&m_Start,sizeof(float));
f->Read(&m_End,sizeof(float));
char hasAction = 0x0;
f->Read(&hasAction,sizeof(char));
}
#ifdef NCK_BXON
void Camera::Read(BXON::Map * entry){
m_Name = entry->GetString("name");
m_Fov = entry->GetFloat("fov");
m_Start = entry->GetFloat("start");
m_End = entry->GetFloat("end");
}
#endif
DatablockType Camera::GetType()
{
return DATABLOCK_CAMERA;
}
void Camera::RenderViewportContour()
{
int vp[4];
m_Device->GetProperty(Graph::PROPERTY_VIEWPORT,vp);
m_Device->Begin(Graph::PRIMITIVE_LINES);
m_Device->Vertex(0.1f*vp[2],0.1f*vp[3]);
m_Device->Vertex(0.9f*vp[2],0.1f*vp[3]);
m_Device->Vertex(0.1f*vp[2],0.1f*vp[3]);
m_Device->Vertex(0.1f*vp[2],0.9f*vp[3]);
m_Device->Vertex(0.9f*vp[2],0.9f*vp[3]);
m_Device->Vertex(0.1f*vp[2],0.9f*vp[3]);
m_Device->Vertex(0.9f*vp[2],0.9f*vp[3]);
m_Device->Vertex(0.9f*vp[2],0.1f*vp[3]);
m_Device->End();
}
_SCENE_END
| [
"nczeroshift.dev@gmail.com"
] | nczeroshift.dev@gmail.com |
6eea6e515dd559b44d418a66099a7dc09684c986 | aa2c9edcdd4be2c3f0aaa641378cee8dabd75842 | /chp7drill/calculator08buggy.cpp | 447d7c3bb2d27c589e47be9767900ba3b4e759c2 | [] | no_license | asztalosattila007/bevprog | 46cbf73767c0407d06b33ca57596eae5423c75a0 | 8b13194926972a8d5b58d490be1c8dd18e7ea6e4 | refs/heads/master | 2023-01-23T19:30:34.421406 | 2020-12-01T21:50:51 | 2020-12-01T21:50:51 | 296,564,546 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,594 | cpp | /*
calculator08buggy.cpp
Helpful comments removed.
We have inserted 3 bugs that the compiler will catch and 3 that it won't.
*/
#include "std_lib_facilities.h"
constexpr char number = '8'; //szimbolikus állandó a számhoz
constexpr char let = 'L';
constexpr char quit = 'Q'; //szimbolikus állandó a kilépéshez (szimbolikus állandó előnye hogy csak egy helyen kell módosítani)
constexpr char print = ';';
constexpr char name = 'a';
const string declkey = "let";
constexpr string sqrtkey = "sqrt";
constexpr char square_root = '@';
const char prompt = ">";
const char result = "=";
//const string quitkey = "quit";
double expression(); //az expression prototípusa (mivel a primary után lett deklarálva)
bool is_declared();
class Token {
public:
char kind; //típus
double value; //érték
string name; //név
Token(): kind(0) {} //alapértelmezett konstruktor (nem kötelező)
Token(char ch) :kind(ch), value(0) { } //konstuktor függvények
Token(char ch, double val) :kind(ch), value(val) { }
Token(char ch, string s) :kind(ch), name(s) { }
};
class Token_stream {
public: //publikus rész
Token_stream() :full(0), buffer(0) { }
Token get();
void putback(Token t); //A tokent visszateszi a streambe későbbi használatra
void ignore(char c); //megadjuk hogy melyik karakterig töröljük a token_stream-ben a kifejezéseket
private: //privát rész(implementációhoz kell)
bool full; //nyílvántartjuk vele hogy van bufferban valami
Token buffer; // buffer :1 tokent bele tudunk tenni
};
Token_stream::Token_stream()
:full(false), buffer(0) // Token stream definiálása(Token_stream függv Token_stream osztályon belül definiáljuk)
{
}
void Token_stream::putback(Token t)
{
if (full) error("putback() into a full buffer"); //ha a stream tele van: error
buffer = t; // copy t to buffer
full = true; //jelezzük vele hogy a buffer megtelt
}
Token Token_stream::get() // Token stream get függvénye
{
if (full) { full = false; return buffer; } //ha van a bufferben egy token akkor azt adja vissza. Mielőtt visszadjuk a full-t falsera állítjuk
char ch;
cin >> ch; //itt olvassa be
switch (ch) { //esetek beolvasáskor.
case quit:
case '(':
case ')':
case '+':
case '-':
case '*':
case '/':
case '%':
case print:
case '=':
return Token(ch); //token a ch operátorral : meg fog jelenni a kind-ban és a t.kind-ot így lehet leképezni.
case '.':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{ cin.putback(ch); //a karaktereket visszatesszük a standard inputba
double val = 0; //számok esetén
cin >> val;
return Token(number, val); //szám típusú token az értéket visszaadja (a primary függvénynél kell)
}
default:
if (isalpha(ch)) { //isalpha igazzal tér vissza ha a kapott paraméter betü
string s;
s += ch; //a string s-hez hozzácsatoljuk a karaktert
while (cin.get(ch) && (isalpha(ch) || isdigit(ch))) s += ch; //amíg betü vagy szám (nem lehet spéci karakter pl:#)
cin.putback(ch);
if (s == declkey) return Token{let}; //Let tipusú tokennel tér vissza amit a statementben vizsgál
//if (s == quitkey) return Token(quit);
else if(s == sqrtkey) return Token{square_root};
else if (is_declared(s))
return Token(number, get_value(s));
return Token{name, s};
}
error("Bad token"); //egyéb esetben bad token errort ír ki
}
}
void Token_stream::ignore(char c) //hiba esetén törli a karaktereket és a buffereket így újra tudunk próbálkozni
{
if (full && c == buffer.kind) { //ha tele van a buffer és pontosvessző van a bufferban
full = false; // full hamis lesz (buffer nem lesz tele)
return;
}
full = false; //buffer ürítés
char ch;
while (cin >> ch) //karakterenként olvassa a bemenetet
if (ch == c) return; //ha az a karakter amit keresünk (a ';') akkor visszatér a calculate()-hez
}
class Variable { //változó
string name; //neve
double value; //értéke
Variable(string n, double v) :name(n), value(v) { }
};
vector<Variable> names; //változókat tároló vektor var_table
double define_name(string var, double val){ //név definiálása (változó név,érték)
if(is_declared(var)) error("Variable is declared: ", var); //megnézi hogy ezen a néven van e változó deklarálva, ha van, akkor error
names.push_back(Variable{var,val}); //ha nincs akkor beleteszi a Variable vektor végébe
return val;
}
double get_value(string s) //egy változó értékét kérjük el
{
for (int i = 0; i < names.size(); ++i) //for (const auto& v : names -t is lehet használni)
if (names[i].name == s) return names[i].value; //if (v.name == s) return v.value
error("get: undefined name ", s);
}
void set_value(string s, double d) //beállítjuk a változó értéket,
{
for (int i = 0; i <= names.size(); ++i) //for (auto& v: names)
if (names[i].name == s) { // if (v.name == s){ v.value = d; return;}
names[i].value = d;
return;
}
error("set: undefined name ", s);
}
bool is_declared(string var) //változónak átadunk egy nevet
{
for (int i = 0; i < names.size(); ++i) //végig megy a vektoron. for(const auto& v: names) is jó.
if (names[i].name == var) return true; // ha találunk olyan nevet, ami ugyanaz,amit keresünk, akkor igaz.
return false;
}
Token_stream ts; // globális változó (ha kell egy token token_stream-től kell bekérni)
double calc_sqrt(){
char ch;
if(cin.get(ch) && ch != '(') error (" '(' expected");
cin.putback(ch);
double d = expression();
if(d < 0) error("sqrt: negative value");
return sqrt(d);
}
double primary()
{
Token t = ts.get(); //a ts.get olvas be
switch (t.kind) { //milyen tipusa van a tokennek
case '(': // '(' kifejezés ')'
{ double d = expression();
t = ts.get();
if (t.kind != ')') error("')' expected"); // ha nem ')'-t írunk errort írki
return d;
}
case '-': //negatív számok esete: - jelet írunk a szám elé.
return - primary();
case '+': //ha + jelet írunk a szám elé
return primary();
case number:
return t.value;
case square_root: //
return calc_sqrt();
//case name:
//return get_value(t.name);
default:
error("primary expected");
return 0;
}
}
double term() //szorzás osztás
{
double left = primary();
while (true) {
Token t = ts.get();
switch (t.kind) {
case '*':
left *= primary();
t = ts.get();
break;
case '/':
{ double d = primary();
if (d == 0) error("divide by zero");
left /= d;
t = ts.get();
break;
}
case '%': // opcionális
{
double d = primary();
if (d == 0) error("%: zero divider"); // ha nullát írunk a moduló jel(%) után.
left = fmod (left, d); // fmod függvény segítségével lehet törtekkel használni a modulót
t = ts.get();
}
default:
ts.putback(t); //ha nem szorzás(*) vagy osztás(/) akkor visszateszi a tokent a tokenstream-be
return left;
}
}
}
double expression() //összeadás és kivonás
{
double left = term();
while (true) {
Token t = ts.get();
switch (t.kind) {
case '+':
left += term();
t = ts.get();
break;
case '-':
left -= term();
t = ts.get();
break;
default:
ts.putback(t); //ha nem összeadás(+) vagy kivonás(-) akkor azt a tokent visszateszi a tokenstream-be
return left;
}
}
}
double declaration()
{
Token t = ts.get();
if (t.kind != name) error("name expected in declaration"); //ha a token típusa nem név (pl:let 2 = 4;)
string name = t.name;
if (is_declared(name)) error(name, " declared twice");
Token t2 = ts.get(); // Itt ellenőriizzük,hogy egyenlőségjel jön-e utána.
if (t2.kind != '=') error("= missing in declaration of ", name);
double d = expression(); //változó értéke
define_name(name, d); //define_name nélkül: names.push_back(Variable(name, d)); A változó elkészítése(neve,értéke)
return d;
}
double statement() //itt döntjük el hogy "let" jön vagy expression
{
Token t = ts.get();
switch (t.kind) {
case let: //kulcsszó -e a let?
return declaration(); // let esetén visszatér a declaration fv-hez
default:
ts.putback(t); // Vissza teszi a tokent (amit a Token t = ts.get() kivett) ha nem declaration
return expression(); //expression fv-t hívja
}
}
void clean_up_mess()
{
ts.ignore(print); // ';'-ig ignorálja a kifejezést
}
void calculate()
{
while (true) try {
cout << prompt;
Token t = ts.get();
while (t.kind == print) t = ts.get(); //addig kérjük a következő tokent amíg a printhez nem jutunk.
if (t.kind == quit) return; //ha a token kilépés akkor visszatér a main() függvényhez (végzett a calculate-el)
ts.putback(t);
cout << result << statement() << endl;
}
catch (exception& e) {
cerr << e.what() << endl;
clean_up_mess(); //ez a függvény törli a rossz kifejezéseket amelyeket a token_streamben az ignore() választ ki.
}
}
int main() //eredmény kiíratás
try {
calculate(); //calculate függvényben a kiíratás és kilépés
return 0;
}
catch (exception& e) {
cerr << "exception: " << e.what() << endl;
char c;
while (cin >> c && c != ';');
return 1;
}
catch (...) {
cerr << "exception\n";
char c;
while (cin >> c && c != ';');
return 2;
} | [
"asztalosattila007@gmail.com"
] | asztalosattila007@gmail.com |
67fb91b0e8665896fe7cf07a79bef15f6862f42b | 1806a340ec0e78ceae9bfead8bab37800a5e4765 | /tesseract-2.04/ccmain/reject.cpp | 7ed84202ca324735a9c7e6efab26901857532b6c | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | jkrall/ocropus | 6fc862eb43d62f80529c14283ffbece26c8e71d8 | ac3cf67b7df925813b4c01dc7c02acda19c72775 | refs/heads/master | 2016-09-05T13:59:16.046621 | 2010-03-27T08:56:32 | 2010-03-27T08:56:32 | 581,605 | 13 | 11 | null | null | null | null | UTF-8 | C++ | false | false | 59,146 | cpp | /**********************************************************************
* File: reject.cpp (Formerly reject.c)
* Description: Rejection functions used in tessedit
* Author: Phil Cheatle
* Created: Wed Sep 23 16:50:21 BST 1992
*
* (C) Copyright 1992, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#include "mfcpch.h"
#include "tessvars.h"
#ifdef __UNIX__
#include <assert.h>
#include <errno.h>
#endif
#include "scanutils.h"
#include <ctype.h>
#include <string.h>
//#include "tessbox.h"
#include "memry.h"
#include "reject.h"
#include "tfacep.h"
#include "mainblk.h"
#include "charcut.h"
#include "imgs.h"
#include "scaleimg.h"
#include "control.h"
#include "docqual.h"
#include "secname.h"
#include "globals.h"
/* #define SECURE_NAMES done in secnames.h when necessary */
//extern "C" {
#include "callnet.h"
//}
#include "notdll.h"
CLISTIZEH (STRING) CLISTIZE (STRING)
#define EXTERN
EXTERN
INT_VAR (tessedit_reject_mode, 0, "Rejection algorithm");
EXTERN
INT_VAR (tessedit_ok_mode, 5, "Acceptance decision algorithm");
EXTERN
BOOL_VAR (tessedit_use_nn, FALSE, "");
EXTERN
BOOL_VAR (tessedit_rejection_debug, FALSE, "Adaption debug");
EXTERN
BOOL_VAR (tessedit_rejection_stats, FALSE, "Show NN stats");
EXTERN
BOOL_VAR (tessedit_flip_0O, TRUE, "Contextual 0O O0 flips");
EXTERN
double_VAR (tessedit_lower_flip_hyphen, 1.5,
"Aspect ratio dot/hyphen test");
EXTERN
double_VAR (tessedit_upper_flip_hyphen, 1.8,
"Aspect ratio dot/hyphen test");
EXTERN
BOOL_VAR (rej_trust_doc_dawg, FALSE,
"Use DOC dawg in 11l conf. detector");
EXTERN
BOOL_VAR (rej_1Il_use_dict_word, FALSE, "Use dictword test");
EXTERN
BOOL_VAR (rej_1Il_trust_permuter_type, TRUE, "Dont double check");
EXTERN
BOOL_VAR (one_ell_conflict_default, TRUE, "one_ell_conflict default");
EXTERN
BOOL_VAR (show_char_clipping, FALSE, "Show clip image window?");
EXTERN
BOOL_VAR (nn_debug, FALSE, "NN DEBUGGING?");
EXTERN
BOOL_VAR (nn_reject_debug, FALSE, "NN DEBUG each char?");
EXTERN
BOOL_VAR (nn_lax, FALSE, "Use 2nd rate matches");
EXTERN
BOOL_VAR (nn_double_check_dict, FALSE, "Double check");
EXTERN
BOOL_VAR (nn_conf_double_check_dict, TRUE,
"Double check for confusions");
EXTERN
BOOL_VAR (nn_conf_1Il, TRUE, "NN use 1Il conflicts");
EXTERN
BOOL_VAR (nn_conf_Ss, TRUE, "NN use Ss conflicts");
EXTERN
BOOL_VAR (nn_conf_hyphen, TRUE, "NN hyphen conflicts");
EXTERN
BOOL_VAR (nn_conf_test_good_qual, FALSE, "NN dodgy 1Il cross check");
EXTERN
BOOL_VAR (nn_conf_test_dict, TRUE, "NN dodgy 1Il cross check");
EXTERN
BOOL_VAR (nn_conf_test_sensible, TRUE, "NN dodgy 1Il cross check");
EXTERN
BOOL_VAR (nn_conf_strict_on_dodgy_chs, TRUE,
"Require stronger NN match");
EXTERN
double_VAR (nn_dodgy_char_threshold, 0.99, "min accept score");
EXTERN
INT_VAR (nn_conf_accept_level, 4, "NN accept dodgy 1Il matches? ");
EXTERN
INT_VAR (nn_conf_initial_i_level, 3,
"NN accept initial Ii match level ");
EXTERN
BOOL_VAR (no_unrej_dubious_chars, TRUE, "Dubious chars next to reject?");
EXTERN
BOOL_VAR (no_unrej_no_alphanum_wds, TRUE, "Stop unrej of non A/N wds?");
EXTERN
BOOL_VAR (no_unrej_1Il, FALSE, "Stop unrej of 1Ilchars?");
EXTERN
BOOL_VAR (rej_use_tess_accepted, TRUE, "Individual rejection control");
EXTERN
BOOL_VAR (rej_use_tess_blanks, TRUE, "Individual rejection control");
EXTERN
BOOL_VAR (rej_use_good_perm, TRUE, "Individual rejection control");
EXTERN
BOOL_VAR (rej_use_sensible_wd, FALSE, "Extend permuter check");
EXTERN
BOOL_VAR (rej_alphas_in_number_perm, FALSE, "Extend permuter check");
EXTERN
double_VAR (rej_whole_of_mostly_reject_word_fract, 0.85,
"if >this fract");
EXTERN
INT_VAR (rej_mostly_reject_mode, 1,
"0-never, 1-afterNN, 2-after new xht");
EXTERN
double_VAR (tessed_fullstop_aspect_ratio, 1.2,
"if >this fract then reject");
EXTERN
INT_VAR (net_image_width, 40, "NN input image width");
EXTERN
INT_VAR (net_image_height, 36, "NN input image height");
EXTERN
INT_VAR (net_image_x_height, 22, "NN input image x_height");
EXTERN
INT_VAR (tessedit_image_border, 2, "Rej blbs near image edge limit");
/*
Net input is assumed to have (net_image_width * net_image_height) input
units of image pixels, followed by 0, 1, or N units representing the
baseline position. 0 implies no baseline information. 1 implies a floating
point value. N implies a "guage" of N units. For any char an initial set
of these are ON, the remainder OFF to indicate the "level" of the
baseline.
HOWEVER!!! NOTE THAT EACH NEW INPUT LAYER FORMAT EXPECTS TO BE RUN WITH A
DIFFERENT tessed/netmatch/nmatch.c MODULE. - These are classic C modules
generated by aspirin with HARD CODED CONSTANTS
*/
EXTERN
INT_VAR (net_bl_nodes, 20, "Number of baseline nodes");
EXTERN
double_VAR (nn_reject_threshold, 0.5, "NN min accept score");
EXTERN
double_VAR (nn_reject_head_and_shoulders, 0.6, "top scores sep factor");
/* NOTE - ctoh doesn't handle "=" properly, hence \075 */
EXTERN
STRING_VAR (ok_single_ch_non_alphanum_wds, "-?\075",
"Allow NN to unrej");
EXTERN
STRING_VAR (ok_repeated_ch_non_alphanum_wds, "-?*\075",
"Allow NN to unrej");
EXTERN
STRING_VAR (conflict_set_I_l_1, "Il1[]", "Il1 conflict set");
EXTERN
STRING_VAR (conflict_set_S_s, "Ss$", "Ss conflict set");
EXTERN
STRING_VAR (conflict_set_hyphen, "-_~", "hyphen conflict set");
EXTERN
STRING_VAR (dubious_chars_left_of_reject, "!'+`()-./\\<>;:^_,~\"",
"Unreliable chars");
EXTERN
STRING_VAR (dubious_chars_right_of_reject, "!'+`()-./\\<>;:^_,~\"",
"Unreliable chars");
EXTERN
INT_VAR (min_sane_x_ht_pixels, 8, "Reject any x-ht lt or eq than this");
/*************************************************************************
* set_done()
*
* Set the done flag based on the word acceptability criteria
*************************************************************************/
void set_done( //set done flag
WERD_RES *word,
inT16 pass) {
/*
0: Original heuristic used in Tesseract and Ray's prototype Resaljet
*/
if (tessedit_ok_mode == 0) {
/* NOTE - done even if word contains some or all spaces !!! */
word->done = word->tess_accepted;
}
/*
1: Reject words containing blanks and on pass 1 reject I/l/1 conflicts
*/
else if (tessedit_ok_mode == 1) {
word->done = word->tess_accepted &&
(strchr (word->best_choice->string ().string (), ' ') == NULL);
if (word->done && (pass == 1) && one_ell_conflict (word, FALSE))
word->done = FALSE;
}
/*
2: as 1 + only accept dict words or numerics in pass 1
*/
else if (tessedit_ok_mode == 2) {
word->done = word->tess_accepted &&
(strchr (word->best_choice->string ().string (), ' ') == NULL);
if (word->done && (pass == 1) && one_ell_conflict (word, FALSE))
word->done = FALSE;
if (word->done &&
(pass == 1) &&
(word->best_choice->permuter () != SYSTEM_DAWG_PERM) &&
(word->best_choice->permuter () != FREQ_DAWG_PERM) &&
(word->best_choice->permuter () != USER_DAWG_PERM) &&
(word->best_choice->permuter () != NUMBER_PERM)) {
#ifndef SECURE_NAMES
if (tessedit_rejection_debug)
tprintf ("\nVETO Tess accepting poor word \"%s\"\n",
word->best_choice->string ().string ());
#endif
word->done = FALSE;
}
}
/*
3: as 2 + only accept dict words or numerics in pass 2 as well
*/
else if (tessedit_ok_mode == 3) {
word->done = word->tess_accepted &&
(strchr (word->best_choice->string ().string (), ' ') == NULL);
if (word->done && (pass == 1) && one_ell_conflict (word, FALSE))
word->done = FALSE;
if (word->done &&
(word->best_choice->permuter () != SYSTEM_DAWG_PERM) &&
(word->best_choice->permuter () != FREQ_DAWG_PERM) &&
(word->best_choice->permuter () != USER_DAWG_PERM) &&
(word->best_choice->permuter () != NUMBER_PERM)) {
#ifndef SECURE_NAMES
if (tessedit_rejection_debug)
tprintf ("\nVETO Tess accepting poor word \"%s\"\n",
word->best_choice->string ().string ());
#endif
word->done = FALSE;
}
}
/*
4: as 2 + reject dict ambigs in pass 1
*/
else if (tessedit_ok_mode == 4) {
word->done = word->tess_accepted &&
(strchr (word->best_choice->string ().string (), ' ') == NULL);
if (word->done && (pass == 1) && one_ell_conflict (word, FALSE))
word->done = FALSE;
if (word->done &&
(pass == 1) &&
(((word->best_choice->permuter () != SYSTEM_DAWG_PERM) &&
(word->best_choice->permuter () != FREQ_DAWG_PERM) &&
(word->best_choice->permuter () != USER_DAWG_PERM) &&
(word->best_choice->permuter () != NUMBER_PERM)) ||
(test_ambig_word (word)))) {
#ifndef SECURE_NAMES
if (tessedit_rejection_debug)
tprintf ("\nVETO Tess accepting poor word \"%s\"\n",
word->best_choice->string ().string ());
#endif
word->done = FALSE;
}
}
/*
5: as 3 + reject dict ambigs in both passes
*/
else if (tessedit_ok_mode == 5) {
word->done = word->tess_accepted &&
(strchr (word->best_choice->string ().string (), ' ') == NULL);
if (word->done && (pass == 1) && one_ell_conflict (word, FALSE))
word->done = FALSE;
if (word->done &&
(((word->best_choice->permuter () != SYSTEM_DAWG_PERM) &&
(word->best_choice->permuter () != FREQ_DAWG_PERM) &&
(word->best_choice->permuter () != USER_DAWG_PERM) &&
(word->best_choice->permuter () != NUMBER_PERM)) ||
(test_ambig_word (word)))) {
#ifndef SECURE_NAMES
if (tessedit_rejection_debug)
tprintf ("\nVETO Tess accepting poor word \"%s\"\n",
word->best_choice->string ().string ());
#endif
word->done = FALSE;
}
}
else {
tprintf ("BAD tessedit_ok_mode\n");
err_exit();
}
}
/*************************************************************************
* make_reject_map()
*
* Sets the done flag to indicate whether the resylt is acceptable.
*
* Sets a reject map for the word.
*************************************************************************/
void make_reject_map( //make rej map for wd //detailed results
WERD_RES *word,
BLOB_CHOICE_LIST_CLIST *blob_choices,
ROW *row,
inT16 pass //1st or 2nd?
) {
int i;
int offset;
flip_0O(word);
check_debug_pt (word, -1); //For trap only
set_done(word, pass); //Set acceptance
word->reject_map.initialise (word->best_choice->lengths ().length ());
reject_blanks(word);
/*
0: Rays original heuristic - the baseline
*/
if (tessedit_reject_mode == 0) {
if (!word->done)
reject_poor_matches(word, blob_choices);
}
/*
5: Reject I/1/l from words where there is no strong contextual confirmation;
the whole of any unacceptable words (incl PERM rej of dubious 1/I/ls);
and the whole of any words which are very small
*/
else if (tessedit_reject_mode == 5) {
if (bln_x_height / word->denorm.scale () <= min_sane_x_ht_pixels)
word->reject_map.rej_word_small_xht ();
else {
one_ell_conflict(word, TRUE);
/*
Originally the code here just used the done flag. Now I have duplicated
and unpacked the conditions for setting the done flag so that each
mechanism can be turned on or off independently. This works WITHOUT
affecting the done flag setting.
*/
if (rej_use_tess_accepted && !word->tess_accepted)
word->reject_map.rej_word_not_tess_accepted ();
if (rej_use_tess_blanks &&
(strchr (word->best_choice->string ().string (), ' ') != NULL))
word->reject_map.rej_word_contains_blanks ();
if (rej_use_good_perm) {
if (((word->best_choice->permuter () == SYSTEM_DAWG_PERM) ||
(word->best_choice->permuter () == FREQ_DAWG_PERM) ||
(word->best_choice->permuter () == USER_DAWG_PERM)) &&
(!rej_use_sensible_wd ||
(acceptable_word_string
(word->best_choice->string ().string (),
word->best_choice->lengths ().string ()) !=
AC_UNACCEPTABLE))) {
//PASSED TEST
}
else if (word->best_choice->permuter () == NUMBER_PERM) {
if (rej_alphas_in_number_perm) {
for (i = 0, offset = 0;
word->best_choice->string ()[offset] != '\0';
offset += word->best_choice->lengths()[i++]) {
if (word->reject_map[i].accepted () &&
unicharset.get_isalpha (word->best_choice->string ().string()
+ offset,
word->best_choice->lengths()[i]))
word->reject_map[i].setrej_bad_permuter ();
//rej alpha
}
}
}
else {
word->reject_map.rej_word_bad_permuter ();
}
}
/* Ambig word rejection was here once !!*/
}
}
else {
tprintf ("BAD tessedit_reject_mode\n");
err_exit();
}
if (tessedit_image_border > -1)
reject_edge_blobs(word);
check_debug_pt (word, 10);
if (tessedit_rejection_debug) {
tprintf ("Permuter Type = %d\n", word->best_choice->permuter ());
tprintf ("Certainty: %f Rating: %f\n",
word->best_choice->certainty (), word->best_choice->rating ());
tprintf ("Dict word: %d\n",
dict_word (word->best_choice->string ().string ()));
}
/* Un-reject any rejected characters if NN permits */
if (tessedit_use_nn && (pass == 2) &&
word->reject_map.recoverable_rejects ())
nn_recover_rejects(word, row);
flip_hyphens(word);
check_debug_pt (word, 20);
}
void reject_blanks(WERD_RES *word) {
inT16 i;
inT16 offset;
for (i = 0, offset = 0; word->best_choice->string ()[offset] != '\0';
offset += word->best_choice->lengths ()[i], i += 1) {
if (word->best_choice->string ()[offset] == ' ')
//rej unrecognised blobs
word->reject_map[i].setrej_tess_failure ();
}
}
void reject_I_1_L(WERD_RES *word) {
inT16 i;
inT16 offset;
for (i = 0, offset = 0; word->best_choice->string ()[offset] != '\0';
offset += word->best_choice->lengths ()[i], i += 1) {
if (STRING (conflict_set_I_l_1).
contains (word->best_choice->string ()[offset])) {
//rej 1Il conflict
word->reject_map[i].setrej_1Il_conflict ();
}
}
}
void reject_poor_matches( //detailed results
WERD_RES *word,
BLOB_CHOICE_LIST_CLIST *blob_choices) {
float threshold;
inT16 i = 0;
inT16 offset = 0;
//super iterator
BLOB_CHOICE_LIST_C_IT list_it = blob_choices;
BLOB_CHOICE_IT choice_it; //real iterator
#ifndef SECURE_NAMES
if (strlen (word->best_choice->lengths ().string ()) != list_it.length ()) {
tprintf
("ASSERT FAIL string:\"%s\"; strlen=%d; choices len=%d; blob len=%d\n",
word->best_choice->string ().string (),
strlen (word->best_choice->lengths ().string ()), list_it.length (),
word->outword->blob_list ()->length ());
}
#endif
ASSERT_HOST (strlen (word->best_choice->lengths ().string ()) ==
list_it.length ());
ASSERT_HOST (word->outword->blob_list ()->length () == list_it.length ());
threshold = compute_reject_threshold (blob_choices);
for (list_it.mark_cycle_pt ();
!list_it.cycled_list (); list_it.forward (), i++,
offset += word->best_choice->lengths ()[i]) {
/* NB - only compares the threshold against the TOP choice char in the
choices list for a blob !! - the selected one may be below the threshold */
choice_it.set_to_list (list_it.data ());
if ((word->best_choice->string ()[offset] == ' ') ||
(choice_it.length () == 0))
//rej unrecognised blobs
word->reject_map[i].setrej_tess_failure ();
else if (choice_it.data ()->certainty () < threshold)
//rej poor score blob
word->reject_map[i].setrej_poor_match ();
}
}
/**********************************************************************
* compute_reject_threshold
*
* Set a rejection threshold for this word.
* Initially this is a trivial function which looks for the largest
* gap in the certainty value.
**********************************************************************/
float compute_reject_threshold( //compute threshold //detailed results
BLOB_CHOICE_LIST_CLIST *blob_choices) {
inT16 index; //to ratings
inT16 blob_count; //no of blobs in word
inT16 ok_blob_count = 0; //non TESS rej blobs in word
float *ratings; //array of confidences
float threshold; //rejection threshold
float bestgap; //biggest gap
float gapstart; //bottom of gap
//super iterator
BLOB_CHOICE_LIST_C_IT list_it = blob_choices;
BLOB_CHOICE_IT choice_it; //real iterator
blob_count = blob_choices->length ();
ratings = (float *) alloc_mem (blob_count * sizeof (float));
for (list_it.mark_cycle_pt (), index = 0;
!list_it.cycled_list (); list_it.forward (), index++) {
choice_it.set_to_list (list_it.data ());
if (choice_it.length () > 0) {
ratings[ok_blob_count] = choice_it.data ()->certainty ();
//get in an array
// tprintf("Rating[%d]=%c %g %g\n",
// index,choice_it.data()->char_class(),
// choice_it.data()->rating(),choice_it.data()->certainty());
ok_blob_count++;
}
}
ASSERT_HOST (index == blob_count);
qsort (ratings, ok_blob_count, sizeof (float), sort_floats);
//sort them
bestgap = 0;
gapstart = ratings[0] - 1; //all reject if none better
if (ok_blob_count >= 3) {
for (index = 0; index < ok_blob_count - 1; index++) {
if (ratings[index + 1] - ratings[index] > bestgap) {
bestgap = ratings[index + 1] - ratings[index];
//find biggest
gapstart = ratings[index];
}
}
}
threshold = gapstart + bestgap / 2;
// tprintf("First=%g, last=%g, gap=%g, threshold=%g\n",
// ratings[0],ratings[index],bestgap,threshold);
free_mem(ratings);
return threshold;
}
/**********************************************************************
* sort_floats
*
* qsort function to sort 2 floats.
**********************************************************************/
int sort_floats( //qsort function
const void *arg1, //ptrs to floats
const void *arg2) {
float diff; //difference
diff = *((float *) arg1) - *((float *) arg2);
if (diff > 0)
return 1;
else if (diff < 0)
return -1;
else
return 0;
}
/*************************************************************************
* reject_edge_blobs()
*
* If the word is perilously close to the edge of the image, reject those blobs
* in the word which are too close to the edge as they could be clipped.
*************************************************************************/
void reject_edge_blobs(WERD_RES *word) {
TBOX word_box = word->word->bounding_box ();
TBOX blob_box;
PBLOB_IT blob_it = word->outword->blob_list ();
//blobs
int blobindex = 0;
float centre;
if ((word_box.left () < tessedit_image_border) ||
(word_box.bottom () < tessedit_image_border) ||
(word_box.right () + tessedit_image_border >
page_image.get_xsize () - 1) ||
(word_box.top () + tessedit_image_border > page_image.get_ysize () - 1)) {
ASSERT_HOST (word->reject_map.length () == blob_it.length ());
for (blobindex = 0, blob_it.mark_cycle_pt ();
!blob_it.cycled_list (); blobindex++, blob_it.forward ()) {
blob_box = blob_it.data ()->bounding_box ();
centre = (blob_box.left () + blob_box.right ()) / 2.0;
if ((word->denorm.x (blob_box.left ()) < tessedit_image_border) ||
(word->denorm.y (blob_box.bottom (), centre) <
tessedit_image_border) ||
(word->denorm.x (blob_box.right ()) + tessedit_image_border >
page_image.get_xsize () - 1) ||
(word->denorm.y (blob_box.top (), centre)
+ tessedit_image_border > page_image.get_ysize () - 1)) {
word->reject_map[blobindex].setrej_edge_char ();
//close to edge
}
}
}
}
/**********************************************************************
* one_ell_conflict()
*
* Identify words where there is a potential I/l/1 error.
* - A bundle of contextual heuristics!
**********************************************************************/
BOOL8 one_ell_conflict(WERD_RES *word_res, BOOL8 update_map) {
const char *word;
const char *lengths;
inT16 word_len; //its length
inT16 first_alphanum_index_;
inT16 first_alphanum_offset_;
inT16 i;
inT16 offset;
BOOL8 non_conflict_set_char; //non conf set a/n?
BOOL8 conflict = FALSE;
BOOL8 allow_1s;
ACCEPTABLE_WERD_TYPE word_type;
BOOL8 dict_perm_type;
BOOL8 dict_word_ok;
int dict_word_type;
word = word_res->best_choice->string ().string ();
lengths = word_res->best_choice->lengths().string();
word_len = strlen (lengths);
/*
If there are no occurrences of the conflict set characters then the word
is OK.
*/
if (strpbrk (word, conflict_set_I_l_1.string ()) == NULL)
return FALSE;
/*
There is a conflict if there are NO other (confirmed) alphanumerics apart
from those in the conflict set.
*/
for (i = 0, offset = 0, non_conflict_set_char = FALSE;
(i < word_len) && !non_conflict_set_char; offset += lengths[i++])
non_conflict_set_char =
(unicharset.get_isalpha(word + offset, lengths[i]) ||
unicharset.get_isdigit(word + offset, lengths[i])) &&
!STRING (conflict_set_I_l_1).contains (word[offset]);
if (!non_conflict_set_char) {
if (update_map)
reject_I_1_L(word_res);
return TRUE;
}
/*
If the word is accepted by a dawg permuter, and the first alpha character
is "I" or "l", check to see if the alternative is also a dawg word. If it
is, then there is a potential error otherwise the word is ok.
*/
dict_perm_type = (word_res->best_choice->permuter () == SYSTEM_DAWG_PERM) ||
(word_res->best_choice->permuter () == USER_DAWG_PERM) ||
(rej_trust_doc_dawg &&
(word_res->best_choice->permuter () == DOC_DAWG_PERM)) ||
(word_res->best_choice->permuter () == FREQ_DAWG_PERM);
dict_word_type = dict_word (word);
dict_word_ok = (dict_word_type > 0) &&
(rej_trust_doc_dawg || (dict_word_type != DOC_DAWG_PERM));
if ((rej_1Il_use_dict_word && dict_word_ok) ||
(rej_1Il_trust_permuter_type && dict_perm_type) ||
(dict_perm_type && dict_word_ok)) {
first_alphanum_index_ = first_alphanum_index (word, lengths);
first_alphanum_offset_ = first_alphanum_offset (word, lengths);
if (lengths[first_alphanum_index_] == 1 &&
word[first_alphanum_offset_] == 'I') {
word_res->best_choice->string ()[first_alphanum_offset_] = 'l';
if (safe_dict_word (word) > 0) {
word_res->best_choice->string ()[first_alphanum_offset_] = 'I';
if (update_map)
word_res->reject_map[first_alphanum_index_].
setrej_1Il_conflict();
return TRUE;
}
else {
word_res->best_choice->string ()[first_alphanum_offset_] = 'I';
return FALSE;
}
}
if (lengths[first_alphanum_index_] == 1 &&
word[first_alphanum_offset_] == 'l') {
word_res->best_choice->string ()[first_alphanum_offset_] = 'I';
if (safe_dict_word (word) > 0) {
word_res->best_choice->string ()[first_alphanum_offset_] = 'l';
if (update_map)
word_res->reject_map[first_alphanum_index_].
setrej_1Il_conflict();
return TRUE;
}
else {
word_res->best_choice->string ()[first_alphanum_offset_] = 'l';
return FALSE;
}
}
return FALSE;
}
/*
NEW 1Il code. The old code relied on permuter types too much. In fact,
tess will use TOP_CHOICE permute for good things like "palette".
In this code the string is examined independently to see if it looks like
a well formed word.
*/
/*
REGARDLESS OF PERMUTER, see if flipping a leading I/l generates a
dictionary word.
*/
first_alphanum_index_ = first_alphanum_index (word, lengths);
first_alphanum_offset_ = first_alphanum_offset (word, lengths);
if (lengths[first_alphanum_index_] == 1 &&
word[first_alphanum_offset_] == 'l') {
word_res->best_choice->string ()[first_alphanum_offset_] = 'I';
if (safe_dict_word (word) > 0)
return FALSE;
else
word_res->best_choice->string ()[first_alphanum_offset_] = 'l';
}
else if (lengths[first_alphanum_index_] == 1 &&
word[first_alphanum_offset_] == 'I') {
word_res->best_choice->string ()[first_alphanum_offset_] = 'l';
if (safe_dict_word (word) > 0)
return FALSE;
else
word_res->best_choice->string ()[first_alphanum_offset_] = 'I';
}
/*
For strings containing digits:
If there are no alphas OR the numeric permuter liked the word,
reject any non 1 conflict chs
Else reject all conflict chs
*/
if (word_contains_non_1_digit (word, lengths)) {
allow_1s = (alpha_count (word, lengths) == 0) ||
(word_res->best_choice->permuter () == NUMBER_PERM);
inT16 offset;
conflict = FALSE;
for (i = 0, offset = 0; word[offset] != '\0';
offset += word_res->best_choice->lengths ()[i++]) {
if ((!allow_1s || (word[offset] != '1')) &&
STRING (conflict_set_I_l_1).contains (word[offset])) {
if (update_map)
word_res->reject_map[i].setrej_1Il_conflict ();
conflict = TRUE;
}
}
return conflict;
}
/*
For anything else. See if it conforms to an acceptable word type. If so,
treat accordingly.
*/
word_type = acceptable_word_string (word, lengths);
if ((word_type == AC_LOWER_CASE) || (word_type == AC_INITIAL_CAP)) {
first_alphanum_index_ = first_alphanum_index (word, lengths);
first_alphanum_offset_ = first_alphanum_offset (word, lengths);
if (STRING (conflict_set_I_l_1).contains (word[first_alphanum_offset_])) {
if (update_map)
word_res->reject_map[first_alphanum_index_].
setrej_1Il_conflict ();
return TRUE;
}
else
return FALSE;
}
else if (word_type == AC_UPPER_CASE) {
return FALSE;
}
else {
if (update_map)
reject_I_1_L(word_res);
return TRUE;
}
}
inT16 first_alphanum_index(const char *word,
const char *word_lengths) {
inT16 i;
inT16 offset;
for (i = 0, offset = 0; word[offset] != '\0'; offset += word_lengths[i++]) {
if (unicharset.get_isalpha(word + offset, word_lengths[i]) ||
unicharset.get_isdigit(word + offset, word_lengths[i]))
return i;
}
return -1;
}
inT16 first_alphanum_offset(const char *word,
const char *word_lengths) {
inT16 i;
inT16 offset;
for (i = 0, offset = 0; word[offset] != '\0'; offset += word_lengths[i++]) {
if (unicharset.get_isalpha(word + offset, word_lengths[i]) ||
unicharset.get_isdigit(word + offset, word_lengths[i]))
return offset;
}
return -1;
}
inT16 alpha_count(const char *word,
const char *word_lengths) {
inT16 i;
inT16 offset;
inT16 count = 0;
for (i = 0, offset = 0; word[offset] != '\0'; offset += word_lengths[i++]) {
if (unicharset.get_isalpha (word + offset, word_lengths[i]))
count++;
}
return count;
}
BOOL8 word_contains_non_1_digit(const char *word,
const char *word_lengths) {
inT16 i;
inT16 offset;
for (i = 0, offset = 0; word[offset] != '\0'; offset += word_lengths[i++]) {
if (unicharset.get_isdigit (word + offset, word_lengths[i]) &&
(word_lengths[i] != 1 || word[offset] != '1'))
return TRUE;
}
return FALSE;
}
BOOL8 test_ambig_word( //test for ambiguity
WERD_RES *word) {
BOOL8 ambig = FALSE;
if ((word->best_choice->permuter () == SYSTEM_DAWG_PERM) ||
(word->best_choice->permuter () == FREQ_DAWG_PERM) ||
(word->best_choice->permuter () == USER_DAWG_PERM)) {
ambig = !NoDangerousAmbig(word->best_choice->string().string(),
word->best_choice->lengths().string(),
NULL);
}
return ambig;
}
/*************************************************************************
* ambig_word()
*
* This is a recursive routine which tests the dictionary for all combinations
* of conflict set alternatives for characters in a given word.
*************************************************************************/
BOOL8 ambig_word( //original word
const char *start_word,
char *temp_word, //alterable copy
inT16 test_char_pos //idx to char to alter
) {
const char *ambigs; //Ambiguities for char
if (*(temp_word + test_char_pos) == '\0') {
if (safe_dict_word (temp_word)) {
if (strcmp (start_word, temp_word) == 0)
return FALSE;
else
return TRUE;
}
else
return FALSE;
}
else {
ambigs = char_ambiguities (*(temp_word + test_char_pos));
if (ambigs == NULL)
return ambig_word (start_word, temp_word, test_char_pos + 1);
else {
while (*ambigs != '\0') {
*(temp_word + test_char_pos) = *ambigs++;
//test next ambiguity
if (ambig_word (start_word, temp_word, test_char_pos + 1))
return TRUE;
}
return FALSE;
}
}
}
/*************************************************************************
* char_ambiguities()
*
* Return a pointer to a string containing the full conflict set of characters
* which includes the specified character, if there is one. If the specified
* character is not a member of a conflict set, return NULL.
* (NOTE that a character is assumed to be a member of only ONE conflict set.)
*************************************************************************/
const char *char_ambiguities(char c) {
static STRING_CLIST conflict_sets;
static BOOL8 read_conflict_sets = FALSE;
STRING_C_IT cs_it(&conflict_sets);
const char *cs;
STRING cs_file_name;
FILE *cs_file;
char buff[1024];
if (!read_conflict_sets) {
cs_file_name = datadir + "confsets";
if (!(cs_file = fopen (cs_file_name.string (), "r"))) {
CANTOPENFILE.error ("char_ambiguities", EXIT, "%s %d",
cs_file_name.string (), errno);
}
while (fscanf (cs_file, "%s", buff) == 1) {
cs_it.add_after_then_move (new STRING (buff));
}
read_conflict_sets = TRUE;
cs_it.move_to_first ();
if (tessedit_rejection_debug) {
for (cs_it.mark_cycle_pt ();
!cs_it.cycled_list (); cs_it.forward ()) {
tprintf ("\"%s\"\n", cs_it.data ()->string ());
}
}
}
cs_it.move_to_first ();
for (cs_it.mark_cycle_pt (); !cs_it.cycled_list (); cs_it.forward ()) {
cs = cs_it.data ()->string ();
if (strchr (cs, c) != NULL)
return cs;
}
return NULL;
}
#ifndef EMBEDDED
void test_ambigs(const char *word) {
char orig_word[80];
char temp_word[80];
if (strlen (word) > 80)
tprintf ("Ridiculously long word \"%s\"\n", word);
else {
strcpy(orig_word, word);
while (strlen (orig_word) > 0) {
strcpy(temp_word, orig_word);
#ifndef SECURE_NAMES
if (ambig_word (orig_word, temp_word, 0))
tprintf ("Ambiguity \"%s\" -> \"%s\"\n", orig_word, temp_word);
else
tprintf ("NO Ambiguities for \"%s\"\n", orig_word);
tprintf ("Next Word > ");
#endif
scanf ("%s", orig_word);
}
}
}
#endif
/*************************************************************************
* nn_recover_rejects()
* Generate the nn_reject_map - a copy of the current reject map, but dont
* reject previously rejected chars if the NN matcher agrees with the best
* choice.
*************************************************************************/
void nn_recover_rejects(WERD_RES *word, ROW *row) {
//copy for debug
REJMAP old_map = word->reject_map;
/*
NOTE THAT THIS IS RELATIVELY INEFFICIENT AS THE WHOLE OF THE WERD IS
MATCHED BY THE NN MATCHER. IF COULD EASILY BE RESTRICTED TO JUST THE
REJECT CHARACTERS (Though initial use is when words are total rejects
anyway).
*/
set_global_subsubloc_code(SUBSUBLOC_NN);
nn_match_word(word, row);
if (no_unrej_1Il)
dont_allow_1Il(word);
if (no_unrej_dubious_chars)
dont_allow_dubious_chars(word);
if (rej_mostly_reject_mode == 1)
reject_mostly_rejects(word);
/*
IF there are no unrejected alphanumerics AND
The word is not an acceptable single non alphanum char word AND
The word is not an acceptable repeated non alphanum char word
THEN Reject whole word
*/
if (no_unrej_no_alphanum_wds &&
(count_alphanums (word) < 1) &&
!((word->best_choice->lengths ().length () == 1) &&
STRING (ok_single_ch_non_alphanum_wds).contains (word->best_choice->
string ()[0]))
&& !repeated_nonalphanum_wd (word, row))
word->reject_map.rej_word_no_alphanums ();
#ifndef SECURE_NAMES
if (nn_debug) {
tprintf ("\nTess: \"%s\" MAP ", word->best_choice->string ().string ());
old_map.print (stdout);
tprintf ("->");
word->reject_map.print (stdout);
tprintf ("\n");
}
#endif
set_global_subsubloc_code(SUBSUBLOC_OTHER);
}
void nn_match_word( //Match a word
WERD_RES *word,
ROW *row) {
PIXROW_LIST *pixrow_list;
PIXROW_IT pixrow_it;
IMAGELINE *imlines; //lines of the image
TBOX pix_box; //box of imlines extent
#ifndef GRAPHICS_DISABLED
ScrollView* win = NULL;
#endif
IMAGE clip_image;
IMAGE scaled_image;
float baseline_pos;
inT16 net_image_size;
inT16 clip_image_size;
WERD copy_outword; // copy to denorm
inT16 i;
const char *word_string;
const char *word_string_lengths;
BOOL8 word_in_dict; //Tess wd in dict
BOOL8 checked_dict_word; //Tess wd definitely in dict
BOOL8 sensible_word; //OK char string
BOOL8 centre; //Not at word end chs
BOOL8 good_quality_word;
inT16 char_quality;
inT16 accepted_char_quality;
inT16 conf_level; //0:REJECT
//1:DODGY ACCEPT
//2:DICT ACCEPT
//3:CLEAR ACCEPT
inT16 first_alphanum_index_;
inT16 first_alphanum_offset_;
word_string = word->best_choice->string ().string ();
word_string_lengths = word->best_choice->lengths ().string ();
first_alphanum_index_ = first_alphanum_index (word_string,
word_string_lengths);
first_alphanum_offset_ = first_alphanum_offset (word_string,
word_string_lengths);
word_in_dict = ((word->best_choice->permuter () == SYSTEM_DAWG_PERM) ||
(word->best_choice->permuter () == FREQ_DAWG_PERM) ||
(word->best_choice->permuter () == USER_DAWG_PERM));
checked_dict_word = word_in_dict && (safe_dict_word (word_string) > 0);
sensible_word = acceptable_word_string (word_string, word_string_lengths) !=
AC_UNACCEPTABLE;
word_char_quality(word, row, &char_quality, &accepted_char_quality);
good_quality_word = word->best_choice->lengths ().length () == char_quality;
#ifndef SECURE_NAMES
if (nn_reject_debug) {
tprintf ("Dict: %c Checked Dict: %c Sensible: %c Quality: %c\n",
word_in_dict ? 'T' : 'F',
checked_dict_word ? 'T' : 'F',
sensible_word ? 'T' : 'F', good_quality_word ? 'T' : 'F');
}
#endif
if (word->best_choice->lengths ().length () !=
word->outword->blob_list ()->length ()) {
#ifndef SECURE_NAMES
tprintf ("nn_match_word ASSERT FAIL String:\"%s\"; #Blobs=%d\n",
word->best_choice->string ().string (),
word->outword->blob_list ()->length ());
#endif
err_exit();
}
copy_outword = *(word->outword);
copy_outword.baseline_denormalise (&word->denorm);
/*
For each character, generate and match a new image, containing JUST the
character we have clipped, centered in the image, on a white background.
Note that we MUST have a square image so that we can scale it uniformly in
x and y. We base the size on x_height as this can be found fairly reliably.
*/
net_image_size = (net_image_width > net_image_height) ?
net_image_width : net_image_height;
clip_image_size = (inT16) floor (0.5 +
net_image_size * word->x_height /
net_image_x_height);
if ((clip_image_size <= 1) || (net_image_size <= 1)) {
return;
}
/*
Get the image of the word and the pix positions of each char
*/
char_clip_word(©_outword, page_image, pixrow_list, imlines, pix_box);
#ifndef GRAPHICS_DISABLED
if (show_char_clipping) {
win = display_clip_image (©_outword, page_image,
pixrow_list, pix_box);
}
#endif
pixrow_it.set_to_list (pixrow_list);
pixrow_it.move_to_first ();
for (pixrow_it.mark_cycle_pt (), i = 0;
!pixrow_it.cycled_list (); pixrow_it.forward (), i++) {
if (pixrow_it.data ()->
bad_box (page_image.get_xsize (), page_image.get_ysize ()))
continue;
clip_image.create (clip_image_size, clip_image_size, 1);
//make bin imge
if (!copy_outword.flag (W_INVERSE))
invert_image(&clip_image); //white background for black on white
pixrow_it.data ()->char_clip_image (imlines, pix_box, row,
clip_image, baseline_pos);
if (copy_outword.flag (W_INVERSE))
invert_image(&clip_image); //invert white on black for scaling &NN
scaled_image.create (net_image_size, net_image_size, 1);
scale_image(clip_image, scaled_image);
baseline_pos *= net_image_size / clip_image_size;
//scale with im
centre = !pixrow_it.at_first () && !pixrow_it.at_last ();
conf_level = nn_match_char (scaled_image, baseline_pos,
word_in_dict, checked_dict_word,
sensible_word, centre,
good_quality_word, word_string[i]);
if (word->reject_map[i].recoverable ()) {
if ((i == first_alphanum_index_) &&
word_string_lengths[first_alphanum_index_] == 1 &&
((word_string[first_alphanum_offset_] == 'I') ||
(word_string[first_alphanum_offset_] == 'i'))) {
if (conf_level >= nn_conf_initial_i_level)
word->reject_map[i].setrej_nn_accept ();
//un-reject char
}
else if (conf_level > 0)
//un-reject char
word->reject_map[i].setrej_nn_accept ();
}
#ifndef GRAPHICS_DISABLED
if (show_char_clipping)
display_images(clip_image, scaled_image);
#endif
clip_image.destroy();
scaled_image.destroy();
}
delete[]imlines; // Free array of imlines
delete pixrow_list;
#ifndef GRAPHICS_DISABLED
if (show_char_clipping) {
// destroy_window(win);
// win->Destroy();
delete win;
}
#endif
}
/*************************************************************************
* nn_match_char()
* Call Neural Net matcher to match a single character, given a scaled,
* square image
*************************************************************************/
inT16 nn_match_char( //of character
IMAGE &scaled_image,
float baseline_pos, //rel to scaled_image
BOOL8 dict_word, //part of dict wd?
BOOL8 checked_dict_word, //part of dict wd?
BOOL8 sensible_word, //part acceptable str?
BOOL8 centre, //not at word ends?
BOOL8 good_quality_word, //initial segmentation
char tess_ch //confirm this?
) {
inT16 conf_level; //0..2
inT32 row;
inT32 col;
inT32 y_size = scaled_image.get_ysize ();
inT32 start_y = y_size - (y_size - net_image_height) / 2 - 1;
inT32 end_y = start_y - net_image_height + 1;
IMAGELINE imline;
float *input_vector;
float *input_vec_ptr;
char top;
float top_score;
char next;
float next_score;
inT16 input_nodes = (net_image_height * net_image_width) + net_bl_nodes;
inT16 j;
input_vector = (float *) alloc_mem (input_nodes * sizeof (float));
input_vec_ptr = input_vector;
invert_image(&scaled_image); //cos nns work better
for (row = start_y; row >= end_y; row--) {
scaled_image.fast_get_line (0, row, net_image_width, &imline);
for (col = 0; col < net_image_width; col++)
*input_vec_ptr++ = imline.pixels[col];
}
/*
The bit map presented to the net may be shorter than the image, so shift
the coord to be relative to the bitmap portion.
*/
baseline_pos -= (y_size - net_image_height) / 2.0;
/*
Baseline pos is 0 if below bitmap, 1 if above and in proportion otherwise.
This is represented to the net as a set of bl_nodes, an initial proportion
of which are set to 1.0, indicating the level of the baseline. The
remainder are 0.0
*/
if (baseline_pos < 0)
baseline_pos = 0;
else if (baseline_pos >= net_image_height)
baseline_pos = net_image_height + 1;
else
baseline_pos = baseline_pos + 1;
baseline_pos = baseline_pos / (net_image_height + 1);
if (net_bl_nodes > 0) {
baseline_pos *= 1.7; //Use a wider range
if (net_bl_nodes > 1) {
/* Multi-node baseline representation */
for (j = 0; j < net_bl_nodes; j++) {
if (baseline_pos > ((float) j / net_bl_nodes))
*input_vec_ptr++ = 1.0;
else
*input_vec_ptr++ = 0.0;
}
}
else {
/* Single node baseline */
*input_vec_ptr++ = baseline_pos;
}
}
callnet(input_vector, &top, &top_score, &next, &next_score);
conf_level = evaluate_net_match (top, top_score, next, next_score,
tess_ch, dict_word, checked_dict_word,
sensible_word, centre, good_quality_word);
#ifndef SECURE_NAMES
if (nn_reject_debug) {
tprintf ("top:\"%c\" %4.2f next:\"%c\" %4.2f TESS:\"%c\" Conf: %d\n",
top, top_score, next, next_score, tess_ch, conf_level);
}
#endif
free_mem(input_vector);
return conf_level;
}
inT16 evaluate_net_match(char top,
float top_score,
char next,
float next_score,
char tess_ch,
BOOL8 dict_word,
BOOL8 checked_dict_word,
BOOL8 sensible_word,
BOOL8 centre,
BOOL8 good_quality_word) {
inT16 accept_level; //0 Very clearly matched
//1 Clearly top
//2 Top but poor match
//3 Next & poor top match
//4 Next but good top match
//5 No chance
BOOL8 good_top_choice;
BOOL8 excellent_top_choice;
BOOL8 confusion_match = FALSE;
BOOL8 dodgy_char = !isalnum (tess_ch);
good_top_choice = (top_score > nn_reject_threshold) &&
(nn_reject_head_and_shoulders * top_score > next_score);
excellent_top_choice = good_top_choice &&
(top_score > nn_dodgy_char_threshold);
if (top == tess_ch) {
if (excellent_top_choice)
accept_level = 0;
else if (good_top_choice)
accept_level = 1; //Top correct and well matched
else
accept_level = 2; //Top correct but poor match
}
else if ((nn_conf_1Il &&
STRING (conflict_set_I_l_1).contains (tess_ch) &&
STRING (conflict_set_I_l_1).contains (top)) ||
(nn_conf_hyphen &&
STRING (conflict_set_hyphen).contains (tess_ch) &&
STRING (conflict_set_hyphen).contains (top)) ||
(nn_conf_Ss &&
STRING (conflict_set_S_s).contains (tess_ch) &&
STRING (conflict_set_S_s).contains (top))) {
confusion_match = TRUE;
if (good_top_choice)
accept_level = 1; //Good top confusion
else
accept_level = 2; //Poor top confusion
}
else if ((nn_conf_1Il &&
STRING (conflict_set_I_l_1).contains (tess_ch) &&
STRING (conflict_set_I_l_1).contains (next)) ||
(nn_conf_hyphen &&
STRING (conflict_set_hyphen).contains (tess_ch) &&
STRING (conflict_set_hyphen).contains (next)) ||
(nn_conf_Ss &&
STRING (conflict_set_S_s).contains (tess_ch) &&
STRING (conflict_set_S_s).contains (next))) {
confusion_match = TRUE;
if (!good_top_choice)
accept_level = 3; //Next confusion and top match dodgy
else
accept_level = 4; //Next confusion and good top match
}
else if (next == tess_ch) {
if (!good_top_choice)
accept_level = 3; //Next match and top match dodgy
else
accept_level = 4; //Next match and good top match
}
else
accept_level = 5;
/* Could allow some match flexibility here sS$ etc */
/* Now set confirmation level according to how much we can believe the tess
char. */
if ((accept_level == 0) && !confusion_match)
return 3;
if ((accept_level <= 1) &&
(!nn_conf_strict_on_dodgy_chs || !dodgy_char) && !confusion_match)
return 3;
if ((accept_level == 2) &&
!confusion_match && !dodgy_char &&
good_quality_word &&
dict_word &&
(checked_dict_word || !nn_double_check_dict) && sensible_word)
return 2;
if (confusion_match &&
(accept_level <= nn_conf_accept_level) &&
(good_quality_word ||
(!nn_conf_test_good_qual &&
!STRING (conflict_set_I_l_1).contains (tess_ch))) &&
(dict_word || !nn_conf_test_dict) &&
(checked_dict_word || !nn_conf_double_check_dict) &&
(sensible_word || !nn_conf_test_sensible))
return 1;
if (!confusion_match &&
nn_lax &&
(accept_level == 3) &&
(good_quality_word || !nn_conf_test_good_qual) &&
(dict_word || !nn_conf_test_dict) &&
(sensible_word || !nn_conf_test_sensible))
return 1;
else
return 0;
}
/*************************************************************************
* dont_allow_dubious_chars()
* Let Rejects "eat" into adjacent "dubious" chars. I.e those prone to be wrong
* if adjacent to a reject.
*************************************************************************/
void dont_allow_dubious_chars(WERD_RES *word) {
int i = 0;
int offset = 0;
int rej_pos;
int word_len = word->reject_map.length ();
while (i < word_len) {
/* Find next reject */
while ((i < word_len) && (word->reject_map[i].accepted ()))
{
offset += word->best_choice->lengths()[i];
i++;
}
if (i < word_len) {
rej_pos = i;
/* Reject dubious chars to the left */
i--;
offset -= word->best_choice->lengths()[i];
while ((i >= 0) &&
STRING (dubious_chars_left_of_reject).contains (word->
best_choice->
string ()
[offset])) {
word->reject_map[i--].setrej_dubious ();
offset -= word->best_choice->lengths()[i];
}
/* Skip adjacent rejects */
for (i = rej_pos;
(i < word_len) && (word->reject_map[i].rejected ());
offset += word->best_choice->lengths()[i++]);
/* Reject dubious chars to the right */
while ((i < word_len) &&
STRING (dubious_chars_right_of_reject).contains (word->
best_choice->
string ()
[offset])) {
offset += word->best_choice->lengths()[i];
word->reject_map[i++].setrej_dubious ();
}
}
}
}
/*************************************************************************
* dont_allow_1Il()
* Dont unreject LONE accepted 1Il conflict set chars
*************************************************************************/
void dont_allow_1Il(WERD_RES *word) {
int i = 0;
int offset;
int word_len = word->reject_map.length ();
const char *s = word->best_choice->string ().string ();
const char *lengths = word->best_choice->lengths ().string ();
BOOL8 accepted_1Il = FALSE;
for (i = 0, offset = 0; i < word_len;
offset += word->best_choice->lengths()[i++]) {
if (word->reject_map[i].accepted ()) {
if (STRING (conflict_set_I_l_1).contains (s[offset]))
accepted_1Il = TRUE;
else {
if (unicharset.get_isalpha (s + offset, lengths[i]) ||
unicharset.get_isdigit (s + offset, lengths[i]))
return; // >=1 non 1Il ch accepted
}
}
}
if (!accepted_1Il)
return; //Nothing to worry about
for (i = 0, offset = 0; i < word_len;
offset += word->best_choice->lengths()[i++]) {
if (STRING (conflict_set_I_l_1).contains (s[offset]) &&
word->reject_map[i].accepted ())
word->reject_map[i].setrej_postNN_1Il ();
}
}
inT16 count_alphanums( //how many alphanums
WERD_RES *word) {
int count = 0;
int i;
int offset;
for (i = 0, offset = 0; i < word->reject_map.length ();
offset += word->best_choice->lengths()[i++]) {
if ((word->reject_map[i].accepted ()) &&
(unicharset.get_isalpha (word->best_choice->string ().string() + offset,
word->best_choice->lengths ()[i]) ||
unicharset.get_isdigit (word->best_choice->string ().string() + offset,
word->best_choice->lengths ()[i])))
count++;
}
return count;
}
void reject_mostly_rejects( //rej all if most rejectd
WERD_RES *word) {
/* Reject the whole of the word if the fraction of rejects exceeds a limit */
if ((float) word->reject_map.reject_count () / word->reject_map.length () >=
rej_whole_of_mostly_reject_word_fract)
word->reject_map.rej_word_mostly_rej ();
}
BOOL8 repeated_nonalphanum_wd(WERD_RES *word, ROW *row) {
inT16 char_quality;
inT16 accepted_char_quality;
if (word->best_choice->lengths ().length () <= 1)
return FALSE;
if (!STRING (ok_repeated_ch_non_alphanum_wds).
contains (word->best_choice->string ()[0]))
return FALSE;
if (!repeated_ch_string (word->best_choice->string ().string (),
word->best_choice->lengths ().string ()))
return FALSE;
word_char_quality(word, row, &char_quality, &accepted_char_quality);
if ((word->best_choice->lengths ().length () == char_quality) &&
(char_quality == accepted_char_quality))
return TRUE;
else
return FALSE;
}
BOOL8 repeated_ch_string(const char *rep_ch_str,
const char *lengths) {
UNICHAR_ID c;
if ((rep_ch_str == NULL) || (*rep_ch_str == '\0')) {
return FALSE;
}
c = unicharset.unichar_to_id(rep_ch_str, *lengths);
rep_ch_str += *(lengths++);
while (*rep_ch_str != '\0' &&
unicharset.unichar_to_id(rep_ch_str, *lengths) == c) {
rep_ch_str++;
}
if (*rep_ch_str == '\0')
return TRUE;
return FALSE;
}
inT16 safe_dict_word(const char *s) {
int dict_word_type;
dict_word_type = dict_word (s);
if (dict_word_type == DOC_DAWG_PERM)
return 0;
else
return dict_word_type;
}
void flip_hyphens(WERD_RES *word) {
char *str = (char *) word->best_choice->string ().string ();
int i = 0;
int offset = 0;
PBLOB_IT outword_it;
int prev_right = -9999;
int next_left;
TBOX out_box;
float aspect_ratio;
if (tessedit_lower_flip_hyphen <= 1)
return;
outword_it.set_to_list (word->outword->blob_list ());
for (outword_it.mark_cycle_pt ();
!outword_it.cycled_list (); outword_it.forward (),
offset += word->best_choice->lengths()[i++]) {
out_box = outword_it.data ()->bounding_box ();
if (outword_it.at_last ())
next_left = 9999;
else
next_left = outword_it.data_relative (1)->bounding_box ().left ();
/*
Dont touch small or touching blobs - it is too dangerous
*/
if ((out_box.width () > 8 * word->denorm.scale ()) &&
(out_box.left () > prev_right) && (out_box.right () < next_left)) {
aspect_ratio = out_box.width () / (float) out_box.height ();
if (str[offset] == '.') {
if (aspect_ratio >= tessedit_upper_flip_hyphen) {
/* Certain HYPHEN */
str[offset] = '-';
if (word->reject_map[i].rejected ())
word->reject_map[i].setrej_hyphen_accept ();
}
if ((aspect_ratio > tessedit_lower_flip_hyphen) &&
word->reject_map[i].accepted ())
//Suspected HYPHEN
word->reject_map[i].setrej_hyphen ();
}
else if (str[offset] == '-') {
if ((aspect_ratio >= tessedit_upper_flip_hyphen) &&
(word->reject_map[i].rejected ()))
word->reject_map[i].setrej_hyphen_accept ();
//Certain HYPHEN
if ((aspect_ratio <= tessedit_lower_flip_hyphen) &&
(word->reject_map[i].accepted ()))
//Suspected HYPHEN
word->reject_map[i].setrej_hyphen ();
}
}
prev_right = out_box.right ();
}
}
void flip_0O(WERD_RES *word) {
char *str = (char *) word->best_choice->string ().string ();
char *lengths = (char *) word->best_choice->lengths ().string ();
int i;
int offset;
PBLOB_IT outword_it;
TBOX out_box;
if (!tessedit_flip_0O)
return;
outword_it.set_to_list (word->outword->blob_list ());
for (i = 0, offset = 0, outword_it.mark_cycle_pt ();
!outword_it.cycled_list (); offset += lengths[i++], outword_it.forward ()) {
if (unicharset.get_isupper (str + offset, lengths[i]) ||
unicharset.get_isdigit (str + offset, lengths[i])) {
out_box = outword_it.data ()->bounding_box ();
if ((out_box.top () < bln_baseline_offset + bln_x_height) ||
(out_box.bottom () > bln_baseline_offset + bln_x_height / 4))
return; //Beware words with sub/superscripts
}
}
for (i = 1, offset = lengths[0]; str[offset] != '\0';
offset += lengths[i++], outword_it.forward ()) {
if (lengths[i] == 1 &&
((str[offset] == '0') || (str[offset] == 'O'))) {
/* A0A */
if (non_O_upper (str + offset - lengths[i - 1], lengths[i - 1]) &&
lengths[i + 1] > 0 &&
non_O_upper (str + offset + lengths[i], lengths[i + 1])) {
str[offset] = 'O';
}
/* A00A */
if (non_O_upper (str + offset - lengths[i - 1], lengths[i - 1]) &&
((lengths[i + 1] == 1 && str[offset + lengths[i]] == '0') ||
(lengths[i + 1] == 1 && str[offset + lengths[i]] == 'O')) &&
lengths[i + 2] > 0 &&
non_O_upper (str + offset + lengths[i] + lengths[i + 1],
lengths[i + 2])) {
str[offset] = 'O';
str[offset + lengths[i]] = 'O';
offset += lengths[i++];
}
/* AA0<non digit or end of word> */
if ((i > 1) &&
non_O_upper (str + offset - lengths[i - 1] - lengths[i - 2],
lengths[i - 2]) &&
non_O_upper (str + offset - lengths[i - 1], lengths[i - 1]) &&
lengths[i + 1] > 0 &&
!unicharset.get_isdigit (str + offset + lengths[i], lengths[i + 1]) &&
(lengths[i + 1] != 1 || str[offset + lengths[i]] != 'l') &&
(lengths[i + 1] != 1 || str[offset + lengths[i]] != 'I')) {
str[offset] = 'O';
}
/* 9O9 */
if (non_0_digit (str + offset - lengths[i - 1], lengths[i - 1]) &&
lengths[i + 1] > 0 &&
non_0_digit (str + offset + lengths[i], lengths[i + 1])) {
str[offset] = '0';
}
/* 9OOO */
if (non_0_digit (str + offset - lengths[i - 1], lengths[i - 1]) &&
((lengths[i + 1] == 1 && str[offset + lengths[i]] == '0') ||
(lengths[i + 1] == 1 && str[offset + lengths[i]] == 'O')) &&
((lengths[i + 2] == 1 &&
str[offset + lengths[i] + lengths[i + 1]] == '0') ||
(lengths[i + 2] == 1 &&
str[offset + lengths[i] + lengths[i + 1]] == 'O'))) {
str[offset] = '0';
str[offset + lengths[i]] = '0';
str[offset + lengths[i] + lengths[i + 1]] = '0';
offset += lengths[i++];
offset += lengths[i++];
}
/* 9OO<non upper> */
if (non_0_digit (str + offset - lengths[i - 1], lengths[i - 1]) &&
((lengths[i + 1] == 1 && str[offset + lengths[i]] == '0') ||
(lengths[i + 1] == 1 && str[offset + lengths[i]] == 'O')) &&
lengths[i + 2] > 0 &&
!unicharset.get_isupper (str + offset + lengths[i] + lengths[i + 1],
lengths[i + 2])) {
str[offset] = '0';
str[offset + lengths[i]] = '0';
offset += lengths[i++];
}
/* 9O<non upper> */
if (non_0_digit (str + offset - lengths[i - 1], lengths[i - 1]) &&
lengths[i + 1] > 0 &&
!unicharset.get_isupper (str + offset + lengths[i], lengths[i + 1])) {
str[offset] = '0';
}
/* 9[.,]OOO.. */
if ((i > 1) &&
((lengths[i - 1] == 1 && str[offset - lengths[i - 1]] == '.') ||
(lengths[i - 1] == 1 && str[offset - lengths[i - 1]] == ',')) &&
(unicharset.get_isdigit (str + offset -
lengths[i - 1] - lengths[i - 2],
lengths[i - 2]) ||
(lengths[i - 2] == 1 &&
str[offset - lengths[i - 1] - lengths[i - 2]] == 'O'))) {
if (lengths[i - 2] == 1 &&
str[offset - lengths[i - 1] - lengths[i - 2]] == 'O')
str[offset - lengths[i - 1] - lengths[i - 2]] = '0';
while (lengths[i] == 1 &&
((str[offset] == 'O') || (str[offset] == '0'))) {
str[offset] = '0';
offset += lengths[i++];
}
i--;
offset -= lengths[i];
}
}
}
}
BOOL8 non_O_upper(const char* str, int length) {
return unicharset.get_isupper (str, length) &&
(!unicharset.eq(unicharset.unichar_to_id(str, length), "O"));
}
BOOL8 non_0_digit(const char* str, int length) {
return unicharset.get_isdigit (str, length) &&
(!unicharset.eq(unicharset.unichar_to_id(str, length), "0"));
}
| [
"josh@transfs.com"
] | josh@transfs.com |
b0708bb595013ba3a5a0e60758260f4ce7ad513a | 07c3e4c4f82056e76285c81f14ea0fbb263ed906 | /Re-Abyss/app/views/Actor/Ooparts/Nyan/NyanVM.cpp | 51e6a21792651b43b3e6a75d34aaac95b4172335 | [] | no_license | tyanmahou/Re-Abyss | f030841ca395c6b7ca6f9debe4d0de8a8c0036b5 | bd36687ddabad0627941dbe9b299b3c715114240 | refs/heads/master | 2023-08-02T22:23:43.867123 | 2023-08-02T14:20:26 | 2023-08-02T14:20:26 | 199,132,051 | 9 | 1 | null | 2021-11-22T20:46:39 | 2019-07-27T07:28:34 | C++ | UTF-8 | C++ | false | false | 659 | cpp | #include <abyss/views/Actor/Ooparts/Nyan/NyanVM.hpp>
#include <abyss/commons/Resource/Assets/Assets.hpp>
#include <Siv3D.hpp>
namespace abyss::Actor::Ooparts::Nyan
{
NyanVM::NyanVM():
m_texture(Resource::Assets::Main()->load(U"Actor/Ooparts/Nyan/Nyan.png"))
{}
void NyanVM::draw(const s3d::ColorF & color) const
{
bool isRight = m_forward.isRight();
int32 page = static_cast<int32>(Periodic::Square0_1(1s, m_time)) % 2;
m_texture({ 0, 20 * page }, { 20, 20 }).mirrored(isRight).drawAt(m_pos, color);
}
s3d::TextureRegion NyanVM::icon() const
{
return m_texture({ 0, 0 }, {20, 20});
}
}
| [
"tyanmahou@gmail.com"
] | tyanmahou@gmail.com |
c31aaa0f09f562e03b1e2cf2179fd1755483abce | 5ab00390e167637ba8d590910c34aff69330f1b3 | /0924/set.cpp | 1b2a8b3e1a270ab4f536a4fd7fd5983236fb92c2 | [] | no_license | ymelon7/Backup | 56d06ca3674ca52f7db345bcf149ce232243414a | f6ae41e1da7fece056f78ffa150384f1d4faa3f8 | refs/heads/master | 2021-01-10T21:06:30.804282 | 2014-11-24T14:35:23 | 2014-11-24T14:35:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 507 | cpp | /*************************************************************************
> File Name: set.cpp
> Author: Melon
> Mail:ymelon7@gmail.com
> Created Time: Fri 14 Nov 2014 04:29:47 AM PST
************************************************************************/
#include <iostream>
#include <set>
using namespace std;
int main (int argc, char *argv[])
{
set<int> t;
for(int cnt = 1; cnt < 20; cnt ++)
{
t.insert(cnt);
t.insert(cnt);
}
cout << t.size() << endl;
}
| [
"ymelon7@gmail.com"
] | ymelon7@gmail.com |
064d1fe83783b595ef4bc94258d88d8534e40f28 | 477101ffc26e052ef90e138f81e5b082d65a7dc5 | /tests/vulkan/ShaderTrace_Test4.cpp | bac36d5a19cd0df90c80a08b771c218c2c3e339c | [
"MIT"
] | permissive | azhirnov/glsl_trace | 1f7a5167f8969942f05848b7d71e22dedc0cfd6b | d6499dda98640d38cc7a918fae2209808bd6db24 | refs/heads/master | 2023-07-20T02:28:39.275964 | 2023-07-14T16:36:07 | 2023-07-14T16:36:07 | 252,840,675 | 31 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 6,951 | cpp | // Copyright (c) 2018-2020, Zhirnov Andrey. For more information see 'LICENSE'
#include "Device.h"
/*
=================================================
CompileShaders
=================================================
*/
static bool CompileShaders (Device &vulkan, OUT VkShaderModule &vertShader, OUT VkShaderModule &fragShader)
{
// create vertex shader
{
static const char vert_shader_source[] = R"#(
const vec2 g_Positions[] = {
{-1.0f, -1.0f}, {-1.0f, 2.0f}, {2.0f, -1.0f}, // primitive 0 - must hit
};
void main()
{
gl_Position = vec4( g_Positions[gl_VertexIndex], float(gl_VertexIndex) * 0.02f, 1.0f );
})#";
CHECK_ERR( vulkan.Compile( OUT vertShader, {vert_shader_source}, EShLangVertex ));
}
// create fragment shader
{
static const char frag_shader_source[] = R"#(
#extension GL_ARB_gpu_shader_int64 : require
layout(location = 0) out vec4 out_Color;
void main ()
{
uint64_t i = 0xFFFFFFFF00000000ul;
dvec2 d = dvec2(1.234e+50LF, 3.875732LF);
i |= 0xFFFFFFFFul;
d *= 2.0;
out_Color[0] = float(i);
out_Color[1] = float(d.x);
out_Color[2] = float(d.y);
})#";
CHECK_ERR( vulkan.Compile( OUT fragShader, {frag_shader_source}, EShLangFragment, ETraceMode::DebugTrace, 0 ));
}
return true;
}
/*
=================================================
ShaderTrace_Test4
=================================================
*/
extern bool ShaderTrace_Test4 (Device& vulkan)
{
if ( not (vulkan.deviceFeat.shaderFloat64 and vulkan.deviceFeat.shaderInt64) )
return true;
// create renderpass and framebuffer
uint width = 16, height = 16;
VkRenderPass render_pass;
VkImage color_target;
VkFramebuffer framebuffer;
CHECK_ERR( vulkan.CreateRenderTarget( VK_FORMAT_R8G8B8A8_UNORM, width, height, 0,
OUT render_pass, OUT color_target, OUT framebuffer ));
// create pipeline
VkShaderModule vert_shader, frag_shader;
CHECK_ERR( CompileShaders( vulkan, OUT vert_shader, OUT frag_shader ));
VkDescriptorSetLayout ds_layout;
VkDescriptorSet desc_set;
CHECK_ERR( vulkan.CreateDebugDescriptorSet( VK_SHADER_STAGE_FRAGMENT_BIT, OUT ds_layout, OUT desc_set ));
VkPipelineLayout ppln_layout;
VkPipeline pipeline;
CHECK_ERR( vulkan.CreateGraphicsPipelineVar1( vert_shader, frag_shader, ds_layout, render_pass, OUT ppln_layout, OUT pipeline ));
// build command buffer
VkCommandBufferBeginInfo begin = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, nullptr, VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, nullptr };
VK_CHECK( vulkan.vkBeginCommandBuffer( vulkan.cmdBuffer, &begin ));
// image layout undefined -> color_attachment
{
VkImageMemoryBarrier barrier = {};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.srcAccessMask = 0;
barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
barrier.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
barrier.image = color_target;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
vulkan.vkCmdPipelineBarrier( vulkan.cmdBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0,
0, nullptr, 0, nullptr, 1, &barrier);
}
// setup storage buffer
{
const uint data[] = { width/2, height/2 }; // selected pixel
vulkan.vkCmdFillBuffer( vulkan.cmdBuffer, vulkan.debugOutputBuf, sizeof(data), VK_WHOLE_SIZE, 0 );
vulkan.vkCmdUpdateBuffer( vulkan.cmdBuffer, vulkan.debugOutputBuf, 0, sizeof(data), data );
}
// debug output storage read/write after write
{
VkBufferMemoryBarrier barrier = {};
barrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
barrier.buffer = vulkan.debugOutputBuf;
barrier.offset = 0;
barrier.size = VK_WHOLE_SIZE;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
vulkan.vkCmdPipelineBarrier( vulkan.cmdBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0,
0, nullptr, 1, &barrier, 0, nullptr);
}
// begin render pass
{
VkClearValue clear_value = {{{ 0.0f, 0.0f, 0.0f, 1.0f }}};
VkRenderPassBeginInfo begin_rp = {};
begin_rp.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
begin_rp.framebuffer = framebuffer;
begin_rp.renderPass = render_pass;
begin_rp.renderArea = { {0,0}, {width, height} };
begin_rp.clearValueCount = 1;
begin_rp.pClearValues = &clear_value;
vulkan.vkCmdBeginRenderPass( vulkan.cmdBuffer, &begin_rp, VK_SUBPASS_CONTENTS_INLINE );
}
vulkan.vkCmdBindPipeline( vulkan.cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline );
vulkan.vkCmdBindDescriptorSets( vulkan.cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, ppln_layout, 0, 1, &desc_set, 0, nullptr );
// set dynamic states
{
VkViewport viewport = {};
viewport.x = 0.0f;
viewport.y = 0.0f;
viewport.width = float(width);
viewport.height = float(height);
viewport.minDepth = 0.0f;
viewport.maxDepth = 1.0f;
vulkan.vkCmdSetViewport( vulkan.cmdBuffer, 0, 1, &viewport );
VkRect2D scissor_rect = { {0,0}, {width, height} };
vulkan.vkCmdSetScissor( vulkan.cmdBuffer, 0, 1, &scissor_rect );
}
vulkan.vkCmdDraw( vulkan.cmdBuffer, 3, 1, 0, 0 );
vulkan.vkCmdEndRenderPass( vulkan.cmdBuffer );
// debug output storage read after write
{
VkBufferMemoryBarrier barrier = {};
barrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
barrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
barrier.buffer = vulkan.debugOutputBuf;
barrier.offset = 0;
barrier.size = VK_WHOLE_SIZE;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
vulkan.vkCmdPipelineBarrier( vulkan.cmdBuffer, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
0, nullptr, 1, &barrier, 0, nullptr);
}
// copy shader debug output into host visible memory
{
VkBufferCopy region = {};
region.srcOffset = 0;
region.dstOffset = 0;
region.size = vulkan.debugOutputSize;
vulkan.vkCmdCopyBuffer( vulkan.cmdBuffer, vulkan.debugOutputBuf, vulkan.readBackBuf, 1, ®ion );
}
VK_CHECK( vulkan.vkEndCommandBuffer( vulkan.cmdBuffer ));
// submit commands and wait
{
VkSubmitInfo submit = {};
submit.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit.commandBufferCount = 1;
submit.pCommandBuffers = &vulkan.cmdBuffer;
VK_CHECK( vulkan.vkQueueSubmit( vulkan.queue, 1, &submit, VK_NULL_HANDLE ));
VK_CHECK( vulkan.vkQueueWaitIdle( vulkan.queue ));
}
CHECK_ERR( vulkan.TestDebugTraceOutput( {frag_shader}, "ShaderTrace_Test4.txt" ));
vulkan.FreeTempHandles();
TEST_PASSED();
return true;
}
| [
"zh1dron@gmail.com"
] | zh1dron@gmail.com |
4bb8d36e05305e839edb5251ebc96b070b6de24d | 8a87f5b889a9ce7d81421515f06d9c9cbf6ce64a | /3rdParty/boost/1.78.0/boost/metaparse/v1/cpp11/nth_of_c.hpp | c8cc51dc93cd15c8b6c64509d0a66e0b83f9491b | [
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause",
"ICU",
"Zlib",
"GPL-1.0-or-later",
"OpenSSL",
"ISC",
"LicenseRef-scancode-gutenberg-2020",
"MIT",
"GPL-2.0-only",
"CC0-1.0",
"LicenseRef-scancode-autoconf-simple-exception",
"LicenseRef-scancode-pcre",
"Bison-exception-2.2",
"LicenseRef-scancode... | permissive | arangodb/arangodb | 0980625e76c56a2449d90dcb8d8f2c485e28a83b | 43c40535cee37fc7349a21793dc33b1833735af5 | refs/heads/devel | 2023-08-31T09:34:47.451950 | 2023-08-31T07:25:02 | 2023-08-31T07:25:02 | 2,649,214 | 13,385 | 982 | Apache-2.0 | 2023-09-14T17:02:16 | 2011-10-26T06:42:00 | C++ | UTF-8 | C++ | false | false | 1,112 | hpp | #ifndef BOOST_METAPARSE_V1_CPP11_NTH_OF_C_HPP
#define BOOST_METAPARSE_V1_CPP11_NTH_OF_C_HPP
// Copyright Abel Sinkovics (abel@sinkovics.hu) 2017.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/metaparse/v1/cpp11/impl/nth_of_c.hpp>
#include <boost/metaparse/v1/fail.hpp>
#include <boost/metaparse/v1/error/index_out_of_range.hpp>
#include <type_traits>
namespace boost
{
namespace metaparse
{
namespace v1
{
template <int N, class... Ps>
struct nth_of_c
{
typedef nth_of_c type;
template <class S, class Pos>
struct apply :
std::conditional<
(0 <= N && N < sizeof...(Ps)),
impl::nth_of_c<N, S, Pos, Ps...>,
typename fail<error::index_out_of_range<0, sizeof...(Ps) - 1, N>>
::template apply<S, Pos>
>::type
{};
};
template <int N>
struct nth_of_c<N> : fail<error::index_out_of_range<0, -1, N>> {};
}
}
}
#endif
| [
"noreply@github.com"
] | noreply@github.com |
798029f384f010b880e9a60c52250d6e666b1873 | 44b02905e5363c4a3e3bc6b7f94f8d1a9471a6db | /Interpreter/src/cell.h | e7bdb92dff9aa48b180ed0179cadd754249598f6 | [] | no_license | ghlin/grapha | c5abcdc3fd0f4bfa7e7988e57788165ec18787bf | f9df3df3ec19d3f524d11a7f0d8e8d24271511fb | refs/heads/master | 2022-04-08T12:50:17.058551 | 2020-02-03T07:52:16 | 2020-02-03T07:52:16 | 186,529,454 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,009 | h | #pragma once
#include "prelude.h"
#include "instruction.h"
namespace gi {
enum CellType { CT_HOLE
, CT_PRIM
, CT_PROC
, CT_PACK
, CT_APP
};
using cell_type_t = u32;
struct cell_s;
struct proc_s;
struct cell_field_list_s;
using cell_ref_t = cell_s *;
struct cell_data_s
{
union {
i32 val;
cell_s *fun;
char const *tag;
char const *name;
};
union {
cell_s *arg;
cell_field_list_s *pack;
proc_s const *proc;
};
};
struct cell_s
{
u32 t :4;
u32 gc_mark :4;
u32 id :24;
cell_data_s d;
};
struct cell_field_list_s
{
u32 arity;
u32 ref_count = 0;
cell_ref_t fields[];
};
extern std::string
pretty_print_cell_type(cell_type_t ty);
extern std::string
pretty_print_cell(cell_s const &cell);
extern std::string
pretty_print_tree(std::string const &leading, cell_ref_t root);
} // namespace gi
| [
"2012.2.9.ghl@gmail.com"
] | 2012.2.9.ghl@gmail.com |
d274c79b29c4583a7be908984f420b8bbe7e622a | b3710dfdd0eeb3e28d3a4c666af5df6558a03553 | /cgodeps/godot_engine/platform/windows/joypad_windows.cpp | d1454c909651a95d9e361605c71c7303cee07d05 | [
"MIT",
"LicenseRef-scancode-free-unknown",
"CC-BY-3.0",
"OFL-1.1",
"BSD-3-Clause",
"Bitstream-Vera",
"FTL",
"MPL-2.0",
"Zlib",
"LicenseRef-scancode-nvidia-2002",
"BSL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"CC-BY-4.0"
] | permissive | gabstv/godot-go | 5befd7539ef35a9e459046644dd4b246a0db1ad9 | e0e7f07e1e44716e18330f063c9b3fd3c2468d31 | refs/heads/master | 2021-05-21T23:48:25.434825 | 2020-08-27T16:52:18 | 2020-08-27T16:52:18 | 252,864,512 | 10 | 3 | MIT | 2020-08-27T16:52:20 | 2020-04-03T23:26:52 | C++ | UTF-8 | C++ | false | false | 17,457 | cpp | /*************************************************************************/
/* joypad_windows.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "joypad_windows.h"
#include <oleauto.h>
#include <wbemidl.h>
#if defined(__GNUC__)
// Workaround GCC warning from -Wcast-function-type.
#define GetProcAddress (void *)GetProcAddress
#endif
DWORD WINAPI _xinput_get_state(DWORD dwUserIndex, XINPUT_STATE *pState) {
return ERROR_DEVICE_NOT_CONNECTED;
}
DWORD WINAPI _xinput_set_state(DWORD dwUserIndex, XINPUT_VIBRATION *pVibration) {
return ERROR_DEVICE_NOT_CONNECTED;
}
JoypadWindows::JoypadWindows() {
}
JoypadWindows::JoypadWindows(HWND *hwnd) {
input = Input::get_singleton();
hWnd = hwnd;
joypad_count = 0;
dinput = nullptr;
xinput_dll = nullptr;
xinput_get_state = nullptr;
xinput_set_state = nullptr;
load_xinput();
for (int i = 0; i < JOYPADS_MAX; i++)
attached_joypads[i] = false;
HRESULT result = DirectInput8Create(GetModuleHandle(nullptr), DIRECTINPUT_VERSION, IID_IDirectInput8, (void **)&dinput, nullptr);
if (result == DI_OK) {
probe_joypads();
} else {
ERR_PRINT("Couldn't initialize DirectInput. Error: " + itos(result));
if (result == DIERR_OUTOFMEMORY) {
ERR_PRINT("The Windows DirectInput subsystem could not allocate sufficient memory.");
ERR_PRINT("Rebooting your PC may solve this issue.");
}
// Ensure dinput is still a nullptr.
dinput = nullptr;
}
}
JoypadWindows::~JoypadWindows() {
close_joypad();
if (dinput) {
dinput->Release();
}
unload_xinput();
}
bool JoypadWindows::have_device(const GUID &p_guid) {
for (int i = 0; i < JOYPADS_MAX; i++) {
if (d_joypads[i].guid == p_guid) {
d_joypads[i].confirmed = true;
return true;
}
}
return false;
}
// adapted from SDL2, works a lot better than the MSDN version
bool JoypadWindows::is_xinput_device(const GUID *p_guid) {
static GUID IID_ValveStreamingGamepad = { MAKELONG(0x28DE, 0x11FF), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } };
static GUID IID_X360WiredGamepad = { MAKELONG(0x045E, 0x02A1), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } };
static GUID IID_X360WirelessGamepad = { MAKELONG(0x045E, 0x028E), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } };
if (p_guid == &IID_ValveStreamingGamepad || p_guid == &IID_X360WiredGamepad || p_guid == &IID_X360WirelessGamepad)
return true;
PRAWINPUTDEVICELIST dev_list = nullptr;
unsigned int dev_list_count = 0;
if (GetRawInputDeviceList(nullptr, &dev_list_count, sizeof(RAWINPUTDEVICELIST)) == (UINT)-1) {
return false;
}
dev_list = (PRAWINPUTDEVICELIST)malloc(sizeof(RAWINPUTDEVICELIST) * dev_list_count);
if (!dev_list)
return false;
if (GetRawInputDeviceList(dev_list, &dev_list_count, sizeof(RAWINPUTDEVICELIST)) == (UINT)-1) {
free(dev_list);
return false;
}
for (unsigned int i = 0; i < dev_list_count; i++) {
RID_DEVICE_INFO rdi;
char dev_name[128];
UINT rdiSize = sizeof(rdi);
UINT nameSize = sizeof(dev_name);
rdi.cbSize = rdiSize;
if ((dev_list[i].dwType == RIM_TYPEHID) &&
(GetRawInputDeviceInfoA(dev_list[i].hDevice, RIDI_DEVICEINFO, &rdi, &rdiSize) != (UINT)-1) &&
(MAKELONG(rdi.hid.dwVendorId, rdi.hid.dwProductId) == (LONG)p_guid->Data1) &&
(GetRawInputDeviceInfoA(dev_list[i].hDevice, RIDI_DEVICENAME, &dev_name, &nameSize) != (UINT)-1) &&
(strstr(dev_name, "IG_") != nullptr)) {
free(dev_list);
return true;
}
}
free(dev_list);
return false;
}
bool JoypadWindows::setup_dinput_joypad(const DIDEVICEINSTANCE *instance) {
ERR_FAIL_NULL_V_MSG(dinput, false, "DirectInput not initialized. Rebooting your PC may solve this issue.");
HRESULT hr;
int num = input->get_unused_joy_id();
if (have_device(instance->guidInstance) || num == -1)
return false;
d_joypads[num] = dinput_gamepad();
dinput_gamepad *joy = &d_joypads[num];
const DWORD devtype = (instance->dwDevType & 0xFF);
if ((devtype != DI8DEVTYPE_JOYSTICK) && (devtype != DI8DEVTYPE_GAMEPAD) && (devtype != DI8DEVTYPE_1STPERSON)) {
return false;
}
hr = dinput->CreateDevice(instance->guidInstance, &joy->di_joy, nullptr);
if (FAILED(hr)) {
return false;
}
const GUID &guid = instance->guidProduct;
char uid[128];
ERR_FAIL_COND_V_MSG(memcmp(&guid.Data4[2], "PIDVID", 6), false, "DirectInput device not recognised.");
WORD type = BSWAP16(0x03);
WORD vendor = BSWAP16(LOWORD(guid.Data1));
WORD product = BSWAP16(HIWORD(guid.Data1));
WORD version = 0;
sprintf_s(uid, "%04x%04x%04x%04x%04x%04x%04x%04x", type, 0, vendor, 0, product, 0, version, 0);
id_to_change = num;
slider_count = 0;
joy->di_joy->SetDataFormat(&c_dfDIJoystick2);
joy->di_joy->SetCooperativeLevel(*hWnd, DISCL_FOREGROUND);
joy->di_joy->EnumObjects(objectsCallback, this, 0);
joy->joy_axis.sort();
joy->guid = instance->guidInstance;
input->joy_connection_changed(num, true, instance->tszProductName, uid);
joy->attached = true;
joy->id = num;
attached_joypads[num] = true;
joy->confirmed = true;
joypad_count++;
return true;
}
void JoypadWindows::setup_joypad_object(const DIDEVICEOBJECTINSTANCE *ob, int p_joy_id) {
if (ob->dwType & DIDFT_AXIS) {
HRESULT res;
DIPROPRANGE prop_range;
DIPROPDWORD dilong;
DWORD ofs;
if (ob->guidType == GUID_XAxis)
ofs = DIJOFS_X;
else if (ob->guidType == GUID_YAxis)
ofs = DIJOFS_Y;
else if (ob->guidType == GUID_ZAxis)
ofs = DIJOFS_Z;
else if (ob->guidType == GUID_RxAxis)
ofs = DIJOFS_RX;
else if (ob->guidType == GUID_RyAxis)
ofs = DIJOFS_RY;
else if (ob->guidType == GUID_RzAxis)
ofs = DIJOFS_RZ;
else if (ob->guidType == GUID_Slider) {
if (slider_count < 2) {
ofs = DIJOFS_SLIDER(slider_count);
slider_count++;
} else {
return;
}
} else
return;
prop_range.diph.dwSize = sizeof(DIPROPRANGE);
prop_range.diph.dwHeaderSize = sizeof(DIPROPHEADER);
prop_range.diph.dwObj = ob->dwType;
prop_range.diph.dwHow = DIPH_BYID;
prop_range.lMin = -MAX_JOY_AXIS;
prop_range.lMax = +MAX_JOY_AXIS;
dinput_gamepad &joy = d_joypads[p_joy_id];
res = IDirectInputDevice8_SetProperty(joy.di_joy, DIPROP_RANGE, &prop_range.diph);
if (FAILED(res))
return;
dilong.diph.dwSize = sizeof(dilong);
dilong.diph.dwHeaderSize = sizeof(dilong.diph);
dilong.diph.dwObj = ob->dwType;
dilong.diph.dwHow = DIPH_BYID;
dilong.dwData = 0;
res = IDirectInputDevice8_SetProperty(joy.di_joy, DIPROP_DEADZONE, &dilong.diph);
if (FAILED(res))
return;
joy.joy_axis.push_back(ofs);
}
}
BOOL CALLBACK JoypadWindows::enumCallback(const DIDEVICEINSTANCE *p_instance, void *p_context) {
JoypadWindows *self = (JoypadWindows *)p_context;
if (self->is_xinput_device(&p_instance->guidProduct)) {
return DIENUM_CONTINUE;
}
self->setup_dinput_joypad(p_instance);
return DIENUM_CONTINUE;
}
BOOL CALLBACK JoypadWindows::objectsCallback(const DIDEVICEOBJECTINSTANCE *instance, void *context) {
JoypadWindows *self = (JoypadWindows *)context;
self->setup_joypad_object(instance, self->id_to_change);
return DIENUM_CONTINUE;
}
void JoypadWindows::close_joypad(int id) {
if (id == -1) {
for (int i = 0; i < JOYPADS_MAX; i++) {
close_joypad(i);
}
return;
}
if (!d_joypads[id].attached)
return;
d_joypads[id].di_joy->Unacquire();
d_joypads[id].di_joy->Release();
d_joypads[id].attached = false;
attached_joypads[d_joypads[id].id] = false;
d_joypads[id].guid.Data1 = d_joypads[id].guid.Data2 = d_joypads[id].guid.Data3 = 0;
input->joy_connection_changed(d_joypads[id].id, false, "");
joypad_count--;
}
void JoypadWindows::probe_joypads() {
ERR_FAIL_NULL_MSG(dinput, "DirectInput not initialized. Rebooting your PC may solve this issue.");
DWORD dwResult;
for (DWORD i = 0; i < XUSER_MAX_COUNT; i++) {
ZeroMemory(&x_joypads[i].state, sizeof(XINPUT_STATE));
dwResult = xinput_get_state(i, &x_joypads[i].state);
if (dwResult == ERROR_SUCCESS) {
int id = input->get_unused_joy_id();
if (id != -1 && !x_joypads[i].attached) {
x_joypads[i].attached = true;
x_joypads[i].id = id;
x_joypads[i].ff_timestamp = 0;
x_joypads[i].ff_end_timestamp = 0;
x_joypads[i].vibrating = false;
attached_joypads[id] = true;
input->joy_connection_changed(id, true, "XInput Gamepad", "__XINPUT_DEVICE__");
}
} else if (x_joypads[i].attached) {
x_joypads[i].attached = false;
attached_joypads[x_joypads[i].id] = false;
input->joy_connection_changed(x_joypads[i].id, false, "");
}
}
for (int i = 0; i < joypad_count; i++) {
d_joypads[i].confirmed = false;
}
dinput->EnumDevices(DI8DEVCLASS_GAMECTRL, enumCallback, this, DIEDFL_ATTACHEDONLY);
for (int i = 0; i < joypad_count; i++) {
if (!d_joypads[i].confirmed) {
close_joypad(i);
}
}
}
void JoypadWindows::process_joypads() {
HRESULT hr;
for (int i = 0; i < XUSER_MAX_COUNT; i++) {
xinput_gamepad &joy = x_joypads[i];
if (!joy.attached) {
continue;
}
ZeroMemory(&joy.state, sizeof(XINPUT_STATE));
xinput_get_state(i, &joy.state);
if (joy.state.dwPacketNumber != joy.last_packet) {
int button_mask = XINPUT_GAMEPAD_DPAD_UP;
for (int j = 0; j <= 16; j++) {
input->joy_button(joy.id, j, joy.state.Gamepad.wButtons & button_mask);
button_mask = button_mask * 2;
}
input->joy_axis(joy.id, JOY_AXIS_LEFT_X, axis_correct(joy.state.Gamepad.sThumbLX, true));
input->joy_axis(joy.id, JOY_AXIS_LEFT_Y, axis_correct(joy.state.Gamepad.sThumbLY, true, false, true));
input->joy_axis(joy.id, JOY_AXIS_RIGHT_X, axis_correct(joy.state.Gamepad.sThumbRX, true));
input->joy_axis(joy.id, JOY_AXIS_RIGHT_Y, axis_correct(joy.state.Gamepad.sThumbRY, true, false, true));
input->joy_axis(joy.id, JOY_AXIS_TRIGGER_LEFT, axis_correct(joy.state.Gamepad.bLeftTrigger, true, true));
input->joy_axis(joy.id, JOY_AXIS_TRIGGER_RIGHT, axis_correct(joy.state.Gamepad.bRightTrigger, true, true));
joy.last_packet = joy.state.dwPacketNumber;
}
uint64_t timestamp = input->get_joy_vibration_timestamp(joy.id);
if (timestamp > joy.ff_timestamp) {
Vector2 strength = input->get_joy_vibration_strength(joy.id);
float duration = input->get_joy_vibration_duration(joy.id);
if (strength.x == 0 && strength.y == 0) {
joypad_vibration_stop_xinput(i, timestamp);
} else {
joypad_vibration_start_xinput(i, strength.x, strength.y, duration, timestamp);
}
} else if (joy.vibrating && joy.ff_end_timestamp != 0) {
uint64_t current_time = OS::get_singleton()->get_ticks_usec();
if (current_time >= joy.ff_end_timestamp)
joypad_vibration_stop_xinput(i, current_time);
}
}
for (int i = 0; i < JOYPADS_MAX; i++) {
dinput_gamepad *joy = &d_joypads[i];
if (!joy->attached)
continue;
DIJOYSTATE2 js;
hr = joy->di_joy->Poll();
if (hr == DIERR_INPUTLOST || hr == DIERR_NOTACQUIRED) {
IDirectInputDevice8_Acquire(joy->di_joy);
joy->di_joy->Poll();
}
hr = joy->di_joy->GetDeviceState(sizeof(DIJOYSTATE2), &js);
if (FAILED(hr)) {
continue;
}
post_hat(joy->id, js.rgdwPOV[0]);
for (int j = 0; j < 128; j++) {
if (js.rgbButtons[j] & 0x80) {
if (!joy->last_buttons[j]) {
input->joy_button(joy->id, j, true);
joy->last_buttons[j] = true;
}
} else {
if (joy->last_buttons[j]) {
input->joy_button(joy->id, j, false);
joy->last_buttons[j] = false;
}
}
}
// on mingw, these constants are not constants
int count = 8;
unsigned int axes[] = { DIJOFS_X, DIJOFS_Y, DIJOFS_Z, DIJOFS_RX, DIJOFS_RY, DIJOFS_RZ, DIJOFS_SLIDER(0), DIJOFS_SLIDER(1) };
int values[] = { js.lX, js.lY, js.lZ, js.lRx, js.lRy, js.lRz, js.rglSlider[0], js.rglSlider[1] };
for (int j = 0; j < joy->joy_axis.size(); j++) {
for (int k = 0; k < count; k++) {
if (joy->joy_axis[j] == axes[k]) {
input->joy_axis(joy->id, j, axis_correct(values[k]));
break;
};
};
};
}
return;
}
void JoypadWindows::post_hat(int p_device, DWORD p_dpad) {
int dpad_val = 0;
// Should be -1 when centered, but according to docs:
// "Some drivers report the centered position of the POV indicator as 65,535. Determine whether the indicator is centered as follows:
// BOOL POVCentered = (LOWORD(dwPOV) == 0xFFFF);"
// https://docs.microsoft.com/en-us/previous-versions/windows/desktop/ee416628(v%3Dvs.85)#remarks
if (LOWORD(p_dpad) == 0xFFFF) {
dpad_val = Input::HAT_MASK_CENTER;
}
if (p_dpad == 0) {
dpad_val = Input::HAT_MASK_UP;
} else if (p_dpad == 4500) {
dpad_val = (Input::HAT_MASK_UP | Input::HAT_MASK_RIGHT);
} else if (p_dpad == 9000) {
dpad_val = Input::HAT_MASK_RIGHT;
} else if (p_dpad == 13500) {
dpad_val = (Input::HAT_MASK_RIGHT | Input::HAT_MASK_DOWN);
} else if (p_dpad == 18000) {
dpad_val = Input::HAT_MASK_DOWN;
} else if (p_dpad == 22500) {
dpad_val = (Input::HAT_MASK_DOWN | Input::HAT_MASK_LEFT);
} else if (p_dpad == 27000) {
dpad_val = Input::HAT_MASK_LEFT;
} else if (p_dpad == 31500) {
dpad_val = (Input::HAT_MASK_LEFT | Input::HAT_MASK_UP);
}
input->joy_hat(p_device, dpad_val);
};
Input::JoyAxis JoypadWindows::axis_correct(int p_val, bool p_xinput, bool p_trigger, bool p_negate) const {
Input::JoyAxis jx;
if (Math::abs(p_val) < MIN_JOY_AXIS) {
jx.min = p_trigger ? 0 : -1;
jx.value = 0.0f;
return jx;
}
if (p_xinput) {
if (p_trigger) {
jx.min = 0;
jx.value = (float)p_val / MAX_TRIGGER;
return jx;
}
jx.min = -1;
if (p_val < 0) {
jx.value = (float)p_val / MAX_JOY_AXIS;
} else {
jx.value = (float)p_val / (MAX_JOY_AXIS - 1);
}
if (p_negate) {
jx.value = -jx.value;
}
return jx;
}
jx.min = -1;
jx.value = (float)p_val / MAX_JOY_AXIS;
return jx;
}
void JoypadWindows::joypad_vibration_start_xinput(int p_device, float p_weak_magnitude, float p_strong_magnitude, float p_duration, uint64_t p_timestamp) {
xinput_gamepad &joy = x_joypads[p_device];
if (joy.attached) {
XINPUT_VIBRATION effect;
effect.wLeftMotorSpeed = (65535 * p_strong_magnitude);
effect.wRightMotorSpeed = (65535 * p_weak_magnitude);
if (xinput_set_state(p_device, &effect) == ERROR_SUCCESS) {
joy.ff_timestamp = p_timestamp;
joy.ff_end_timestamp = p_duration == 0 ? 0 : p_timestamp + (uint64_t)(p_duration * 1000000.0);
joy.vibrating = true;
}
}
}
void JoypadWindows::joypad_vibration_stop_xinput(int p_device, uint64_t p_timestamp) {
xinput_gamepad &joy = x_joypads[p_device];
if (joy.attached) {
XINPUT_VIBRATION effect;
effect.wLeftMotorSpeed = 0;
effect.wRightMotorSpeed = 0;
if (xinput_set_state(p_device, &effect) == ERROR_SUCCESS) {
joy.ff_timestamp = p_timestamp;
joy.vibrating = false;
}
}
}
void JoypadWindows::load_xinput() {
xinput_get_state = &_xinput_get_state;
xinput_set_state = &_xinput_set_state;
xinput_dll = LoadLibrary("XInput1_4.dll");
if (!xinput_dll) {
xinput_dll = LoadLibrary("XInput1_3.dll");
if (!xinput_dll) {
xinput_dll = LoadLibrary("XInput9_1_0.dll");
}
}
if (!xinput_dll) {
print_verbose("Could not find XInput, using DirectInput only");
return;
}
XInputGetState_t func = (XInputGetState_t)GetProcAddress((HMODULE)xinput_dll, "XInputGetState");
XInputSetState_t set_func = (XInputSetState_t)GetProcAddress((HMODULE)xinput_dll, "XInputSetState");
if (!func || !set_func) {
unload_xinput();
return;
}
xinput_get_state = func;
xinput_set_state = set_func;
}
void JoypadWindows::unload_xinput() {
if (xinput_dll) {
FreeLibrary((HMODULE)xinput_dll);
}
}
| [
"gabs@gabs.tv"
] | gabs@gabs.tv |
90d56bff4f66cf0b5b444e89fd4143cf629c84e3 | c656ad53ecf35b511a078ff59014f828d6e963c1 | /Interpreter Project/Interpreter Project/Program.cpp | 5850c084a5685129e3a5e87ee53092f57d1d5199 | [] | no_license | lewisjnewman/2017-18_A-level-project | fc4064e26d78714b5fa27daa7de0a695f6144aa6 | 60aa62d6c696aeb3c262bf35f0383c97669c3588 | refs/heads/master | 2023-04-10T01:42:38.260486 | 2021-04-06T22:55:45 | 2021-04-06T22:55:45 | 293,648,932 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,156 | cpp | #include "Program.hpp"
#include "Interpreter.hpp"
#include <chrono>
#include <thread>
//Methods
Value Program::Delay(std::vector<Value> args, bool& error, std::string& error_message) {
if (args.size() != 1) {
error = true;
error_message = "Program Error - Program.Delay Expected 1 argument but was passed " + std::to_string(args.size());
return Value();
}
if (args[0].Get_Type() == Value::INT) {
std::this_thread::sleep_for(std::chrono::milliseconds(args[0].Get_Int()));
return Value();
}
else if (args[0].Get_Type() == Value::FLOAT) {
std::this_thread::sleep_for(std::chrono::milliseconds((int64_t)args[0].Get_Float()));
return Value();
}
else {
error = true;
error_message = "Program Error - Program.Delay Type mismatch with arguments";
return Value();
}
}
Value Program::End(std::vector<Value> args, bool& error, std::string& error_message) {
if (args.size() != 0) {
error = true;
error_message = "Program Error - Program.End Expected no arguments but was passed " + std::to_string(args.size());
return Value();
}
Interpreter::GetInterpreter()->Stop();
return Value();
}
| [
"lewis.newman.uk@gmail.com"
] | lewis.newman.uk@gmail.com |
cd529d727ac39905ce013c7276da2f6316d4cb3c | 9c249a7e5a704c4850fe7b760f37502382094f5f | /voltage_divider.ino | 0e126448b3d05c4d327f21a90cedf5fbfb0fe680 | [] | no_license | troncart/Unknown-Resistance-calculator | a7de4e17392a8fcca56a97687e2c4cbbb9e6fa23 | 13816806c565075c8113283c04ab92a66f0d322a | refs/heads/master | 2020-06-20T12:49:33.103733 | 2019-07-16T05:49:29 | 2019-07-16T05:49:29 | 197,128,455 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 656 | ino | /*********TACHLOG powered********
*********www.troncart.com*******
**electronics components online**
***********Voltage divider**************
***********16-07-2019**************
*/
int value = 0;
int Vin= 5; //The input voltage is 5 Volt
float Vout= 0;
float R1= 1000;
float R2= 0;
float buffer= 0;
void setup()
{
Serial.begin(9600);
}
void loop()
{
value = analogRead(A0); //reading the analog pin
if(value)
{
buffer= value * Vin;
Vout= (buffer)/1024.0;
buffer= (Vin/Vout) -1;
R2= R1 * buffer;
Serial.print("Vout: ");
Serial.println(Vout); //output voltage across R2
Serial.print("R2: ");
Serial.println(R2); //Unknown resistor value
delay(1000);
}
}
| [
"47349813+troncart@users.noreply.github.com"
] | 47349813+troncart@users.noreply.github.com |
660fffae2cf328c63309d4e459c32fee82fc8c90 | 46f61fcf9678018fcc2c88f89342e60fa484e28e | /GoalCell.cpp | 5688f8a66c7f79164f038d1bd87bff5891f786f6 | [] | no_license | dohahosam/Packman-Game | 2e4f42669cb22c263dd603a9d586a236a8739a3c | 858ba47b0d4bb32e4289050d88a6e29516db5c48 | refs/heads/main | 2023-03-07T11:41:05.655914 | 2021-02-23T10:41:31 | 2021-02-23T10:41:31 | 341,519,003 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 443 | cpp | #include "GoalCell.h"
GoalCell::GoalCell(int row, int col) :Cell(row, col)
{
ImagePath = "images\\Cells\\GoalCell.jpg";
}
GoalCell::GoalCell(Cell * old) : Cell(old->getRow(), old->getCol()) {
ImagePath = "images\\Cells\\GoalCell.jpg";
}
GoalCell::~GoalCell(void)
{
}
bool GoalCell::ActOn(Player* p)
{
//Empty cell takes no action on player
//it returns true as it is NOT an obstacle cell
return true;
}
| [
"noreply@github.com"
] | noreply@github.com |
09d1af23c15bcda45eca4e704b2da47df8da2ee9 | bd3630cebd53befb1c5ba3f4281eff3f4503b991 | /VS 2019/Arduino/new_LMDZ/valuesPrint.cpp | 866dfc4271d3cc2c0e118c53fab2134d4cc52ad2 | [] | no_license | YeungShaoFeng/FIlesBackUps | e4dd3d9082049c1caa913a3c11c9e94955d4720c | 9d1b10fdfe3a6acc0a1aad082127f431e718dd9b | refs/heads/master | 2020-09-07T12:34:24.159158 | 2019-11-22T01:37:59 | 2019-11-22T01:37:59 | 220,781,495 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 581 | cpp | #include <HardwareSerial.h>
#include "pre_def.h"
#include "mystructs.h"
#include "valuesPrint.h"
void valuesPrint(sensor *sen1, sensor *sen2) {
Serial.print(" ");
stepPrint_a(sen1);
stepPrint_b(sen1);
if (sen2 != NULL) {
stepPrint_a(sen2);
stepPrint_b(sen2);
}
}
void stepPrint_a(sensor* sen) {
int i;
for (i = 0; i < length; i++) {
Serial.print(sen->values_a[i]);
Serial.print(",");
}
Serial.println();
}
void stepPrint_b(sensor* sen) {
int i;
for (i = 0; i < length; i++) {
Serial.print(sen->values_b[i]);
Serial.print(",");
}
Serial.println();
} | [
"2013114698@qq.com"
] | 2013114698@qq.com |
aef6f3cfe857ca664b424bd4484e5a21dc01e8ef | 860b066d88e6b342c33bcec58171d9b714ee2b3b | /src/Reader/ReaderBase.cpp | 97cc45f4a9f8831947cb60e1c64c0506627ba491 | [] | no_license | siklosid/co-cluster | 1924567124163daada837221ff9eeb0f0d6d8c71 | 08c9afff01b78e501680a0c739126a14f5463615 | refs/heads/master | 2021-01-10T03:20:32.107828 | 2015-11-21T18:05:49 | 2015-11-21T18:05:49 | 46,627,261 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 525 | cpp | #include "ReaderBase.h"
ReaderBase::ReaderBase(uint32_t num_lines, Data<double>* data,
ReaderControl *reader_control) :
has_more_lines_(true),
data_(data),
reader_control_(reader_control),
num_lines_(num_lines) {
}
void ReaderBase::Main() {
log_dbg("start reading");
if (has_more_lines_) {
log_fdbg("Asking for reading")
reader_control_->CanIRead();
Read(num_lines_);
log_fdbg("Signs that finished reading");
reader_control_->FinishedRead();
} else {
Stop();
}
}
| [
"david.siklosi@prezi.com"
] | david.siklosi@prezi.com |
3adb5d975c863477846d24f41d01ecea41c51f05 | a67aff40080148e6ef791cae0a983d3dfc51a3e5 | /LeetCode/tags/array/add-to-array-form-of-integer.cpp | daafd22661f0a94aa5c4c9ff3b80059fa75f56cb | [] | no_license | llenroc/CP | 622b97676dafc80dbcb7054977fcb73702f370fe | fa4c5160f37b6cc550b062bf77b17b0484efc671 | refs/heads/master | 2023-03-28T17:25:28.548230 | 2021-04-06T11:09:14 | 2021-04-06T11:09:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 697 | cpp | #include<bits/stdc++.h>
using namespace std;
#define endl '\n'
#define MOD 1000000007
typedef vector<int> vi;
typedef vector<vector<int>> vii;
class Solution {
public:
vector<int> addToArrayForm(vector<int>& A, int K) {
reverse(A.begin(), A.end()); int carry=0, d=0, s=0;
for(auto &x:A) {
d = K % 10; K = K/10;
s = x + carry + d;
x = s % 10;
carry = s / 10;
}
while (K>0) {
d = K % 10; K = K/10;
s = carry + d;
A.push_back(s % 10);
carry = s/10;
}
if(carry > 0) A.push_back(carry);
reverse(A.begin(), A.end());
return A;
}
};
| [
"jitendra.iitp@gmail.com"
] | jitendra.iitp@gmail.com |
9e5499e23dcac066281c64c4e93cdec4030956bb | 985139aa62f1e4c20d0495c2d689ceecd6259ba9 | /dev_workspace/build/message_pkg/rosidl_typesupport_opensplice_cpp/message_pkg/msg/dds_opensplice/Num_SplDcps.cpp | 598f3f387e9450c0db993df762eca1054182bdee | [] | no_license | oskolss/WaveRunner2021 | b59c3bddfeda31c60f80389a20d7800d6df6aea0 | 13e199788c1849adca72e4a163f1fe27254f8665 | refs/heads/master | 2023-04-19T15:28:03.672327 | 2021-05-05T12:49:26 | 2021-05-05T12:49:26 | 343,691,827 | 0 | 0 | null | 2021-03-02T10:02:54 | 2021-03-02T08:01:17 | null | UTF-8 | C++ | false | false | 783 | cpp | #include "Num_SplDcps.h"
#include "ccpp_Num_.h"
#include <v_copyIn.h>
#include <v_topic.h>
#include <os_stdlib.h>
#include <string.h>
#include <os_report.h>
v_copyin_result
__message_pkg_msg_dds__Num___copyIn(
c_base base,
const struct ::message_pkg::msg::dds_::Num_ *from,
struct _message_pkg_msg_dds__Num_ *to)
{
v_copyin_result result = V_COPYIN_RESULT_OK;
(void) base;
to->num_ = (c_longlong)from->num_;
return result;
}
void
__message_pkg_msg_dds__Num___copyOut(
const void *_from,
void *_to)
{
const struct _message_pkg_msg_dds__Num_ *from = (const struct _message_pkg_msg_dds__Num_ *)_from;
struct ::message_pkg::msg::dds_::Num_ *to = (struct ::message_pkg::msg::dds_::Num_ *)_to;
to->num_ = (::DDS::LongLong)from->num_;
}
| [
"oskolss@student.chalmers.se"
] | oskolss@student.chalmers.se |
a2b7e9de32950cfabbb9acd16045a564b33e0c91 | 6c4e0336ea7a314dda84655ccdf140c012ea0607 | /SevenServer/net/SocketManager.cpp | 2be03e7fbf2bff6e407fc0361f2b8b809464ce68 | [] | no_license | youngtry/SevenServer | 2edc6c61def8bb6899a901486da4ab55badfa970 | a83bf7874f33385413b7994290df7149c7fe1013 | refs/heads/master | 2020-09-23T01:28:43.754942 | 2016-09-11T15:32:20 | 2016-09-11T15:32:20 | 67,788,551 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 918 | cpp | //
// SocketManager.cpp
// SevenClient
//
// Created by TianRunyan on 16/9/11.
//
//
#include "../lib/common.h"
void testNet(){
int listenfd,connfd;
pid_t childpid;
socklen_t chilen;
struct sockaddr_in chiladdr,servaddr;
listenfd = Socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERV_PORT);
Bind(listenfd, (SA *)&servaddr, sizeof(servaddr));
Listen(listenfd, LISTENQ);
while(true){
chilen = sizeof(chiladdr);
connfd = Accept(listenfd, (SA *)&chiladdr, &chilen);
printf("accpet");
if((childpid = Fork()) == 0){
printf("fork()");
Close(childpid);
str_echo(connfd);
exit(0);
}
Close(connfd);
}
} | [
"tianrunyan@TianRunyandeMacBook-Pro.local"
] | tianrunyan@TianRunyandeMacBook-Pro.local |
2e90c176a9e7c6990cd119ccfa1060bfd18fac04 | 340af75c93896609307208c7ca169086697f1629 | /src/MycParam.cpp | c027d7ad9bd6c4e0e41c0e20e6f65964be51d7e9 | [] | no_license | QuotationCitation/CSE2-Hard | 70c9a041e8649a5bf3d883c439f2c88b03c3bfe1 | ba8acc9edf7186978e601fac7236356c99349372 | refs/heads/master | 2022-11-16T04:23:17.713683 | 2020-07-10T14:58:25 | 2020-07-10T14:58:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,883 | cpp | #include "MycParam.h"
#include <stdio.h>
#include "WindowsWrapper.h"
#include "ArmsItem.h"
#include "CommonDefines.h"
#include "Caret.h"
#include "Draw.h"
#include "File.h"
#include "Game.h"
#include "Main.h"
#include "MyChar.h"
#include "NpChar.h"
#include "Sound.h"
#include "TextScr.h"
#include "ValueView.h"
ARMS_LEVEL gArmsLevelTable[14] =
{
{{0, 0, 100}},
{{30, 40, 16}},
{{10, 20, 10}},
{{10, 20, 20}},
{{30, 40, 10}},
{{10, 20, 10}},
{{10, 20, 30}},
{{10, 20, 5}},
{{10, 20, 100}},
{{30, 60, 0}},
{{30, 60, 10}},
{{10, 20, 100}},
{{1, 1, 1}},
{{40, 60, 200}}
};
void AddExpMyChar(int x)
{
int lv = gArmsData[gSelectedArms].level - 1;
int arms_code = gArmsData[gSelectedArms].code;
gArmsData[gSelectedArms].exp += x;
if (lv == 2)
{
if (gArmsData[gSelectedArms].exp >= gArmsLevelTable[arms_code].exp[lv])
{
gArmsData[gSelectedArms].exp = gArmsLevelTable[arms_code].exp[lv];
if (gMC.equip & 0x80)
{
if (gMC.star < 3)
++gMC.star;
}
}
}
else
{
for (; lv < 2; ++lv)
{
if (gArmsData[gSelectedArms].exp >= gArmsLevelTable[arms_code].exp[lv])
{
++gArmsData[gSelectedArms].level;
gArmsData[gSelectedArms].exp = 0;
if (gArmsData[gSelectedArms].code != 13)
{
PlaySoundObject(27, 1);
SetCaret(gMC.x, gMC.y, 10, 0);
}
}
}
}
if (gArmsData[gSelectedArms].code != 13)
{
gMC.exp_count += x;
gMC.exp_wait = 30;
}
else
{
gMC.exp_wait = 10;
}
}
void ZeroExpMyChar(void)
{
gArmsData[gSelectedArms].level = 1;
gArmsData[gSelectedArms].exp = 0;
}
BOOL IsMaxExpMyChar(void)
{
int arms_code;
if (gArmsData[gSelectedArms].level == 3)
{
arms_code = gArmsData[gSelectedArms].code;
if (gArmsData[gSelectedArms].exp >= gArmsLevelTable[arms_code].exp[2])
return TRUE;
}
return FALSE;
}
void DamageMyChar(int damage)
{
#ifdef FIX_BUGS
if (!(g_GameFlags & 2))
#else
// I'm preeeetty sure this is a typo. The Linux port optimised it out.
if (!(g_GameFlags | 2))
#endif
return;
if (gMC.shock)
return;
// Damage player
PlaySoundObject(16, 1);
gMC.cond &= ~1;
gMC.shock = 128;
if (gMC.unit == 1)
{
// Another weird case where there *has* to be an empty 'if' here to produce the same assembly.
// Chances are there used to be some commented-out code here.
}
else
{
gMC.ym = -0x400;
}
gMC.life -= (short)damage * 2;
// Lose a whimsical star
if (gMC.equip & 0x80 && gMC.star > 0)
gMC.star = (short)gMC.star - 1; // For some reason, this does a cast to short. Might not be accurate to the original source code (possibly, Pixel was just being careful about int size/conversion, or this is from some weird macro)
// Lose experience
if (gMC.equip & 4)
gArmsData[gSelectedArms].exp -= damage * 3;
else
gArmsData[gSelectedArms].exp -= damage * 6;
while (gArmsData[gSelectedArms].exp < 0)
{
if (gArmsData[gSelectedArms].level > 1)
{
--gArmsData[gSelectedArms].level;
int lv = gArmsData[gSelectedArms].level - 1;
int arms_code = gArmsData[gSelectedArms].code;
gArmsData[gSelectedArms].exp = gArmsLevelTable[arms_code].exp[lv] + gArmsData[gSelectedArms].exp;
if (gMC.life > 0 && gArmsData[gSelectedArms].code != 13)
SetCaret(gMC.x, gMC.y, 10, 2);
}
else
{
gArmsData[gSelectedArms].exp = 0;
}
}
// Tell player how much damage was taken
SetValueView(&gMC.x, &gMC.y, -damage * 2);
// Death
if (gMC.life <= 0)
{
PlaySoundObject(17, 1);
gMC.cond = 0;
SetDestroyNpChar(gMC.x, gMC.y, 0x1400, 0x40);
StartTextScript(40);
}
}
void ZeroArmsEnergy_All(void)
{
int a;
for (a = 0; a < ARMS_MAX; a++)
{
gArmsData[a].level = 1;
gArmsData[a].exp = 0;
}
}
void AddBulletMyChar(int no, int val)
{
int a;
// Missile Launcher
a = 0;
while (a < ARMS_MAX && gArmsData[a].code != 5)
++a;
if (a == ARMS_MAX)
{
// Super Missile Launcher
a = 0;
while (a < ARMS_MAX && gArmsData[a].code != 10)
++a;
if (a == ARMS_MAX)
return;
}
gArmsData[a].num += val;
if (gArmsData[a].num > gArmsData[a].max_num)
gArmsData[a].num = gArmsData[a].max_num;
}
void AddLifeMyChar(int x)
{
gMC.life += (short)x;
if (gMC.life > gMC.max_life)
gMC.life = gMC.max_life;
gMC.lifeBr = gMC.life;
}
void AddMaxLifeMyChar(int val)
{
gMC.max_life += (short)val;
if (gMC.max_life > 232)
gMC.max_life = 232;
gMC.life += (short)val;
gMC.lifeBr = gMC.life;
}
void PutArmsEnergy(BOOL flash)
{
static unsigned char add_flash;
RECT rcPer = {72, 48, 80, 56};
RECT rcLv = {80, 80, 96, 88};
RECT rcView = {0, 0, WINDOW_WIDTH, WINDOW_HEIGHT};
RECT rcNone = {80, 48, 96, 56};
if (gArmsEnergyX > 16)
gArmsEnergyX -= 2;
if (gArmsEnergyX < 16)
gArmsEnergyX += 2;
// Draw max ammo
if (gArmsData[gSelectedArms].max_num)
{
PutNumber4(gArmsEnergyX + 32, 16, gArmsData[gSelectedArms].num, FALSE);
PutNumber4(gArmsEnergyX + 32, 24, gArmsData[gSelectedArms].max_num, FALSE);
}
else
{
PutBitmap3(&rcView, PixelToScreenCoord(gArmsEnergyX + 48), PixelToScreenCoord(16), &rcNone, SURFACE_ID_TEXT_BOX);
PutBitmap3(&rcView, PixelToScreenCoord(gArmsEnergyX + 48), PixelToScreenCoord(24), &rcNone, SURFACE_ID_TEXT_BOX);
}
// Draw experience and ammo
if (flash == TRUE && (gMC.shock / 2) % 2)
return;
PutBitmap3(&rcView, PixelToScreenCoord(gArmsEnergyX + 32), PixelToScreenCoord(24), &rcPer, SURFACE_ID_TEXT_BOX);
PutBitmap3(&rcView, PixelToScreenCoord(gArmsEnergyX), PixelToScreenCoord(32), &rcLv, SURFACE_ID_TEXT_BOX);
PutNumber4(gArmsEnergyX - 8, 32, gArmsData[gSelectedArms].level, FALSE);
RECT rcExpBox = {0, 72, 40, 80};
RECT rcExpVal = {0, 80, 0, 88};
RECT rcExpMax = {40, 72, 80, 80};
RECT rcExpFlash = {40, 80, 80, 88};
int lv = gArmsData[gSelectedArms].level - 1;
if (lv < 0) // Detect the case where the level is 0 (no weapon)
lv = 0; // Set lv to a safe value
int arms_code = gArmsData[gSelectedArms].code;
int exp_now = gArmsData[gSelectedArms].exp;
int exp_next = gArmsLevelTable[arms_code].exp[lv];
PutBitmap3(&rcView, PixelToScreenCoord(gArmsEnergyX + 24), PixelToScreenCoord(32), &rcExpBox, SURFACE_ID_TEXT_BOX);
if (lv == 2 && gArmsData[gSelectedArms].exp == gArmsLevelTable[arms_code].exp[lv])
{
PutBitmap3(&rcView, PixelToScreenCoord(gArmsEnergyX + 24), PixelToScreenCoord(32), &rcExpMax, SURFACE_ID_TEXT_BOX);
}
else
{
if (exp_next != 0)
rcExpVal.right += (exp_now * 40) / exp_next;
else
rcExpVal.right = 0;
PutBitmap3(&rcView, PixelToScreenCoord(gArmsEnergyX + 24), PixelToScreenCoord(32), &rcExpVal, SURFACE_ID_TEXT_BOX);
}
if (gMC.exp_wait && ((add_flash++ / 2) % 2))
PutBitmap3(&rcView, PixelToScreenCoord(gArmsEnergyX + 24), PixelToScreenCoord(32), &rcExpFlash, SURFACE_ID_TEXT_BOX);
}
void PutActiveArmsList(void)
{
int x;
int a;
RECT rect = {0, 0, 0, 16};
int arms_num = 0;
while (gArmsData[arms_num].code != 0)
++arms_num;
if (arms_num == 0)
return;
for (a = 0; a < arms_num; ++a)
{
// Get X position to draw at
x = ((a - gSelectedArms) * 16) + gArmsEnergyX;
if (x < 8)
x += 48 + (arms_num * 16);
else if (x >= 24)
x += 48;
if (x >= 72 + ((arms_num - 1) * 16))
x -= 48 + (arms_num * 16);
if (x < 72 && x >= 24)
x -= 48;
// Draw icon
rect.left = gArmsData[a].code * 16;
rect.right = rect.left + 16;
PutBitmap3(&grcGame, PixelToScreenCoord(x), PixelToScreenCoord(16), &rect, SURFACE_ID_ARMS_IMAGE);
}
}
void PutMyLife(BOOL flash)
{
RECT rcCase = {0, 40, 232, 48};
RECT rcLife = {0, 24, 232, 32};
RECT rcBr = {0, 32, 232, 40};
if (flash == TRUE && gMC.shock / 2 % 2)
return;
if (gMC.lifeBr < gMC.life)
gMC.lifeBr = gMC.life;
if (gMC.lifeBr > gMC.life)
{
if (++gMC.lifeBr_count > 30)
--gMC.lifeBr;
}
else
{
gMC.lifeBr_count = 0;
}
// Draw bar
rcCase.right = 64;
rcLife.right = ((gMC.life * 40) / gMC.max_life) - 1;
rcBr.right = ((gMC.lifeBr * 40) / gMC.max_life) - 1;
PutBitmap3(&grcGame, PixelToScreenCoord(16), PixelToScreenCoord(40), &rcCase, SURFACE_ID_TEXT_BOX);
PutBitmap3(&grcGame, PixelToScreenCoord(40), PixelToScreenCoord(40), &rcBr, SURFACE_ID_TEXT_BOX);
PutBitmap3(&grcGame, PixelToScreenCoord(40), PixelToScreenCoord(40), &rcLife, SURFACE_ID_TEXT_BOX);
PutNumber4(8, 40, gMC.lifeBr, FALSE);
}
void PutMyAir(int x, int y)
{
RECT rcAir[2] = {
{112, 72, 144, 80},
{112, 80, 144, 88},
};
if (gMC.no_splash_or_air_limit_underwater)
return;
if (gMC.equip & 0x10)
return;
if (gMC.air_get != 0)
{
// Draw how much air is left
if (gMC.air_get % 6 < 4)
PutNumber4(x + 32, y, gMC.air / 10, FALSE);
// Draw "AIR" text
if (gMC.air % 30 > 10)
PutBitmap3(&grcGame, PixelToScreenCoord(x), PixelToScreenCoord(y), &rcAir[0], SURFACE_ID_TEXT_BOX);
else
PutBitmap3(&grcGame, PixelToScreenCoord(x), PixelToScreenCoord(y), &rcAir[1], SURFACE_ID_TEXT_BOX);
}
}
static int time_count;
void PutTimeCounter(int x, int y)
{
RECT rcTime[3] = {
{112, 104, 120, 112},
{120, 104, 128, 112},
{128, 104, 160, 112},
};
if (gMC.equip & 0x100)
{
// Draw clock and increase time
if (g_GameFlags & 2)
{
if (time_count < 100 * 60 * (gb60fps ? 60 : 50)) // 100 minutes
++time_count;
if (time_count % 30 > 10)
PutBitmap3(&grcGame, PixelToScreenCoord(x), PixelToScreenCoord(y), &rcTime[0], SURFACE_ID_TEXT_BOX);
else
PutBitmap3(&grcGame, PixelToScreenCoord(x), PixelToScreenCoord(y), &rcTime[1], SURFACE_ID_TEXT_BOX);
}
else
{
PutBitmap3(&grcGame, PixelToScreenCoord(x), PixelToScreenCoord(y), &rcTime[0], SURFACE_ID_TEXT_BOX);
}
// Draw time
if (gb60fps)
{
PutNumber4(x, y, time_count / (60 * 60), FALSE);
PutNumber4(x + 20, y, time_count / 60 % 60, TRUE);
PutNumber4(x + 32, y, time_count / 6 % 10, FALSE);
}
else
{
PutNumber4(x, y, time_count / (60 * 50), FALSE);
PutNumber4(x + 20, y, time_count / 50 % 60, TRUE);
PutNumber4(x + 32, y, time_count / 5 % 10, FALSE);
}
PutBitmap3(&grcGame, PixelToScreenCoord(x + 30), PixelToScreenCoord(y), &rcTime[2], SURFACE_ID_TEXT_BOX);
}
else
{
time_count = 0;
}
}
BOOL SaveTimeCounter(void)
{
int i;
unsigned char p[4];
REC rec;
FILE *fp;
char path[MAX_PATH];
// Quit if player doesn't have the Nikumaru Counter
if (!(gMC.equip & 0x100))
return TRUE;
// Get last time
sprintf(path, "%s/290.rec", gModulePath);
fp = fopen(path, "rb");
if (fp != NULL)
{
// Read data
rec.counter[0] = File_ReadLE32(fp);
rec.counter[1] = File_ReadLE32(fp);
rec.counter[2] = File_ReadLE32(fp);
rec.counter[3] = File_ReadLE32(fp);
rec.random[0] = fgetc(fp);
rec.random[1] = fgetc(fp);
rec.random[2] = fgetc(fp);
rec.random[3] = fgetc(fp);
fclose(fp);
p[0] = (unsigned char)(rec.counter[0] - rec.random[0]);
p[1] = (unsigned char)((rec.counter[0] >> 8) - rec.random[0]);
p[2] = (unsigned char)((rec.counter[0] >> 16) - rec.random[0]);
p[3] = (unsigned char)((rec.counter[0] >> 24) - rec.random[0] / 2);
rec.counter[0] = p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
// If this is faster than our new time, quit
if (rec.counter[0] < time_count)
return TRUE;
}
// Save new time
for (i = 0; i < 4; ++i)
{
rec.counter[i] = time_count;
rec.random[i] = Random(0, 250) + i;
p[0] = (unsigned char)(rec.counter[i] + rec.random[i]);
p[1] = (unsigned char)((rec.counter[i] >> 8) + rec.random[i]);
p[2] = (unsigned char)((rec.counter[i] >> 16) + rec.random[i]);
p[3] = (unsigned char)((rec.counter[i] >> 24) + rec.random[i] / 2);
rec.counter[i] = p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
}
fp = fopen(path, "wb");
if (fp == NULL)
return FALSE;
File_WriteLE32(rec.counter[0], fp);
File_WriteLE32(rec.counter[1], fp);
File_WriteLE32(rec.counter[2], fp);
File_WriteLE32(rec.counter[3], fp);
fputc(rec.random[0], fp);
fputc(rec.random[1], fp);
fputc(rec.random[2], fp);
fputc(rec.random[3], fp);
fclose(fp);
return TRUE;
}
int LoadTimeCounter(void)
{
int i;
unsigned char p[4];
REC rec;
FILE *fp;
char path[MAX_PATH];
// Open file
sprintf(path, "%s/290.rec", gModulePath);
fp = fopen(path, "rb");
if (fp == NULL)
return 0;
// Read data
rec.counter[0] = File_ReadLE32(fp);
rec.counter[1] = File_ReadLE32(fp);
rec.counter[2] = File_ReadLE32(fp);
rec.counter[3] = File_ReadLE32(fp);
rec.random[0] = fgetc(fp);
rec.random[1] = fgetc(fp);
rec.random[2] = fgetc(fp);
rec.random[3] = fgetc(fp);
fclose(fp);
// Decode from checksum
for (i = 0; i < 4; ++i)
{
p[0] = (unsigned char)(rec.counter[i] - rec.random[i]);
p[1] = (unsigned char)((rec.counter[i] >> 8) - rec.random[i]);
p[2] = (unsigned char)((rec.counter[i] >> 16) - rec.random[i]);
p[3] = (unsigned char)((rec.counter[i] >> 24) - rec.random[i] / 2);
rec.counter[i] = p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
}
// Verify checksum's result
if (rec.counter[0] != rec.counter[1] || rec.counter[0] != rec.counter[2])
{
time_count = 0;
return 0;
}
time_count = rec.counter[0];
return time_count;
}
| [
"42366259+Bryce101189@users.noreply.github.com"
] | 42366259+Bryce101189@users.noreply.github.com |
7d6c324ddfc8f8ba7f35751c9fa79facf39c9e3b | 830a83f0ef9b16b2cc5b236960477c380bf3ac6e | /CSL/Spatializers/VBAP/DelayLine.cpp | 9512f60ef33c7573b095461adcb7465eaf21520c | [] | no_license | eriser/CSL | a085f59d9e25e62ed271ec7d4dd6860d09bd6a45 | 6f4646369f0c90ea90e2c113374044818ab37ded | refs/heads/master | 2020-06-08T03:06:15.678916 | 2013-09-24T17:02:29 | 2013-09-24T17:02:29 | 35,820,808 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,424 | cpp | //
// DLine.h -- an Interpolating Delay Line
// See the copyright notice and acknowledgment of authors in the file COPYRIGHT
//
// This is a typical circular buffer with one writer and multiple readers (tap instances)
#include "DelayLine.h"
using namespace csl;
// DelayLine implementation
DelayLine :: DelayLine(unsigned maxDelayInSamples) : UnitGenerator(), Effect() {
// add a little bit of wiggle room to the delay length this is necessary to make setDelayLength work
mMaxDelayInSamples = maxDelayInSamples;
mTotalDelayInSamples = maxDelayInSamples + CGestalt::maxBufferFrames();
mRingBuffer.mBuffer.setSize(CGestalt::numOutChannels(), mTotalDelayInSamples); // Prepare the buffer to be used for storage.
mRingBuffer.mBuffer.allocateMonoBuffers(); // Allocate memory for my buffer.
}
unsigned DelayLine::delayLength() {
int length = mRingBuffer.mCurrentWriteFrame - mRingBuffer.mTap.mCurrentFrame;
if (length < 0)
length += mTotalDelayInSamples;
return (unsigned)length;
}
// change the delay length and return the new value
unsigned DelayLine::setDelayLength(unsigned delayInSamples) {
if (delayInSamples > mMaxDelayInSamples) {
logMsg(kLogError, "Cannot set delay line length: asked for %d in line of length %d", delayInSamples, mMaxDelayInSamples);
return delayLength();
}
mRingBuffer.mTap.seekTo(delayInSamples, kPositionStart); // Cue the read head (tap) to the new position.
return delayLength();
}
// change the delay length and return the new value
float DelayLine::setDelayTime(float delayInMiliseconds) {
unsigned delayInSamples = (unsigned)(delayInMiliseconds * mFrameRate / 1000); // Converting ms to samples.
if (delayInSamples > mMaxDelayInSamples) { // If larger than the maximum size specified, keep last value and print an error.
logMsg(kLogError, "Cannot set delay line length: asked for %d in line of length %d", delayInSamples, mMaxDelayInSamples);
return (delayLength() * (float)mFrameRate / 1000); // Converting back to miliseconds.
}
mRingBuffer.mTap.seekTo(delayInSamples, kPositionStart); // Cue the read head (tap) to the new position.
return delayInMiliseconds; // If everything went well, return the requested value.
}
// The next_buffer call writes, then reads
void DelayLine::nextBuffer(Buffer& output) throw(Exception) {
getInput(output);
mRingBuffer.writeBuffer(output);
mRingBuffer.nextBuffer(output);
return;
}
//
//
//
//DLine :: DLine ( FrameStream &input, float max_delay ) : Processor(input),
// max_delay_time(max_delay),
// delay_time(0.5 * max_delay),
// max_delay_in_frames( (unsigned) (_sampleRate * max_delay + CGestalt::block_size() ) ),
// interp_type(kTruncate),
// start_frame(0),
//// end_frame(0),
// write_frame(0),
// ring_buffer(FrameStream::channels(), max_delay_in_frames)
//{
//// max_delay_in_frames = _sampleRate * max_delay;
// ring_buffer.allocate_mono_buffers();
// ring_buffer.zero_buffers();
//
//}
//
//DLine :: ~DLine() {
// ring_buffer.free_mono_buffers();
//}
//
//bool DLine :: init_delay_time( float dt ) {
// if (dt > max_delay_time)
// return false;
// delay_time = dt;
// return set_target_delay_time(dt);
//}
//
//bool DLine :: set_target_delay_time( float tdt ) {
// if (tdt > max_delay_time)
// return false;
// target_delay_time = tdt;
// return true;
//}
//
//bool DLine :: set_interp_type( InterpType it ) {
// interp_type = it;
// return true;
//}
//
//// Do the work
//
//status DLine :: mono_next_buffer(Buffer & inputBuffer, Buffer & outputBuffer, unsigned inBufNum, unsigned outBufNum) {
// unsigned temp_write_frame = write_frame;
// sample * rbPtr = ring_buffer._monoBuffers[outBufNum] + temp_write_frame;
// sample * outPtr = outputBuffer._monoBuffers[outBufNum];
///*
// for (int i=0; i<outputBuffer._numFrames; i++){
// // ring_buffer._monoBuffers[outBufNum][temp_write_frame] = outputBuffer._monoBuffers[outBufNum][i];
// *rbPtr++ = *outPtr++
// if (++temp_write_frame >= ring_buffer._numFrames)
// temp_write_frame = 0;
// rbPtr = ring_buffer._monoBuffers[outBufNum];
// }
//*/
// sample *tempSamplePtr;
// outPtr = outputBuffer._monoBuffers[outBufNum];
// float ramp_factor = 0.0001; // ??
// rbPtr = ring_buffer._monoBuffers[outBufNum];
// for (unsigned i = 0; i < outputBuffer._numFrames; i++) {
// delay_time = (1.0 - ramp_factor) * delay_time + ramp_factor * target_delay_time;
// float r_index_and_mant = (delay_time * _sampleRate);
// unsigned index = (unsigned) floor(r_index_and_mant);
// float mantissa = r_index_and_mant - index;
// int read_frame = temp_write_frame - index;
// while (read_frame < 0)
// read_frame += ring_buffer._numFrames;
// sample lower_read_value = *(rbPtr + read_frame);
// tempSamplePtr = ((unsigned)(rbPtr + read_frame + 1)) % ring_buffer._numFrames;
// sample upper_read_value = *tempSamplePtr;
// if ( ++temp_write_frame >= ring_buffer._numFrames)
// temp_write_frame -= ring_buffer._numFrames;
// *outPtr++ = ((1.0 - mantissa) * lower_read_value) + (mantissa * upper_read_value);
// }
// write_frame = temp_write_frame;
//}
//
//// Call inherited version
//
//status DLine :: next_buffer(Buffer & inputBuffer, Buffer & outputBuffer){
// Processor :: pull_input( inputBuffer, outputBuffer );
// FrameStream :: next_buffer( inputBuffer, outputBuffer );
//// update_write_frame(outputBuffer._numFrames);
// write_frame += outputBuffer._numFrames;
// write_frame %= ring_buffer._numFrames;
//
//}
//
//
//
//
| [
"stp@8dbe4bbd-3ee8-4342-98fd-6560e08c6d14"
] | stp@8dbe4bbd-3ee8-4342-98fd-6560e08c6d14 |
ace1b52df1925b2517410fb445c2e8c48e7cb1b0 | baeecdbb529e81365fb3ed7fece1267394c2012e | /ReverseSearchIterater/src/dominating_set.hpp | a4ecd5b3cf381d1499681ae40053c51eb84d48eb | [] | no_license | ikn-lab/EnumerationAlgorithms | 7a119923211e1b27bf5c886a7bf8094bead2faf7 | 1e7ee634583a93d8e86c1c1a857952a898dbc71b | refs/heads/master | 2020-12-24T19:51:25.409974 | 2019-04-25T13:33:37 | 2019-04-25T13:33:37 | 86,220,950 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 426 | hpp | #ifndef __DOMINATING_SET__
#define __DOMINATING_SET__
#include"graph.hpp"
#include"reverse_search.hpp"
class DominatingSetEnumerator:
public ReverseSearch<Graph, std::vector<int> >{
public:
Graph G;
DominatingSetEnumerator(Graph _G);
private:
std::vector<int>* Parent(std::vector<int>* X);
std::vector<int>* Child(std::vector<int>* X, int k);
bool isDominate(std::vector<int> X);
};
#endif // __DOMINATING_SET__
| [
"chocobaby.aporo@gmail.com"
] | chocobaby.aporo@gmail.com |
6cbc67c1e54ca98d0f58a5d9bb73d2357850c29c | c00af100684b7e65b569438b56e659cd8539fe33 | /bindings/python/multibody/fcl/mesh-loader.hpp | e37e1bce46b1a053c5d262e30a81fc52228e905b | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | alan0526/pinocchio | e21b470dd551b2317c2d098ad3f1a179326c2616 | e038c7bf283b1df56a35014455e0e2d6f36e03ac | refs/heads/master | 2021-01-04T16:10:51.558851 | 2019-12-30T14:57:44 | 2019-12-30T16:36:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,601 | hpp | //
// Copyright (c) 2017-2019 CNRS INRIA
//
#ifndef __pinocchio_python_fcl_mesh_loader_hpp__
#define __pinocchio_python_fcl_mesh_loader_hpp__
#include "pinocchio/spatial/fcl-pinocchio-conversions.hpp"
#include <hpp/fcl/mesh_loader/loader.h>
#include <boost/python.hpp>
#include <typeinfo>
namespace pinocchio
{
namespace python
{
namespace fcl
{
namespace bp = boost::python;
template<typename MeshLoader>
struct MeshLoaderPythonVisitor
: public bp::def_visitor< MeshLoaderPythonVisitor<MeshLoader> >
{
typedef boost::shared_ptr<MeshLoader> MeshLoaderPtr_t;
template <typename T>
static boost::shared_ptr<T> create()
{
return boost::shared_ptr<T>(new T);
}
template<class PyClass>
void visit(PyClass& cl) const
{
cl
.def(bp::init<>(bp::arg("self"),"Default constructor"))
.def("create",&MeshLoaderPythonVisitor::create<MeshLoader>,"Create a new object.")
.staticmethod("create")
;
}
static void expose(const std::string & doc = "")
{
static const std::string class_name = typeid(MeshLoader).name();
bp::class_<MeshLoader, MeshLoaderPtr_t>
(class_name.c_str(),
doc.c_str(),
bp::no_init)
.def(MeshLoaderPythonVisitor())
;
}
};
} // namespace fcl
} // namespace python
} // namespace pinocchio
#endif // namespace __pinocchio_python_fcl_mesh_loader_hpp__
| [
"justin.carpentier@inria.fr"
] | justin.carpentier@inria.fr |
2565f6514b1cb001afc0efefd041ff43a7282b37 | d2a6b4076e1f68c98045ea5686c5c2024a8ab23c | /Jogo/src/Principal.cpp | 0b62c0f64992e8bf9411e320290d374989a77833 | [] | no_license | WhiteScoupeBr/Corrida-para-o-Oeste | 9562b1088b2e5565de57d0a779c188c4d6e71f8b | 0908ebb77af0fd84c2124d9bfe662993be9d4efb | refs/heads/master | 2020-04-05T19:20:15.323416 | 2018-11-21T02:04:20 | 2018-11-21T02:04:20 | 157,129,656 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,288 | cpp | #include "Principal.h"
Principal::Principal()
{
}
Principal::~Principal()
{
//dtor
}
void Principal::Executar()
{
RenderWindow window(sf::VideoMode(800, 600), "Corrida para o Oeste",Style::Close|Style::Titlebar);
Texture textureJogador1, textureJogador2;;
textureJogador1.loadFromFile("sprite2.png");
textureJogador2.loadFromFile("sprite22.png");
Jogador jogador1(&textureJogador1,Vector2u(8,12),0.1f,200.0f,128.f);
Jogador2 jogador2(&textureJogador2,Vector2u(8,12),0.1f,200.0f,128.f);
View view(Vector2f(0.0f,0.0f), Vector2f(800.f,600.f));
Vector2u textureSize = textureJogador1.getSize();
textureSize.x/=8;
textureSize.y/=12;
Vector2u textureSize2 = textureJogador2.getSize();
textureSize2.x/=8;
textureSize2.y/=12;
Music music,music2;
music.openFromFile("Cash.wav");
music2.openFromFile("Good.wav");
Fase1 fase1;
Fase2 fase2;
Menu menu1(window.getSize().x, window.getSize().y);
Pause pause (window.getSize().x, window.getSize().y);
float deltaTime=0.0f;
Clock relogio;
while (window.isOpen())
{
deltaTime = relogio.restart().asSeconds();
if(deltaTime>1.f/20.f)
deltaTime=1.f/20.f;
Event event;
if(desenhaMenu==true||desenhaMenu2==true)
{
music2.play();
}
while (window.pollEvent(event))
{
if(desenhaMenu==true)
{
switch (event.type)
{
case sf::Event::KeyReleased:
switch (event.key.code)
{
case sf::Keyboard::Up:
menu1.MoveUp();
break;
case sf::Keyboard::Down:
menu1.MoveDown();
break;
case sf::Keyboard::Return:
switch (menu1.GetPressedItem())
{
case 0:
fase1Pronta=true;
menu1.Altera(window.getSize().x, window.getSize().y);
desenhaMenu=false;
desenhaMenu2=true;
break;
case 1:
fase1Pronta=false;
menu1.Altera(window.getSize().x, window.getSize().y);
desenhaMenu2=true;
desenhaMenu=false;
Sleep(500);
break;
case 2:
{
_game =true;
desenhaMenu=false;
_save=true;
string line;
ifstream save("save.txt");
if(save.is_open())
{
while (getline(save,line))
{
stringstream ss(line);
getline(ss,fase1t,',');
getline(ss,jog2,',');
getline(ss,posx,',');
getline(ss,posy,',');
}
}
else
printf("Error opening save!");
istringstream(fase1t) >> fase1Pronta;
istringstream(jog2) >> jogoPronto2;
_posx = std::stof(posx);
_posy = std::stof (posy);
}
break;
case 3:
printf("RANKING");
break;
case 4:
window.close();
break;
}
break;
}
}
}
if(desenhaMenu2==true)
{
switch (event.type)
{
case sf::Event::KeyPressed:
switch (event.key.code)
{
case sf::Keyboard::Up:
menu1.MoveUp();
break;
case sf::Keyboard::Down:
menu1.MoveDown();
break;
case sf::Keyboard::Return:
switch (menu1.GetPressedItem())
{
case 0:
jogoPronto2=false;
_game =true;
desenhaMenu=false;
desenhaMenu2=false;
menu1.Altera2(window.getSize().x, window.getSize().y);
break;
case 1:
jogoPronto2=true;
_game =true;
desenhaMenu=false;
desenhaMenu2=false;
menu1.Altera2(window.getSize().x, window.getSize().y);
break;
case 2:
window.close();
break;
}
break;
}
}
}
if (event.type == sf::Event::Closed)
window.close();
if(sf::Keyboard::isKeyPressed(Keyboard::Escape))
{
_pause=true;
Sleep(500);
}
if(_pause==true)
{
switch (event.type)
{
case sf::Event::KeyReleased:
switch (event.key.code)
{
case sf::Keyboard::Up:
pause.MoveUp();
break;
case sf::Keyboard::Down:
pause.MoveDown();
break;
case sf::Keyboard::Return:
switch (pause.GetPressedItem())
{
case 0:
_pause=false;
break;
case 1:
{
ofstream myfile ("save.txt");
if (myfile.is_open())
{
myfile << fase1Pronta;
myfile << ",";
myfile << jogoPronto2;
myfile << ",";
myfile << jogador1.GetPosition().x;
myfile << ",";
myfile << jogador1.GetPosition().y;
myfile.close();
printf("Saved!");
}
else
printf("Unable to save!");
}
break;
case 2:
window.close();
break;
}
break;
}
}
}
}
if(_game)
{
start = std::clock();
if (_fimFase1)
{
fase1Pronta=false;
}
if (jogoPronto2==false && fase1Pronta)
{
if(_save)
{
jogador1.setPosition(_posx,_posy);
_save=false;
}
fase1.Executar(window,deltaTime,jogador1,view, _fimFase1);
jogador1.Desenha(window);
if(_pause==false)
{
jogador1.Atualiza(deltaTime);
fase1.Atualiza(deltaTime);
}
}
else if (jogoPronto2==true && fase1Pronta)
{
if(_save)
{
jogador1.setPosition(_posx,_posy);
jogador2.setPosition(_posx,_posy);
_save=false;
}
fase1.Executar2(window,deltaTime,jogador1,view,jogador2, _fimFase1);
jogador2.Desenha(window);
jogador1.Desenha(window);
if(_pause==false)
{
jogador1.Atualiza(deltaTime);
jogador2.Atualiza(deltaTime);
fase1.Atualiza2(deltaTime);
}
}
else if (jogoPronto2==false && fase1Pronta==false)
{
if(_save)
{
jogador1.setPosition(_posx,_posy);
_save=false;
}
fase2.Executar(window,deltaTime,jogador1,view, _fimFase2);
jogador1.Desenha(window);
if(_pause==false)
{
jogador1.Atualiza(deltaTime);
fase2.Atualiza(deltaTime);
}
}
else if (jogoPronto2==true && fase1Pronta==false)
{
if(_save)
{
jogador1.setPosition(_posx,_posy);
jogador2.setPosition(_posx,_posy);
_save=false;
}
fase2.Executar2(window,deltaTime,jogador1,view,jogador2, _fimFase2);
jogador2.Desenha(window);
jogador1.Desenha(window);
if(_pause==false)
{
jogador1.Atualiza(deltaTime);
jogador2.Atualiza(deltaTime);
fase2.Atualiza2(deltaTime);
}
}
}
if(_fimFase2)
{
fim = clock();
tempoTotal=fim-start;
duration = tempoTotal / (double) CLOCKS_PER_SEC;
_game=false;
desenhaMenu=true;
}
if (desenhaMenu==true)
{
if (_fimFase2)
{
menu1.setPosition(jogador1.GetPosition().x, jogador1.GetPosition().y);
}
menu1.Desenha(window);
}
if (desenhaMenu2==true)
{
menu1.Desenha(window);
}
if(_pause)
{
pause.setPosition(jogador1.GetPosition().x,jogador1.GetPosition().y);
pause.Desenha(window);
}
window.display();
window.clear();
}
}
| [
"noreply@github.com"
] | noreply@github.com |
7e2ad816cfd00b5fd721d85c4dcf057ddc560399 | 7d752fd65c4e938f896662a29cc045da8c3aa041 | /POJ2524.cpp | 944af996fbd0a9c8a7762b047813bfd5a5b13bdf | [] | no_license | Phimos/POJ-solves | 4f5f1fbdac9b6ace3285bd509e6afaa753fca2b8 | 7a351ba86510ec7c669345e586e83c7edbfe45c0 | refs/heads/master | 2021-07-11T02:08:25.067397 | 2019-02-05T07:01:15 | 2019-02-05T07:01:15 | 146,992,750 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 809 | cpp | #include<iostream>
#include<vector>
using namespace std;
vector<int> religion_num;
int get_religion(int k)
{
if (k != religion_num[k])
religion_num[k] = get_religion(religion_num[k]);
return religion_num[k];
}
void merge(int a, int b)
{
int ra = get_religion(a);
int rb = get_religion(b);
if (ra == rb)
return;
religion_num[rb] = ra;
}
int main()
{
int n, m, case_num = 0;
while (cin >> n >> m && (n || m))
{
++case_num;
religion_num.resize(n);
for (int i = 0; i<n; ++i)
religion_num[i] = i;
for (int i = 0; i<m; ++i)
{
int student_a, student_b;
cin >> student_a >> student_b;
merge(student_a - 1, student_b - 1);
}
int cnt = 0;
for (int i = 0; i<n; ++i)
if (i == religion_num[i])
++cnt;
cout << "Case " << case_num << ": " << cnt << endl;
}
return 0;
} | [
"41637559+Phimos@users.noreply.github.com"
] | 41637559+Phimos@users.noreply.github.com |
e59bd1b4c0fc1b4fbcb2e885def4e87cd9c4bfa5 | ba691b7aa18a01eae73671a80642a047016f711c | /dprofiler/stdafx.cpp | ccdaef77d9c9e8825c6681f485241e0c20dc3bfd | [] | no_license | xwlan/dprofiler | 84544d3c5d7e31aafac354562bb02396a3a6651e | 3897cfadbf66b75bf968f37e0cc616a5c15a31ca | refs/heads/master | 2022-12-11T00:24:01.991875 | 2022-12-02T03:44:24 | 2022-12-02T03:44:24 | 28,292,358 | 79 | 28 | null | null | null | null | UTF-8 | C++ | false | false | 296 | cpp | // stdafx.cpp : source file that includes just the standard includes
// dprofiler.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"lan.john@gmail.com"
] | lan.john@gmail.com |
12efd8373b8ee215905d62867c48731858499f05 | 39240f11267b4ca816c039cb5fc63b0ec772fa87 | /PROJECT/PhysX-3.3/PhysXSDK/Snippets/SnippetVehicleCommon/SnippetVehicleRaycast.cpp | 222b36f488c7584f4cdb9dc943f4faba3598143f | [] | no_license | flylong0204/osgProjs | 39f34f177fce27847162c2e4d5d4ffa671e2ec60 | b7a113a1db345fe424721e0f261c54d054ec5996 | refs/heads/master | 2021-06-21T21:31:42.507231 | 2017-08-24T02:19:51 | 2017-08-24T07:54:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,132 | cpp | /*
* Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved.
*
* NVIDIA CORPORATION and its licensors retain all intellectual property
* and proprietary rights in and to this software, related documentation
* and any modifications thereto. Any use, reproduction, disclosure or
* distribution of this software and related documentation without an express
* license agreement from NVIDIA CORPORATION is strictly prohibited.
*/
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include <new>
#include "SnippetVehicleRaycast.h"
#include "PxPhysicsAPI.h"
using namespace physx;
void setupDrivableSurface(PxFilterData& filterData)
{
filterData.word3 = (PxU32)DRIVABLE_SURFACE;
}
void setupNonDrivableSurface(PxFilterData& filterData)
{
filterData.word3 = UNDRIVABLE_SURFACE;
}
PxQueryHitType::Enum WheelRaycastPreFilter
(PxFilterData filterData0, PxFilterData filterData1,
const void* constantBlock, PxU32 constantBlockSize,
PxHitFlags& queryFlags)
{
//filterData0 is the vehicle suspension raycast.
//filterData1 is the shape potentially hit by the raycast.
PX_UNUSED(constantBlockSize);
PX_UNUSED(constantBlock);
PX_UNUSED(filterData0);
PX_UNUSED(queryFlags);
return ((0 == (filterData1.word3 & DRIVABLE_SURFACE)) ? PxQueryHitType::eNONE : PxQueryHitType::eBLOCK);
}
VehicleSceneQueryData::VehicleSceneQueryData()
: mNumRaycastsPerBatch(0),
mSqResults(NULL),
mSqHitBuffer(NULL),
mPreFilterShader(WheelRaycastPreFilter)
{
}
VehicleSceneQueryData::~VehicleSceneQueryData()
{
}
VehicleSceneQueryData* VehicleSceneQueryData::allocate(const PxU32 maxNumVehicles, const PxU32 maxNumWheelsPerVehicle, const PxU32 numVehiclesInBatch, PxAllocatorCallback& allocator)
{
PX_COMPILE_TIME_ASSERT(0 == (sizeof(PxRaycastQueryResult) & 15));
PX_COMPILE_TIME_ASSERT(0 == (sizeof(PxRaycastHit) & 15));
const PxU32 sqDataSize = ((sizeof(VehicleSceneQueryData) + 15) & ~15);
const PxU32 maxNumWheels = maxNumVehicles*maxNumWheelsPerVehicle;
const PxU32 size = sqDataSize + sizeof(PxRaycastQueryResult)*maxNumWheels + sizeof(PxRaycastHit)*maxNumWheels;
PxU8* buffer = (PxU8*)allocator.allocate(size, NULL, NULL, 0);
VehicleSceneQueryData* sqData = new(buffer) VehicleSceneQueryData();
buffer += sqDataSize;
sqData->mNumRaycastsPerBatch = numVehiclesInBatch*maxNumWheelsPerVehicle;
sqData->mSqResults = (PxRaycastQueryResult*)buffer;
buffer += sizeof(PxRaycastQueryResult)*maxNumWheels;
sqData->mSqHitBuffer = (PxRaycastHit*)buffer;
buffer += sizeof(PxRaycastHit)*maxNumWheels;
for(PxU32 i = 0; i < maxNumVehicles; i++)
{
for(PxU32 j = 0; j < maxNumWheelsPerVehicle; j++)
{
PX_ASSERT((size_t)(sqData->mSqResults + i*maxNumWheelsPerVehicle + j) < (size_t)buffer);
PX_ASSERT((size_t)(sqData->mSqHitBuffer + i*maxNumWheelsPerVehicle + j) < (size_t)buffer);
new(sqData->mSqResults + i*maxNumWheelsPerVehicle + j) PxRaycastQueryResult();
new(sqData->mSqHitBuffer + i*maxNumWheelsPerVehicle + j) PxRaycastHit();
}
}
return sqData;
}
void VehicleSceneQueryData::free(PxAllocatorCallback& allocator)
{
allocator.deallocate(this);
}
PxBatchQuery* VehicleSceneQueryData::setUpBatchedSceneQuery(const PxU32 batchId, const VehicleSceneQueryData& vehicleSceneQueryData, PxScene* scene)
{
const PxU32 maxNumRaycastsInBatch = vehicleSceneQueryData.mNumRaycastsPerBatch;
PxBatchQueryDesc sqDesc(maxNumRaycastsInBatch, 0, 0);
sqDesc.queryMemory.userRaycastResultBuffer = vehicleSceneQueryData.mSqResults + batchId*maxNumRaycastsInBatch;
sqDesc.queryMemory.userRaycastTouchBuffer = vehicleSceneQueryData.mSqHitBuffer + batchId*maxNumRaycastsInBatch;
sqDesc.queryMemory.raycastTouchBufferSize = maxNumRaycastsInBatch;
sqDesc.preFilterShader = vehicleSceneQueryData.mPreFilterShader;
return scene->createBatchQuery(sqDesc);
}
PxRaycastQueryResult* VehicleSceneQueryData::getRaycastQueryResultBuffer(const PxU32 batchId)
{
return (mSqResults + batchId*mNumRaycastsPerBatch);
}
PxU32 VehicleSceneQueryData::getRaycastQueryResultBufferSize() const
{
return mNumRaycastsPerBatch;
}
| [
"lc@burun.com"
] | lc@burun.com |
e6f470067550bc46877b9a6a2e2d907e23b98dc9 | 72659c2918765a56588f1cf4edc331d36ddfbf6d | /qualification/cookie-clicker-alpha.cpp | 374a6483b8932d3effcc4f7c3621bf9ad90ee701 | [] | no_license | razaninter/google-code-jam-2014 | 276b6455f8942134d151d3e65af2194aeb43aa8b | b50de2a84671eb07cea854348763f26c6c9f8c1a | refs/heads/master | 2020-06-20T16:18:41.896594 | 2018-05-15T22:39:48 | 2018-05-15T22:39:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 473 | cpp | #include <cstdio>
#include <cstring>
#include <iostream>
#define SIZE 4
using namespace std;
bool chosen[SIZE * SIZE];
int main() {
int t; cin >> t;
for(int tc = 1; tc <= t; tc++) {
double c, f, x; cin >> c >> f >> x;
double rate = 2.0, time = 0.0;
while(x / rate > (c / rate + (x / (rate + f)))) {
time += c / rate;
rate += f;
}
time += x / rate;
cout << "Case #" << tc << ": ";
printf("%.7lf\n", time);
}
return 0;
}
| [
"ruippeixotog@gmail.com"
] | ruippeixotog@gmail.com |
c90040bf9cbc3a1d934219ddb38abdfc4ea3290a | b627bafa118132e50b99e4435bcf00a60f066166 | /Day12_2.cpp | a5dde0d27bdfa231882399135b61c797ad0170a5 | [] | no_license | DavidBuzatu-Marian/AdeventOfCode | 7061803fcfd72bc0f2cb477d5d7d88f1f4372bf3 | 248d82531fa08a982d5c0c694b64592b8c8269a6 | refs/heads/main | 2023-02-08T21:03:53.233673 | 2020-12-20T08:59:47 | 2020-12-20T08:59:47 | 319,006,724 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,267 | cpp | #include <boost/multiprecision/cpp_int.hpp>
#include <fstream>
#include <iostream>
#include <vector>
using namespace boost::multiprecision;
using namespace std;
void parseIDLine(string &line, vector<int> &ids) {
size_t pos = 0;
while ((pos = line.find(',')) != std::string::npos) {
string value = line.substr(0, pos);
if (value.compare("x") != 0) {
ids.push_back(stoi(value));
} else {
ids.push_back(-1);
}
line.erase(0, pos + 1);
}
if (line.compare("x") != 0) {
ids.push_back(stoi(line));
}
}
int sequential(const long long &res, const vector<int> &ids) {
for (int i = 0; i < ids.size(); ++i) {
if (ids[i] == -1) {
continue;
}
if ((res + i) % ids[i] != 0) {
return 0;
}
}
return 1;
}
cpp_int findX(cpp_int mult, const int &modulo) {
mult %= modulo;
if (mult == 1) {
return 1;
} else {
cpp_int m = mult;
cpp_int cnt = 1;
while (mult % modulo != 1) {
mult += m;
++cnt;
}
return cnt;
}
}
cpp_int chineseDivision(const vector<int> &ids) {
vector<cpp_int> b, Ns, x;
cpp_int res = 0, N = 1, sum = 0;
for (int i = 0; i < ids.size(); ++i) {
if (ids[i] != -1) {
if (b.size() == 0) {
b.push_back(0);
} else {
b.push_back(ids[i] - i);
}
N *= ids[i];
}
}
for (int i = 0; i < ids.size(); ++i) {
if (ids[i] != -1) {
Ns.push_back(N / ids[i]);
x.push_back(findX(N / ids[i], ids[i]));
}
}
for (int i = 0; i < b.size(); ++i) {
sum += (b[i] * Ns[i] * x[i]);
}
return sum % N;
}
int main() {
ifstream f("day12_1.txt");
int ID, minTime = INT_MAX, minID = 0, minMinutes = 0;
string idLine;
vector<int> ids;
f >> ID;
f >> idLine;
parseIDLine(idLine, ids);
// long long result = 0;
// while (!sequential(result, ids)) {
// result += ids[0];
// }
// cout << result << '\n';
cout << chineseDivision(ids) << '\n';
} | [
"davidm.buzatu@gmail.com"
] | davidm.buzatu@gmail.com |
cd91398ef524dbd5f205d4b5b512ec1df3b4e4aa | 3a940c14587980cb8858fe3debf846952faf8329 | /Pass_by_Reference/DISTANCEANDPOINT.cpp | 43fecd189df4d4643c33a3932e5c775b993c28ef | [] | no_license | odelva/Cpp_Assignments | 62d97cc7310eb8f347c757f0b9e6ac89730c1aa7 | adef75b2ef2d2621063f4436400c1348cc9463df | refs/heads/master | 2021-10-19T18:23:47.740547 | 2019-02-23T03:06:19 | 2019-02-23T03:06:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,042 | cpp | #include "DISTANCEANDPOINT.h"
#include<sstream>
#include<cmath>
#include<iostream>
using namespace std;
Point::Point()
{
cout<<"The constructor is called"<<endl;
}
Point::Point(const Point& source)
{
m_x=source.m_x;
m_y=source.m_y;
}
Point::Point(double x, double y)
{
m_x=x;
m_y=y;
}
Point::~Point()
{
cout<<"The destructor is called"<<endl;
}
// Get the x value
double Point::GetX()
{
return m_x;
}
// Get the y value
double Point::GetY()
{
return m_y;
}
// Set the x value
void Point::SetX(double newxval)
{
m_x = newxval;
}
// Set the y value
void Point::SetY(double newyval)
{
m_y = newyval;
}
void Point::ToString()
{
std::stringstream ss;
ss << "Point(" << GetX() << "," << GetY() << ")";
std::string mystr=ss.str();
cout << mystr << endl;
}
double Point:: DistanceOrigin()
{
double result= pow(m_x,2) + pow( m_y, 2);
return sqrt(result);
}
double Point:: Distance (const Point& p)
{
double xbetween= (p.m_x-m_x)*(p.m_x-m_x);
double ybetween= (p.m_y-m_y)*(p.m_y-m_y);
return sqrt( xbetween + ybetween);
}
| [
"odekyc@gmail.com"
] | odekyc@gmail.com |
7d2b133bada45b77a6fec420e6fb16cce4ada42e | 12935cbca4804c048fc7826a5a5b3d5ad31dc331 | /Src/WindowsHelpers.cpp | 1465e771737922d902238c162a43ba7c35ed32c6 | [
"MIT"
] | permissive | mbeytekin/wangtiler | fd7a9ceea429566d5f80cb91b8debb2a578daeb5 | 588c8e2d301b4054fe88dc2578b09bab5c807d74 | refs/heads/master | 2023-02-19T07:47:00.189336 | 2021-01-20T20:43:56 | 2021-01-20T20:43:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,841 | cpp | /// \file WindowsHelpers.cpp
/// \brief Code for some helpful Windows-specific functions.
///
/// These platform-dependent functions are hidden away so that the faint-of-heart
/// don't have to see them if they're offended by them.
// MIT License
//
// Copyright (c) 2020 Ian Parberry
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
#include <shobjidl_core.h>
#include <atlbase.h>
#include "WindowsHelpers.h"
#include "Includes.h"
#include "resource.h"
///////////////////////////////////////////////////////////////////////////////
// Initialization functions
#pragma region Initialization
/// Create and initialize a window.
/// \param hInst Instance handle.
/// \param nShow 1 to show window, 0 to hide.
/// \param WndProc Window procedure.
void InitWindow(HINSTANCE hInst, INT nShow, WNDPROC WndProc){
const char appname[] = "WangTiler";
WNDCLASSEX wndClass = {0}; //extended window class structure
wndClass.cbSize = sizeof(WNDCLASSEX);
wndClass.style = CS_HREDRAW | CS_VREDRAW;
wndClass.lpfnWndProc = WndProc;
wndClass.cbClsExtra = 0;
wndClass.cbWndExtra = 0;
wndClass.hInstance = hInst;
wndClass.hIcon = LoadIcon(hInst, MAKEINTRESOURCE(IDI_ICON1));
wndClass.hCursor = LoadCursor(nullptr, IDC_ARROW);
wndClass.hbrBackground = nullptr;
wndClass.lpszMenuName = nullptr;
wndClass.lpszClassName = appname;
wndClass.hIconSm = LoadIcon(hInst, MAKEINTRESOURCE(IDI_ICON2));
RegisterClassEx(&wndClass);
const DWORD dwStyle = WS_CAPTION | WS_MINIMIZEBOX | WS_SYSMENU;
const DWORD dwStyleEx = WS_EX_APPWINDOW | WS_EX_DLGMODALFRAME;
const int w = 600; //window client area width.
const int h = 600; //window client area height.
RECT r;
r.left = 0; r.right = w;
r.top = 0; r.bottom = h + GetSystemMetrics(SM_CYMENU);
AdjustWindowRectEx(&r, dwStyle, FALSE, dwStyleEx);
const HWND hwnd = CreateWindowEx(dwStyleEx, appname, appname, dwStyle,
CW_USEDEFAULT, CW_USEDEFAULT, r.right - r.left, r.bottom - r.top,
nullptr, nullptr, hInst, nullptr);
ShowWindow(hwnd, nShow);
UpdateWindow(hwnd);
} //InitWindow
/// Initialize GDI+ and get a GDI+ token.
/// \return A GDI+ token.
ULONG_PTR InitGDIPlus(){
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, nullptr);
return gdiplusToken;
} //InitGDIPlus
#pragma endregion Initialization
///////////////////////////////////////////////////////////////////////////////
// Save functions
#pragma region Save
/// Get an encoder clsid for an image file format.
/// \param format File format using wide characters.
/// \param pClsid [OUT] Pointer to clsid.
/// \return S_OK for success, E_FAIL for failure.
HRESULT GetEncoderClsid(const WCHAR* format, CLSID* pClsid){
UINT num = 0; //number of image encoders
UINT n = 0; //size of the image encoder array in bytes
HRESULT hr = E_FAIL; //return result
Gdiplus::ImageCodecInfo* pCodecInfo = nullptr; //for codec info
if(FAILED(Gdiplus::GetImageEncodersSize(&num, &n)))return E_FAIL; //get sizes
if(n == 0)return E_FAIL; //there are no encoders
pCodecInfo = (Gdiplus::ImageCodecInfo*)(malloc(n)); //allocate codec info memory
if(pCodecInfo == nullptr)return E_FAIL; //malloc failed (as if)
if(FAILED(GetImageEncoders(num, n, pCodecInfo)))return E_FAIL; //get encoders
for(UINT j=0; j<num && hr!=S_OK; j++) //for each encoder, while not found
if(wcscmp(pCodecInfo[j].MimeType, format) == 0){ //found the codex we want
*pClsid = pCodecInfo[j].Clsid; //return it
hr = S_OK; //success
} //if
free(pCodecInfo); //clean up
return hr;
} //GetEncoderClsid
/// Display a `Save` dialog box for png files and save a bitmap to the file name
/// that the user selects. Only files with a `.png` extension are allowed. The
/// default file name is "ImageN.png", where N is the number of images saved
/// so far in the current instance of this program. This prevents any collisions
/// with files already saved by this instance. If there is a collision with a
/// file from a previous instance, then the user is prompted to overwrite or
/// rename it in the normal fashion.
/// \param hwnd Window handle.
/// \param pBitmap Pointer to a bitmap.
/// \return S_OK for success, E_FAIL for failure.
HRESULT SaveBitmap(HWND hwnd, Gdiplus::Bitmap* pBitmap){
COMDLG_FILTERSPEC filetypes[] = { //png files only
{L"PNG Files", L"*.png"}
}; //filetypes
std::wstring wstrFileName; //result
CComPtr<IFileSaveDialog> pDlg; //pointer to save dialog box
static int n = 0; //number of images saved in this run
std::wstring wstrName = L"Image" + std::to_wstring(n++); //default file name
CComPtr<IShellItem> pItem; //item pointer
LPWSTR pwsz = nullptr; //pointer to null-terminated wide string for result
//fire up the save dialog box
if(FAILED(pDlg.CoCreateInstance(__uuidof(FileSaveDialog))))return E_FAIL;
pDlg->SetFileTypes(_countof(filetypes), filetypes); //set file types to png
pDlg->SetTitle(L"Save Image"); //set title bar text
pDlg->SetFileName(wstrName.c_str()); //set default file name
pDlg->SetDefaultExtension(L"png"); //set default extension
if(FAILED(pDlg->Show(hwnd)))return E_FAIL; //show the dialog box
if(FAILED(pDlg->GetResult(&pItem)))return E_FAIL; //get the result item
if(FAILED(pItem->GetDisplayName(SIGDN_FILESYSPATH, &pwsz)))return E_FAIL; //get file name
//wstrFileName should now contain the selected file name
CLSID clsid; //for PNG class id
if(FAILED(GetEncoderClsid((WCHAR*)L"image/png", &clsid)))return E_FAIL; //get
pBitmap->Save(pwsz, &clsid, nullptr); //the actual save happens here
CoTaskMemFree(pwsz); //clean up
return S_OK;
} //SaveBitmap
#pragma endregion Save
| [
"Ian-Parberry@users.noreply.github.com"
] | Ian-Parberry@users.noreply.github.com |
928baa23fba80b54271cd5fa3e01567d452e35c5 | 44331d532a4710b2f6aec3128a82a3d74c5602fd | /activation_function/ActivationFunction/mainwindow.cpp | 3f9b2dd2697d9e30dda9901a1e7268ad3c420b14 | [] | no_license | Taro3/DeepLearning_Cpp | 8eeb288a61633f95ca99c6b91e01694a8986f3a9 | 070418c0da1675e360c69e94e04276c18111236d | refs/heads/master | 2022-01-23T07:33:16.243277 | 2019-08-29T10:20:42 | 2019-08-29T10:20:42 | 198,218,110 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,244 | cpp | #include <QtCharts>
#include <Eigen/Dense>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "activationfunction.h"
#include "plotgraph.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
_plotGraph(new PlotGraph())
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
delete _plotGraph;
}
/**
* @brief MainWindow::on_pushButton_clicked
* ステップ関数グラフ描画
*/
void MainWindow::on_pushButton_clicked()
{
Eigen::ArrayXd x;
x.setLinSpaced(100, -5, 5);
ActivationFunction af;
auto y = af.step_function(x);
_plotGraph->plot(x, y.cast<double>());
}
/**
* @brief MainWindow::on_pushButton_2_clicked
* シグモイド関数グラフ描画
*/
void MainWindow::on_pushButton_2_clicked()
{
Eigen::ArrayXd x;
x.setLinSpaced(100, -5, 5);
ActivationFunction af;
auto y = af.sigmoid(x);
_plotGraph->plot(x, y);
}
/**
* @brief MainWindow::on_pushButton_3_clicked
* ReLU関数グラフ描画
*/
void MainWindow::on_pushButton_3_clicked()
{
Eigen::ArrayXd x;
x.setLinSpaced(100, -5, 5);
ActivationFunction af;
auto y = af.relu(x);
_plotGraph->plot(x, y);
}
| [
"taro.develop@gmail.com"
] | taro.develop@gmail.com |
e2985ef847836c4367dc97df906bf43e73b4a4f2 | bacf55a4cd2862d8fc1283de9296972c10b8f3fe | /src/leveldb/db/autocompact_test.cc | 910931782d6921e81888d4358716a74929e902ba | [
"MIT",
"BSD-3-Clause"
] | permissive | ddnut/Investacoin | c9db11305f25cc9827f689581864b85d010ca6c0 | 2722e0c2e9cd2941e32eb7c597b868fe12103a78 | refs/heads/master | 2020-05-23T08:04:36.474374 | 2016-10-08T10:15:02 | 2016-10-08T10:15:02 | 70,313,646 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,373 | cc | // Copyright (c) 2013 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "leveldb/db.h"
#include "db/db_impl.h"
#include "leveldb/cache.h"
#include "util/testharness.h"
#include "util/testutil.h"
namespace leveldb {
class AutoCompactTest {
public:
std::string dbname_;
Cache* tiny_cache_;
Options options_;
DB* db_;
AutoCompactTest() {
dbname_ = test::TmpDir() + "/autocompact_test";
tiny_cache_ = NewLRUCache(100);
options_.block_cache = tiny_cache_;
DestroyDB(dbname_, options_);
options_.create_if_missing = true;
options_.compression = kNoCompression;
ASSERT_OK(DB::Open(options_, dbname_, &db_));
}
~AutoCompactTest() {
delete db_;
DestroyDB(dbname_, Options());
delete tiny_cache_;
}
std::string Key(int i) {
char buf[100];
snprintf(buf, sizeof(buf), "key%06d", i);
return std::string(buf);
}
uint64_t Size(const Slice& start, const Slice& limit) {
Range r(start, limit);
uint64_t size;
db_->GetApproximateSizes(&r, 1, &size);
return size;
}
void DoReads(int n);
};
static const int kValueSize = 200 * 1024;
static const int kTotalSize = 100 * 1024 * 1024;
static const int kCount = kTotalSize / kValueSize;
// Read through the first n keys repeatedly and check that they get
// compacted (verified by checking the size of the key space).
void AutoCompactTest::DoReads(int n) {
std::string value(kValueSize, 'x');
DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
// Fill database
for (int i = 0; i < kCount; i++) {
ASSERT_OK(db_->Put(WriteOptions(), Key(i), value));
}
ASSERT_OK(dbi->INVT_CompactMemTable());
// Delete everything
for (int i = 0; i < kCount; i++) {
ASSERT_OK(db_->Delete(WriteOptions(), Key(i)));
}
ASSERT_OK(dbi->INVT_CompactMemTable());
// Get initial measurement of the space we will be reading.
const int64_t initial_size = Size(Key(0), Key(n));
const int64_t initial_other_size = Size(Key(n), Key(kCount));
// Read until size drops significantly.
std::string limit_key = Key(n);
for (int read = 0; true; read++) {
ASSERT_LT(read, 100) << "Taking too long to compact";
Iterator* iter = db_->NewIterator(ReadOptions());
for (iter->SeekToFirst();
iter->Valid() && iter->key().ToString() < limit_key;
iter->Next()) {
// Drop data
}
delete iter;
// Wait a little bit to allow any triggered compactions to complete.
Env::Default()->SleepForMicroseconds(1000000);
uint64_t size = Size(Key(0), Key(n));
fprintf(stderr, "iter %3d => %7.3f MB [other %7.3f MB]\n",
read+1, size/1048576.0, Size(Key(n), Key(kCount))/1048576.0);
if (size <= initial_size/10) {
break;
}
}
// Verify that the size of the key space not touched by the reads
// is pretty much unchanged.
const int64_t final_other_size = Size(Key(n), Key(kCount));
ASSERT_LE(final_other_size, initial_other_size + 1048576);
ASSERT_GE(final_other_size, initial_other_size/5 - 1048576);
}
INVT(AutoCompactTest, ReadAll) {
DoReads(kCount);
}
INVT(AutoCompactTest, ReadHalf) {
DoReads(kCount/2);
}
} // namespace leveldb
int main(int argc, char** argv) {
return leveldb::test::RunAllTests();
}
| [
"corey@razorgames.org"
] | corey@razorgames.org |
feed1074c1a1ec633bf91bd354ddbc7746481255 | f8d3bf4d49e27e9673263c4683a96445a835cea4 | /videotodigital.cpp | 08adbfa26cedc91da94b5608f73599bf2d2b8d5d | [
"Apache-2.0"
] | permissive | Fagear/SDVPCMdecoder | c803771f377c4fa99fc81522ba4fab7874b78604 | df650811db5d21c12d818f9dfb8173009f40bed6 | refs/heads/main | 2023-06-29T21:31:54.166352 | 2023-02-26T22:56:40 | 2023-02-26T22:56:40 | 540,895,609 | 26 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 84,673 | cpp | #include "videotodigital.h"
VideoToDigital::VideoToDigital(QObject *parent) : QObject(parent)
{
in_video = NULL;
out_pcm1 = NULL;
out_pcm16x0 = NULL;
out_stc007 = NULL;
mtx_vid = NULL;
mtx_pcm1 = NULL;
mtx_pcm16x0 = NULL;
mtx_stc007 = NULL;
log_level = 0;
pcm_type = TYPE_STC007;
pcm_sample_fmt = PCM_FMT_NOT_SET;
binarization_mode = Binarizer::MODE_NORMAL;
fine_bin_preset.reset();
line_converter.setFineSettings(fine_bin_preset);
signal_quality.clear();
line_dump_help_done = false;
coordinate_damper = true;
check_line_copy = true;
reset_stats = true;
finish_work = false;
}
//------------------------ Set pointers to shared input data.
void VideoToDigital::setInputPointers(std::deque<VideoLine> *in_vline, QMutex *mtx_vline)
{
if((in_vline==NULL)||(mtx_vline==NULL))
{
qWarning()<<DBG_ANCHOR<<"[V2D] Empty input pointer provided, unable to apply!";
}
else
{
in_video = in_vline;
mtx_vid = mtx_vline;
}
}
//------------------------ Set pointers to shared PCM-1 output data.
void VideoToDigital::setOutPCM1Pointers(std::deque<PCM1Line> *out_pcmline, QMutex *mtx_pcmline)
{
if((out_pcmline==NULL)||(mtx_pcmline==NULL))
{
qWarning()<<DBG_ANCHOR<<"[V2D] Empty output pointer provided, unable to apply!";
}
else
{
out_pcm1 = out_pcmline;
mtx_pcm1 = mtx_pcmline;
}
}
//------------------------ Set pointers to shared PCM-16x0 output data.
void VideoToDigital::setOutPCM16X0Pointers(std::deque<PCM16X0SubLine> *out_pcmline, QMutex *mtx_pcmline)
{
if((out_pcmline==NULL)||(mtx_pcmline==NULL))
{
qWarning()<<DBG_ANCHOR<<"[V2D] Empty output pointer provided, unable to apply!";
}
else
{
out_pcm16x0 = out_pcmline;
mtx_pcm16x0 = mtx_pcmline;
}
}
//------------------------ Set pointers to shared STC-007 output data.
void VideoToDigital::setOutSTC007Pointers(std::deque<STC007Line> *out_pcmline, QMutex *mtx_pcmline)
{
if((out_pcmline==NULL)||(mtx_pcmline==NULL))
{
qWarning()<<DBG_ANCHOR<<"[V2D] Empty output pointer provided, unable to apply!";
}
else
{
out_stc007 = out_pcmline;
mtx_stc007 = mtx_pcmline;
}
}
//------------------------ Wait until one full frame is in the input queue.
bool VideoToDigital::waitForOneFrame()
{
bool frame_lock;
std::deque<VideoLine>::iterator buf_scaner;
frame_lock = false;
// Pick start of the queue.
buf_scaner = in_video->begin();
// Scan the buffer until there is nothing in the input.
while(buf_scaner!=in_video->end())
{
// Still at the first frame in the buffer.
if(frame_lock==false)
{
// End of the frame is not detected yet.
// Check if there is service tag for the end of the frame.
if((*buf_scaner).isServEndFrame()!=false)
{
// Got to the end of the first frame: one full frame is in the buffer.
frame_lock = true;
#ifdef LB_EN_DBG_OUT
if((log_level&Binarizer::LOG_PROCESS)!=0)
{
qInfo()<<"[V2D] Detected end of a frame, exiting search...";
}
#endif
break;
}
}
// Go to the next line in the input.
buf_scaner++;
}
if(frame_lock!=false)
{
#ifdef LB_EN_DBG_OUT
if((log_level&Binarizer::LOG_PROCESS)!=0)
{
qInfo()<<"[V2D] Dumping one frame into internal buffer...";
}
#endif
while(in_video->size()>0)
{
frame_buf.push_back(in_video->front());
in_video->pop_front();
if(frame_buf.back().isServEndFrame()!=false)
{
#ifdef LB_EN_DBG_OUT
if((log_level&Binarizer::LOG_PROCESS)!=0)
{
qInfo()<<"[V2D] One frame buffered";
}
#endif
break;
}
}
}
return frame_lock;
}
//------------------------ Pre-scan whole buffer and calculate average data coordinates.
void VideoToDigital::prescanCoordinates(CoordinatePair *out_coords, uint8_t *out_ref)
{
// TODO: prescan most of the frame in INSANE mode.
bool suppress_log;
uint8_t index;
uint16_t lines_cnt, gap_length;
std::vector<uint16_t> scan_ofs;
std::vector<uint8_t> refs_list;
std::vector<CoordinatePair> coord_list;
VideoLine *source_line;
PCM1Line pcm1_line;
PCM16X0SubLine pcm16x0_line;
STC007Line stc007_line;
PCMLine *work_line;
suppress_log = ((log_level&(Binarizer::LOG_PROCESS))==0);
//suppress_log = false;
if((out_coords==NULL)||(out_ref==NULL))
{
#ifdef LB_EN_DBG_OUT
qWarning()<<"[V2D] Unable to prescan, null pointer provided";
#endif
return;
}
lines_cnt = frame_buf.size();
if((lines_cnt<=COORD_CHECK_PARTS)
||(pcm_type==TYPE_STC007)||(pcm_type==TYPE_M2)
||(fine_bin_preset.en_force_coords!=false))
{
#ifdef LB_EN_DBG_OUT
if(suppress_log==false)
{
if((pcm_type==TYPE_STC007)||(pcm_type==TYPE_M2))
{
qInfo()<<"[V2D] Unable to prescan, its disabled for STC-007";
}
else if(fine_bin_preset.en_force_coords!=false)
{
qInfo()<<"[V2D] Unable to prescan, its disabled in fine binarization settings";
}
else if(lines_cnt<=COORD_CHECK_PARTS)
{
QString log_line;
log_line.sprintf("[V2D] Unable to prescan, not enough lines in the buffer: [%03u]<[%03u]",
lines_cnt, COORD_CHECK_PARTS);
qInfo()<<log_line;
}
}
#endif
return;
}
scan_ofs.resize(COORD_CHECK_LINES);
refs_list.reserve(COORD_CHECK_LINES);
coord_list.reserve(COORD_CHECK_LINES);
// Calculate line gap between checked lines.
gap_length = lines_cnt/(COORD_CHECK_PARTS-1);
// Calculate line offsets to perform scan.
for(index=0;index<COORD_CHECK_LINES;index++)
{
scan_ofs[index] = (index+1)*gap_length;
}
#ifdef LB_EN_DBG_OUT
if(suppress_log==false)
{
QString log_line;
qInfo()<<"[V2D] ---------- Starting frame data coordinates prescan...";
log_line = "[V2D] Prescan buffer indexes: ";
for(index=0;index<COORD_CHECK_LINES;index++)
{
log_line += QString::number(scan_ofs[index]);
if(index!=(COORD_CHECK_LINES-1))
{
log_line += ", ";
}
}
log_line += " (scan gap: "+QString::number(gap_length)+" of "+QString::number(lines_cnt)+" lines)";
qInfo()<<log_line;
}
#endif
// Reset everything in binarizer.
line_converter.setGoodParameters();
// Enable coordinates search.
line_converter.setCoordinatesSearch(true);
if(pcm_type==TYPE_PCM1)
{
// Process video line as single PCM line.
line_converter.setLinePartMode(Binarizer::FULL_LINE);
// Take pointer to PCM-1 line object.
work_line = static_cast<PCMLine *>(&pcm1_line);
}
else if(pcm_type==TYPE_PCM16X0)
{
// Right part of the video line (it usually has narrower window of good coordinates).
line_converter.setLinePartMode(Binarizer::PART_PCM16X0_RIGHT);
// Take pointer to PCM-16X0 line object.
work_line = static_cast<PCMLine *>(&pcm16x0_line);
}
else
{
// Process video line as single PCM line.
line_converter.setLinePartMode(Binarizer::FULL_LINE);
// Take pointer to STC-007 line object.
work_line = static_cast<PCMLine *>(&stc007_line);
}
// Set pointer to output PCM line for binarizer.
line_converter.setOutput(work_line);
for(index=0;index<COORD_CHECK_LINES;index++)
{
// Pick source line from the buffer.
source_line = &frame_buf.at(scan_ofs[index]);
if(source_line->isServiceLine()==false)
{
line_converter.setSource(source_line);
line_converter.setMode(binarization_mode);
#ifdef LB_EN_DBG_OUT
if(suppress_log==false)
{
QString log_line;
log_line = "[V2D] ---------- Starting prescan at frame buffer index [";
log_line += QString::number(scan_ofs[index]);
log_line += "] line ["+QString::number(source_line->frame_number)+":"+QString::number(source_line->line_number)+"]...";
qInfo()<<log_line;
}
#endif
// Perform binarization.
line_converter.processLine();
// Check if CRC is valid for the line.
if(work_line->isCRCValid()!=false)
{
// Save found coordinates.
coord_list.push_back(work_line->coords);
// Save reference level for valid coordinates.
refs_list.push_back(work_line->ref_level);
// Update binarizator coordinates.
//line_converter.setGoodParameters(work_line);
//if(coord_list.size()>2) break;
}
}
}
#ifdef LB_EN_DBG_OUT
if(suppress_log==false)
{
QString log_line;
if(coord_list.size()>0)
{
qInfo()<<"[V2D] Coordinates list:";
for(index=0;index<coord_list.size();index++)
{
log_line.sprintf("[%03d:%04d]@[%03u] at line index [%03u]",
coord_list[index].data_start, coord_list[index].data_stop, refs_list[index], scan_ofs[index]);
qInfo()<<log_line;
}
}
}
#endif
// Check if any coordinates were found.
if(coord_list.size()>0)
{
// Sort coordinates.
std::sort(coord_list.begin(), coord_list.end());
// Pick center value.
*out_coords = coord_list.at(coord_list.size()/2);
#ifdef LB_EN_DBG_OUT
if(suppress_log==false)
{
QString log_line;
log_line.sprintf("[V2D] Prescan is finished, coordinates: [%03d:%04d] from [%01u] lines of [%01u]",
out_coords->data_start, out_coords->data_stop, coord_list.size(), COORD_CHECK_LINES);
qInfo()<<log_line;
}
#endif
// Sort reference levels.
std::sort(refs_list.begin(), refs_list.end());
// Pick center value.
*out_ref = refs_list.at(refs_list.size()/2);
#ifdef LB_EN_DBG_OUT
if(suppress_log==false)
{
QString log_line;
log_line.sprintf("[V2D] Reference level selected: [%03u]", (*out_ref));
qInfo()<<log_line;
}
#endif
}
#ifdef LB_EN_DBG_OUT
else
{
if(suppress_log==false)
{
qInfo()<<"[V2D] Prescan is done, no valid coordinates found";
}
}
#endif
}
//------------------------ Apply median filter to the list of coordinates.
CoordinatePair VideoToDigital::medianCoordinates(std::deque<CoordinatePair> *in_list)
{
CoordinatePair dummy;
if(in_list->size()>0)
{
size_t buf_middle;
std::deque<CoordinatePair> sort_buf;
// Copy list for sorting (so source will not be affected).
std::copy(in_list->begin(), in_list->end(), std::inserter(sort_buf, sort_buf.begin()));
// Calculate the middle of the list (for median filtering).
buf_middle = sort_buf.size()/2;
// Put sorted value in that spot.
std::nth_element(sort_buf.begin(), sort_buf.begin()+buf_middle, sort_buf.end());
// Return filtered value.
return sort_buf[buf_middle];
}
else
{
// Nothing in the input list.
// Return dummy invalid coordinates.
return dummy;
}
}
//------------------------ Output PCM line into output queue (blocking).
void VideoToDigital::outNewLine(PCMLine *in_line)
{
size_t queue_size;
bool size_lock;
size_lock = false;
if(in_line->getPCMType()==PCMLine::TYPE_PCM1)
{
//return;
if((out_pcm1==NULL)||(mtx_pcm1==NULL))
{
qWarning()<<DBG_ANCHOR<<"[V2D] Empty PCM-1 pointer provided, result discarded!";
}
else
{
while(1)
{
// Put processed line into the queue.
mtx_pcm1->lock();
queue_size = (out_pcm1->size()+1);
if(queue_size<MAX_PCMLINE_QUEUE_SIZE)
{
out_pcm1->push_back(*static_cast<PCM1Line *>(in_line));
mtx_pcm1->unlock();
if((in_line->isServiceLine()==false)||(in_line->isServFiller()!=false))
{
// Duplicate new line through event.
emit newLine(*static_cast<PCM1Line *>(in_line));
}
if(size_lock!=false)
{
size_lock = false;
#ifdef LB_EN_DBG_OUT
if((log_level&Binarizer::LOG_PROCESS)!=0)
{
qInfo()<<"[V2D] Output PCM-1 line queue has some space, continuing...";
}
#endif
}
break;
}
else
{
mtx_pcm1->unlock();
if(size_lock==false)
{
size_lock = true;
#ifdef LB_EN_DBG_OUT
if((log_level&Binarizer::LOG_PROCESS)!=0)
{
qInfo()<<"[V2D] Output PCM-1 line queue is at size limit ("<<MAX_PCMLINE_QUEUE_SIZE<<"), waiting...";
}
#endif
}
// Wait for queue to free up.
QThread::msleep(50);
}
}
}
}
else if(in_line->getPCMType()==PCMLine::TYPE_PCM16X0)
{
//return;
if((out_pcm16x0==NULL)||(mtx_pcm16x0==NULL))
{
qWarning()<<DBG_ANCHOR<<"[V2D] Empty PCM-16x0 pointer provided, result discarded!";
}
else
{
while(1)
{
// Put processed line into the queue.
mtx_pcm16x0->lock();
queue_size = (out_pcm16x0->size()+1);
if(queue_size<(MAX_PCMLINE_QUEUE_SIZE*PCM16X0SubLine::SUBLINES_PER_LINE))
{
out_pcm16x0->push_back(*static_cast<PCM16X0SubLine *>(in_line));
mtx_pcm16x0->unlock();
if((in_line->isServiceLine()==false)||(in_line->isServFiller()!=false))
{
// Duplicate new line through event.
emit newLine(*static_cast<PCM16X0SubLine *>(in_line));
}
if(size_lock!=false)
{
size_lock = false;
#ifdef LB_EN_DBG_OUT
if((log_level&Binarizer::LOG_PROCESS)!=0)
{
qInfo()<<"[V2D] Output PCM-16x0 line queue has some space, continuing...";
}
#endif
}
break;
}
else
{
mtx_pcm16x0->unlock();
if(size_lock==false)
{
size_lock = true;
#ifdef LB_EN_DBG_OUT
if((log_level&Binarizer::LOG_PROCESS)!=0)
{
qInfo()<<"[V2D] Output PCM-16x0 line queue is at size limit ("<<(MAX_PCMLINE_QUEUE_SIZE*PCM16X0SubLine::SUBLINES_PER_LINE)<<"), waiting...";
}
#endif
}
// Wait for queue to free up.
QThread::msleep(50);
}
}
}
}
else if(in_line->getPCMType()==PCMLine::TYPE_STC007)
{
//return;
if((out_stc007==NULL)||(mtx_stc007==NULL))
{
qWarning()<<DBG_ANCHOR<<"[V2D] Empty STC-007 pointer provided, result discarded!";
}
else
{
while(1)
{
// Put processed line into the queue.
mtx_stc007->lock();
queue_size = (out_stc007->size()+1);
//qInfo()<<"[V2D] Sizes:"<<sizeof(STC007Line)<<queue_size<<MAX_PCMLINE_QUEUE_SIZE;
if(queue_size<MAX_PCMLINE_QUEUE_SIZE)
{
out_stc007->push_back(*static_cast<STC007Line *>(in_line));
mtx_stc007->unlock();
if((in_line->isServiceLine()==false)||(in_line->isServFiller()!=false))
{
// Duplicate new line through event.
emit newLine(*static_cast<STC007Line *>(in_line));
}
if(size_lock!=false)
{
size_lock = false;
#ifdef LB_EN_DBG_OUT
if((log_level&Binarizer::LOG_PROCESS)!=0)
{
qInfo()<<"[V2D] Output STC-007 line queue has some space, continuing...";
}
#endif
}
break;
}
else
{
mtx_stc007->unlock();
if(size_lock==false)
{
size_lock = true;
#ifdef LB_EN_DBG_OUT
if((log_level&Binarizer::LOG_PROCESS)!=0)
{
qInfo()<<"[V2D] Output STC-007 line queue is at size limit ("<<MAX_PCMLINE_QUEUE_SIZE<<"), waiting...";
}
#endif
}
// Wait for queue to free up.
QThread::msleep(50);
}
}
}
}
}
//------------------------ Set debug logging level (LOG_PROCESS, etc...).
void VideoToDigital::setLogLevel(uint8_t new_log)
{
log_level = new_log;
if((log_level&Binarizer::LOG_LINE_DUMP)==0)
{
line_dump_help_done = false;
}
line_converter.setLogLevel(log_level);
}
//------------------------ Set PCM type in source video.
void VideoToDigital::setPCMType(uint8_t in_pcm)
{
line_dump_help_done = false;
#ifdef LB_EN_DBG_OUT
if((log_level&Binarizer::LOG_SETTINGS)!=0)
{
if(in_pcm==TYPE_PCM1)
{
qInfo()<<"[V2D] PCM type set to 'PCM-1'.";
}
else if(in_pcm==TYPE_PCM16X0)
{
qInfo()<<"[V2D] PCM type set to 'PCM-1600/1610/1630'.";
}
else if(in_pcm==TYPE_STC007)
{
qInfo()<<"[V2D] PCM type set to 'STC-007/008/PCM-F1'.";
}
else if(in_pcm==TYPE_M2)
{
qInfo()<<"[V2D] PCM type set to 'M2'.";
}
else
{
qInfo()<<"[V2D] Unknown PCM type provided, ignored!";
}
}
#endif
if(in_pcm<TYPE_MAX)
{
// Set value from the input.
pcm_type = in_pcm;
// Special case for M2, using STC-007 processing but with different sample format.
if(pcm_type==TYPE_M2)
{
pcm_type = TYPE_STC007;
pcm_sample_fmt = PCM_FMT_M2;
}
else
{
pcm_sample_fmt = PCM_FMT_NOT_SET;
}
// Reset "good" settings.
line_converter.setGoodParameters();
// Clear stats.
reset_stats = true;
}
}
//------------------------ Set binarizator mode.
void VideoToDigital::setBinarizationMode(uint8_t in_mode)
{
#ifdef LB_EN_DBG_OUT
if(binarization_mode!=in_mode)
{
if((log_level&Binarizer::LOG_SETTINGS)!=0)
{
if(in_mode==Binarizer::MODE_DRAFT)
{
qInfo()<<"[V2D] Binarization mode set to 'draft'.";
}
else if(in_mode==Binarizer::MODE_FAST)
{
qInfo()<<"[V2D] Binarization mode set to 'fast'.";
}
else if(in_mode==Binarizer::MODE_NORMAL)
{
qInfo()<<"[V2D] Binarization mode set to 'normal'.";
}
else if(in_mode==Binarizer::MODE_INSANE)
{
qInfo()<<"[V2D] Binarization mode set to 'insane'.";
}
else
{
qInfo()<<"[V2D] Unknown binarization mode provided, ignored!";
}
}
}
#endif
if(in_mode<Binarizer::MODE_MAX)
{
// Set value from the input.
binarization_mode = in_mode;
}
}
//------------------------ Set line duplication detection mode.
void VideoToDigital::setCheckLineDup(bool flag)
{
#ifdef LB_EN_DBG_OUT
if(check_line_copy!=flag)
{
if((log_level&Binarizer::LOG_SETTINGS)!=0)
{
if(flag==false)
{
qInfo()<<"[V2D] Line duplication detection set to 'disabled'.";
}
else
{
qInfo()<<"[V2D] Line duplication detection set to 'enabled'.";
}
}
}
#endif
check_line_copy = flag;
}
//------------------------ Set fine binarization settings.
void VideoToDigital::setFineSettings(bin_preset_t in_set)
{
// Clear stats.
reset_stats = true;
// Set binarization fine settings.
fine_bin_preset = in_set;
line_converter.setFineSettings(fine_bin_preset);
// Report about new fine settings.
emit guiUpdFineSettings(fine_bin_preset);
}
//------------------------ Set fine binarization settings to defaults.
void VideoToDigital::setDefaultFineSettings()
{
// Clear stats.
reset_stats = true;
// Reset binarization fine settings.
fine_bin_preset = line_converter.getDefaultFineSettings();
line_converter.setFineSettings(fine_bin_preset);
// Report about new fine settings.
emit guiUpdFineSettings(fine_bin_preset);
}
//------------------------ Get current fine binarization settings.
void VideoToDigital::requestCurrentFineSettings()
{
fine_bin_preset = line_converter.getCurrentFineSettings();
emit guiUpdFineSettings(fine_bin_preset);
}
//------------------------ Main processing loop.
void VideoToDigital::doBinarize()
{
bool force_bad_line, even_line;
uint8_t sub_line_cnt;
uint8_t field_state;
uint8_t prescan_ref;
uint16_t line_in_field_cnt;
uint16_t good_coords_in_field, pcm_lines_in_field;
CoordinatePair frame_avg, target_coord, coord_delta;
std::deque<CoordinatePair> last_valid_coord_list; // Last [COORD_HISTORY_DEPTH] lines' valid data coordinates history.
std::deque<CoordinatePair> frame_valid_coord_list; // Queue of all valid data coordinates for the current frame.
std::deque<CoordinatePair> frame_invalid_coord_list;// Queue of all invalid data coordinates for the current frame.
std::deque<CoordinatePair> long_valid_coords; // Last [COORD_LONG_HISTORY] frames' valid data coordinates history.
quint64 time_spent;
VideoLine source_line;
PCM1Line pcm1_line;
PCM16X0SubLine pcm16x0_line;
STC007Line stc007_line;
PCMLine *work_line;
PCM1Line last_pcm1_line;
PCM16X0SubLine last_pcm16x0_p0_line, last_pcm16x0_p1_line, last_pcm16x0_p2_line;
STC007Line last_stc007_line;
//ArVidLine arvid_line;
#ifdef LB_EN_DBG_OUT
qInfo()<<"[V2D] Launched, thread:"<<this->thread()<<"ID"<<QString::number((uint)QThread::currentThreadId());
#endif
work_line = NULL;
sub_line_cnt = 0;
prescan_ref = 128;
line_in_field_cnt = 0;
good_coords_in_field = pcm_lines_in_field = 0;
signal_quality.clear();
// Check working pointers.
if((in_video==NULL)||(mtx_vid==NULL))
{
qWarning()<<DBG_ANCHOR<<"[V2D] Empty video pointer provided, unable to continue!";
emit finished();
return;
}
QElapsedTimer time_per_line, time_per_frame;
// Inf. loop in a thread.
while(finish_work==false)
{
// Process Qt events.
QApplication::processEvents();
if(finish_work!=false)
{
// Break the loop and do nothing if got shutdown event.
break;
}
// Lock shared access.
mtx_vid->lock();
if(in_video->empty()!=false)
{
// Input queue is empty.
// Unlock shared access.
mtx_vid->unlock();
// Wait (~a frame) for input to fill up.
QThread::msleep(50);
}
else
{
// Wait for sufficient data in the input queue.
if(waitForOneFrame()!=false)
{
// One full frame is available.
// Unlock shared access.
mtx_vid->unlock();
time_per_frame.start();
// Reset field state to "searching new field".
field_state = FIELD_NEW;
// New frame started: reset "good coordinates found" counter (for PCM-16x0).
good_coords_in_field = pcm_lines_in_field = 0;
if(reset_stats!=false)
{
reset_stats = false;
// Reset stats.
last_valid_coord_list.clear();
frame_valid_coord_list.clear();
frame_invalid_coord_list.clear();
long_valid_coords.clear();
target_coord.clear();
frame_avg.clear();
// Reset "good" parameters.
line_converter.setGoodParameters();
}
// Try to prepare some averaged target horizontal data coordinates.
frame_avg.clear();
// Check if forced horizontal data coordinates are set.
if(fine_bin_preset.en_force_coords==false)
{
if(binarization_mode!=Binarizer::MODE_DRAFT)
{
// Find average coordinates for the frame buffer (usefull for markerless PCM formats).
// Don't run this in fastest mode, cause it takes some time.
prescanCoordinates(&frame_avg, &prescan_ref);
}
// Check if frame prescan returned valid coordinates.
if(frame_avg.areValid()==false)
{
// No valid coordinates with prescan.
// Take average from multi-frame stats.
frame_avg = medianCoordinates(&long_valid_coords);
}
else
{
// Valid coordinates were found during prescan.
// Set reference level by prescan.
line_converter.setReferenceLevel(prescan_ref);
}
// Re-check coordinates again.
if(frame_avg.areValid()!=false)
{
// Something valid was found, set it as target data coordinates.
line_converter.setDataCoordinates(frame_avg.data_start, frame_avg.data_stop);
}
}
// Process the buffer line by line.
while(frame_buf.empty()==false)
{
// Pick first line in the buffer.
source_line = frame_buf.front();
frame_buf.pop_front();
// Determine if current line is from even field.
even_line = ((source_line.line_number%2)==0);
line_converter.setLogLevel(log_level);
// Set parameters for converter.
line_converter.setMode(binarization_mode);
line_converter.setSource(&source_line);
if(pcm_type==TYPE_PCM16X0)
{
// Preset number of passes on one video line for PCM-16x0.
sub_line_cnt = PCM16X0SubLine::SUBLINES_PER_LINE;
}
else
{
// Preset default setting: 1 video line = 1 PCM line.
sub_line_cnt = 1;
}
force_bad_line = false;
// Cycle through sub-lines.
while(sub_line_cnt>0)
{
sub_line_cnt--;
time_per_line.start();
// ArVid Audio Debug
//pcm_type = PCMLine::TYPE_ARVA;
// Preset settings for binarizator for selected PCM type.
if(pcm_type==TYPE_PCM1)
{
// Process video line as single PCM-1 line.
line_converter.setLinePartMode(Binarizer::FULL_LINE);
// Check for "real-time" modes.
if((binarization_mode==Binarizer::MODE_DRAFT)||(binarization_mode==Binarizer::MODE_FAST))
{
// Let binarizator run data search until enough lines has passed.
if((good_coords_in_field>2)||(pcm_lines_in_field>2))
{
// Disable coordinates search for fast modes if good enough coordinates were found.
line_converter.setCoordinatesSearch(false);
#ifdef LB_EN_DBG_OUT
if((good_coords_in_field==3)&&((log_level&Binarizer::LOG_PROCESS)!=0))
{
qInfo()<<"[V2D] Enough good CRCs in the frame, coordinates search is disabled for speed.";
}
#endif
}
else
{
// Enable coordinates search.
line_converter.setCoordinatesSearch(true);
}
}
else
{
// Always enable coordinates search for non-realtime modes.
line_converter.setCoordinatesSearch(true);
}
// Make pointer to PCM-1 line object.
work_line = static_cast<PCMLine *>(&pcm1_line);
}
else if(pcm_type==TYPE_PCM16X0)
{
// In this format one video line contains three PCM-16x0 sub-lines.
// Pick part of the line to process.
if(sub_line_cnt==(PCM16X0SubLine::SUBLINES_PER_LINE-1))
{
// Left part of the video line.
line_converter.setLinePartMode(Binarizer::PART_PCM16X0_LEFT);
}
else if(sub_line_cnt==(PCM16X0SubLine::SUBLINES_PER_LINE-2))
{
// Middle part of the video line.
line_converter.setLinePartMode(Binarizer::PART_PCM16X0_MIDDLE);
}
else if(sub_line_cnt==(PCM16X0SubLine::SUBLINES_PER_LINE-3))
{
// Right part of the video line.
line_converter.setLinePartMode(Binarizer::PART_PCM16X0_RIGHT);
}
else
{
qWarning()<<DBG_ANCHOR<<"[V2D] Illegal line part detected:"<<sub_line_cnt;
continue;
}
// Check for "real-time" modes.
if((binarization_mode==Binarizer::MODE_DRAFT)||(binarization_mode==Binarizer::MODE_FAST))
{
// Let binarizator run data search until enough lines has passed.
if((good_coords_in_field>9)||(pcm_lines_in_field>15))
{
// Disable coordinates search for fast modes if good enough coordinates were found.
line_converter.setCoordinatesSearch(false);
#ifdef LB_EN_DBG_OUT
if((good_coords_in_field==4)&&((log_level&Binarizer::LOG_PROCESS)!=0))
{
qInfo()<<"[V2D] Enough good CRCs in the frame, coordinates search is disabled for speed.";
}
#endif
}
else
{
// Enable coordinates search.
line_converter.setCoordinatesSearch(true);
}
}
else
{
// Always enable coordinates search for non-realtime modes.
line_converter.setCoordinatesSearch(true);
}
// Make pointer to PCM-16X0 line object.
work_line = static_cast<PCMLine *>(&pcm16x0_line);
}
else if(pcm_type==TYPE_STC007)
{
// Process video line as single PCM line.
line_converter.setLinePartMode(Binarizer::FULL_LINE);
// Always enable coordinates search, it's fast for STC-007 because of markers.
line_converter.setCoordinatesSearch(true);
// Take pointer to STC-007 line object.
work_line = static_cast<PCMLine *>(&stc007_line);
}
/*else if(pcm_type==TYPE_ARVA)
{
// Process video line as single PCM line.
line_converter.setLinePartMode(Binarizer::FULL_LINE);
// Always enable coordinates search, it's fast for STC-007 because of markers.
line_converter.setCoordinatesSearch(false);
// Take pointer to ArVid Audio line object.
work_line = static_cast<PCMLine *>(&arvid_line);
}*/
else
{
qWarning()<<DBG_ANCHOR<<"[V2D] Unknown PCM type provided:"<<pcm_type;
continue;
}
// Set pointer to output PCM line for binarizer.
line_converter.setOutput(work_line);
#ifdef LB_EN_DBG_OUT
if((log_level&Binarizer::LOG_PROCESS)!=0)
{
QString log_line, sprint_line;
log_line = "[V2D] Frame average coordinates: ";
if(frame_avg.areValid()==false)
{
sprint_line = "[N/A: N/A]";
}
else
{
sprint_line.sprintf("[%03d:%04d]", frame_avg.data_start, frame_avg.data_stop);
}
log_line += sprint_line+", last target: ";
if(target_coord.areValid()==false)
{
sprint_line = "[N/A: N/A]";
}
else
{
sprint_line.sprintf("[%03d:%04d]", target_coord.data_start, target_coord.data_stop);
}
log_line += sprint_line;
qInfo()<<log_line;
}
#endif
// Convert video line into PCM line.
// (perorm AGC, TBC, binarization)
line_converter.processLine();
// Check if processed line contains service tags.
if(work_line->isServiceLine()!=false)
{
// Make no more than one service line from a video line (for PCM-16x0).
sub_line_cnt = 0;
// Current line contains service line.
if((work_line->isServNewFile()!=false)||(work_line->isServEndFile()!=false))
{
// New file has started or playback ended.
line_in_field_cnt = 0;
// Reset stats.
last_valid_coord_list.clear();
frame_valid_coord_list.clear();
frame_invalid_coord_list.clear();
long_valid_coords.clear();
target_coord.clear();
if((work_line->isServEndFile()!=false)||(frame_avg.areValid()==false))
{
// Reset data for the new source.
line_converter.setGoodParameters();
}
#ifdef LB_EN_DBG_OUT
if((log_level&Binarizer::LOG_PROCESS)!=0)
{
qInfo()<<"[V2D] Stats and settings are reset for new source";
}
#endif
}
else if(work_line->isServEndField()!=false)
{
// Video field has ended.
// Set state to "searching new field".
field_state = FIELD_NEW;
line_in_field_cnt = 0;
// New field started: reset "good coordinates found" counter.
good_coords_in_field = 0;
pcm_lines_in_field = 0;
// Reset "last line".
last_pcm1_line.clear();
last_pcm16x0_p0_line.clear(); last_pcm16x0_p1_line.clear(); last_pcm16x0_p2_line.clear();
last_stc007_line.clear();
#ifdef LB_EN_DBG_OUT
if((log_level&Binarizer::LOG_PROCESS)!=0)
{
qInfo()<<"[V2D] Last line copy flushed at the end of the field.";
}
#endif
}
else if(work_line->getPCMType()==PCMLine::TYPE_PCM1)
{
// Check for special service line for PCM-1.
if(pcm1_line.isServHeader()!=false)
{
// Line contains Header.
// Check if Header is at the start of the field.
if(field_state==FIELD_NEW)
{
// Set state to "All next lines in the field are safe to process".
field_state = FIELD_SAFE;
#ifdef LB_EN_DBG_OUT
if(((log_level&Binarizer::LOG_PROCESS)!=0)||((log_level&Binarizer::LOG_LINE_DUMP)!=0))
{
qInfo()<<"[V2D] First line with PCM in new field is safe to process (Header at the top)";
}
#endif
}
else
{
#ifdef LB_EN_DBG_OUT
if((log_level&Binarizer::LOG_PROCESS)!=0)
{
qInfo()<<"[V2D] Header not at the top of the field, possibly Emphasis flag is set";
}
#endif
}
}
}
else if(work_line->getPCMType()==PCMLine::TYPE_STC007)
{
// Check for special service line for STC-007.
if(stc007_line.isServCtrlBlk()!=false)
{
// Line contains Control Block.
//qInfo()<<QString::fromStdString("[DEBUG] "+work_line->dumpContentString());
// Check if Control Block is at the start of the field.
if(field_state==FIELD_NEW)
{
// Set state to "All next lines in the field are safe to process".
field_state = FIELD_SAFE;
#ifdef LB_EN_DBG_OUT
if(((log_level&Binarizer::LOG_PROCESS)!=0)||((log_level&Binarizer::LOG_LINE_DUMP)!=0))
{
qInfo()<<"[V2D] First line with PCM in new field is safe to process (Control Block at the top)";
}
#endif
}
else
{
#ifdef LB_EN_DBG_OUT
if((log_level&Binarizer::LOG_PROCESS)!=0)
{
qInfo()<<"[V2D] Frame composition error: Control Block in the middle of the field!";
}
#endif
}
}
}
}
else
{
// Current line does not contain service tag.
// Count total number of video lines in the frame.
if(even_line==false)
{
signal_quality.lines_odd++;
}
else
{
signal_quality.lines_even++;
}
bool count_has_pcm;
count_has_pcm = false;
// Determine if current line should be count as having PCM data in it.
if(work_line->getPCMType()==PCMLine::TYPE_PCM1)
{
// Check if line contains PCM data.
if((work_line->isCRCValid()!=false)||(work_line->hasBWSet()!=false))
{
// CRC is valid or at least BLACK and WHITE levels were found.
count_has_pcm = true;
}
}
else if(work_line->getPCMType()==PCMLine::TYPE_PCM16X0)
{
// Check if line contains PCM data.
if((work_line->isCRCValid()!=false)||(work_line->hasBWSet()!=false))
{
// CRC is valid or at least BLACK and WHITE levels were found.
count_has_pcm = true;
}
// Add number of the line into the PCM line object.
pcm16x0_line.queue_order = line_in_field_cnt;
}
else if(work_line->getPCMType()==PCMLine::TYPE_STC007)
{
// Check if line contains PCM data.
if((work_line->isCRCValid()!=false)||(stc007_line.hasMarkers()!=false))
{
// CRC is valid or at least PCM markers were found.
count_has_pcm = true;
}
// Set M2 sample format to correctly process silent samples.
if(pcm_sample_fmt==PCM_FMT_M2)
{
stc007_line.setM2Format(true);
}
else
{
stc007_line.setM2Format(false);
}
}
// Check if line contains PCM data.
if(count_has_pcm!=false)
{
// Count lines with PCM.
if(even_line==false)
{
signal_quality.lines_pcm_odd++;
}
else
{
signal_quality.lines_pcm_even++;
}
pcm_lines_in_field++;
// Check if this line as right after the start of the field.
if(field_state==FIELD_NEW)
{
// Set state to "First line in the field is not safe to process with line-copy detection".
// The fact that this line (and not Control Block or Header) is first means that part of the video was cut at the top
// and dropout compensator may have compensated this line from previous ones in cut region.
field_state = FIELD_UNSAFE;
}
}
// Check if previous sub-line (PCM-16x0) was forced bad.
if((work_line->isCRCValid()!=false)&&(force_bad_line!=false))
{
// Force bad state for the line.
work_line->setForcedBad();
#ifdef LB_EN_DBG_OUT
if((log_level&Binarizer::LOG_PROCESS)!=0)
{
qInfo()<<"[V2D] Previous sub-line in the same line was forced bad: forcing sub-line"<<pcm16x0_line.line_part<<"bad";
}
#endif
}
// Check if valid audio data was found.
if(work_line->isCRCValid()!=false)
{
// Line has VALID CRC.
// Increase counter of good CRCs in frame to disable data coordinates search.
good_coords_in_field++;
// Update line length.
signal_quality.line_length = (uint16_t)source_line.pixel_data.size();
// Check if line-copy detection is enabled.
if(check_line_copy!=false)
{
// Current line contains regular audio data.
if(field_state==FIELD_UNSAFE)
{
// This is first line of the new field
// and it is unsafe to check line copy against it.
// Update "good" binarizing parameters (BW levels, ref. level, data coordinates) if CRC is OK.
line_converter.setGoodParameters(work_line);
if(fine_bin_preset.en_first_line_dup!=false)
{
// Force bad state for the line.
work_line->setForcedBad();
force_bad_line = true;
}
#ifdef LB_EN_DBG_OUT
if(((log_level&Binarizer::LOG_PROCESS)!=0)||((log_level&Binarizer::LOG_LINE_DUMP)!=0))
{
qInfo()<<"[V2D] First line with PCM in new field: unsafe to process!";
}
#endif
}
else
{
// Check if current line equals to previous one.
// (that could indicate "too smart" VTR with full-line dropout compensator)
bool same_words;
same_words = false;
// Determine if current line has the same data words as the last one.
if(work_line->getPCMType()==PCMLine::TYPE_PCM1)
{
// Single line for PCM-1.
same_words = pcm1_line.hasSameWords(&last_pcm1_line);
}
else if(work_line->getPCMType()==PCMLine::TYPE_PCM16X0)
{
// Sub-lines for PCM-16x0.
if(pcm16x0_line.line_part==PCM16X0SubLine::PART_LEFT)
{
same_words = pcm16x0_line.hasSameWords(&last_pcm16x0_p0_line);
}
else if(pcm16x0_line.line_part==PCM16X0SubLine::PART_MIDDLE)
{
same_words = pcm16x0_line.hasSameWords(&last_pcm16x0_p1_line);
}
else if(pcm16x0_line.line_part==PCM16X0SubLine::PART_RIGHT)
{
same_words = pcm16x0_line.hasSameWords(&last_pcm16x0_p2_line);
}
}
else if(work_line->getPCMType()==PCMLine::TYPE_STC007)
{
// Single line for STC-007.
same_words = stc007_line.hasSameWords(&last_stc007_line);
}
// Check if line repeats and it is not silent.
if((work_line->isAlmostSilent()==false)&&(same_words!=false))
{
// Lines are not silent but are identical!
work_line->setForcedBad();
// Count bad CRCs and duplicated lines.
if(even_line==false)
{
signal_quality.lines_dup_odd++;
}
else
{
signal_quality.lines_dup_even++;
}
#ifdef LB_EN_DBG_OUT
if((log_level&Binarizer::LOG_PROCESS)!=0)
{
QString log_line;
log_line = "[V2D] Repeated line detected! At ["+QString::number(work_line->frame_number)+":"+QString::number(work_line->line_number)+"]";
qInfo()<<log_line;
}
#endif
}
}
} // check_line_copy!=false
// Re-check if line is still valid.
if(work_line->isCRCValidIgnoreForced()!=false)
{
// Line is still valid.
#ifdef LB_EN_DBG_OUT
if((log_level&Binarizer::LOG_PROCESS)!=0)
{
QString log_line;
log_line.sprintf("[V2D] Adding to coordinates history: [%03d|%04d]",
work_line->coords.data_start, work_line->coords.data_stop);
qInfo()<<log_line;
}
#endif
// Add coordinates from valid data to the lists.
last_valid_coord_list.push_back(work_line->coords);
frame_valid_coord_list.push_back(work_line->coords);
// Keep sliding window at the limited size.
if(work_line->getPCMType()==PCMLine::TYPE_PCM16X0)
{
// Keep all sub-lines in the history.
while(last_valid_coord_list.size()>(COORD_HISTORY_DEPTH*PCM16X0SubLine::SUBLINES_PER_LINE))
{
last_valid_coord_list.pop_front();
}
}
else
{
while(last_valid_coord_list.size()>COORD_HISTORY_DEPTH)
{
last_valid_coord_list.pop_front();
}
}
// Check if coordinate damper is enabled and has collected enough data.
if((coordinate_damper!=false)&&(fine_bin_preset.en_force_coords==false)&&(last_valid_coord_list.size()>(COORD_HISTORY_DEPTH/2)))
{
// Get last lines median coordinates.
target_coord = medianCoordinates(&last_valid_coord_list);
// Check if those are valid.
if(target_coord.areValid()==false)
{
// Not enought history.
// Copy pre-scanned median (or last frames median is falled back).
target_coord = frame_avg;
}
// Re-check if now there are valid coordinates.
if(target_coord.areValid()!=false)
{
// Calculate data coordinates delta between current data coordinates and stats.
coord_delta = work_line->coords;
coord_delta = coord_delta-target_coord;
#ifdef LB_EN_DBG_OUT
if((log_level&Binarizer::LOG_PROCESS)!=0)
{
QString log_line;
log_line.sprintf("[V2D] Coordinate delta: [%03d|%04d], target: [%03d|%04d]",
coord_delta.data_start, coord_delta.data_stop,
target_coord.data_start, target_coord.data_stop);
qInfo()<<log_line;
}
#endif
// Check if coordinate delta is above threshold.
if(coord_delta.hasDeltaWarning(work_line->getPPB()*3)!=false)
{
// Data coordinates drifted too far.
// Make this line invalid.
work_line->setForcedBad();
force_bad_line = true;
#ifdef LB_EN_DBG_OUT
if((log_level&Binarizer::LOG_PROCESS)!=0)
{
QString log_line;
log_line.sprintf("[V2D] Coordinate delta warning! Line [%03u:%03u] data at [%03d|%04d] (d[%03d|%04d]), target at [%03d|%04d]",
work_line->frame_number, work_line->line_number,
work_line->coords.data_start, work_line->coords.data_stop,
coord_delta.data_start, coord_delta.data_stop,
target_coord.data_start, target_coord.data_stop);
qInfo()<<log_line;
}
#endif
}
}
}
}
// Re-check if line is still valid.
if(work_line->isCRCValid()!=false)
{
// Update "good" binarizing parameters (BW levels, ref. level, data coordinates) if CRC is OK.
line_converter.setGoodParameters(work_line);
}
else
{
// Count bad CRCs.
if(even_line==false)
{
signal_quality.lines_bad_odd++;
}
else
{
signal_quality.lines_bad_even++;
}
}
// Update last line for future comparisons.
if(work_line->getPCMType()==PCMLine::TYPE_PCM1)
{
// Update stored last line.
last_pcm1_line = pcm1_line;
// Begining of the field has passed.
field_state = FIELD_INIT;
}
else if(work_line->getPCMType()==PCMLine::TYPE_PCM16X0)
{
// Update stored last line.
if(pcm16x0_line.line_part==PCM16X0SubLine::PART_LEFT)
{
// Last sub-line for the left part.
last_pcm16x0_p0_line = pcm16x0_line;
}
else if(pcm16x0_line.line_part==PCM16X0SubLine::PART_MIDDLE)
{
// Last sub-line for the middle part.
last_pcm16x0_p1_line = pcm16x0_line;
}
else if(pcm16x0_line.line_part==PCM16X0SubLine::PART_RIGHT)
{
// Last sub-line for the right part.
last_pcm16x0_p2_line = pcm16x0_line;
// Begining of the field has passed.
field_state = FIELD_INIT;
}
}
else if(work_line->getPCMType()==PCMLine::TYPE_STC007)
{
// Update stored last line.
last_stc007_line = stc007_line;
// Begining of the field has passed.
field_state = FIELD_INIT;
}
}
// Check if at least PCM was found with bad CRC.
else
{
// CRC was invalid.
bool count_bad_crc;
count_bad_crc = false;
if(signal_quality.line_length==0)
{
// Update line length if not set by valid lines yet.
signal_quality.line_length = (uint16_t)source_line.pixel_data.size();
}
// Line is invalid.
if(work_line->coords.areValid()!=false)
{
// Save coordinates for fallback data coordinates for stats.
frame_invalid_coord_list.push_back(work_line->coords);
}
// Update last line data to compare next time.
if(work_line->getPCMType()==PCMLine::TYPE_PCM1)
{
if(work_line->hasBWSet()!=false)
{
count_bad_crc = true;
// Update stored last line.
last_pcm1_line = pcm1_line;
}
}
else if(work_line->getPCMType()==PCMLine::TYPE_PCM16X0)
{
if(work_line->hasBWSet()!=false)
{
count_bad_crc = true;
// Update stored last line.
if(pcm16x0_line.line_part==PCM16X0SubLine::PART_LEFT)
{
// Last sub-line for the left part.
last_pcm16x0_p0_line = pcm16x0_line;
}
else if(pcm16x0_line.line_part==PCM16X0SubLine::PART_MIDDLE)
{
// Last sub-line for the middle part.
last_pcm16x0_p1_line = pcm16x0_line;
}
else if(pcm16x0_line.line_part==PCM16X0SubLine::PART_RIGHT)
{
// Last sub-line for the right part.
last_pcm16x0_p2_line = pcm16x0_line;
}
}
}
else if(work_line->getPCMType()==PCMLine::TYPE_STC007)
{
if(stc007_line.hasMarkers()!=false)
{
count_bad_crc = true;
// Update stored last line.
last_stc007_line = stc007_line;
}
}
// Check if any PCM data was registered.
if(count_bad_crc!=false)
{
// CRC was bad, count it.
if(even_line==false)
{
signal_quality.lines_bad_odd++;
}
else
{
signal_quality.lines_bad_even++;
}
// Some data probably is there but CRC is invalid.
CoordinatePair preset_coords;
if(fine_bin_preset.en_force_coords==false)
{
// First, preset for median if last valid coordinates.
preset_coords = medianCoordinates(&last_valid_coord_list);
// Check if those are valid.
if(preset_coords.areValid()==false)
{
// Set to last frame median coordinates.
preset_coords = frame_avg;
}
}
#ifdef LB_EN_DBG_OUT
if(((log_level&Binarizer::LOG_PROCESS)!=0)||((log_level&Binarizer::LOG_LINE_DUMP)!=0))
{
if(field_state==FIELD_SAFE)
{
qInfo()<<"[V2D] First line with PCM in new field: safe to process, but bad CRC";
}
else if(field_state==FIELD_UNSAFE)
{
qInfo()<<"[V2D] First line with PCM in new field: unsafe to process and already bad CRC";
}
}
#endif
if(work_line->getPCMType()==PCMLine::TYPE_PCM16X0)
{
if(pcm16x0_line.line_part==PCM16X0SubLine::PART_RIGHT)
{
// Begining of the field has passed.
field_state = FIELD_INIT;
#ifdef LB_EN_DBG_OUT
if((log_level&Binarizer::LOG_PROCESS)!=0)
{
QString log_line;
log_line.sprintf("[V2D] No valid data found, last sub-line passed, set default coordinates to [%03d|%04d]",
preset_coords.data_start, preset_coords.data_stop);
qInfo()<<log_line;
}
#endif
// Try to get a result next time with averaged coordinates.
line_converter.setDataCoordinates(preset_coords);
// Reset preset BW levels.
line_converter.setBWLevels();
}
else
{
// Transfer reference level to next subline in the same line.
line_converter.setReferenceLevel(pcm16x0_line.ref_level);
line_converter.setBWLevels(pcm16x0_line.black_level, pcm16x0_line.white_level);
//if((work_line->isCRCValidIgnoreForced()!=false)||(source_line.scan_done!=false))
if(source_line.scan_done!=false)
{
#ifdef LB_EN_DBG_OUT
if((log_level&Binarizer::LOG_PROCESS)!=0)
{
QString log_line;
log_line.sprintf("[V2D] No valid data found, currently processing sub-line from one line, set default coordinates as to previous part at [%03d|%04d]",
work_line->coords.data_start, work_line->coords.data_stop);
qInfo()<<log_line;
}
#endif
// Try to get a result for next sub-line time with already valid coordinates.
line_converter.setDataCoordinates(work_line->coords);
}
else
{
#ifdef LB_EN_DBG_OUT
if((log_level&Binarizer::LOG_PROCESS)!=0)
{
QString log_line;
log_line.sprintf("[V2D] No valid data found, currently processing sub-line from one line, set default coordinates to [%03d|%04d]",
preset_coords.data_start, preset_coords.data_stop);
qInfo()<<log_line;
}
#endif
// Try to get a result next time with averaged coordinates.
line_converter.setDataCoordinates(preset_coords);
}
}
}
else
{
// Begining of the field has passed.
field_state = FIELD_INIT;
// Try to get a result next time with averaged coordinates.
line_converter.setDataCoordinates(preset_coords);
// Reset preset BW levels.
line_converter.setBWLevels();
}
}
else
{
// Reset preset BW levels.
line_converter.setBWLevels();
}
}
line_in_field_cnt++;
} // service tag presence check
// Check if frame ended.
if(work_line->isServEndFrame()!=false)
{
if(pcm_type==TYPE_PCM1)
{
// Limit number of lines with PCM to standard.
signal_quality.lines_odd = signal_quality.lines_even = PCM1DataStitcher::LINES_PF;
}
else if(pcm_type==TYPE_PCM16X0)
{
// Limit number of lines with PCM to standard.
signal_quality.lines_odd = signal_quality.lines_even = PCM16X0DataStitcher::LINES_PF;
// Account for sub-lines in one line in PCM-16x0.
signal_quality.lines_pcm_odd = signal_quality.lines_pcm_odd/PCM16X0SubLine::SUBLINES_PER_LINE;
signal_quality.lines_pcm_even = signal_quality.lines_pcm_even/PCM16X0SubLine::SUBLINES_PER_LINE;
signal_quality.lines_bad_odd = signal_quality.lines_bad_odd/PCM16X0SubLine::SUBLINES_PER_LINE;
signal_quality.lines_bad_even = signal_quality.lines_bad_even/PCM16X0SubLine::SUBLINES_PER_LINE;
}
// Put counters in limits for GUI.
if(signal_quality.lines_pcm_odd>signal_quality.lines_odd)
{
signal_quality.lines_pcm_odd = signal_quality.lines_odd;
}
if(signal_quality.lines_pcm_even>signal_quality.lines_even)
{
signal_quality.lines_pcm_even = signal_quality.lines_even;
}
if(signal_quality.lines_bad_odd>signal_quality.lines_odd)
{
signal_quality.lines_bad_odd = signal_quality.lines_odd;
}
if(signal_quality.lines_bad_even>signal_quality.lines_even)
{
signal_quality.lines_bad_even = signal_quality.lines_even;
}
// Save processed frame number.
signal_quality.frame_id = work_line->frame_number;
// Get median coordinates for the frame.
// Overwrite pre-scan median, it will be recalculated at the start of the next frame.
frame_avg = medianCoordinates(&frame_valid_coord_list);
if(frame_avg.areValid()!=false)
{
// Save target data coordinates.
signal_quality.data_coord = frame_avg;
// Add filtered coordinates from the current frame to the multi-frame history.
long_valid_coords.push_back(frame_avg);
while(long_valid_coords.size()>COORD_LONG_HISTORY)
{
// Remove oldest entry to keep history size in check.
long_valid_coords.pop_front();
}
}
else
{
// No valid coordinates for current frame.
frame_avg = medianCoordinates(&frame_invalid_coord_list);
if(frame_avg.areValid()==false)
{
// Take median from last frames.
frame_avg = medianCoordinates(&long_valid_coords);
}
// Save target data coordinates.
signal_quality.data_coord = frame_avg;
signal_quality.data_coord.not_sure = true;
}
// Reset frame coordinates stats.
frame_valid_coord_list.clear();
frame_invalid_coord_list.clear();
// Measure time spent on the frame.
time_spent = time_per_frame.nsecsElapsed()/1000;
signal_quality.time_odd = time_spent;
signal_quality.time_even = 0; // TODO: threads per field
emit loopTime(signal_quality.totalProcessTime());
// Report about new binarized frame.
emit guiUpdFrameBin(signal_quality);
//qDebug()<<"[DBG] Time per frame:"<<signal_quality.totalProcessTime();
// Reset tracking.
signal_quality.clear();
}
// Put the resulting PCM line with into PCM lines queue.
outNewLine(work_line);
//qDebug()<<"S1"<<pcm16x0_line.line_part<<time_per_line.nsecsElapsed()/1000;
#ifdef LB_EN_DBG_OUT
if((log_level&Binarizer::LOG_LINE_DUMP)!=0)
{
if(line_dump_help_done==false)
{
uint8_t line_count;
std::string help_line;
line_dump_help_done = true;
// Restart internal help line counter.
work_line->helpDumpRestart();
if(work_line->getPCMType()==PCMLine::TYPE_PCM1)
{
// Set limits for the dump cycle.
line_count = PCM1_LINE_HELP_SIZE;
while(line_count!=0)
{
// Get next help line.
help_line = pcm1_line.helpDumpNext();
if(help_line.size()>0)
{
// Dump help.
qInfo()<<QString::fromStdString("[V2D] "+help_line);
}
else
{
// No more help left.
break;
}
line_count--;
};
}
else if(work_line->getPCMType()==PCMLine::TYPE_PCM16X0)
{
// Set limits for the dump cycle.
line_count = PCM16X0_LINE_HELP_SIZE;
while(line_count!=0)
{
// Get next help line.
help_line = pcm16x0_line.helpDumpNext();
if(help_line.size()>0)
{
// Dump help.
qInfo()<<QString::fromStdString("[V2D] "+help_line);
}
else
{
// No more help left.
break;
}
line_count--;
};
}
else if(work_line->getPCMType()==PCMLine::TYPE_STC007)
{
// Set limits for the dump cycle.
line_count = STC_LINE_HELP_SIZE;
while(line_count!=0)
{
// Get next help line.
help_line = stc007_line.helpDumpNext();
if(help_line.size()>0)
{
// Dump help.
qInfo()<<QString::fromStdString("[V2D] "+help_line);
}
else
{
// No more help left.
break;
}
line_count--;
};
}
}
// Dump raw PCM line into console.
qInfo()<<QString::fromStdString("[V2D] "+work_line->dumpContentString());
}
//qDebug()<<time_per_line.nsecsElapsed()/1000;
#endif
}
// Sub-lines sub-cycle ended.
}
// Internal buffer is empty.
}
else
{
// Not enough data in the input queue.
// Unlock shared access.
mtx_vid->unlock();
// Wait (~a frame) for input to fill up.
QThread::msleep(25);
}
}
}
qInfo()<<"[V2D] Loop stop.";
emit finished();
}
//------------------------ Set "stop thread" flag.
void VideoToDigital::stop()
{
#ifdef LB_EN_DBG_OUT
qInfo()<<"[V2D] Received termination request";
#endif
finish_work = true;
}
| [
"fagear@mail.ru"
] | fagear@mail.ru |
03602683cee677e414553944a4a7874f458d4331 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/curl/gumtree/curl_new_hunk_725.cpp | 0dc2c1ea6587c89f388d4c9783343ff2d3c3b56d | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 391 | cpp | # undef vsnprintf
# undef aprintf
# undef vaprintf
# define printf curl_mprintf
# define fprintf curl_mfprintf
#ifdef CURLDEBUG
/* When built with CURLDEBUG we define away the sprintf functions since we
don't want internal code to be using them */
# define sprintf sprintf_was_used
# define vsprintf vsprintf_was_used
#else
# define sprintf curl_msprintf
# define vsprintf curl_mvsprintf
| [
"993273596@qq.com"
] | 993273596@qq.com |
37cac1621b5cd155027dacd031439628abe0ea92 | fa345d30d723c9cbdb750235c832bb3af635d77f | /690. Employee Importance.cpp | be8670e50c8c526575fac3ff4e810f37b5fc20e2 | [] | no_license | AparnaChinya/100DaysOfCode | 03c50ff1dc7e003f7c3510ee1c40f2c0588021ec | 436ff8302eaeea705d92de4dc8c5a763b84b3348 | refs/heads/master | 2021-07-18T13:24:06.102900 | 2018-12-07T06:04:29 | 2018-12-07T06:04:29 | 72,006,131 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,943 | cpp | /*
690. Employee Importance
You are given a data structure of employee information, which includes the employee's unique id, his importance value and his directsubordinates' id.
For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. They have importance value 15, 10 and 5, respectively. Then employee 1 has a data structure like [1, 15, [2]], and employee 2 has [2, 10, [3]], and employee 3 has [3, 5, []]. Note that although employee 3 is also a subordinate of employee 1, the relationship is not direct.
Now given the employee information of a company, and an employee id, you need to return the total importance value of this employee and all his subordinates.
Example 1:
Input: [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1
Output: 11
Explanation:
Employee 1 has importance value 5, and he has two direct subordinates: employee 2 and employee 3. They both have importance value 3. So the total importance value of employee 1 is 5 + 3 + 3 = 11.
Note:
1. One employee has at most one direct leader and may have several subordinates.
2. The maximum number of employees won't exceed 2000.
From <https://leetcode.com/problems/employee-importance/description/>
*/
/*
// Employee info
class Employee {
public:
// It's the unique ID of each node.
// unique id of this employee
int id;
// the importance value of this employee
int importance;
// the id of direct subordinates
vector<int> subordinates;
};
*/
class Solution {
public:
unordered_map<int,Employee*> myMap;
int dfs(int idNumber) {
Employee *emp = myMap[idNumber];
int sum = emp->importance;
for(auto item : emp->subordinates) {
sum += dfs(item);
}
return sum;
}
int getImportance(vector<Employee*> employees, int id) {
for(auto emp : employees) {
myMap[emp->id] = emp;
}
return dfs(id);
}
};
| [
"apchin@outlook.com"
] | apchin@outlook.com |
4db0f5e3cfa7cdb75dc816de3296837d5d769d8c | faee54f9a7aae830f1d29fbdd9ab3c340772fdd5 | /src/HID-APIs/SurfaceDialAPI.hpp | c09b5d291a709e183cbed890316932df3ff2dbf8 | [
"MIT"
] | permissive | NicoHood/HID | 7a46f0895e7a8c654edcf50f3574aad80e52255e | b16be57caef4295c6cd382a7e4c64db5073647f7 | refs/heads/master | 2023-08-29T21:58:09.295209 | 2022-09-23T22:00:41 | 2022-09-23T22:00:41 | 20,446,682 | 2,201 | 419 | MIT | 2022-12-26T05:30:40 | 2014-06-03T14:47:03 | C | UTF-8 | C++ | false | false | 1,972 | hpp | /*
Copyright (c) 2014-2015 NicoHood
See the readme for credit to other people.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
// Include guard
#pragma once
SurfaceDialAPI::SurfaceDialAPI(void) : _button(false)
{
// Empty
}
void SurfaceDialAPI::begin(void)
{
end();
}
void SurfaceDialAPI::end(void)
{
_button = false;
rotate(0);
}
void SurfaceDialAPI::click(void)
{
_button = true;
rotate(0);
_button = false;
rotate(0);
}
void SurfaceDialAPI::rotate(int16_t rotation)
{
HID_SurfaceDialReport_Data_t report;
report.button = _button;
report.rotation = rotation;
//report.xAxis = x;
//report.yAxis = y;
SendReport(&report, sizeof(report));
}
void SurfaceDialAPI::button(bool b)
{
if (b != _button)
{
_button = b;
rotate(0);
}
}
void SurfaceDialAPI::press(void)
{
button(true);
}
void SurfaceDialAPI::release(void)
{
button(false);
}
void SurfaceDialAPI::releaseAll(void)
{
_button = false;
rotate(0);
}
bool SurfaceDialAPI::isPressed()
{
return _button;
}
| [
"hansmbakker+github@gmail.com"
] | hansmbakker+github@gmail.com |
22b1b05bc41f605db4708b532d6258b3657f9752 | f95975d9454984803586de7f0600f3ecf9918f60 | /algorithms/kernel/linear_regression/linear_regression_train_dense_qr_online_fpt_cpu.cpp | 95c6517e051246346e1e9483f9f69fba9ab6bb8d | [
"Intel",
"Apache-2.0"
] | permissive | jjuribe/daal | f4e05656ca5f01e56debdbd2de51eeb2f506ca3d | 242d358db584dd4c9c65826b345fe63313ff8f2a | refs/heads/master | 2020-09-15T01:33:34.752543 | 2019-11-21T08:27:26 | 2019-11-21T08:27:26 | 223,316,648 | 0 | 0 | Apache-2.0 | 2019-11-22T03:33:41 | 2019-11-22T03:33:39 | null | UTF-8 | C++ | false | false | 1,306 | cpp | /* file: linear_regression_train_dense_qr_online_fpt_cpu.cpp */
/*******************************************************************************
* Copyright 2014-2019 Intel Corporation
*
* 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.
*******************************************************************************/
/*
//++
// Implementation of linear regression training functions for the QR method
// in online compute mode.
//--
*/
#include "linear_regression_train_container.h"
#include "linear_regression_train_dense_qr_impl.i"
namespace daal
{
namespace algorithms
{
namespace linear_regression
{
namespace training
{
namespace interface1
{
template class OnlineContainer<DAAL_FPTYPE, qrDense, DAAL_CPU>;
}
namespace internal
{
template class OnlineKernel<DAAL_FPTYPE, qrDense, DAAL_CPU>;
}
}
}
}
}
| [
"nikolay.a.petrov@intel.com"
] | nikolay.a.petrov@intel.com |
1aabbf0c021395da2262cb5c213a46c1e5bff4d5 | 034f9cb98df7583efd372c65838f7f497cdf5295 | /Stock/Stock/usestock.cpp | 8f4a979b70d6a9e121d2ebd1a2e6ec57c4534f8d | [] | no_license | thb32133451/windows | 9f091209ddb82ed3e12f3b6746010daba9449ce3 | 4a39671265fa37fc638a0862161ed3846a1b8a30 | refs/heads/master | 2021-01-02T22:57:12.377138 | 2018-01-04T00:40:57 | 2018-01-04T00:40:57 | 99,430,383 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 552 | cpp | #include <iostream>
#include "stock-1.h"
int main() {
{
using std::cout;
cout << "Using constructors to create new objects\n";
Stock stock1("NanoSmart", 12, 20.0);
stock1.show();
Stock stock2 = Stock("Boffo objects", 2, 2.0);
stock2.show();
cout << "Assigning stock1 to stock2:\n";
stock2 = stock1;
stock1.show();
stock2.show();
cout << "Using a constructor to reset an object\n";
stock1 = Stock("Nifty Foods", 10, 50.0);
cout << "Revised stock1:\n";
stock1.show();
cout << "Done!\n";
}
std::cin.get();
return 0;
} | [
"2586557491@qq.com"
] | 2586557491@qq.com |
d2673c3eba91f82240389a3294a11638ab039412 | 204b6773cc5c22a6362c39e6936983e7332482e5 | /legend/legend/src/util/resource/geometry_shader.cpp | 643f5559ac281c280da791e6771a5d7cc62f9968 | [] | no_license | matsumoto0112/create_legend | d67632bd071c78d820499085974303a744c365da | 1c84381cbb056bcce2525c67bd3e9de857c05c80 | refs/heads/develop | 2022-12-17T16:03:58.642327 | 2020-09-14T04:40:07 | 2020-09-14T04:40:07 | 274,089,531 | 1 | 0 | null | 2020-09-14T02:18:54 | 2020-06-22T09:03:26 | C++ | SHIFT_JIS | C++ | false | false | 802 | cpp | #include "src/util/resource/geometry_shader.h"
#include "src/game/game_device.h"
namespace legend {
namespace util {
namespace resource {
//コンストラクタ
GeometryShader::GeometryShader() {}
//デストラクタ
GeometryShader::~GeometryShader() {}
//読み込む
bool GeometryShader::Load(const std::wstring& name) {
auto& device = game::GameDevice::GetInstance()->GetDevice();
auto shader_path = Path::GetInstance()->shader();
auto geometry_shader = std::make_shared<directx::shader::GeometryShader>();
if (!geometry_shader->Init(device, shader_path / name)) {
MY_LOG(L"ジオメトリシェーダーの初期化に失敗しました。");
return false;
}
return Register(name, geometry_shader);
}
} // namespace resource
} // namespace util
} // namespace legend | [
"matsumoto.k017a1377@gmail.com"
] | matsumoto.k017a1377@gmail.com |
438805e1ab46df9ed51da18be23b626c1833fd5f | 52ca17dca8c628bbabb0f04504332c8fdac8e7ea | /boost/units/base_units/metric/liter.hpp | 63091ced6d2b9aa403f32b5231d5e7a01d0044ec | [] | no_license | qinzuoyan/thirdparty | f610d43fe57133c832579e65ca46e71f1454f5c4 | bba9e68347ad0dbffb6fa350948672babc0fcb50 | refs/heads/master | 2021-01-16T17:47:57.121882 | 2015-04-21T06:59:19 | 2015-04-21T06:59:19 | 33,612,579 | 0 | 0 | null | 2015-04-08T14:39:51 | 2015-04-08T14:39:51 | null | UTF-8 | C++ | false | false | 75 | hpp | #include "thirdparty/boost_1_58_0/boost/units/base_units/metric/liter.hpp"
| [
"qinzuoyan@xiaomi.com"
] | qinzuoyan@xiaomi.com |
e7099886a5a6e57a2743a463fdc6e6eb0a3d9f1b | ee1ba0f1072864d3d26e3a64085bc88396e6bc15 | /9.cpp | 007ea4d4744d6646e472114561c3f25661a132e0 | [] | no_license | donzoru/data_structure | ffbfba925e99e264fed1b0019b17d591c7493221 | a9d2db406cdde8e6cffbb83128572bd4f1a8b409 | refs/heads/master | 2021-01-12T12:05:41.247597 | 2016-12-15T04:29:42 | 2016-12-15T04:29:42 | 69,233,409 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 649 | cpp | #include<bits/stdc++.h>
using namespace std;
bool mapp[26][26];
bool vis[26];
int n;
char a,b,c;
void dfs(int n)
{
if(n+'A' ==b) return;
for(int i=0;i<26;++i)
{
if(mapp[n][i] && !vis[i]){
vis[i] = 1;
dfs(i);
}
}
}
int main()
{
int m;
memset(mapp,0,sizeof(mapp));
memset(vis,0,sizeof(vis));
cin>>n;
c = getchar();
while((a=getchar())!='\n');
cin>>m;
while(m--){
cin>>a>>b;
mapp[a-'A'][b-'A'] = 1;
}
cin>>a>>b;
dfs(a-'A');
if(vis[b-'A']) printf("1\n");
else printf("0\n");
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
2f37286b95ecb0fa3856afa7f2480312221d7044 | 088c2bfdcefef3799aecd08359e40bac8848d0f1 | /Assignment 4.2.cpp | 58a1b944f5d3480e5b12d45825e7db72978fd216 | [] | no_license | nddat1908/T1908A | 6f403182a87f0e692af2659d5ca36b38e9183fff | 7df56835aaa4d5cd599759b694efaf5934c106c2 | refs/heads/master | 2020-07-13T15:25:39.178989 | 2019-09-19T09:03:29 | 2019-09-19T09:03:29 | 205,105,942 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 350 | cpp | #include<stdio.h>
int main(){
int a,b,c;
scanf("%d",&a);
scanf("%d",&b);
scanf("%d",&c);
int i = 1;
while(i<(a+b)&&i<(a+c)&&(i<b+c)){
if((a+b>c) && (a + c>b)&& (b+c>a)){
printf("La 3 canh cua tam giac\n");
return 0;
}else{
printf("Nhap lai:\n");
scanf("%d",&a);
scanf("%d",&b);
scanf("%d",&c);
}
i++;
}
}
| [
"54591227+nddat1908@users.noreply.github.com"
] | 54591227+nddat1908@users.noreply.github.com |
49d268bc4db7a041e7468cd27e88ab552fb15f8d | b5a443c6dfc570af51e23367ef1b0afc7a3fd035 | /Graphs/inCpp/adjacency_list.cpp | 3946efeb736756547c34165b3f872a2873a7ca39 | [] | no_license | saychakra/DS_Algorithms | c4eaea047096c5a0251f719bb824c3ba5e463815 | 02fdecf83c53565e11311ce500c6045a3ba33ccd | refs/heads/main | 2023-02-02T04:35:43.030963 | 2020-12-06T18:38:14 | 2020-12-06T18:38:14 | 298,683,980 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,037 | cpp | #include <bits/stdc++.h>
using namespace std;
void addEdge(vector<int> adjList[], int src, int dest) {
adjList[src].push_back(dest);
adjList[dest].push_back(src); // since this is an undirected graph, we need to put in both the directions
}
void printGraph(vector<int> adjList[], int v) {
for(int i = 0; i < v; i++) {
cout << "Adjacency list of vertex " << i << "\nhead ";
for(auto x : adjList[i]) {
cout << " -> " << x;
}
cout << endl;
}
}
int main() {
// ios_base::sync_with_stdio(false);
// cin.tie(NULL);
int v;
cout << "Enter the number of vertices you wish to enter: ";
cin >> v;
vector<int> adjList[v];
addEdge(adjList, 0, 1);
addEdge(adjList, 0, 4);
addEdge(adjList, 1, 2);
addEdge(adjList, 1, 3);
addEdge(adjList, 1, 4);
addEdge(adjList, 2, 3);
addEdge(adjList, 3, 4);
cout << "\nPrinting the graph in adjacency list format: ";
printGraph(adjList, v);
return 0;
}
/*
0 - 1 \
| / | / 2
4 - 3
*/ | [
"saychakra@gmail.com"
] | saychakra@gmail.com |
1ef2a292701b5104479614d03b26c0844e3c0e3e | b756014ce8ce5ada5edd5500816bb79953fbddb3 | /Linked_List/priority.cpp | 4b964e0e39de1e7b9459b34f8422a00524663580 | [] | no_license | berkayalatas/data-structures-and-algorithms | d0e50d974028f5500dc4364c246f696e43c7972b | 4a0fc44a1071f8ee5319e88eb74c013f6d90b234 | refs/heads/main | 2023-01-31T05:35:10.462248 | 2020-12-12T21:32:13 | 2020-12-12T21:32:13 | 320,926,445 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,893 | cpp | #include<iostream>
#include<cstdlib>
//ilk giren ilk cikar. 8 elemandan ilk 4'ü cikar.
using namespace std;
typedef struct node
{
int data;
int priority;
struct node* next;
} Node;
//function to create new node
Node* newNode(int new_data, int p)
{
Node* temp = (Node*)malloc(sizeof(Node));
temp->data = new_data;
temp->priority = p;
temp->next = NULL;
return temp;
}
//return the value at head
int peek(Node** head)
{
return (*head)->data;
}
//removes the element with the
// highest priority form the list
void pop(Node** head)
{
Node* temp = *head;
(*head) = (*head)->next;
free(temp);
}
void push(Node** head, int d, int p)
{
Node* start = (*head);
// Create new Node
Node* temp = newNode(d, p);
// Special Case: The head of list has
// lesser priority than new node. So
// insert newnode before head node
// and change head node.
if ((*head)->priority > p)
{
temp->next = *head;
(*head) = temp;
}
else
{
// Traverse the list and find a
// position to insert new node
while (start->next != NULL &&
start->next->priority < p)
{
start = start->next;
}
// Either at the ends of the list
// or at required position
temp->next = start->next;
start->next = temp;
}
}
// Function to check is list is empty
int isEmpty(Node** head)
{
return (*head) == NULL;
}
int main()
{
int a,b,c,d,e,f,g,h;
cout<<"8 rakam giriniz: "<<endl;
cin>>a;
cin>>b;
cin>>c;
cin>>d;
cin>>e;
cin>>f;
cin>>g;
cin>>h;
Node* pq = newNode(a, e);
push(&pq, b, f);
push(&pq, c, g);
push(&pq, d, h);
/*
// Create a Priority Queue
// 7->4->5->6
Node* pq = newNode(4, 1);
push(&pq, 5, 2);
push(&pq, 6, 3);
push(&pq, 7, 0);
*/
while (!isEmpty(&pq))
{
cout << " " << peek(&pq);
pop(&pq);
}
return 0;
}
| [
"berkay.3304@gmail.com"
] | berkay.3304@gmail.com |
68270316a91adc2cd0fd66d49bba5fbf923fd949 | 72d9009d19e92b721d5cc0e8f8045e1145921130 | /Rpvt/inst/testfiles/CO_STANDING/libFuzzer_CO_STANDING/CO_STANDING_DeepState_TestHarness.cpp | 870b4428a84cf6355cc539d7da63a7b657dc1890 | [] | no_license | akhikolla/TestedPackages-NoIssues | be46c49c0836b3f0cf60e247087089868adf7a62 | eb8d498cc132def615c090941bc172e17fdce267 | refs/heads/master | 2023-03-01T09:10:17.227119 | 2021-01-25T19:44:44 | 2021-01-25T19:44:44 | 332,027,727 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,024 | cpp | // AUTOMATICALLY GENERATED BY RCPPDEEPSTATE PLEASE DO NOT EDIT BY HAND, INSTEAD EDIT
// CO_STANDING_DeepState_TestHarness_generation.cpp and CO_STANDING_DeepState_TestHarness_checks.cpp
#include <fstream>
#include <RInside.h>
#include <iostream>
#include <RcppDeepState.h>
#include <qs.h>
#include <DeepState.hpp>
double CO_STANDING(double t, const double p, const double api, const double spgr, const double rsi, const double tsc, const double psca, const double tpc, const double ppc);
TEST(Rpvt_deepstate_test,CO_STANDING_test){
static int rinside_flag = 0;
if(rinside_flag == 0)
{
rinside_flag = 1;
RInside R;
} std::time_t current_timestamp = std::time(0);
std::cout << "input starts" << std::endl;
NumericVector t(1);
t[0] = RcppDeepState_double();
std::string t_t = "/home/akhila/fuzzer_packages/fuzzedpackages/Rpvt/inst/testfiles/CO_STANDING/libFuzzer_CO_STANDING/libfuzzer_inputs/" + std::to_string(current_timestamp) +
"_t.qs";
qs::c_qsave(t,t_t,
"high", "zstd", 1, 15, true, 1);
std::cout << "t values: "<< t << std::endl;
NumericVector p(1);
p[0] = RcppDeepState_double();
std::string p_t = "/home/akhila/fuzzer_packages/fuzzedpackages/Rpvt/inst/testfiles/CO_STANDING/libFuzzer_CO_STANDING/libfuzzer_inputs/" + std::to_string(current_timestamp) +
"_p.qs";
qs::c_qsave(p,p_t,
"high", "zstd", 1, 15, true, 1);
std::cout << "p values: "<< p << std::endl;
NumericVector api(1);
api[0] = RcppDeepState_double();
std::string api_t = "/home/akhila/fuzzer_packages/fuzzedpackages/Rpvt/inst/testfiles/CO_STANDING/libFuzzer_CO_STANDING/libfuzzer_inputs/" + std::to_string(current_timestamp) +
"_api.qs";
qs::c_qsave(api,api_t,
"high", "zstd", 1, 15, true, 1);
std::cout << "api values: "<< api << std::endl;
NumericVector spgr(1);
spgr[0] = RcppDeepState_double();
std::string spgr_t = "/home/akhila/fuzzer_packages/fuzzedpackages/Rpvt/inst/testfiles/CO_STANDING/libFuzzer_CO_STANDING/libfuzzer_inputs/" + std::to_string(current_timestamp) +
"_spgr.qs";
qs::c_qsave(spgr,spgr_t,
"high", "zstd", 1, 15, true, 1);
std::cout << "spgr values: "<< spgr << std::endl;
NumericVector rsi(1);
rsi[0] = RcppDeepState_double();
std::string rsi_t = "/home/akhila/fuzzer_packages/fuzzedpackages/Rpvt/inst/testfiles/CO_STANDING/libFuzzer_CO_STANDING/libfuzzer_inputs/" + std::to_string(current_timestamp) +
"_rsi.qs";
qs::c_qsave(rsi,rsi_t,
"high", "zstd", 1, 15, true, 1);
std::cout << "rsi values: "<< rsi << std::endl;
NumericVector tsc(1);
tsc[0] = RcppDeepState_double();
std::string t_t = "/home/akhila/fuzzer_packages/fuzzedpackages/Rpvt/inst/testfiles/CO_STANDING/libFuzzer_CO_STANDING/libfuzzer_inputs/" + std::to_string(current_timestamp) +
"_t.qs";
std::string tsc_t = "/home/akhila/fuzzer_packages/fuzzedpackages/Rpvt/inst/testfiles/CO_STANDING/libFuzzer_CO_STANDING/libfuzzer_inputs/" + std::to_string(current_timestamp) +
"_tsc.qs";
qs::c_qsave(tsc,tsc_t,
"high", "zstd", 1, 15, true, 1);
std::cout << "tsc values: "<< tsc << std::endl;
NumericVector psca(1);
psca[0] = RcppDeepState_double();
std::string p_t = "/home/akhila/fuzzer_packages/fuzzedpackages/Rpvt/inst/testfiles/CO_STANDING/libFuzzer_CO_STANDING/libfuzzer_inputs/" + std::to_string(current_timestamp) +
"_p.qs";
std::string psca_t = "/home/akhila/fuzzer_packages/fuzzedpackages/Rpvt/inst/testfiles/CO_STANDING/libFuzzer_CO_STANDING/libfuzzer_inputs/" + std::to_string(current_timestamp) +
"_psca.qs";
qs::c_qsave(psca,psca_t,
"high", "zstd", 1, 15, true, 1);
std::cout << "psca values: "<< psca << std::endl;
NumericVector tpc(1);
tpc[0] = RcppDeepState_double();
std::string t_t = "/home/akhila/fuzzer_packages/fuzzedpackages/Rpvt/inst/testfiles/CO_STANDING/libFuzzer_CO_STANDING/libfuzzer_inputs/" + std::to_string(current_timestamp) +
"_t.qs";
std::string tpc_t = "/home/akhila/fuzzer_packages/fuzzedpackages/Rpvt/inst/testfiles/CO_STANDING/libFuzzer_CO_STANDING/libfuzzer_inputs/" + std::to_string(current_timestamp) +
"_tpc.qs";
qs::c_qsave(tpc,tpc_t,
"high", "zstd", 1, 15, true, 1);
std::cout << "tpc values: "<< tpc << std::endl;
NumericVector ppc(1);
ppc[0] = RcppDeepState_double();
std::string p_t = "/home/akhila/fuzzer_packages/fuzzedpackages/Rpvt/inst/testfiles/CO_STANDING/libFuzzer_CO_STANDING/libfuzzer_inputs/" + std::to_string(current_timestamp) +
"_p.qs";
std::string ppc_t = "/home/akhila/fuzzer_packages/fuzzedpackages/Rpvt/inst/testfiles/CO_STANDING/libFuzzer_CO_STANDING/libfuzzer_inputs/" + std::to_string(current_timestamp) +
"_ppc.qs";
qs::c_qsave(ppc,ppc_t,
"high", "zstd", 1, 15, true, 1);
std::cout << "ppc values: "<< ppc << std::endl;
std::cout << "input ends" << std::endl;
try{
CO_STANDING(t[0],p[0],api[0],spgr[0],rsi[0],tsc[0],psca[0],tpc[0],ppc[0]);
}
catch(Rcpp::exception& e){
std::cout<<"Exception Handled"<<std::endl;
}
}
| [
"akhilakollasrinu424jf@gmail.com"
] | akhilakollasrinu424jf@gmail.com |
9fbce19c8ada8a9d5ee3996ac20ca01c800652ce | 5a0d25eb307984f564527bc1875933b9b68f612e | /ptz/tour4/A/a.cpp | 6db0f332e152630f3ec84fb30725ac81109a7fb2 | [] | no_license | ssmike/acm | b42e74f7456e7961ccf1fda36b3e2cf90b2b6076 | c9ce1876ce3a3ad23846923a2bce85b53dc64c82 | refs/heads/master | 2016-09-09T22:19:19.502341 | 2015-08-21T17:04:32 | 2015-08-21T17:04:32 | 30,544,731 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,764 | cpp | #include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <iostream>
#include <cassert>
#include <cmath>
#include <string>
#include <queue>
#include <set>
#include <map>
#include <cstdlib>
using namespace std;
#define INF 1e+9
#define mp make_pair
#define pb push_back
#define fi first
#define fs first
#define se second
#define i64 long long
#define li long long
#define lint long long
#define pii pair<int, int>
#define vi vector<int>
#define forn(i, n) for (int i = 0; i < (int)n; i++)
#define fore(i, b, e) for (int i = (int)b; i <= (int)e; i++)
#define TASKNAME "adsadasd"
void solve(int test_number);
int main() {
ios_base::sync_with_stdio(false);
cout.setf(ios::fixed);
cout.precision(9);
cerr.setf(ios::fixed);
cerr.precision(3);
#ifdef LOCAL
freopen("inp", "r", stdin);
//freopen("outp", "w", stdout);
#else
// freopen(TASKNAME ".in", "r", stdin);
// freopen(TASKNAME ".out", "w", stdout);
#endif
int n = 1;
forn(i, n)
solve(i);
}
bool check_more_eq(int pos, int X)
{
if (exact[pos])
{
return pref[pos] >= X;
}
bool f = check_more_eq(p[pos], X - 1);
if (f)
{
}
}
void solve(int test_number)
{
scanf("%d%d", &n, &m);
forn(p, n)
order.push(p);
forn(iter, n - 1)
{
order.push(iter + n + 1);
op_cnt = 5;
calc();
printf("$ 0\n");
fflush(stdout);
}
int cur = 0;
fore(iter, n, m - 1)
{
//order.push(iter + n + 1);
op_cnt = 5;
if (!check_more_eq(n + iter, n - 1))
{
printf("$ %d\n", cur);
}
else
{
if (check_more_eq(n + iter + 1, n))
}
}
}
| [
"surinmike@gmail.com"
] | surinmike@gmail.com |
cd2432951eaa356d85c0119566f7b980e2290ae8 | 45825ba94ceec26a791dfb3fb373a12edfb0c5dd | /trees.cpp | 5273332ab662f457d2e9ded7bb0e42d61e0d8aff | [] | no_license | divayjindal95/Algorithms | fd8c90aca5a4005f955fe20158649efe7f821c0a | 73937bbcff328b703c556450e13bc7fd6d81a9c2 | refs/heads/master | 2021-01-18T14:16:00.619639 | 2015-09-18T06:13:17 | 2015-09-18T06:13:17 | 41,728,099 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,642 | cpp | #include<iostream>
#include<stdlib.h>
using namespace std;
struct node{
int key;
node *left=NULL;
node *right=NULL;
node *parent=NULL;
};
struct node* rec_insert(struct node *root , int key){
struct node *temp;
if(root==NULL){
//root=(struct node*)malloc(sizeof(struct node));
root=new node;
root->key=key;
root->left=NULL;
root->right=NULL;
root->parent=NULL;
return root;
}
if(root->key>=key){
root->left=rec_insert(root->left,key);
root->left->parent=root;
}
else{
root->right=rec_insert(root->right,key);
root->right->parent=root;
}
return root;
}
struct node* iterative_insert(struct node *root , int key){
struct node *x , *y;
x=root;
y=NULL;
while(x!=NULL){
y=x;
if(x->key<=key) x=x->left;
else x=x->right;
}
struct node *z;
z=new node;
z->key=key;
z->left=NULL;
z->right=NULL;
z->parent=y;
if(y==NULL) return z;
elseif(z->key<=y->key) y->left=z;
else y->right=z;
}
return root;
}
struct node* search(struct node *root,int key){
if(root==NULL) return NULL;
if(root->key==key) return root;
if(root->key>key) return search(root->left);
else return search(root->right);
}
struct node* iterative_search(struct node *root ,int key){
while(1){
if(root==NULL) return root;
if(root->key==key) return root;
if(root->key<key) root=root->left;
else root=root->right;
}
return root;
}
void preorder(struct node *root){
}
int main(){
struct node *root=NULL;
int key;
root=rec_insert(root,5);
root=rec_insert(root,4);
}
| [
"jindal.divay2@gmail.com"
] | jindal.divay2@gmail.com |
3d9510d770a5a790e82abbb35d9dcbb49b984ed6 | 3280f8861acd201c9859e481b0501352da9a5dc2 | /Pong.cpp | ce0c65ac21a6dea34830cf27e7cd21e2c4178633 | [] | no_license | Jurosale/CplusplusProjects | e4c4617c28f75fdaa41bbb3d5c62c14ab3c774ce | 7040c0512fd46eece9f4a3fde9dba34c0c97b848 | refs/heads/master | 2020-04-17T21:46:25.594150 | 2019-01-22T09:44:23 | 2019-01-22T09:44:23 | 166,965,564 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,538 | cpp | #include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <SFML/Audio.hpp>
#include <SFML/Network.hpp>
#include <SFML/System.hpp>
#include <SFML/OpenGL.hpp>
#include <SFML/Main.hpp>
#include <cmath>
#include <ctime>
#include <iostream>
#include <sstream>
#include <string>
#define PI 3.14159265
//Sets up the dimensions and positions that we'll be using throughout the program
float widthWin = 800.0f;
float lengthWin = 600.0f;
float widthPad = 20.0f;
float lengthPad = 100.0f;
float ypos1 = (lengthWin / 2) - (lengthPad/2);
float ypos2 = (lengthWin / 2) - (lengthPad / 2);
float radiusBall = 10.0f;
float xposBstart = (widthWin / 2);
float yposBstart = (lengthWin / 2);
//sets up flags and other in game elements to trigger events
int winner = 0;
int players = 0;
bool isSpawn = true;
bool checkForPlayers = true;
bool twoballs = true;
bool collidedObs;
bool collidedObs2;
time_t timer;
double delay;
//initalizes all the SFML tools we'll need for this project
sf::RectangleShape rect;
sf::CircleShape sphere;
sf::Font font;
sf::Texture background;
sf::SoundBuffer cheer;
sf::Sound sound;
//sets up the classes for the paddles and ball
struct Vector2f {
float x;
float y;
};
class Paddle {
public:
sf::Color color;
Vector2f dim;
Vector2f pos;
Vector2f vel;
int score;
void set_properties(float, float, float, float, sf::Color);
sf::RectangleShape update();
bool collided(float,float, float);
sf::Text displayScore(int, int);
sf::RectangleShape obs_update(float);
};
class Ball {
public:
sf::Color color;
float radius;
Vector2f pos;
Vector2f vel;
int point;
void set_properties(float, float, float, float, float, sf::Color);
sf::CircleShape update(float);
double startRound();
void bounceStuff(float, float, float, float);
};
int main()
{
sf::RenderWindow window(sf::VideoMode(widthWin, lengthWin), "Welcome to Pong!");
font.loadFromFile("BERNHC.ttf");
background.loadFromFile("background.jpg");
cheer.loadFromFile("cheer2.wav");
//this part of code provided by SFML tutorials
//displays the background image
sf::Sprite bg;
bg.setTexture(background);
bg.setTextureRect(sf::IntRect(0, 0, widthWin, lengthWin));
bg.setColor(sf::Color(255, 255, 255, 200));
sound.setBuffer(cheer);
srand(time(NULL));
sf::Clock clock;
//creats the paddles, obstacle, and ball and gives them their starting values
Paddle player1, player2, obstacle;
Ball ball, ball2;
player1.set_properties(widthPad, lengthPad, widthPad, ypos1, sf::Color::Red);
player2.set_properties(widthPad, lengthPad, widthWin - widthPad*2, ypos2, sf::Color::Blue);
obstacle.set_properties(widthPad, lengthPad, widthWin/2, 0, sf::Color::Black);
ball.set_properties(radiusBall, xposBstart, yposBstart, 0.0f, 0.0f, sf::Color::White);
player1.vel.y = 500.0f;
player2.vel.y = 500.0f;
obstacle.vel.y = 10.0f;
//this part of code provided by SFML tutorials
//Displays the inital text that tells the player to pick 1 or 2 players
sf::Text result;
result.setFont(font);
result.setCharacterSize(70);
result.setColor(sf::Color::Yellow);
result.setStyle(sf::Text::Bold);
result.setPosition(xposBstart/4 , yposBstart/2);
result.setString("Press '1' for 1 player,\n '2' for 2 players ");
window.clear();
window.draw(result);
window.display();
//the game loop
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) { window.close(); } }
//continues to play as long as no winner has been declared yet
if (winner == 0 && players != 0) {
//When someone has scores a point, the ball resets back to the center and the 2nd ball (if active) disappears
if (isSpawn) {
timer = time(NULL);
delay = ball.startRound();
ball2.pos.x = xposBstart;
ball2.pos.y = -yposBstart;
ball2.vel.x = 0;
ball2.vel.y = 0;
twoballs = true;
isSpawn = false;
}
float dt = clock.restart().asSeconds();
window.clear();
window.draw(bg);
window.draw(player1.update());
window.draw(player2.update());
window.draw(obstacle.obs_update(dt));
//this part of the code ensures the obstacle doesn't move through the ball as it's respawning back to the center
if (difftime(time(NULL), timer) < delay && (collidedObs == true)) {
if (obstacle.vel.y > 0) { obstacle.pos.y += obstacle.dim.y; }
else { obstacle.pos.y -= obstacle.dim.y; }
}
//the ball will start moving once it's delay timer is up
else if (difftime(time(NULL), timer) > delay) { window.draw(ball.update(dt)); }
else {
window.draw(ball.update(0));
}
//if 15 seconds have passed, a 2nd ball spawns out of the 1st ball
if (difftime(time(NULL), timer) > 15.0f && twoballs) {
float uselessFloat = ball2.startRound();
ball2.set_properties(radiusBall, ball.pos.x, ball.pos.y, ball2.vel.x, ball2.vel.y, sf::Color::White);
twoballs = false;
}
//checks and updates the 2nd ball for collisions between the paddles and obstacle
if (difftime(time(NULL), timer) > 15.0f) {
window.draw(ball2.update(dt));
bool collideP1b2 = player1.collided(ball2.pos.x, ball2.pos.y, ball2.radius);
bool collideP2b2 = player2.collided(ball2.pos.x, ball2.pos.y, ball2.radius);
collidedObs2 = obstacle.collided(ball2.pos.x, ball2.pos.y, ball2.radius);
if (collideP1b2) { ball2.bounceStuff(player1.pos.x, player1.pos.y, player1.dim.x, player1.dim.y); }
else if (collideP2b2) { ball2.bounceStuff(player2.pos.x, player2.pos.y, player2.dim.x, player2.dim.y); }
else if (collidedObs2) { ball2.bounceStuff(obstacle.pos.x, obstacle.pos.y, obstacle.dim.x, obstacle.dim.y); }
}
//checks and updates the original ball for collisions between the paddles and obstacle
bool collideP1 = player1.collided(ball.pos.x, ball.pos.y, ball.radius);
bool collideP2 = player2.collided(ball.pos.x, ball.pos.y, ball.radius);
collidedObs = obstacle.collided(ball.pos.x, ball.pos.y, ball.radius);
if (collideP1) { ball.bounceStuff(player1.pos.x, player1.pos.y, player1.dim.x, player1.dim.y); }
else if (collideP2) { ball.bounceStuff(player2.pos.x, player2.pos.y, player2.dim.x, player2.dim.y); }
else if (collidedObs) { ball.bounceStuff(obstacle.pos.x, obstacle.pos.y, obstacle.dim.x, obstacle.dim.y); }
//this code tells the paddles to update their respective scores when they score a point
if (ball.point == 1 || ball2.point == 1) {
player1.score++;
ball.point = 0;
ball2.point = 0;
}
if (ball.point == -1 || ball2.point == -1) {
player2.score++;
ball.point = 0;
ball2.point = 0;
}
//If either player reaches 5 points, the game declares them the winner
if (player1.score >= 5) {
winner = 1;
result.setString("Player 1 Wins!");
result.setColor(sf::Color::Red);
window.draw(result);
}
else if (player2.score >= 5) {
winner = 2;
result.setString("Player 2 Wins!");
result.setColor(sf::Color::Blue);
window.draw(result);
}
window.draw(player1.displayScore(player1.score, 1));
window.draw(player1.displayScore(player2.score, 2));
window.display();
//updates the paddles movement based on player(s) input or ball position in the AI's case
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W) && player1.pos.y > 0.0f) { player1.pos.y -= player1.vel.y*dt; }
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S) && (player1.pos.y + player1.dim.y) < lengthWin) { player1.pos.y += player1.vel.y*dt; }
if (players == 1) {
if (player2.pos.y + (player2.dim.y / 2) > ball.pos.y && player2.pos.y > 0.0f) { player2.pos.y -= player2.vel.y*dt*.75; }
else if (player2.pos.y + (player2.dim.y / 2) < ball.pos.y && (player2.pos.y + player2.dim.y) < lengthWin) { player2.pos.y += player2.vel.y*dt*.75; }
}
else if (players == 2) {
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up) && player2.pos.y > 0.0f) { player2.pos.y -= player2.vel.y*dt; }
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down) && (player2.pos.y + player2.dim.y) < lengthWin) { player2.pos.y += player2.vel.y*dt; }
}
}
//When someone has won, the player(s) can press 'space' to start a new game
if (winner != 0 && sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) {
player1.score = 0;
player2.score = 0;
player1.pos.y = ypos1;
player2.pos.y = ypos2;
obstacle.pos.y = 0;
winner = 0;
float dt = clock.restart().asSeconds();
result.setString("");
}
//takes the input from the very beginning of the game to determine the number of players
if (checkForPlayers) {
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Num1)) {
players = 1;
checkForPlayers = false;
result.setString("");
result.setPosition(xposBstart - xposBstart / 2, yposBstart);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Num2)) {
players = 2;
checkForPlayers = false;
result.setString("");
result.setPosition(xposBstart - xposBstart / 2, yposBstart);
}
}
}
return 0;
}
//sets up the initial values for all of paddle's attributes
void Paddle::set_properties(float w, float l, float x, float y, sf::Color c) {
dim.x = w;
dim.y = l;
pos.x = x;
pos.y = y;
color = c;
score = 0;
rect.setSize(sf::Vector2f(dim.x, dim.y));
rect.setPosition(pos.x,pos.y);
rect.setFillColor(color);
}
//constantly updates the paddle's position
sf::RectangleShape Paddle::update() {
rect.setPosition(pos.x, pos.y);
rect.setFillColor(color);
return rect;
}
//This portion of code provided by Walter's example
//checks whether or not the paddle is colliding with the ball
bool Paddle::collided(float xpos, float ypos, float rad) {
return pos.x + dim.x >= xpos &&
pos.x < xpos + rad*2 &&
pos.y + dim.y >= ypos &&
pos.y < ypos + rad*2;
}
//This part of the code provided by SFML tutorials
//displays the player of the respective paddle's score on the top
sf::Text Paddle::displayScore(int currScore, int numP) {
std::stringstream ss;
ss << currScore;
std::string str = ss.str();
sf::Text text;
text.setFont(font);
text.setCharacterSize(100);
text.setColor(sf::Color::Yellow);
text.setStyle(sf::Text::Bold);
text.setString(str);
if (numP == 1) { text.setPosition((widthWin / 2) - widthWin / 4, 0.0f); }
else { text.setPosition((widthWin / 2) - 50 + widthWin / 4, 0.0f); }
return text;
}
//This portion of code provided by Walter's example
//gives the obstacle its own method of movement and detecting boundary lines
sf::RectangleShape Paddle::obs_update(float dt) {
pos.y += vel.y * dt;
if (pos.y + dim.y > lengthWin && vel.y > 0)
vel.y = -vel.y;
if (pos.y < 0 && vel.y < 0)
vel.y = -vel.y;
if (pos.x + dim.x > widthWin && vel.x > 0) {
vel.x = -vel.x;
}
if (pos.x < 0 && vel.x < 0) {
vel.x = -vel.x;
}
rect.setPosition(pos.x, pos.y);
rect.setFillColor(sf::Color::Green);
return rect;
}
//sets up the initial values for all of ball's attributes
void Ball::set_properties(float r, float x, float y, float dx, float dy, sf::Color c) {
radius = r;
pos.x = x;
pos.y = y;
color = c;
vel.x = dx;
vel.y = dy;
sphere.setRadius(radius);
sphere.setPosition(pos.x, pos.y);
sphere.setFillColor(color);
}
//This portion of code provided by Walter's example
//constantly updates the ball's position and checks for boundary collision; also checks if players have scored a point
sf::CircleShape Ball::update(float dt) {
pos.x += vel.x * dt;
pos.y += vel.y * dt;
if (pos.y + radius*2 > lengthWin && vel.y > 0)
vel.y = -vel.y;
if (pos.y < 0 && vel.y < 0)
vel.y = -vel.y;
if (pos.x > widthWin && vel.x > 0) {
point = 1;
isSpawn = true;
sound.play();
}
if (pos.x + radius*2 < 0 && vel.x < 0) {
point = -1;
isSpawn = true;
sound.play();
}
sphere.setPosition(pos.x, pos.y);
return sphere;
}
//gives the ball a random y velocity, random x direction and a random "delay" timer
double Ball::startRound() {
pos.x = xposBstart;
pos.y = yposBstart;
vel.x = rand() % 2;
vel.y = rand() % 2;
if (vel.x == 0.0f) { vel.x = -1.0f; }
if (vel.y == 0.0f) { vel.y = -1.0f; }
vel.x = (vel.x * 400.f);
float numY = rand() % 10;
numY++;
vel.y = (vel.y * 50 * numY);
double pause = rand() % 3;
pause++;
return pause;
}
//checks the point on the paddle where the ball collides with it and adjusts its velocities accordingly
void Ball::bounceStuff(float xpos, float ypos, float width, float length) {
if (vel.x > 0) { vel.x += 25.0f; }
else { vel.x -= 25.0f; }
vel.x = -vel.x;
float midpoint = length / 2;
float point = (pos.y + radius) - ypos;
float value = (point - midpoint)/midpoint;
float angle = sinf(value*PI/2);
vel.y = 500.0f * angle;
} | [
"jurosale@ucsc.edu"
] | jurosale@ucsc.edu |
bda2a61f7a3952efd3d16288ab03aa47d3ab0546 | b7f3edb5b7c62174bed808079c3b21fb9ea51d52 | /chromeos/services/device_sync/cryptauth_group_private_key_sharer_impl.cc | 27b25f6935924cd42707414eaad92caaa480639e | [
"BSD-3-Clause"
] | permissive | otcshare/chromium-src | 26a7372773b53b236784c51677c566dc0ad839e4 | 64bee65c921db7e78e25d08f1e98da2668b57be5 | refs/heads/webml | 2023-03-21T03:20:15.377034 | 2020-11-16T01:40:14 | 2020-11-16T01:40:14 | 209,262,645 | 18 | 21 | BSD-3-Clause | 2023-03-23T06:20:07 | 2019-09-18T08:52:07 | null | UTF-8 | C++ | false | false | 14,252 | cc | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/services/device_sync/cryptauth_group_private_key_sharer_impl.h"
#include <utility>
#include "base/bind.h"
#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_functions.h"
#include "chromeos/components/multidevice/logging/logging.h"
#include "chromeos/services/device_sync/async_execution_time_metrics_logger.h"
#include "chromeos/services/device_sync/cryptauth_client.h"
#include "chromeos/services/device_sync/cryptauth_ecies_encryptor_impl.h"
#include "chromeos/services/device_sync/cryptauth_key.h"
#include "chromeos/services/device_sync/cryptauth_task_metrics_logger.h"
#include "crypto/sha2.h"
namespace chromeos {
namespace device_sync {
namespace {
// Timeout values for asynchronous operations.
// TODO(https://crbug.com/933656): Use async execution time metrics to tune
// these timeout values. For now, set these timeouts to the max execution time
// recorded by the metrics.
constexpr base::TimeDelta kWaitingForGroupPrivateKeyEncryptionTimeout =
kMaxAsyncExecutionTime;
constexpr base::TimeDelta kWaitingForShareGroupPrivateKeyResponseTimeout =
kMaxAsyncExecutionTime;
CryptAuthDeviceSyncResult::ResultCode
ShareGroupPrivateKeyNetworkRequestErrorToResultCode(NetworkRequestError error) {
switch (error) {
case NetworkRequestError::kOffline:
return CryptAuthDeviceSyncResult::ResultCode::
kErrorShareGroupPrivateKeyApiCallOffline;
case NetworkRequestError::kEndpointNotFound:
return CryptAuthDeviceSyncResult::ResultCode::
kErrorShareGroupPrivateKeyApiCallEndpointNotFound;
case NetworkRequestError::kAuthenticationError:
return CryptAuthDeviceSyncResult::ResultCode::
kErrorShareGroupPrivateKeyApiCallAuthenticationError;
case NetworkRequestError::kBadRequest:
return CryptAuthDeviceSyncResult::ResultCode::
kErrorShareGroupPrivateKeyApiCallBadRequest;
case NetworkRequestError::kResponseMalformed:
return CryptAuthDeviceSyncResult::ResultCode::
kErrorShareGroupPrivateKeyApiCallResponseMalformed;
case NetworkRequestError::kInternalServerError:
return CryptAuthDeviceSyncResult::ResultCode::
kErrorShareGroupPrivateKeyApiCallInternalServerError;
case NetworkRequestError::kUnknown:
return CryptAuthDeviceSyncResult::ResultCode::
kErrorShareGroupPrivateKeyApiCallUnknownError;
}
}
// The first 8 bytes of the SHA-256 hash of |str|, converted into a 64-bit
// signed integer in little-endian order. This format is chosen to be consistent
// with the CryptAuth backend implementation.
int64_t CalculateInt64Sha256Hash(const std::string& str) {
uint8_t hash_bytes[sizeof(int64_t)];
crypto::SHA256HashString(str, hash_bytes, sizeof(hash_bytes));
int64_t hash_int64 = 0;
for (size_t i = 0; i < 8u; ++i)
hash_int64 |= static_cast<int64_t>(hash_bytes[i]) << (i * 8);
return hash_int64;
}
void RecordGroupPrivateKeyEncryptionMetrics(
const base::TimeDelta& execution_time,
CryptAuthAsyncTaskResult result) {
LogAsyncExecutionTimeMetric(
"CryptAuth.DeviceSyncV2.GroupPrivateKeySharer.ExecutionTime."
"GroupPrivateKeyEncryption",
execution_time);
LogCryptAuthAsyncTaskSuccessMetric(
"CryptAuth.DeviceSyncV2.GroupPrivateKeySharer.AsyncTaskResult."
"GroupPrivateKeyEncryption",
result);
}
void RecordShareGroupPrivateKeyMetrics(const base::TimeDelta& execution_time,
CryptAuthApiCallResult result) {
LogAsyncExecutionTimeMetric(
"CryptAuth.DeviceSyncV2.GroupPrivateKeySharer.ExecutionTime."
"ShareGroupPrivateKey",
execution_time);
LogCryptAuthApiCallSuccessMetric(
"CryptAuth.DeviceSyncV2.GroupPrivateKeySharer.ApiCallResult."
"ShareGroupPrivateKey",
result);
}
} // namespace
// static
CryptAuthGroupPrivateKeySharerImpl::Factory*
CryptAuthGroupPrivateKeySharerImpl::Factory::test_factory_ = nullptr;
// static
std::unique_ptr<CryptAuthGroupPrivateKeySharer>
CryptAuthGroupPrivateKeySharerImpl::Factory::Create(
CryptAuthClientFactory* client_factory,
std::unique_ptr<base::OneShotTimer> timer) {
if (test_factory_)
return test_factory_->CreateInstance(client_factory, std::move(timer));
return base::WrapUnique(
new CryptAuthGroupPrivateKeySharerImpl(client_factory, std::move(timer)));
}
// static
void CryptAuthGroupPrivateKeySharerImpl::Factory::SetFactoryForTesting(
Factory* test_factory) {
test_factory_ = test_factory;
}
CryptAuthGroupPrivateKeySharerImpl::Factory::~Factory() = default;
CryptAuthGroupPrivateKeySharerImpl::CryptAuthGroupPrivateKeySharerImpl(
CryptAuthClientFactory* client_factory,
std::unique_ptr<base::OneShotTimer> timer)
: client_factory_(client_factory), timer_(std::move(timer)) {
DCHECK(client_factory);
}
CryptAuthGroupPrivateKeySharerImpl::~CryptAuthGroupPrivateKeySharerImpl() =
default;
// static
base::Optional<base::TimeDelta>
CryptAuthGroupPrivateKeySharerImpl::GetTimeoutForState(State state) {
switch (state) {
case State::kWaitingForGroupPrivateKeyEncryption:
return kWaitingForGroupPrivateKeyEncryptionTimeout;
case State::kWaitingForShareGroupPrivateKeyResponse:
return kWaitingForShareGroupPrivateKeyResponseTimeout;
default:
// Signifies that there should not be a timeout.
return base::nullopt;
}
}
// static
base::Optional<CryptAuthDeviceSyncResult::ResultCode>
CryptAuthGroupPrivateKeySharerImpl::ResultCodeErrorFromTimeoutDuringState(
State state) {
switch (state) {
case State::kWaitingForGroupPrivateKeyEncryption:
return CryptAuthDeviceSyncResult::ResultCode::
kErrorTimeoutWaitingForGroupPrivateKeyEncryption;
case State::kWaitingForShareGroupPrivateKeyResponse:
return CryptAuthDeviceSyncResult::ResultCode::
kErrorTimeoutWaitingForShareGroupPrivateKeyResponse;
default:
return base::nullopt;
}
}
void CryptAuthGroupPrivateKeySharerImpl::SetState(State state) {
timer_->Stop();
PA_LOG(INFO) << "Transitioning from " << state_ << " to " << state;
state_ = state;
last_state_change_timestamp_ = base::TimeTicks::Now();
base::Optional<base::TimeDelta> timeout_for_state = GetTimeoutForState(state);
if (!timeout_for_state)
return;
timer_->Start(FROM_HERE, *timeout_for_state,
base::BindOnce(&CryptAuthGroupPrivateKeySharerImpl::OnTimeout,
base::Unretained(this)));
}
void CryptAuthGroupPrivateKeySharerImpl::OnTimeout() {
// If there's a timeout specified, there should be a corresponding error code.
base::Optional<CryptAuthDeviceSyncResult::ResultCode> error_code =
ResultCodeErrorFromTimeoutDuringState(state_);
DCHECK(error_code);
base::TimeDelta execution_time =
base::TimeTicks::Now() - last_state_change_timestamp_;
switch (state_) {
case State::kWaitingForGroupPrivateKeyEncryption:
RecordGroupPrivateKeyEncryptionMetrics(
execution_time, CryptAuthAsyncTaskResult::kTimeout);
break;
case State::kWaitingForShareGroupPrivateKeyResponse:
RecordShareGroupPrivateKeyMetrics(execution_time,
CryptAuthApiCallResult::kTimeout);
break;
default:
NOTREACHED();
}
FinishAttempt(*error_code);
}
void CryptAuthGroupPrivateKeySharerImpl::OnAttemptStarted(
const cryptauthv2::RequestContext& request_context,
const CryptAuthKey& group_key,
const IdToEncryptingKeyMap& id_to_encrypting_key_map) {
DCHECK_EQ(State::kNotStarted, state_);
DCHECK(!group_key.private_key().empty());
CryptAuthEciesEncryptor::IdToInputMap group_private_keys_to_encrypt;
for (const auto& id_encrypting_key_pair : id_to_encrypting_key_map) {
const std::string& id = id_encrypting_key_pair.first;
const std::string& encrypting_key = id_encrypting_key_pair.second;
// If the encrypting key is empty, the group private key cannot be
// encrypted. Skip this ID and attempt to encrypt the group private key for
// as many IDs as possible.
bool is_encrypting_key_empty = encrypting_key.empty();
base::UmaHistogramBoolean(
"CryptAuth.DeviceSyncV2.GroupPrivateKeySharer.IsEncryptingKeyEmpty",
is_encrypting_key_empty);
if (is_encrypting_key_empty) {
PA_LOG(ERROR) << "Cannot encrypt group private key for device with ID "
<< id << ". Encrypting key is empty.";
did_non_fatal_error_occur_ = true;
continue;
}
group_private_keys_to_encrypt[id] = CryptAuthEciesEncryptor::PayloadAndKey(
group_key.private_key(), encrypting_key);
}
// All encrypting keys are empty; encryption not possible.
if (group_private_keys_to_encrypt.empty()) {
FinishAttempt(
CryptAuthDeviceSyncResult::ResultCode::kErrorEncryptingGroupPrivateKey);
return;
}
SetState(State::kWaitingForGroupPrivateKeyEncryption);
encryptor_ = CryptAuthEciesEncryptorImpl::Factory::Create();
encryptor_->BatchEncrypt(
group_private_keys_to_encrypt,
base::BindOnce(
&CryptAuthGroupPrivateKeySharerImpl::OnGroupPrivateKeysEncrypted,
base::Unretained(this), request_context, group_key));
}
void CryptAuthGroupPrivateKeySharerImpl::OnGroupPrivateKeysEncrypted(
const cryptauthv2::RequestContext& request_context,
const CryptAuthKey& group_key,
const CryptAuthEciesEncryptor::IdToOutputMap&
id_to_encrypted_group_private_key_map) {
DCHECK_EQ(State::kWaitingForGroupPrivateKeyEncryption, state_);
// Record a success because the operation did not timeout. A separate metric
// tracks individual encryption failures.
RecordGroupPrivateKeyEncryptionMetrics(
base::TimeTicks::Now() - last_state_change_timestamp_,
CryptAuthAsyncTaskResult::kSuccess);
cryptauthv2::ShareGroupPrivateKeyRequest request;
request.mutable_context()->CopyFrom(request_context);
for (const auto& id_encrypted_key_pair :
id_to_encrypted_group_private_key_map) {
// If the group private key could not be encrypted for this ID--due to an
// invalid encrypting key, for instance--skip it. Continue to share as many
// encrypted group private keys as possible.
bool was_encryption_successful = id_encrypted_key_pair.second.has_value();
base::UmaHistogramBoolean(
"CryptAuth.DeviceSyncV2.GroupPrivateKeySharer.EncryptionSuccess",
was_encryption_successful);
if (!was_encryption_successful) {
PA_LOG(ERROR) << "Group private key could not be encrypted for device "
<< "with ID " << id_encrypted_key_pair.first;
did_non_fatal_error_occur_ = true;
continue;
}
cryptauthv2::EncryptedGroupPrivateKey* encrypted_key =
request.add_encrypted_group_private_keys();
encrypted_key->set_recipient_device_id(id_encrypted_key_pair.first);
encrypted_key->set_sender_device_id(request_context.device_id());
encrypted_key->set_encrypted_private_key(*id_encrypted_key_pair.second);
// CryptAuth requires a SHA-256 hash of the group public key as an int64.
encrypted_key->set_group_public_key_hash(
CalculateInt64Sha256Hash(group_key.public_key()));
}
// All encryption attempts failed; nothing to share.
if (request.encrypted_group_private_keys().empty()) {
FinishAttempt(
CryptAuthDeviceSyncResult::ResultCode::kErrorEncryptingGroupPrivateKey);
return;
}
SetState(State::kWaitingForShareGroupPrivateKeyResponse);
cryptauth_client_ = client_factory_->CreateInstance();
cryptauth_client_->ShareGroupPrivateKey(
request,
base::Bind(
&CryptAuthGroupPrivateKeySharerImpl::OnShareGroupPrivateKeySuccess,
base::Unretained(this)),
base::Bind(
&CryptAuthGroupPrivateKeySharerImpl::OnShareGroupPrivateKeyFailure,
base::Unretained(this)));
}
void CryptAuthGroupPrivateKeySharerImpl::OnShareGroupPrivateKeySuccess(
const cryptauthv2::ShareGroupPrivateKeyResponse& response) {
DCHECK_EQ(State::kWaitingForShareGroupPrivateKeyResponse, state_);
RecordShareGroupPrivateKeyMetrics(
base::TimeTicks::Now() - last_state_change_timestamp_,
CryptAuthApiCallResult::kSuccess);
CryptAuthDeviceSyncResult::ResultCode result_code =
did_non_fatal_error_occur_
? CryptAuthDeviceSyncResult::ResultCode::kFinishedWithNonFatalErrors
: CryptAuthDeviceSyncResult::ResultCode::kSuccess;
FinishAttempt(result_code);
}
void CryptAuthGroupPrivateKeySharerImpl::OnShareGroupPrivateKeyFailure(
NetworkRequestError error) {
DCHECK_EQ(State::kWaitingForShareGroupPrivateKeyResponse, state_);
RecordShareGroupPrivateKeyMetrics(
base::TimeTicks::Now() - last_state_change_timestamp_,
CryptAuthApiCallResultFromNetworkRequestError(error));
FinishAttempt(ShareGroupPrivateKeyNetworkRequestErrorToResultCode(error));
}
void CryptAuthGroupPrivateKeySharerImpl::FinishAttempt(
CryptAuthDeviceSyncResult::ResultCode result_code) {
encryptor_.reset();
cryptauth_client_.reset();
SetState(State::kFinished);
OnAttemptFinished(result_code);
}
std::ostream& operator<<(
std::ostream& stream,
const CryptAuthGroupPrivateKeySharerImpl::State& state) {
switch (state) {
case CryptAuthGroupPrivateKeySharerImpl::State::kNotStarted:
stream << "[GroupPrivateKeySharer state: Not started]";
break;
case CryptAuthGroupPrivateKeySharerImpl::State::
kWaitingForGroupPrivateKeyEncryption:
stream << "[GroupPrivateKeySharer state: Waiting for group private key "
<< "encryption]";
break;
case CryptAuthGroupPrivateKeySharerImpl::State::
kWaitingForShareGroupPrivateKeyResponse:
stream << "[GroupPrivateKeySharer state: Waiting for "
<< "ShareGroupPrivateKey response]";
break;
case CryptAuthGroupPrivateKeySharerImpl::State::kFinished:
stream << "[GroupPrivateKeySharer state: Finished]";
break;
}
return stream;
}
} // namespace device_sync
} // namespace chromeos
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
576aa26fea47af18c6396a76d1f09d4b040df1c1 | 00c091e7b9e6667cf3be9b9b65ce1eda9a9b746c | /Source/CoopGame/Public/SGameMode.h | 2827012b8c29dac861519cf53bcc38278da1cabf | [] | no_license | mpulcinelli/CoopGame | fa51002421abacd25b68941a262f986deb132fcc | 76555809255058eb9f6136416d0fc10bec66eebc | refs/heads/master | 2020-03-23T04:15:50.104326 | 2018-11-26T16:23:06 | 2018-11-26T16:23:06 | 141,073,184 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,453 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/GameModeBase.h"
#include <TimerManager.h>
#include "SGameState.h"
#include "SPlayerState.h"
#include <GameFramework/Controller.h>
#include "SGameMode.generated.h"
DECLARE_DYNAMIC_MULTICAST_DELEGATE_ThreeParams(FOnActorKilled, AActor*, VictimActor, AActor*, KillerActor, AController*, KillerController);
//DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FOnActorKilled, AActor*, VictimActor, AActor*, KillerActor);
enum class EWaveState: uint8;
/**
*
*/
UCLASS()
class COOPGAME_API ASGameMode : public AGameModeBase
{
GENERATED_BODY()
protected:
int32 NrBotsToSpawn;
int32 WaveCount;
UPROPERTY(EditDefaultsOnly, Category="GameMode")
float TimeBetweenWaves;
FTimerHandle TimerHandle_BotSpawnner;
FTimerHandle TimerHandle_NextWaveStart;
UFUNCTION(BlueprintImplementableEvent, Category = "GameMode")
void SpawnNewBot();
void SpawnBotTimerElapsed();
void StartWave();
void EndWave();
void PrepareForNextWave();
void CheckWaveStatte();
void CheckAnyPlayerAlive();
void GameOver();
void SetWaveState(EWaveState NewWaveState);
void RestartDeadPlayers();
bool HasPlayersToPlay();
public:
ASGameMode();
virtual void StartPlay() override;
virtual void Tick(float DeltaSeconds) override;
UPROPERTY(BlueprintAssignable, Category="GameMode")
FOnActorKilled OnActorKilled;
};
| [
"mpulcinelli@gmail.com"
] | mpulcinelli@gmail.com |
e20f74c46d7be2d6609ff45b1c1d842a311b8711 | b19f30140cef064cbf4b18e749c9d8ebdd8bf27f | /D3DGame_180000_022_1_Frustum/Viewer/Frustum.h | b71d89ff24951d72dca3b14fbdb2f09f434c2c78 | [] | no_license | evehour/SGADHLee | 675580e199991916cf3134e7c61749b0a0bfa070 | 0ebbedf5d0692b782e2e5f9a372911c65f98ddc4 | refs/heads/master | 2020-03-25T13:22:42.597811 | 2019-01-03T07:05:54 | 2019-01-03T07:05:54 | 143,822,128 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 537 | h | #pragma once
class Frustum
{
public:
Frustum(ExecuteValues* values, float zFar, Camera* camera = NULL, Perspective* perspective = NULL);
~Frustum();
void Update();
bool ContainPoint(D3DXVECTOR3& position, const int & cases = 0);
private:
ExecuteValues* values;
D3DXPLANE planes[6];
float zFar;
Camera* camera;
Perspective* perspective;
private:
//Multi-Picking Frustum Area
D3DXPLANE pickAreaPlanes[6];
public:
void SetPickingArea(const D3DXVECTOR3& start, const D3DXVECTOR3& end, D3DXVECTOR3* const arr = NULL);
}; | [
"evehour@naver.com"
] | evehour@naver.com |
9c2162243a4d0cc0627a9cea36b4ac762b365ebf | f6f8b26ea114113f2ed3bbaf90d17585e6ae349b | /08-01~08-14/File3b.cpp | bdc78399ce9a97678c3e14223561e6ff294e8e61 | [] | no_license | AmGacrux/cpp_study_2011 | a1d4c0a268edf389aed86ef63b60b0323c3cd0f4 | 2134ea1eae97c7b1fe12e7f29f8087b9823badd3 | refs/heads/master | 2020-04-27T15:01:53.517817 | 2019-03-07T22:28:52 | 2019-03-07T22:28:52 | 174,429,387 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 436 | cpp | #include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main() {
fstream file;
file.open("binary.txt", ios::in | ios::binary);
if(! file.is_open()) {
return EXIT_FAILURE;
}
int n;
file.read((char*)&n, sizeof n);
file.close();
// 10 進数表示であることに注意!
// ./File3 を実行した後の cat binary.txt とは出力内容が違って見える
cout << n << endl;
}
| [
"amangacrux@gmail.com"
] | amangacrux@gmail.com |
df27993a1434d88b5c9205d7294511a4fa10d217 | 3b49d85b657eaa723df65038499b2b46a8fcd741 | /tools/ParticleEditor/source/QIrrlichtWidget.h | a921fe8f6a011b3b8a54816e31c021cfa9179fe9 | [] | no_license | threkk/psibranch3irrlicht | 47de7ed14dbf7e361329774810f5d78618860ef6 | 38bdf72bb605ced834aa15a0d8bca3c109849537 | refs/heads/master | 2016-08-07T04:05:52.311380 | 2014-06-12T16:28:15 | 2014-06-12T16:28:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,541 | h | #ifndef QIRRLICHTWIDGET_H
#define QIRRLICHTWIDGET_H
#include <qwidget.h>
#include <irrlicht.h>
#include <qfont.h>
class QPaintEvent;
class IrrDisplay;
class InputReceiver;
class QIrrlichtWidget : public QWidget
{
Q_OBJECT
public:
irr::IrrlichtDevice* getIrrlichtDevice();
void setDriverType( irr::video::E_DRIVER_TYPE driver );
QIrrlichtWidget( QWidget *parent=0 );
~QIrrlichtWidget();
void init(InputReceiver* inputReceiver, IrrDisplay* irrDisplay);
public slots:
void autoUpdateIrrlicht( irr::IrrlichtDevice* device );
signals:
void updateIrrlicht( irr::IrrlichtDevice* device );
protected:
irr::video::E_DRIVER_TYPE driverType;
virtual void paintEvent( QPaintEvent* event );
void sendKeyEventToIrrlicht( QKeyEvent* event, bool pressedDown );
virtual void keyPressEvent( QKeyEvent* event );
virtual void keyReleaseEvent( QKeyEvent* event );
void sendMouseEventToIrrlicht( QMouseEvent* event, bool pressedDown );
virtual void mousePressEvent( QMouseEvent* event );
virtual void mouseReleaseEvent( QMouseEvent* event );
virtual void mouseMoveEvent( QMouseEvent* event );
virtual void wheelEvent( QWheelEvent* event );
virtual void timerEvent( QTimerEvent* event );
virtual void resizeEvent( QResizeEvent* event );
private:
// Irrlicht device
irr::IrrlichtDevice* device;
// Class to display the particle effect
IrrDisplay* irrDisplay;
// Class to register input events on
InputReceiver* inputReceiver;
};
#endif // QIRRLICHTWIDGET_H
| [
"me@arcomul.nl"
] | me@arcomul.nl |
57e7d76075f7490a0816f028297877969fa16eb3 | ad6bf5258014ddb47fc46e120a3868bf8e75592d | /textedit.cpp | 7876cb3ea3052ccb5a9a9e645baca853237a4b8c | [] | no_license | Schikasi/spmiTest | b1ffb448d56d6510cf5da385c1d906e3ce7db3e7 | aa17db0fe5df03830a4ae7feb5fbca6340b7c3f7 | refs/heads/master | 2023-06-15T00:53:34.657593 | 2021-07-16T12:22:21 | 2021-07-16T12:22:21 | 382,876,703 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,311 | cpp | #include "textedit.h"
#include <QFile>
#include <QFileInfo>
#include <QMimeData>
#include <QImageReader>
bool TextEdit::canInsertFromMimeData(const QMimeData* source) const
{
return source->hasImage() || source->hasUrls() ||
QTextEdit::canInsertFromMimeData(source);
}
void TextEdit::insertFromMimeData(const QMimeData* source)
{
if (source->hasImage())
{
static int i = 1;
QUrl url(QString("dropped_image_%1").arg(i++));
dropImage(url, qvariant_cast<QImage>(source->imageData()));
}
else if (source->hasUrls())
{
foreach (QUrl url, source->urls())
{
QFileInfo info(url.toLocalFile());
if (QImageReader::supportedImageFormats().contains(info.suffix().toLower().toLatin1()))
dropImage(url, QImage(info.filePath()));
else
dropTextFile(url);
}
}
else
{
QTextEdit::insertFromMimeData(source);
}
}
void TextEdit::dropImage(const QUrl& url, const QImage& image)
{
if (!image.isNull())
{
textCursor().insertImage(image);
}
}
void TextEdit::dropTextFile(const QUrl& url)
{
QFile file(url.toLocalFile());
if (file.open(QIODevice::ReadOnly | QIODevice::Text))
textCursor().insertText(file.readAll());
}
| [
"35520439+Schikasi@users.noreply.github.com"
] | 35520439+Schikasi@users.noreply.github.com |
696e1e819fcdb01a0d677c432b90f01e1836b774 | 2fb47a8e262e0efa4f1ecd70b1dcf02f2960854b | /unityplugin/ptest/ptest.cpp | 22d0af08955441c267181be815b365c08968f689 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | simonhb12/blog | 33fa1b7f17851c1d6f10593bf876c670a91c8335 | 4de49cd56886e107ee0b20c1bf6c3e5e4bbb5eae | refs/heads/master | 2023-03-15T23:47:00.032362 | 2019-02-08T16:13:13 | 2019-02-08T16:13:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,815 | cpp | #include <IUnityInterface.h>
#include <Windows.h>
#include <string.h>
extern "C" {
#define PLUGINEX(rtype) UNITY_INTERFACE_EXPORT rtype UNITY_INTERFACE_API
PLUGINEX(int) ReturnInt()
{
return 0xBABE;
}
PLUGINEX(void) AcceptArray1(char *arr, int length)
{
for (int i = 0; i < length; i++) {
arr[i] = 'A' + i;
}
}
PLUGINEX(void) AcceptArray2(char *arr, int length)
{
for (int i = 0; i < length; i++) {
arr[i] = 'A' + i;
}
}
PLUGINEX(bool) AcceptStr(LPCSTR pStr)
{
return !strcmp(pStr, "FOO");
}
PLUGINEX(int) AcceptStrArray(const char* const *strArray, int size)
{
int total = 0;
for (int i = 0; i < size; i++) {
auto str = strArray[i];
total += (int)strlen(str);
}
// return total length of the strings in the array to demonstrate that
// it was passed correctly
return total;
}
PLUGINEX(LPSTR) ReturnDynamicStr()
{
LPSTR str = (LPSTR)CoTaskMemAlloc(512);
strcpy_s(str, 512, "Dynamic string");
return str;
}
PLUGINEX(LPCSTR) ReturnConstStr()
{
return "Constant string";
}
PLUGINEX(LPBYTE) ReturnDynamicByteArray(int &pSize)
{
pSize = 0xFF;
LPBYTE pData = (LPBYTE)CoTaskMemAlloc(pSize);
// fill with example data
for (int i = 0; i < pSize; i++) {
pData[i] = i + 1;
}
return pData;
}
PLUGINEX(LPSTR*) ReturnDynamicStrArray(int &pSize)
{
// Allocate an array with pointers to 3 dynamically allocated strings
pSize = 3;
LPSTR* pData = (LPSTR*)CoTaskMemAlloc((pSize)*sizeof(LPSTR));
pData[0] = (LPSTR)CoTaskMemAlloc(128);
pData[1] = (LPSTR)CoTaskMemAlloc(128);
pData[2] = (LPSTR)CoTaskMemAlloc(128);
strcpy_s(pData[0], 128, "String 1");
strcpy_s(pData[1], 128, "String 2");
strcpy_s(pData[2], 128, "String 3");
return pData;
}
struct ExampleStruct {
INT16 val1;
INT32 array1[3];
INT16 array2len;
INT32 array2[10];
LPSTR str1;
};
PLUGINEX(int) AcceptStruct(ExampleStruct &s)
{
// Modify struct
s.val1 -= 1111;
for (int i= 0; i < 3; i++) {
s.array1[i] += 1;
}
for (int i = 0; i < s.array2len; i++) {
s.array2[i] += 10;
}
// return length of the string in the argument struct to demonstrate that
// it was passed correctly
return (int)strlen(s.str1);
}
struct ExamplePoint {
FLOAT x;
FLOAT y;
FLOAT z;
};
PLUGINEX(ExamplePoint *) ReturnArrayOfPoints(int &size)
{
size = 4;
ExamplePoint *pointArr = (ExamplePoint*)CoTaskMemAlloc(sizeof(ExamplePoint) * size);
// fill with some example data
for (int i = 0; i < size; i++) {
pointArr[i] = { i + 0.1f, i + 0.2f, i + 0.3f };
}
return pointArr;
}
// this return type is blittable
// https://stackoverflow.com/questions/10320502/c-sharp-calling-c-function-that-returns-struct-with-fixed-size-char-array
//
PLUGINEX(ExamplePoint) ReturnStruct()
{
return { 1, 2, 3 };
}
}
| [
"teemu.ikonen@iki.fi"
] | teemu.ikonen@iki.fi |
b3dc0dc3982b5ca652752a59c0aba88654917bc9 | 6e7e07d2872e9321c082db6bbf353f0f12090736 | /tests/tests/UserDefaultTest/UserDefaultTest.cpp | c8e3da0e1f1d0ef313a93df552bf4d2718292600 | [
"MIT"
] | permissive | haiweizhang/MyCocos2d-xV2.0 | e9a9fd7ed002db551caa391def644375095cd266 | 54759a2602f251091a3e1bce3be6b4d33ba0f15b | refs/heads/master | 2021-01-06T20:37:17.133750 | 2013-07-25T06:02:40 | 2013-07-25T06:02:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,961 | cpp | // enable log
#define COCOS2D_DEBUG 1
#include "UserDefaultTest.h"
#include "stdio.h"
#include "stdlib.h"
UserDefaultTest::UserDefaultTest()
{
CCSize s = CCDirector::sharedDirector()->getWinSize();
CCLabelTTF* label = CCLabelTTF::labelWithString("CCUserDefault test see log", "Arial", 28);
addChild(label, 0);
label->setPosition( ccp(s.width/2, s.height-50) );
doTest();
}
void UserDefaultTest::doTest()
{
CCLOG("********************** init value ***********************");
// set default value
CCUserDefault::sharedUserDefault()->setStringForKey("string", "value1");
CCUserDefault::sharedUserDefault()->setIntegerForKey("integer", 10);
CCUserDefault::sharedUserDefault()->setFloatForKey("float", 2.3f);
CCUserDefault::sharedUserDefault()->setDoubleForKey("double", 2.4);
CCUserDefault::sharedUserDefault()->setBoolForKey("bool", true);
// print value
string ret = CCUserDefault::sharedUserDefault()->getStringForKey("string");
CCLOG("string is %s", ret.c_str());
double d = CCUserDefault::sharedUserDefault()->getDoubleForKey("double");
CCLOG("double is %f", d);
int i = CCUserDefault::sharedUserDefault()->getIntegerForKey("integer");
CCLOG("integer is %d", i);
float f = CCUserDefault::sharedUserDefault()->getFloatForKey("float");
CCLOG("float is %f", f);
bool b = CCUserDefault::sharedUserDefault()->getBoolForKey("bool");
if (b)
{
CCLOG("bool is true");
}
else
{
CCLOG("bool is false");
}
//CCUserDefault::sharedUserDefault()->flush();
CCLOG("********************** after change value ***********************");
// change the value
CCUserDefault::sharedUserDefault()->setStringForKey("string", "value2");
CCUserDefault::sharedUserDefault()->setIntegerForKey("integer", 11);
CCUserDefault::sharedUserDefault()->setFloatForKey("float", 2.5f);
CCUserDefault::sharedUserDefault()->setDoubleForKey("double", 2.6);
CCUserDefault::sharedUserDefault()->setBoolForKey("bool", false);
CCUserDefault::sharedUserDefault()->flush();
// print value
ret = CCUserDefault::sharedUserDefault()->getStringForKey("string");
CCLOG("string is %s", ret.c_str());
d = CCUserDefault::sharedUserDefault()->getDoubleForKey("double");
CCLOG("double is %f", d);
i = CCUserDefault::sharedUserDefault()->getIntegerForKey("integer");
CCLOG("integer is %d", i);
f = CCUserDefault::sharedUserDefault()->getFloatForKey("float");
CCLOG("float is %f", f);
b = CCUserDefault::sharedUserDefault()->getBoolForKey("bool");
if (b)
{
CCLOG("bool is true");
}
else
{
CCLOG("bool is false");
}
}
UserDefaultTest::~UserDefaultTest()
{
}
void UserDefaultTestScene::runThisTest()
{
CCLayer* pLayer = new UserDefaultTest();
addChild(pLayer);
CCDirector::sharedDirector()->replaceScene(this);
pLayer->release();
}
| [
"deanzhang@163.com"
] | deanzhang@163.com |
f7962a53dc00180bc6c53653d9548534a1dfe8c2 | 23b8c080d7bbf7d304db777025c1e7179149b795 | /유소은/3-3_5598_카이사르 암호.cpp | 57c62183c952ac2275a14f0db77a7ee2aa1cfa13 | [] | no_license | YuSoeun/2021_Summer_PPS_Group6 | 0f4db49751e4b64b884f95cb5247e62f9b99b801 | 1bab73890dea9f6d6e8692c04f20828f5150e1ec | refs/heads/master | 2023-06-20T22:30:42.529997 | 2021-08-01T14:57:17 | 2021-08-01T14:57:17 | 384,442,777 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 457 | cpp | #include <iostream>
#include <string>
using namespace std;
int main(void)
{
ios_base::sync_with_stdio(0);
cin.tie(0);
string s, result;
cin >> s;
for (int i = 0; i < s.length(); i++)
if (s[i] < 'D')
result += s[i] - 'A' + 'X';
else
result += s[i] - 'D' + 'A';
cout << result << "\n";
return 0;
} | [
"so-eunyu@So-Eunui-MacBookPro.local"
] | so-eunyu@So-Eunui-MacBookPro.local |
8391190e2307ca321ce2dd50b6e61f7326371d5a | a6f9386c7264b40030b84fada4cc236c93f975a1 | /actor.hpp | 489f2e4c238261c4321d88cc98c58b2579ad49e0 | [] | no_license | dmitry64/evolution-system | 555b8768aa36f4b84988f74b013ce07ca9aa44f8 | acd3709414548a00d4339374bddfd4d9ee5a4664 | refs/heads/master | 2021-01-23T12:53:48.090690 | 2017-09-10T13:07:57 | 2017-09-10T13:07:57 | 102,657,042 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,266 | hpp | #ifndef ACTOR_HPP
#define ACTOR_HPP
#include "chrono/core/ChRealtimeStep.h"
#include "chrono/physics/ChBodyEasy.h"
#include "chrono/physics/ChSystemNSC.h"
class Actor {
std::unique_ptr<std::vector<std::shared_ptr<chrono::ChBody>>> _bodies;
std::unique_ptr<std::vector<std::shared_ptr<chrono::ChLink>>> _links;
std::shared_ptr<chrono::ChFunction_Const> _leftLegMuscle;
std::shared_ptr<chrono::ChFunction_Const> _leftFootMuscle;
std::shared_ptr<chrono::ChFunction_Const> _rightLegMuscle;
std::shared_ptr<chrono::ChFunction_Const> _rightFootMuscle;
std::shared_ptr<chrono::ChFunction_Const> _bodyRightLegMuscle;
std::shared_ptr<chrono::ChFunction_Const> _bodyLeftLegMuscle;
std::shared_ptr<chrono::ChBodyEasyBox> _leftUpperLeg;
std::shared_ptr<chrono::ChBodyEasyBox> _rightUpperLeg;
public:
Actor();
void simulateTime(double time);
std::vector<double> getNNInput();
void useNNOutput(const std::vector<double>& values);
std::vector<std::vector<chrono::ChVector<>>> getLines();
std::vector<std::shared_ptr<chrono::ChLink>>* getLinks() const;
std::vector<std::shared_ptr<chrono::ChBody>>* getBodies() const;
private:
void createLeftLeg();
void createRightLeg();
};
#endif // ACTOR_HPP
| [
"dmitriizykov64@gmail.com"
] | dmitriizykov64@gmail.com |
a6d2df7a43d49276f647c0233d63dfc89b2c0480 | 69c301a984141521e1530fa227fe5f48eb26f387 | /careercup/13.9-smart-ptr.cpp | 4e9850af17c0bd1a607b4b7a4e23fc1e7b3a9e78 | [] | no_license | harrypotter0/algorithm | e203a820df0174e358a5131e5f1dbcd8a4a0760c | 715b4815130fa0ae4aa3bb6a4e19d6c2c449fce0 | refs/heads/master | 2021-01-13T07:53:25.317216 | 2017-02-25T13:25:40 | 2017-02-25T13:25:40 | 71,687,145 | 1 | 0 | null | 2016-10-23T07:00:55 | 2016-10-23T07:00:54 | null | UTF-8 | C++ | false | false | 1,425 | cpp | #include <iostream>
using namespace std;
template <typename T>
class smart_ptr {
public:
smart_ptr(T *ptr) : ptr_(ptr){
cout << "Initing " << this->ptr_ << endl;
refcount_ = new unsigned int {1};
}
smart_ptr(const smart_ptr<T> &sp) : ptr_(sp.ptr_), refcount_(sp.refcount_) {
this->ptr_ = sp.ptr_;
this->refcount_ = sp.refcount_;
++(*refcount_);
cout << "Copying " << sp.ptr_;
cout << ". Refcount = " << *refcount_ << endl;
}
smart_ptr& operator = (const smart_ptr<T> &sp) {
// point to the same object, does nothing
if (sp.ptr_ == ptr_)
return *this;
this->decrement_count();
this->ptr_ = sp.ptr_;
this->refcount_ = sp.refcount_;
++(*refcount_);
return *this;
}
~smart_ptr() {
cout << this->ptr_ << " : ref count = " << *this->refcount_ << ". Decrement one." << endl;
decrement_count();
}
T val() const {return *ptr_;}
T& ref() {return *ptr_;}
// T& val() {return *ptr_;}
private:
void decrement_count() {
--(*refcount_);
if (*refcount_ == 0) {
cout << "Destroying object..." << endl;
delete ptr_;
delete refcount_;
}
}
unsigned int *refcount_ {0};
T *ptr_ {NULL};
};
int main(int argc, char const *argv[])
{
smart_ptr<int> ptr(new int{3});
smart_ptr<int> p2 = ptr;
smart_ptr<int> p3(new int{5});
p2.ref() = 20;
cout << p2.val() << endl;
ptr = p2;
ptr = p3;
return 0;
} | [
"iveney@gmail.com"
] | iveney@gmail.com |
242115edcfe3b0ac875a435fb215fb22168b1e1f | 1fdbbb773bf42057e56578c03ac7d90376cca6b9 | /leetcode1094.cpp | 0b7b6ac2567824d7029541462ade3a5c7ca31856 | [] | no_license | skanda99/Hackerrank-Leetcode | 813cd2eec3c2f401f5f98f95f8248ae508a2bea6 | bab468b1eeae6866d7b486424d95d381668d961f | refs/heads/master | 2022-09-03T12:28:56.462218 | 2022-06-12T04:32:19 | 2022-06-12T04:32:19 | 163,795,441 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 997 | cpp |
// problem: "https://leetcode.com/problems/car-pooling/"
bool func1 (vector<int>&p1, vector<int>&p2) {
return p1[1] < p2[1];
}
bool func2 (vector<int>&p1, vector<int>&p2) {
return p1[2] < p2[2];
}
class Solution {
public:
bool carPooling(vector<vector<int>>& trips, int capacity) {
if(trips.empty()) {
return true;
}
vector<vector<int>>trips_c(trips);
sort(trips.begin(), trips.end(), func1);
sort(trips_c.begin(), trips_c.end(), func2);
int i,j,n;
i = j = 0;
n = trips.size();
while(i < n) {it
if(trips_c[j][2] <= trips[i][1]) {
capacity += trips_c[j][0];
j++;
}
else {
capacity -= trips[i][0];
i++;
}
if(capacity < 0) {
return false;
}
}
return true;
}
};
| [
"skandaupadhyaya1999@gmail.com"
] | skandaupadhyaya1999@gmail.com |
ee2c131fe622864f3a2d4a8449e47fbaa7487f37 | 7d3494a8adc37f4adc859a5dfa5568124e9350a2 | /AMS_progetto/PROGETTO_AMS INIZIALE/src/AMS_TDF_testbench.cc | b0a2fbe410a05b17dc19bbad97c33130fd4841b5 | [] | no_license | snukneLeo/LABORATORIO_PSE | c8c1f099e14103a27468d1985cadc6a5463f0eab | dec0a5020a11f39d9625ec7ddf36ef651c9334da | refs/heads/master | 2020-04-12T16:22:05.743100 | 2018-12-30T17:55:04 | 2018-12-30T17:55:04 | 162,609,395 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 884 | cc | #include "AMS_TDF_testbench.hh"
amsTest::amsTest( sc_core::sc_module_name):
command("command"), thresholding("thresholding"), waterTank("waterTank")
{
thresh = 0.7;
samples = 0;
counter = 0;
}
void amsTest::set_attributes()
{
waterTank.set_timestep(5,SC_MS);
waterTank.set_delay(1);
samplesTowait = 1000;//numero campioni da inviare
}
void amsTest::processing() //input: idle/open/close; thresholding
{
if(waterTank.read() >= 5 && waterTank.read() <= 8.8)
{
command = IDLE;
counter = 0;
}
else if(waterTank.read() > 8.8 && counter == samplesTowait)
{
command = CLOSE;
thresh *= 0.7;
counter = 0;
}
else if(waterTank.read() < 5 && counter == samplesTowait)
{
command = OPEN;
thresh *= 1.1;
counter = 0;
}
thresholding.write(thresh);
counter++;
} | [
"leonardo.testolin@studenti.univr.it"
] | leonardo.testolin@studenti.univr.it |
f2d7013fec9ee083c6ca576d61b5da2dbf25fa38 | 327fe241637119d26e6b3e02b7fad124e242646a | /HeapsAndMaps/MaximunInSlidingWindow.cpp | 9c3c28c8ec44788a22804783440cf7a9bd9b05ca | [] | no_license | keshavjoshi142/Code-Archive | 8e8cd5a34bc46460de40d39a05c66bfeb66bcf07 | 399e2f98b730ae94081ae5e2d83cc1e27c9c09ab | refs/heads/master | 2021-04-27T14:54:02.455780 | 2018-12-19T13:18:17 | 2018-12-19T13:18:17 | 122,456,880 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 578 | cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
int k;
cin >> k;
vector < int > v(n);
for(int i=0 ; i < n ; i++)
cin >> v[i];
deque < int > dq;
vector < int > res;
for(int i=0 ; i < n ; i++)
{
cout << v[i] << " ";
}
cout << endl;
for(int i=0 ; i < n ; i++)
{
if(!dq.empty() && dq.front() == i - k)
dq.pop_front();
while(!dq.empty() && v[dq.back()] < v[i])
dq.pop_back();
dq.push_back(i);
if(i >= k - 1)
res.push_back(v[dq.front()]);
}
for(int i = 0; i < res.size() ; i++)
cout << res[i] << " ";
} | [
"keshavjoshi142@gmail.com"
] | keshavjoshi142@gmail.com |
c69647eef6149529ff4ded2343d0b479b294ab84 | dc7ec385bdac570a2824017632ac322aab7ca3ba | /src/grove-sensors-actuators.ino | 7653bc757ad15617a9721494ebd6a2943093021c | [] | no_license | ponlawat-w/particle-grove-sensors_actuators | cf11b40e5894009fc46265aab5b5ac4603ef34eb | 326782be5a03279e2076d8789ef1a73d249d198d | refs/heads/master | 2023-01-08T08:49:02.878483 | 2020-11-11T12:59:15 | 2020-11-11T12:59:15 | 311,954,608 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,732 | ino | /*
* Project grove-sensors-actuators
* Description: Grove Sensors and Actuators
* Author: Ponlawat W.
* Date: 9 November 2020
*
* In this code, allows users to read one sensor and write one actuator at the time.
* The sensor must send normalised value between 0 to 1, and the actuator must act depending on the value.
*/
#include "DHT.h"
#include "Grove_4Digit_Display.h"
#include "Grove_ChainableLED.h"
#include "Grove-Ultrasonic-Ranger.h"
// Enumeration Constants
#define ACTUATOR_7SEG 1
#define ACTUATOR_BUZZ 2
#define ACTUATOR_LED 3
#define SENSOR_BUTTON 1
#define SENSOR_LIGHT 2
#define SENSOR_ROTARY 3
#define SENSOR_ULTRASONIC 4
#define SENSOR_DHT_HUMIDITY 5
#define SENSOR_DHT_TEMPERATURE 6
// Customisation //
// ↓ interval of delay in loop()
#define INTERVAL 10
// ↓ how many times loop() executed to publish message to Particle server with publishNumber() function
#define PUBLISH_WAIT 100
#define SENSOR_BUTTON_PIN D4
#define SENSOR_DHT_PIN D2
#define SENSOR_DHT_TYPE DHT11
#define SENSOR_LIGHT_PIN A4
#define SENSOR_ROTARY_PIN A2
#define SENSOR_ULTRASONIC_PIN D2
// ↓ For temperature sensor in degree celcius, which temperature will be minimum of being considered as 0
#define TEMP_MIN 10
// ↓ For temperature sensor, TEMP_MIN + TEMP_RANGE will be considered as 1
#define TEMP_RANGE 20
#define ACTUATOR_7SEG_CLK D2
#define ACTUATOR_7SEG_DIO D3
#define ACTUATOR_BUZZ_PIN A0
#define ACTUATOR_LED_1 D4
#define ACTUATOR_LED_2 D5
// Sensors and Actuators //
// ↓ Select desired sensor here, 0 when read no sensors
const int SENSOR = SENSOR_ROTARY;
// ↓ Select desired actuator here, 0 when write to no actuators
const int ACTUATOR = ACTUATOR_7SEG;
// ↓ false when sensor read 0 to 1, true when sensor read 1 to 0
const bool REVERSE = false;
// Library Initialisation //
ChainableLED leds(ACTUATOR_LED_1, ACTUATOR_LED_2, 1);
DHT dht(SENSOR_DHT_PIN, SENSOR_DHT_TYPE);
TM1637 tm1637(ACTUATOR_7SEG_CLK, ACTUATOR_7SEG_DIO);
Ultrasonic ultrasonic(SENSOR_ULTRASONIC_PIN);
float SensorValue = 0; // initial normalised sensor value to be zero
int PublishWaitCount = PUBLISH_WAIT;
/**
* Publish number in parameter to Particle cloud
*/
void publishNumber(float number) {
if (++PublishWaitCount > PUBLISH_WAIT) {
char valueStr[10];
sprintf(valueStr, "%f", number);
Particle.publish(valueStr, PRIVATE);
PublishWaitCount = 0;
}
}
// Sensor Read Functions //
/**
* Read value from button, returns 1.0 when pressed, 0.0 when released
*/
float readButton() {
return digitalRead(SENSOR_BUTTON_PIN) == HIGH ? 1.0 : 0.0;
}
/**
* Read humidity from dht sensor, returns 1.0 when 100% humidity, 0.0 when 0% humidity
*/
float readDhtHumidity(float previousValue) {
float value = dht.readHumidity(true);
return isnan(value) ? previousValue : value / 100.0;
}
/**
* Read temperature from dht sensor, returns 0.0 when TEMP_MIN, 1.0 when TEMP_MIN + TEMP_RANGE
*/
float readDhtTemperature(float previousValue) {
float value = dht.readTemperature(false, true);
if (isnan(value)) {
return previousValue;
}
value -= TEMP_MIN;
value /= TEMP_RANGE;
return value < 0 ? 0 : (value > 1 ? 1 : value);
}
/**
* Read brightness from light sensor, the sensor should return value from 0 to 1023,
* then it will be normalised to be between 0.0 and 1.0
*/
float readLight() {
float value = 1 - ((float)analogRead(SENSOR_LIGHT_PIN) / 1023.0);
return value < 0 ? 0 : (value > 1 ? 1 : value);
}
/**
* Read value from rotary sensor, returns between 0.0 and 1.0 depends on rotation degree.
* The sensor should originally be read integer between 0 and 4096
*/
float readRotary() {
float value = (float)analogRead(SENSOR_ROTARY_PIN);
value = value < 26 ? 0 : value;
return value / 4096.0;
}
/**
* Read value from ultrasonic sensor, returns 0.0 to 1.0 if the object is between 0 and 1 metre.
* If the object is further than 1 metre, returns 1.0
*/
float readUltrasonic() {
float range = (float)ultrasonic.MeasureInCentimeters() / 100.0;
range = (range > 1 ? 1 : (range < 0 ? 0 : range));
return range;
}
/**
* Write value to 4-digit 7-segment display
* 0.0 will be displayed 0000, and 1.0 will be displayed 9999
*/
void write7Seg(float value) {
int displayValue = (int)(round(value * 100000.0 / 10.0));
displayValue = displayValue > 9999 ? 9999 : (displayValue < 0 ? 0 : displayValue);
tm1637.display(0, (displayValue / 1000) % 10);
tm1637.display(1, (displayValue / 100) % 10);
tm1637.display(2, (displayValue / 10) % 10);
tm1637.display(3, displayValue % 10);
}
/**
* Write value to buzzer, value 0.0 will mute the buzzer, the more the value is, the lounder the buzzer buzzes.
*/
void writeBuzz(float value) {
value *= 255.0;
value = value < 0 ? 0 : (value > 255 ? 255 : value);
analogWrite(ACTUATOR_BUZZ_PIN, value);
}
/**
* Write value to chainable LED, the colour will always be white, brightness will depend on value from 0: darkest, 1: brightness
*/
void writeLed(float value) {
value *= 255.0;
value = value < 0 ? 0 : (value > 255 ? 255 : value);
leds.setColorRGB(0, (int)value, (int)value, (int)value);
}
void setup() {
switch (SENSOR) {
case SENSOR_BUTTON:
pinMode(SENSOR_BUTTON_PIN, INPUT); break;
case SENSOR_DHT_HUMIDITY:
dht.begin(); break;
case SENSOR_DHT_TEMPERATURE:
dht.begin(); break;
case SENSOR_LIGHT:
pinMode(SENSOR_LIGHT_PIN, INPUT); break;
case SENSOR_ROTARY:
pinMode(SENSOR_ROTARY_PIN, INPUT); break;
}
switch (ACTUATOR) {
case ACTUATOR_7SEG:
tm1637.init();
tm1637.set(BRIGHT_TYPICAL);
tm1637.point(POINT_OFF);
break;
case ACTUATOR_BUZZ:
pinMode(ACTUATOR_BUZZ_PIN, OUTPUT); break;
case ACTUATOR_LED:
leds.init(); break;
}
}
void loop() {
switch (SENSOR) {
case SENSOR_BUTTON:
SensorValue = readButton(); break;
case SENSOR_DHT_HUMIDITY:
SensorValue = readDhtHumidity(SensorValue); break;
case SENSOR_DHT_TEMPERATURE:
SensorValue = readDhtTemperature(SensorValue); break;
case SENSOR_LIGHT:
SensorValue = readLight(); break;
case SENSOR_ROTARY:
SensorValue = readRotary(); break;
case SENSOR_ULTRASONIC:
SensorValue = readUltrasonic(); break;
}
if (REVERSE) {
SensorValue = 1 - SensorValue;
}
// ↓ Uncomment to publish SensorValue to Particle cloud every PUBLISH_WAIT loops
// publishNumber(SensorValue);
switch (ACTUATOR) {
case ACTUATOR_7SEG:
write7Seg(SensorValue); break;
case ACTUATOR_BUZZ:
writeBuzz(SensorValue); break;
case ACTUATOR_LED:
writeLed(SensorValue); break;
}
delay(INTERVAL);
}
| [
"ponlawat_w@cmu.ac.th"
] | ponlawat_w@cmu.ac.th |
30845cb82887893b825778fc8f4ef5349dae9cc2 | 3966bdaa82deff3f5007ce8e5ca0c7b81fbc3e81 | /atcoder/bcu30/c.cpp | 24dec84cd169ce3dbc210598860bf39e9fb92877 | [] | no_license | sogapalag/contest | be955b61af67f1c104862e10ed51da9cea596016 | c1a2a8268d269c559d937148e7c7fa8c236a61ad | refs/heads/master | 2023-03-18T04:51:39.882314 | 2021-03-08T00:16:04 | 2021-03-08T00:16:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 562 | cpp | #include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
#include <map>
#include <set>
using namespace std;
#define rep(i, n) for (int i = 0; i < int(n); ++i)
typedef long long i64;
int main(void) {
int n, m;
cin>>n>>m;
vector<vector<int> > mat(n, vector<int>(n));
rep(i, m) {
int a, b;
cin >> a >> b;
a--, b--;
mat[a][b] = 1;
}
vector<vector<int> > mat2(n, vector<int>(n));
rep(k, n)rep(i,n)rep(j,n) {
mat2[i][j] += mat[i][k] * mat[k][j];
}
i64 tot = 0;
rep(i, n)rep(j, n) {
tot += (i64)mat2[i][j] * mat2[i][j];
}
cout << tot << endl;
}
| [
"koba_max@kobas-Air.pohe"
] | koba_max@kobas-Air.pohe |
fa2f3999b59584ed2aefa01d64e7e1e9f7449db0 | bac2e3150dad528691b93c7b7d0ca4959cece801 | /Baekjoon/구현/1074-z.cpp | 93ccb3e80e1332638588486e519d6b5a275f9542 | [] | no_license | bbvch13531/algorithm | 78c566bcac9dd642dd81ad4d6aca10fa50746cfb | cf2737d2ffe7f1ef53841c273ff460e38e397ebf | refs/heads/master | 2023-01-06T05:24:55.207768 | 2022-12-21T11:17:49 | 2022-12-21T11:17:49 | 164,439,044 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 732 | cpp | #include <iostream>
#include <stdio.h>
using namespace std;
void func(int n, int x, int y);
int twoexp(int n);
int cnt;
int map[16][16];
int main(void){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int N, R, C, exp;
cin>> N >> R >> C;
exp = twoexp(N);
cout<<"exp is "<<exp<<"\n";
func(N, exp-1, exp-1);
for(int i=0; i<exp; i++){
for(int j=0; j<exp; j++){
cout<<map[i][j]<<" ";
}
cout<<"\n";
}
return 0;
}
void func(int n, int x, int y){
if(n == 0){
cout<<n<<" "<<cnt<<" "<<x<<" "<<y<<"\n";
map[x][y] = cnt;
cnt++;
return ;
}
func(n/2, x/2, y/2);
func(n/2, x/2, y);
func(n/2, x, y/2);
func(n/2, x, y);
}
int twoexp(int n){
int num = 1;
for(int i=0; i<n; i++)
num *= 2;
return num;
}
| [
"bbvch13531@gmail.com"
] | bbvch13531@gmail.com |
a227ec7d47d39a08a356e097ac8acc0eec8f92b6 | f17a88ddef74abe099a0c9d9d9aa91b90075959c | /Code/Runtime/Asset/AssetObject.h | d7bd54d1cd1533d5a246447b9abaf571d9bf7957 | [
"MIT",
"Apache-2.0"
] | permissive | NathanSaidas/LiteForgeMirror | bf4b0feb9702b590b510f98f32a3cc1d472f9bb0 | dcb7f690378dd0abe0d1dc3e2783510ce9462fde | refs/heads/master | 2022-06-12T11:55:06.321048 | 2022-05-30T04:37:59 | 2022-05-30T04:37:59 | 184,840,363 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,128 | h | // ********************************************************************
// Copyright (c) 2019-2020 Nathan Hanlan
//
// 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.
// ********************************************************************
#ifndef LF_RUNTIME_ASSET_OBJECT_H
#define LF_RUNTIME_ASSET_OBJECT_H
#include "Core/Reflection/Object.h"
#include "Core/Memory/AtomicSmartPointer.h"
#include "Runtime/Asset/AssetTypeInfo.h"
#include "Runtime/Reflection/ReflectionTypes.h"
namespace lf {
DECLARE_MANAGED_CPTR(AssetTypeInfo);
class AssetPath;
class LF_RUNTIME_API AssetObject : public Object, public TAtomicWeakPointerConvertible<AssetObject>
{
DECLARE_CLASS(AssetObject, Object);
public:
using PointerConvertible = PointerConvertibleType;
AssetObject();
virtual ~AssetObject();
void SetAssetType(const AssetTypeInfo* type) { mAssetType = AssetTypeInfoCPtr(type); }
const AssetTypeInfoCPtr& GetAssetType() const { return mAssetType; }
const AssetPath& GetAssetPath() const;
private:
AssetTypeInfoCPtr mAssetType;
};
}
#endif // LF_RUNTIME_ASSET_OBJECT_H | [
"nathanhanlan@gmail.com"
] | nathanhanlan@gmail.com |
04b9006d749dcefe1124f47bcbd83f64317bd1e0 | e485e6ec3a2e8ee6751dace40b6a9dc69f0ada5a | /SPH2S_FINAL_TWO_SCALE/cuda.cpp | 414978e3383790370a789d3c61b520d11813fbe2 | [] | no_license | segfault11/SPH2S_FINAL | 83a797dbfec392695fc4bbe4b5a96907294276e3 | 1106a19d90ad2715ba4343918279e45bf87c6835 | refs/heads/master | 2020-04-13T00:20:37.068642 | 2013-06-03T01:09:06 | 2013-06-03T01:09:06 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,577 | cpp | //------------------------------------------------------------------------------
// cuda.h
// FastTurbulentFluids
//
// Created by Arno in Wolde Lübke on 18.02.13.
// Copyright (c) 2013. All rights reserved.
//------------------------------------------------------------------------------
#include <iostream>
#include "cuda.h"
//------------------------------------------------------------------------------
CUDA::Timer::Timer ()
: mState(CT_STOPPED)
{
cudaEventCreate(&mStart);
cudaEventCreate(&mStop);
}
//------------------------------------------------------------------------------
CUDA::Timer::~Timer ()
{
cudaEventDestroy(mStart);
cudaEventDestroy(mStop);
}
//------------------------------------------------------------------------------
void CUDA::Timer::Start ()
{
cudaEventRecord(mStart, 0);
mState = CT_TAKING_TIME;
}
//------------------------------------------------------------------------------
void CUDA::Timer::Stop ()
{
cudaEventRecord(mStop, 0);
cudaEventSynchronize(mStop);
cudaEventElapsedTime(&mTime, mStart, mStop);
mState = CT_STOPPED;
}
//------------------------------------------------------------------------------
void CUDA::Timer::DumpElapsed () const
{
if (mState == CT_TAKING_TIME)
{
return;
}
std::cout << mTime << " [ms] elapsed" << std::endl;
}
//------------------------------------------------------------------------------
float CUDA::Timer::GetElapsed() const
{
return mTime;
}
//------------------------------------------------------------------------------ | [
"arno.luebke@googlemail.com"
] | arno.luebke@googlemail.com |
ef83259be643b6ea801bf76692da865ed7a7ab7d | a8b95e78736b14a46bf70f8225a68673de2d29d1 | /ref/flange/system/meshQualityDict | 80e219f5fa6a9eaf3616733890c261f529fd4fd1 | [] | no_license | randomwangran/randomwangran-mesh | 1c2c28ea3968a538471a045a215290665b1a4d28 | 97d51bd4c4f3ef7f0fd97f44c54818cac2712d43 | refs/heads/main | 2023-03-14T15:10:05.337209 | 2021-03-05T04:33:43 | 2021-03-05T04:33:43 | 340,110,787 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 785 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 7
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class dictionary;
object meshQualityDict;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// Include defaults parameters from master dictionary
#includeEtc "caseDicts/mesh/generation/meshQualityDict"
// ************************************************************************* //
| [
"randombazinga@gmail.com"
] | randombazinga@gmail.com | |
4e3b5da10cac12c5cc275d8572611405651f849a | d0fb46aecc3b69983e7f6244331a81dff42d9595 | /drds/include/alibabacloud/drds/model/SetBackupLocalResult.h | fec009662927283f1d4ee475fba91452a1ae6316 | [
"Apache-2.0"
] | permissive | aliyun/aliyun-openapi-cpp-sdk | 3d8d051d44ad00753a429817dd03957614c0c66a | e862bd03c844bcb7ccaa90571bceaa2802c7f135 | refs/heads/master | 2023-08-29T11:54:00.525102 | 2023-08-29T03:32:48 | 2023-08-29T03:32:48 | 115,379,460 | 104 | 82 | NOASSERTION | 2023-09-14T06:13:33 | 2017-12-26T02:53:27 | C++ | UTF-8 | C++ | false | false | 1,417 | h | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ALIBABACLOUD_DRDS_MODEL_SETBACKUPLOCALRESULT_H_
#define ALIBABACLOUD_DRDS_MODEL_SETBACKUPLOCALRESULT_H_
#include <string>
#include <vector>
#include <utility>
#include <alibabacloud/core/ServiceResult.h>
#include <alibabacloud/drds/DrdsExport.h>
namespace AlibabaCloud
{
namespace Drds
{
namespace Model
{
class ALIBABACLOUD_DRDS_EXPORT SetBackupLocalResult : public ServiceResult
{
public:
SetBackupLocalResult();
explicit SetBackupLocalResult(const std::string &payload);
~SetBackupLocalResult();
bool getSuccess()const;
std::string getResult()const;
protected:
void parse(const std::string &payload);
private:
bool success_;
std::string result_;
};
}
}
}
#endif // !ALIBABACLOUD_DRDS_MODEL_SETBACKUPLOCALRESULT_H_ | [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
264f77e8e4db045874272843b8341c6c55aa97af | 4c11a4f4e835b48c37f8a4bb779acaa4436463d7 | /Source/DualCombatColor_FPS/Parkour_GameMode.cpp | 8d27bda2fa23fc3c739befb7a4ca1f518a7422ce | [] | no_license | TheoLeyenda/TSDVJ-UnrealGame | a2e48ce9f7963dc6d8cad513a67de4f70af57148 | bf4adf0c7b811034fbd44d2df9e2f90ce768027c | refs/heads/master | 2022-11-06T06:08:19.588523 | 2020-07-04T01:37:52 | 2020-07-04T01:37:52 | 270,111,055 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,458 | cpp | #include "Parkour_GameMode.h"
#include "Engine/World.h"
#include "PlatformPawn.h"
#include "Kismet/GameplayStatics.h"
#include "GameFramework/Actor.h"
#include "AssetLoaderManager.h"
AParkour_GameMode::AParkour_GameMode()
{
}
void AParkour_GameMode::Tick(float DeltaTime)
{
}
void AParkour_GameMode::BeginPlay()
{
UGameplayStatics::GetAllActorsOfClass(GetWorld(), platformPawn_Class, actorPlatforms);
for (AActor* actor : actorPlatforms)
{
if (actor != nullptr)
{
UE_LOG(LogTemp, Warning, TEXT("Hola Actors:D"));
refPlatforms.Add(Cast<APlatformPawn>(actor));
}
}
for (APlatformPawn* refplatform : refPlatforms)
{
if (refplatform != nullptr)
{
UE_LOG(LogTemp, Warning, TEXT("Hola Platforms :D"));
FVector position = GetRandomPosition(refplatform->length, refplatform->wight, refplatform->GetActorTransform().GetLocation().Z + 10);
FRotator rotator = refplatform->GetActorRotation();
//Spawning objects
}
}
//Carga El Asset de forma Asyncronica//
AAssetLoaderManager* AssetLoader = Cast<AAssetLoaderManager>(AAssetLoaderManager::StaticClass()->GetDefaultObject());
AssetLoader->LoadAssets();
GEngine->AddOnScreenDebugMessage(-1, 10.0f, FColor::Green, TEXT("AssetLoadStart"));
//----------------------------------//
}
FVector AParkour_GameMode::GetRandomPosition(float maxLength, float maxWight, float hight)
{
return FVector(FMath::RandRange(-maxLength, maxLength), hight, FMath::RandRange(-maxWight, maxWight));
} | [
"31700515+TheoLeyenda@users.noreply.github.com"
] | 31700515+TheoLeyenda@users.noreply.github.com |
1692a927138798a89c5c900602593eac21d4e6da | ef0e1123d212a169ed9e0a72634e9f2e2050eee6 | /MathLib/matrix3.hpp | 46da9f25cbccf551024a1c4f34a4b226458fd71c | [] | no_license | seanseankim/CS200ClassProject | 0d2487fe5fc795678c25d28886fc5000a89adf6a | b6a3ebd7a81889bf0ce7ebd9fd4b4d0331ff5a63 | refs/heads/master | 2020-09-21T15:40:43.216387 | 2019-12-08T13:05:33 | 2019-12-08T13:05:33 | 224,834,687 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,038 | hpp | /*
*Jeesoo Kim
*Class Project
*CS200
*Fall 2019
*/
#pragma once
#include "vector2.hpp"
#include "vector3.hpp"
#pragma warning(push)
#pragma warning(disable : 4201) // warning C4201 : nonstandard extension used : nameless struct / union
/**
* \brief Column first 3x3 matrix class
*/
template <typename T>
struct [[nodiscard]] matrix3
{
public:
union {
float elements[3][3];
struct
{
vector3<T> column0;
vector3<T> column1;
vector3<T> column2;
};
};
constexpr matrix3() noexcept;
constexpr matrix3(vector3<T> first_column, vector3<T> second_column, vector3<T> third_column) noexcept;
constexpr matrix3(T column0_row0, T column0_row1, T column0_row2, T column1_row0, T column1_row1,
T column1_row2, T column2_row0, T column2_row1, T column2_row2) noexcept;
constexpr T operator()(T column, T row) const noexcept;
constexpr T& operator()(int column, int row) noexcept;
};
template <typename T>
constexpr matrix3<T> operator*(const matrix3<T>& m1, const matrix3<T>& m2) noexcept;
template <typename T>
constexpr void operator*=(matrix3<T>& m1, const matrix3<T>& m2) noexcept;
template <typename T>
constexpr vector3<T> operator*(const matrix3<T>& m, vector3<T> v) noexcept;
template <typename T>
struct vector2;
namespace MATRIX3
{
template <typename T>
constexpr matrix3<T> transpose(const matrix3<T>& m) noexcept;
template <typename T>
constexpr matrix3<T> build_rotation(T angle_in_radians) noexcept;
template <typename T>
constexpr matrix3<T> build_identity(T iden) noexcept;
template <typename T>
constexpr matrix3<T> build_scale(T scale_x, T scale_y) noexcept;
template <typename T>
constexpr matrix3<T> build_scale(T scale) noexcept;
template <typename T>
constexpr matrix3<T> build_scale(const vector2<T>& scale) noexcept;
template <typename T>
constexpr matrix3<T> build_translation(T translate_x, T translate_y) noexcept;
template <typename T>
constexpr matrix3<T> build_translation(const vector2<T>& translation) noexcept;
}
#pragma warning(pop)
#include "matrix3.inl"
| [
"seanseanseankim@gmail.com"
] | seanseanseankim@gmail.com |
da282acfabeaaeb3e716c6db58d5bb79f3290337 | 3f513b591efa8fe6aadc8e8b9d7f3245afcc444f | /ThirdParty/accidental-noise-library/VM/noise_gen.inl | c3b88e1881b190ee8abcc9ef79e91d9693ac1ba0 | [
"Zlib",
"MIT"
] | permissive | elix22/U3DTerrainEditor | be0b6e066d5fa53296565b9e9fd4a8e87a01fe60 | 78e74c6dad705f037b70a8bf1f912b574c4ccde5 | refs/heads/master | 2021-04-29T23:47:14.870630 | 2020-11-11T22:52:13 | 2020-11-11T22:52:13 | 121,564,169 | 0 | 0 | MIT | 2020-11-11T22:52:15 | 2018-02-14T21:37:15 | CMake | WINDOWS-1250 | C++ | false | false | 44,723 | inl |
#include <vector>
#include <algorithm>
#include <math.h>
namespace anl
{
double noInterp(double t)
{
return 0;
}
double linearInterp(double t)
{
return t;
}
double hermiteInterp(double t)
{
return (t*t*(3-2*t));
}
double quinticInterp(double t)
{
return t*t*t*(t*(t*6-15)+10);
}
inline int fast_floor(double t)
{
return (t>0 ? (int)t : (int)t - 1);
}
inline double array_dot2(double *arr, double a, double b)
{
return a*arr[0] + b*arr[1];
}
inline double array_dot3(double *arr, double a, double b, double c)
{
return a*arr[0]+b*arr[1]+c*arr[2];
}
inline double array_dot4(double *arr, double x, double y, double z, double w)
{
return x*arr[0]+y*arr[1]+z*arr[2]+w*arr[3];
}
inline double array_dot6(double *arr, double x, double y, double z, double w, double u, double v)
{
return x*arr[0]+y*arr[1]+z*arr[2]+w*arr[3]+u*arr[4]+v*arr[5];
}
// Distance
double distEuclid2(double x1, double y1, double x2, double y2)
{
double dx=x2-x1;
double dy=y2-y1;
return sqrt(dx*dx+dy*dy);
}
double distEuclid3(double x1, double y1, double z1, double x2, double y2, double z2)
{
double dx=x2-x1;
double dy=y2-y1;
double dz=z2-z1;
return sqrt(dx*dx+dy*dy+dz*dz);
}
double distEuclid4(double x1, double y1, double z1, double w1, double x2, double y2, double z2, double w2)
{
double dx=x2-x1;
double dy=y2-y1;
double dz=z2-z1;
double dw=w2-w1;
return sqrt(dx*dx+dy*dy+dz*dz+dw*dw);
}
double distEuclid6(double x1, double y1, double z1, double w1, double u1, double v1, double x2, double y2, double z2, double w2, double u2, double v2)
{
double dx=x2-x1;
double dy=y2-y1;
double dz=z2-z1;
double dw=w2-w1;
double du=u2-u1;
double dv=v2-v1;
return sqrt(dx*dx+dy*dy+dz*dz+dw*dw+du*du+dv*dv);
}
double distManhattan2(double x1, double y1, double x2, double y2)
{
double dx=fabs(x2-x1);
double dy=fabs(y2-y1);
//return std::max(dx,dy);
return dx+dy;
}
double distManhattan3(double x1, double y1, double z1, double x2, double y2, double z2)
{
double dx=fabs(x2-x1);
double dy=fabs(y2-y1);
double dz=fabs(z2-z1);
//return std::max(dz,std::max(dx,dy));
return dx+dy+dz;
}
double distManhattan4(double x1, double y1, double z1, double w1, double x2, double y2, double z2, double w2)
{
double dx=fabs(x2-x1);
double dy=fabs(y2-y1);
double dz=fabs(z2-z1);
double dw=fabs(w2-w1);
//return std::max(dw,std::max(dz,std::max(dx,dy)));
return dx+dy+dz+dw;
}
double distManhattan6(double x1, double y1, double z1, double w1, double u1, double v1, double x2, double y2, double z2, double w2, double u2, double v2)
{
double dx=fabs(x2-x1);
double dy=fabs(y2-y1);
double dz=fabs(z2-z1);
double dw=fabs(w2-w1);
double du=fabs(u2-u1);
double dv=fabs(v2-v1);
//return std::max(du,std::max(dv,std::max(dw,std::max(dz,std::max(dx,dy)))));
return dx+dy+dz+dw+du+dv;
}
double distGreatestAxis2(double x1, double y1, double x2, double y2)
{
double dx=fabs(x2-x1);
double dy=fabs(y2-y1);
return std::max(dx,dy);
}
double distGreatestAxis3(double x1, double y1, double z1, double x2, double y2, double z2)
{
double dx=fabs(x2-x1);
double dy=fabs(y2-y1);
double dz=fabs(z2-z1);
return std::max(dz,std::max(dx,dy));
}
double distGreatestAxis4(double x1, double y1, double z1, double w1, double x2, double y2, double z2, double w2)
{
double dx=fabs(x2-x1);
double dy=fabs(y2-y1);
double dz=fabs(z2-z1);
double dw=fabs(w2-w1);
return std::max(dw,std::max(dz,std::max(dx,dy)));
}
double distGreatestAxis6(double x1, double y1, double z1, double w1, double u1, double v1, double x2, double y2, double z2, double w2, double u2, double v2)
{
double dx=fabs(x2-x1);
double dy=fabs(y2-y1);
double dz=fabs(z2-z1);
double dw=fabs(w2-w1);
double du=fabs(u2-u1);
double dv=fabs(v2-v1);
return std::max(du,std::max(dv,std::max(dw,std::max(dz,std::max(dx,dy)))));
}
double distLeastAxis2(double x1, double y1, double x2, double y2)
{
double dx=fabs(x2-x1);
double dy=fabs(y2-y1);
return std::min(dx,dy);
}
double distLeastAxis3(double x1, double y1, double z1, double x2, double y2, double z2)
{
double dx=fabs(x2-x1);
double dy=fabs(y2-y1);
double dz=fabs(z2-z1);
return std::min(dz,std::min(dx,dy));
}
double distLeastAxis4(double x1, double y1, double z1, double w1, double x2, double y2, double z2, double w2)
{
double dx=fabs(x2-x1);
double dy=fabs(y2-y1);
double dz=fabs(z2-z1);
double dw=fabs(w2-w1);
return std::min(dw,std::min(dz,std::min(dx,dy)));
}
double distLeastAxis6(double x1, double y1, double z1, double w1, double u1, double v1, double x2, double y2, double z2, double w2, double u2, double v2)
{
double dx=fabs(x2-x1);
double dy=fabs(y2-y1);
double dz=fabs(z2-z1);
double dw=fabs(w2-w1);
double du=fabs(u2-u1);
double dv=fabs(v2-v1);
return std::min(du,std::min(dv,std::min(dw,std::min(dz,std::min(dx,dy)))));
}
unsigned int compute_hash_double_2(double x, double y, unsigned int seed)
{
//double d[3]={x,y,(double)seed};
//unsigned int s=sizeof(d) / sizeof(unsigned int);
//return xor_fold_hash(fnv_32_a_buf(d, s));
unsigned int hash=FNV_32_INIT;
hash=fnv_32_a_combine(hash, (unsigned int)(x*(double)1000000));
hash=fnv_32_a_combine(hash, (unsigned int)(y*(double)1000000));
hash=fnv_32_a_combine(hash, seed);
return xor_fold_hash(hash);
}
unsigned int compute_hash_double_3(double x, double y, double z, unsigned int seed)
{
//double d[4]={x,y,z,(double)seed};
//unsigned int s=sizeof(d) / sizeof(unsigned int);
//return xor_fold_hash(fnv_32_a_buf(d, s));
unsigned int hash=FNV_32_INIT;
hash=fnv_32_a_combine(hash, (unsigned int)(x*(double)1000000));
hash=fnv_32_a_combine(hash, (unsigned int)(y*(double)1000000));
hash=fnv_32_a_combine(hash, (unsigned int)(z*(double)1000000));
hash=fnv_32_a_combine(hash, seed);
return xor_fold_hash(hash);
}
unsigned int compute_hash_double_4(double x, double y, double z, double w, unsigned int seed)
{
//double d[5]={x,y,z,w,(double)seed};
//unsigned int s=sizeof(d) / sizeof(unsigned int);
//return xor_fold_hash(fnv_32_a_buf(d, s));
unsigned int hash=FNV_32_INIT;
hash=fnv_32_a_combine(hash, (unsigned int)(x*(double)1000000));
hash=fnv_32_a_combine(hash, (unsigned int)(y*(double)1000000));
hash=fnv_32_a_combine(hash, (unsigned int)(z*(double)1000000));
hash=fnv_32_a_combine(hash, (unsigned int)(w*(double)1000000));
hash=fnv_32_a_combine(hash, seed);
return xor_fold_hash(hash);
}
unsigned int compute_hash_double_6(double x, double y, double z, double w, double u, double v, unsigned int seed)
{
//double d[7]={x,y,z,w,u,v,(double)seed};
//unsigned int s=sizeof(d) / sizeof(unsigned int);
//return xor_fold_hash(fnv_32_a_buf(d, s));
unsigned int hash=FNV_32_INIT;
hash=fnv_32_a_combine(hash, (unsigned int)(x*(double)1000000));
hash=fnv_32_a_combine(hash, (unsigned int)(y*(double)1000000));
hash=fnv_32_a_combine(hash, (unsigned int)(z*(double)1000000));
hash=fnv_32_a_combine(hash, (unsigned int)(w*(double)1000000));
hash=fnv_32_a_combine(hash, (unsigned int)(u*(double)1000000));
hash=fnv_32_a_combine(hash, (unsigned int)(v*(double)1000000));
hash=fnv_32_a_combine(hash, seed);
return xor_fold_hash(hash);
}
// Worker noise functions
typedef double (*worker_noise_2)(double, double, int, int, unsigned int);
typedef double (*worker_noise_3)(double, double, double, int, int, int, unsigned int);
typedef double (*worker_noise_4)(double,double,double,double,int,int,int,int,unsigned int);
typedef double (*worker_noise_6)(double,double,double,double,double,double,int,int,int,int,int,int,unsigned int);
double value_noise_2( double x, double y, int ix, int iy, unsigned int seed)
{
unsigned int n = (hash_coords_2(ix,iy,seed)) % 256;
double noise = (double)n / 255.0;
return noise*2.0 - 1.0;
}
double value_noise_3(double x, double y, double z, int ix, int iy, int iz, unsigned int seed)
{
unsigned int n = (hash_coords_3(ix,iy,iz,seed)) % 256;
double noise=(double)n/(255.0);
return noise*2.0-1.0;
}
double value_noise_4(double x, double y, double z, double w, int ix, int iy,int iz,int iw, unsigned int seed)
{
unsigned int n = (hash_coords_4(ix,iy,iz,iw,seed)) % 256;
double noise = (double)n / 255.0;
return noise*2.0 - 1.0;
}
double value_noise_6(double x, double y, double z, double w, double u, double v, int ix, int iy,int iz,int iw, int iu, int iv, unsigned int seed)
{
unsigned int n = (hash_coords_6(ix,iy,iz,iw,iu,iv,seed)) % 256;
double noise = (double)n / 255.0;
return noise*2.0 - 1.0;
}
double grad_noise_2(double x, double y, int ix, int iy, unsigned int seed)
{
unsigned int hash=hash_coords_2(ix,iy,seed)%8;
double *vec=&gradient2D_lut[hash][0];
double dx=x-(double)ix;
double dy=y-(double)iy;
return (dx*vec[0] + dy*vec[1]);
}
double grad_noise_3(double x, double y, double z, int ix, int iy, int iz, unsigned int seed)
{
unsigned int hash=hash_coords_3(ix,iy,iz,seed)%12;
double *vec=&gradient3D_lut[hash][0];
double dx=x-(double)ix;
double dy=y-(double)iy;
double dz=z-(double)iz;
return (dx*vec[0]+dy*vec[1]+dz*vec[2]);
}
double grad_noise_4(double x, double y, double z, double w, int ix, int iy, int iz, int iw, unsigned int seed)
{
unsigned int hash=hash_coords_4(ix,iy,iz,iw,seed)%64;
double *vec=&gradient4D_lut[hash][0];
double dx=x-(double)ix;
double dy=y-(double)iy;
double dz=z-(double)iz;
double dw=w-(double)iw;
return (dx*vec[0] + dy*vec[1] + dz*vec[2] + dw*vec[3]);
}
double grad_noise_6(double x, double y, double z, double w, double u, double v, int ix, int iy, int iz, int iw, int iu, int iv, unsigned int seed)
{
unsigned int hash=hash_coords_6(ix,iy,iz,iw,iu,iv,seed)%192;
double *vec=&gradient6D_lut[hash][0];
double dx=x-(double)ix;
double dy=y-(double)iy;
double dz=z-(double)iz;
double dw=w-(double)iw;
double du=u-(double)iu;
double dv=v-(double)iv;
return (dx*vec[0] + dy*vec[1] + dz*vec[2] + dw*vec[3] + du*vec[4] + dv*vec[5]);
}
// Edge/Face/Cube/Hypercube interpolation
double lerp(double s, double v1, double v2)
{
return v1+s*(v2-v1);
}
double interp_X_2(double x, double y, double xs, int x0, int x1, int iy, unsigned int seed, worker_noise_2 noisefunc)
{
double v1=noisefunc(x,y,x0,iy,seed);
double v2=noisefunc(x,y,x1,iy,seed);
return lerp(xs,v1,v2);
}
double interp_XY_2(double x, double y, double xs, double ys, int x0, int x1, int y0, int y1, unsigned int seed, worker_noise_2 noisefunc)
{
double v1=interp_X_2(x,y,xs,x0,x1,y0,seed,noisefunc);
double v2=interp_X_2(x,y,xs,x0,x1,y1,seed,noisefunc);
return lerp(ys,v1,v2);
}
double interp_X_3(double x, double y, double z, double xs, int x0, int x1, int iy, int iz, unsigned int seed, worker_noise_3 noisefunc)
{
double v1=noisefunc(x,y,z,x0,iy,iz,seed);
double v2=noisefunc(x,y,z,x1,iy,iz,seed);
return lerp(xs,v1,v2);
}
double interp_XY_3(double x, double y, double z, double xs, double ys, int x0, int x1, int y0, int y1, int iz, unsigned int seed, worker_noise_3 noisefunc)
{
double v1=interp_X_3(x,y,z,xs,x0,x1,y0,iz,seed,noisefunc);
double v2=interp_X_3(x,y,z,xs,x0,x1,y1,iz,seed,noisefunc);
return lerp(ys,v1,v2);
}
double interp_XYZ_3(double x, double y, double z, double xs, double ys, double zs, int x0, int x1, int y0, int y1, int z0, int z1, unsigned int seed, worker_noise_3 noisefunc)
{
double v1=interp_XY_3(x,y,z,xs,ys,x0,x1,y0,y1,z0,seed,noisefunc);
double v2=interp_XY_3(x,y,z,xs,ys,x0,x1,y0,y1,z1,seed,noisefunc);
return lerp(zs,v1,v2);
}
double interp_X_4(double x, double y, double z, double w, double xs, int x0, int x1, int iy, int iz, int iw, unsigned int seed, worker_noise_4 noisefunc)
{
double v1=noisefunc(x,y,z,w,x0,iy,iz,iw,seed);
double v2=noisefunc(x,y,z,w,x1,iy,iz,iw,seed);
return lerp(xs,v1,v2);
}
double interp_XY_4(double x, double y, double z, double w, double xs, double ys, int x0, int x1, int y0, int y1, int iz, int iw, unsigned int seed, worker_noise_4 noisefunc)
{
double v1=interp_X_4(x,y,z,w,xs,x0,x1,y0,iz,iw,seed,noisefunc);
double v2=interp_X_4(x,y,z,w,xs,x0,x1,y1,iz,iw,seed,noisefunc);
return lerp(ys,v1,v2);
}
double interp_XYZ_4(double x, double y, double z, double w, double xs, double ys, double zs, int x0, int x1, int y0, int y1, int z0, int z1, int iw, unsigned int seed, worker_noise_4 noisefunc)
{
double v1=interp_XY_4(x,y,z,w,xs,ys,x0,x1,y0,y1,z0,iw,seed,noisefunc);
double v2=interp_XY_4(x,y,z,w,xs,ys,x0,x1,y0,y1,z1,iw,seed,noisefunc);
return lerp(zs,v1,v2);
}
double interp_XYZW_4(double x, double y, double z, double w, double xs, double ys, double zs, double ws, int x0, int x1, int y0, int y1, int z0, int z1, int w0, int w1, unsigned int seed, worker_noise_4 noisefunc)
{
double v1=interp_XYZ_4(x,y,z,w,xs,ys,zs,x0,x1,y0,y1,z0,z1,w0,seed,noisefunc);
double v2=interp_XYZ_4(x,y,z,w,xs,ys,zs,x0,x1,y0,y1,z0,z1,w1,seed,noisefunc);
return lerp(ws,v1,v2);
}
double interp_X_6(double x, double y, double z, double w, double u, double v, double xs, int x0, int x1, int iy, int iz, int iw, int iu, int iv, unsigned int seed, worker_noise_6 noisefunc)
{
double v1=noisefunc(x,y,z,w,u,v,x0,iy,iz,iw,iu,iv,seed);
double v2=noisefunc(x,y,z,w,u,v,x1,iy,iz,iw,iu,iv,seed);
return lerp(xs,v1,v2);
}
double interp_XY_6(double x, double y, double z, double w, double u, double v, double xs, double ys, int x0, int x1, int y0, int y1, int iz, int iw, int iu, int iv, unsigned int seed, worker_noise_6 noisefunc)
{
double v1=interp_X_6(x,y,z,w,u,v,xs, x0,x1,y0,iz,iw,iu,iv,seed,noisefunc);
double v2=interp_X_6(x,y,z,w,u,v,xs,x0,x1,y1,iz,iw,iu,iv,seed,noisefunc);
return lerp(ys,v1,v2);
}
double interp_XYZ_6(double x, double y, double z, double w, double u, double v, double xs, double ys, double zs, int x0, int x1, int y0, int y1, int z0, int z1, int iw, int iu, int iv, unsigned int seed, worker_noise_6 noisefunc)
{
double v1=interp_XY_6(x,y,z,w,u,v,xs,ys,x0,x1,y0,y1,z0,iw,iu,iv,seed,noisefunc);
double v2=interp_XY_6(x,y,z,w,u,v,xs,ys,x0,x1,y0,y1,z1,iw,iu,iv,seed,noisefunc);
return lerp(zs,v1,v2);
}
double interp_XYZW_6(double x, double y, double z, double w, double u, double v, double xs, double ys, double zs, double ws, int x0, int x1, int y0, int y1, int z0, int z1, int w0, int w1, int iu, int iv, unsigned int seed,worker_noise_6 noisefunc)
{
double v1=interp_XYZ_6(x,y,z,w,u,v,xs,ys,zs,x0,x1,y0,y1,z0,z1,w0,iu,iv,seed,noisefunc);
double v2=interp_XYZ_6(x,y,z,w,u,v,xs,ys,zs,x0,x1,y0,y1,z0,z1,w1,iu,iv,seed,noisefunc);
return lerp(ws,v1,v2);
}
double interp_XYZWU_6(double x, double y, double z, double w, double u, double v, double xs, double ys, double zs, double ws, double us, int x0, int x1, int y0, int y1, int z0, int z1, int w0, int w1, int u0, int u1, int iv, unsigned int seed, worker_noise_6 noisefunc)
{
double v1=interp_XYZW_6(x,y,z,w,u,v,xs,ys,zs,ws,x0,x1,y0,y1,z0,z1,w0,w1,u0,iv,seed,noisefunc);
double v2=interp_XYZW_6(x,y,z,w,u,v,xs,ys,zs,ws,x0,x1,y0,y1,z0,z1,w0,w1,u1,iv,seed,noisefunc);
return lerp(us,v1,v2);
}
double interp_XYZWUV_6(double x, double y, double z, double w, double u, double v, double xs, double ys, double zs, double ws, double us, double vs, int x0, int x1, int y0, int y1, int z0, int z1, int w0, int w1, int u0, int u1, int v0, int v1, unsigned int seed, worker_noise_6 noisefunc)
{
double val1=interp_XYZWU_6(x,y,z,w,u,v,xs,ys,zs,ws,us,x0,x1,y0,y1,z0,z1,w0,w1,u0,u1,v0,seed,noisefunc);
double val2=interp_XYZWU_6(x,y,z,w,u,v,xs,ys,zs,ws,us,x0,x1,y0,y1,z0,z1,w0,w1,u0,u1,v1,seed,noisefunc);
return lerp(vs,val1,val2);
}
// The usable noise functions
double value_noise2D(double x, double y, unsigned int seed, interp_func interp)
{
int x0=fast_floor(x);
int y0=fast_floor(y);
int x1=x0+1;
int y1=y0+1;
double xs=interp((x-(double)x0));
double ys=interp((y-(double)y0));
return interp_XY_2(x,y,xs,ys,x0,x1,y0,y1,seed,value_noise_2);
}
double value_noise3D(double x, double y, double z, unsigned int seed, interp_func interp)
{
int x0=fast_floor(x);
int y0=fast_floor(y);
int z0=fast_floor(z);
int x1=x0+1;
int y1=y0+1;
int z1=z0+1;
double xs=interp((x-(double)x0));
double ys=interp((y-(double)y0));
double zs=interp((z-(double)z0));
return interp_XYZ_3(x,y,z,xs,ys,zs,x0,x1,y0,y1,z0,z1,seed,value_noise_3);
}
double value_noise4D(double x, double y, double z, double w, unsigned int seed, interp_func interp)
{
int x0=fast_floor(x);
int y0=fast_floor(y);
int z0=fast_floor(z);
int w0=fast_floor(w);
int x1=x0+1;
int y1=y0+1;
int z1=z0+1;
int w1=w0+1;
double xs=interp((x-(double)x0));
double ys=interp((y-(double)y0));
double zs=interp((z-(double)z0));
double ws=interp((w-(double)w0));
return interp_XYZW_4(x,y,z,w,xs,ys,zs,ws,x0,x1,y0,y1,z0,z1,w0,w1,seed,value_noise_4);
}
double value_noise6D(double x, double y, double z, double w, double u, double v, unsigned int seed, interp_func interp)
{
int x0=fast_floor(x);
int y0=fast_floor(y);
int z0=fast_floor(z);
int w0=fast_floor(w);
int u0=fast_floor(u);
int v0=fast_floor(v);
int x1=x0+1;
int y1=y0+1;
int z1=z0+1;
int w1=w0+1;
int u1=u0+1;
int v1=v0+1;
double xs=interp((x-(double)x0));
double ys=interp((y-(double)y0));
double zs=interp((z-(double)z0));
double ws=interp((w-(double)w0));
double us=interp((u-(double)u0));
double vs=interp((v-(double)v0));
return interp_XYZWUV_6(x,y,z,w,u,v,xs,ys,zs,ws,us,vs,x0,x1,y0,y1,z0,z1,w0,w1,u0,u1,v0,v1,seed,value_noise_6);
}
double gradient_noise2D(double x, double y, unsigned int seed, interp_func interp)
{
int x0=fast_floor(x);
int y0=fast_floor(y);
int x1=x0+1;
int y1=y0+1;
double xs=interp((x-(double)x0));
double ys=interp((y-(double)y0));
return interp_XY_2(x,y,xs,ys,x0,x1,y0,y1,seed,grad_noise_2);
}
double gradient_noise3D(double x, double y, double z, unsigned int seed, interp_func interp)
{
int x0=fast_floor(x);
int y0=fast_floor(y);
int z0=fast_floor(z);
int x1=x0+1;
int y1=y0+1;
int z1=z0+1;
double xs=interp((x-(double)x0));
double ys=interp((y-(double)y0));
double zs=interp((z-(double)z0));
return interp_XYZ_3(x,y,z,xs,ys,zs,x0,x1,y0,y1,z0,z1,seed,grad_noise_3);
}
double gradient_noise4D(double x, double y, double z, double w, unsigned int seed, interp_func interp)
{
int x0=fast_floor(x);
int y0=fast_floor(y);
int z0=fast_floor(z);
int w0=fast_floor(w);
int x1=x0+1;
int y1=y0+1;
int z1=z0+1;
int w1=w0+1;
double xs=interp((x-(double)x0));
double ys=interp((y-(double)y0));
double zs=interp((z-(double)z0));
double ws=interp((w-(double)w0));
return interp_XYZW_4(x,y,z,w,xs,ys,zs,ws,x0,x1,y0,y1,z0,z1,w0,w1,seed,grad_noise_4);
}
double gradient_noise6D(double x, double y, double z, double w, double u, double v, unsigned int seed, interp_func interp)
{
int x0=fast_floor(x);
int y0=fast_floor(y);
int z0=fast_floor(z);
int w0=fast_floor(w);
int u0=fast_floor(u);
int v0=fast_floor(v);
int x1=x0+1;
int y1=y0+1;
int z1=z0+1;
int w1=w0+1;
int u1=u0+1;
int v1=v0+1;
double xs=interp((x-(double)x0));
double ys=interp((y-(double)y0));
double zs=interp((z-(double)z0));
double ws=interp((w-(double)w0));
double us=interp((u-(double)u0));
double vs=interp((v-(double)v0));
return interp_XYZWUV_6(x,y,z,w,u,v,xs,ys,zs,ws,us,vs,x0,x1,y0,y1,z0,z1,w0,w1,u0,u1,v0,v1,seed,grad_noise_6);
}
double gradval_noise2D(double x, double y, unsigned int seed, interp_func interp)
{
return value_noise2D(x,y,seed,interp)+gradient_noise2D(x,y,seed,interp);
}
double gradval_noise3D(double x, double y, double z, unsigned int seed, interp_func interp)
{
return value_noise3D(x,y,z,seed,interp)+gradient_noise3D(x,y,z,seed,interp);
}
double gradval_noise4D(double x, double y, double z, double w, unsigned int seed, interp_func interp)
{
return value_noise4D(x,y,z,w,seed,interp)+gradient_noise4D(x,y,z,w,seed,interp);
}
double gradval_noise6D(double x, double y, double z, double w, double u, double v, unsigned int seed, interp_func interp)
{
return value_noise6D(x,y,z,w,u,v,seed,interp)+gradient_noise6D(x,y,z,w,u,v,seed,interp);
}
double white_noise2D(double x, double y, unsigned int seed, interp_func interp)
{
unsigned char hash=compute_hash_double_2(x,y,seed);
return whitenoise_lut[hash];
}
double white_noise3D(double x, double y, double z, unsigned int seed, interp_func interp)
{
unsigned char hash=compute_hash_double_3(x,y,z,seed);
//std::cout << (unsigned int)hash << std::endl;
return whitenoise_lut[hash];
}
double white_noise4D(double x, double y, double z, double w, unsigned int seed, interp_func interp)
{
unsigned char hash=compute_hash_double_4(x,y,z,w,seed);
return whitenoise_lut[hash];
}
double white_noise6D(double x, double y, double z, double w, double u, double v, unsigned int seed, interp_func interp)
{
unsigned char hash=compute_hash_double_6(x,y,z,w,u,v,seed);
return whitenoise_lut[hash];
}
void add_dist(double *f, double *disp, double testdist, double testdisp)
{
int index;
// Compare the given distance to the ones already in f
if(testdist < f[3])
{
index=3;
while(index>0 && testdist<f[index-1]) index--;
for(int i=3; i-->index;)
{
f[i+1]=f[i];
disp[i+1]=disp[i];
}
f[index]=testdist;
disp[index]=testdisp;
}
}
// Cellular functions. Compute distance (for cellular modules) and displacement (for voronoi modules)
void cellular_function2D(double x, double y, unsigned int seed, double *f, double *disp, dist_func2 distance)
{
int xint = fast_floor(x);
int yint = fast_floor(y);
for(int c=0; c<4; ++c)
{
f[c]=99999.0;
disp[c]=0.0;
}
{
for(int ycur=yint-3; ycur<=yint+3; ++ycur)
{
for(int xcur=xint-3; xcur<=xint+3; ++xcur)
{
double xpos = (double)xcur + value_noise_2(x,y,xcur,ycur,seed);
double ypos = (double)ycur + value_noise_2(x,y,xcur,ycur,seed+1);
//double xdist=xpos-x;
//double ydist=ypos-y;
//double dist=(xdist*xdist + ydist*ydist);
double dist=distance(xpos,ypos,x,y);
int xval=fast_floor(xpos);
int yval=fast_floor(ypos);
double dsp=value_noise_2(x,y,xval,yval,seed+3);
add_dist(f,disp, dist, dsp);
}
}
}
}
void cellular_function3D(double x, double y, double z, unsigned int seed, double *f, double *disp, dist_func3 distance)
{
int xint = fast_floor(x);
int yint = fast_floor(y);
int zint = fast_floor(z);
for(int c=0; c<4; ++c)
{
f[c]=99999.0;
disp[c]=0.0;
}
for (int zcur=zint-2; zcur<=zint+2; ++zcur)
{
for(int ycur=yint-2; ycur<=yint+2; ++ycur)
{
for(int xcur=xint-2; xcur<=xint+2; ++xcur)
{
double xpos = (double)xcur + value_noise_3(x,y,z,xcur,ycur,zcur,seed);
double ypos = (double)ycur + value_noise_3(x,y,z,xcur,ycur,zcur,seed+1);
double zpos = (double)zcur + value_noise_3(x,y,z,xcur,ycur,zcur,seed+2);
//double xdist=xpos-x;
//double ydist=ypos-y;
//double zdist=zpos-z;
//double dist=(xdist*xdist + ydist*ydist + zdist*zdist);
double dist=distance(xpos,ypos,zpos,x,y,z);
int xval=fast_floor(xpos);
int yval=fast_floor(ypos);
int zval=fast_floor(zpos);
double dsp=value_noise_3(x,y,z,xval,yval,zval,seed+3);
add_dist(f,disp, dist, dsp);
}
}
}
}
void cellular_function4D(double x, double y, double z, double w, unsigned int seed, double *f, double *disp, dist_func4 distance)
{
int xint = fast_floor(x);
int yint = fast_floor(y);
int zint = fast_floor(z);
int wint = fast_floor(w);
for(int c=0; c<4; ++c)
{
f[c]=99999.0;
disp[c]=0.0;
}
for (int wcur=wint-2; wcur<=wint+2; ++wcur)
{
for (int zcur=zint-2; zcur<=zint+2; ++zcur)
{
for(int ycur=yint-2; ycur<=yint+2; ++ycur)
{
for(int xcur=xint-2; xcur<=xint+2; ++xcur)
{
double xpos = (double)xcur + value_noise_4(x,y,z,w,xcur,ycur,zcur,wcur,seed);
double ypos = (double)ycur + value_noise_4(x,y,z,w,xcur,ycur,zcur,wcur,seed+1);
double zpos = (double)zcur + value_noise_4(x,y,z,w,xcur,ycur,zcur,wcur,seed+2);
double wpos = (double)wcur + value_noise_4(x,y,z,w,xcur,ycur,zcur,wcur,seed+3);
//double xdist=xpos-x;
//double ydist=ypos-y;
//double zdist=zpos-z;
//double wdist=wpos-w;
//double dist=(xdist*xdist + ydist*ydist + zdist*zdist + wdist*wdist);
double dist=distance(xpos,ypos,zpos,wpos,x,y,z,w);
int xval=fast_floor(xpos);
int yval=fast_floor(ypos);
int zval=fast_floor(zpos);
int wval=fast_floor(wpos);
double dsp=value_noise_4(x,y,z,w,xval,yval,zval,wval,seed+3);
add_dist(f,disp, dist, dsp);
}
}
}
}
}
void cellular_function6D(double x, double y, double z, double w, double u, double v, unsigned int seed, double *f, double *disp, dist_func6 distance)
{
int xint = fast_floor(x);
int yint = fast_floor(y);
int zint = fast_floor(z);
int wint = fast_floor(w);
int uint = fast_floor(u);
int vint = fast_floor(v);
for(int c=0; c<4; ++c)
{
f[c]=99999.0;
disp[c]=0.0;
}
for (int vcur=vint-1; vcur<=vint+1; ++vcur)
{
for(int ucur=uint-1; ucur<=uint+1; ++ucur)
{
for (int wcur=wint-2; wcur<=wint+2; ++wcur)
{
for (int zcur=zint-2; zcur<=zint+2; ++zcur)
{
for(int ycur=yint-2; ycur<=yint+2; ++ycur)
{
for(int xcur=xint-2; xcur<=xint+2; ++xcur)
{
double xpos = (double)xcur + value_noise_6(x,y,z,w,u,v,xcur,ycur,zcur,wcur,ucur,vcur,seed);
double ypos = (double)ycur + value_noise_6(x,y,z,w,u,v,xcur,ycur,zcur,wcur,ucur,vcur,seed+1);
double zpos = (double)zcur + value_noise_6(x,y,z,w,u,v,xcur,ycur,zcur,wcur,ucur,vcur,seed+2);
double wpos = (double)wcur + value_noise_6(x,y,z,w,u,v,xcur,ycur,zcur,wcur,ucur,vcur,seed+3);
double upos = (double)ucur + value_noise_6(x,y,z,w,u,v,xcur,ycur,zcur,wcur,ucur,vcur,seed+4);
double vpos = (double)vcur + value_noise_6(x,y,z,w,u,v,xcur,ycur,zcur,wcur,ucur,vcur,seed+5);
//double xdist=xpos-x;
//double ydist=ypos-y;
//double zdist=zpos-z;
//double wdist=wpos-w;
//double udist=upos-u;
//double vdist=vpos-v;
//double dist=(xdist*xdist + ydist*ydist + zdist*zdist + wdist*wdist + udist*udist + vdist*vdist);
double dist=distance(xpos,ypos,zpos,wpos,upos,vpos,x,y,z,w,u,v);
int xval=fast_floor(xpos);
int yval=fast_floor(ypos);
int zval=fast_floor(zpos);
int wval=fast_floor(wpos);
int uval=fast_floor(upos);
int vval=fast_floor(vpos);
double dsp=value_noise_6(x,y,z,w,u,v,xval,yval,zval,wval,uval,vval,seed+6);
add_dist(f,disp, dist, dsp);
}
}
}
}
}
}
}
const double F2=0.36602540378443864676372317075294;
const double G2=0.21132486540518711774542560974902;
const double F3=1.0/3.0;
const double G3=1.0/6.0;
double simplex_noise2D(double x, double y, unsigned int seed, interp_func interp)
{
double s = (x+y)*F2;
int i=fast_floor(x+s);
int j=fast_floor(y+s);
double t = (i+j)*G2;
double X0=i-t;
double Y0=j-t;
double x0=x-X0;
double y0=y-Y0;
int i1,j1;
if(x0>y0)
{
i1=1;
j1=0;
}
else
{
i1=0;
j1=1;
}
double x1=x0-(double)i1+G2;
double y1=y0-(double)j1+G2;
double x2=x0-1.0+2.0*G2;
double y2=y0-1.0+2.0*G2;
// Hash the triangle coordinates to index the gradient table
unsigned int h0=hash_coords_2(i,j,seed)%8;
unsigned int h1=hash_coords_2(i+i1,j+j1,seed)%8;
unsigned int h2=hash_coords_2(i+1,j+1,seed)%8;
// Now, index the tables
double *g0 = &gradient2D_lut[h0][0];
double *g1 = &gradient2D_lut[h1][0];
double *g2 = &gradient2D_lut[h2][0];
double n0,n1,n2;
// Calculate the contributions from the 3 corners
double t0=0.5-x0*x0-y0*y0;
if(t0<0) n0=0;
else
{
t0 *= t0;
n0 = t0 * t0 * array_dot2(g0,x0,y0);
}
double t1=0.5-x1*x1-y1*y1;
if(t1<0) n1=0;
else
{
t1*=t1;
n1=t1*t1*array_dot2(g1,x1,y1);
}
double t2=0.5-x2*x2-y2*y2;
if(t2<0) n2=0;
else
{
t2*=t2;
n2=t2*t2*array_dot2(g2,x2,y2);
}
// Add contributions together
return (40.0 * (n0+n1+n2));
}
double simplex_noise3D(double x, double y, double z, unsigned int seed, interp_func interp)
{
//static double F3 = 1.0/3.0;
//static double G3 = 1.0/6.0;
double n0,n1,n2,n3;
double s=(x+y+z)*F3;
int i=fast_floor(x+s);
int j=fast_floor(y+s);
int k=fast_floor(z+s);
double t=(i+j+k)*G3;
double X0=i-t;
double Y0=j-t;
double Z0=k-t;
double x0=x-X0;
double y0=y-Y0;
double z0=z-Z0;
int i1, j1, k1;
int i2, j2, k2;
if(x0>=y0)
{
if(y0>=z0)
{
i1=1;
j1=0;
k1=0;
i2=1;
j2=1;
k2=0;
}
else if(x0>=z0)
{
i1=1;
j1=0;
k1=0;
i2=1;
j2=0;
k2=1;
}
else
{
i1=0;
j1=0;
k1=1;
i2=1;
j2=0;
k2=1;
}
}
else
{
if(y0<z0)
{
i1=0;
j1=0;
k1=1;
i2=0;
j2=1;
k2=1;
}
else if(x0<z0)
{
i1=0;
j1=1;
k1=0;
i2=0;
j2=1;
k2=1;
}
else
{
i1=0;
j1=1;
k1=0;
i2=1;
j2=1;
k2=0;
}
}
double x1=x0-i1+G3;
double y1=y0-j1+G3;
double z1=z0-k1+G3;
double x2=x0-i2+2.0*G3;
double y2=y0-j2+2.0*G3;
double z2=z0-k2+2.0*G3;
double x3=x0-1.0+3.0*G3;
double y3=y0-1.0+3.0*G3;
double z3=z0-1.0+3.0*G3;
unsigned int h0,h1,h2,h3;
h0=hash_coords_3(i,j,k,seed)%24;
h1=hash_coords_3(i+i1,j+j1,k+k1,seed)%24;
h2=hash_coords_3(i+i2,j+j2,k+k2,seed)%24;
h3=hash_coords_3(i+1,j+1,k+1,seed)%24;
double *g0=&gradient3D_lut[h0][0];
double *g1=&gradient3D_lut[h1][0];
double *g2=&gradient3D_lut[h2][0];
double *g3=&gradient3D_lut[h3][0];
double t0=0.6-x0*x0-y0*y0-z0*z0;
if(t0<0.0) n0=0.0;
else
{
t0 *= t0;
n0 = t0*t0*array_dot3(g0,x0,y0,z0);
}
double t1=0.6-x1*x1-y1*y1-z1*z1;
if(t1<0.0) n1=0.0;
else
{
t1*=t1;
n1=t1*t1*array_dot3(g1,x1,y1,z1);
}
double t2=0.6-x2*x2-y2*y2-z2*z2;
if(t2<0) n2=0.0;
else
{
t2 *= t2;
n2 = t2*t2*array_dot3(g2,x2,y2,z2);
}
double t3=0.6-x3*x3-y3*y3-z3*z3;
if(t3<0) n3=0.0;
else
{
t3*=t3;
n3=t3*t3*array_dot3(g3,x3,y3,z3);
}
return (32.0*(n0+n1+n2+n3))*1.25086885 + 0.0003194984;
}
double simplex_noise4D(double x, double y, double z, double w, unsigned int seed, interp_func interp)
{
static int simplex[64][4] =
{
{0,1,2,3},{0,1,3,2},{0,0,0,0},{0,2,3,1},{0,0,0,0},{0,0,0,0},{0,0,0,0},{1,2,3,0},
{0,2,1,3},{0,0,0,0},{0,3,1,2},{0,3,2,1},{0,0,0,0},{0,0,0,0},{0,0,0,0},{1,3,2,0},
{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},
{1,2,0,3},{0,0,0,0},{1,3,0,2},{0,0,0,0},{0,0,0,0},{0,0,0,0},{2,3,0,1},{2,3,1,0},
{1,0,2,3},{1,0,3,2},{0,0,0,0},{0,0,0,0},{0,0,0,0},{2,0,3,1},{0,0,0,0},{2,1,3,0},
{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},
{2,0,1,3},{0,0,0,0},{0,0,0,0},{0,0,0,0},{3,0,1,2},{3,0,2,1},{0,0,0,0},{3,1,2,0},
{2,1,0,3},{0,0,0,0},{0,0,0,0},{0,0,0,0},{3,1,0,2},{0,0,0,0},{3,2,0,1},{3,2,1,0}
};
double F4 = (sqrt(5.0)-1.0)/4.0;
double G4 = (5.0-sqrt(5.0))/20.0;
double n0, n1, n2, n3, n4; // Noise contributions from the five corners
// Skew the (x,y,z,w) space to determine which cell of 24 simplices we're in
double s = (x + y + z + w) * F4; // Factor for 4D skewing
int i = fast_floor(x + s);
int j = fast_floor(y + s);
int k = fast_floor(z + s);
int l = fast_floor(w + s);
double t = (i + j + k + l) * G4; // Factor for 4D unskewing
double X0 = i - t; // Unskew the cell origin back to (x,y,z,w) space
double Y0 = j - t;
double Z0 = k - t;
double W0 = l - t;
double x0 = x - X0; // The x,y,z,w distances from the cell origin
double y0 = y - Y0;
double z0 = z - Z0;
double w0 = w - W0;
// For the 4D case, the simplex is a 4D shape I won't even try to describe.
// To find out which of the 24 possible simplices we're in, we need to
// determine the magnitude ordering of x0, y0, z0 and w0.
// The method below is a good way of finding the ordering of x,y,z,w and
// then find the correct traversal order for the simplex we’re in.
// First, six pair-wise comparisons are performed between each possible pair
// of the four coordinates, and the results are used to add up binary bits
// for an integer index.
int c1 = (x0 > y0) ? 32 : 0;
int c2 = (x0 > z0) ? 16 : 0;
int c3 = (y0 > z0) ? 8 : 0;
int c4 = (x0 > w0) ? 4 : 0;
int c5 = (y0 > w0) ? 2 : 0;
int c6 = (z0 > w0) ? 1 : 0;
int c = c1 + c2 + c3 + c4 + c5 + c6;
int i1, j1, k1, l1; // The integer offsets for the second simplex corner
int i2, j2, k2, l2; // The integer offsets for the third simplex corner
int i3, j3, k3, l3; // The integer offsets for the fourth simplex corner
// simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order.
// Many values of c will never occur, since e.g. x>y>z>w makes x<z, y<w and x<w
// impossible. Only the 24 indices which have non-zero entries make any sense.
// We use a thresholding to set the coordinates in turn from the largest magnitude.
// The number 3 in the "simplex" array is at the position of the largest coordinate.
i1 = simplex[c][0]>=3 ? 1 : 0;
j1 = simplex[c][1]>=3 ? 1 : 0;
k1 = simplex[c][2]>=3 ? 1 : 0;
l1 = simplex[c][3]>=3 ? 1 : 0;
// The number 2 in the "simplex" array is at the second largest coordinate.
i2 = simplex[c][0]>=2 ? 1 : 0;
j2 = simplex[c][1]>=2 ? 1 : 0;
k2 = simplex[c][2]>=2 ? 1 : 0;
l2 = simplex[c][3]>=2 ? 1 : 0;
// The number 1 in the "simplex" array is at the second smallest coordinate.
i3 = simplex[c][0]>=1 ? 1 : 0;
j3 = simplex[c][1]>=1 ? 1 : 0;
k3 = simplex[c][2]>=1 ? 1 : 0;
l3 = simplex[c][3]>=1 ? 1 : 0;
// The fifth corner has all coordinate offsets = 1, so no need to look that up.
double x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) coords
double y1 = y0 - j1 + G4;
double z1 = z0 - k1 + G4;
double w1 = w0 - l1 + G4;
double x2 = x0 - i2 + 2.0*G4; // Offsets for third corner in (x,y,z,w) coords
double y2 = y0 - j2 + 2.0*G4;
double z2 = z0 - k2 + 2.0*G4;
double w2 = w0 - l2 + 2.0*G4;
double x3 = x0 - i3 + 3.0*G4; // Offsets for fourth corner in (x,y,z,w) coords
double y3 = y0 - j3 + 3.0*G4;
double z3 = z0 - k3 + 3.0*G4;
double w3 = w0 - l3 + 3.0*G4;
double x4 = x0 - 1.0 + 4.0*G4; // Offsets for last corner in (x,y,z,w) coords
double y4 = y0 - 1.0 + 4.0*G4;
double z4 = z0 - 1.0 + 4.0*G4;
double w4 = w0 - 1.0 + 4.0*G4;
// Work out the hashed gradient indices of the five simplex corners
unsigned int h0,h1,h2,h3,h4;
h0=hash_coords_4(i,j,k,l,seed)%64;
h1=hash_coords_4(i+i1,j+j1,k+k1,l+l1,seed)%64;
h2=hash_coords_4(i+i2,j+j2,k+k2,l+l2,seed)%64;
h3=hash_coords_4(i+i3,j+j3,k+k3,l+l3,seed)%64;
h4=hash_coords_4(i+1,j+1,k+1,l+1,seed)%64;
double *g0=&gradient4D_lut[h0][0];
double *g1=&gradient4D_lut[h1][0];
double *g2=&gradient4D_lut[h2][0];
double *g3=&gradient4D_lut[h3][0];
double *g4=&gradient4D_lut[h4][0];
// Calculate the contribution from the five corners
double t0 = 0.6 - x0*x0 - y0*y0 - z0*z0 - w0*w0;
if(t0<0) n0 = 0.0;
else
{
t0 *= t0;
n0 = t0 * t0 * array_dot4(g0, x0, y0, z0, w0);
}
double t1 = 0.6 - x1*x1 - y1*y1 - z1*z1 - w1*w1;
if(t1<0) n1 = 0.0;
else
{
t1 *= t1;
n1 = t1 * t1 * array_dot4(g1, x1, y1, z1, w1);
}
double t2 = 0.6 - x2*x2 - y2*y2 - z2*z2 - w2*w2;
if(t2<0) n2 = 0.0;
else
{
t2 *= t2;
n2 = t2 * t2 * array_dot4(g2, x2, y2, z2, w2);
}
double t3 = 0.6 - x3*x3 - y3*y3 - z3*z3 - w3*w3;
if(t3<0) n3 = 0.0;
else
{
t3 *= t3;
n3 = t3 * t3 * array_dot4(g3, x3, y3, z3, w3);
}
double t4 = 0.6 - x4*x4 - y4*y4 - z4*z4 - w4*w4;
if(t4<0) n4 = 0.0;
else
{
t4 *= t4;
n4 = t4 * t4 * array_dot4(g4, x4, y4, z4, w4);
}
// Sum up and scale the result to cover the range [-1,1]
return 27.0 * (n0 + n1 + n2 + n3 + n4);
}
struct SVectorOrdering4
{
SVectorOrdering4(double v, int X, int Y, int Z, int W)
{
coord=v;
x=X;
y=Y;
z=Z;
w=W;
};
double coord;
int x,y,z,w;
};
bool svec4Compare(SVectorOrdering4 v1, SVectorOrdering4 v2)
{
if(v1.coord > v2.coord) return true;
return false;
}
struct SVectorOrdering
{
SVectorOrdering()
{
val=0;
axis=0;
}
SVectorOrdering(double v, int a)
{
val=v;
axis=a;
};
double val;
int axis;
};
bool vectorOrderingCompare(SVectorOrdering v1, SVectorOrdering v2)
{
if(v1.val > v2.val) return true;
return false;
}
void sortBy_4(double *l1, int *l2)
{
SVectorOrdering a[4];
for(int c=0; c<4; ++c)
{
a[c].val=l1[c];
a[c].axis=l2[c];
}
std::sort(&a[0],&a[4],vectorOrderingCompare);
for(int c=0; c<4; ++c) l2[c]=a[c].axis;
}
void sortBy_6(double *l1, int *l2)
{
SVectorOrdering a[6];
for(int c=0; c<6; ++c)
{
a[c].val=l1[c];
a[c].axis=l2[c];
}
std::sort(&a[0],&a[6],vectorOrderingCompare);
for(int c=0; c<6; ++c) l2[c]=a[c].axis;
}
double new_simplex_noise4D(double x, double y, double z, double w, unsigned int seed, interp_func interp)
{
// f = ((self.d + 1) ** .5 - 1) / self.d
double F4=(sqrt(5.0)-1.0)/4.0;
// g=self.f/(1+self.d*self.f)
double G4 = F4/(1.0+4.0*F4);
static double sideLength=2.0 / (4.0 * F4 + 1.0);
static double a=sqrt((sideLength*sideLength)-((sideLength/2.0)*(sideLength/2.0)));
static double cornerToFace=sqrt((a*a+(a/2.0)*(a/2.0)));
static double cornerToFaceSquared=cornerToFace*cornerToFace;
static double valueScaler=pow(3.0, -0.5);
// Rough estimated/expirmentally determined function
// for scaling output to be -1 to 1
valueScaler*=pow(3.0, -3.5)*100.0 + 13.0;
double loc[4]= {x,y,z,w};
double s=0;
for (int c=0; c<4; ++c) s+=loc[c];
s*=F4;
int skewLoc[4]= {fast_floor(x+s),fast_floor(y+s),fast_floor(z+s),fast_floor(w+s)};
int intLoc[4]= {fast_floor(x+s),fast_floor(y+s),fast_floor(z+s),fast_floor(w+s)};
double unskew=0.0;
for(int c=0; c<4; ++c) unskew+=skewLoc[c];
unskew*=G4;
double cellDist[4]= {loc[0]-(double)skewLoc[0]+unskew, loc[1]-(double)skewLoc[1]+unskew,
loc[2]-(double)skewLoc[2]+unskew, loc[3]-(double)skewLoc[3]+unskew
};
int distOrder[4]= {0,1,2,3};
sortBy_4(cellDist,distOrder);
int newDistOrder[5]= {-1,distOrder[0],distOrder[1],distOrder[2],distOrder[3]};
double n=0.0;
double skewOffset=0.0;
for(int c=0; c<5; ++c)
{
int i=newDistOrder[c];
if(i!=-1) intLoc[i]+=1;
double u[4];
for(int d=0; d<4; ++d)
{
u[d]=cellDist[d]-(intLoc[d]-skewLoc[d])+skewOffset;
}
double t=cornerToFaceSquared;
for(int d=0; d<4; ++d)
{
t-=u[d]*u[d];
}
if(t>0.0)
{
unsigned int h=hash_coords_4(intLoc[0],intLoc[1],intLoc[2],intLoc[3],seed)%64;
double *vec=&gradient4D_lut[h][0];
double gr=0.0;
for(int d=0; d<4; ++d)
{
gr+=vec[d]*u[d];
}
n+=gr*t*t*t*t;
}
skewOffset+=G4;
}
n*=valueScaler;
return n;
}
double simplex_noise6D(double x, double y, double z, double w, double u, double v, unsigned int seed, interp_func interp)
{
// Skew
//self.f = ((self.d + 1) ** .5 - 1) / self.d
static double F4 = (sqrt(7.0)-1.0)/6.0; //(sqrt(5.0)-1.0)/4.0;
// Unskew
// self.g=self.f/(1+self.d*self.f)
static double G4 = F4/(1.0+6.0*F4);
static double sideLength=sqrt(6.0)/ (6.0 * F4 +1.0);
static double a=sqrt((sideLength*sideLength)-((sideLength/2.0)*(sideLength/2.0)));
static double cornerFace=sqrt(a*a + (a/2.0)*(a/2.0));
static double cornerFaceSqrd=cornerFace*cornerFace;
//self.valueScaler=(self.d-1)**-.5
double valueScaler=pow(5.0, -0.5);
valueScaler*=pow(5.0, -3.5)*100+13;
double loc[6]= {x,y,z,w,u,v};
double s=0;
for (int c=0; c<6; ++c) s+=loc[c];
s*=F4;
int skewLoc[6]= {fast_floor(x+s),fast_floor(y+s),fast_floor(z+s),fast_floor(w+s),fast_floor(u+s),fast_floor(v+s)};
int intLoc[6]= {fast_floor(x+s),fast_floor(y+s),fast_floor(z+s),fast_floor(w+s),fast_floor(u+s),fast_floor(v+s)};
double unskew=0.0;
for(int c=0; c<6; ++c) unskew+=skewLoc[c];
unskew*=G4;
double cellDist[6]= {loc[0]-(double)skewLoc[0]+unskew, loc[1]-(double)skewLoc[1]+unskew,
loc[2]-(double)skewLoc[2]+unskew, loc[3]-(double)skewLoc[3]+unskew,
loc[4]-(double)skewLoc[4]+unskew, loc[5]-(double)skewLoc[5]+unskew
};
int distOrder[6]= {0,1,2,3,4,5};
sortBy_6(cellDist,distOrder);
int newDistOrder[7]= {-1,distOrder[0],distOrder[1],distOrder[2],distOrder[3],distOrder[4],distOrder[5]};
double n=0.0;
double skewOffset=0.0;
for(int c=0; c<7; ++c)
{
int i=newDistOrder[c];
if(i!=-1) intLoc[i]+=1;
double u[6];
for(int d=0; d<6; ++d)
{
u[d]=cellDist[d]-(intLoc[d]-skewLoc[d])+skewOffset;
}
double t=cornerFaceSqrd;
for(int d=0; d<6; ++d)
{
t-=u[d]*u[d];
}
if(t>0.0)
{
unsigned int h=hash_coords_6(intLoc[0],intLoc[1],intLoc[2],intLoc[3],intLoc[4],intLoc[5],seed)%192;
double *vec=&gradient6D_lut[h][0];
double gr=0.0;
for(int d=0; d<6; ++d)
{
gr+=vec[d]*u[d];
}
n+=gr*t*t*t*t*t;
}
skewOffset+=G4;
}
n*=valueScaler;
return n;
}
}
| [
"vertexnormal@gmail.com"
] | vertexnormal@gmail.com |
0b4b170259bcec6beffee5b9e1eb0a69e5a8ec7b | dc933e6c4af6db8e5938612935bb51ead04da9b3 | /android-x86/external/icu4c/i18n/decimfmt.cpp | 00ac7a45dd811653b18c9f08490ffef8cb1f5c31 | [
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unicode",
"LicenseRef-scancode-public-domain",
"ICU"
] | permissive | leotfrancisco/patch-hosting-for-android-x86-support | 213f0b28a7171570a77a3cec48a747087f700928 | e932645af3ff9515bd152b124bb55479758c2344 | refs/heads/master | 2021-01-10T08:40:36.731838 | 2009-05-28T04:29:43 | 2009-05-28T04:29:43 | 51,474,005 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 151,845 | cpp | /*
*******************************************************************************
* Copyright (C) 1997-2007, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* File DECIMFMT.CPP
*
* Modification History:
*
* Date Name Description
* 02/19/97 aliu Converted from java.
* 03/20/97 clhuang Implemented with new APIs.
* 03/31/97 aliu Moved isLONG_MIN to DigitList, and fixed it.
* 04/3/97 aliu Rewrote parsing and formatting completely, and
* cleaned up and debugged. Actually works now.
* Implemented NAN and INF handling, for both parsing
* and formatting. Extensive testing & debugging.
* 04/10/97 aliu Modified to compile on AIX.
* 04/16/97 aliu Rewrote to use DigitList, which has been resurrected.
* Changed DigitCount to int per code review.
* 07/09/97 helena Made ParsePosition into a class.
* 08/26/97 aliu Extensive changes to applyPattern; completely
* rewritten from the Java.
* 09/09/97 aliu Ported over support for exponential formats.
* 07/20/98 stephen JDK 1.2 sync up.
* Various instances of '0' replaced with 'NULL'
* Check for grouping size in subFormat()
* Brought subParse() in line with Java 1.2
* Added method appendAffix()
* 08/24/1998 srl Removed Mutex calls. This is not a thread safe class!
* 02/22/99 stephen Removed character literals for EBCDIC safety
* 06/24/99 helena Integrated Alan's NF enhancements and Java2 bug fixes
* 06/28/99 stephen Fixed bugs in toPattern().
* 06/29/99 stephen Fixed operator= to copy fFormatWidth, fPad,
* fPadPosition
********************************************************************************
*/
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "unicode/decimfmt.h"
#include "unicode/choicfmt.h"
#include "unicode/ucurr.h"
#include "unicode/ustring.h"
#include "unicode/dcfmtsym.h"
#include "unicode/ures.h"
#include "unicode/uchar.h"
#include "unicode/curramt.h"
#include "ucurrimp.h"
#include "../common/util.h"
#include "digitlst.h"
#include "cmemory.h"
#include "cstring.h"
#include "umutex.h"
#include "uassert.h"
#include "putilimp.h"
#include <stdio.h>
#define LOGI(...) printf("<I>"); printf(__VA_ARGS__); printf("</I>");
U_NAMESPACE_BEGIN
//#define FMT_DEBUG
#ifdef FMT_DEBUG
#include <stdio.h>
static void debugout(UnicodeString s) {
char buf[2000];
s.extract((int32_t) 0, s.length(), buf);
printf("%s", buf);
}
#define debug(x) printf("%s", x);
#else
#define debugout(x)
#define debug(x)
#endif
// *****************************************************************************
// class DecimalFormat
// *****************************************************************************
UOBJECT_DEFINE_RTTI_IMPLEMENTATION(DecimalFormat)
// Constants for characters used in programmatic (unlocalized) patterns.
#define kPatternZeroDigit ((UChar)0x0030) /*'0'*/
#define kPatternSignificantDigit ((UChar)0x0040) /*'@'*/
#define kPatternGroupingSeparator ((UChar)0x002C) /*','*/
#define kPatternDecimalSeparator ((UChar)0x002E) /*'.'*/
#define kPatternPerMill ((UChar)0x2030)
#define kPatternPercent ((UChar)0x0025) /*'%'*/
#define kPatternDigit ((UChar)0x0023) /*'#'*/
#define kPatternSeparator ((UChar)0x003B) /*';'*/
#define kPatternExponent ((UChar)0x0045) /*'E'*/
#define kPatternPlus ((UChar)0x002B) /*'+'*/
#define kPatternMinus ((UChar)0x002D) /*'-'*/
#define kPatternPadEscape ((UChar)0x002A) /*'*'*/
#define kQuote ((UChar)0x0027) /*'\''*/
/**
* The CURRENCY_SIGN is the standard Unicode symbol for currency. It
* is used in patterns and substitued with either the currency symbol,
* or if it is doubled, with the international currency symbol. If the
* CURRENCY_SIGN is seen in a pattern, then the decimal separator is
* replaced with the monetary decimal separator.
*/
#define kCurrencySign ((UChar)0x00A4)
#define kDefaultPad ((UChar)0x0020) /* */
const int32_t DecimalFormat::kDoubleIntegerDigits = 309;
const int32_t DecimalFormat::kDoubleFractionDigits = 340;
const int32_t DecimalFormat::kMaxScientificIntegerDigits = 8;
/**
* These are the tags we expect to see in normal resource bundle files associated
* with a locale.
*/
const char DecimalFormat::fgNumberPatterns[]="NumberPatterns";
inline int32_t _min(int32_t a, int32_t b) { return (a<b) ? a : b; }
inline int32_t _max(int32_t a, int32_t b) { return (a<b) ? b : a; }
//------------------------------------------------------------------------------
// Constructs a DecimalFormat instance in the default locale.
DecimalFormat::DecimalFormat(UErrorCode& status)
: NumberFormat(),
fPosPrefixPattern(0),
fPosSuffixPattern(0),
fNegPrefixPattern(0),
fNegSuffixPattern(0),
fCurrencyChoice(0),
fMultiplier(0),
fGroupingSize(0),
fGroupingSize2(0),
fSymbols(0),
fUseSignificantDigits(FALSE),
fMinSignificantDigits(1),
fMaxSignificantDigits(6),
fMinExponentDigits(0),
fRoundingIncrement(0),
fPad(0),
fFormatWidth(0)
{
UParseError parseError;
construct(status, parseError);
}
//------------------------------------------------------------------------------
// Constructs a DecimalFormat instance with the specified number format
// pattern in the default locale.
DecimalFormat::DecimalFormat(const UnicodeString& pattern,
UErrorCode& status)
: NumberFormat(),
fPosPrefixPattern(0),
fPosSuffixPattern(0),
fNegPrefixPattern(0),
fNegSuffixPattern(0),
fCurrencyChoice(0),
fMultiplier(0),
fGroupingSize(0),
fGroupingSize2(0),
fSymbols(0),
fUseSignificantDigits(FALSE),
fMinSignificantDigits(1),
fMaxSignificantDigits(6),
fMinExponentDigits(0),
fRoundingIncrement(0),
fPad(0),
fFormatWidth(0)
{
UParseError parseError;
construct(status, parseError, &pattern);
}
//------------------------------------------------------------------------------
// Constructs a DecimalFormat instance with the specified number format
// pattern and the number format symbols in the default locale. The
// created instance owns the symbols.
DecimalFormat::DecimalFormat(const UnicodeString& pattern,
DecimalFormatSymbols* symbolsToAdopt,
UErrorCode& status)
: NumberFormat(),
fPosPrefixPattern(0),
fPosSuffixPattern(0),
fNegPrefixPattern(0),
fNegSuffixPattern(0),
fCurrencyChoice(0),
fMultiplier(0),
fGroupingSize(0),
fGroupingSize2(0),
fSymbols(0),
fUseSignificantDigits(FALSE),
fMinSignificantDigits(1),
fMaxSignificantDigits(6),
fMinExponentDigits(0),
fRoundingIncrement(0),
fPad(0),
fFormatWidth(0)
{
UParseError parseError;
if (symbolsToAdopt == NULL)
status = U_ILLEGAL_ARGUMENT_ERROR;
construct(status, parseError, &pattern, symbolsToAdopt);
}
DecimalFormat::DecimalFormat( const UnicodeString& pattern,
DecimalFormatSymbols* symbolsToAdopt,
UParseError& parseErr,
UErrorCode& status)
: NumberFormat(),
fPosPrefixPattern(0),
fPosSuffixPattern(0),
fNegPrefixPattern(0),
fNegSuffixPattern(0),
fCurrencyChoice(0),
fMultiplier(0),
fGroupingSize(0),
fGroupingSize2(0),
fSymbols(0),
fUseSignificantDigits(FALSE),
fMinSignificantDigits(1),
fMaxSignificantDigits(6),
fMinExponentDigits(0),
fRoundingIncrement(0),
fPad(0),
fFormatWidth(0)
{
if (symbolsToAdopt == NULL)
status = U_ILLEGAL_ARGUMENT_ERROR;
construct(status,parseErr, &pattern, symbolsToAdopt);
}
//------------------------------------------------------------------------------
// Constructs a DecimalFormat instance with the specified number format
// pattern and the number format symbols in the default locale. The
// created instance owns the clone of the symbols.
DecimalFormat::DecimalFormat(const UnicodeString& pattern,
const DecimalFormatSymbols& symbols,
UErrorCode& status)
: NumberFormat(),
fPosPrefixPattern(0),
fPosSuffixPattern(0),
fNegPrefixPattern(0),
fNegSuffixPattern(0),
fCurrencyChoice(0),
fMultiplier(0),
fGroupingSize(0),
fGroupingSize2(0),
fSymbols(0),
fUseSignificantDigits(FALSE),
fMinSignificantDigits(1),
fMaxSignificantDigits(6),
fMinExponentDigits(0),
fRoundingIncrement(0),
fPad(0),
fFormatWidth(0)
{
UParseError parseError;
construct(status, parseError, &pattern, new DecimalFormatSymbols(symbols));
}
//------------------------------------------------------------------------------
// Constructs a DecimalFormat instance with the specified number format
// pattern and the number format symbols in the desired locale. The
// created instance owns the symbols.
void
DecimalFormat::construct(UErrorCode& status,
UParseError& parseErr,
const UnicodeString* pattern,
DecimalFormatSymbols* symbolsToAdopt)
{
fSymbols = symbolsToAdopt; // Do this BEFORE aborting on status failure!!!
// fDigitList = new DigitList(); // Do this BEFORE aborting on status failure!!!
fRoundingIncrement = NULL;
fRoundingDouble = 0.0;
fRoundingMode = kRoundHalfEven;
fPad = kPatternPadEscape;
fPadPosition = kPadBeforePrefix;
if (U_FAILURE(status))
return;
fPosPrefixPattern = fPosSuffixPattern = NULL;
fNegPrefixPattern = fNegSuffixPattern = NULL;
fMultiplier = 1;
fGroupingSize = 3;
fGroupingSize2 = 0;
fDecimalSeparatorAlwaysShown = FALSE;
fIsCurrencyFormat = FALSE;
fUseExponentialNotation = FALSE;
fMinExponentDigits = 0;
if (fSymbols == NULL)
{
fSymbols = new DecimalFormatSymbols(Locale::getDefault(), status);
/* test for NULL */
if (fSymbols == 0) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
}
UnicodeString str;
// Uses the default locale's number format pattern if there isn't
// one specified.
if (pattern == NULL)
{
int32_t len = 0;
UResourceBundle *resource = ures_open(NULL, Locale::getDefault().getName(), &status);
resource = ures_getByKey(resource, fgNumberPatterns, resource, &status);
const UChar *resStr = ures_getStringByIndex(resource, (int32_t)0, &len, &status);
str.setTo(TRUE, resStr, len);
pattern = &str;
ures_close(resource);
}
if (U_FAILURE(status))
{
return;
}
if (pattern->indexOf((UChar)kCurrencySign) >= 0) {
// If it looks like we are going to use a currency pattern
// then do the time consuming lookup.
setCurrencyForSymbols();
} else {
setCurrency(NULL, status);
}
applyPattern(*pattern, FALSE /*not localized*/,parseErr, status);
// If it was a currency format, apply the appropriate rounding by
// resetting the currency. NOTE: this copies fCurrency on top of itself.
if (fIsCurrencyFormat) {
setCurrency(getCurrency(), status);
}
}
//------------------------------------------------------------------------------
DecimalFormat::~DecimalFormat()
{
// delete fDigitList;
delete fPosPrefixPattern;
delete fPosSuffixPattern;
delete fNegPrefixPattern;
delete fNegSuffixPattern;
delete fCurrencyChoice;
delete fSymbols;
delete fRoundingIncrement;
}
//------------------------------------------------------------------------------
// copy constructor
DecimalFormat::DecimalFormat(const DecimalFormat &source)
: NumberFormat(source),
// fDigitList(NULL),
fPosPrefixPattern(NULL),
fPosSuffixPattern(NULL),
fNegPrefixPattern(NULL),
fNegSuffixPattern(NULL),
fCurrencyChoice(NULL),
fSymbols(NULL),
fRoundingIncrement(NULL)
{
*this = source;
}
//------------------------------------------------------------------------------
// assignment operator
// Note that fDigitList is not considered a significant part of the
// DecimalFormat because it's used as a buffer to process the numbers.
static void _copy_us_ptr(UnicodeString** pdest, const UnicodeString* source) {
if (source == NULL) {
delete *pdest;
*pdest = NULL;
} else if (*pdest == NULL) {
*pdest = new UnicodeString(*source);
} else {
**pdest = *source;
}
}
DecimalFormat&
DecimalFormat::operator=(const DecimalFormat& rhs)
{
if(this != &rhs) {
NumberFormat::operator=(rhs);
fPositivePrefix = rhs.fPositivePrefix;
fPositiveSuffix = rhs.fPositiveSuffix;
fNegativePrefix = rhs.fNegativePrefix;
fNegativeSuffix = rhs.fNegativeSuffix;
_copy_us_ptr(&fPosPrefixPattern, rhs.fPosPrefixPattern);
_copy_us_ptr(&fPosSuffixPattern, rhs.fPosSuffixPattern);
_copy_us_ptr(&fNegPrefixPattern, rhs.fNegPrefixPattern);
_copy_us_ptr(&fNegSuffixPattern, rhs.fNegSuffixPattern);
if (rhs.fCurrencyChoice == 0) {
delete fCurrencyChoice;
fCurrencyChoice = 0;
} else {
fCurrencyChoice = (ChoiceFormat*) rhs.fCurrencyChoice->clone();
}
if(rhs.fRoundingIncrement == NULL) {
delete fRoundingIncrement;
fRoundingIncrement = NULL;
}
else if(fRoundingIncrement == NULL) {
fRoundingIncrement = new DigitList(*rhs.fRoundingIncrement);
}
else {
*fRoundingIncrement = *rhs.fRoundingIncrement;
}
fRoundingDouble = rhs.fRoundingDouble;
fRoundingMode = rhs.fRoundingMode;
fMultiplier = rhs.fMultiplier;
fGroupingSize = rhs.fGroupingSize;
fGroupingSize2 = rhs.fGroupingSize2;
fDecimalSeparatorAlwaysShown = rhs.fDecimalSeparatorAlwaysShown;
if(fSymbols == NULL) {
fSymbols = new DecimalFormatSymbols(*rhs.fSymbols);
} else {
*fSymbols = *rhs.fSymbols;
}
fUseExponentialNotation = rhs.fUseExponentialNotation;
fExponentSignAlwaysShown = rhs.fExponentSignAlwaysShown;
/*Bertrand A. D. Update 98.03.17*/
fIsCurrencyFormat = rhs.fIsCurrencyFormat;
/*end of Update*/
fMinExponentDigits = rhs.fMinExponentDigits;
// if (fDigitList == NULL)
// fDigitList = new DigitList();
/* sfb 990629 */
fFormatWidth = rhs.fFormatWidth;
fPad = rhs.fPad;
fPadPosition = rhs.fPadPosition;
/* end sfb */
fMinSignificantDigits = rhs.fMinSignificantDigits;
fMaxSignificantDigits = rhs.fMaxSignificantDigits;
fUseSignificantDigits = rhs.fUseSignificantDigits;
}
return *this;
}
//------------------------------------------------------------------------------
UBool
DecimalFormat::operator==(const Format& that) const
{
if (this == &that)
return TRUE;
// NumberFormat::operator== guarantees this cast is safe
const DecimalFormat* other = (DecimalFormat*)&that;
#ifdef FMT_DEBUG
// This code makes it easy to determine why two format objects that should
// be equal aren't.
UBool first = TRUE;
if (!NumberFormat::operator==(that)) {
if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
debug("NumberFormat::!=");
}
if (!((fPosPrefixPattern == other->fPosPrefixPattern && // both null
fPositivePrefix == other->fPositivePrefix)
|| (fPosPrefixPattern != 0 && other->fPosPrefixPattern != 0 &&
*fPosPrefixPattern == *other->fPosPrefixPattern))) {
if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
debug("Pos Prefix !=");
}
if (!((fPosSuffixPattern == other->fPosSuffixPattern && // both null
fPositiveSuffix == other->fPositiveSuffix)
|| (fPosSuffixPattern != 0 && other->fPosSuffixPattern != 0 &&
*fPosSuffixPattern == *other->fPosSuffixPattern))) {
if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
debug("Pos Suffix !=");
}
if (!((fNegPrefixPattern == other->fNegPrefixPattern && // both null
fNegativePrefix == other->fNegativePrefix)
|| (fNegPrefixPattern != 0 && other->fNegPrefixPattern != 0 &&
*fNegPrefixPattern == *other->fNegPrefixPattern))) {
if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
debug("Neg Prefix ");
if (fNegPrefixPattern == NULL) {
debug("NULL(");
debugout(fNegativePrefix);
debug(")");
} else {
debugout(*fNegPrefixPattern);
}
debug(" != ");
if (other->fNegPrefixPattern == NULL) {
debug("NULL(");
debugout(other->fNegativePrefix);
debug(")");
} else {
debugout(*other->fNegPrefixPattern);
}
}
if (!((fNegSuffixPattern == other->fNegSuffixPattern && // both null
fNegativeSuffix == other->fNegativeSuffix)
|| (fNegSuffixPattern != 0 && other->fNegSuffixPattern != 0 &&
*fNegSuffixPattern == *other->fNegSuffixPattern))) {
if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
debug("Neg Suffix ");
if (fNegSuffixPattern == NULL) {
debug("NULL(");
debugout(fNegativeSuffix);
debug(")");
} else {
debugout(*fNegSuffixPattern);
}
debug(" != ");
if (other->fNegSuffixPattern == NULL) {
debug("NULL(");
debugout(other->fNegativeSuffix);
debug(")");
} else {
debugout(*other->fNegSuffixPattern);
}
}
if (!((fRoundingIncrement == other->fRoundingIncrement) // both null
|| (fRoundingIncrement != NULL &&
other->fRoundingIncrement != NULL &&
*fRoundingIncrement == *other->fRoundingIncrement))) {
if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
debug("Rounding Increment !=");
}
if (fMultiplier != other->fMultiplier) {
if (first) { printf("[ "); first = FALSE; }
printf("Multiplier %ld != %ld", fMultiplier, other->fMultiplier);
}
if (fGroupingSize != other->fGroupingSize) {
if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
printf("Grouping Size %ld != %ld", fGroupingSize, other->fGroupingSize);
}
if (fGroupingSize2 != other->fGroupingSize2) {
if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
printf("Secondary Grouping Size %ld != %ld", fGroupingSize2, other->fGroupingSize2);
}
if (fDecimalSeparatorAlwaysShown != other->fDecimalSeparatorAlwaysShown) {
if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
printf("Dec Sep Always %d != %d", fDecimalSeparatorAlwaysShown, other->fDecimalSeparatorAlwaysShown);
}
if (fUseExponentialNotation != other->fUseExponentialNotation) {
if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
debug("Use Exp !=");
}
if (!(!fUseExponentialNotation ||
fMinExponentDigits != other->fMinExponentDigits)) {
if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
debug("Exp Digits !=");
}
if (*fSymbols != *(other->fSymbols)) {
if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
debug("Symbols !=");
}
// TODO Add debug stuff for significant digits here
if (!first) { printf(" ]"); }
#endif
return (NumberFormat::operator==(that) &&
((fPosPrefixPattern == other->fPosPrefixPattern && // both null
fPositivePrefix == other->fPositivePrefix)
|| (fPosPrefixPattern != 0 && other->fPosPrefixPattern != 0 &&
*fPosPrefixPattern == *other->fPosPrefixPattern)) &&
((fPosSuffixPattern == other->fPosSuffixPattern && // both null
fPositiveSuffix == other->fPositiveSuffix)
|| (fPosSuffixPattern != 0 && other->fPosSuffixPattern != 0 &&
*fPosSuffixPattern == *other->fPosSuffixPattern)) &&
((fNegPrefixPattern == other->fNegPrefixPattern && // both null
fNegativePrefix == other->fNegativePrefix)
|| (fNegPrefixPattern != 0 && other->fNegPrefixPattern != 0 &&
*fNegPrefixPattern == *other->fNegPrefixPattern)) &&
((fNegSuffixPattern == other->fNegSuffixPattern && // both null
fNegativeSuffix == other->fNegativeSuffix)
|| (fNegSuffixPattern != 0 && other->fNegSuffixPattern != 0 &&
*fNegSuffixPattern == *other->fNegSuffixPattern)) &&
((fRoundingIncrement == other->fRoundingIncrement) // both null
|| (fRoundingIncrement != NULL &&
other->fRoundingIncrement != NULL &&
*fRoundingIncrement == *other->fRoundingIncrement)) &&
fMultiplier == other->fMultiplier &&
fGroupingSize == other->fGroupingSize &&
fGroupingSize2 == other->fGroupingSize2 &&
fDecimalSeparatorAlwaysShown == other->fDecimalSeparatorAlwaysShown &&
fUseExponentialNotation == other->fUseExponentialNotation &&
(!fUseExponentialNotation ||
fMinExponentDigits == other->fMinExponentDigits) &&
*fSymbols == *(other->fSymbols) &&
fUseSignificantDigits == other->fUseSignificantDigits &&
(!fUseSignificantDigits ||
(fMinSignificantDigits == other->fMinSignificantDigits &&
fMaxSignificantDigits == other->fMaxSignificantDigits)));
}
//------------------------------------------------------------------------------
Format*
DecimalFormat::clone() const
{
return new DecimalFormat(*this);
}
//------------------------------------------------------------------------------
UnicodeString&
DecimalFormat::format(int32_t number,
UnicodeString& appendTo,
FieldPosition& fieldPosition) const
{
return format((int64_t)number, appendTo, fieldPosition, NULL);
}
UnicodeString&
DecimalFormat::format(int32_t number,
UnicodeString& appendTo,
FieldPosition& fieldPosition,
AttrBuffer attrBuffer) const
{
return format((int64_t)number, appendTo, fieldPosition, attrBuffer);
}
//------------------------------------------------------------------------------
UnicodeString&
DecimalFormat::format(int64_t number,
UnicodeString& appendTo,
FieldPosition& fieldPosition) const
{
return format(number, appendTo, fieldPosition, NULL);
}
UnicodeString&
DecimalFormat::format(int64_t number,
UnicodeString& appendTo,
FieldPosition& fieldPosition,
AttrBuffer attrBuffer) const
{
DigitList digits;
// Clears field positions.
fieldPosition.setBeginIndex(0);
fieldPosition.setEndIndex(0);
// If we are to do rounding, we need to move into the BigDecimal
// domain in order to do divide/multiply correctly.
// ||
// In general, long values always represent real finite numbers, so
// we don't have to check for +/- Infinity or NaN. However, there
// is one case we have to be careful of: The multiplier can push
// a number near MIN_VALUE or MAX_VALUE outside the legal range. We
// check for this before multiplying, and if it happens we use doubles
// instead, trading off accuracy for range.
if (fRoundingIncrement != NULL
|| (fMultiplier != 0 && (number > (U_INT64_MAX / fMultiplier)
|| number < (U_INT64_MIN / fMultiplier))))
{
digits.set(((double)number) * fMultiplier,
precision(FALSE),
!fUseExponentialNotation && !areSignificantDigitsUsed());
}
else
{
digits.set(number * fMultiplier, precision(TRUE));
}
return subformat(appendTo, fieldPosition, attrBuffer, digits, TRUE);
}
//------------------------------------------------------------------------------
UnicodeString&
DecimalFormat::format( double number,
UnicodeString& appendTo,
FieldPosition& fieldPosition) const
{
return format(number, appendTo, fieldPosition, NULL);
}
UnicodeString&
DecimalFormat::format( double number,
UnicodeString& appendTo,
FieldPosition& fieldPosition,
AttrBuffer attrBuffer) const
{
// Clears field positions.
fieldPosition.setBeginIndex(0);
fieldPosition.setEndIndex(0);
// Special case for NaN, sets the begin and end index to be the
// the string length of localized name of NaN.
if (uprv_isNaN(number))
{
int begin = appendTo.length();
if (fieldPosition.getField() == NumberFormat::kIntegerField)
fieldPosition.setBeginIndex(begin);
appendTo += getConstSymbol(DecimalFormatSymbols::kNaNSymbol);
int end = appendTo.length();
if (fieldPosition.getField() == NumberFormat::kIntegerField)
fieldPosition.setEndIndex(end);
addAttribute(attrBuffer, "integer", begin, end);
addPadding(appendTo, fieldPosition, 0, 0);
return appendTo;
}
/* Detecting whether a double is negative is easy with the exception of
* the value -0.0. This is a double which has a zero mantissa (and
* exponent), but a negative sign bit. It is semantically distinct from
* a zero with a positive sign bit, and this distinction is important
* to certain kinds of computations. However, it's a little tricky to
* detect, since (-0.0 == 0.0) and !(-0.0 < 0.0). How then, you may
* ask, does it behave distinctly from +0.0? Well, 1/(-0.0) ==
* -Infinity. Proper detection of -0.0 is needed to deal with the
* issues raised by bugs 4106658, 4106667, and 4147706. Liu 7/6/98.
*/
UBool isNegative = uprv_isNegative(number);
// Do this BEFORE checking to see if value is infinite! Sets the
// begin and end index to be length of the string composed of
// localized name of Infinite and the positive/negative localized
// signs.
number *= fMultiplier;
// Apply rounding after multiplier
if (fRoundingIncrement != NULL) {
if (isNegative) // For rounding in the correct direction
number = -number;
number = fRoundingDouble
* round(number / fRoundingDouble, fRoundingMode, isNegative);
if (isNegative)
number = -number;
}
// Special case for INFINITE,
if (uprv_isInfinite(number))
{
int32_t prefixLen = appendAffix(appendTo, number, attrBuffer, isNegative, TRUE);
int begin = appendTo.length();
if (fieldPosition.getField() == NumberFormat::kIntegerField)
fieldPosition.setBeginIndex(begin);
appendTo += getConstSymbol(DecimalFormatSymbols::kInfinitySymbol);
int end = appendTo.length();
if (fieldPosition.getField() == NumberFormat::kIntegerField)
fieldPosition.setEndIndex(end);
addAttribute(attrBuffer, "integer", begin, end);
int32_t suffixLen = appendAffix(appendTo, number, attrBuffer, isNegative, FALSE);
addPadding(appendTo, fieldPosition, prefixLen, suffixLen);
return appendTo;
}
DigitList digits;
// This detects negativity too.
if (fRoundingIncrement == NULL) {
// If we did not round in binary space, round in decimal space
digits.fRoundingMode = fRoundingMode;
}
digits.set(number, precision(FALSE),
!fUseExponentialNotation && !areSignificantDigitsUsed());
return subformat(appendTo, fieldPosition, attrBuffer, digits, FALSE);
}
/**
* Round a double value to the nearest integer according to the
* given mode.
* @param a the absolute value of the number to be rounded
* @param mode a BigDecimal rounding mode
* @param isNegative true if the number to be rounded is negative
* @return the absolute value of the rounded result
*/
double DecimalFormat::round(double a, ERoundingMode mode, UBool isNegative) {
switch (mode) {
case kRoundCeiling:
return isNegative ? uprv_floor(a) : uprv_ceil(a);
case kRoundFloor:
return isNegative ? uprv_ceil(a) : uprv_floor(a);
case kRoundDown:
return uprv_floor(a);
case kRoundUp:
return uprv_ceil(a);
case kRoundHalfEven:
{
double f = uprv_floor(a);
if ((a - f) != 0.5) {
return uprv_floor(a + 0.5);
}
double g = f / 2.0;
return (g == uprv_floor(g)) ? f : (f + 1.0);
}
case kRoundHalfDown:
return ((a - uprv_floor(a)) <= 0.5) ? uprv_floor(a) : uprv_ceil(a);
case kRoundHalfUp:
return ((a - uprv_floor(a)) < 0.5) ? uprv_floor(a) : uprv_ceil(a);
}
return 1.0;
}
UnicodeString&
DecimalFormat::format( const Formattable& obj,
UnicodeString& appendTo,
FieldPosition& fieldPosition,
UErrorCode& status) const
{
return NumberFormat::format(obj, appendTo, fieldPosition, status);
}
/**
* Return true if a grouping separator belongs at the given
* position, based on whether grouping is in use and the values of
* the primary and secondary grouping interval.
* @param pos the number of integer digits to the right of
* the current position. Zero indicates the position after the
* rightmost integer digit.
* @return true if a grouping character belongs at the current
* position.
*/
UBool DecimalFormat::isGroupingPosition(int32_t pos) const {
UBool result = FALSE;
if (isGroupingUsed() && (pos > 0) && (fGroupingSize > 0)) {
if ((fGroupingSize2 > 0) && (pos > fGroupingSize)) {
result = ((pos - fGroupingSize) % fGroupingSize2) == 0;
} else {
result = pos % fGroupingSize == 0;
}
}
return result;
}
//------------------------------------------------------------------------------
/**
* Complete the formatting of a finite number. On entry, the fDigitList must
* be filled in with the correct digits.
*/
UnicodeString&
DecimalFormat::subformat(UnicodeString& appendTo,
FieldPosition& fieldPosition,
DigitList& digits,
UBool isInteger) const
{
return subformat(appendTo, fieldPosition, NULL, digits, isInteger);
}
/**
* Complete the formatting of a finite number. On entry, the fDigitList must
* be filled in with the correct digits.
*/
UnicodeString&
DecimalFormat::subformat(UnicodeString& appendTo,
FieldPosition& fieldPosition,
AttrBuffer attrBuffer,
DigitList& digits,
UBool isInteger) const
{
// Gets the localized zero Unicode character.
UChar32 zero = getConstSymbol(DecimalFormatSymbols::kZeroDigitSymbol).char32At(0);
int32_t zeroDelta = zero - '0'; // '0' is the DigitList representation of zero
const UnicodeString *grouping ;
if(fIsCurrencyFormat) {
grouping = &getConstSymbol(DecimalFormatSymbols::kMonetaryGroupingSeparatorSymbol);
}else{
grouping = &getConstSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol);
}
const UnicodeString *decimal;
if(fIsCurrencyFormat) {
decimal = &getConstSymbol(DecimalFormatSymbols::kMonetarySeparatorSymbol);
} else {
decimal = &getConstSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol);
}
UBool useSigDig = areSignificantDigitsUsed();
int32_t maxIntDig = getMaximumIntegerDigits();
int32_t minIntDig = getMinimumIntegerDigits();
/* Per bug 4147706, DecimalFormat must respect the sign of numbers which
* format as zero. This allows sensible computations and preserves
* relations such as signum(1/x) = signum(x), where x is +Infinity or
* -Infinity. Prior to this fix, we always formatted zero values as if
* they were positive. Liu 7/6/98.
*/
if (digits.isZero())
{
digits.fDecimalAt = digits.fCount = 0; // Normalize
}
// Appends the prefix.
double doubleValue = digits.getDouble();
int32_t prefixLen = appendAffix(appendTo, doubleValue, attrBuffer, !digits.fIsPositive, TRUE);
if (fUseExponentialNotation)
{
// Record field information for caller.
if (fieldPosition.getField() == NumberFormat::kIntegerField)
{
fieldPosition.setBeginIndex(appendTo.length());
fieldPosition.setEndIndex(-1);
}
else if (fieldPosition.getField() == NumberFormat::kFractionField)
{
fieldPosition.setBeginIndex(-1);
}
int currentLength = appendTo.length();
int intBegin = currentLength;
int intEnd = -1;
int fracBegin = -1;
int32_t minFracDig = 0;
if (useSigDig) {
maxIntDig = minIntDig = 1;
minFracDig = getMinimumSignificantDigits() - 1;
} else {
minFracDig = getMinimumFractionDigits();
if (maxIntDig > kMaxScientificIntegerDigits) {
maxIntDig = 1;
if (maxIntDig < minIntDig) {
maxIntDig = minIntDig;
}
}
if (maxIntDig > minIntDig) {
minIntDig = 1;
}
}
// Minimum integer digits are handled in exponential format by
// adjusting the exponent. For example, 0.01234 with 3 minimum
// integer digits is "123.4E-4".
// Maximum integer digits are interpreted as indicating the
// repeating range. This is useful for engineering notation, in
// which the exponent is restricted to a multiple of 3. For
// example, 0.01234 with 3 maximum integer digits is "12.34e-3".
// If maximum integer digits are defined and are larger than
// minimum integer digits, then minimum integer digits are
// ignored.
int32_t exponent = digits.fDecimalAt;
if (maxIntDig > 1 && maxIntDig != minIntDig) {
// A exponent increment is defined; adjust to it.
exponent = (exponent > 0) ? (exponent - 1) / maxIntDig
: (exponent / maxIntDig) - 1;
exponent *= maxIntDig;
} else {
// No exponent increment is defined; use minimum integer digits.
// If none is specified, as in "#E0", generate 1 integer digit.
exponent -= (minIntDig > 0 || minFracDig > 0)
? minIntDig : 1;
}
// We now output a minimum number of digits, and more if there
// are more digits, up to the maximum number of digits. We
// place the decimal point after the "integer" digits, which
// are the first (decimalAt - exponent) digits.
int32_t minimumDigits = minIntDig + minFracDig;
// The number of integer digits is handled specially if the number
// is zero, since then there may be no digits.
int32_t integerDigits = digits.isZero() ? minIntDig :
digits.fDecimalAt - exponent;
int32_t totalDigits = digits.fCount;
if (minimumDigits > totalDigits)
totalDigits = minimumDigits;
if (integerDigits > totalDigits)
totalDigits = integerDigits;
// totalDigits records total number of digits needs to be processed
int32_t i;
for (i=0; i<totalDigits; ++i)
{
if (i == integerDigits)
{
intEnd = appendTo.length();
addAttribute(attrBuffer, "integer", intBegin, intEnd);
// Record field information for caller.
if (fieldPosition.getField() == NumberFormat::kIntegerField)
fieldPosition.setEndIndex(intEnd);
appendTo += *decimal;
fracBegin = appendTo.length();
addAttribute(attrBuffer, "decimal_separator", fracBegin - 1, fracBegin);
// Record field information for caller.
if (fieldPosition.getField() == NumberFormat::kFractionField)
fieldPosition.setBeginIndex(fracBegin);
}
// Restores the digit character or pads the buffer with zeros.
UChar32 c = (UChar32)((i < digits.fCount) ?
(digits.fDigits[i] + zeroDelta) :
zero);
appendTo += c;
}
currentLength = appendTo.length();
// Record field information
if (fieldPosition.getField() == NumberFormat::kIntegerField)
{
if (fieldPosition.getEndIndex() < 0)
fieldPosition.setEndIndex(currentLength);
}
else if (fieldPosition.getField() == NumberFormat::kFractionField)
{
if (fieldPosition.getBeginIndex() < 0)
fieldPosition.setBeginIndex(appendTo.length());
fieldPosition.setEndIndex(currentLength);
}
if (intEnd < 0) {
addAttribute(attrBuffer, "integer", intBegin, currentLength);
}
if (fracBegin > 0) {
addAttribute(attrBuffer, "fraction", fracBegin, currentLength);
}
// The exponent is output using the pattern-specified minimum
// exponent digits. There is no maximum limit to the exponent
// digits, since truncating the exponent would appendTo in an
// unacceptable inaccuracy.
appendTo += getConstSymbol(DecimalFormatSymbols::kExponentialSymbol);
addAttribute(attrBuffer, "exponent_symbol",currentLength, appendTo.length());
currentLength = appendTo.length();
// For zero values, we force the exponent to zero. We
// must do this here, and not earlier, because the value
// is used to determine integer digit count above.
if (digits.isZero())
exponent = 0;
if (exponent < 0) {
appendTo += getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol);
addAttribute(attrBuffer, "exponent_sign",currentLength,appendTo.length());
} else if (fExponentSignAlwaysShown) {
appendTo += getConstSymbol(DecimalFormatSymbols::kPlusSignSymbol);
addAttribute(attrBuffer, "exponent_sign",currentLength,appendTo.length());
}
currentLength = appendTo.length();
DigitList expDigits;
expDigits.set(exponent);
{
int expDig = fMinExponentDigits;
if (fUseExponentialNotation && expDig < 1) {
expDig = 1;
}
for (i=expDigits.fDecimalAt; i<expDig; ++i)
appendTo += (zero);
}
for (i=0; i<expDigits.fDecimalAt; ++i)
{
UChar32 c = (UChar32)((i < expDigits.fCount) ?
(expDigits.fDigits[i] + zeroDelta) : zero);
appendTo += c;
}
addAttribute(attrBuffer, "exponent", currentLength, appendTo.length());
}
else // Not using exponential notation
{
int currentLength = appendTo.length();
int intBegin = currentLength;
// Record field information for caller.
if (fieldPosition.getField() == NumberFormat::kIntegerField)
fieldPosition.setBeginIndex(appendTo.length());
int32_t sigCount = 0;
int32_t minSigDig = getMinimumSignificantDigits();
int32_t maxSigDig = getMaximumSignificantDigits();
if (!useSigDig) {
minSigDig = 0;
maxSigDig = INT32_MAX;
}
// Output the integer portion. Here 'count' is the total
// number of integer digits we will display, including both
// leading zeros required to satisfy getMinimumIntegerDigits,
// and actual digits present in the number.
int32_t count = useSigDig ?
_max(1, digits.fDecimalAt) : minIntDig;
if (digits.fDecimalAt > 0 && count < digits.fDecimalAt) {
count = digits.fDecimalAt;
}
// Handle the case where getMaximumIntegerDigits() is smaller
// than the real number of integer digits. If this is so, we
// output the least significant max integer digits. For example,
// the value 1997 printed with 2 max integer digits is just "97".
int32_t digitIndex = 0; // Index into digitList.fDigits[]
if (count > maxIntDig && maxIntDig >= 0) {
count = maxIntDig;
digitIndex = digits.fDecimalAt - count;
}
int32_t sizeBeforeIntegerPart = appendTo.length();
int32_t i;
for (i=count-1; i>=0; --i)
{
if (i < digits.fDecimalAt && digitIndex < digits.fCount &&
sigCount < maxSigDig) {
// Output a real digit
appendTo += ((UChar32)(digits.fDigits[digitIndex++] + zeroDelta));
++sigCount;
}
else
{
// Output a zero (leading or trailing)
appendTo += (zero);
if (sigCount > 0) {
++sigCount;
}
}
// Output grouping separator if necessary.
if (isGroupingPosition(i)) {
currentLength = appendTo.length();
appendTo.append(*grouping);
addAttribute(attrBuffer, "grouping_separator",currentLength,appendTo.length());
}
}
// Record field information for caller.
if (fieldPosition.getField() == NumberFormat::kIntegerField)
fieldPosition.setEndIndex(appendTo.length());
// Determine whether or not there are any printable fractional
// digits. If we've used up the digits we know there aren't.
UBool fractionPresent = (!isInteger && digitIndex < digits.fCount) ||
(useSigDig ? (sigCount < minSigDig) : (getMinimumFractionDigits() > 0));
// If there is no fraction present, and we haven't printed any
// integer digits, then print a zero. Otherwise we won't print
// _any_ digits, and we won't be able to parse this string.
if (!fractionPresent && appendTo.length() == sizeBeforeIntegerPart)
appendTo += (zero);
currentLength = appendTo.length();
addAttribute(attrBuffer, "integer", intBegin, currentLength);
// Output the decimal separator if we always do so.
if (fDecimalSeparatorAlwaysShown || fractionPresent) {
appendTo += *decimal;
addAttribute(attrBuffer, "decimal_separator", currentLength, appendTo.length());
currentLength = appendTo.length();
}
int fracBegin = currentLength;
// Record field information for caller.
if (fieldPosition.getField() == NumberFormat::kFractionField)
fieldPosition.setBeginIndex(fracBegin);
count = useSigDig ? INT32_MAX : getMaximumFractionDigits();
if (useSigDig && (sigCount == maxSigDig ||
(sigCount >= minSigDig && digitIndex == digits.fCount))) {
count = 0;
}
for (i=0; i < count; ++i) {
// Here is where we escape from the loop. We escape
// if we've output the maximum fraction digits
// (specified in the for expression above). We also
// stop when we've output the minimum digits and
// either: we have an integer, so there is no
// fractional stuff to display, or we're out of
// significant digits.
if (!useSigDig && i >= getMinimumFractionDigits() &&
(isInteger || digitIndex >= digits.fCount)) {
break;
}
// Output leading fractional zeros. These are zeros
// that come after the decimal but before any
// significant digits. These are only output if
// abs(number being formatted) < 1.0.
if (-1-i > (digits.fDecimalAt-1)) {
appendTo += zero;
continue;
}
// Output a digit, if we have any precision left, or a
// zero if we don't. We don't want to output noise digits.
if (!isInteger && digitIndex < digits.fCount) {
appendTo += ((UChar32)(digits.fDigits[digitIndex++] + zeroDelta));
} else {
appendTo += zero;
}
// If we reach the maximum number of significant
// digits, or if we output all the real digits and
// reach the minimum, then we are done.
++sigCount;
if (useSigDig &&
(sigCount == maxSigDig ||
(digitIndex == digits.fCount && sigCount >= minSigDig))) {
break;
}
}
// Record field information for caller.
if (fieldPosition.getField() == NumberFormat::kFractionField)
fieldPosition.setEndIndex(appendTo.length());
addAttribute(attrBuffer, "fraction", fracBegin, appendTo.length());
}
int32_t suffixLen = appendAffix(appendTo, doubleValue, attrBuffer, !digits.fIsPositive, FALSE);
addPadding(appendTo, fieldPosition, prefixLen, suffixLen);
return appendTo;
}
/**
* Inserts the character fPad as needed to expand result to fFormatWidth.
* @param result the string to be padded
*/
void DecimalFormat::addPadding(UnicodeString& appendTo,
FieldPosition& fieldPosition,
int32_t prefixLen,
int32_t suffixLen) const
{
if (fFormatWidth > 0) {
int32_t len = fFormatWidth - appendTo.length();
if (len > 0) {
UnicodeString padding;
for (int32_t i=0; i<len; ++i) {
padding += fPad;
}
switch (fPadPosition) {
case kPadAfterPrefix:
appendTo.insert(prefixLen, padding);
break;
case kPadBeforePrefix:
appendTo.insert(0, padding);
break;
case kPadBeforeSuffix:
appendTo.insert(appendTo.length() - suffixLen, padding);
break;
case kPadAfterSuffix:
appendTo += padding;
break;
}
if (fPadPosition == kPadBeforePrefix ||
fPadPosition == kPadAfterPrefix) {
fieldPosition.setBeginIndex(len + fieldPosition.getBeginIndex());
fieldPosition.setEndIndex(len + fieldPosition.getEndIndex());
}
}
}
}
//------------------------------------------------------------------------------
void
DecimalFormat::parse(const UnicodeString& text,
Formattable& result,
UErrorCode& status) const
{
NumberFormat::parse(text, result, status);
}
void
DecimalFormat::parse(const UnicodeString& text,
Formattable& result,
ParsePosition& parsePosition) const {
parse(text, result, parsePosition, FALSE);
}
Formattable& DecimalFormat::parseCurrency(const UnicodeString& text,
Formattable& result,
ParsePosition& pos) const {
parse(text, result, pos, TRUE);
return result;
}
// BEGIN android-changed
/**
* Parses the given text as either a number or a currency amount.
* @param text the string to parse
* @param result output parameter for the result
* @param parsePosition input-output position; on input, the
* position within text to match; must have 0 <= pos.getIndex() <
* text.length(); on output, the position after the last matched
* character. If the parse fails, the position in unchanged upon
* output.
* @param parseCurrency if true, a currency amount is parsed;
* otherwise a Number is parsed
*/
void DecimalFormat::parse(const UnicodeString& text,
Formattable& result,
ParsePosition& parsePosition,
UBool parseCurrency) const {
bool resultAssigned;
DigitList digits;
parse(text, resultAssigned, result, parsePosition, parseCurrency, digits);
if(!resultAssigned) {
result.setDouble(digits.getDouble());
}
}
/**
* Parses the given text as either a number or a currency amount.
* @param text the string to parse
* @param resultAssigned indicates whether or not the param result is assigned
* @param result output parameter for the parsing result
* ATTENTION: result is assigned ONLY for types long and int64
* @param parsePosition input-output position; on input, the
* position within text to match; must have 0 <= pos.getIndex() <
* text.length(); on output, the position after the last matched
* character. If the parse fails, the position in unchanged upon
* output.
* @param parseCurrency if true, a currency amount is parsed;
* otherwise a Number is parsed
* @param digits The DigitList that represents the result will be returned
* ATTENTION: digits are only returned when result was not assigned
*/
void DecimalFormat::parse(const UnicodeString& text,
bool& resultAssigned,
Formattable& result,
ParsePosition& parsePosition,
UBool parseCurrency,
DigitList& digits) const {
int32_t backup;
int32_t i = backup = parsePosition.getIndex();
resultAssigned = true;
// Handle NaN as a special case:
// Skip padding characters, if around prefix
if (fFormatWidth > 0 && (fPadPosition == kPadBeforePrefix ||
fPadPosition == kPadAfterPrefix)) {
i = skipPadding(text, i);
}
// If the text is composed of the representation of NaN, returns NaN.length
const UnicodeString *nan = &getConstSymbol(DecimalFormatSymbols::kNaNSymbol);
int32_t nanLen = (text.compare(i, nan->length(), *nan)
? 0 : nan->length());
if (nanLen) {
i += nanLen;
if (fFormatWidth > 0 && (fPadPosition == kPadBeforeSuffix ||
fPadPosition == kPadAfterSuffix)) {
i = skipPadding(text, i);
}
parsePosition.setIndex(i);
result.setDouble(uprv_getNaN());
return;
}
// NaN parse failed; start over
i = backup;
// status is used to record whether a number is infinite.
UBool status[fgStatusLength];
UChar curbuf[4];
UChar* currency = parseCurrency ? curbuf : NULL;
if (!subparse(text, parsePosition, digits, status, currency)) {
parsePosition.setIndex(backup);
return;
}
// Handle infinity
if (status[fgStatusInfinite]) {
double inf = uprv_getInfinity();
result.setDouble(digits.fIsPositive ? inf : -inf);
}
else {
// Do as much of the multiplier conversion as possible without
// losing accuracy.
int32_t mult = fMultiplier; // Don't modify this.multiplier
while (mult % 10 == 0) {
mult /= 10;
--digits.fDecimalAt;
}
// Handle integral values. We want to return the most
// parsimonious type that will accommodate all of the result's
// precision. We therefore only return a long if the result fits
// entirely within a long (taking into account the multiplier) --
// otherwise we fall through and return a double. When more
// numeric types are supported by Formattable (e.g., 64-bit
// integers, bignums) we will extend this logic to include them.
if (digits.fitsIntoLong(isParseIntegerOnly())) {
int32_t n = digits.getLong();
if (n % mult == 0) {
result.setLong(n / mult);
}
else { // else handle the remainder
result.setDouble(((double)n) / mult);
}
}
else if (digits.fitsIntoInt64(isParseIntegerOnly())) {
int64_t n = digits.getInt64();
if (n % mult == 0) {
result.setInt64(n / mult);
}
else { // else handle the remainder
result.setDouble(((double)n) / mult);
}
}
else {
resultAssigned = false;
}
}
if (parseCurrency) {
UErrorCode ec = U_ZERO_ERROR;
Formattable n(result);
result.adoptObject(new CurrencyAmount(n, curbuf, ec));
U_ASSERT(U_SUCCESS(ec)); // should always succeed
}
}
// END android-changed
/*
This is an old implimentation that was preparing for 64-bit numbers in ICU.
It is very slow, and 64-bit numbers are not ANSI-C compatible. This code
is here if we change our minds.
^^^ what is this referring to? remove? ^^^ [alan]
*/
/**
* Parse the given text into a number. The text is parsed beginning at
* parsePosition, until an unparseable character is seen.
* @param text the string to parse.
* @param parsePosition The position at which to being parsing. Upon
* return, the first unparsed character.
* @param digits the DigitList to set to the parsed value.
* @param status output param containing boolean status flags indicating
* whether the value was infinite and whether it was positive.
* @param currency return value for parsed currency, for generic
* currency parsing mode, or NULL for normal parsing. In generic
* currency parsing mode, any currency is parsed, not just the
* currency that this formatter is set to.
*/
UBool DecimalFormat::subparse(const UnicodeString& text, ParsePosition& parsePosition,
DigitList& digits, UBool* status,
UChar* currency) const
{
int32_t position = parsePosition.getIndex();
int32_t oldStart = position;
// Match padding before prefix
if (fFormatWidth > 0 && fPadPosition == kPadBeforePrefix) {
position = skipPadding(text, position);
}
// Match positive and negative prefixes; prefer longest match.
int32_t posMatch = compareAffix(text, position, FALSE, TRUE, currency);
int32_t negMatch = compareAffix(text, position, TRUE, TRUE, currency);
if (posMatch >= 0 && negMatch >= 0) {
if (posMatch > negMatch) {
negMatch = -1;
} else if (negMatch > posMatch) {
posMatch = -1;
}
}
if (posMatch >= 0) {
position += posMatch;
} else if (negMatch >= 0) {
position += negMatch;
} else {
parsePosition.setErrorIndex(position);
return FALSE;
}
// Match padding before prefix
if (fFormatWidth > 0 && fPadPosition == kPadAfterPrefix) {
position = skipPadding(text, position);
}
// process digits or Inf, find decimal position
const UnicodeString *inf = &getConstSymbol(DecimalFormatSymbols::kInfinitySymbol);
int32_t infLen = (text.compare(position, inf->length(), *inf)
? 0 : inf->length());
position += infLen; // infLen is non-zero when it does equal to infinity
status[fgStatusInfinite] = (UBool)infLen;
if (!infLen)
{
// We now have a string of digits, possibly with grouping symbols,
// and decimal points. We want to process these into a DigitList.
// We don't want to put a bunch of leading zeros into the DigitList
// though, so we keep track of the location of the decimal point,
// put only significant digits into the DigitList, and adjust the
// exponent as needed.
digits.fDecimalAt = digits.fCount = 0;
UChar32 zero = getConstSymbol(DecimalFormatSymbols::kZeroDigitSymbol).char32At(0);
const UnicodeString *decimal;
if(fIsCurrencyFormat) {
decimal = &getConstSymbol(DecimalFormatSymbols::kMonetarySeparatorSymbol);
} else {
decimal = &getConstSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol);
}
const UnicodeString *grouping = &getConstSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol);
UBool sawDecimal = FALSE;
UBool sawDigit = FALSE;
int32_t backup = -1;
int32_t digit;
int32_t textLength = text.length(); // One less pointer to follow
int32_t groupingLen = grouping->length();
int32_t decimalLen = decimal->length();
// We have to track digitCount ourselves, because digits.fCount will
// pin when the maximum allowable digits is reached.
int32_t digitCount = 0;
for (; position < textLength; )
{
UChar32 ch = text.char32At(position);
/* We recognize all digit ranges, not only the Latin digit range
* '0'..'9'. We do so by using the Character.digit() method,
* which converts a valid Unicode digit to the range 0..9.
*
* The character 'ch' may be a digit. If so, place its value
* from 0 to 9 in 'digit'. First try using the locale digit,
* which may or MAY NOT be a standard Unicode digit range. If
* this fails, try using the standard Unicode digit ranges by
* calling Character.digit(). If this also fails, digit will
* have a value outside the range 0..9.
*/
digit = ch - zero;
if (digit < 0 || digit > 9)
{
digit = u_charDigitValue(ch);
}
if (digit > 0 && digit <= 9)
{
// Cancel out backup setting (see grouping handler below)
backup = -1;
sawDigit = TRUE;
// output a regular non-zero digit.
++digitCount;
digits.append((char)(digit + '0'));
position += U16_LENGTH(ch);
}
else if (digit == 0)
{
// Cancel out backup setting (see grouping handler below)
backup = -1;
sawDigit = TRUE;
// Check for leading zeros
if (digits.fCount != 0)
{
// output a regular zero digit.
++digitCount;
digits.append((char)(digit + '0'));
}
else if (sawDecimal)
{
// If we have seen the decimal, but no significant digits yet,
// then we account for leading zeros by decrementing the
// digits.fDecimalAt into negative values.
--digits.fDecimalAt;
}
// else ignore leading zeros in integer part of number.
position += U16_LENGTH(ch);
}
else if (!text.compare(position, groupingLen, *grouping) && isGroupingUsed())
{
// Ignore grouping characters, if we are using them, but require
// that they be followed by a digit. Otherwise we backup and
// reprocess them.
backup = position;
position += groupingLen;
}
else if (!text.compare(position, decimalLen, *decimal) && !isParseIntegerOnly() && !sawDecimal)
{
// If we're only parsing integers, or if we ALREADY saw the
// decimal, then don't parse this one.
digits.fDecimalAt = digitCount; // Not digits.fCount!
sawDecimal = TRUE;
position += decimalLen;
}
else {
const UnicodeString *tmp;
tmp = &getConstSymbol(DecimalFormatSymbols::kExponentialSymbol);
if (!text.caseCompare(position, tmp->length(), *tmp, U_FOLD_CASE_DEFAULT)) // error code is set below if !sawDigit
{
// Parse sign, if present
int32_t pos = position + tmp->length();
DigitList exponentDigits;
if (pos < textLength)
{
tmp = &getConstSymbol(DecimalFormatSymbols::kPlusSignSymbol);
if (!text.compare(pos, tmp->length(), *tmp))
{
pos += tmp->length();
}
else {
tmp = &getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol);
if (!text.compare(pos, tmp->length(), *tmp))
{
pos += tmp->length();
exponentDigits.fIsPositive = FALSE;
}
}
}
while (pos < textLength) {
ch = text[(int32_t)pos];
digit = ch - zero;
if (digit < 0 || digit > 9) {
digit = u_charDigitValue(ch);
}
if (0 <= digit && digit <= 9) {
++pos;
exponentDigits.append((char)(digit + '0'));
} else {
break;
}
}
if (exponentDigits.fCount > 0) {
exponentDigits.fDecimalAt = exponentDigits.fCount;
digits.fDecimalAt += exponentDigits.getLong();
position = pos; // Advance past the exponent
}
break; // Whether we fail or succeed, we exit this loop
}
else {
break;
}
}
}
if (backup != -1)
{
position = backup;
}
// If there was no decimal point we have an integer
if (!sawDecimal)
{
digits.fDecimalAt += digitCount; // Not digits.fCount!
}
// If none of the text string was recognized. For example, parse
// "x" with pattern "#0.00" (return index and error index both 0)
// parse "$" with pattern "$#0.00". (return index 0 and error index
// 1).
if (!sawDigit && digitCount == 0) {
parsePosition.setIndex(oldStart);
parsePosition.setErrorIndex(oldStart);
return FALSE;
}
}
// Match padding before suffix
if (fFormatWidth > 0 && fPadPosition == kPadBeforeSuffix) {
position = skipPadding(text, position);
}
// Match positive and negative suffixes; prefer longest match.
if (posMatch >= 0) {
posMatch = compareAffix(text, position, FALSE, FALSE, currency);
}
if (negMatch >= 0) {
negMatch = compareAffix(text, position, TRUE, FALSE, currency);
}
if (posMatch >= 0 && negMatch >= 0) {
if (posMatch > negMatch) {
negMatch = -1;
} else if (negMatch > posMatch) {
posMatch = -1;
}
}
// Fail if neither or both
if ((posMatch >= 0) == (negMatch >= 0)) {
parsePosition.setErrorIndex(position);
return FALSE;
}
position += (posMatch>=0 ? posMatch : negMatch);
// Match padding before suffix
if (fFormatWidth > 0 && fPadPosition == kPadAfterSuffix) {
position = skipPadding(text, position);
}
parsePosition.setIndex(position);
digits.fIsPositive = (posMatch >= 0);
if(parsePosition.getIndex() == oldStart)
{
parsePosition.setErrorIndex(position);
return FALSE;
}
return TRUE;
}
/**
* Starting at position, advance past a run of pad characters, if any.
* Return the index of the first character after position that is not a pad
* character. Result is >= position.
*/
int32_t DecimalFormat::skipPadding(const UnicodeString& text, int32_t position) const {
int32_t padLen = U16_LENGTH(fPad);
while (position < text.length() &&
text.char32At(position) == fPad) {
position += padLen;
}
return position;
}
/**
* Return the length matched by the given affix, or -1 if none.
* Runs of white space in the affix, match runs of white space in
* the input. Pattern white space and input white space are
* determined differently; see code.
* @param text input text
* @param pos offset into input at which to begin matching
* @param isNegative
* @param isPrefix
* @param currency return value for parsed currency, for generic
* currency parsing mode, or null for normal parsing. In generic
* currency parsing mode, any currency is parsed, not just the
* currency that this formatter is set to.
* @return length of input that matches, or -1 if match failure
*/
int32_t DecimalFormat::compareAffix(const UnicodeString& text,
int32_t pos,
UBool isNegative,
UBool isPrefix,
UChar* currency) const
{
const UnicodeString *patternToCompare;
if (fCurrencyChoice != NULL || currency != NULL) {
if (isNegative) {
if (isPrefix) {
patternToCompare = fNegPrefixPattern;
}
else {
patternToCompare = fNegSuffixPattern;
}
}
else {
if (isPrefix) {
patternToCompare = fPosPrefixPattern;
}
else {
patternToCompare = fPosSuffixPattern;
}
}
if (patternToCompare != NULL) {
return compareComplexAffix(*patternToCompare, text, pos, currency);
}
/* else the caller modified the pattern. Fallback to normal behavior. */
}
if (isNegative) {
if (isPrefix) {
patternToCompare = &fNegativePrefix;
}
else {
patternToCompare = &fNegativeSuffix;
}
}
else {
if (isPrefix) {
patternToCompare = &fPositivePrefix;
}
else {
patternToCompare = &fPositiveSuffix;
}
}
return compareSimpleAffix(*patternToCompare, text, pos);
}
/**
* Return the length matched by the given affix, or -1 if none.
* Runs of white space in the affix, match runs of white space in
* the input. Pattern white space and input white space are
* determined differently; see code.
* @param affix pattern string, taken as a literal
* @param input input text
* @param pos offset into input at which to begin matching
* @return length of input that matches, or -1 if match failure
*/
int32_t DecimalFormat::compareSimpleAffix(const UnicodeString& affix,
const UnicodeString& input,
int32_t pos) {
int32_t start = pos;
for (int32_t i=0; i<affix.length(); ) {
UChar32 c = affix.char32At(i);
int32_t len = U16_LENGTH(c);
if (uprv_isRuleWhiteSpace(c)) {
// We may have a pattern like: \u200F \u0020
// and input text like: \u200F \u0020
// Note that U+200F and U+0020 are RuleWhiteSpace but only
// U+0020 is UWhiteSpace. So we have to first do a direct
// match of the run of RULE whitespace in the pattern,
// then match any extra characters.
UBool literalMatch = FALSE;
while (pos < input.length() &&
input.char32At(pos) == c) {
literalMatch = TRUE;
i += len;
pos += len;
if (i == affix.length()) {
break;
}
c = affix.char32At(i);
len = U16_LENGTH(c);
if (!uprv_isRuleWhiteSpace(c)) {
break;
}
}
// Advance over run in pattern
i = skipRuleWhiteSpace(affix, i);
// Advance over run in input text
// Must see at least one white space char in input,
// unless we've already matched some characters literally.
int32_t s = pos;
pos = skipUWhiteSpace(input, pos);
if (pos == s && !literalMatch) {
return -1;
}
} else {
if (pos < input.length() &&
input.char32At(pos) == c) {
i += len;
pos += len;
} else {
return -1;
}
}
}
return pos - start;
}
/**
* Skip over a run of zero or more isRuleWhiteSpace() characters at
* pos in text.
*/
int32_t DecimalFormat::skipRuleWhiteSpace(const UnicodeString& text, int32_t pos) {
while (pos < text.length()) {
UChar32 c = text.char32At(pos);
if (!uprv_isRuleWhiteSpace(c)) {
break;
}
pos += U16_LENGTH(c);
}
return pos;
}
/**
* Skip over a run of zero or more isUWhiteSpace() characters at pos
* in text.
*/
int32_t DecimalFormat::skipUWhiteSpace(const UnicodeString& text, int32_t pos) {
while (pos < text.length()) {
UChar32 c = text.char32At(pos);
if (!u_isUWhiteSpace(c)) {
break;
}
pos += U16_LENGTH(c);
}
return pos;
}
/**
* Return the length matched by the given affix, or -1 if none.
* @param affixPat pattern string
* @param input input text
* @param pos offset into input at which to begin matching
* @param currency return value for parsed currency, for generic
* currency parsing mode, or null for normal parsing. In generic
* currency parsing mode, any currency is parsed, not just the
* currency that this formatter is set to.
* @return length of input that matches, or -1 if match failure
*/
int32_t DecimalFormat::compareComplexAffix(const UnicodeString& affixPat,
const UnicodeString& text,
int32_t pos,
UChar* currency) const
{
int32_t start = pos;
U_ASSERT(currency != NULL ||
(fCurrencyChoice != NULL && *getCurrency() != 0));
for (int32_t i=0; i<affixPat.length() && pos >= 0; ) {
UChar32 c = affixPat.char32At(i);
i += U16_LENGTH(c);
if (c == kQuote) {
U_ASSERT(i <= affixPat.length());
c = affixPat.char32At(i);
i += U16_LENGTH(c);
const UnicodeString* affix = NULL;
switch (c) {
case kCurrencySign: {
// If currency != null, then perform generic currency matching.
// Otherwise, do currency choice parsing.
UBool intl = i<affixPat.length() &&
affixPat.char32At(i) == kCurrencySign;
// Parse generic currency -- anything for which we
// have a display name, or any 3-letter ISO code.
if (currency != NULL) {
// Try to parse display name for our locale; first
// determine our locale.
UErrorCode ec = U_ZERO_ERROR;
const char* loc = getLocaleID(ULOC_VALID_LOCALE, ec);
if (U_FAILURE(ec) || loc == NULL || *loc == 0) {
// applyPattern has been called; use the symbols
loc = fSymbols->getLocale().getName();
ec = U_ZERO_ERROR;
}
// Delegate parse of display name => ISO code to Currency
ParsePosition ppos(pos);
UChar curr[4];
uprv_parseCurrency(loc, text, ppos, curr, ec);
// If parse succeeds, populate currency[0]
if (U_SUCCESS(ec) && ppos.getIndex() != pos) {
u_strcpy(currency, curr);
pos = ppos.getIndex();
} else {
pos = -1;
}
} else {
if (intl) {
++i;
pos = match(text, pos, getCurrency());
} else {
ParsePosition ppos(pos);
Formattable result;
fCurrencyChoice->parse(text, result, ppos);
pos = (ppos.getIndex() == pos) ? -1 : ppos.getIndex();
}
}
continue;
}
case kPatternPercent:
affix = &getConstSymbol(DecimalFormatSymbols::kPercentSymbol);
break;
case kPatternPerMill:
affix = &getConstSymbol(DecimalFormatSymbols::kPerMillSymbol);
break;
case kPatternPlus:
affix = &getConstSymbol(DecimalFormatSymbols::kPlusSignSymbol);
break;
case kPatternMinus:
affix = &getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol);
break;
default:
// fall through to affix!=0 test, which will fail
break;
}
if (affix != NULL) {
pos = match(text, pos, *affix);
continue;
}
}
pos = match(text, pos, c);
if (uprv_isRuleWhiteSpace(c)) {
i = skipRuleWhiteSpace(affixPat, i);
}
}
return pos - start;
}
/**
* Match a single character at text[pos] and return the index of the
* next character upon success. Return -1 on failure. If
* isRuleWhiteSpace(ch) then match a run of white space in text.
*/
int32_t DecimalFormat::match(const UnicodeString& text, int32_t pos, UChar32 ch) {
if (uprv_isRuleWhiteSpace(ch)) {
// Advance over run of white space in input text
// Must see at least one white space char in input
int32_t s = pos;
pos = skipUWhiteSpace(text, pos);
if (pos == s) {
return -1;
}
return pos;
}
return (pos >= 0 && text.char32At(pos) == ch) ?
(pos + U16_LENGTH(ch)) : -1;
}
/**
* Match a string at text[pos] and return the index of the next
* character upon success. Return -1 on failure. Match a run of
* white space in str with a run of white space in text.
*/
int32_t DecimalFormat::match(const UnicodeString& text, int32_t pos, const UnicodeString& str) {
for (int32_t i=0; i<str.length() && pos >= 0; ) {
UChar32 ch = str.char32At(i);
i += U16_LENGTH(ch);
if (uprv_isRuleWhiteSpace(ch)) {
i = skipRuleWhiteSpace(str, i);
}
pos = match(text, pos, ch);
}
return pos;
}
//------------------------------------------------------------------------------
// Gets the pointer to the localized decimal format symbols
const DecimalFormatSymbols*
DecimalFormat::getDecimalFormatSymbols() const
{
return fSymbols;
}
//------------------------------------------------------------------------------
// De-owning the current localized symbols and adopt the new symbols.
void
DecimalFormat::adoptDecimalFormatSymbols(DecimalFormatSymbols* symbolsToAdopt)
{
if (symbolsToAdopt == NULL) {
return; // do not allow caller to set fSymbols to NULL
}
UBool sameSymbols = FALSE;
if (fSymbols != NULL) {
sameSymbols = (UBool)(getConstSymbol(DecimalFormatSymbols::kCurrencySymbol) ==
symbolsToAdopt->getConstSymbol(DecimalFormatSymbols::kCurrencySymbol) &&
getConstSymbol(DecimalFormatSymbols::kIntlCurrencySymbol) ==
symbolsToAdopt->getConstSymbol(DecimalFormatSymbols::kIntlCurrencySymbol));
delete fSymbols;
}
fSymbols = symbolsToAdopt;
if (!sameSymbols) {
// If the currency symbols are the same, there is no need to recalculate.
setCurrencyForSymbols();
}
expandAffixes();
}
//------------------------------------------------------------------------------
// Setting the symbols is equlivalent to adopting a newly created localized
// symbols.
void
DecimalFormat::setDecimalFormatSymbols(const DecimalFormatSymbols& symbols)
{
adoptDecimalFormatSymbols(new DecimalFormatSymbols(symbols));
}
/**
* Update the currency object to match the symbols. This method
* is used only when the caller has passed in a symbols object
* that may not be the default object for its locale.
*/
void
DecimalFormat::setCurrencyForSymbols() {
/*Bug 4212072
Update the affix strings accroding to symbols in order to keep
the affix strings up to date.
[Richard/GCL]
*/
// With the introduction of the Currency object, the currency
// symbols in the DFS object are ignored. For backward
// compatibility, we check any explicitly set DFS object. If it
// is a default symbols object for its locale, we change the
// currency object to one for that locale. If it is custom,
// we set the currency to null.
UErrorCode ec = U_ZERO_ERROR;
const UChar* c = NULL;
const char* loc = fSymbols->getLocale().getName();
UChar intlCurrencySymbol[4];
ucurr_forLocale(loc, intlCurrencySymbol, 4, &ec);
UnicodeString currencySymbol;
uprv_getStaticCurrencyName(intlCurrencySymbol, loc, currencySymbol, ec);
if (U_SUCCESS(ec)
&& getConstSymbol(DecimalFormatSymbols::kCurrencySymbol) == currencySymbol
&& getConstSymbol(DecimalFormatSymbols::kIntlCurrencySymbol) == intlCurrencySymbol)
{
// Trap an error in mapping locale to currency. If we can't
// map, then don't fail and set the currency to "".
c = intlCurrencySymbol;
}
ec = U_ZERO_ERROR; // reset local error code!
setCurrency(c, ec);
}
//------------------------------------------------------------------------------
// Gets the positive prefix of the number pattern.
UnicodeString&
DecimalFormat::getPositivePrefix(UnicodeString& result) const
{
result = fPositivePrefix;
return result;
}
//------------------------------------------------------------------------------
// Sets the positive prefix of the number pattern.
void
DecimalFormat::setPositivePrefix(const UnicodeString& newValue)
{
fPositivePrefix = newValue;
delete fPosPrefixPattern;
fPosPrefixPattern = 0;
}
//------------------------------------------------------------------------------
// Gets the negative prefix of the number pattern.
UnicodeString&
DecimalFormat::getNegativePrefix(UnicodeString& result) const
{
result = fNegativePrefix;
return result;
}
//------------------------------------------------------------------------------
// Gets the negative prefix of the number pattern.
void
DecimalFormat::setNegativePrefix(const UnicodeString& newValue)
{
fNegativePrefix = newValue;
delete fNegPrefixPattern;
fNegPrefixPattern = 0;
}
//------------------------------------------------------------------------------
// Gets the positive suffix of the number pattern.
UnicodeString&
DecimalFormat::getPositiveSuffix(UnicodeString& result) const
{
result = fPositiveSuffix;
return result;
}
//------------------------------------------------------------------------------
// Sets the positive suffix of the number pattern.
void
DecimalFormat::setPositiveSuffix(const UnicodeString& newValue)
{
fPositiveSuffix = newValue;
delete fPosSuffixPattern;
fPosSuffixPattern = 0;
}
//------------------------------------------------------------------------------
// Gets the negative suffix of the number pattern.
UnicodeString&
DecimalFormat::getNegativeSuffix(UnicodeString& result) const
{
result = fNegativeSuffix;
return result;
}
//------------------------------------------------------------------------------
// Sets the negative suffix of the number pattern.
void
DecimalFormat::setNegativeSuffix(const UnicodeString& newValue)
{
fNegativeSuffix = newValue;
delete fNegSuffixPattern;
fNegSuffixPattern = 0;
}
//------------------------------------------------------------------------------
// Gets the multiplier of the number pattern.
int32_t DecimalFormat::getMultiplier() const
{
return fMultiplier;
}
//------------------------------------------------------------------------------
// Sets the multiplier of the number pattern.
void
DecimalFormat::setMultiplier(int32_t newValue)
{
// if (newValue <= 0) {
// throw new IllegalArgumentException("Bad multiplier: " + newValue);
// }
// if (newValue > 0) {
fMultiplier = newValue;
// }
// else No way to return an error.
}
/**
* Get the rounding increment.
* @return A positive rounding increment, or 0.0 if rounding
* is not in effect.
* @see #setRoundingIncrement
* @see #getRoundingMode
* @see #setRoundingMode
*/
double DecimalFormat::getRoundingIncrement() const {
return fRoundingDouble;
}
/**
* Set the rounding increment. This method also controls whether
* rounding is enabled.
* @param newValue A positive rounding increment, or 0.0 to disable rounding.
* Negative increments are equivalent to 0.0.
* @see #getRoundingIncrement
* @see #getRoundingMode
* @see #setRoundingMode
*/
void DecimalFormat::setRoundingIncrement(double newValue) {
if (newValue > 0.0) {
if (fRoundingIncrement == NULL) {
fRoundingIncrement = new DigitList();
}
fRoundingIncrement->set((int32_t)newValue);
fRoundingDouble = newValue;
} else {
delete fRoundingIncrement;
fRoundingIncrement = NULL;
fRoundingDouble = 0.0;
}
}
/**
* Get the rounding mode.
* @return A rounding mode
* @see #setRoundingIncrement
* @see #getRoundingIncrement
* @see #setRoundingMode
*/
DecimalFormat::ERoundingMode DecimalFormat::getRoundingMode() const {
return fRoundingMode;
}
/**
* Set the rounding mode. This has no effect unless the rounding
* increment is greater than zero.
* @param roundingMode A rounding mode
* @see #setRoundingIncrement
* @see #getRoundingIncrement
* @see #getRoundingMode
*/
void DecimalFormat::setRoundingMode(ERoundingMode roundingMode) {
fRoundingMode = roundingMode;
}
/**
* Get the width to which the output of <code>format()</code> is padded.
* @return the format width, or zero if no padding is in effect
* @see #setFormatWidth
* @see #getPadCharacter
* @see #setPadCharacter
* @see #getPadPosition
* @see #setPadPosition
*/
int32_t DecimalFormat::getFormatWidth() const {
return fFormatWidth;
}
/**
* Set the width to which the output of <code>format()</code> is padded.
* This method also controls whether padding is enabled.
* @param width the width to which to pad the result of
* <code>format()</code>, or zero to disable padding. A negative
* width is equivalent to 0.
* @see #getFormatWidth
* @see #getPadCharacter
* @see #setPadCharacter
* @see #getPadPosition
* @see #setPadPosition
*/
void DecimalFormat::setFormatWidth(int32_t width) {
fFormatWidth = (width > 0) ? width : 0;
}
UnicodeString DecimalFormat::getPadCharacterString() const {
return fPad;
}
void DecimalFormat::setPadCharacter(const UnicodeString &padChar) {
if (padChar.length() > 0) {
fPad = padChar.char32At(0);
}
else {
fPad = kDefaultPad;
}
}
/**
* Get the position at which padding will take place. This is the location
* at which padding will be inserted if the result of <code>format()</code>
* is shorter than the format width.
* @return the pad position, one of <code>kPadBeforePrefix</code>,
* <code>kPadAfterPrefix</code>, <code>kPadBeforeSuffix</code>, or
* <code>kPadAfterSuffix</code>.
* @see #setFormatWidth
* @see #getFormatWidth
* @see #setPadCharacter
* @see #getPadCharacter
* @see #setPadPosition
* @see #kPadBeforePrefix
* @see #kPadAfterPrefix
* @see #kPadBeforeSuffix
* @see #kPadAfterSuffix
*/
DecimalFormat::EPadPosition DecimalFormat::getPadPosition() const {
return fPadPosition;
}
/**
* <strong><font face=helvetica color=red>NEW</font></strong>
* Set the position at which padding will take place. This is the location
* at which padding will be inserted if the result of <code>format()</code>
* is shorter than the format width. This has no effect unless padding is
* enabled.
* @param padPos the pad position, one of <code>kPadBeforePrefix</code>,
* <code>kPadAfterPrefix</code>, <code>kPadBeforeSuffix</code>, or
* <code>kPadAfterSuffix</code>.
* @see #setFormatWidth
* @see #getFormatWidth
* @see #setPadCharacter
* @see #getPadCharacter
* @see #getPadPosition
* @see #kPadBeforePrefix
* @see #kPadAfterPrefix
* @see #kPadBeforeSuffix
* @see #kPadAfterSuffix
*/
void DecimalFormat::setPadPosition(EPadPosition padPos) {
fPadPosition = padPos;
}
/**
* Return whether or not scientific notation is used.
* @return TRUE if this object formats and parses scientific notation
* @see #setScientificNotation
* @see #getMinimumExponentDigits
* @see #setMinimumExponentDigits
* @see #isExponentSignAlwaysShown
* @see #setExponentSignAlwaysShown
*/
UBool DecimalFormat::isScientificNotation() {
return fUseExponentialNotation;
}
/**
* Set whether or not scientific notation is used.
* @param useScientific TRUE if this object formats and parses scientific
* notation
* @see #isScientificNotation
* @see #getMinimumExponentDigits
* @see #setMinimumExponentDigits
* @see #isExponentSignAlwaysShown
* @see #setExponentSignAlwaysShown
*/
void DecimalFormat::setScientificNotation(UBool useScientific) {
fUseExponentialNotation = useScientific;
}
/**
* Return the minimum exponent digits that will be shown.
* @return the minimum exponent digits that will be shown
* @see #setScientificNotation
* @see #isScientificNotation
* @see #setMinimumExponentDigits
* @see #isExponentSignAlwaysShown
* @see #setExponentSignAlwaysShown
*/
int8_t DecimalFormat::getMinimumExponentDigits() const {
return fMinExponentDigits;
}
/**
* Set the minimum exponent digits that will be shown. This has no
* effect unless scientific notation is in use.
* @param minExpDig a value >= 1 indicating the fewest exponent digits
* that will be shown. Values less than 1 will be treated as 1.
* @see #setScientificNotation
* @see #isScientificNotation
* @see #getMinimumExponentDigits
* @see #isExponentSignAlwaysShown
* @see #setExponentSignAlwaysShown
*/
void DecimalFormat::setMinimumExponentDigits(int8_t minExpDig) {
fMinExponentDigits = (int8_t)((minExpDig > 0) ? minExpDig : 1);
}
/**
* Return whether the exponent sign is always shown.
* @return TRUE if the exponent is always prefixed with either the
* localized minus sign or the localized plus sign, false if only negative
* exponents are prefixed with the localized minus sign.
* @see #setScientificNotation
* @see #isScientificNotation
* @see #setMinimumExponentDigits
* @see #getMinimumExponentDigits
* @see #setExponentSignAlwaysShown
*/
UBool DecimalFormat::isExponentSignAlwaysShown() {
return fExponentSignAlwaysShown;
}
/**
* Set whether the exponent sign is always shown. This has no effect
* unless scientific notation is in use.
* @param expSignAlways TRUE if the exponent is always prefixed with either
* the localized minus sign or the localized plus sign, false if only
* negative exponents are prefixed with the localized minus sign.
* @see #setScientificNotation
* @see #isScientificNotation
* @see #setMinimumExponentDigits
* @see #getMinimumExponentDigits
* @see #isExponentSignAlwaysShown
*/
void DecimalFormat::setExponentSignAlwaysShown(UBool expSignAlways) {
fExponentSignAlwaysShown = expSignAlways;
}
//------------------------------------------------------------------------------
// Gets the grouping size of the number pattern. For example, thousand or 10
// thousand groupings.
int32_t
DecimalFormat::getGroupingSize() const
{
return fGroupingSize;
}
//------------------------------------------------------------------------------
// Gets the grouping size of the number pattern.
void
DecimalFormat::setGroupingSize(int32_t newValue)
{
fGroupingSize = newValue;
}
//------------------------------------------------------------------------------
int32_t
DecimalFormat::getSecondaryGroupingSize() const
{
return fGroupingSize2;
}
//------------------------------------------------------------------------------
void
DecimalFormat::setSecondaryGroupingSize(int32_t newValue)
{
fGroupingSize2 = newValue;
}
//------------------------------------------------------------------------------
// Checks if to show the decimal separator.
UBool
DecimalFormat::isDecimalSeparatorAlwaysShown() const
{
return fDecimalSeparatorAlwaysShown;
}
//------------------------------------------------------------------------------
// Sets to always show the decimal separator.
void
DecimalFormat::setDecimalSeparatorAlwaysShown(UBool newValue)
{
fDecimalSeparatorAlwaysShown = newValue;
}
//------------------------------------------------------------------------------
// Emits the pattern of this DecimalFormat instance.
UnicodeString&
DecimalFormat::toPattern(UnicodeString& result) const
{
return toPattern(result, FALSE);
}
//------------------------------------------------------------------------------
// Emits the localized pattern this DecimalFormat instance.
UnicodeString&
DecimalFormat::toLocalizedPattern(UnicodeString& result) const
{
return toPattern(result, TRUE);
}
//------------------------------------------------------------------------------
/**
* Expand the affix pattern strings into the expanded affix strings. If any
* affix pattern string is null, do not expand it. This method should be
* called any time the symbols or the affix patterns change in order to keep
* the expanded affix strings up to date.
*/
void DecimalFormat::expandAffixes() {
if (fPosPrefixPattern != 0) {
expandAffix(*fPosPrefixPattern, fPositivePrefix, 0, FALSE);
}
if (fPosSuffixPattern != 0) {
expandAffix(*fPosSuffixPattern, fPositiveSuffix, 0, FALSE);
}
if (fNegPrefixPattern != 0) {
expandAffix(*fNegPrefixPattern, fNegativePrefix, 0, FALSE);
}
if (fNegSuffixPattern != 0) {
expandAffix(*fNegSuffixPattern, fNegativeSuffix, 0, FALSE);
}
#ifdef FMT_DEBUG
UnicodeString s;
s.append("[")
.append(*fPosPrefixPattern).append("|").append(*fPosSuffixPattern)
.append(";") .append(*fNegPrefixPattern).append("|").append(*fNegSuffixPattern)
.append("]->[")
.append(fPositivePrefix).append("|").append(fPositiveSuffix)
.append(";") .append(fNegativePrefix).append("|").append(fNegativeSuffix)
.append("]\n");
debugout(s);
#endif
}
void DecimalFormat::expandAffix(const UnicodeString& pattern,
UnicodeString& affix,
double number,
UBool doFormat) const {
expandAffix(pattern, affix, number, NULL, doFormat);
}
/**
* Expand an affix pattern into an affix string. All characters in the
* pattern are literal unless prefixed by kQuote. The following characters
* after kQuote are recognized: PATTERN_PERCENT, PATTERN_PER_MILLE,
* PATTERN_MINUS, and kCurrencySign. If kCurrencySign is doubled (kQuote +
* kCurrencySign + kCurrencySign), it is interpreted as an international
* currency sign. Any other character after a kQuote represents itself.
* kQuote must be followed by another character; kQuote may not occur by
* itself at the end of the pattern.
*
* This method is used in two distinct ways. First, it is used to expand
* the stored affix patterns into actual affixes. For this usage, doFormat
* must be false. Second, it is used to expand the stored affix patterns
* given a specific number (doFormat == true), for those rare cases in
* which a currency format references a ChoiceFormat (e.g., en_IN display
* name for INR). The number itself is taken from digitList.
*
* When used in the first way, this method has a side effect: It sets
* currencyChoice to a ChoiceFormat object, if the currency's display name
* in this locale is a ChoiceFormat pattern (very rare). It only does this
* if currencyChoice is null to start with.
*
* @param pattern the non-null, fPossibly empty pattern
* @param affix string to receive the expanded equivalent of pattern.
* Previous contents are deleted.
* @param doFormat if false, then the pattern will be expanded, and if a
* currency symbol is encountered that expands to a ChoiceFormat, the
* currencyChoice member variable will be initialized if it is null. If
* doFormat is true, then it is assumed that the currencyChoice has been
* created, and it will be used to format the value in digitList.
*/
void DecimalFormat::expandAffix(const UnicodeString& pattern,
UnicodeString& affix,
double number,
AttrBuffer attrBuffer,
UBool doFormat) const {
affix.remove();
for (int i=0; i<pattern.length(); ) {
UChar32 c = pattern.char32At(i);
i += U16_LENGTH(c);
if (c == kQuote) {
c = pattern.char32At(i);
i += U16_LENGTH(c);
int beginIdx = affix.length();
switch (c) {
case kCurrencySign: {
// As of ICU 2.2 we use the currency object, and
// ignore the currency symbols in the DFS, unless
// we have a null currency object. This occurs if
// resurrecting a pre-2.2 object or if the user
// sets a custom DFS.
UBool intl = i<pattern.length() &&
pattern.char32At(i) == kCurrencySign;
if (intl) {
++i;
}
const UChar* currencyUChars = getCurrency();
if (currencyUChars[0] != 0) {
UErrorCode ec = U_ZERO_ERROR;
if(intl) {
affix += currencyUChars;
addAttribute(attrBuffer, "currency", beginIdx, affix.length());
} else {
int32_t len;
UBool isChoiceFormat;
const UChar* s = ucurr_getName(currencyUChars, fSymbols->getLocale().getName(),
UCURR_SYMBOL_NAME, &isChoiceFormat, &len, &ec);
if (isChoiceFormat) {
// Two modes here: If doFormat is false, we set up
// currencyChoice. If doFormat is true, we use the
// previously created currencyChoice to format the
// value in digitList.
if (!doFormat) {
// If the currency is handled by a ChoiceFormat,
// then we're not going to use the expanded
// patterns. Instantiate the ChoiceFormat and
// return.
if (fCurrencyChoice == NULL) {
// TODO Replace double-check with proper thread-safe code
ChoiceFormat* fmt = new ChoiceFormat(s, ec);
if (U_SUCCESS(ec)) {
umtx_lock(NULL);
if (fCurrencyChoice == NULL) {
// Cast away const
((DecimalFormat*)this)->fCurrencyChoice = fmt;
fmt = NULL;
}
umtx_unlock(NULL);
delete fmt;
}
}
// We could almost return null or "" here, since the
// expanded affixes are almost not used at all
// in this situation. However, one method --
// toPattern() -- still does use the expanded
// affixes, in order to set up a padding
// pattern. We use the CURRENCY_SIGN as a
// placeholder.
affix.append(kCurrencySign);
} else {
if (fCurrencyChoice != NULL) {
FieldPosition pos(0); // ignored
if (number < 0) {
number = -number;
}
fCurrencyChoice->format(number, affix, pos);
} else {
// We only arrive here if the currency choice
// format in the locale data is INVALID.
affix += currencyUChars;
addAttribute(attrBuffer, "currency", beginIdx, affix.length());
}
}
continue;
}
affix += UnicodeString(s, len);
addAttribute(attrBuffer, "currency", beginIdx, affix.length());
}
} else {
if(intl) {
affix += getConstSymbol(DecimalFormatSymbols::kIntlCurrencySymbol);
} else {
affix += getConstSymbol(DecimalFormatSymbols::kCurrencySymbol);
}
addAttribute(attrBuffer, "currency", beginIdx, affix.length());
}
break;
}
case kPatternPercent:
affix += getConstSymbol(DecimalFormatSymbols::kPercentSymbol);
addAttribute(attrBuffer, "percent", beginIdx, affix.length());
break;
case kPatternPerMill:
affix += getConstSymbol(DecimalFormatSymbols::kPerMillSymbol);
addAttribute(attrBuffer, "permille", beginIdx, affix.length());
break;
case kPatternPlus:
affix += getConstSymbol(DecimalFormatSymbols::kPlusSignSymbol);
addAttribute(attrBuffer, "sign", beginIdx, affix.length());
break;
case kPatternMinus:
affix += getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol);
addAttribute(attrBuffer, "sign", beginIdx, affix.length());
break;
default:
affix.append(c);
break;
}
}
else {
affix.append(c);
}
}
}
int32_t DecimalFormat::appendAffix(UnicodeString& buf, double number,
UBool isNegative, UBool isPrefix) const {
return appendAffix(buf, number, NULL, isNegative, isPrefix);
}
/**
* Append an affix to the given StringBuffer.
* @param buf buffer to append to
* @param isNegative
* @param isPrefix
*/
int32_t DecimalFormat::appendAffix(UnicodeString& buf, double number,
AttrBuffer attrBuffer, UBool isNegative,
UBool isPrefix) const {
if (fCurrencyChoice != 0) {
const UnicodeString* affixPat;
if (isPrefix) {
affixPat = isNegative ? fNegPrefixPattern : fPosPrefixPattern;
} else {
affixPat = isNegative ? fNegSuffixPattern : fPosSuffixPattern;
}
if (affixPat) {
UnicodeString affixBuf;
expandAffix(*affixPat, affixBuf, number, attrBuffer, TRUE);
buf.append(affixBuf);
return affixBuf.length();
}
// else someone called a function that reset the pattern.
}
const UnicodeString* affix;
if (isPrefix) {
affix = isNegative ? &fNegativePrefix : &fPositivePrefix;
} else {
affix = isNegative ? &fNegativeSuffix : &fPositiveSuffix;
}
int begin = (int)buf.length();
buf.append(*affix);
int offset = (int) (*affix).indexOf(getConstSymbol(DecimalFormatSymbols::kCurrencySymbol));
if (offset > -1) {
UnicodeString aff = getConstSymbol(DecimalFormatSymbols::kCurrencySymbol);
addAttribute(attrBuffer, "currency", begin + offset, begin + offset + aff.length());
}
offset = (int) (*affix).indexOf(getConstSymbol(DecimalFormatSymbols::kIntlCurrencySymbol));
if (offset > -1) {
UnicodeString aff = getConstSymbol(DecimalFormatSymbols::kIntlCurrencySymbol);
addAttribute(attrBuffer, "currency", begin + offset, begin + offset + aff.length());
}
offset = (int) (*affix).indexOf(getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol));
if (offset > -1) {
UnicodeString aff = getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol);
addAttribute(attrBuffer, "sign", begin + offset, begin + offset + aff.length());
}
offset = (int) (*affix).indexOf(getConstSymbol(DecimalFormatSymbols::kPercentSymbol));
if (offset > -1) {
UnicodeString aff = getConstSymbol(DecimalFormatSymbols::kPercentSymbol);
addAttribute(attrBuffer, "percent", begin + offset, begin + offset + aff.length());
}
offset = (int) (*affix).indexOf(getConstSymbol(DecimalFormatSymbols::kPerMillSymbol));
if (offset > -1) {
UnicodeString aff = getConstSymbol(DecimalFormatSymbols::kPerMillSymbol);
addAttribute(attrBuffer, "permille", begin + offset, begin + offset + aff.length());
}
return affix->length();
}
/**
* Appends an affix pattern to the given StringBuffer, quoting special
* characters as needed. Uses the internal affix pattern, if that exists,
* or the literal affix, if the internal affix pattern is null. The
* appended string will generate the same affix pattern (or literal affix)
* when passed to toPattern().
*
* @param appendTo the affix string is appended to this
* @param affixPattern a pattern such as fPosPrefixPattern; may be null
* @param expAffix a corresponding expanded affix, such as fPositivePrefix.
* Ignored unless affixPattern is null. If affixPattern is null, then
* expAffix is appended as a literal affix.
* @param localized true if the appended pattern should contain localized
* pattern characters; otherwise, non-localized pattern chars are appended
*/
void DecimalFormat::appendAffixPattern(UnicodeString& appendTo,
const UnicodeString* affixPattern,
const UnicodeString& expAffix,
UBool localized) const {
if (affixPattern == 0) {
appendAffixPattern(appendTo, expAffix, localized);
} else {
int i;
for (int pos=0; pos<affixPattern->length(); pos=i) {
i = affixPattern->indexOf(kQuote, pos);
if (i < 0) {
UnicodeString s;
affixPattern->extractBetween(pos, affixPattern->length(), s);
appendAffixPattern(appendTo, s, localized);
break;
}
if (i > pos) {
UnicodeString s;
affixPattern->extractBetween(pos, i, s);
appendAffixPattern(appendTo, s, localized);
}
UChar32 c = affixPattern->char32At(++i);
++i;
if (c == kQuote) {
appendTo.append(c).append(c);
// Fall through and append another kQuote below
} else if (c == kCurrencySign &&
i<affixPattern->length() &&
affixPattern->char32At(i) == kCurrencySign) {
++i;
appendTo.append(c).append(c);
} else if (localized) {
switch (c) {
case kPatternPercent:
appendTo += getConstSymbol(DecimalFormatSymbols::kPercentSymbol);
break;
case kPatternPerMill:
appendTo += getConstSymbol(DecimalFormatSymbols::kPerMillSymbol);
break;
case kPatternPlus:
appendTo += getConstSymbol(DecimalFormatSymbols::kPlusSignSymbol);
break;
case kPatternMinus:
appendTo += getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol);
break;
default:
appendTo.append(c);
}
} else {
appendTo.append(c);
}
}
}
}
/**
* Append an affix to the given StringBuffer, using quotes if
* there are special characters. Single quotes themselves must be
* escaped in either case.
*/
void
DecimalFormat::appendAffixPattern(UnicodeString& appendTo,
const UnicodeString& affix,
UBool localized) const {
UBool needQuote;
if(localized) {
needQuote = affix.indexOf(getConstSymbol(DecimalFormatSymbols::kZeroDigitSymbol)) >= 0
|| affix.indexOf(getConstSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol)) >= 0
|| affix.indexOf(getConstSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol)) >= 0
|| affix.indexOf(getConstSymbol(DecimalFormatSymbols::kPercentSymbol)) >= 0
|| affix.indexOf(getConstSymbol(DecimalFormatSymbols::kPerMillSymbol)) >= 0
|| affix.indexOf(getConstSymbol(DecimalFormatSymbols::kDigitSymbol)) >= 0
|| affix.indexOf(getConstSymbol(DecimalFormatSymbols::kPatternSeparatorSymbol)) >= 0
|| affix.indexOf(getConstSymbol(DecimalFormatSymbols::kPlusSignSymbol)) >= 0
|| affix.indexOf(getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol)) >= 0
|| affix.indexOf(kCurrencySign) >= 0;
}
else {
needQuote = affix.indexOf(kPatternZeroDigit) >= 0
|| affix.indexOf(kPatternGroupingSeparator) >= 0
|| affix.indexOf(kPatternDecimalSeparator) >= 0
|| affix.indexOf(kPatternPercent) >= 0
|| affix.indexOf(kPatternPerMill) >= 0
|| affix.indexOf(kPatternDigit) >= 0
|| affix.indexOf(kPatternSeparator) >= 0
|| affix.indexOf(kPatternExponent) >= 0
|| affix.indexOf(kPatternPlus) >= 0
|| affix.indexOf(kPatternMinus) >= 0
|| affix.indexOf(kCurrencySign) >= 0;
}
if (needQuote)
appendTo += (UChar)0x0027 /*'\''*/;
if (affix.indexOf((UChar)0x0027 /*'\''*/) < 0)
appendTo += affix;
else {
for (int32_t j = 0; j < affix.length(); ) {
UChar32 c = affix.char32At(j);
j += U16_LENGTH(c);
appendTo += c;
if (c == 0x0027 /*'\''*/)
appendTo += c;
}
}
if (needQuote)
appendTo += (UChar)0x0027 /*'\''*/;
}
//------------------------------------------------------------------------------
UnicodeString&
DecimalFormat::toPattern(UnicodeString& result, UBool localized) const
{
result.remove();
UChar32 zero, sigDigit = kPatternSignificantDigit;
UnicodeString digit, group;
int32_t i;
int32_t roundingDecimalPos = 0; // Pos of decimal in roundingDigits
UnicodeString roundingDigits;
int32_t padPos = (fFormatWidth > 0) ? fPadPosition : -1;
UnicodeString padSpec;
UBool useSigDig = areSignificantDigitsUsed();
if (localized) {
digit.append(getConstSymbol(DecimalFormatSymbols::kDigitSymbol));
group.append(getConstSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol));
zero = getConstSymbol(DecimalFormatSymbols::kZeroDigitSymbol).char32At(0);
if (useSigDig) {
sigDigit = getConstSymbol(DecimalFormatSymbols::kSignificantDigitSymbol).char32At(0);
}
}
else {
digit.append((UChar)kPatternDigit);
group.append((UChar)kPatternGroupingSeparator);
zero = (UChar32)kPatternZeroDigit;
}
if (fFormatWidth > 0) {
if (localized) {
padSpec.append(getConstSymbol(DecimalFormatSymbols::kPadEscapeSymbol));
}
else {
padSpec.append((UChar)kPatternPadEscape);
}
padSpec.append(fPad);
}
if (fRoundingIncrement != NULL) {
for(i=0; i<fRoundingIncrement->fCount; ++i) {
roundingDigits.append((UChar)fRoundingIncrement->fDigits[i]);
}
roundingDecimalPos = fRoundingIncrement->fDecimalAt;
}
for (int32_t part=0; part<2; ++part) {
if (padPos == kPadBeforePrefix) {
result.append(padSpec);
}
appendAffixPattern(result,
(part==0 ? fPosPrefixPattern : fNegPrefixPattern),
(part==0 ? fPositivePrefix : fNegativePrefix),
localized);
if (padPos == kPadAfterPrefix && ! padSpec.isEmpty()) {
result.append(padSpec);
}
int32_t sub0Start = result.length();
int32_t g = isGroupingUsed() ? _max(0, fGroupingSize) : 0;
if (g > 0 && fGroupingSize2 > 0 && fGroupingSize2 != fGroupingSize) {
g += fGroupingSize2;
}
int32_t maxDig = 0, minDig = 0, maxSigDig = 0;
if (useSigDig) {
minDig = getMinimumSignificantDigits();
maxDig = maxSigDig = getMaximumSignificantDigits();
} else {
minDig = getMinimumIntegerDigits();
maxDig = getMaximumIntegerDigits();
}
if (fUseExponentialNotation) {
if (maxDig > kMaxScientificIntegerDigits) {
maxDig = 1;
}
} else if (useSigDig) {
maxDig = _max(maxDig, g+1);
} else {
maxDig = _max(_max(g, getMinimumIntegerDigits()),
roundingDecimalPos) + 1;
}
for (i = maxDig; i > 0; --i) {
if (!fUseExponentialNotation && i<maxDig &&
isGroupingPosition(i)) {
result.append(group);
}
if (useSigDig) {
// #@,@### (maxSigDig == 5, minSigDig == 2)
// 65 4321 (1-based pos, count from the right)
// Use # if pos > maxSigDig or 1 <= pos <= (maxSigDig - minSigDig)
// Use @ if (maxSigDig - minSigDig) < pos <= maxSigDig
if (maxSigDig >= i && i > (maxSigDig - minDig)) {
result.append(sigDigit);
} else {
result.append(digit);
}
} else {
if (! roundingDigits.isEmpty()) {
int32_t pos = roundingDecimalPos - i;
if (pos >= 0 && pos < roundingDigits.length()) {
result.append((UChar) (roundingDigits.char32At(pos) - kPatternZeroDigit + zero));
continue;
}
}
if (i<=minDig) {
result.append(zero);
} else {
result.append(digit);
}
}
}
if (!useSigDig) {
if (getMaximumFractionDigits() > 0 || fDecimalSeparatorAlwaysShown) {
if (localized) {
result += getConstSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol);
}
else {
result.append((UChar)kPatternDecimalSeparator);
}
}
int32_t pos = roundingDecimalPos;
for (i = 0; i < getMaximumFractionDigits(); ++i) {
if (! roundingDigits.isEmpty() && pos < roundingDigits.length()) {
if (pos < 0) {
result.append(zero);
}
else {
result.append((UChar)(roundingDigits.char32At(pos) - kPatternZeroDigit + zero));
}
++pos;
continue;
}
if (i<getMinimumFractionDigits()) {
result.append(zero);
}
else {
result.append(digit);
}
}
}
if (fUseExponentialNotation) {
if (localized) {
result += getConstSymbol(DecimalFormatSymbols::kExponentialSymbol);
}
else {
result.append((UChar)kPatternExponent);
}
if (fExponentSignAlwaysShown) {
if (localized) {
result += getConstSymbol(DecimalFormatSymbols::kPlusSignSymbol);
}
else {
result.append((UChar)kPatternPlus);
}
}
for (i=0; i<fMinExponentDigits; ++i) {
result.append(zero);
}
}
if (! padSpec.isEmpty() && !fUseExponentialNotation) {
int32_t add = fFormatWidth - result.length() + sub0Start
- ((part == 0)
? fPositivePrefix.length() + fPositiveSuffix.length()
: fNegativePrefix.length() + fNegativeSuffix.length());
while (add > 0) {
result.insert(sub0Start, digit);
++maxDig;
--add;
// Only add a grouping separator if we have at least
// 2 additional characters to be added, so we don't
// end up with ",###".
if (add>1 && isGroupingPosition(maxDig)) {
result.insert(sub0Start, group);
--add;
}
}
}
if (fPadPosition == kPadBeforeSuffix && ! padSpec.isEmpty()) {
result.append(padSpec);
}
if (part == 0) {
appendAffixPattern(result, fPosSuffixPattern, fPositiveSuffix, localized);
if (fPadPosition == kPadAfterSuffix && ! padSpec.isEmpty()) {
result.append(padSpec);
}
UBool isDefault = FALSE;
if ((fNegSuffixPattern == fPosSuffixPattern && // both null
fNegativeSuffix == fPositiveSuffix)
|| (fNegSuffixPattern != 0 && fPosSuffixPattern != 0 &&
*fNegSuffixPattern == *fPosSuffixPattern))
{
if (fNegPrefixPattern != NULL && fPosPrefixPattern != NULL)
{
int32_t length = fPosPrefixPattern->length();
isDefault = fNegPrefixPattern->length() == (length+2) &&
(*fNegPrefixPattern)[(int32_t)0] == kQuote &&
(*fNegPrefixPattern)[(int32_t)1] == kPatternMinus &&
fNegPrefixPattern->compare(2, length, *fPosPrefixPattern, 0, length) == 0;
}
if (!isDefault &&
fNegPrefixPattern == NULL && fPosPrefixPattern == NULL)
{
int32_t length = fPositivePrefix.length();
isDefault = fNegativePrefix.length() == (length+1) &&
fNegativePrefix.compare(getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol)) == 0 &&
fNegativePrefix.compare(1, length, fPositivePrefix, 0, length) == 0;
}
}
if (isDefault) {
break; // Don't output default negative subpattern
} else {
if (localized) {
result += getConstSymbol(DecimalFormatSymbols::kPatternSeparatorSymbol);
}
else {
result.append((UChar)kPatternSeparator);
}
}
} else {
appendAffixPattern(result, fNegSuffixPattern, fNegativeSuffix, localized);
if (fPadPosition == kPadAfterSuffix && ! padSpec.isEmpty()) {
result.append(padSpec);
}
}
}
return result;
}
//------------------------------------------------------------------------------
void
DecimalFormat::applyPattern(const UnicodeString& pattern, UErrorCode& status)
{
UParseError parseError;
applyPattern(pattern, FALSE, parseError, status);
}
//------------------------------------------------------------------------------
void
DecimalFormat::applyPattern(const UnicodeString& pattern,
UParseError& parseError,
UErrorCode& status)
{
applyPattern(pattern, FALSE, parseError, status);
}
//------------------------------------------------------------------------------
void
DecimalFormat::applyLocalizedPattern(const UnicodeString& pattern, UErrorCode& status)
{
UParseError parseError;
applyPattern(pattern, TRUE,parseError,status);
}
//------------------------------------------------------------------------------
void
DecimalFormat::applyLocalizedPattern(const UnicodeString& pattern,
UParseError& parseError,
UErrorCode& status)
{
applyPattern(pattern, TRUE,parseError,status);
}
//------------------------------------------------------------------------------
void
DecimalFormat::applyPattern(const UnicodeString& pattern,
UBool localized,
UParseError& parseError,
UErrorCode& status)
{
if (U_FAILURE(status))
{
return;
}
// Clear error struct
parseError.offset = -1;
parseError.preContext[0] = parseError.postContext[0] = (UChar)0;
// Set the significant pattern symbols
UChar32 zeroDigit = kPatternZeroDigit; // '0'
UChar32 sigDigit = kPatternSignificantDigit; // '@'
UnicodeString groupingSeparator ((UChar)kPatternGroupingSeparator);
UnicodeString decimalSeparator ((UChar)kPatternDecimalSeparator);
UnicodeString percent ((UChar)kPatternPercent);
UnicodeString perMill ((UChar)kPatternPerMill);
UnicodeString digit ((UChar)kPatternDigit); // '#'
UnicodeString separator ((UChar)kPatternSeparator);
UnicodeString exponent ((UChar)kPatternExponent);
UnicodeString plus ((UChar)kPatternPlus);
UnicodeString minus ((UChar)kPatternMinus);
UnicodeString padEscape ((UChar)kPatternPadEscape);
// Substitute with the localized symbols if necessary
if (localized) {
zeroDigit = getConstSymbol(DecimalFormatSymbols::kZeroDigitSymbol).char32At(0);
sigDigit = getConstSymbol(DecimalFormatSymbols::kSignificantDigitSymbol).char32At(0);
groupingSeparator. remove().append(getConstSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol));
decimalSeparator. remove().append(getConstSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol));
percent. remove().append(getConstSymbol(DecimalFormatSymbols::kPercentSymbol));
perMill. remove().append(getConstSymbol(DecimalFormatSymbols::kPerMillSymbol));
digit. remove().append(getConstSymbol(DecimalFormatSymbols::kDigitSymbol));
separator. remove().append(getConstSymbol(DecimalFormatSymbols::kPatternSeparatorSymbol));
exponent. remove().append(getConstSymbol(DecimalFormatSymbols::kExponentialSymbol));
plus. remove().append(getConstSymbol(DecimalFormatSymbols::kPlusSignSymbol));
minus. remove().append(getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol));
padEscape. remove().append(getConstSymbol(DecimalFormatSymbols::kPadEscapeSymbol));
}
UChar nineDigit = (UChar)(zeroDigit + 9);
int32_t digitLen = digit.length();
int32_t groupSepLen = groupingSeparator.length();
int32_t decimalSepLen = decimalSeparator.length();
int32_t pos = 0;
int32_t patLen = pattern.length();
// Part 0 is the positive pattern. Part 1, if present, is the negative
// pattern.
for (int32_t part=0; part<2 && pos<patLen; ++part) {
// The subpart ranges from 0 to 4: 0=pattern proper, 1=prefix,
// 2=suffix, 3=prefix in quote, 4=suffix in quote. Subpart 0 is
// between the prefix and suffix, and consists of pattern
// characters. In the prefix and suffix, percent, perMill, and
// currency symbols are recognized and translated.
int32_t subpart = 1, sub0Start = 0, sub0Limit = 0, sub2Limit = 0;
// It's important that we don't change any fields of this object
// prematurely. We set the following variables for the multiplier,
// grouping, etc., and then only change the actual object fields if
// everything parses correctly. This also lets us register
// the data from part 0 and ignore the part 1, except for the
// prefix and suffix.
UnicodeString prefix;
UnicodeString suffix;
int32_t decimalPos = -1;
int32_t multiplier = 1;
int32_t digitLeftCount = 0, zeroDigitCount = 0, digitRightCount = 0, sigDigitCount = 0;
int8_t groupingCount = -1;
int8_t groupingCount2 = -1;
int32_t padPos = -1;
UChar32 padChar = 0;
int32_t roundingPos = -1;
DigitList roundingInc;
int8_t expDigits = -1;
UBool expSignAlways = FALSE;
UBool isCurrency = FALSE;
// The affix is either the prefix or the suffix.
UnicodeString* affix = &prefix;
int32_t start = pos;
UBool isPartDone = FALSE;
UChar32 ch;
for (; !isPartDone && pos < patLen; ) {
// Todo: account for surrogate pairs
ch = pattern.char32At(pos);
switch (subpart) {
case 0: // Pattern proper subpart (between prefix & suffix)
// Process the digits, decimal, and grouping characters. We
// record five pieces of information. We expect the digits
// to occur in the pattern ####00.00####, and we record the
// number of left digits, zero (central) digits, and right
// digits. The position of the last grouping character is
// recorded (should be somewhere within the first two blocks
// of characters), as is the position of the decimal point,
// if any (should be in the zero digits). If there is no
// decimal point, then there should be no right digits.
if (pattern.compare(pos, digitLen, digit) == 0) {
if (zeroDigitCount > 0 || sigDigitCount > 0) {
++digitRightCount;
} else {
++digitLeftCount;
}
if (groupingCount >= 0 && decimalPos < 0) {
++groupingCount;
}
pos += digitLen;
} else if ((ch >= zeroDigit && ch <= nineDigit) ||
ch == sigDigit) {
if (digitRightCount > 0) {
// Unexpected '0'
debug("Unexpected '0'")
status = U_UNEXPECTED_TOKEN;
syntaxError(pattern,pos,parseError);
return;
}
if (ch == sigDigit) {
++sigDigitCount;
} else {
++zeroDigitCount;
if (ch != zeroDigit && roundingPos < 0) {
roundingPos = digitLeftCount + zeroDigitCount;
}
if (roundingPos >= 0) {
roundingInc.append((char)(ch - zeroDigit + '0'));
}
}
if (groupingCount >= 0 && decimalPos < 0) {
++groupingCount;
}
pos += U16_LENGTH(ch);
} else if (pattern.compare(pos, groupSepLen, groupingSeparator) == 0) {
if (decimalPos >= 0) {
// Grouping separator after decimal
debug("Grouping separator after decimal")
status = U_UNEXPECTED_TOKEN;
syntaxError(pattern,pos,parseError);
return;
}
groupingCount2 = groupingCount;
groupingCount = 0;
pos += groupSepLen;
} else if (pattern.compare(pos, decimalSepLen, decimalSeparator) == 0) {
if (decimalPos >= 0) {
// Multiple decimal separators
debug("Multiple decimal separators")
status = U_MULTIPLE_DECIMAL_SEPARATORS;
syntaxError(pattern,pos,parseError);
return;
}
// Intentionally incorporate the digitRightCount,
// even though it is illegal for this to be > 0
// at this point. We check pattern syntax below.
decimalPos = digitLeftCount + zeroDigitCount + digitRightCount;
pos += decimalSepLen;
} else {
if (pattern.compare(pos, exponent.length(), exponent) == 0) {
if (expDigits >= 0) {
// Multiple exponential symbols
debug("Multiple exponential symbols")
status = U_MULTIPLE_EXPONENTIAL_SYMBOLS;
syntaxError(pattern,pos,parseError);
return;
}
if (groupingCount >= 0) {
// Grouping separator in exponential pattern
debug("Grouping separator in exponential pattern")
status = U_MALFORMED_EXPONENTIAL_PATTERN;
syntaxError(pattern,pos,parseError);
return;
}
pos += exponent.length();
// Check for positive prefix
if (pos < patLen
&& pattern.compare(pos, plus.length(), plus) == 0) {
expSignAlways = TRUE;
pos += plus.length();
}
// Use lookahead to parse out the exponential part of the
// pattern, then jump into suffix subpart.
expDigits = 0;
while (pos < patLen &&
pattern.char32At(pos) == zeroDigit) {
++expDigits;
pos += U16_LENGTH(zeroDigit);
}
// 1. Require at least one mantissa pattern digit
// 2. Disallow "#+ @" in mantissa
// 3. Require at least one exponent pattern digit
if (((digitLeftCount + zeroDigitCount) < 1 &&
(sigDigitCount + digitRightCount) < 1) ||
(sigDigitCount > 0 && digitLeftCount > 0) ||
expDigits < 1) {
// Malformed exponential pattern
debug("Malformed exponential pattern")
status = U_MALFORMED_EXPONENTIAL_PATTERN;
syntaxError(pattern,pos,parseError);
return;
}
}
// Transition to suffix subpart
subpart = 2; // suffix subpart
affix = &suffix;
sub0Limit = pos;
continue;
}
break;
case 1: // Prefix subpart
case 2: // Suffix subpart
// Process the prefix / suffix characters
// Process unquoted characters seen in prefix or suffix
// subpart.
// Several syntax characters implicitly begins the
// next subpart if we are in the prefix; otherwise
// they are illegal if unquoted.
if (!pattern.compare(pos, digitLen, digit) ||
!pattern.compare(pos, groupSepLen, groupingSeparator) ||
!pattern.compare(pos, decimalSepLen, decimalSeparator) ||
(ch >= zeroDigit && ch <= nineDigit) ||
ch == sigDigit) {
if (subpart == 1) { // prefix subpart
subpart = 0; // pattern proper subpart
sub0Start = pos; // Reprocess this character
continue;
} else {
status = U_UNQUOTED_SPECIAL;
syntaxError(pattern,pos,parseError);
return;
}
} else if (ch == kCurrencySign) {
affix->append(kQuote); // Encode currency
// Use lookahead to determine if the currency sign is
// doubled or not.
U_ASSERT(U16_LENGTH(kCurrencySign) == 1);
if ((pos+1) < pattern.length() && pattern[pos+1] == kCurrencySign) {
affix->append(kCurrencySign);
++pos; // Skip over the doubled character
}
isCurrency = TRUE;
// Fall through to append(ch)
} else if (ch == kQuote) {
// A quote outside quotes indicates either the opening
// quote or two quotes, which is a quote literal. That is,
// we have the first quote in 'do' or o''clock.
U_ASSERT(U16_LENGTH(kQuote) == 1);
++pos;
if (pos < pattern.length() && pattern[pos] == kQuote) {
affix->append(kQuote); // Encode quote
// Fall through to append(ch)
} else {
subpart += 2; // open quote
continue;
}
} else if (pattern.compare(pos, separator.length(), separator) == 0) {
// Don't allow separators in the prefix, and don't allow
// separators in the second pattern (part == 1).
if (subpart == 1 || part == 1) {
// Unexpected separator
debug("Unexpected separator")
status = U_UNEXPECTED_TOKEN;
syntaxError(pattern,pos,parseError);
return;
}
sub2Limit = pos;
isPartDone = TRUE; // Go to next part
pos += separator.length();
break;
} else if (pattern.compare(pos, percent.length(), percent) == 0) {
// Next handle characters which are appended directly.
if (multiplier != 1) {
// Too many percent/perMill characters
debug("Too many percent characters")
status = U_MULTIPLE_PERCENT_SYMBOLS;
syntaxError(pattern,pos,parseError);
return;
}
affix->append(kQuote); // Encode percent/perMill
affix->append(kPatternPercent); // Use unlocalized pattern char
multiplier = 100;
pos += percent.length();
break;
} else if (pattern.compare(pos, perMill.length(), perMill) == 0) {
// Next handle characters which are appended directly.
if (multiplier != 1) {
// Too many percent/perMill characters
debug("Too many perMill characters")
status = U_MULTIPLE_PERMILL_SYMBOLS;
syntaxError(pattern,pos,parseError);
return;
}
affix->append(kQuote); // Encode percent/perMill
affix->append(kPatternPerMill); // Use unlocalized pattern char
multiplier = 1000;
pos += perMill.length();
break;
} else if (pattern.compare(pos, padEscape.length(), padEscape) == 0) {
if (padPos >= 0 || // Multiple pad specifiers
(pos+1) == pattern.length()) { // Nothing after padEscape
debug("Multiple pad specifiers")
status = U_MULTIPLE_PAD_SPECIFIERS;
syntaxError(pattern,pos,parseError);
return;
}
padPos = pos;
pos += padEscape.length();
padChar = pattern.char32At(pos);
pos += U16_LENGTH(padChar);
break;
} else if (pattern.compare(pos, minus.length(), minus) == 0) {
affix->append(kQuote); // Encode minus
affix->append(kPatternMinus);
pos += minus.length();
break;
} else if (pattern.compare(pos, plus.length(), plus) == 0) {
affix->append(kQuote); // Encode plus
affix->append(kPatternPlus);
pos += plus.length();
break;
}
// Unquoted, non-special characters fall through to here, as
// well as other code which needs to append something to the
// affix.
affix->append(ch);
pos += U16_LENGTH(ch);
break;
case 3: // Prefix subpart, in quote
case 4: // Suffix subpart, in quote
// A quote within quotes indicates either the closing
// quote or two quotes, which is a quote literal. That is,
// we have the second quote in 'do' or 'don''t'.
if (ch == kQuote) {
++pos;
if (pos < pattern.length() && pattern[pos] == kQuote) {
affix->append(kQuote); // Encode quote
// Fall through to append(ch)
} else {
subpart -= 2; // close quote
continue;
}
}
affix->append(ch);
pos += U16_LENGTH(ch);
break;
}
}
if (sub0Limit == 0) {
sub0Limit = pattern.length();
}
if (sub2Limit == 0) {
sub2Limit = pattern.length();
}
/* Handle patterns with no '0' pattern character. These patterns
* are legal, but must be recodified to make sense. "##.###" ->
* "#0.###". ".###" -> ".0##".
*
* We allow patterns of the form "####" to produce a zeroDigitCount
* of zero (got that?); although this seems like it might make it
* possible for format() to produce empty strings, format() checks
* for this condition and outputs a zero digit in this situation.
* Having a zeroDigitCount of zero yields a minimum integer digits
* of zero, which allows proper round-trip patterns. We don't want
* "#" to become "#0" when toPattern() is called (even though that's
* what it really is, semantically).
*/
if (zeroDigitCount == 0 && sigDigitCount == 0 &&
digitLeftCount > 0 && decimalPos >= 0) {
// Handle "###.###" and "###." and ".###"
int n = decimalPos;
if (n == 0)
++n; // Handle ".###"
digitRightCount = digitLeftCount - n;
digitLeftCount = n - 1;
zeroDigitCount = 1;
}
// Do syntax checking on the digits, decimal points, and quotes.
if ((decimalPos < 0 && digitRightCount > 0 && sigDigitCount == 0) ||
(decimalPos >= 0 &&
(sigDigitCount > 0 ||
decimalPos < digitLeftCount ||
decimalPos > (digitLeftCount + zeroDigitCount))) ||
groupingCount == 0 || groupingCount2 == 0 ||
(sigDigitCount > 0 && zeroDigitCount > 0) ||
subpart > 2)
{ // subpart > 2 == unmatched quote
debug("Syntax error")
status = U_PATTERN_SYNTAX_ERROR;
syntaxError(pattern,pos,parseError);
return;
}
// Make sure pad is at legal position before or after affix.
if (padPos >= 0) {
if (padPos == start) {
padPos = kPadBeforePrefix;
} else if (padPos+2 == sub0Start) {
padPos = kPadAfterPrefix;
} else if (padPos == sub0Limit) {
padPos = kPadBeforeSuffix;
} else if (padPos+2 == sub2Limit) {
padPos = kPadAfterSuffix;
} else {
// Illegal pad position
debug("Illegal pad position")
status = U_ILLEGAL_PAD_POSITION;
syntaxError(pattern,pos,parseError);
return;
}
}
if (part == 0) {
delete fPosPrefixPattern;
delete fPosSuffixPattern;
delete fNegPrefixPattern;
delete fNegSuffixPattern;
fPosPrefixPattern = new UnicodeString(prefix);
/* test for NULL */
if (fPosPrefixPattern == 0) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
fPosSuffixPattern = new UnicodeString(suffix);
/* test for NULL */
if (fPosSuffixPattern == 0) {
status = U_MEMORY_ALLOCATION_ERROR;
delete fPosPrefixPattern;
return;
}
fNegPrefixPattern = 0;
fNegSuffixPattern = 0;
fUseExponentialNotation = (expDigits >= 0);
if (fUseExponentialNotation) {
fMinExponentDigits = expDigits;
}
fExponentSignAlwaysShown = expSignAlways;
fIsCurrencyFormat = isCurrency;
int32_t digitTotalCount = digitLeftCount + zeroDigitCount + digitRightCount;
// The effectiveDecimalPos is the position the decimal is at or
// would be at if there is no decimal. Note that if
// decimalPos<0, then digitTotalCount == digitLeftCount +
// zeroDigitCount.
int32_t effectiveDecimalPos = decimalPos >= 0 ? decimalPos : digitTotalCount;
UBool isSigDig = (sigDigitCount > 0);
setSignificantDigitsUsed(isSigDig);
if (isSigDig) {
setMinimumSignificantDigits(sigDigitCount);
setMaximumSignificantDigits(sigDigitCount + digitRightCount);
} else {
int32_t minInt = effectiveDecimalPos - digitLeftCount;
setMinimumIntegerDigits(minInt);
setMaximumIntegerDigits(fUseExponentialNotation
? digitLeftCount + getMinimumIntegerDigits()
: kDoubleIntegerDigits);
setMaximumFractionDigits(decimalPos >= 0
? (digitTotalCount - decimalPos) : 0);
setMinimumFractionDigits(decimalPos >= 0
? (digitLeftCount + zeroDigitCount - decimalPos) : 0);
}
setGroupingUsed(groupingCount > 0);
fGroupingSize = (groupingCount > 0) ? groupingCount : 0;
fGroupingSize2 = (groupingCount2 > 0 && groupingCount2 != groupingCount)
? groupingCount2 : 0;
fMultiplier = multiplier;
setDecimalSeparatorAlwaysShown(decimalPos == 0
|| decimalPos == digitTotalCount);
if (padPos >= 0) {
fPadPosition = (EPadPosition) padPos;
// To compute the format width, first set up sub0Limit -
// sub0Start. Add in prefix/suffix length later.
// fFormatWidth = prefix.length() + suffix.length() +
// sub0Limit - sub0Start;
fFormatWidth = sub0Limit - sub0Start;
fPad = padChar;
} else {
fFormatWidth = 0;
}
if (roundingPos >= 0) {
roundingInc.fDecimalAt = effectiveDecimalPos - roundingPos;
if (fRoundingIncrement != NULL) {
*fRoundingIncrement = roundingInc;
} else {
fRoundingIncrement = new DigitList(roundingInc);
/* test for NULL */
if (fRoundingIncrement == 0) {
status = U_MEMORY_ALLOCATION_ERROR;
delete fPosPrefixPattern;
delete fPosSuffixPattern;
return;
}
}
fRoundingDouble = fRoundingIncrement->getDouble();
fRoundingMode = kRoundHalfEven;
} else {
setRoundingIncrement(0.0);
}
} else {
fNegPrefixPattern = new UnicodeString(prefix);
/* test for NULL */
if (fNegPrefixPattern == 0) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
fNegSuffixPattern = new UnicodeString(suffix);
/* test for NULL */
if (fNegSuffixPattern == 0) {
delete fNegPrefixPattern;
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
}
}
if (pattern.length() == 0) {
delete fNegPrefixPattern;
delete fNegSuffixPattern;
fNegPrefixPattern = NULL;
fNegSuffixPattern = NULL;
if (fPosPrefixPattern != NULL) {
fPosPrefixPattern->remove();
} else {
fPosPrefixPattern = new UnicodeString();
/* test for NULL */
if (fPosPrefixPattern == 0) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
}
if (fPosSuffixPattern != NULL) {
fPosSuffixPattern->remove();
} else {
fPosSuffixPattern = new UnicodeString();
/* test for NULL */
if (fPosSuffixPattern == 0) {
delete fPosPrefixPattern;
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
}
setMinimumIntegerDigits(0);
setMaximumIntegerDigits(kDoubleIntegerDigits);
setMinimumFractionDigits(0);
setMaximumFractionDigits(kDoubleFractionDigits);
fUseExponentialNotation = FALSE;
fIsCurrencyFormat = FALSE;
setGroupingUsed(FALSE);
fGroupingSize = 0;
fGroupingSize2 = 0;
fMultiplier = 1;
setDecimalSeparatorAlwaysShown(FALSE);
fFormatWidth = 0;
setRoundingIncrement(0.0);
}
// If there was no negative pattern, or if the negative pattern is
// identical to the positive pattern, then prepend the minus sign to the
// positive pattern to form the negative pattern.
if (fNegPrefixPattern == NULL ||
(*fNegPrefixPattern == *fPosPrefixPattern
&& *fNegSuffixPattern == *fPosSuffixPattern)) {
_copy_us_ptr(&fNegSuffixPattern, fPosSuffixPattern);
if (fNegPrefixPattern == NULL) {
fNegPrefixPattern = new UnicodeString();
/* test for NULL */
if (fNegPrefixPattern == 0) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
} else {
fNegPrefixPattern->remove();
}
fNegPrefixPattern->append(kQuote).append(kPatternMinus)
.append(*fPosPrefixPattern);
}
#ifdef FMT_DEBUG
UnicodeString s;
s.append("\"").append(pattern).append("\"->");
debugout(s);
#endif
expandAffixes();
if (fFormatWidth > 0) {
// Finish computing format width (see above)
fFormatWidth += fPositivePrefix.length() + fPositiveSuffix.length();
}
}
/**
* Sets the maximum number of digits allowed in the integer portion of a
* number. This override limits the integer digit count to 309.
* @see NumberFormat#setMaximumIntegerDigits
*/
void DecimalFormat::setMaximumIntegerDigits(int32_t newValue) {
NumberFormat::setMaximumIntegerDigits(_min(newValue, kDoubleIntegerDigits));
}
/**
* Sets the minimum number of digits allowed in the integer portion of a
* number. This override limits the integer digit count to 309.
* @see NumberFormat#setMinimumIntegerDigits
*/
void DecimalFormat::setMinimumIntegerDigits(int32_t newValue) {
NumberFormat::setMinimumIntegerDigits(_min(newValue, kDoubleIntegerDigits));
}
/**
* Sets the maximum number of digits allowed in the fraction portion of a
* number. This override limits the fraction digit count to 340.
* @see NumberFormat#setMaximumFractionDigits
*/
void DecimalFormat::setMaximumFractionDigits(int32_t newValue) {
NumberFormat::setMaximumFractionDigits(_min(newValue, kDoubleFractionDigits));
}
/**
* Sets the minimum number of digits allowed in the fraction portion of a
* number. This override limits the fraction digit count to 340.
* @see NumberFormat#setMinimumFractionDigits
*/
void DecimalFormat::setMinimumFractionDigits(int32_t newValue) {
NumberFormat::setMinimumFractionDigits(_min(newValue, kDoubleFractionDigits));
}
int32_t DecimalFormat::getMinimumSignificantDigits() const {
return fMinSignificantDigits;
}
int32_t DecimalFormat::getMaximumSignificantDigits() const {
return fMaxSignificantDigits;
}
void DecimalFormat::setMinimumSignificantDigits(int32_t min) {
if (min < 1) {
min = 1;
}
// pin max sig dig to >= min
int32_t max = _max(fMaxSignificantDigits, min);
fMinSignificantDigits = min;
fMaxSignificantDigits = max;
}
void DecimalFormat::setMaximumSignificantDigits(int32_t max) {
if (max < 1) {
max = 1;
}
// pin min sig dig to 1..max
U_ASSERT(fMinSignificantDigits >= 1);
int32_t min = _min(fMinSignificantDigits, max);
fMinSignificantDigits = min;
fMaxSignificantDigits = max;
}
UBool DecimalFormat::areSignificantDigitsUsed() const {
return fUseSignificantDigits;
}
void DecimalFormat::setSignificantDigitsUsed(UBool useSignificantDigits) {
fUseSignificantDigits = useSignificantDigits;
}
void DecimalFormat::setCurrency(const UChar* theCurrency, UErrorCode& ec) {
// If we are a currency format, then modify our affixes to
// encode the currency symbol for the given currency in our
// locale, and adjust the decimal digits and rounding for the
// given currency.
// Note: The code is ordered so that this object is *not changed*
// until we are sure we are going to succeed.
// NULL or empty currency is *legal* and indicates no currency.
UBool isCurr = (theCurrency && *theCurrency);
double rounding = 0.0;
int32_t frac = 0;
if (fIsCurrencyFormat && isCurr) {
rounding = ucurr_getRoundingIncrement(theCurrency, &ec);
frac = ucurr_getDefaultFractionDigits(theCurrency, &ec);
}
NumberFormat::setCurrency(theCurrency, ec);
if (U_FAILURE(ec)) return;
if (fIsCurrencyFormat) {
// NULL or empty currency is *legal* and indicates no currency.
if (isCurr) {
setRoundingIncrement(rounding);
setMinimumFractionDigits(frac);
setMaximumFractionDigits(frac);
}
expandAffixes();
}
}
// Deprecated variant with no UErrorCode parameter
void DecimalFormat::setCurrency(const UChar* theCurrency) {
UErrorCode ec = U_ZERO_ERROR;
setCurrency(theCurrency, ec);
}
void DecimalFormat::getEffectiveCurrency(UChar* result, UErrorCode& /*ec*/) const {
const UChar* c = getCurrency();
if (*c == 0) {
const UnicodeString &intl =
fSymbols->getConstSymbol(DecimalFormatSymbols::kIntlCurrencySymbol);
c = intl.getBuffer(); // ok for intl to go out of scope
}
u_strncpy(result, c, 3);
result[3] = 0;
}
/**
* Return the number of fraction digits to display, or the total
* number of digits for significant digit formats and exponential
* formats.
*/
int32_t
DecimalFormat::precision(UBool isIntegral) const {
if (areSignificantDigitsUsed()) {
return getMaximumSignificantDigits();
} else if (fUseExponentialNotation) {
return getMinimumIntegerDigits() + getMaximumFractionDigits();
} else {
return isIntegral ? 0 : getMaximumFractionDigits();
}
}
void DecimalFormat::addAttribute(AttrBuffer attrBuffer, char *fieldname,
int begin, int end) const {
if(attrBuffer == NULL || begin == end) {
return;
}
char * tmp;
tmp = attrBuffer->buffer;
if((128 + strlen(attrBuffer->buffer)) > attrBuffer->bufferSize) {
attrBuffer->bufferSize = 2 * attrBuffer->bufferSize;
attrBuffer->buffer =
(char *) malloc(attrBuffer->bufferSize * sizeof(char));
attrBuffer->buffer[0] = '\0';
sprintf(attrBuffer->buffer,"%s;%s;%d;%d", tmp, fieldname, begin, end);
free(tmp);
return;
}
sprintf(attrBuffer->buffer,"%s;%s;%d;%d", tmp, fieldname, begin, end);
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
//eof
| [
"beyounn@8848914e-2522-11de-9896-099eabac0e35"
] | beyounn@8848914e-2522-11de-9896-099eabac0e35 |
407a4095856975df76f7958b655b9d009be0e39c | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/inetsrv/query/filters/html/source/specchar.cxx | 3cae1a33bbd3026190a362b20473ac97fe0d9546 | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 12,306 | cxx | //+---------------------------------------------------------------------------
//
// Copyright (C) 2002 - 2002 Microsoft Corporation.
//
// File: specchar.cxx
//
// Contents: Table that maps special characters to Unicode
//
// Classes: CSpecialCharTable
//
//----------------------------------------------------------------------------
#include <pch.cxx>
#pragma hdrstop
struct SStringCharEntry
{
WCHAR const * pwcString;
WCHAR wcChar;
};
const SStringCharEntry g_aCharMap[] =
{
{ L"AElig", 0xC6 },
{ L"AMP", 0x26 },
{ L"Aacute", 0xC1 },
{ L"Abreve", 0x102 },
{ L"Acirc", 0xC2 },
{ L"Agrave", 0xC0 },
{ L"Alpha", 913 },
{ L"Amacr", 0x100 },
{ L"Aogon", 0x104 },
{ L"Aring", 0xC5 },
{ L"Atilde", 0xC3 },
{ L"Auml", 0xC4 },
{ L"Beta", 914 },
{ L"COPY", 0xA9 },
{ L"Cacute", 0x106 },
{ L"Ccaron", 0x10C },
{ L"Ccedil", 0xC7 },
{ L"Ccirc", 0x108 },
{ L"Cdot", 0x10A },
{ L"Chi", 935 },
{ L"Dagger", 8225 },
{ L"Dcaron", 0x10E },
{ L"Delta", 916 },
{ L"Dstrok", 0x110 },
{ L"ENG", 0x14A },
{ L"ETH", 0xD0 },
{ L"Eacute", 0xC9 },
{ L"Ebreve", 0x114 },
{ L"Ecaron", 0x11A },
{ L"Ecirc", 0xCA },
{ L"Edot", 0x116 },
{ L"Egrave", 0xC8 },
{ L"Emacr", 0x112 },
{ L"Eogon", 0x118 },
{ L"Epsilon", 917 },
{ L"Eta", 919 },
{ L"Euml", 0xCB },
{ L"GT", PRIVATE_USE_MAPPING_FOR_GT },
{ L"Gamma", 915 },
{ L"Gbreve", 0x11E },
{ L"Gcedil", 0x122 },
{ L"Gcirc", 0x11C },
{ L"Gdot", 0x120 },
{ L"Iacute", 0xCD },
{ L"Icirc", 0xCE },
{ L"Idot", 0x130 },
{ L"Igrave", 0xCC },
{ L"Imacr", 0x12A },
{ L"Iogon", 0x12E },
{ L"Iota", 921 },
{ L"Itilde", 0x128 },
{ L"Iuml", 0xCF },
{ L"Kappa", 922 },
{ L"Kcedil", 0x136 },
{ L"LT", PRIVATE_USE_MAPPING_FOR_LT },
{ L"Lacute", 0x139 },
{ L"Lambda", 923 },
{ L"Lcaron", 0x13D },
{ L"Lcedil", 0x13B },
{ L"Lstrok", 0x141 },
{ L"Mu", 924 },
{ L"Nacute", 0x143 },
{ L"Ncaron", 0x147 },
{ L"Ncedil", 0x145 },
{ L"Ntilde", 0xD1 },
{ L"Nu", 925 },
{ L"OElig", 0x152 },
{ L"Oacute", 0xD3 },
{ L"Ocirc", 0xD4 },
{ L"Odblac", 0x150 },
{ L"Ograve", 0xD2 },
{ L"Omacr", 0x14C },
{ L"Omega", 937 },
{ L"Omicron", 927 },
{ L"Oslash", 0xD8 },
{ L"Otilde", 0xD5 },
{ L"Ouml", 0xD6 },
{ L"Phi", 934 },
{ L"Pi", 928 },
{ L"Prime", 8243 },
{ L"Psi", 936 },
{ L"QUOT", PRIVATE_USE_MAPPING_FOR_QUOT },
{ L"REG", 0xAE },
{ L"Racute", 0x154 },
{ L"Rcaron", 0x158 },
{ L"Rho", 929 },
{ L"Sacute", 0x15A },
{ L"Scaron", 0x160 },
{ L"Scedil", 0x15E },
{ L"Sigma", 931 },
{ L"THORN", 0xDE },
{ L"TRADE", 8482 },
{ L"Tau", 932 },
{ L"Tcaron", 0x164 },
{ L"Tcedil", 0x162 },
{ L"Theta", 920 },
{ L"Tstrok", 0x166 },
{ L"Uacute", 0xDA },
{ L"Ucirc", 0xDB },
{ L"Udblac", 0x170 },
{ L"Ugrave", 0xD9 },
{ L"Umacr", 0x16A },
{ L"Uogon", 0x172 },
{ L"Upsilon", 933 },
{ L"Uring", 0x16E },
{ L"Utilde", 0x168 },
{ L"Uuml", 0xDC },
{ L"Xi", 926 },
{ L"Yacute", 0xDD },
{ L"Yuml", 0x178 },
{ L"Zacute", 0x179 },
{ L"Zcaron", 0x17D },
{ L"Zdot", 0x17B },
{ L"Zeta", 918 },
{ L"aacute", 0xE1 },
{ L"aafs", 8301 },
{ L"abreve", 0x103 },
{ L"acirc", 0xE2 },
{ L"acute", 0xB4 },
{ L"aelig", 0xE6 },
{ L"agrave", 0xE0 },
{ L"alefsym", 8501 },
{ L"alpha", 945 },
{ L"amacr", 0x101 },
{ L"amp", 0x26 },
{ L"and", 8743 },
{ L"ang", 8736 },
{ L"aogon", 0x105 },
{ L"apos", 0x27 },
{ L"aring", 0xE5 },
{ L"ass", 8299 },
{ L"asymp", 8776 },
{ L"atilde", 0xE3 },
{ L"auml", 0xE4 },
{ L"bdquo", 8222 },
{ L"beta", 946 },
{ L"breve", 0x2D8 },
{ L"brvbar", 0xA6 },
{ L"bull", 8226 },
{ L"cacute", 0x107 },
{ L"cap", 8745 },
{ L"caron", 0x2C7 },
{ L"ccaron", 0x10D },
{ L"ccedil", 0xE7 },
{ L"ccirc", 0x109 },
{ L"cdot", 0x10B },
{ L"cedil", 0xB8 },
{ L"cent", 0xA2 },
{ L"chi", 967 },
{ L"circ", 710 },
{ L"clubs", 9827 },
{ L"colon", 0x3A },
{ L"comma", 0x2C },
{ L"cong", 8773 },
{ L"copy", 0xA9 },
{ L"crarr", 8629 },
{ L"cup", 8746 },
{ L"curren", 0xA4 },
{ L"dArr", 8659 },
{ L"dagger", 8224 },
{ L"darr", 8595 },
{ L"dblacc", 0x2DD },
{ L"dcaron", 0x10F },
{ L"deg", 0xB0 },
{ L"delta", 948 },
{ L"diams", 9830 },
{ L"divide", 0xF7 },
{ L"dot", 0x2D9 },
{ L"dstrok", 0x111 },
{ L"eacute", 0xE9 },
{ L"ebreve", 0x115 },
{ L"ecaron", 0x11B },
{ L"ecirc", 0xEA },
{ L"edot", 0x117 },
{ L"egrave", 0xE8 },
{ L"emacr", 0x113 },
{ L"empty", 8709 },
{ L"emsp", 8195 },
{ L"eng", 0x14B },
{ L"ensp", 8194 },
{ L"eogon", 0x119 },
{ L"epsilon", 949 },
{ L"equals", 0x3D },
{ L"equiv", 8801 },
{ L"eta", 951 },
{ L"eth", 0xF0 },
{ L"euml", 0xEB },
{ L"euro", 8364 },
{ L"excl", 0x21 },
{ L"exist", 8707 },
{ L"fnof", 402 },
{ L"forall", 8704 },
{ L"frac12", 0xBD },
{ L"frac14", 0xBC },
{ L"frac34", 0xBE },
{ L"frasl", 8260 },
{ L"gamma", 947 },
{ L"gbreve", 0x11F },
{ L"gcedil", 0x123 },
{ L"gcirc", 0x11D },
{ L"gdot", 0x121 },
{ L"ge", 8805 },
{ L"grave", 0x60 },
{ L"gt", PRIVATE_USE_MAPPING_FOR_GT },
{ L"hArr", 8660 },
{ L"harr", 8596 },
{ L"hearts", 9829 },
{ L"hellip", 8230 },
{ L"iacute", 0xED },
{ L"iafs", 8300 },
{ L"icirc", 0xEE },
{ L"iexcl", 0xA1 },
{ L"igrave", 0xEC },
{ L"imacr", 0x12B },
{ L"image", 8465 },
{ L"infin", 8734 },
{ L"inodot", 0x131 },
{ L"int", 8747 },
{ L"iogon", 0x12F },
{ L"iota", 953 },
{ L"iquest", 0xBF },
{ L"isin", 8712 },
{ L"iss", 8298 },
{ L"itilde", 0x129 },
{ L"iuml", 0xEF },
{ L"kappa", 954 },
{ L"kcedil", 0x137 },
{ L"kra", 0x138 },
{ L"lArr", 8656 },
{ L"lacute", 0x13A },
{ L"lambda", 955 },
{ L"lang", 9001 },
{ L"laquo", 0xAB },
{ L"larr", 8592 },
{ L"lcaron", 0x13E },
{ L"lcedil", 0x13C },
{ L"lceil", 8968 },
{ L"ldquo", 8220 },
{ L"le", 8804 },
{ L"lfloor", 8970 },
{ L"lowast", 8727 },
{ L"lowbar", 0x5F },
{ L"loz", 9674 },
{ L"lre", 8234 },
{ L"lrm", 8206 },
{ L"lro", 8237 },
{ L"lsaquo", 8249 },
{ L"lsqb", 0x5B },
{ L"lsquo", 8216 },
{ L"lstrok", 0x142 },
{ L"lt", PRIVATE_USE_MAPPING_FOR_LT },
{ L"macr", 0xAF },
{ L"mdash", 8212 },
{ L"micro", 0xB5 },
{ L"middot", 0xB7 },
{ L"minus", 8722 },
{ L"mu", 956 },
{ L"nabla", 8711 },
{ L"nacute", 0x144 },
{ L"nads", 8302 },
{ L"nbsp", 0xA0 },
{ L"ncaron", 0x148 },
{ L"ncedil", 0x146 },
{ L"ndash", 8211 },
{ L"ne", 8800 },
{ L"ni", 8715 },
{ L"nods", 8303 },
{ L"not", 0xAC },
{ L"notin", 8713 },
{ L"nsub", 8836 },
{ L"ntilde", 0xF1 },
{ L"nu", 957 },
{ L"oacute", 0xF3 },
{ L"ocirc", 0xF4 },
{ L"odblac", 0x151 },
{ L"oelig", 0x153 },
{ L"ogon", 0x2DB },
{ L"ograve", 0xF2 },
{ L"oline", 8254 },
{ L"omacr", 0x14D },
{ L"omega", 969 },
{ L"omicron", 959 },
{ L"oplus", 8853 },
{ L"or", 8744 },
{ L"ordf", 0xAA },
{ L"ordm", 0xBA },
{ L"oslash", 0xF8 },
{ L"otilde", 0xF5 },
{ L"otimes", 8855 },
{ L"ouml", 0xF6 },
{ L"para", 0xB6 },
{ L"part", 8706 },
{ L"pdf", 8236 },
{ L"period", 0x2E },
{ L"permil", 8240 },
{ L"perp", 8869 },
{ L"phi", 966 },
{ L"pi", 960 },
{ L"piv", 982 },
{ L"plus", 0x2B },
{ L"plusmn", 0xB1 },
{ L"pound", 0xA3 },
{ L"prime", 8242 },
{ L"prod", 8719 },
{ L"prop", 8733 },
{ L"psi", 968 },
{ L"quest", 0x3F },
{ L"quot", PRIVATE_USE_MAPPING_FOR_QUOT },
{ L"rArr", 8658 },
{ L"racute", 0x155 },
{ L"radic", 8730 },
{ L"rang", 9002 },
{ L"raquo", 0xBB },
{ L"rarr", 8594 },
{ L"rcaron", 0x159 },
{ L"rceil", 8969 },
{ L"rdquo", 8221 },
{ L"real", 8476 },
{ L"reg", 0xAE },
{ L"rfloor", 8971 },
{ L"rho", 961 },
{ L"rle", 8235 },
{ L"rlm", 8207 },
{ L"rlo", 8238 },
{ L"rsaquo", 8250 },
{ L"rsqb", 0x5D },
{ L"rsquo", 8217 },
{ L"sacute", 0x15B },
{ L"sbquo", 8218 },
{ L"scaron", 0x161 },
{ L"scedil", 0x15F },
{ L"sdot", 8901 },
{ L"sect", 0xA7 },
{ L"semi", 0x3B },
{ L"shy", 0xAD },
{ L"sigma", 963 },
{ L"sigmaf", 962 },
{ L"sim", 8764 },
{ L"spades", 9824 },
{ L"sub", 8834 },
{ L"sube", 8838 },
{ L"sum", 8721 },
{ L"sup", 8835 },
{ L"sup1", 0xB9 },
{ L"sup2", 0xB2 },
{ L"sup3", 0xB3 },
{ L"supe", 8839 },
{ L"supl", 0xB9 },
{ L"szlig", 0xDF },
{ L"tau", 964 },
{ L"tcaron", 0x165 },
{ L"tcedil", 0x163 },
{ L"there4", 8756 },
{ L"theta", 952 },
{ L"thetasym",977 },
{ L"thinsp", 8201 },
{ L"thorn", 0xFE },
{ L"tilde", 0x2DC },
{ L"times", 0xD7 },
{ L"trade", 8482 },
{ L"tstrok", 0x167 },
{ L"uArr", 8657 },
{ L"uacute", 0xFA },
{ L"uarr", 8593 },
{ L"ucirc", 0xFB },
{ L"udblac", 0x171 },
{ L"ugrave", 0xF9 },
{ L"umacr", 0x16B },
{ L"uml", 0xA8 },
{ L"uogon", 0x173 },
{ L"upsih", 978 },
{ L"upsilon", 965 },
{ L"uring", 0x16F },
{ L"utilde", 0x169 },
{ L"uuml", 0xFC },
{ L"weierp", 8472 },
{ L"xi", 958 },
{ L"yacute", 0xFD },
{ L"yen", 0xA5 },
{ L"yuml", 0xFF },
{ L"zacute", 0x17A },
{ L"zcaron", 0x17E },
{ L"zdot", 0x17C },
{ L"zeta", 950 },
{ L"zwj", 8205 },
{ L"zwnj", 8204 },
{ L"zwsp", 8203 },
};
#define ArraySize(x) ( sizeof( x ) / sizeof( x[0] ) )
const ULONG g_cCharMap = ArraySize( g_aCharMap );
int __cdecl StringCharEntryCompare(
WCHAR const * pwcKey,
SStringCharEntry const * pEntry )
{
return wcscmp( pwcKey, pEntry->pwcString );
} //StringCharEntryCompare
BOOL LookupSpecialChar( WCHAR const * pwcTag, ULONG cwcTag, WCHAR & wc )
{
WCHAR awc[ 50 ];
if ( cwcTag >= ArraySize( awc ) )
return FALSE;
memcpy( awc, pwcTag, cwcTag * sizeof WCHAR );
awc[ cwcTag ] = 0;
SStringCharEntry * pEntry = (SStringCharEntry *)
bsearch( awc,
g_aCharMap,
g_cCharMap,
sizeof SStringCharEntry,
(int (__cdecl *)(const void *, const void *) )
StringCharEntryCompare );
if ( 0 != pEntry )
{
wc = pEntry->wcChar;
return TRUE;
}
return FALSE;
} //LookupSpecialChar
| [
"seta7D5@protonmail.com"
] | seta7D5@protonmail.com |
ddf9f4968ae50fefc4a1b4f57d55e4acee9a960d | cf05cfc5a6278a859a2a32d3b118516499002955 | /linux/my_application.cc | 5516eb111afbc3a2cef6df519c772fea2000dc1b | [] | no_license | AmbujaAK/flutter_whatsapp_clone | 3ecbf74bb76a8472536af0c466ecd8e5c2e08630 | be377ed5b7f44199d84b0bad770ce6e949e55b52 | refs/heads/main | 2023-05-29T21:09:37.224980 | 2021-06-16T19:12:58 | 2021-06-16T19:12:58 | 315,687,755 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,676 | cc | #include "my_application.h"
#include <flutter_linux/flutter_linux.h>
#ifdef GDK_WINDOWING_X11
#include <gdk/gdkx.h>
#endif
#include "flutter/generated_plugin_registrant.h"
struct _MyApplication {
GtkApplication parent_instance;
char** dart_entrypoint_arguments;
};
G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION)
// Implements GApplication::activate.
static void my_application_activate(GApplication* application) {
MyApplication* self = MY_APPLICATION(application);
GtkWindow* window =
GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application)));
// Use a header bar when running in GNOME as this is the common style used
// by applications and is the setup most users will be using (e.g. Ubuntu
// desktop).
// If running on X and not using GNOME then just use a traditional title bar
// in case the window manager does more exotic layout, e.g. tiling.
// If running on Wayland assume the header bar will work (may need changing
// if future cases occur).
gboolean use_header_bar = TRUE;
#ifdef GDK_WINDOWING_X11
GdkScreen *screen = gtk_window_get_screen(window);
if (GDK_IS_X11_SCREEN(screen)) {
const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen);
if (g_strcmp0(wm_name, "GNOME Shell") != 0) {
use_header_bar = FALSE;
}
}
#endif
if (use_header_bar) {
GtkHeaderBar *header_bar = GTK_HEADER_BAR(gtk_header_bar_new());
gtk_widget_show(GTK_WIDGET(header_bar));
gtk_header_bar_set_title(header_bar, "flutter_whatsapp_clone");
gtk_header_bar_set_show_close_button(header_bar, TRUE);
gtk_window_set_titlebar(window, GTK_WIDGET(header_bar));
}
else {
gtk_window_set_title(window, "flutter_whatsapp_clone");
}
gtk_window_set_default_size(window, 1280, 720);
gtk_widget_show(GTK_WIDGET(window));
g_autoptr(FlDartProject) project = fl_dart_project_new();
fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments);
FlView* view = fl_view_new(project);
gtk_widget_show(GTK_WIDGET(view));
gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view));
fl_register_plugins(FL_PLUGIN_REGISTRY(view));
gtk_widget_grab_focus(GTK_WIDGET(view));
}
// Implements GApplication::local_command_line.
static gboolean my_application_local_command_line(GApplication* application, gchar ***arguments, int *exit_status) {
MyApplication* self = MY_APPLICATION(application);
// Strip out the first argument as it is the binary name.
self->dart_entrypoint_arguments = g_strdupv(*arguments + 1);
g_autoptr(GError) error = nullptr;
if (!g_application_register(application, nullptr, &error)) {
g_warning("Failed to register: %s", error->message);
*exit_status = 1;
return TRUE;
}
g_application_activate(application);
*exit_status = 0;
return TRUE;
}
// Implements GObject::dispose.
static void my_application_dispose(GObject *object) {
MyApplication* self = MY_APPLICATION(object);
g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev);
G_OBJECT_CLASS(my_application_parent_class)->dispose(object);
}
static void my_application_class_init(MyApplicationClass* klass) {
G_APPLICATION_CLASS(klass)->activate = my_application_activate;
G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line;
G_OBJECT_CLASS(klass)->dispose = my_application_dispose;
}
static void my_application_init(MyApplication* self) {}
MyApplication* my_application_new() {
return MY_APPLICATION(g_object_new(my_application_get_type(),
"application-id", APPLICATION_ID,
nullptr));
}
| [
"itsambuja@gmail.com"
] | itsambuja@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.