hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
93cdb4f7ff40cd1e4970dd692635256ee9f4bd86
2,225
hpp
C++
external/mapnik/include/mapnik/pixel_position.hpp
baiyicanggou/mapnik_mvt
9bde52fa9958d81361c015c816858534ec0931bb
[ "Apache-2.0" ]
null
null
null
external/mapnik/include/mapnik/pixel_position.hpp
baiyicanggou/mapnik_mvt
9bde52fa9958d81361c015c816858534ec0931bb
[ "Apache-2.0" ]
null
null
null
external/mapnik/include/mapnik/pixel_position.hpp
baiyicanggou/mapnik_mvt
9bde52fa9958d81361c015c816858534ec0931bb
[ "Apache-2.0" ]
null
null
null
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_PIXEL_POSITION_HPP #define MAPNIK_PIXEL_POSITION_HPP // stl #include <cmath> namespace mapnik { struct rotation; struct pixel_position { double x; double y; pixel_position(double x_, double y_) : x(x_), y(y_) {} pixel_position() : x(0), y(0) {} pixel_position operator+ (pixel_position const& other) const { return pixel_position(x + other.x, y + other.y); } pixel_position operator- (pixel_position const& other) const { return pixel_position(x - other.x, y - other.y); } pixel_position operator* (double other) const { return pixel_position(x * other, y * other); } void set(double x_, double y_) { x = x_; y = y_; } void clear() { x = 0; y = 0; } pixel_position rotate(rotation const& rot) const; pixel_position operator~() const { return pixel_position(x, -y); } double length() { return std::sqrt(x * x + y * y); } }; inline pixel_position operator* (double factor, pixel_position const& pos) { return pixel_position(factor * pos.x, factor * pos.y); } } #endif // MAPNIK_PIXEL_POSITION_HPP
24.722222
79
0.606292
baiyicanggou
93d0c017e4c6a664c47d05878b8e336acba64bb3
762
cpp
C++
chtho/logging/tests/LogFile_test.cpp
WineChord/chtho
f43c56a1c2faf83e5f48361ca1b06366ce061aab
[ "MIT" ]
null
null
null
chtho/logging/tests/LogFile_test.cpp
WineChord/chtho
f43c56a1c2faf83e5f48361ca1b06366ce061aab
[ "MIT" ]
null
null
null
chtho/logging/tests/LogFile_test.cpp
WineChord/chtho
f43c56a1c2faf83e5f48361ca1b06366ce061aab
[ "MIT" ]
null
null
null
// Copyright (c) 2021 Qizhou Guo // // This software is released under the MIT License. // https://opensource.org/licenses/MIT #include "chtho/logging/Logger.h" #include "chtho/logging/LogFile.h" #include <memory> #include <unistd.h> std::unique_ptr<chtho::LogFile> logfile; void outputFunc(const char* msg, int len) { logfile->append(msg, len); } void flushFunc() { logfile->flush(); } int main(int argc, char* argv[]) { // roll size is 200 KB logfile.reset(new chtho::LogFile(::basename(argv[0]), 200*1000)); chtho::Logger::setOutput(outputFunc); chtho::Logger::setFlush(flushFunc); std::string line = "qwertyuioplkjhgfdsazxcvbnm0987654321"; for(int i = 0; i < 10000; ++i) { LOG_INFO << line << i; usleep(1000); // sleep 1ms } }
27.214286
72
0.678478
WineChord
93d6a97b2033a24daea2f1994741410bf62ec338
27,263
cpp
C++
DesktopSharing/xop/RtmpConnection.cpp
JungleZy/DesktopSharing
b8d551a50a3abad8f54db9e5a74d778725422f22
[ "MIT" ]
502
2018-06-12T14:48:54.000Z
2022-03-31T07:33:00.000Z
DesktopSharing/xop/RtmpConnection.cpp
JungleZy/DesktopSharing
b8d551a50a3abad8f54db9e5a74d778725422f22
[ "MIT" ]
37
2018-11-23T20:43:27.000Z
2021-12-24T07:39:17.000Z
DesktopSharing/xop/RtmpConnection.cpp
JungleZy/DesktopSharing
b8d551a50a3abad8f54db9e5a74d778725422f22
[ "MIT" ]
198
2018-06-13T13:19:05.000Z
2022-03-30T07:32:20.000Z
#include "RtmpConnection.h" #include "RtmpServer.h" #include "RtmpPublisher.h" #include "RtmpClient.h" #include "net/Logger.h" #include <random> using namespace xop; RtmpConnection::RtmpConnection(std::shared_ptr<RtmpServer> rtmp_server, TaskScheduler *task_scheduler, SOCKET sockfd) : RtmpConnection(task_scheduler, sockfd, rtmp_server.get()) { handshake_.reset(new RtmpHandshake(RtmpHandshake::HANDSHAKE_C0C1)); rtmp_server_ = rtmp_server; connection_mode_ = RTMP_SERVER; } RtmpConnection::RtmpConnection(std::shared_ptr<RtmpPublisher> rtmp_publisher, TaskScheduler *task_scheduler, SOCKET sockfd) : RtmpConnection(task_scheduler, sockfd, rtmp_publisher.get()) { handshake_.reset(new RtmpHandshake(RtmpHandshake::HANDSHAKE_S0S1S2)); rtmp_publisher_ = rtmp_publisher; connection_mode_ = RTMP_PUBLISHER; } RtmpConnection::RtmpConnection(std::shared_ptr<RtmpClient> rtmp_client, TaskScheduler *task_scheduler, SOCKET sockfd) : RtmpConnection(task_scheduler, sockfd, rtmp_client.get()) { handshake_.reset(new RtmpHandshake(RtmpHandshake::HANDSHAKE_S0S1S2)); rtmp_client_ = rtmp_client; connection_mode_ = RTMP_CLIENT; } RtmpConnection::RtmpConnection(TaskScheduler *task_scheduler, SOCKET sockfd, Rtmp* rtmp) : TcpConnection(task_scheduler, sockfd) , task_scheduler_(task_scheduler) , channel_(new Channel(sockfd)) , rtmp_chunk_(new RtmpChunk) , connection_state_(HANDSHAKE) { peer_bandwidth_ = rtmp->GetPeerBandwidth(); acknowledgement_size_ = rtmp->GetAcknowledgementSize(); max_gop_cache_len_ = rtmp->GetGopCacheLen(); max_chunk_size_ = rtmp->GetChunkSize(); stream_path_ = rtmp->GetStreamPath(); stream_name_ = rtmp->GetStreamName(); app_ = rtmp->GetApp(); this->SetReadCallback([this](std::shared_ptr<TcpConnection> conn, xop::BufferReader& buffer) { return this->OnRead(buffer); }); this->SetCloseCallback([this](std::shared_ptr<TcpConnection> conn) { this->OnClose(); }); } RtmpConnection::~RtmpConnection() { } bool RtmpConnection::OnRead(BufferReader& buffer) { bool ret = true; if (handshake_->IsCompleted()) { ret = HandleChunk(buffer); } else { std::shared_ptr<char> res(new char[4096], std::default_delete<char[]>()); int res_size = handshake_->Parse(buffer, res.get(), 4096); if (res_size < 0) { ret = false; } if (res_size > 0) { this->Send(res.get(), res_size); } if (handshake_->IsCompleted()) { if(buffer.ReadableBytes() > 0) { ret = HandleChunk(buffer); } if (connection_mode_ == RTMP_PUBLISHER || connection_mode_ == RTMP_CLIENT) { this->SetChunkSize(); this->Connect(); } } } return ret; } void RtmpConnection::OnClose() { if (connection_mode_ == RTMP_SERVER) { this->HandleDeleteStream(); } else if (connection_mode_ == RTMP_PUBLISHER) { this->DeleteStream(); } } bool RtmpConnection::HandleChunk(BufferReader& buffer) { int ret = -1; do { RtmpMessage rtmp_msg; ret = rtmp_chunk_->Parse(buffer, rtmp_msg); if (ret >= 0) { if (rtmp_msg.IsCompleted()) { if (!HandleMessage(rtmp_msg)) { return false; } } if (ret == 0) { break; } } else if (ret < 0) { return false; } } while (buffer.ReadableBytes() > 0); return true; } bool RtmpConnection::HandleMessage(RtmpMessage& rtmp_msg) { bool ret = true; switch(rtmp_msg.type_id) { case RTMP_VIDEO: ret = HandleVideo(rtmp_msg); break; case RTMP_AUDIO: ret = HandleAudio(rtmp_msg); break; case RTMP_INVOKE: ret = HandleInvoke(rtmp_msg); break; case RTMP_NOTIFY: ret = HandleNotify(rtmp_msg); break; case RTMP_FLEX_MESSAGE: LOG_INFO("unsupported rtmp flex message.\n"); ret = false; break; case RTMP_SET_CHUNK_SIZE: rtmp_chunk_->SetInChunkSize(ReadUint32BE(rtmp_msg.payload.get())); break; case RTMP_BANDWIDTH_SIZE: break; case RTMP_FLASH_VIDEO: LOG_INFO("unsupported rtmp flash video.\n"); ret = false; break; case RTMP_ACK: break; case RTMP_ACK_SIZE: break; case RTMP_USER_EVENT: break; default: LOG_INFO("unkonw message type : %d\n", rtmp_msg.type_id); break; } if (!ret) { //printf("rtmp_msg.type_id:%x\n", rtmp_msg.type_id); } return ret; } bool RtmpConnection::HandleInvoke(RtmpMessage& rtmp_msg) { bool ret = true; amf_decoder_.reset(); int bytes_used = amf_decoder_.decode((const char *)rtmp_msg.payload.get(), rtmp_msg.length, 1); if (bytes_used < 0) { return false; } std::string method = amf_decoder_.getString(); //LOG_INFO("[Method] %s\n", method.c_str()); if (connection_mode_ == RTMP_PUBLISHER || connection_mode_ == RTMP_CLIENT) { bytes_used += amf_decoder_.decode(rtmp_msg.payload.get() + bytes_used, rtmp_msg.length - bytes_used); if (method == "_result") { ret = HandleResult(rtmp_msg); } else if (method == "onStatus") { ret = HandleOnStatus(rtmp_msg); } } else if (connection_mode_ == RTMP_SERVER) { if(rtmp_msg.stream_id == 0) { bytes_used += amf_decoder_.decode(rtmp_msg.payload.get()+bytes_used, rtmp_msg.length-bytes_used); if(method == "connect") { ret = HandleConnect(); } else if(method == "createStream") { ret = HandleCreateStream(); } } else if(rtmp_msg.stream_id == stream_id_) { bytes_used += amf_decoder_.decode((const char *)rtmp_msg.payload.get()+bytes_used, rtmp_msg.length-bytes_used, 3); stream_name_ = amf_decoder_.getString(); stream_path_ = "/" + app_ + "/" + stream_name_; if((int)rtmp_msg.length > bytes_used) { bytes_used += amf_decoder_.decode((const char *)rtmp_msg.payload.get()+bytes_used, rtmp_msg.length-bytes_used); } if(method == "publish") { ret = HandlePublish(); } else if(method == "play") { ret = HandlePlay(); } else if(method == "play2") { ret = HandlePlay2(); } else if(method == "DeleteStream") { ret = HandleDeleteStream(); } else if (method == "releaseStream") { } } } return ret; } bool RtmpConnection::HandleNotify(RtmpMessage& rtmp_msg) { amf_decoder_.reset(); int bytes_used = amf_decoder_.decode((const char *)rtmp_msg.payload.get(), rtmp_msg.length, 1); if(bytes_used < 0) { return false; } if(amf_decoder_.getString() == "@setDataFrame") { amf_decoder_.reset(); bytes_used = amf_decoder_.decode((const char *)rtmp_msg.payload.get()+bytes_used, rtmp_msg.length-bytes_used, 1); if(bytes_used < 0) { return false; } if(amf_decoder_.getString() == "onMetaData") { amf_decoder_.decode((const char *)rtmp_msg.payload.get()+bytes_used, rtmp_msg.length-bytes_used); meta_data_ = amf_decoder_.getObjects(); auto server = rtmp_server_.lock(); if (!server) { return false; } auto session = server->GetSession(stream_path_); if(session) { session->SetMetaData(meta_data_); session->SendMetaData(meta_data_); } } } return true; } bool RtmpConnection::HandleVideo(RtmpMessage& rtmp_msg) { uint8_t type = RTMP_VIDEO; uint8_t *payload = (uint8_t *)rtmp_msg.payload.get(); uint32_t length = rtmp_msg.length; uint8_t frame_type = (payload[0] >> 4) & 0x0f; uint8_t codec_id = payload[0] & 0x0f; if (connection_mode_ == RTMP_CLIENT) { if (is_playing_ && connection_state_ == START_PLAY) { if (play_cb_) { play_cb_(payload, length, codec_id, (uint32_t)rtmp_msg._timestamp); } } } else if(connection_mode_ == RTMP_SERVER) { auto server = rtmp_server_.lock(); if (!server) { return false; } auto session = server->GetSession(stream_path_); if (session == nullptr) { return false; } if (frame_type == 1 && codec_id == RTMP_CODEC_ID_H264) { if (payload[1] == 0) { avc_sequence_header_size_ = length; avc_sequence_header_.reset(new char[length], std::default_delete<char[]>()); memcpy(avc_sequence_header_.get(), rtmp_msg.payload.get(), length); session->SetAvcSequenceHeader(avc_sequence_header_, avc_sequence_header_size_); type = RTMP_AVC_SEQUENCE_HEADER; } } session->SendMediaData(type, rtmp_msg._timestamp, rtmp_msg.payload, rtmp_msg.length); } return true; } bool RtmpConnection::HandleAudio(RtmpMessage& rtmp_msg) { uint8_t type = RTMP_AUDIO; uint8_t *payload = (uint8_t *)rtmp_msg.payload.get(); uint32_t length = rtmp_msg.length; uint8_t sound_format = (payload[0] >> 4) & 0x0f; //uint8_t sound_size = (payload[0] >> 1) & 0x01; //uint8_t sound_rate = (payload[0] >> 2) & 0x03; uint8_t codec_id = payload[0] & 0x0f; if (connection_mode_ == RTMP_CLIENT) { if (connection_state_ == START_PLAY && is_playing_) { if (play_cb_) { play_cb_(payload, length, codec_id, (uint32_t)rtmp_msg._timestamp); } } } else { auto server = rtmp_server_.lock(); if (!server) { return false; } auto session = server->GetSession(stream_path_); if (session == nullptr) { return false; } if (sound_format == RTMP_CODEC_ID_AAC && payload[1] == 0) { aac_sequence_header_size_ = rtmp_msg.length; aac_sequence_header_.reset(new char[rtmp_msg.length], std::default_delete<char[]>()); memcpy(aac_sequence_header_.get(), rtmp_msg.payload.get(), rtmp_msg.length); session->SetAacSequenceHeader(aac_sequence_header_, aac_sequence_header_size_); type = RTMP_AAC_SEQUENCE_HEADER; } session->SendMediaData(type, rtmp_msg._timestamp, rtmp_msg.payload, rtmp_msg.length); } return true; } bool RtmpConnection::Handshake() { uint32_t req_size = 1 + 1536; //COC1 std::shared_ptr<char> req(new char[req_size], std::default_delete<char[]>()); handshake_->BuildC0C1(req.get(), req_size); this->Send(req.get(), req_size); return true; } bool RtmpConnection::Connect() { AmfObjects objects; amf_encoder_.reset(); amf_encoder_.encodeString("connect", 7); amf_encoder_.encodeNumber((double)(++number_)); objects["app"] = AmfObject(app_); objects["type"] = AmfObject(std::string("nonprivate")); if (connection_mode_ == RTMP_PUBLISHER) { auto publisher = rtmp_publisher_.lock(); if (!publisher) { return false; } objects["swfUrl"] = AmfObject(publisher->GetSwfUrl()); objects["tcUrl"] = AmfObject(publisher->GetTcUrl()); } else if (connection_mode_ == RTMP_CLIENT) { auto client = rtmp_client_.lock(); if (!client) { return false; } objects["swfUrl"] = AmfObject(client->GetSwfUrl()); objects["tcUrl"] = AmfObject(client->GetTcUrl()); } amf_encoder_.encodeObjects(objects); connection_state_ = START_CONNECT; SendInvokeMessage(RTMP_CHUNK_INVOKE_ID, amf_encoder_.data(), amf_encoder_.size()); return true; } bool RtmpConnection::CretaeStream() { AmfObjects objects; amf_encoder_.reset(); amf_encoder_.encodeString("createStream", 12); amf_encoder_.encodeNumber((double)(++number_)); amf_encoder_.encodeObjects(objects); connection_state_ = START_CREATE_STREAM; SendInvokeMessage(RTMP_CHUNK_INVOKE_ID, amf_encoder_.data(), amf_encoder_.size()); return true; } bool RtmpConnection::Publish() { AmfObjects objects; amf_encoder_.reset(); amf_encoder_.encodeString("publish", 7); amf_encoder_.encodeNumber((double)(++number_)); amf_encoder_.encodeObjects(objects); amf_encoder_.encodeString(stream_name_.c_str(), (int)stream_name_.size()); connection_state_ = START_PUBLISH; SendInvokeMessage(RTMP_CHUNK_INVOKE_ID, amf_encoder_.data(), amf_encoder_.size()); return true; } bool RtmpConnection::Play() { AmfObjects objects; amf_encoder_.reset(); amf_encoder_.encodeString("play", 4); amf_encoder_.encodeNumber((double)(++number_)); amf_encoder_.encodeObjects(objects); amf_encoder_.encodeString(stream_name_.c_str(), (int)stream_name_.size()); connection_state_ = START_PLAY; SendInvokeMessage(RTMP_CHUNK_INVOKE_ID, amf_encoder_.data(), amf_encoder_.size()); return true; } bool RtmpConnection::DeleteStream() { AmfObjects objects; amf_encoder_.reset(); amf_encoder_.encodeString("DeleteStream", 12); amf_encoder_.encodeNumber((double)(++number_)); amf_encoder_.encodeObjects(objects); amf_encoder_.encodeNumber(stream_id_); connection_state_ = START_DELETE_STREAM; SendInvokeMessage(RTMP_CHUNK_INVOKE_ID, amf_encoder_.data(), amf_encoder_.size()); return true; } bool RtmpConnection::HandleConnect() { if(!amf_decoder_.hasObject("app")) { return false; } AmfObject amfObj = amf_decoder_.getObject("app"); app_ = amfObj.amf_string; if(app_ == "") { return false; } SendAcknowledgement(); SetPeerBandwidth(); SetChunkSize(); AmfObjects objects; amf_encoder_.reset(); amf_encoder_.encodeString("_result", 7); amf_encoder_.encodeNumber(amf_decoder_.getNumber()); objects["fmsVer"] = AmfObject(std::string("FMS/4,5,0,297")); objects["capabilities"] = AmfObject(255.0); objects["mode"] = AmfObject(1.0); amf_encoder_.encodeObjects(objects); objects.clear(); objects["level"] = AmfObject(std::string("status")); objects["code"] = AmfObject(std::string("NetConnection.Connect.Success")); objects["description"] = AmfObject(std::string("Connection succeeded.")); objects["objectEncoding"] = AmfObject(0.0); amf_encoder_.encodeObjects(objects); SendInvokeMessage(RTMP_CHUNK_INVOKE_ID, amf_encoder_.data(), amf_encoder_.size()); return true; } bool RtmpConnection::HandleCreateStream() { int stream_id = rtmp_chunk_->GetStreamId(); AmfObjects objects; amf_encoder_.reset(); amf_encoder_.encodeString("_result", 7); amf_encoder_.encodeNumber(amf_decoder_.getNumber()); amf_encoder_.encodeObjects(objects); amf_encoder_.encodeNumber(stream_id); SendInvokeMessage(RTMP_CHUNK_INVOKE_ID, amf_encoder_.data(), amf_encoder_.size()); stream_id_ = stream_id; return true; } bool RtmpConnection::HandlePublish() { LOG_INFO("[Publish] app: %s, stream name: %s, stream path: %s\n", app_.c_str(), stream_name_.c_str(), stream_path_.c_str()); auto server = rtmp_server_.lock(); if (!server) { return false; } AmfObjects objects; amf_encoder_.reset(); amf_encoder_.encodeString("onStatus", 8); amf_encoder_.encodeNumber(0); amf_encoder_.encodeObjects(objects); bool is_error = false; if(server->HasPublisher(stream_path_)) { is_error = true; objects["level"] = AmfObject(std::string("error")); objects["code"] = AmfObject(std::string("NetStream.Publish.BadName")); objects["description"] = AmfObject(std::string("Stream already publishing.")); } else if(connection_state_ == START_PUBLISH) { is_error = true; objects["level"] = AmfObject(std::string("error")); objects["code"] = AmfObject(std::string("NetStream.Publish.BadConnection")); objects["description"] = AmfObject(std::string("Connection already publishing.")); } /* else if(0) { // 认证处理 } */ else { objects["level"] = AmfObject(std::string("status")); objects["code"] = AmfObject(std::string("NetStream.Publish.Start")); objects["description"] = AmfObject(std::string("Start publising.")); server->AddSession(stream_path_); } amf_encoder_.encodeObjects(objects); SendInvokeMessage(RTMP_CHUNK_INVOKE_ID, amf_encoder_.data(), amf_encoder_.size()); if(is_error) { // Close ? } else { connection_state_ = START_PUBLISH; is_publishing_ = true; } auto session = server->GetSession(stream_path_); if(session) { session->SetGopCache(max_gop_cache_len_); session->AddRtmpClient(std::dynamic_pointer_cast<RtmpConnection>(shared_from_this())); } return true; } bool RtmpConnection::HandlePlay() { LOG_INFO("[Play] app: %s, stream name: %s, stream path: %s\n", app_.c_str(), stream_name_.c_str(), stream_path_.c_str()); auto server = rtmp_server_.lock(); if (!server) { return false; } AmfObjects objects; amf_encoder_.reset(); amf_encoder_.encodeString("onStatus", 8); amf_encoder_.encodeNumber(0); amf_encoder_.encodeObjects(objects); objects["level"] = AmfObject(std::string("status")); objects["code"] = AmfObject(std::string("NetStream.Play.Reset")); objects["description"] = AmfObject(std::string("Resetting and playing stream.")); amf_encoder_.encodeObjects(objects); if(!SendInvokeMessage(RTMP_CHUNK_INVOKE_ID, amf_encoder_.data(), amf_encoder_.size())) { return false; } objects.clear(); amf_encoder_.reset(); amf_encoder_.encodeString("onStatus", 8); amf_encoder_.encodeNumber(0); amf_encoder_.encodeObjects(objects); objects["level"] = AmfObject(std::string("status")); objects["code"] = AmfObject(std::string("NetStream.Play.Start")); objects["description"] = AmfObject(std::string("Started playing.")); amf_encoder_.encodeObjects(objects); if(!SendInvokeMessage(RTMP_CHUNK_INVOKE_ID, amf_encoder_.data(), amf_encoder_.size())) { return false; } amf_encoder_.reset(); amf_encoder_.encodeString("|RtmpSampleAccess", 17); amf_encoder_.encodeBoolean(true); amf_encoder_.encodeBoolean(true); if(!this->SendNotifyMessage(RTMP_CHUNK_DATA_ID, amf_encoder_.data(), amf_encoder_.size())) { return false; } connection_state_ = START_PLAY; auto session = server->GetSession(stream_path_); if(session) { session->AddRtmpClient(std::dynamic_pointer_cast<RtmpConnection>(shared_from_this())); } return true; } bool RtmpConnection::HandlePlay2() { HandlePlay(); //printf("[Play2] stream path: %s\n", stream_path_.c_str()); return false; } bool RtmpConnection::HandleDeleteStream() { auto server = rtmp_server_.lock(); if (!server) { return false; } if(stream_path_ != "") { auto session = server->GetSession(stream_path_); if(session != nullptr) { auto conn = std::dynamic_pointer_cast<RtmpConnection>(shared_from_this()); task_scheduler_->AddTimer([session, conn] { session->RemoveRtmpClient(conn); return false; }, 1); } is_playing_ = false; is_publishing_ = false; has_key_frame_ = false; rtmp_chunk_->Clear(); } return true; } bool RtmpConnection::HandleResult(RtmpMessage& rtmp_msg) { bool ret = false; if (connection_state_ == START_CONNECT) { if (amf_decoder_.hasObject("code")) { AmfObject amfObj = amf_decoder_.getObject("code"); if (amfObj.amf_string == "NetConnection.Connect.Success") { CretaeStream(); ret = true; } } } else if (connection_state_ == START_CREATE_STREAM) { if (amf_decoder_.getNumber() > 0) { stream_id_ = (uint32_t)amf_decoder_.getNumber(); if (connection_mode_ == RTMP_PUBLISHER) { this->Publish(); } else if (connection_mode_ == RTMP_CLIENT) { this->Play(); } ret = true; } } return ret; } bool RtmpConnection::HandleOnStatus(RtmpMessage& rtmp_msg) { bool ret = true; if (connection_state_ == START_PUBLISH || connection_state_ == START_PLAY) { if (amf_decoder_.hasObject("code")) { AmfObject amfObj = amf_decoder_.getObject("code"); status_ = amfObj.amf_string; if (connection_mode_ == RTMP_PUBLISHER) { if (status_ == "NetStream.Publish.Start") { is_publishing_ = true; } else if(status_ == "NetStream.publish.Unauthorized" || status_ == "NetStream.Publish.BadConnection" /*"Connection already publishing"*/ || status_ == "NetStream.Publish.BadName") /*Stream already publishing*/ { ret = false; } } else if (connection_mode_ == RTMP_CLIENT) { if (/*amfObj.amf_string == "NetStream.Play.Reset" || */ status_ == "NetStream.Play.Start") { is_playing_ = true; } else if(status_ == "NetStream.play.Unauthorized" || status_ == "NetStream.Play.UnpublishNotify" /*"stream is now unpublished."*/ || status_ == "NetStream.Play.BadConnection") /*"Connection already playing"*/ { ret = false; } } } } if (connection_state_ == START_DELETE_STREAM) { if (amf_decoder_.hasObject("code")) { AmfObject amfObj = amf_decoder_.getObject("code"); if (amfObj.amf_string != "NetStream.Unpublish.Success") { ret = false; } } } return ret; } bool RtmpConnection::SendMetaData(AmfObjects metaData) { if(this->IsClosed()) { return false; } if (metaData.size() == 0) { return false; } amf_encoder_.reset(); amf_encoder_.encodeString("onMetaData", 10); amf_encoder_.encodeECMA(metaData); if(!this->SendNotifyMessage(RTMP_CHUNK_DATA_ID, amf_encoder_.data(), amf_encoder_.size())) { return false; } return true; } void RtmpConnection::SetPeerBandwidth() { std::shared_ptr<char> data(new char[5], std::default_delete<char[]>()); WriteUint32BE(data.get(), peer_bandwidth_); data.get()[4] = 2; RtmpMessage rtmp_msg; rtmp_msg.type_id = RTMP_BANDWIDTH_SIZE; rtmp_msg.payload = data; rtmp_msg.length = 5; SendRtmpChunks(RTMP_CHUNK_CONTROL_ID, rtmp_msg); } void RtmpConnection::SendAcknowledgement() { std::shared_ptr<char> data(new char[4], std::default_delete<char[]>()); WriteUint32BE(data.get(), acknowledgement_size_); RtmpMessage rtmp_msg; rtmp_msg.type_id = RTMP_ACK_SIZE; rtmp_msg.payload = data; rtmp_msg.length = 4; SendRtmpChunks(RTMP_CHUNK_CONTROL_ID, rtmp_msg); } void RtmpConnection::SetChunkSize() { rtmp_chunk_->SetOutChunkSize(max_chunk_size_); std::shared_ptr<char> data(new char[4], std::default_delete<char[]>()); WriteUint32BE((char*)data.get(), max_chunk_size_); RtmpMessage rtmp_msg; rtmp_msg.type_id = RTMP_SET_CHUNK_SIZE; rtmp_msg.payload = data; rtmp_msg.length = 4; SendRtmpChunks(RTMP_CHUNK_CONTROL_ID, rtmp_msg); } void RtmpConnection::setPlayCB(const PlayCallback& cb) { play_cb_ = cb; } bool RtmpConnection::SendInvokeMessage(uint32_t csid, std::shared_ptr<char> payload, uint32_t payload_size) { if(this->IsClosed()) { return false; } RtmpMessage rtmp_msg; rtmp_msg.type_id = RTMP_INVOKE; rtmp_msg.timestamp = 0; rtmp_msg.stream_id = stream_id_; rtmp_msg.payload = payload; rtmp_msg.length = payload_size; SendRtmpChunks(csid, rtmp_msg); return true; } bool RtmpConnection::SendNotifyMessage(uint32_t csid, std::shared_ptr<char> payload, uint32_t payload_size) { if(this->IsClosed()) { return false; } RtmpMessage rtmp_msg; rtmp_msg.type_id = RTMP_NOTIFY; rtmp_msg.timestamp = 0; rtmp_msg.stream_id = stream_id_; rtmp_msg.payload = payload; rtmp_msg.length = payload_size; SendRtmpChunks(csid, rtmp_msg); return true; } bool RtmpConnection::IsKeyFrame(std::shared_ptr<char> payload, uint32_t payload_size) { uint8_t frame_type = (payload.get()[0] >> 4) & 0x0f; uint8_t codec_id = payload.get()[0] & 0x0f; return (frame_type == 1 && codec_id == RTMP_CODEC_ID_H264); } bool RtmpConnection::SendMediaData(uint8_t type, uint64_t timestamp, std::shared_ptr<char> payload, uint32_t payload_size) { if(this->IsClosed()) { return false; } if (payload_size == 0) { return false; } is_playing_ = true; if (type == RTMP_AVC_SEQUENCE_HEADER) { avc_sequence_header_ = payload; avc_sequence_header_size_ = payload_size; } else if (type == RTMP_AAC_SEQUENCE_HEADER) { aac_sequence_header_ = payload; aac_sequence_header_size_ = payload_size; } auto conn = std::dynamic_pointer_cast<RtmpConnection>(shared_from_this()); task_scheduler_->AddTriggerEvent([conn, type, timestamp, payload, payload_size] { if (!conn->has_key_frame_ && conn->avc_sequence_header_size_ > 0 && (type != RTMP_AVC_SEQUENCE_HEADER) && (type != RTMP_AAC_SEQUENCE_HEADER)) { if (conn->IsKeyFrame(payload, payload_size)) { conn->has_key_frame_ = true; } else { return ; } } RtmpMessage rtmp_msg; rtmp_msg._timestamp = timestamp; rtmp_msg.stream_id = conn->stream_id_; rtmp_msg.payload = payload; rtmp_msg.length = payload_size; if (type == RTMP_VIDEO || type == RTMP_AVC_SEQUENCE_HEADER) { rtmp_msg.type_id = RTMP_VIDEO; conn->SendRtmpChunks(RTMP_CHUNK_VIDEO_ID, rtmp_msg); } else if (type == RTMP_AUDIO || type == RTMP_AAC_SEQUENCE_HEADER) { rtmp_msg.type_id = RTMP_AUDIO; conn->SendRtmpChunks(RTMP_CHUNK_AUDIO_ID, rtmp_msg); } }); return true; } bool RtmpConnection::SendVideoData(uint64_t timestamp, std::shared_ptr<char> payload, uint32_t payload_size) { if (payload_size == 0) { return false; } auto conn = std::dynamic_pointer_cast<RtmpConnection>(shared_from_this()); task_scheduler_->AddTriggerEvent([conn, timestamp, payload, payload_size] { RtmpMessage rtmp_msg; rtmp_msg.type_id = RTMP_VIDEO; rtmp_msg._timestamp = timestamp; rtmp_msg.stream_id = conn->stream_id_; rtmp_msg.payload = payload; rtmp_msg.length = payload_size; conn->SendRtmpChunks(RTMP_CHUNK_VIDEO_ID, rtmp_msg); }); return true; } bool RtmpConnection::SendAudioData(uint64_t timestamp, std::shared_ptr<char> payload, uint32_t payload_size) { if (payload_size == 0) { return false; } auto conn = std::dynamic_pointer_cast<RtmpConnection>(shared_from_this()); task_scheduler_->AddTriggerEvent([conn, timestamp, payload, payload_size] { RtmpMessage rtmp_msg; rtmp_msg.type_id = RTMP_AUDIO; rtmp_msg._timestamp = timestamp; rtmp_msg.stream_id = conn->stream_id_; rtmp_msg.payload = payload; rtmp_msg.length = payload_size; conn->SendRtmpChunks(RTMP_CHUNK_VIDEO_ID, rtmp_msg); }); return true; } void RtmpConnection::SendRtmpChunks(uint32_t csid, RtmpMessage& rtmp_msg) { uint32_t capacity = rtmp_msg.length + rtmp_msg.length/ max_chunk_size_ *5 + 1024; std::shared_ptr<char> buffer(new char[capacity], std::default_delete<char[]>()); int size = rtmp_chunk_->CreateChunk(csid, rtmp_msg, buffer.get(), capacity); if (size > 0) { this->Send(buffer.get(), size); } }
28.788807
138
0.658732
JungleZy
93d76a4d4cbe0476bba5e2b6fafa268ed4a68046
573
hpp
C++
508 - A4-spbspu-labs-2020-904-3/spbspu-labs-2020-904-3-master-yakovlev.alexey/3/A1/base-types.hpp
NekoSilverFox/CPP
c6797264fceda4a65ac3452acca496e468d1365a
[ "Apache-2.0" ]
5
2020-02-08T20:57:21.000Z
2021-12-23T06:24:41.000Z
508 - A4-spbspu-labs-2020-904-3/spbspu-labs-2020-904-3-master-yakovlev.alexey/3/A1/base-types.hpp
NekoSilverFox/CPP
c6797264fceda4a65ac3452acca496e468d1365a
[ "Apache-2.0" ]
2
2020-03-02T14:44:55.000Z
2020-11-11T16:25:33.000Z
508 - A4-spbspu-labs-2020-904-3/spbspu-labs-2020-904-3-master-yakovlev.alexey/3/A1/base-types.hpp
NekoSilverFox/CPP
c6797264fceda4a65ac3452acca496e468d1365a
[ "Apache-2.0" ]
4
2020-09-27T17:30:03.000Z
2022-02-16T09:48:23.000Z
#ifndef YAKOVLEV_BASE #define YAKOVLEV_BASE #include <ios> struct point_t { double x; double y; }; bool operator==(const point_t &lhs, const point_t &rhs); bool operator!=(const point_t &lhs, const point_t &rhs); std::ostream& operator<<(std::ostream &os, const point_t &point); double getDistanceBetweenPoints(const point_t &p1, const point_t &p2); struct rectangle_t { double width; double height; point_t pos; }; bool operator==(const rectangle_t &lhs, const rectangle_t &rhs); bool operator!=(const rectangle_t &lhs, const rectangle_t &rhs); #endif
17.90625
70
0.731239
NekoSilverFox
93d7cb0b25270dc678d7f1828d4f934df0f26f62
4,497
hpp
C++
src/graphlab/serialization/vector.hpp
iivek/graphlab-cmu-mirror
028321757ea979e6a0859687e37933be375153eb
[ "ECL-2.0", "Apache-2.0" ]
1
2018-08-01T06:32:58.000Z
2018-08-01T06:32:58.000Z
src/graphlab/serialization/vector.hpp
iivek/graphlab-cmu-mirror
028321757ea979e6a0859687e37933be375153eb
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/graphlab/serialization/vector.hpp
iivek/graphlab-cmu-mirror
028321757ea979e6a0859687e37933be375153eb
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/** * Copyright (c) 2009 Carnegie Mellon University. * 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. * * For more about this software visit: * * http://www.graphlab.ml.cmu.edu * */ #ifndef GRAPHLAB_SERIALIZE_VECTOR_HPP #define GRAPHLAB_SERIALIZE_VECTOR_HPP #include <vector> #include <graphlab/serialization/iarchive.hpp> #include <graphlab/serialization/oarchive.hpp> #include <graphlab/serialization/iterator.hpp> namespace graphlab { namespace archive_detail { /** * We re-dispatch vectors because based on the contained type, * it is actually possible to serialize them like a POD */ template <typename ArcType, typename ValueType, bool IsPOD> struct vector_serialize_impl { static void exec(ArcType &a, const ValueType& vec) { // really this is an assert false. But the static assert // must depend on a template parameter BOOST_STATIC_ASSERT(sizeof(ArcType) == 0); assert(false); }; }; /** * We re-dispatch vectors because based on the contained type, * it is actually possible to deserialize them like a POD */ template <typename ArcType, typename ValueType, bool IsPOD> struct vector_deserialize_impl { static void exec(ArcType &a, ValueType& vec) { // really this is an assert false. But the static assert // must depend on a template parameter BOOST_STATIC_ASSERT(sizeof(ArcType) == 0); assert(false); }; }; /// If contained type is not a POD use the standard serializer template <typename ArcType, typename ValueType> struct vector_serialize_impl<ArcType, ValueType, false > { static void exec(ArcType &a, const std::vector<ValueType>& vec) { serialize_impl<ArcType, size_t, false>::exec(a, vec.size()); serialize_iterator(a,vec.begin(), vec.end()); } }; /// Fast vector serialization if contained type is a POD template <typename ArcType, typename ValueType> struct vector_serialize_impl<ArcType, ValueType, true > { static void exec(ArcType &a, const std::vector<ValueType>& vec) { serialize_impl<ArcType, size_t, false>::exec(a, vec.size()); serialize(a, &(vec[0]),sizeof(ValueType)*vec.size()); } }; /// If contained type is not a POD use the standard deserializer template <typename ArcType, typename ValueType> struct vector_deserialize_impl<ArcType, ValueType, false > { static void exec(ArcType& a, std::vector<ValueType>& vec){ size_t len; deserialize_impl<ArcType, size_t, false>::exec(a, len); vec.clear(); vec.reserve(len); deserialize_iterator<ArcType, ValueType>(a, std::inserter(vec, vec.end())); } }; /// Fast vector deserialization if contained type is a POD template <typename ArcType, typename ValueType> struct vector_deserialize_impl<ArcType, ValueType, true > { static void exec(ArcType& a, std::vector<ValueType>& vec){ size_t len; deserialize_impl<ArcType, size_t, false>::exec(a, len); vec.clear(); vec.resize(len); deserialize(a, &(vec[0]), sizeof(ValueType)*vec.size()); } }; /** Serializes a vector */ template <typename ArcType, typename ValueType> struct serialize_impl<ArcType, std::vector<ValueType>, false > { static void exec(ArcType &a, const std::vector<ValueType>& vec) { vector_serialize_impl<ArcType, ValueType, gl_is_pod<ValueType>::value>::exec(a, vec); } }; /** deserializes a vector */ template <typename ArcType, typename ValueType> struct deserialize_impl<ArcType, std::vector<ValueType>, false > { static void exec(ArcType& a, std::vector<ValueType>& vec){ vector_deserialize_impl<ArcType, ValueType, gl_is_pod<ValueType>::value>::exec(a, vec); } }; } // archive_detail } // namespace graphlab #endif
36.266129
95
0.66978
iivek
93de5aefe281faec3eed55cdfbdb5467c4f7dc05
5,294
cpp
C++
src/phyx-1.01/src/main_rlt.cpp
jlanga/smsk_selection
08070c6d4a6fbd9320265e1e698c95ba80f81123
[ "MIT" ]
4
2021-07-18T05:20:20.000Z
2022-01-03T10:22:33.000Z
src/phyx-1.01/src/main_rlt.cpp
jlanga/smsk_selection
08070c6d4a6fbd9320265e1e698c95ba80f81123
[ "MIT" ]
1
2017-08-21T07:26:13.000Z
2018-11-08T13:59:48.000Z
src/phyx-1.01/src/main_rlt.cpp
jlanga/smsk_orthofinder
08070c6d4a6fbd9320265e1e698c95ba80f81123
[ "MIT" ]
2
2021-07-18T05:20:26.000Z
2022-03-31T18:23:31.000Z
#include <iostream> #include <fstream> #include <vector> #include <string> #include <cstring> #include <getopt.h> using namespace std; #include "utils.h" #include "tree_reader.h" #include "relabel.h" #include "tree_utils.h" #include "log.h" void print_help() { cout << "Taxon relabelling for trees." << endl; cout << "This will take nexus and newick inputs." << endl; cout << "Two ordered lists of taxa, -c (current) and -n (new) must be provided." << endl; cout << endl; cout << "Usage: pxrlt [OPTION]... " << endl; cout << endl; cout << " -t, --treef=FILE input tree file, stdin otherwise" << endl; cout << " -c, --cnames=FILE file containing current taxon labels (one per line)" << endl; cout << " -n, --nnames=FILE file containing new taxon labels (one per line)" << endl; cout << " -o, --outf=FILE output file, stout otherwise" << endl; cout << " -v, --verbose make the output more verbose" << endl; cout << " -h, --help display this help and exit" << endl; cout << " -V, --version display version and exit" << endl; cout << endl; cout << "Report bugs to: <https://github.com/FePhyFoFum/phyx/issues>" << endl; cout << "phyx home page: <https://github.com/FePhyFoFum/phyx>" << endl; } string versionline("pxrlt 0.1\nCopyright (C) 2018 FePhyFoFum\nLicense GPLv3\nwritten by Joseph W. Brown, Stephen A. Smith (blackrim)"); static struct option const long_options[] = { {"treef", required_argument, NULL, 't'}, {"cnames", required_argument, NULL, 'c'}, {"nnames", required_argument, NULL, 'n'}, {"outf", required_argument, NULL, 'o'}, {"verbose", no_argument, NULL, 'v'}, {"help", no_argument, NULL, 'h'}, {"version", no_argument, NULL, 'V'}, {NULL, 0, NULL, 0} }; int main(int argc, char * argv[]) { log_call(argc, argv); bool outfileset = false; bool tfileset = false; bool cfileset = false; bool nfileset = false; bool verbose = false; char * outf = NULL; char * treef = NULL; string cnamef = ""; string nnamef = ""; while (1) { int oi = -1; int c = getopt_long(argc, argv, "t:c:n:o:vhV", long_options, &oi); if (c == -1) { break; } switch(c) { case 't': tfileset = true; treef = strdup(optarg); check_file_exists(treef); break; case 'c': cfileset = true; cnamef = strdup(optarg); check_file_exists(cnamef.c_str()); break; case 'n': nfileset = true; nnamef = strdup(optarg); check_file_exists(nnamef.c_str()); break; case 'o': outfileset = true; outf = strdup(optarg); break; case 'v': verbose = true; break; case 'h': print_help(); exit(0); case 'V': cout << versionline << endl; exit(0); default: print_error(argv[0], (char)c); exit(0); } } if (tfileset && outfileset) { check_inout_streams_identical(treef, outf); } istream * pios = NULL; ostream * poos = NULL; ifstream * fstr = NULL; ofstream * ofstr = NULL; if (!nfileset | !cfileset) { cerr << "Must supply both name files (-c for current, -n for new)." << endl; exit(0); } if (tfileset == true) { fstr = new ifstream(treef); pios = fstr; } else { pios = &cin; if (check_for_input_to_stream() == false) { print_help(); exit(1); } } if (outfileset == true) { ofstr = new ofstream(outf); poos = ofstr; } else { poos = &cout; } Relabel rl (cnamef, nnamef, verbose); string retstring; int ft = test_tree_filetype_stream(*pios, retstring); if (ft != 0 && ft != 1) { cerr << "this really only works with nexus or newick" << endl; exit(0); } bool going = true; if (ft == 1) { Tree * tree; while (going) { tree = read_next_tree_from_stream_newick(*pios, retstring, &going); if (going) { rl.relabel_tree(tree); (*poos) << getNewickString(tree) << endl; delete tree; } } } else if (ft == 0) { // Nexus. need to worry about possible translation tables map <string, string> translation_table; bool ttexists; ttexists = get_nexus_translation_table(*pios, &translation_table, &retstring); Tree * tree; while (going) { tree = read_next_tree_from_stream_nexus(*pios, retstring, ttexists, &translation_table, &going); if (tree != NULL) { rl.relabel_tree(tree); (*poos) << getNewickString(tree) << endl; delete tree; } } } if (outfileset) { ofstr->close(); delete poos; } return EXIT_SUCCESS; }
30.079545
135
0.513411
jlanga
93de959e2074203e27e6365e684acc22f4415261
1,320
cc
C++
test/lazy_string_unittest.cc
Mercy1101/my_log
593dddc9cc4d7b6f2fa51176c7f83429fe43c266
[ "MIT" ]
null
null
null
test/lazy_string_unittest.cc
Mercy1101/my_log
593dddc9cc4d7b6f2fa51176c7f83429fe43c266
[ "MIT" ]
null
null
null
test/lazy_string_unittest.cc
Mercy1101/my_log
593dddc9cc4d7b6f2fa51176c7f83429fe43c266
[ "MIT" ]
null
null
null
/// Copyright (c) 2019,2020 Lijiancong. All rights reserved. /// /// Use of this source code is governed by a MIT license /// that can be found in the License file. #include "my_log/lazy_string.hpp" #include <catch2/catch.hpp> #include "profiler.hpp" TEST_CASE("lazy_string", "[my_log][lazy_string]") { { PROFILER_F(); for (int i = 0; i < 10000; ++i) { lee::lazy_string_concat_helper<> lazy_concat; std::string str_log = lazy_concat + lee::get_time_string() + " " + std::to_string(i) + " " + " <In Function: " + std::to_string(0.0 + i) + "," + ", File: " + "lksjdflksdjflkdsjlkdsfjldskfjsdlkfjslkdfjlksddjfsl" + " Line: " + std::to_string(__LINE__) + ", PID: " + __FILE__ + ">\n"; std::cout << str_log << std::endl; } } } TEST_CASE("string", "[my_log][lazy_string]") { { PROFILER_F(); for (int i = 0; i < 10000; ++i) { std::string lazy_concat; std::string str_log = lazy_concat + lee::get_time_string() + " " + std::to_string(i) + " " + " <In Function: " + std::to_string(0.0 + i) + "," + ", File: " + "lksjdflksdjflkdsjlkdsfjldskfjsdlkfjslkdfjlksddjfsl" + " Line: " + std::to_string(__LINE__) + ", PID: " + __FILE__ + ">\n"; std::cout << str_log << std::endl; } } }
32.195122
80
0.567424
Mercy1101
93ded1ddca3b29d61cdea4317793aac8c7ebece8
4,247
cpp
C++
src/Solver/g2oEdgeSE3Self.cpp
zjcs/PKVIO
7e26df3f3ee5bf0f44624c2ce94e15d33bb5544b
[ "Unlicense" ]
null
null
null
src/Solver/g2oEdgeSE3Self.cpp
zjcs/PKVIO
7e26df3f3ee5bf0f44624c2ce94e15d33bb5544b
[ "Unlicense" ]
null
null
null
src/Solver/g2oEdgeSE3Self.cpp
zjcs/PKVIO
7e26df3f3ee5bf0f44624c2ce94e15d33bb5544b
[ "Unlicense" ]
null
null
null
#include "g2oEdgeSE3Self.h" #include "g2o/core/factory.h" #include "g2o/stuff/macros.h" namespace g2o { using namespace std; using namespace Eigen; //G2O_REGISTER_TYPE_GROUP(expmap2); //G2O_REGISTER_TYPE(EDGE_SE3:EXPMAP2, EdgeSE3ProjectXYZRight2); //G2O_REGISTER_TYPE(EDGE_SE3:EXPMAP2, EdgeSE3ProjectXYZRight); //EdgeSE3ProjectXYZ2 Vector2 project2d(const Vector3& v) { Vector2 res; res(0) = v(0)/v(2); res(1) = v(1)/v(2); return res; } void EdgeSE3ProjectXYZ2::computeError() { EdgeSE3ProjectXYZ::computeError(); //cout << _error << endl; } void EdgeSE3ProjectXYZ2::linearizeOplus() { EdgeSE3ProjectXYZ::linearizeOplus(); //cout << _jacobianOplusXj <<endl; } void EdgeSE3ProjectXYZRight2::computeError() { const VertexSE3Expmap *v1 = static_cast<const VertexSE3Expmap *>(_vertices[1]); const VertexSBAPointXYZ *v2 = static_cast<const VertexSBAPointXYZ *>(_vertices[0]); Vector2 obs(_measurement); SE3Quat nPrTPw = mPrTPl*v1->estimate(); _error = obs - cam_project(nPrTPw.map(v2->estimate())); //cout << _error <<endl; } void EdgeSE3ProjectXYZRight2::linearizeOplus() { VertexSE3Expmap *vj = static_cast<VertexSE3Expmap *>(_vertices[1]); SE3Quat T(vj->estimate()); VertexSBAPointXYZ *vi = static_cast<VertexSBAPointXYZ *>(_vertices[0]); Vector3 xyz = vi->estimate(); Vector3 xyz_cl = T.map(xyz); Vector3 xyz_cr = mPrTPl.map(xyz_cl); Vector3 xyz_trans = xyz_cr; number_t x = xyz_trans[0]; number_t y = xyz_trans[1]; number_t z = xyz_trans[2]; number_t z_2 = z * z; Matrix<number_t, 2, 3> tmp; tmp(0, 0) = fx; tmp(0, 1) = 0; tmp(0, 2) = -x / z * fx; tmp(1, 0) = 0; tmp(1, 1) = fy; tmp(1, 2) = -y / z * fy; _jacobianOplusXi = -1. / z * tmp * T.rotation().toRotationMatrix(); Matrix<number_t, 3, 6> tmp2; tmp2.topLeftCorner(3,3) << 0, xyz_cl(2), -xyz_cl(1), -xyz_cl(2), 0, xyz_cl(0), xyz_cl(1), -xyz_cl(0), 0; tmp2.topRightCorner(3,3) = Matrix<number_t, 3, 3>::Identity(); _jacobianOplusXj = -1./z * tmp * mPrTPl.rotation().toRotationMatrix() * tmp2; //cout << xyz_cl<<endl; //cout << _jacobianOplusXj <<endl; } Vector2 EdgeSE3ProjectXYZRight::cam_project(const Vector3& trans_xyz) const { Vector2 proj = project2d(trans_xyz); Vector2 res; res[0] = proj[0] * fx + cx; res[1] = proj[1] * fy + cy; return res; } bool EdgeSE3ProjectXYZRight::write(std::ostream& os) const { for (int i = 0; i < 2; i++) { os << measurement()[i] << " "; } for (int i = 0; i < 2; i++) for (int j = i; j < 2; j++) { os << " " << information()(i, j); } return os.good(); } bool EdgeSE3ProjectXYZRight::read(std::istream& is) { for (int i = 0; i < 2; i++) { is >> _measurement[i]; } for (int i = 0; i < 2; i++) for (int j = i; j < 2; j++) { is >> information()(i, j); if (i != j) information()(j, i) = information()(i, j); } return true; } void EdgeSE3ProjectXYZRight::linearizeOplus() { VertexSE3Expmap *vj = static_cast<VertexSE3Expmap *>(_vertices[1]); SE3Quat T(vj->estimate()); VertexSBAPointXYZ *vi = static_cast<VertexSBAPointXYZ *>(_vertices[0]); Vector3 xyz = vi->estimate(); Vector3 xyz_cl = T.map(xyz); Vector3 xyz_cr = mPrTPl.map(xyz_cl); Vector3 xyz_trans = xyz_cr; number_t x = xyz_trans[0]; number_t y = xyz_trans[1]; number_t z = xyz_trans[2]; number_t z_2 = z * z; Matrix<number_t, 2, 3> tmp; tmp(0, 0) = fx; tmp(0, 1) = 0; tmp(0, 2) = -x / z * fx; tmp(1, 0) = 0; tmp(1, 1) = fy; tmp(1, 2) = -y / z * fy; _jacobianOplusXi = -1. / z * tmp * T.rotation().toRotationMatrix(); Matrix<number_t, 3, 6> tmp2; tmp2.topLeftCorner(3,3) << 0, xyz_cl(2), -xyz_cl(1), -xyz_cl(2), 0, xyz_cl(0), xyz_cl(1), -xyz_cl(0), 0; tmp2.topRightCorner(3,3) = Matrix<number_t, 3, 3>::Identity(); _jacobianOplusXj = -1./z * tmp * mPrTPl.rotation().toRotationMatrix() * tmp2; } /* */ }
26.879747
87
0.579703
zjcs
93e0c4ff2741f421254fd37d5e6b3a1d59563211
17,835
cpp
C++
src/interpreter/library/fn_d3d.cpp
Grossley/opengml
bc3494aae64092f1c32a16361fd781249e2ea630
[ "MIT" ]
26
2019-07-18T04:45:08.000Z
2022-03-13T09:52:04.000Z
src/interpreter/library/fn_d3d.cpp
Grossley/opengml
bc3494aae64092f1c32a16361fd781249e2ea630
[ "MIT" ]
6
2021-09-10T00:48:00.000Z
2021-11-27T22:00:48.000Z
src/interpreter/library/fn_d3d.cpp
Grossley/opengml
bc3494aae64092f1c32a16361fd781249e2ea630
[ "MIT" ]
9
2019-07-26T06:32:53.000Z
2022-01-12T14:38:59.000Z
#include "libpre.h" #include "fn_d3d.h" #include "libpost.h" #include "ogm/interpreter/Variable.hpp" #include "ogm/common/error.hpp" #include "ogm/common/util.hpp" #include "ogm/interpreter/Executor.hpp" #include "ogm/interpreter/execute.hpp" #include "ogm/interpreter/display/Display.hpp" #include "ogm/geometry/Vector.hpp" #include "ogm/common/error.hpp" #include <string> #include <cctype> #include <cstdlib> using namespace ogm::interpreter; using namespace ogm::interpreter::fn; #define frame staticExecutor.m_frame #define display frame.m_display namespace { const std::array<real_t, 16> k_identity = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; } void ogm::interpreter::fn::d3d_set_fog(VO out, V enable, V colour, V start, V end) { display->set_fog(enable.castCoerce<bool>(), start.castCoerce<real_t>(), end.castCoerce<real_t>(), colour.castCoerce<int32_t>()); } void ogm::interpreter::fn::d3d_start(VO out) { display->set_depth_test(true); display->set_culling(false); // TODO: true? display->set_zwrite(true); } void ogm::interpreter::fn::d3d_end(VO out) { display->set_depth_test(false); display->set_culling(false); display->set_zwrite(false); display->set_matrix_projection(k_identity); } void ogm::interpreter::fn::d3d_set_hidden(VO out, V enable) { display->set_depth_test(enable.cond()); } void ogm::interpreter::fn::d3d_set_culling(VO out, V enable) { display->set_culling(enable.cond()); } void ogm::interpreter::fn::d3d_set_zwriteenable(VO out, V enable) { display->set_zwrite(enable.cond()); } void ogm::interpreter::fn::d3d_set_projection(VO out, V xfrom, V yfrom, V zfrom, V xto, V yto, V zto, V xup, V yup, V zup) { display->set_camera( xfrom.castCoerce<real_t>(), yfrom.castCoerce<real_t>(), zfrom.castCoerce<real_t>(), xto.castCoerce<real_t>(), yto.castCoerce<real_t>(), zto.castCoerce<real_t>(), xup.castCoerce<real_t>(), yup.castCoerce<real_t>(), zup.castCoerce<real_t>(), 45.0, display->get_window_dimensions().x / display->get_window_dimensions().y, 0.5, 100000.0 ); } void ogm::interpreter::fn::d3d_set_projection_ext(VO out, V xfrom, V yfrom, V zfrom, V xto, V yto, V zto, V xup, V yup, V zup, V fovangle, V aspect, V znear, V zfar) { display->set_camera( xfrom.castCoerce<real_t>(), yfrom.castCoerce<real_t>(), zfrom.castCoerce<real_t>(), xto.castCoerce<real_t>(), yto.castCoerce<real_t>(), zto.castCoerce<real_t>(), xup.castCoerce<real_t>(), yup.castCoerce<real_t>(), zup.castCoerce<real_t>(), fovangle.castCoerce<real_t>() * TAU / 360.0, aspect.castCoerce<real_t>(), znear.castCoerce<real_t>(), zfar.castCoerce<real_t>() ); } void ogm::interpreter::fn::d3d_set_projection_ortho(VO out, V x, V y, V width, V height, V angle) { display->set_camera_ortho( x.castCoerce<real_t>(), y.castCoerce<real_t>(), width.castCoerce<real_t>(), height.castCoerce<real_t>(), angle.castCoerce<real_t>() * TAU / 360.0 ); } // NOTE: NOT CURRENTLY SERIALIZED namespace { TextureView* g_view = nullptr; std::vector<float> g_vertices; uint32_t g_vertex_type; bool active = false; } void ogm::interpreter::fn::d3d_primitive_begin(VO out, V type) { if (active) { throw MiscError("cannot begin d3d_vertex while already in progress."); } else { active = true; } g_vertices.clear(); g_view = nullptr; g_vertex_type = type.castCoerce<uint32_t>(); } void ogm::interpreter::fn::d3d_primitive_begin_texture(VO out, V type, V tex) { if (active) { throw MiscError("cannot begin d3d_vertex while already in progress."); } else { active = true; } g_vertices.clear(); g_view = static_cast<TextureView*>(tex.castExact<void*>()); g_vertex_type = type.castCoerce<uint32_t>(); } namespace { void push_colour(std::vector<float>& vertices, uint32_t colour, float alpha) { vertices.push_back((colour & (0xff0000) >> 16) / 255.0); vertices.push_back((colour & (0x00ff00) >> 8) / 255.0); vertices.push_back((colour & (0x0000ff) >> 0) / 255.0); vertices.push_back(alpha); } } void ogm::interpreter::fn::d3d_vertex(VO out, V x, V y, V z) { if (!active) { throw MiscError("d3d_vertex requires d3d_primitive_begin."); } else { // vertex g_vertices.push_back(x.castCoerce<real_t>()); g_vertices.push_back(y.castCoerce<real_t>()); g_vertices.push_back(z.castCoerce<real_t>()); // colour push_colour(g_vertices, 0xffffff, 1.0); // texture coordinates g_vertices.push_back(0.0f); g_vertices.push_back(0.0f); } } void ogm::interpreter::fn::d3d_vertex_colour(VO out, V x, V y, V z, V c, V alpha) { if (!active) { throw MiscError("d3d_vertex requires d3d_primitive_begin."); } else { // vertex g_vertices.push_back(x.castCoerce<real_t>()); g_vertices.push_back(y.castCoerce<real_t>()); g_vertices.push_back(z.castCoerce<real_t>()); // colour push_colour(g_vertices, 0xffffff, 1.0); // texture coordinates g_vertices.push_back(0.0f); g_vertices.push_back(0.0f); } } void ogm::interpreter::fn::d3d_vertex_texture(VO out, V x, V y, V z, V u, V v) { if (!active) { throw MiscError("d3d_vertex requires d3d_primitive_begin."); } else { // vertex g_vertices.push_back(x.castCoerce<real_t>()); g_vertices.push_back(y.castCoerce<real_t>()); g_vertices.push_back(z.castCoerce<real_t>()); // colour push_colour(g_vertices, 0xffffff, 1.0); // texture coordinates g_vertices.push_back(g_view->u_global(u.castCoerce<real_t>())); g_vertices.push_back(g_view->v_global(v.castCoerce<real_t>())); } } void ogm::interpreter::fn::d3d_vertex_texture_colour(VO out, V x, V y, V z, V u, V v, V c, V alpha) { if (!active) { throw MiscError("d3d_vertex requires d3d_primitive_begin."); } else { std::array<real_t, 3> vertices = { x.castCoerce<real_t>(), y.castCoerce<real_t>(), z.castCoerce<real_t>(), }; // vertex g_vertices.push_back(vertices[0]); g_vertices.push_back(vertices[1]); g_vertices.push_back(vertices[2]); // colour push_colour(g_vertices, c.castCoerce<real_t>(), alpha.castCoerce<real_t>()); // texture coordinates g_vertices.push_back(g_view->u_global(u.castCoerce<real_t>())); g_vertices.push_back(g_view->v_global(v.castCoerce<real_t>())); } } void ogm::interpreter::fn::d3d_primitive_end(VO out) { if (!active) { throw MiscError("d3d_primitive_end requires d3d_primitive_begin."); } else { display->render_array( g_vertices.size(), &g_vertices.at(0), nullptr, g_vertex_type ); g_vertices.clear(); g_view = nullptr; active = false; } } void ogm::interpreter::fn::d3d_transform_set_identity(VO out) { display->transform_identity(); } void ogm::interpreter::fn::d3d_transform_set_translation(VO out, V x, V y, V z) { display->transform_identity(); std::array<float, 16> mat = { 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, static_cast<float>(x.castCoerce<real_t>()), static_cast<float>(y.castCoerce<real_t>()), static_cast<float>(z.castCoerce<real_t>()), 1.0 }; display->transform_apply(mat); } void ogm::interpreter::fn::d3d_transform_set_scaling(VO out, V x, V y, V z) { display->transform_identity(); std::array<float, 16> mat = { static_cast<float>(x.castCoerce<real_t>()), 0.0, 0.0, 0.0, 0.0, static_cast<float>(y.castCoerce<real_t>()), 0.0, 0.0, 0.0, 0.0, static_cast<float>(z.castCoerce<real_t>()), 0.0, 0.0, 0.0, 0.0, 1.0 }; display->transform_apply(mat); } void ogm::interpreter::fn::d3d_transform_set_rotation_x(VO out, V theta) { display->transform_identity(); display->transform_apply_rotation(theta.castCoerce<real_t>(), 1, 0, 0); } void ogm::interpreter::fn::d3d_transform_set_rotation_y(VO out, V theta) { display->transform_identity(); display->transform_apply_rotation(theta.castCoerce<real_t>(), 0, 1, 0); } void ogm::interpreter::fn::d3d_transform_set_rotation_z(VO out, V theta) { display->transform_identity(); display->transform_apply_rotation(theta.castCoerce<real_t>(), 0, 0, 1); } void ogm::interpreter::fn::d3d_transform_set_rotation_axis(VO out, V theta, V x, V y, V z) { if (x != 0 || y != 0 || z != 0) { display->transform_apply_rotation(theta.castCoerce<real_t>(), x.castCoerce<real_t>(), y.castCoerce<real_t>(), z.castCoerce<real_t>() ); } } void ogm::interpreter::fn::d3d_transform_add_translation(VO out, V x, V y, V z) { std::array<float, 16> mat = { 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, static_cast<float>(x.castCoerce<real_t>()), static_cast<float>(y.castCoerce<real_t>()), static_cast<float>(z.castCoerce<real_t>()), 1.0 }; display->transform_apply(mat); } void ogm::interpreter::fn::d3d_transform_add_scaling(VO out, V x, V y, V z) { std::array<float, 16> mat = { static_cast<float>(x.castCoerce<real_t>()), 0.0, 0.0, 0.0, 0.0, static_cast<float>(y.castCoerce<real_t>()), 0.0, 0.0, 0.0, 0.0, static_cast<float>(z.castCoerce<real_t>()), 0.0, 0.0, 0.0, 0.0, 1.0 }; display->transform_apply(mat); } void ogm::interpreter::fn::d3d_transform_add_rotation_x(VO out, V theta) { display->transform_apply_rotation(theta.castCoerce<real_t>(), 1, 0, 0); } void ogm::interpreter::fn::d3d_transform_add_rotation_y(VO out, V theta) { display->transform_apply_rotation(theta.castCoerce<real_t>(), 0, 1, 0); } void ogm::interpreter::fn::d3d_transform_add_rotation_z(VO out, V theta) { display->transform_apply_rotation(theta.castCoerce<real_t>(), 0, 0, 1); } void ogm::interpreter::fn::d3d_transform_add_rotation_axis(VO out, V theta, V x, V y, V z) { if (x != 0 || y != 0 || z != 0) { display->transform_apply_rotation(theta.castCoerce<real_t>(), x.castCoerce<real_t>(), y.castCoerce<real_t>(), z.castCoerce<real_t>() ); } } void ogm::interpreter::fn::d3d_transform_stack_clear(VO out) { display->transform_stack_clear(); } void ogm::interpreter::fn::d3d_transform_stack_empty(VO out) { out = display->transform_stack_empty(); } void ogm::interpreter::fn::d3d_transform_stack_push(VO out) { out = display->transform_stack_push(); } void ogm::interpreter::fn::d3d_transform_stack_pop(VO out) { out = display->transform_stack_pop(); } void ogm::interpreter::fn::d3d_transform_stack_top(VO out) { out = display->transform_stack_top(); } void ogm::interpreter::fn::d3d_transform_stack_discard(VO out) { out = display->transform_stack_discard(); } void ogm::interpreter::fn::d3d_transform_vertex(VO out, V x, V y, V z) { std::array<real_t, 3> a; a[0] = x.castCoerce<real_t>(); a[1] = y.castCoerce<real_t>(); a[2] = z.castCoerce<real_t>(); display->transform_vertex(a); out.array_ensure(); out.array_get(OGM_2DARRAY_DEFAULT_ROW 2) = a[2]; out.array_get(OGM_2DARRAY_DEFAULT_ROW 1) = a[1]; out.array_get(OGM_2DARRAY_DEFAULT_ROW 0) = a[0]; } void ogm::interpreter::fn::d3d_transform_vertex_model_view(VO out, V x, V y, V z) { std::array<real_t, 3> a; a[0] = x.castCoerce<real_t>(); a[1] = y.castCoerce<real_t>(); a[2] = z.castCoerce<real_t>(); display->transform_vertex_mv(a); out.array_ensure(); out.array_get(OGM_2DARRAY_DEFAULT_ROW 2) = a[2]; out.array_get(OGM_2DARRAY_DEFAULT_ROW 1) = a[1]; out.array_get(OGM_2DARRAY_DEFAULT_ROW 0) = a[0]; } void ogm::interpreter::fn::d3d_transform_vertex_model_view_projection(VO out, V x, V y, V z) { std::array<real_t, 3> a; a[0] = x.castCoerce<real_t>(); a[1] = y.castCoerce<real_t>(); a[2] = z.castCoerce<real_t>(); display->transform_vertex_mvp(a); out.array_ensure(); out.array_get(OGM_2DARRAY_DEFAULT_ROW 2) = a[2]; out.array_get(OGM_2DARRAY_DEFAULT_ROW 1) = a[1]; out.array_get(OGM_2DARRAY_DEFAULT_ROW 0) = a[0]; } void ogm::interpreter::fn::d3d_draw_floor(VO out, V x1, V y1, V z1, V x2, V y2, V z2, V vtex, V hrepeat, V vrepeat) { if (active) throw MiscError("Cannot draw d3d_* while primitive in progress."); display->set_matrix_pre_model(); real_t x[2], y[2], z[2]; x[0] = x1.castCoerce<real_t>(); y[0] = y1.castCoerce<real_t>(); z[0] = z1.castCoerce<real_t>(); x[1] = x2.castCoerce<real_t>(); y[1] = y2.castCoerce<real_t>(); z[1] = z2.castCoerce<real_t>(); TextureView* tv = nullptr; if (vtex.get_type() == VT_PTR) { tv = static_cast<TextureView*>(vtex.castExact<void*>()); } int32_t hrep = 1, vrep = 1; if (tv) { hrep = hrepeat.castCoerce<int32_t>(); vrep = vrepeat.castCoerce<int32_t>(); if (hrep < 1) hrep = 1; if (vrep < 1) vrep = 1; } // add vertices for (int h = 0; h < hrep; ++h) { for (int v = 0; v < vrep; ++v) { // OPTIMIZE: use fewer vertices for (int a=0; a < 6; ++a) { int ah = 0, av = 0; if (a == 1 || a == 3 || a == 4) ah = 1; if (a == 2 || a == 4 || a == 5) av = 1; float hp = ((h + ah) / static_cast<float>(hrep)); float vp = ((v + av) / static_cast<float>(vrep)); float _x = x[0] * (1 - hp) + x[1] * hp; float _y = y[0] * (1 - vp) + y[1] * vp; float _z = z[0] * (1 - hp) + z[1] * hp; g_vertices.push_back(_x); g_vertices.push_back(_y); g_vertices.push_back(_z); // colour push_colour(g_vertices, 0xffffff, 1.0); // texture if (tv) { g_vertices.push_back(tv->u_global(ah)); g_vertices.push_back(tv->v_global(av)); } else { g_vertices.push_back(ah); g_vertices.push_back(av); } } } } display->render_array( g_vertices.size(), &g_vertices.at(0), tv ? tv->m_tpage : nullptr, 4 // pr_trianglelist ); g_vertices.clear(); g_view = nullptr; } void ogm::interpreter::fn::d3d_draw_wall(VO out, V x1, V y1, V z1, V x2, V y2, V z2, V vtex, V hrepeat, V vrepeat) { if (active) throw MiscError("Cannot draw d3d_* while primitive in progress."); display->set_matrix_pre_model(); real_t x[2], y[2], z[2]; x[0] = x1.castCoerce<real_t>(); y[0] = y1.castCoerce<real_t>(); z[0] = z1.castCoerce<real_t>(); x[1] = x2.castCoerce<real_t>(); y[1] = y2.castCoerce<real_t>(); z[1] = z2.castCoerce<real_t>(); TextureView* tv = nullptr; if (vtex.get_type() == VT_PTR) { tv = static_cast<TextureView*>(vtex.castExact<void*>()); } int32_t hrep = 1, vrep = 1; if (tv) { hrep = hrepeat.castCoerce<int32_t>(); vrep = vrepeat.castCoerce<int32_t>(); if (hrep < 1) hrep = 1; if (vrep < 1) vrep = 1; } // add vertices for (int h = 0; h < hrep; ++h) { for (int v = 0; v < vrep; ++v) { // OPTIMIZE: use fewer vertices for (int a = 0; a < 6; ++a) { int ah = 0, av = 0; if (a == 1 || a == 3 || a == 4) ah = 1; if (a == 2 || a == 4 || a == 5) av = 1; float hp = ((h + ah) / static_cast<float>(hrep)); float vp = ((v + av) / static_cast<float>(vrep)); float _x = x[0] * (1 - hp) + x[1] * hp; float _y = y[0] * (1 - hp) + y[1] * hp; float _z = z[0] * (1 - vp) + z[1] * vp; g_vertices.push_back(_x); g_vertices.push_back(_y); g_vertices.push_back(_z); // colour push_colour(g_vertices, 0xffffff, 1.0); // texture if (tv) { g_vertices.push_back(tv->u_global(ah)); g_vertices.push_back(tv->v_global(av)); } else { g_vertices.push_back(ah); g_vertices.push_back(av); } } } } display->render_array( g_vertices.size(), &g_vertices.at(0), tv ? tv->m_tpage : nullptr, 4 // pr_trianglelist ); g_vertices.clear(); g_view = nullptr; } void ogm::interpreter::fn::d3d_draw_block(VO out, V x1, V y1, V z1, V x2, V y2, V z2, V t, V h, V v) { d3d_draw_floor(out, x1, y2, z1, x2, y1, z1, t, v, h); d3d_draw_wall(out, x1, y2, z1, x1, y1, z2, t, v, h); d3d_draw_wall(out, x2, y1, z1, x2, y2, z2, t, v, h); d3d_draw_wall(out, x1, y1, z1, x2, y1, z2, t, v, h); d3d_draw_wall(out, x2, y2, z1, x1, y2, z2, t, v, h); d3d_draw_floor(out, x1, y1, z2, x2, y2, z2, t, v, h); }
28.309524
165
0.579591
Grossley
93e29e69d75f79963091765e46bd1442850b7342
9,026
cpp
C++
TerrainApps/mfcSimple/mfcSimpleView.cpp
nakijun/vtp
7bd2b2abd3a3f778a32ba30be099cfba9b892922
[ "MIT" ]
4
2019-02-08T13:51:26.000Z
2021-12-07T13:11:06.000Z
TerrainApps/mfcSimple/mfcSimpleView.cpp
nakijun/vtp
7bd2b2abd3a3f778a32ba30be099cfba9b892922
[ "MIT" ]
null
null
null
TerrainApps/mfcSimple/mfcSimpleView.cpp
nakijun/vtp
7bd2b2abd3a3f778a32ba30be099cfba9b892922
[ "MIT" ]
7
2017-12-03T10:13:17.000Z
2022-03-29T09:51:18.000Z
// mfcSimpleView.cpp : implementation of the CSimpleView class // // Copyright (c) 2001-2011 Virtual Terrain Project // Free for all uses, see license.txt for details. // #include "stdafx.h" #include "mfcSimple.h" #include "mfcSimpleDoc.h" #include "mfcSimpleView.h" bool CreateScene(); void CleanupScene(); // Header for the vtlib library #include "vtlib/vtlib.h" #include "vtlib/core/Terrain.h" #include "vtlib/core/TerrainScene.h" #include "vtlib/core/NavEngines.h" #include "vtdata/DataPath.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CSimpleView IMPLEMENT_DYNCREATE(CSimpleView, CView) BEGIN_MESSAGE_MAP(CSimpleView, CView) //{{AFX_MSG_MAP(CSimpleView) ON_WM_DESTROY() ON_WM_CREATE() ON_WM_SIZE() ON_WM_PAINT() ON_WM_LBUTTONDOWN() ON_WM_LBUTTONUP() ON_WM_MOUSEMOVE() ON_WM_RBUTTONDOWN() ON_WM_RBUTTONUP() ON_WM_MBUTTONDOWN() ON_WM_MBUTTONUP() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CSimpleView construction/destruction CSimpleView::CSimpleView() { m_hGLContext = NULL; m_GLPixelIndex = 0; } CSimpleView::~CSimpleView() { } BOOL CSimpleView::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs return CView::PreCreateWindow(cs); } ///////////////////////////////////////////////////////////////////////////// // CSimpleView diagnostics #ifdef _DEBUG void CSimpleView::AssertValid() const { CView::AssertValid(); } void CSimpleView::Dump(CDumpContext& dc) const { CView::Dump(dc); } CSimpleDoc* CSimpleView::GetDocument() // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CSimpleDoc))); return (CSimpleDoc*)m_pDocument; } #endif //_DEBUG void CSimpleView::OnDraw(CDC* pDC) { CSimpleDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); } ///////////////////////////////////////////////////////////////////////////// // CSimpleView message handlers // set Windows Pixel Format BOOL CSimpleView::SetWindowPixelFormat(HDC hDC) { PIXELFORMATDESCRIPTOR pixelDesc; pixelDesc.nSize = sizeof(PIXELFORMATDESCRIPTOR); pixelDesc.nVersion = 1; pixelDesc.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_STEREO_DONTCARE; pixelDesc.iPixelType = PFD_TYPE_RGBA; pixelDesc.cColorBits = 32; pixelDesc.cRedBits = 8; pixelDesc.cRedShift = 16; pixelDesc.cGreenBits = 8; pixelDesc.cGreenShift = 8; pixelDesc.cBlueBits = 8; pixelDesc.cBlueShift = 0; pixelDesc.cAlphaBits = 0; pixelDesc.cAlphaShift = 0; pixelDesc.cAccumBits = 64; pixelDesc.cAccumRedBits = 16; pixelDesc.cAccumGreenBits = 16; pixelDesc.cAccumBlueBits = 16; pixelDesc.cAccumAlphaBits = 0; pixelDesc.cDepthBits = 32; pixelDesc.cStencilBits = 8; pixelDesc.cAuxBuffers = 0; pixelDesc.iLayerType = PFD_MAIN_PLANE; pixelDesc.bReserved = 0; pixelDesc.dwLayerMask = 0; pixelDesc.dwVisibleMask = 0; pixelDesc.dwDamageMask = 0; m_GLPixelIndex = ChoosePixelFormat(hDC,&pixelDesc); if (m_GLPixelIndex == 0) // Choose default { m_GLPixelIndex = 1; if (DescribePixelFormat(hDC,m_GLPixelIndex, sizeof(PIXELFORMATDESCRIPTOR),&pixelDesc)==0) return FALSE; } if (!SetPixelFormat(hDC,m_GLPixelIndex,&pixelDesc)) return FALSE; return TRUE; } //******************************************** // CreateViewGLContext // Create an OpenGL rendering context //******************************************** BOOL CSimpleView::CreateViewGLContext(HDC hDC) { m_hGLContext = wglCreateContext(hDC); if (m_hGLContext==NULL) return FALSE; if (wglMakeCurrent(hDC,m_hGLContext)==FALSE) return FALSE; return TRUE; } void CSimpleView::OnDestroy() { CleanupScene(); if (wglGetCurrentContext() != NULL) wglMakeCurrent(NULL,NULL); if (m_hGLContext != NULL) { wglDeleteContext(m_hGLContext); m_hGLContext = NULL; } CView::OnDestroy(); } int CSimpleView::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CView::OnCreate(lpCreateStruct) == -1) return -1; HWND hWnd = GetSafeHwnd(); HDC hDC = ::GetDC(hWnd); if (SetWindowPixelFormat(hDC)==FALSE) return 0; if (CreateViewGLContext(hDC)==FALSE) return 0; int dummy_argc = 1; char *dummy_argv = "mfcSimple.exe"; // Get a handle to the vtScene - one is already created for you vtScene *pScene = vtGetScene(); pScene->Init(dummy_argc, &dummy_argv); pScene->getViewer()->setThreadingModel(osgViewer::Viewer::SingleThreaded); pScene->SetGraphicsContext(new osgViewer::GraphicsWindowEmbedded(0, 0, 800, 600)); return CreateScene(); } void CSimpleView::OnSize(UINT nType, int cx, int cy) { CView::OnSize(nType, cx, cy); glViewport(0,0,cx, cy); vtGetScene()->SetWindowSize(cx, cy); } void CSimpleView::OnPaint() { CPaintDC dc(this); // device context for painting // Render the scene vtGetScene()->DoUpdate(); //this would occur, for example, after your call to glClear() and before calling SwapBuffers() SwapBuffers(dc.m_ps.hdc); InvalidateRect(NULL,FALSE); //for Continuous Rendering } //-----------------------The Following is VTerrain Code----------------- vtTerrainScene *ts = NULL; // // Create the 3d scene // bool CreateScene() { // Look up the camera vtScene *pScene = vtGetScene(); vtCamera *pCamera = pScene->GetCamera(); pCamera->SetHither(10); pCamera->SetYon(150000); // The terrain scene will contain all the terrains that are created. ts = new vtTerrainScene; // Get the global data path char user_config_dir[MAX_PATH]; SHGetFolderPathA(NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, user_config_dir); vtLoadDataPath(user_config_dir, NULL); // And look locally too, just in case the global path isn't set yet vtGetDataPath().push_back("../Data/"); // Begin creating the scene, including the sun and sky vtGroup *pTopGroup = ts->BeginTerrainScene(); // Tell the scene graph to point to this terrain scene pScene->SetRoot(pTopGroup); // Create a new vtTerrain, read its paramters from a file vtTerrain *pTerr = new vtTerrain; pTerr->SetParamFile("Data/Simple.xml"); pTerr->LoadParams(); // Add the terrain to the scene, and contruct it ts->AppendTerrain(pTerr); if (!ts->BuildTerrain(pTerr)) { AfxMessageBox("Terrain creation failed."); return false; } ts->SetCurrentTerrain(pTerr); // Create a navigation engine to move around on the terrain // Get flight speed from terrain parameters float fSpeed = pTerr->GetParams().GetValueFloat(STR_NAVSPEED); vtTerrainFlyer *pFlyer = new vtTerrainFlyer(fSpeed); pFlyer->SetTarget(pCamera); pFlyer->SetHeightField(pTerr->GetHeightField()); pScene->AddEngine(pFlyer); // Minimum height over terrain is 100 m vtHeightConstrain *pConstrain = new vtHeightConstrain(100); pConstrain->SetTarget(pCamera); pConstrain->SetHeightField(pTerr->GetHeightField()); pScene->AddEngine(pConstrain); return true; } void CleanupScene() { vtGetScene()->SetRoot(NULL); if (ts) { ts->CleanupScene(); delete ts; } vtGetScene()->Shutdown(); } //--------------Mouse EVENTS----------------- // // turn MFC events flags in VT flags // int MFCFlagsToVT(int nFlags) { int flags = 0; if ( (nFlags & MK_CONTROL)!=0 ) flags |= VT_CONTROL; if ( (nFlags & MK_SHIFT)!=0 ) flags |= VT_SHIFT; return flags; } // // turn MFC mouse events into VT mouse events // void CSimpleView::OnMouseMove(UINT nFlags, CPoint point) { vtMouseEvent event; event.type = VT_MOVE; event.button = VT_NONE; event.flags = MFCFlagsToVT(nFlags); event.pos.Set(point.x,point.y); vtGetScene()->OnMouse(event); } void CSimpleView::OnLButtonUp(UINT nFlags, CPoint point) { vtMouseEvent event; event.type = VT_UP; event.button = VT_LEFT; event.flags = MFCFlagsToVT(nFlags); event.pos.Set(point.x,point.y); vtGetScene()->OnMouse(event); } void CSimpleView::OnLButtonDown(UINT nFlags, CPoint point) { vtMouseEvent event; event.type = VT_DOWN; event.button = VT_LEFT; event.flags = MFCFlagsToVT(nFlags); event.pos.Set(point.x,point.y); vtGetScene()->OnMouse(event); } void CSimpleView::OnRButtonDown(UINT nFlags, CPoint point) { vtMouseEvent event; event.type = VT_DOWN; event.button = VT_RIGHT; event.flags = MFCFlagsToVT(nFlags); event.pos.Set(point.x,point.y); vtGetScene()->OnMouse(event); } void CSimpleView::OnRButtonUp(UINT nFlags, CPoint point) { vtMouseEvent event; event.type = VT_UP; event.button = VT_RIGHT; event.flags = MFCFlagsToVT(nFlags); event.pos.Set(point.x,point.y); vtGetScene()->OnMouse(event); } void CSimpleView::OnMButtonDown(UINT nFlags, CPoint point) { vtMouseEvent event; event.type = VT_DOWN; event.button = VT_MIDDLE; event.flags = MFCFlagsToVT(nFlags); event.pos.Set(point.x,point.y); vtGetScene()->OnMouse(event); } void CSimpleView::OnMButtonUp(UINT nFlags, CPoint point) { vtMouseEvent event; event.type = VT_UP; event.button = VT_MIDDLE; event.flags = MFCFlagsToVT(nFlags); event.pos.Set(point.x,point.y); vtGetScene()->OnMouse(event); }
22.341584
95
0.697762
nakijun
93e41e4c8ed8de172b7afef1dc5f178b4cb946b7
61
cpp
C++
source/UI/ui_test.cpp
JakobEliasWagner/pomodoro-timer
a5ebda06645d135af4258e9b814ef364f5685541
[ "Unlicense" ]
null
null
null
source/UI/ui_test.cpp
JakobEliasWagner/pomodoro-timer
a5ebda06645d135af4258e9b814ef364f5685541
[ "Unlicense" ]
null
null
null
source/UI/ui_test.cpp
JakobEliasWagner/pomodoro-timer
a5ebda06645d135af4258e9b814ef364f5685541
[ "Unlicense" ]
null
null
null
// // Created by jakob on 09.03.22. // #include "ui_test.h"
10.166667
32
0.606557
JakobEliasWagner
93e722d784bf8d4a071c9c0c48d2bcae46812d1a
1,580
cc
C++
chrome/browser/page_load_metrics/observers/javascript_frameworks_ukm_observer.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-10-18T02:33:40.000Z
2020-10-18T02:33:40.000Z
chrome/browser/page_load_metrics/observers/javascript_frameworks_ukm_observer.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2021-05-17T16:28:52.000Z
2021-05-21T22:42:22.000Z
chrome/browser/page_load_metrics/observers/javascript_frameworks_ukm_observer.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2020 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 "chrome/browser/page_load_metrics/observers/javascript_frameworks_ukm_observer.h" #include "services/metrics/public/cpp/ukm_builders.h" #include "services/metrics/public/cpp/ukm_recorder.h" JavascriptFrameworksUkmObserver::JavascriptFrameworksUkmObserver() = default; JavascriptFrameworksUkmObserver::~JavascriptFrameworksUkmObserver() = default; void JavascriptFrameworksUkmObserver::OnLoadingBehaviorObserved( content::RenderFrameHost* rfh, int behavior_flag) { DetectNextJS(); } void JavascriptFrameworksUkmObserver::DetectNextJS() { if (nextjs_detected_) { return; } nextjs_detected_ = (GetDelegate().GetMainFrameMetadata().behavior_flags & blink::LoadingBehaviorFlag::kLoadingBehaviorNextJSFrameworkUsed) != 0; } void JavascriptFrameworksUkmObserver::OnComplete( const page_load_metrics::mojom::PageLoadTiming&) { RecordJavascriptFrameworkPageLoad(); } JavascriptFrameworksUkmObserver::ObservePolicy JavascriptFrameworksUkmObserver::FlushMetricsOnAppEnterBackground( const page_load_metrics::mojom::PageLoadTiming&) { RecordJavascriptFrameworkPageLoad(); return STOP_OBSERVING; } void JavascriptFrameworksUkmObserver::RecordJavascriptFrameworkPageLoad() { ukm::builders::JavascriptFrameworkPageLoad builder( GetDelegate().GetPageUkmSourceId()); builder.SetNextJSPageLoad(nextjs_detected_); builder.Record(ukm::UkmRecorder::Get()); }
33.617021
90
0.803165
DamieFC
93e8b9f2d181c32a751b0fcce22b3cb86ba92f38
11,393
cpp
C++
Cores/ProSystem/core/Region.cpp
werminghoff/Provenance
de61b4a64a3eb8e2774e0a8ed53488c6c7aa6cb2
[ "BSD-3-Clause" ]
3,459
2015-01-07T14:07:09.000Z
2022-03-25T03:51:10.000Z
Cores/ProSystem/core/Region.cpp
werminghoff/Provenance
de61b4a64a3eb8e2774e0a8ed53488c6c7aa6cb2
[ "BSD-3-Clause" ]
1,046
2018-03-24T17:56:16.000Z
2022-03-23T08:13:09.000Z
Cores/ProSystem/core/Region.cpp
werminghoff/Provenance
de61b4a64a3eb8e2774e0a8ed53488c6c7aa6cb2
[ "BSD-3-Clause" ]
549
2015-01-07T14:07:15.000Z
2022-01-07T16:13:05.000Z
// ---------------------------------------------------------------------------- // ___ ___ ___ ___ ___ ____ ___ _ _ // /__/ /__/ / / /__ /__/ /__ / /_ / |/ / // / / \ /__/ ___/ ___/ ___/ / /__ / / emulator // // ---------------------------------------------------------------------------- // Copyright 2005 Greg Stanton // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. // ---------------------------------------------------------------------------- // Region.h // ---------------------------------------------------------------------------- #include "Region.h" byte region_type = REGION_AUTO; static const rect REGION_DISPLAY_AREA_NTSC = {0, 16, 319, 258}; static const rect REGION_VISIBLE_AREA_NTSC = {0, 26, 319, 250}; static const byte REGION_FREQUENCY_NTSC = 60; static const word REGION_SCANLINES_NTSC = 262; static const rect REGION_DISPLAY_AREA_PAL = {0, 16, 319, 308}; static const rect REGION_VISIBLE_AREA_PAL = {0, 26, 319, 297}; static const byte REGION_FREQUENCY_PAL = 50; static const word REGION_SCANLINES_PAL = 312; // ---------------------------------------------------------------------------- // PALETTE NTSC // ---------------------------------------------------------------------------- static const byte REGION_PALETTE_NTSC[ ] = { 0x00,0x00,0x00,0x25,0x25,0x25,0x34,0x34,0x34,0x4F,0x4F,0x4F, 0x5B,0x5B,0x5B,0x69,0x69,0x69,0x7B,0x7B,0x7B,0x8A,0x8A,0x8A, 0xA7,0xA7,0xA7,0xB9,0xB9,0xB9,0xC5,0xC5,0xC5,0xD0,0xD0,0xD0, 0xD7,0xD7,0xD7,0xE1,0xE1,0xE1,0xF4,0xF4,0xF4,0xFF,0xFF,0xFF, 0x4C,0x32,0x00,0x62,0x3A,0x00,0x7B,0x4A,0x00,0x9A,0x60,0x00, 0xB5,0x74,0x00,0xCC,0x85,0x00,0xE7,0x9E,0x08,0xF7,0xAF,0x10, 0xFF,0xC3,0x18,0xFF,0xD0,0x20,0xFF,0xD8,0x28,0xFF,0xDF,0x30, 0xFF,0xE6,0x3B,0xFF,0xF4,0x40,0xFF,0xFA,0x4B,0xFF,0xFF,0x50, 0x99,0x25,0x00,0xAA,0x25,0x00,0xB4,0x25,0x00,0xD3,0x30,0x00, 0xDD,0x48,0x02,0xE2,0x50,0x09,0xF4,0x67,0x00,0xF4,0x75,0x10, 0xFF,0x9E,0x10,0xFF,0xAC,0x20,0xFF,0xBA,0x3A,0xFF,0xBF,0x50, 0xFF,0xC6,0x6D,0xFF,0xD5,0x80,0xFF,0xE4,0x90,0xFF,0xE6,0x99, 0x98,0x0C,0x0C,0x99,0x0C,0x0C,0xC2,0x13,0x00,0xD3,0x13,0x00, 0xE2,0x35,0x00,0xE3,0x40,0x00,0xE4,0x40,0x20,0xE5,0x52,0x30, 0xFD,0x78,0x54,0xFF,0x8A,0x6A,0xFF,0x98,0x7C,0xFF,0xA4,0x8B, 0xFF,0xB3,0x9E,0xFF,0xC2,0xB2,0xFF,0xD0,0xBA,0xFF,0xD7,0xC0, 0x99,0x00,0x00,0xA9,0x00,0x00,0xC2,0x04,0x00,0xD3,0x04,0x00, 0xDA,0x04,0x00,0xDB,0x08,0x00,0xE4,0x20,0x20,0xF6,0x40,0x40, 0xFB,0x70,0x70,0xFB,0x7E,0x7E,0xFB,0x8F,0x8F,0xFF,0x9F,0x9F, 0xFF,0xAB,0xAB,0xFF,0xB9,0xB9,0xFF,0xC9,0xC9,0xFF,0xCF,0xCF, 0x7E,0x00,0x50,0x80,0x00,0x50,0x80,0x00,0x5F,0x95,0x0B,0x74, 0xAA,0x22,0x88,0xBB,0x2F,0x9A,0xCE,0x3F,0xAD,0xD7,0x5A,0xB6, 0xE4,0x67,0xC3,0xEF,0x72,0xCE,0xFB,0x7E,0xDA,0xFF,0x8D,0xE1, 0xFF,0x9D,0xE5,0xFF,0xA5,0xE7,0xFF,0xAF,0xEA,0xFF,0xB8,0xEC, 0x48,0x00,0x6C,0x5C,0x04,0x88,0x65,0x0D,0x90,0x7B,0x23,0xA7, 0x93,0x3B,0xBF,0x9D,0x45,0xC9,0xA7,0x4F,0xD3,0xB2,0x5A,0xDE, 0xBD,0x65,0xE9,0xC5,0x6D,0xF1,0xCE,0x76,0xFA,0xD5,0x83,0xFF, 0xDA,0x90,0xFF,0xDE,0x9C,0xFF,0xE2,0xA9,0xFF,0xE6,0xB6,0xFF, 0x1B,0x00,0x70,0x22,0x1B,0x8D,0x37,0x30,0xA2,0x48,0x41,0xB3, 0x59,0x52,0xC4,0x63,0x5C,0xCE,0x6F,0x68,0xDA,0x7D,0x76,0xE8, 0x87,0x80,0xF8,0x93,0x8C,0xFF,0x9D,0x97,0xFF,0xA8,0xA3,0xFF, 0xB3,0xAF,0xFF,0xBC,0xB8,0xFF,0xC4,0xC1,0xFF,0xDA,0xD1,0xFF, 0x00,0x0D,0x7F,0x00,0x12,0xA7,0x00,0x18,0xC0,0x0A,0x2B,0xD1, 0x1B,0x4A,0xE3,0x2F,0x58,0xF0,0x37,0x68,0xFF,0x49,0x79,0xFF, 0x5B,0x85,0xFF,0x6D,0x96,0xFF,0x7F,0xA3,0xFF,0x8C,0xAD,0xFF, 0x96,0xB4,0xFF,0xA8,0xC0,0xFF,0xB7,0xCB,0xFF,0xC6,0xD6,0xFF, 0x00,0x29,0x5A,0x00,0x38,0x76,0x00,0x48,0x92,0x00,0x5C,0xAC, 0x00,0x71,0xC6,0x00,0x86,0xD0,0x0A,0x9B,0xDF,0x1A,0xA8,0xEC, 0x2B,0xB6,0xFF,0x3F,0xC2,0xFF,0x45,0xCB,0xFF,0x59,0xD3,0xFF, 0x7F,0xDA,0xFF,0x8F,0xDE,0xFF,0xA0,0xE2,0xFF,0xB0,0xEB,0xFF, 0x00,0x38,0x39,0x00,0x3C,0x48,0x00,0x3D,0x5B,0x02,0x66,0x7F, 0x03,0x73,0x83,0x00,0x9C,0xAA,0x00,0xA1,0xBB,0x01,0xA4,0xCC, 0x03,0xBB,0xFF,0x05,0xDA,0xE2,0x18,0xE5,0xFF,0x34,0xEA,0xFF, 0x49,0xEF,0xFF,0x66,0xF2,0xFF,0x84,0xF4,0xFF,0x9E,0xF9,0xFF, 0x00,0x4A,0x00,0x00,0x5D,0x00,0x00,0x70,0x00,0x00,0x8B,0x00, 0x00,0xA9,0x00,0x00,0xBB,0x05,0x00,0xBD,0x00,0x02,0xD0,0x05, 0x1A,0xD5,0x40,0x5A,0xF1,0x77,0x82,0xEF,0xA7,0x84,0xED,0xD1, 0x89,0xFF,0xED,0x7D,0xFF,0xFF,0x93,0xFF,0xFF,0x9B,0xFF,0xFF, 0x22,0x4A,0x03,0x27,0x53,0x04,0x30,0x64,0x05,0x3C,0x77,0x0C, 0x45,0x8C,0x11,0x5A,0xA5,0x13,0x1B,0xD2,0x09,0x1F,0xDD,0x00, 0x3D,0xCD,0x2D,0x3D,0xCD,0x30,0x58,0xCC,0x40,0x60,0xD3,0x50, 0xA2,0xEC,0x55,0xB3,0xF2,0x4A,0xBB,0xF6,0x5D,0xC4,0xF8,0x70, 0x2E,0x3F,0x0C,0x36,0x4A,0x0F,0x40,0x56,0x15,0x46,0x5F,0x17, 0x57,0x77,0x1A,0x65,0x85,0x1C,0x74,0x93,0x1D,0x8F,0xA5,0x25, 0xAD,0xB7,0x2C,0xBC,0xC7,0x30,0xC9,0xD5,0x33,0xD4,0xE0,0x3B, 0xE0,0xEC,0x42,0xEA,0xF6,0x45,0xF0,0xFD,0x47,0xF4,0xFF,0x6F, 0x55,0x24,0x00,0x5A,0x2C,0x00,0x6C,0x3B,0x00,0x79,0x4B,0x00, 0xB9,0x75,0x00,0xBB,0x85,0x00,0xC1,0xA1,0x20,0xD0,0xB0,0x2F, 0xDE,0xBE,0x3F,0xE6,0xC6,0x45,0xED,0xCD,0x57,0xF5,0xDB,0x62, 0xFB,0xE5,0x69,0xFC,0xEE,0x6F,0xFD,0xF3,0x77,0xFD,0xF3,0x7F, 0x5C,0x27,0x00,0x5C,0x2F,0x00,0x71,0x3B,0x00,0x7B,0x48,0x00, 0xB9,0x68,0x20,0xBB,0x72,0x20,0xC5,0x86,0x29,0xD7,0x96,0x33, 0xE6,0xA4,0x40,0xF4,0xB1,0x4B,0xFD,0xC1,0x58,0xFF,0xCC,0x55, 0xFF,0xD4,0x61,0xFF,0xDD,0x69,0xFF,0xE6,0x79,0xFF,0xEA,0x98 }; // -------------------------------------------------------------------------------------- // PALETTE PAL // -------------------------------------------------------------------------------------- static const byte REGION_PALETTE_PAL[ ] = { 0x00,0x00,0x00,0x1c,0x1c,0x1c,0x39,0x39,0x39,0x59,0x59,0x59, 0x79,0x79,0x79,0x92,0x92,0x92,0xab,0xab,0xab,0xbc,0xbc,0xbc, 0xcd,0xcd,0xcd,0xd9,0xd9,0xd9,0xe6,0xe6,0xe6,0xec,0xec,0xec, 0xf2,0xf2,0xf2,0xf8,0xf8,0xf8,0xff,0xff,0xff,0xff,0xff,0xff, 0x26,0x30,0x01,0x24,0x38,0x03,0x23,0x40,0x05,0x51,0x54,0x1b, 0x80,0x69,0x31,0x97,0x81,0x35,0xaf,0x99,0x3a,0xc2,0xa7,0x3e, 0xd5,0xb5,0x43,0xdb,0xc0,0x3d,0xe1,0xcb,0x38,0xe2,0xd8,0x36, 0xe3,0xe5,0x34,0xef,0xf2,0x58,0xfb,0xff,0x7d,0xfb,0xff,0x7d, 0x39,0x17,0x01,0x5e,0x23,0x04,0x83,0x30,0x08,0xa5,0x47,0x16, 0xc8,0x5f,0x24,0xe3,0x78,0x20,0xff,0x91,0x1d,0xff,0xab,0x1d, 0xff,0xc5,0x1d,0xff,0xce,0x34,0xff,0xd8,0x4c,0xff,0xe6,0x51, 0xff,0xf4,0x56,0xff,0xf9,0x77,0xff,0xff,0x98,0xff,0xff,0x98, 0x45,0x19,0x04,0x72,0x1e,0x11,0x9f,0x24,0x1e,0xb3,0x3a,0x20, 0xc8,0x51,0x22,0xe3,0x69,0x20,0xff,0x81,0x1e,0xff,0x8c,0x25, 0xff,0x98,0x2c,0xff,0xae,0x38,0xff,0xc5,0x45,0xff,0xc5,0x59, 0xff,0xc6,0x6d,0xff,0xd5,0x87,0xff,0xe4,0xa1,0xff,0xe4,0xa1, 0x4a,0x17,0x04,0x7e,0x1a,0x0d,0xb2,0x1d,0x17,0xc8,0x21,0x19, 0xdf,0x25,0x1c,0xec,0x3b,0x38,0xfa,0x52,0x55,0xfc,0x61,0x61, 0xff,0x70,0x6e,0xff,0x7f,0x7e,0xff,0x8f,0x8f,0xff,0x9d,0x9e, 0xff,0xab,0xad,0xff,0xb9,0xbd,0xff,0xc7,0xce,0xff,0xc7,0xce, 0x05,0x05,0x68,0x3b,0x13,0x6d,0x71,0x22,0x72,0x8b,0x2a,0x8c, 0xa5,0x32,0xa6,0xb9,0x38,0xba,0xcd,0x3e,0xcf,0xdb,0x47,0xdd, 0xea,0x51,0xeb,0xf4,0x5f,0xf5,0xfe,0x6d,0xff,0xfe,0x7a,0xfd, 0xff,0x87,0xfb,0xff,0x95,0xfd,0xff,0xa4,0xff,0xff,0xa4,0xff, 0x28,0x04,0x79,0x40,0x09,0x84,0x59,0x0f,0x90,0x70,0x24,0x9d, 0x88,0x39,0xaa,0xa4,0x41,0xc3,0xc0,0x4a,0xdc,0xd0,0x54,0xed, 0xe0,0x5e,0xff,0xe9,0x6d,0xff,0xf2,0x7c,0xff,0xf8,0x8a,0xff, 0xff,0x98,0xff,0xfe,0xa1,0xff,0xfe,0xab,0xff,0xfe,0xab,0xff, 0x35,0x08,0x8a,0x42,0x0a,0xad,0x50,0x0c,0xd0,0x64,0x28,0xd0, 0x79,0x45,0xd0,0x8d,0x4b,0xd4,0xa2,0x51,0xd9,0xb0,0x58,0xec, 0xbe,0x60,0xff,0xc5,0x6b,0xff,0xcc,0x77,0xff,0xd1,0x83,0xff, 0xd7,0x90,0xff,0xdb,0x9d,0xff,0xdf,0xaa,0xff,0xdf,0xaa,0xff, 0x05,0x1e,0x81,0x06,0x26,0xa5,0x08,0x2f,0xca,0x26,0x3d,0xd4, 0x44,0x4c,0xde,0x4f,0x5a,0xee,0x5a,0x68,0xff,0x65,0x75,0xff, 0x71,0x83,0xff,0x80,0x91,0xff,0x90,0xa0,0xff,0x97,0xa9,0xff, 0x9f,0xb2,0xff,0xaf,0xbe,0xff,0xc0,0xcb,0xff,0xc0,0xcb,0xff, 0x05,0x1e,0x81,0x06,0x26,0xa5,0x08,0x2f,0xca,0x26,0x3d,0xd4, 0x44,0x4c,0xde,0x4f,0x5a,0xee,0x5a,0x68,0xff,0x65,0x75,0xff, 0x71,0x83,0xff,0x80,0x91,0xff,0x90,0xa0,0xff,0x97,0xa9,0xff, 0x9f,0xb2,0xff,0xaf,0xbe,0xff,0xc0,0xcb,0xff,0xc0,0xcb,0xff, 0x0c,0x04,0x8b,0x22,0x18,0xa0,0x38,0x2d,0xb5,0x48,0x3e,0xc7, 0x58,0x4f,0xda,0x61,0x59,0xec,0x6b,0x64,0xff,0x7a,0x74,0xff, 0x8a,0x84,0xff,0x91,0x8e,0xff,0x99,0x98,0xff,0xa5,0xa3,0xff, 0xb1,0xae,0xff,0xb8,0xb8,0xff,0xc0,0xc2,0xff,0xc0,0xc2,0xff, 0x1d,0x29,0x5a,0x1d,0x38,0x76,0x1d,0x48,0x92,0x1c,0x5c,0xac, 0x1c,0x71,0xc6,0x32,0x86,0xcf,0x48,0x9b,0xd9,0x4e,0xa8,0xec, 0x55,0xb6,0xff,0x70,0xc7,0xff,0x8c,0xd8,0xff,0x93,0xdb,0xff, 0x9b,0xdf,0xff,0xaf,0xe4,0xff,0xc3,0xe9,0xff,0xc3,0xe9,0xff, 0x2f,0x43,0x02,0x39,0x52,0x02,0x44,0x61,0x03,0x41,0x7a,0x12, 0x3e,0x94,0x21,0x4a,0x9f,0x2e,0x57,0xab,0x3b,0x5c,0xbd,0x55, 0x61,0xd0,0x70,0x69,0xe2,0x7a,0x72,0xf5,0x84,0x7c,0xfa,0x8d, 0x87,0xff,0x97,0x9a,0xff,0xa6,0xad,0xff,0xb6,0xad,0xff,0xb6, 0x0a,0x41,0x08,0x0d,0x54,0x0a,0x10,0x68,0x0d,0x13,0x7d,0x0f, 0x16,0x92,0x12,0x19,0xa5,0x14,0x1c,0xb9,0x17,0x1e,0xc9,0x19, 0x21,0xd9,0x1b,0x47,0xe4,0x2d,0x6e,0xf0,0x40,0x78,0xf7,0x4d, 0x83,0xff,0x5b,0x9a,0xff,0x7a,0xb2,0xff,0x9a,0xb2,0xff,0x9a, 0x04,0x41,0x0b,0x05,0x53,0x0e,0x06,0x66,0x11,0x07,0x77,0x14, 0x08,0x88,0x17,0x09,0x9b,0x1a,0x0b,0xaf,0x1d,0x48,0xc4,0x1f, 0x86,0xd9,0x22,0x8f,0xe9,0x24,0x99,0xf9,0x27,0xa8,0xfc,0x41, 0xb7,0xff,0x5b,0xc9,0xff,0x6e,0xdc,0xff,0x81,0xdc,0xff,0x81, 0x02,0x35,0x0f,0x07,0x3f,0x15,0x0c,0x4a,0x1c,0x2d,0x5f,0x1e, 0x4f,0x74,0x20,0x59,0x83,0x24,0x64,0x92,0x28,0x82,0xa1,0x2e, 0xa1,0xb0,0x34,0xa9,0xc1,0x3a,0xb2,0xd2,0x41,0xc4,0xd9,0x45, 0xd6,0xe1,0x49,0xe4,0xf0,0x4e,0xf2,0xff,0x53,0xf2,0xff,0x53, }; // ---------------------------------------------------------------------------- // Reset // ---------------------------------------------------------------------------- void region_Reset( ) { if(region_type == REGION_PAL || (region_type == REGION_AUTO && cartridge_region == REGION_PAL)) { maria_displayArea = REGION_DISPLAY_AREA_PAL; maria_visibleArea = REGION_VISIBLE_AREA_PAL; if(palette_default) palette_Load(REGION_PALETTE_PAL); // Added check for default - bberlin prosystem_frequency = REGION_FREQUENCY_PAL; prosystem_scanlines = REGION_SCANLINES_PAL; tia_size = 624; pokey_size = 624; } else { maria_displayArea = REGION_DISPLAY_AREA_NTSC; maria_visibleArea = REGION_VISIBLE_AREA_NTSC; if(palette_default) palette_Load(REGION_PALETTE_NTSC); // Added check for default - bberlin prosystem_frequency = REGION_FREQUENCY_NTSC; prosystem_scanlines = REGION_SCANLINES_NTSC; tia_size = 524; pokey_size = 524; } pokey_setSampleRate((prosystem_scanlines * prosystem_frequency) << 1); }
55.57561
100
0.693233
werminghoff
93eb1997c43299a24d5b14b96b602d6819dd660a
394
cpp
C++
src/route/router.cpp
dosisod/zz
5e747c5559c6d383e905781aabfc8d1f9ace4681
[ "MIT" ]
1
2020-03-24T23:25:55.000Z
2020-03-24T23:25:55.000Z
src/route/router.cpp
dosisod/zz
5e747c5559c6d383e905781aabfc8d1f9ace4681
[ "MIT" ]
null
null
null
src/route/router.cpp
dosisod/zz
5e747c5559c6d383e905781aabfc8d1f9ace4681
[ "MIT" ]
null
null
null
#include "router.hpp" #include "route.hpp" void Router::route(const std::string address, const std::function<std::string(void)> func) { routes.emplace_back(address, func); } std::string Router::execute(const std::string address) const { for (const auto& route : routes) if (route.matches(address)) return route.run(); return "<pre>Error 404: \"" + address + "\" not found.</pre>"; }
26.266667
92
0.685279
dosisod
93ee5c32a90cbbca01bd8e10ead090cb35bca096
2,547
cpp
C++
source/lib/src/mohansella/serial/Writer.cpp
mohansella/simple-kvstore
af9948f0a0e4247526ae03f4d639c548c9474837
[ "MIT" ]
null
null
null
source/lib/src/mohansella/serial/Writer.cpp
mohansella/simple-kvstore
af9948f0a0e4247526ae03f4d639c548c9474837
[ "MIT" ]
null
null
null
source/lib/src/mohansella/serial/Writer.cpp
mohansella/simple-kvstore
af9948f0a0e4247526ae03f4d639c548c9474837
[ "MIT" ]
null
null
null
#include <mohansella/serial/Writer.hpp> #include <mohansella/serial/ByteSerialType.hpp> namespace mohansella::serial { Writer::Writer() { } Writer::~Writer() { } Writer & Writer::putNull() { std::uint8_t nullEnVal = ByteSerialType::BSTYPE_NULL; return this->putRaw(&nullEnVal, sizeof(nullEnVal)); } Writer & Writer::putByte(std::uint8_t val) { this->writeSyntaxAndLen(ByteSerialType::BSTYPE_BYTE, &val, sizeof(val)); return *this; } Writer & Writer::putShort(std::int16_t val) { this->writeSyntaxAndLen(ByteSerialType::BSTYPE_SHORT, (std::uint8_t *) &val, sizeof(val)); return *this; } Writer & Writer::putInteger(std::int32_t val) { this->writeSyntaxAndLen(ByteSerialType::BSTYPE_INTEGER, (std::uint8_t *) &val, sizeof(val)); return *this; } Writer & Writer::putFloat(float val) { this->writeSyntaxAndLen(ByteSerialType::BSTYPE_FLOAT, (std::uint8_t *) &val, sizeof(val)); return *this; } Writer & Writer::putLong(std::int64_t val) { this->writeSyntaxAndLen(ByteSerialType::BSTYPE_LONG, (std::uint8_t *) &val, sizeof(val)); return *this; } Writer & Writer::putDouble(double val) { this->writeSyntaxAndLen(ByteSerialType::BSTYPE_DOUBLE, (std::uint8_t *) &val, sizeof(val)); return *this; } Writer & Writer::putString(const std::string & val) { return this->putCharArray(val.c_str(), val.length()); } Writer & Writer::putCharArray(const char * dataPtr, std::int32_t len) { this->writeSyntaxAndLen(ByteSerialType::BSTYPE_STRING, (std::uint8_t *) &len, sizeof(len)); return this->putRaw((const std::uint8_t *) dataPtr, len); } Writer & Writer::putBytes(const std::uint8_t * dataPtr, std::int32_t len) { this->writeSyntaxAndLen(ByteSerialType::BSTYPE_BLOB, (std::uint8_t *) &len, sizeof(len)); return this->putRaw(dataPtr, len); } Writer & Writer::startObject() { this->writeSyntax(ByteSerialType::BSTYPE_OBJECT_START); return *this; } Writer & Writer::endObject() { this->writeSyntax(ByteSerialType::BSTYPE_OBJECT_END); return *this; } Writer & Writer::startArray() { this->writeSyntax(ByteSerialType::BSTYPE_ARRAY_START); return *this; } Writer & Writer::endArray() { this->writeSyntax(ByteSerialType::BSTYPE_ARRAY_END); return *this; } void Writer::writeSyntax(ByteSerialType type) { std::uint8_t data = type; this->putRaw(&data, sizeof(data)); } void Writer::writeSyntaxAndLen(ByteSerialType type, const std::uint8_t * ptr, std::int32_t len) { this->writeSyntax(type); this->putRawInReverse(ptr, len); } }
22.147826
96
0.699647
mohansella
93eed7db58415e5995a906d5fa1b83ccc7deae2c
9,998
cpp
C++
MartrixGoC++/src/Game.cpp
MartrixG/GraduationProject
3f82a48ba27159ae0a1c67b3c441d4d1378543e5
[ "MIT" ]
null
null
null
MartrixGoC++/src/Game.cpp
MartrixG/GraduationProject
3f82a48ba27159ae0a1c67b3c441d4d1378543e5
[ "MIT" ]
null
null
null
MartrixGoC++/src/Game.cpp
MartrixG/GraduationProject
3f82a48ba27159ae0a1c67b3c441d4d1378543e5
[ "MIT" ]
null
null
null
// // Created by 11409 on 2021/4/17. // #include <iostream> #include <cstring> #include "Game.hpp" Game::Game(PointPtr* points, PArVecPtr* around, PDiVecPtr* diagonal) { this->allBoardPoints = points; this->allAround = around; this->allDiagonal = diagonal; this->targetBlock = new GoBlock(); this->nextStep = new Step(-1, -1, -1); this->historyZobristHash.insert(0); this->historyBoard.emplace_back(BOARD_SIZE * BOARD_SIZE); this->board = new int[BOARD_SIZE * BOARD_SIZE]; this->pointBlockMap = new BlockPtr[BOARD_SIZE * BOARD_SIZE]; for(size_t i = 0; i < BOARD_SIZE * BOARD_SIZE; i++) { this->board[i] = 0; this->pointBlockMap[i] = nullptr; this->historyBoard[0][i] = this->board[i]; } } void Game::initHandCap(std::vector<Step*> &handCapSteps, int numOfHandCap) { for (int i = 0; i < numOfHandCap; i++) { int pos = handCapSteps[i]->pos; this->getPickUpBlock(pos); this->board[pos] = player; if(this->mergedBlock.empty()) { this->pointBlockMap[pos] = this->targetBlock; this->targetBlock = new GoBlock(); } else { BlockPtr startBlock = *this->mergedBlock.begin(); startBlock->clear(); startBlock->update(this->targetBlock); this->pointBlockMap[pos] = startBlock; for(auto &block : this->mergedBlock) { if(block != startBlock) { for(int j = 0; j < BOARD_SIZE * BOARD_SIZE; j++) { if(block->points.test(j)) { this->pointBlockMap[j] = startBlock; } } delete block; } } } } this->boardZobristHash = this->newBoardZobristHash; this->historyBoard.emplace_back(BOARD_SIZE * BOARD_SIZE); for(size_t i = 0; i < BOARD_SIZE * BOARD_SIZE; i++) { this->historyBoard.back()[i] = this->board[i]; } } bool Game::moveAnalyze(Step* step) { int pos = step->pos; if (step->player != this->player) { return false; } if (this->board[pos] != 0) { return false; } this->newBoardZobristHash = this->boardZobristHash; this->getPickUpBlock(pos); if (this->targetBlock->getQi() == 0 && !pickUpFlag) { return false; } if (this->historyZobristHash.find(this->newBoardZobristHash) != this->historyZobristHash.end()) { return false; } this->nextStep = step; return true; } void Game::move() { PointPtr targetPoint = this->allBoardPoints[this->nextStep->pos]; this->historyZobristHash.insert(this->newBoardZobristHash); this->steps.push_back(new Step(this->nextStep->pos / BOARD_SIZE, this->nextStep->pos % BOARD_SIZE, this->player)); this->historyBoard.emplace_back(BOARD_SIZE * BOARD_SIZE); for(size_t i = 0; i < BOARD_SIZE * BOARD_SIZE; i++) { this->historyBoard.back()[i] = this->board[i]; } this->boardZobristHash = this->newBoardZobristHash; // board update this->board[targetPoint->pos] = player; this->player = this->player == WHITE_PLAYER ? BLACK_PLAYER : WHITE_PLAYER; // self point update if(this->mergedBlock.empty()) { this->pointBlockMap[targetPoint->pos] = this->targetBlock; this->targetBlock = new GoBlock(); } else { BlockPtr startBlock = *this->mergedBlock.begin(); startBlock->clear(); startBlock->update(this->targetBlock); this->pointBlockMap[targetPoint->pos] = startBlock; for(auto &block : this->mergedBlock) { if(block != startBlock) { for(int i = 0; i < BOARD_SIZE * BOARD_SIZE; i++) { if(block->points.test(i)) { this->pointBlockMap[i] = startBlock; } } delete block; } } } // opponent update for(auto &block : this->opponentBlock) { block->removeQi(targetPoint->pos); if (block->getQi() == 0) { for (int i = 0; i < BOARD_SIZE * BOARD_SIZE; i++) { if(block->points.test(i)) { PArVecPtr around = this->allAround[i]; for(auto &point : *around) { if (this->board[point] + player == BLACK_PLAYER + WHITE_PLAYER) { this->pointBlockMap[point]->addQi(i); } } this->board[i] = 0; this->pointBlockMap[i] = nullptr; } } delete block; } } } void Game::getPickUpBlock(int targetPoint) { this->newBoardZobristHash ^= this->allBoardPoints[targetPoint]->zobristHash[this->player - 1]; this->pickUpFlag = false; this->mergedBlock.clear(); this->opponentBlock.clear(); int isolatedFlag = true; PArVecPtr around = this->allAround[targetPoint]; for (auto &point : *around) { if (this->board[point] != 0) { auto nearBlock = this->pointBlockMap[point]; if(this->mergedBlock.count(nearBlock) != 0 || this->opponentBlock.count(nearBlock) != 0) { continue; } if(this->board[point] == player) { this->mergedBlock.insert(nearBlock); if(isolatedFlag) { this->targetBlock->clear(); this->targetBlock->update(nearBlock); this->targetBlock->addPoint(this->allBoardPoints[targetPoint], around, this->board); isolatedFlag = false; } else { this->targetBlock->merge(this->allBoardPoints[targetPoint], nearBlock); } } else { this->opponentBlock.insert(nearBlock); if(nearBlock->getQi() - 1 == 0) { this->pickUpFlag = true; this->newBoardZobristHash ^= nearBlock->zobristHash; } } } } if(isolatedFlag) { this->targetBlock->clear(); this->targetBlock->update(this->allBoardPoints[targetPoint], this->player, around, this->board); } } void Game::boardStrEncode(char* boardStr) const { boardStr[1] = char(this->player + '0'); for(int i = 0; i < BOARD_SIZE * BOARD_SIZE; i++) { boardStr[i + 2] = char(this->board[i] + '0'); } boardStr[BOARD_SIZE * BOARD_SIZE + 2] = '\0'; } int Game::getWinner() const { int blackCount = 0, whiteCount = 0; for(size_t i = 0; i < BOARD_SIZE * BOARD_SIZE; i++) { switch (this->board[i]) { case BLACK_PLAYER: blackCount++; break; case WHITE_PLAYER: whiteCount++; break; } } return blackCount - whiteCount; } void Game::legalMove(int* legalMoves, int* qiAfterMove, size_t &len) { this->nextStep->player = this->player; for(int i = 0; i < BOARD_SIZE * BOARD_SIZE; i++) { this->nextStep->pos = i; if(this->moveAnalyze(this->nextStep)) { if(!this->isEye(i, this->player)) { legalMoves[len] = i; if(qiAfterMove != nullptr) { qiAfterMove[len] = this->targetBlock->getQi(); } len++; } } } } bool Game::isEye(int pos, int posPlayer) const { PArVecPtr around = this->allAround[pos]; for(auto &point : *around) { if(this->board[point] != posPlayer) { return false; } } size_t count = 0; PArVecPtr diagonal = this->allDiagonal[pos]; for(auto &point : *diagonal) { if(this->board[point] == posPlayer) { count++; } } if((count == 3 && diagonal->size() == 4) || (count !=3 && count == diagonal->size())) { return true; } else { return false; } } void Game::copy(Game* o) const { std::unordered_map<BlockPtr, BlockPtr> blockMap; o->player = this->player; for(size_t i = 0; i < BOARD_SIZE * BOARD_SIZE; i++) { o->board[i] = this->board[i]; } o->historyBoard.assign(this->historyBoard.begin(), this->historyBoard.end()); for(auto& step : this->steps) { o->steps.push_back(new Step(step->pos / BOARD_SIZE, step->pos % BOARD_SIZE, step->player)); } o->boardZobristHash = this->boardZobristHash; o->historyZobristHash = this->historyZobristHash; o->newBoardZobristHash = this->newBoardZobristHash; for(int i = 0; i < BOARD_SIZE * BOARD_SIZE; i++) { BlockPtr nowBlock = this->pointBlockMap[i]; if(nowBlock != nullptr) { if(blockMap.count(nowBlock)) { o->pointBlockMap[i] = blockMap[nowBlock]; } else { auto* tmpBlock = new GoBlock(); tmpBlock->update(nowBlock); o->pointBlockMap[i] = tmpBlock; blockMap[nowBlock] = tmpBlock; } } } } Game::~Game() { std::unordered_set<BlockPtr> blockSet; for(size_t i = 0 ; i < BOARD_SIZE * BOARD_SIZE; i++) { blockSet.insert(this->pointBlockMap[i]); } for(auto &block : blockSet) { delete block; } delete targetBlock; delete nextStep; delete []board; delete []pointBlockMap; for(auto &step : this->steps) { delete step; } }
28.48433
118
0.513303
MartrixG
93f28202826738337e21f8cf69e953d34b285511
1,902
cpp
C++
004_double_link_list_str/cppmain.cpp
aben20807/SI-TONG-CHENG-SYU-YUAN-CHENG-CHANG-JI-HUA
a2817b7c742c02ef557c0aadaec4753be102a802
[ "MIT" ]
null
null
null
004_double_link_list_str/cppmain.cpp
aben20807/SI-TONG-CHENG-SYU-YUAN-CHENG-CHANG-JI-HUA
a2817b7c742c02ef557c0aadaec4753be102a802
[ "MIT" ]
2
2018-09-15T04:13:12.000Z
2018-09-16T02:02:12.000Z
004_double_link_list_str/cppmain.cpp
aben20807/SI-TONG-CHENG-SYU-YUAN-CHENG-CHANG-JI-HUA
a2817b7c742c02ef557c0aadaec4753be102a802
[ "MIT" ]
null
null
null
#include <cstdio> #include "dlist.h" using namespace std; DListRet print_int(void *ctx, void *data, bool is_first) { if (is_first) { printf("%d", *(int *)data); } else { printf(" - %d", *(int *)data); } return OK; } void print(DList *thiz) { printf("size: %d, list: ", dlist_size(thiz)); dlist_foreach(thiz, print_int, NULL); printf("\n"); } DListRet sum_cb(void *ctx, void *data, bool is_first) { long long *result = (long long *)ctx; *result += *(int *)data; return OK; } DListRet max_cb(void *ctx, void *data, bool is_first) { int *result = (int *)ctx; if (is_first) { *result = *(int *)data; } else { *result = (*result > *(int *)data)? *result: *(int *)data; } return OK; } int main(){ printf("OuO\n"); DList *d = dlist_create(); print(d); int data1 = 1; dlist_prepend(d, &data1); print(d); int data2 = 2; dlist_prepend(d, &data2); print(d); int data3 = 3; dlist_append(d, &data3); print(d); int data4 = 4; dlist_append(d, &data4); print(d); int data5 = 5; dlist_insert(d, 3, &data5); print(d); int data6 = 6; dlist_insert(d, 3, &data6); print(d); long long sum = 0; dlist_foreach(d, sum_cb, &sum); printf("sum: %lld\n", sum); int mmax; dlist_foreach(d, max_cb, &mmax); printf("max: %d\n", mmax); dlist_delete(d, 2); print(d); dlist_delete(d, 1); print(d); dlist_delete(d, 11); print(d); dlist_delete(d, 0); print(d); void *data7; dlist_get_by_index(d, 0, &data7); printf("%d\n", *(int *)data7); dlist_get_by_index(d, 2, &data7); printf("%d\n", *(int *)data7); int data8 = 8; dlist_set_by_index(d, 0, &data8); print(d); dlist_set_by_index(d, 2, &data8); print(d); dlist_destroy(d); return 0; }
17.943396
66
0.544164
aben20807
93f6a856a4cd08d788b71cebd0fec7e480c96801
5,651
cpp
C++
LeetCode/C++/188. Best Time to Buy and Sell Stock IV.cpp
shreejitverma/GeeksforGeeks
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
3
2020-12-30T00:29:59.000Z
2021-01-24T22:43:04.000Z
LeetCode/C++/188. Best Time to Buy and Sell Stock IV.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
6
2022-01-13T04:31:04.000Z
2022-03-12T01:06:16.000Z
LeetCode/C++/188. Best Time to Buy and Sell Stock IV.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-14T19:53:53.000Z
2022-02-18T05:14:30.000Z
//Runtime error(MLE) //209 / 211 test cases passed. //time: O(N*k), space: O(k) class Solution { public: int maxProfit(int k, vector<int>& prices) { int n = prices.size(); //0th element for padding vector<int> holds(k+1, INT_MIN); vector<int> cashs(k+1, 0); int ans = 0; for(int price : prices){ // cout << "price: " << price << endl; for(int i = k; i >= 1; i--){ /* we should update cashs[i] and then holds[i]! because when we update cashs[i], we need holds[i] in last iteration! */ /* hold-cash makes a transaction, so holds[i]+price means selling the stock bought in ith transaction */ cashs[i] = max(cashs[i], holds[i]+price); holds[i] = max(holds[i], cashs[i-1]-price); // cout << i << ", " << holds[i] << ", " << cashs[i] << endl; ans = max(ans, cashs[i]); } } return ans; } }; //Time Limit Exceeded //209 / 211 test cases passed. //time: O(N*k), space: O(min(n,k)) class Solution { public: int maxProfit(int k, vector<int>& prices) { int n = prices.size(); //0th element for padding vector<int> holds(min(n,k)+1, INT_MIN); vector<int> cashs(min(n,k)+1, 0); int ans = 0; for(int price : prices){ // cout << "price: " << price << endl; for(int i = min(n,k); i >= 1; i--){ /* we should update cashs[i] and then holds[i]! because when we update cashs[i], we need holds[i] in last iteration! */ /* hold-cash makes a transaction, so holds[i]+price means selling the stock bought in ith transaction */ cashs[i] = max(cashs[i], holds[i]+price); holds[i] = max(holds[i], cashs[i-1]-price); // cout << i << ", " << holds[i] << ", " << cashs[i] << endl; ans = max(ans, cashs[i]); } } return ans; } }; //add quick solution for larger enough k //https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/54113/A-Concise-DP-Solution-in-Java //Runtime: 8 ms, faster than 71.12% of C++ online submissions for Best Time to Buy and Sell Stock IV. //Memory Usage: 12.1 MB, less than 5.55% of C++ online submissions for Best Time to Buy and Sell Stock IV. class Solution { public: int maxProfit(int k, vector<int>& prices) { int n = prices.size(); int ans = 0; //we can do as many transactions as we want if(k >= n/2){ for(int i = 1; i < n; i++){ ans += max(0, prices[i]-prices[i-1]); } return ans; } //0th element for padding vector<int> holds(min(n,k)+1, INT_MIN); vector<int> cashs(min(n,k)+1, 0); for(int price : prices){ // cout << "price: " << price << endl; for(int i = min(n,k); i >= 1; i--){ /* we should update cashs[i] and then holds[i]! because when we update cashs[i], we need holds[i] in last iteration! */ /* hold-cash makes a transaction, so holds[i]+price means selling the stock bought in ith transaction */ cashs[i] = max(cashs[i], holds[i]+price); holds[i] = max(holds[i], cashs[i-1]-price); // cout << i << ", " << holds[i] << ", " << cashs[i] << endl; ans = max(ans, cashs[i]); } } return ans; } }; //DP //https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/54117/Clean-Java-DP-solution-with-comment //Runtime: 8 ms, faster than 71.12% of C++ online submissions for Best Time to Buy and Sell Stock IV. //Memory Usage: 13 MB, less than 5.55% of C++ online submissions for Best Time to Buy and Sell Stock IV. class Solution { public: int maxProfit(int k, vector<int>& prices) { int n = prices.size(); int ans = 0; if(k >= n/2){ for(int i = 1; i < n; i++){ ans += max(0, prices[i]-prices[i-1]); } return ans; } /** * dp[i, j] represents the max profit up until prices[j] using at most i transactions. * dp[i, j] = max(dp[i, j-1], prices[j] - prices[jj] + dp[i-1, jj]) { jj in range of [0, j-1] } * = max(dp[i, j-1], prices[j] + max(dp[i-1, jj] - prices[jj])) * dp[0, j] = 0; 0 transactions makes 0 profit * dp[i, 0] = 0; if there is only one price data point you can't make any transaction. */ //only pad for k(transactions) dimension, not time dimension vector<vector<int>> dp(k+1, vector(n, 0)); for(int i = 1; i <= k; i++){ //transactions // int hold = INT_MIN; //this gives WA!! int hold = dp[i-1][0] - prices[0]; for(int j = 1; j < n; j++){ //days //hold: the max money we have if we hold a stock until j-1 day dp[i][j] = max(dp[i][j-1], prices[j] + hold); hold = max(hold, dp[i-1][j] - prices[j]); } } return dp[k][n-1]; } };
35.765823
116
0.469828
shreejitverma
93fbd1cd77defbec19e6d6eca525cbf1fd17a207
1,142
cpp
C++
Source/Parser/CursorType.cpp
JoinCAD/CPP-Reflection
61163369b6b3b370c4ce726dbf8e60e441723821
[ "MIT" ]
540
2015-09-18T09:44:57.000Z
2022-03-25T07:23:09.000Z
Source/Parser/CursorType.cpp
yangzhengxing/CPP-Reflection
43ec755b7a5c62e3252c174815c2e44727e11e72
[ "MIT" ]
16
2015-09-23T06:37:43.000Z
2020-04-10T15:40:08.000Z
Source/Parser/CursorType.cpp
yangzhengxing/CPP-Reflection
43ec755b7a5c62e3252c174815c2e44727e11e72
[ "MIT" ]
88
2015-09-21T15:12:32.000Z
2021-11-30T14:07:34.000Z
/* ---------------------------------------------------------------------------- ** Copyright (c) 2016 Austin Brunkhorst, All Rights Reserved. ** ** CursorType.cpp ** --------------------------------------------------------------------------*/ #include "Precompiled.h" #include "CursorType.h" CursorType::CursorType(const CXType &handle) : m_handle( handle ) { } std::string CursorType::GetDisplayName(void) const { std::string displayName; utils::ToString( clang_getTypeSpelling( m_handle ), displayName ); return displayName; } int CursorType::GetArgumentCount(void) const { return clang_getNumArgTypes( m_handle ); } CursorType CursorType::GetArgument(unsigned index) const { return clang_getArgType( m_handle, index ); } CursorType CursorType::GetCanonicalType(void) const { return clang_getCanonicalType( m_handle ); } Cursor CursorType::GetDeclaration(void) const { return clang_getTypeDeclaration( m_handle ); } CXTypeKind CursorType::GetKind(void) const { return m_handle.kind; } bool CursorType::IsConst(void) const { return clang_isConstQualifiedType( m_handle ) ? true : false; }
21.148148
79
0.636602
JoinCAD
93fd62c86da1ff1f472c95f051e3b1cad67644f3
6,760
cpp
C++
hookflash-core/core/hookflash/stack/message/cpp/stack_message_PeerToFinderSessionCreateRequest.cpp
ilin-in/OP
bf3e87d90008e2a4106ee70360fbe15b0d694e77
[ "Unlicense" ]
1
2020-02-19T09:55:55.000Z
2020-02-19T09:55:55.000Z
hookflash-core/core/hookflash/stack/message/cpp/stack_message_PeerToFinderSessionCreateRequest.cpp
ilin-in/OP
bf3e87d90008e2a4106ee70360fbe15b0d694e77
[ "Unlicense" ]
null
null
null
hookflash-core/core/hookflash/stack/message/cpp/stack_message_PeerToFinderSessionCreateRequest.cpp
ilin-in/OP
bf3e87d90008e2a4106ee70360fbe15b0d694e77
[ "Unlicense" ]
null
null
null
/* Copyright (c) 2012, SMB Phone Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ #include <hookflash/stack/message/internal/stack_message_PeerToFinderSessionCreateRequest.h> #include <hookflash/stack/message/internal/stack_message_MessageHelper.h> #include <hookflash/stack/IPeerFiles.h> #include <hookflash/stack/IPeerFilePublic.h> #include <hookflash/stack/IPeerFilePrivate.h> #include <hookflash/services/IHelper.h> #include <zsLib/Stringize.h> #include <zsLib/zsHelpers.h> namespace hookflash { namespace stack { namespace message { using zsLib::Stringize; typedef zsLib::Time Time; typedef zsLib::XML::DocumentPtr DocumentPtr; typedef zsLib::XML::Text Text; typedef zsLib::XML::Element Element; typedef zsLib::XML::ElementPtr ElementPtr; typedef zsLib::XML::Exceptions Exceptions; PeerToFinderSessionCreateRequestPtr PeerToFinderSessionCreateRequest::convert(MessagePtr message) { return boost::dynamic_pointer_cast<PeerToFinderSessionCreateRequest>(message); } PeerToFinderSessionCreateRequest::PeerToFinderSessionCreateRequest() : mOneTimeKey(services::IHelper::randomString(32)) { } bool PeerToFinderSessionCreateRequest::hasAttribute(AttributeTypes type) const { switch (type) { case AttributeType_FinderID: return (!mFinderID.isEmpty()); case AttributeType_ContactID: return (!mContactID.isEmpty()); case AttributeType_Expires: return (Time() != mExpires); case AttributeType_PeerFile: return (mPeerFile); case AttributeType_OneTimeKey: return (!mOneTimeKey.isEmpty()); case AttributeType_Location: return (mLocation.hasData()); default: break; } return false; } zsLib::XML::DocumentPtr PeerToFinderSessionCreateRequest::encode(IPeerFilesPtr peerFile) { return internal::PeerToFinderSessionCreateRequest::encode(*this, peerFile); } PeerToFinderSessionCreateRequestPtr PeerToFinderSessionCreateRequest::create() { return internal::PeerToFinderSessionCreateRequest::create(); } namespace internal { PeerToFinderSessionCreateRequestPtr PeerToFinderSessionCreateRequest::create() { PeerToFinderSessionCreateRequestPtr ret(new message::PeerToFinderSessionCreateRequest); return ret; } DocumentPtr PeerToFinderSessionCreateRequest::encode( message::PeerToFinderSessionCreateRequest &msg, IPeerFilesPtr peerFile ) { zsLib::XML::DocumentPtr ret = IMessageHelper::createDocumentWithRoot(msg); zsLib::XML::ElementPtr root = ret->getFirstChildElement(); zsLib::XML::ElementPtr elTb, elT, el; zsLib::XML::TextPtr elTxt; elT = Element::create("token"); elTb = IMessageHelper::createElement("tokenBundle"); elTb->adoptAsFirstChild(elT); root->adoptAsFirstChild(elTb); if(msg.hasAttribute(message::PeerToFinderSessionCreateRequest::AttributeType_FinderID)) { el = Element::create(); el->setValue("finder"); IMessageHelper::setAttributeID(el, msg.mFinderID); elT->adoptAsLastChild(el); } if(msg.hasAttribute(message::PeerToFinderSessionCreateRequest::AttributeType_ContactID)) { el = Element::create(); el->setValue("contact"); IMessageHelper::setAttributeID(el, msg.mContactID); elT->adoptAsLastChild(el); } if(msg.hasAttribute(message::PeerToFinderSessionCreateRequest::AttributeType_OneTimeKey)) { el = Element::create(); el->setValue("oneTimeKey"); IMessageHelper::setAttributeID(el, msg.mOneTimeKey); elT->adoptAsLastChild(el); } if(msg.hasAttribute(message::PeerToFinderSessionCreateRequest::AttributeType_Expires)) { elTxt = Text::create(); elTxt->setValue(Stringize<time_t>(zsLib::toEpoch(msg.mExpires))); el = Element::create(); el->setValue("expires"); el->adoptAsFirstChild(elTxt); elT->adoptAsLastChild(el); } if(peerFile) { IPeerFilePublicPtr pubPeer = peerFile->getPublic(); if (pubPeer) { ElementPtr pubPeerEl = pubPeer->saveToXML(); if (pubPeerEl) elT->adoptAsLastChild(pubPeerEl); } IPeerFilePrivatePtr privPeer = peerFile->getPrivate(); if (privPeer) { privPeer->signElement(elT); } } if(msg.hasAttribute( message::PeerToFinderSessionCreateRequest::AttributeType_Location)) { root->adoptAsLastChild(MessageHelper::createElement(msg.mLocation)); } return ret; } } } } }
35.025907
108
0.648669
ilin-in
93fe47ce8471d35d96cef8d98a26a89b7ffeee5d
6,890
hpp
C++
Tools/RegistersGenerator/Msp432P401Y/fpbregisters.hpp
snorkysnark/CortexLib
0db035332ebdfbebf21ca36e5e04b78a5a908a49
[ "MIT" ]
22
2019-09-07T22:38:01.000Z
2022-01-31T21:35:55.000Z
Tools/RegistersGenerator/Msp432P401Y/fpbregisters.hpp
snorkysnark/CortexLib
0db035332ebdfbebf21ca36e5e04b78a5a908a49
[ "MIT" ]
null
null
null
Tools/RegistersGenerator/Msp432P401Y/fpbregisters.hpp
snorkysnark/CortexLib
0db035332ebdfbebf21ca36e5e04b78a5a908a49
[ "MIT" ]
9
2019-09-22T11:26:24.000Z
2022-03-21T10:53:15.000Z
/******************************************************************************* * Filename : fpbregisters.hpp * * Details : FPB. This header file is auto-generated for MSP432P401Y * device. * * *******************************************************************************/ #if !defined(FPBREGISTERS_HPP) #define FPBREGISTERS_HPP #include "fpbfieldvalues.hpp" //for Bits Fields defs #include "registerbase.hpp" //for RegisterBase #include "register.hpp" //for Register #include "accessmode.hpp" //for ReadMode, WriteMode, ReadWriteMode struct FPB { struct FPBFP_CTRLBase {} ; struct FP_CTRL : public RegisterBase<0xE0002000, 32, ReadWriteMode> { using ENABLE = FPB_FP_CTRL_ENABLE_Values<FPB::FP_CTRL, 0, 1, ReadWriteMode, FPBFP_CTRLBase> ; using KEY = FPB_FP_CTRL_KEY_Values<FPB::FP_CTRL, 1, 1, WriteMode, FPBFP_CTRLBase> ; using NUM_CODE1 = FPB_FP_CTRL_NUM_CODE1_Values<FPB::FP_CTRL, 4, 4, ReadMode, FPBFP_CTRLBase> ; using NUM_LIT = FPB_FP_CTRL_NUM_LIT_Values<FPB::FP_CTRL, 8, 4, ReadMode, FPBFP_CTRLBase> ; using NUM_CODE2 = FPB_FP_CTRL_NUM_CODE2_Values<FPB::FP_CTRL, 12, 2, ReadMode, FPBFP_CTRLBase> ; using FieldValues = FPB_FP_CTRL_NUM_CODE2_Values<FPB::FP_CTRL, 0, 0, NoAccess, NoAccess> ; } ; template<typename... T> using FP_CTRLPack = Register<0xE0002000, 32, ReadWriteMode, FPBFP_CTRLBase, T...> ; struct FPBFP_REMAPBase {} ; struct FP_REMAP : public RegisterBase<0xE0002004, 32, ReadWriteMode> { using REMAP = FPB_FP_REMAP_REMAP_Values<FPB::FP_REMAP, 5, 24, ReadWriteMode, FPBFP_REMAPBase> ; using FieldValues = FPB_FP_REMAP_REMAP_Values<FPB::FP_REMAP, 0, 0, NoAccess, NoAccess> ; } ; template<typename... T> using FP_REMAPPack = Register<0xE0002004, 32, ReadWriteMode, FPBFP_REMAPBase, T...> ; struct FPBFP_COMP0Base {} ; struct FP_COMP0 : public RegisterBase<0xE0002008, 32, ReadWriteMode> { using ENABLE = FPB_FP_COMP0_ENABLE_Values<FPB::FP_COMP0, 0, 1, ReadWriteMode, FPBFP_COMP0Base> ; using COMP = FPB_FP_COMP0_COMP_Values<FPB::FP_COMP0, 2, 27, ReadWriteMode, FPBFP_COMP0Base> ; using REPLACE = FPB_FP_COMP0_REPLACE_Values<FPB::FP_COMP0, 30, 2, ReadWriteMode, FPBFP_COMP0Base> ; using FieldValues = FPB_FP_COMP0_REPLACE_Values<FPB::FP_COMP0, 0, 0, NoAccess, NoAccess> ; } ; template<typename... T> using FP_COMP0Pack = Register<0xE0002008, 32, ReadWriteMode, FPBFP_COMP0Base, T...> ; struct FPBFP_COMP1Base {} ; struct FP_COMP1 : public RegisterBase<0xE000200C, 32, ReadWriteMode> { using ENABLE = FPB_FP_COMP1_ENABLE_Values<FPB::FP_COMP1, 0, 1, ReadWriteMode, FPBFP_COMP1Base> ; using COMP = FPB_FP_COMP1_COMP_Values<FPB::FP_COMP1, 2, 27, ReadWriteMode, FPBFP_COMP1Base> ; using REPLACE = FPB_FP_COMP1_REPLACE_Values<FPB::FP_COMP1, 30, 2, ReadWriteMode, FPBFP_COMP1Base> ; using FieldValues = FPB_FP_COMP1_REPLACE_Values<FPB::FP_COMP1, 0, 0, NoAccess, NoAccess> ; } ; template<typename... T> using FP_COMP1Pack = Register<0xE000200C, 32, ReadWriteMode, FPBFP_COMP1Base, T...> ; struct FPBFP_COMP2Base {} ; struct FP_COMP2 : public RegisterBase<0xE0002010, 32, ReadWriteMode> { using ENABLE = FPB_FP_COMP2_ENABLE_Values<FPB::FP_COMP2, 0, 1, ReadWriteMode, FPBFP_COMP2Base> ; using COMP = FPB_FP_COMP2_COMP_Values<FPB::FP_COMP2, 2, 27, ReadWriteMode, FPBFP_COMP2Base> ; using REPLACE = FPB_FP_COMP2_REPLACE_Values<FPB::FP_COMP2, 30, 2, ReadWriteMode, FPBFP_COMP2Base> ; using FieldValues = FPB_FP_COMP2_REPLACE_Values<FPB::FP_COMP2, 0, 0, NoAccess, NoAccess> ; } ; template<typename... T> using FP_COMP2Pack = Register<0xE0002010, 32, ReadWriteMode, FPBFP_COMP2Base, T...> ; struct FPBFP_COMP3Base {} ; struct FP_COMP3 : public RegisterBase<0xE0002014, 32, ReadWriteMode> { using ENABLE = FPB_FP_COMP3_ENABLE_Values<FPB::FP_COMP3, 0, 1, ReadWriteMode, FPBFP_COMP3Base> ; using COMP = FPB_FP_COMP3_COMP_Values<FPB::FP_COMP3, 2, 27, ReadWriteMode, FPBFP_COMP3Base> ; using REPLACE = FPB_FP_COMP3_REPLACE_Values<FPB::FP_COMP3, 30, 2, ReadWriteMode, FPBFP_COMP3Base> ; using FieldValues = FPB_FP_COMP3_REPLACE_Values<FPB::FP_COMP3, 0, 0, NoAccess, NoAccess> ; } ; template<typename... T> using FP_COMP3Pack = Register<0xE0002014, 32, ReadWriteMode, FPBFP_COMP3Base, T...> ; struct FPBFP_COMP4Base {} ; struct FP_COMP4 : public RegisterBase<0xE0002018, 32, ReadWriteMode> { using ENABLE = FPB_FP_COMP4_ENABLE_Values<FPB::FP_COMP4, 0, 1, ReadWriteMode, FPBFP_COMP4Base> ; using COMP = FPB_FP_COMP4_COMP_Values<FPB::FP_COMP4, 2, 27, ReadWriteMode, FPBFP_COMP4Base> ; using REPLACE = FPB_FP_COMP4_REPLACE_Values<FPB::FP_COMP4, 30, 2, ReadWriteMode, FPBFP_COMP4Base> ; using FieldValues = FPB_FP_COMP4_REPLACE_Values<FPB::FP_COMP4, 0, 0, NoAccess, NoAccess> ; } ; template<typename... T> using FP_COMP4Pack = Register<0xE0002018, 32, ReadWriteMode, FPBFP_COMP4Base, T...> ; struct FPBFP_COMP5Base {} ; struct FP_COMP5 : public RegisterBase<0xE000201C, 32, ReadWriteMode> { using ENABLE = FPB_FP_COMP5_ENABLE_Values<FPB::FP_COMP5, 0, 1, ReadWriteMode, FPBFP_COMP5Base> ; using COMP = FPB_FP_COMP5_COMP_Values<FPB::FP_COMP5, 2, 27, ReadWriteMode, FPBFP_COMP5Base> ; using REPLACE = FPB_FP_COMP5_REPLACE_Values<FPB::FP_COMP5, 30, 2, ReadWriteMode, FPBFP_COMP5Base> ; using FieldValues = FPB_FP_COMP5_REPLACE_Values<FPB::FP_COMP5, 0, 0, NoAccess, NoAccess> ; } ; template<typename... T> using FP_COMP5Pack = Register<0xE000201C, 32, ReadWriteMode, FPBFP_COMP5Base, T...> ; struct FPBFP_COMP6Base {} ; struct FP_COMP6 : public RegisterBase<0xE0002020, 32, ReadWriteMode> { using ENABLE = FPB_FP_COMP6_ENABLE_Values<FPB::FP_COMP6, 0, 1, ReadWriteMode, FPBFP_COMP6Base> ; using COMP = FPB_FP_COMP6_COMP_Values<FPB::FP_COMP6, 2, 27, ReadWriteMode, FPBFP_COMP6Base> ; using REPLACE = FPB_FP_COMP6_REPLACE_Values<FPB::FP_COMP6, 30, 2, ReadWriteMode, FPBFP_COMP6Base> ; using FieldValues = FPB_FP_COMP6_REPLACE_Values<FPB::FP_COMP6, 0, 0, NoAccess, NoAccess> ; } ; template<typename... T> using FP_COMP6Pack = Register<0xE0002020, 32, ReadWriteMode, FPBFP_COMP6Base, T...> ; struct FPBFP_COMP7Base {} ; struct FP_COMP7 : public RegisterBase<0xE0002024, 32, ReadWriteMode> { using ENABLE = FPB_FP_COMP7_ENABLE_Values<FPB::FP_COMP7, 0, 1, ReadWriteMode, FPBFP_COMP7Base> ; using COMP = FPB_FP_COMP7_COMP_Values<FPB::FP_COMP7, 2, 27, ReadWriteMode, FPBFP_COMP7Base> ; using REPLACE = FPB_FP_COMP7_REPLACE_Values<FPB::FP_COMP7, 30, 2, ReadWriteMode, FPBFP_COMP7Base> ; using FieldValues = FPB_FP_COMP7_REPLACE_Values<FPB::FP_COMP7, 0, 0, NoAccess, NoAccess> ; } ; template<typename... T> using FP_COMP7Pack = Register<0xE0002024, 32, ReadWriteMode, FPBFP_COMP7Base, T...> ; } ; #endif //#if !defined(FPBREGISTERS_HPP)
45.03268
103
0.720755
snorkysnark
9e0309e7691fa4ba3ab01037fcc3bab477210650
2,110
cpp
C++
Tests/UnitTests/MathTests/QuantizedOperationsTests.cpp
shyamalschandra/CNTK
0e7a6cd4cc174eab28eaf2ffc660c6380b9e4e2d
[ "MIT" ]
17,702
2016-01-25T14:03:01.000Z
2019-05-06T09:23:41.000Z
Tests/UnitTests/MathTests/QuantizedOperationsTests.cpp
shyamalschandra/CNTK
0e7a6cd4cc174eab28eaf2ffc660c6380b9e4e2d
[ "MIT" ]
3,489
2016-01-25T13:32:09.000Z
2019-05-03T11:29:15.000Z
Tests/UnitTests/MathTests/QuantizedOperationsTests.cpp
shyamalschandra/CNTK
0e7a6cd4cc174eab28eaf2ffc660c6380b9e4e2d
[ "MIT" ]
5,180
2016-01-25T14:02:12.000Z
2019-05-06T04:24:28.000Z
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.md file in the project root for full license information. // #include "stdafx.h" #include "../../../Source/Math/QuantizedOperations.h" #include "../../../Source/Math/Helpers.h" using namespace Microsoft::MSR::CNTK; namespace Microsoft { namespace MSR { namespace CNTK { namespace Test { BOOST_AUTO_TEST_SUITE(QuantizedOperationsUnitTests) BOOST_FIXTURE_TEST_CASE(MultiplyIntToShort, RandomSeedFixture) { // A[m,k]*B[k,n] = C[m,n] int m = 5, n = 4, k = 3; std::vector<float> A = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}; std::vector<float> B = {16,17,18,19,20,21,22,23,24,25,26,27}; std::vector<float> C_expected = { 316, 367, 418, 469, 520, 370, 430, 490, 550, 610, 424, 493, 562, 631, 700, 478, 556, 634, 712, 790 }; std::vector<float> C; C.resize(m*n); shared_ptr<QuantizerBase<float, short>> quantA(new SymmetricQuantizer<float, short>(1)); shared_ptr<QuantizerBase<float, short>> quantB(new SymmetricQuantizer<float, short>(2)); // A - is constant; B - is not QuantizedMultiplier<float> mult(quantA, true, quantB, false); // First pass mult.Multiply(m, n, k, A.data(), B.data(), C.data()); for (size_t i = 0; i < m*n; i++) BOOST_CHECK_EQUAL(round(C[i]), C_expected[i]); // Second pass, the same matrices mult.Multiply(m, n, k, A.data(), B.data(), C.data()); for (size_t i = 0; i < m*n; i++) BOOST_CHECK_EQUAL(round(C[i]), C_expected[i]); // Third pass with updated B (size and values) int n_upd = 5; std::vector<float> B_upd = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 }; std::vector<float> C_expected_upd = { 46, 52, 58, 64, 70, 100, 115, 130, 145, 160, 154, 178, 202, 226, 250, 208, 241, 274, 307, 340, 262, 304, 346, 388, 430}; std::vector<float> C_upd; C_upd.resize(m*n_upd); mult.Multiply(m, n_upd, k, A.data(), B_upd.data(), C_upd.data()); for (size_t i = 0; i < m*n_upd; i++) BOOST_CHECK_EQUAL(round(C_upd[i]), C_expected_upd[i]); } BOOST_AUTO_TEST_SUITE_END() } } } }
37.678571
162
0.633649
shyamalschandra
9e04e6a1bc1c0c4ccca074bc22c05654112324e0
1,286
cpp
C++
SDK/ARKSurvivalEvolved_ProjPoop_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_ProjPoop_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_ProjPoop_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
// ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_ProjPoop_parameters.hpp" namespace sdk { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function ProjPoop.ProjPoop_C.UserConstructionScript // () void AProjPoop_C::UserConstructionScript() { static auto fn = UObject::FindObject<UFunction>("Function ProjPoop.ProjPoop_C.UserConstructionScript"); AProjPoop_C_UserConstructionScript_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ProjPoop.ProjPoop_C.ExecuteUbergraph_ProjPoop // () // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void AProjPoop_C::ExecuteUbergraph_ProjPoop(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function ProjPoop.ProjPoop_C.ExecuteUbergraph_ProjPoop"); AProjPoop_C_ExecuteUbergraph_ProjPoop_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
22.561404
107
0.657076
2bite
9e0524f984f1483e6b3d372a6d1c3482909abd7d
6,103
cpp
C++
test/AdminTest.cpp
avilcheslopez/geopm
35ad0af3f17f42baa009c97ed45eca24333daf33
[ "MIT", "BSD-3-Clause" ]
null
null
null
test/AdminTest.cpp
avilcheslopez/geopm
35ad0af3f17f42baa009c97ed45eca24333daf33
[ "MIT", "BSD-3-Clause" ]
null
null
null
test/AdminTest.cpp
avilcheslopez/geopm
35ad0af3f17f42baa009c97ed45eca24333daf33
[ "MIT", "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2015 - 2022, Intel Corporation * SPDX-License-Identifier: BSD-3-Clause */ #include "config.h" #include <memory> #include <fstream> #include "gtest/gtest.h" #include "gmock/gmock.h" #include "geopm_sched.h" #include "geopm_test.hpp" #include "Admin.hpp" #include "geopm/Helper.hpp" using geopm::Admin; using testing::Return; class AdminTest: public :: testing :: Test { protected: void SetUp(void); void TearDown(void); std::shared_ptr<Admin> m_admin; int m_cpuid; std::string m_default_path; std::string m_override_path; std::string m_policy_path; }; void AdminTest::SetUp(void) { m_cpuid = 0x655; m_default_path = "environment-default.json"; m_override_path = "environment-override.json"; m_policy_path = "admin_test_policy.json"; m_admin = std::make_shared<Admin>(m_default_path, m_override_path, m_cpuid); unlink(m_override_path.c_str()); unlink(m_default_path.c_str()); unlink(m_policy_path.c_str()); } void AdminTest::TearDown(void) { unlink(m_override_path.c_str()); unlink(m_default_path.c_str()); unlink(m_policy_path.c_str()); } TEST_F(AdminTest, help) { const char *argv[2] {"geopmadmin", "--help"}; std::ostringstream std_out; std::ostringstream std_err; m_admin->main(2, argv, std_out, std_err); std::string result = std_out.str(); ASSERT_NE(std::string::npos, result.find("Usage: geopmadmin")); } TEST_F(AdminTest, positional_args) { const char *argv[3] {"geopmadmin", "-d", "extra-arg"}; std::ostringstream std_out; std::ostringstream std_err; GEOPM_EXPECT_THROW_MESSAGE(m_admin->main(3, argv, std_out, std_err), EINVAL, "positional argument"); } TEST_F(AdminTest, main) { const char *argv[2] {"geopmadmin", "-d"}; std::ostringstream std_out; std::ostringstream std_err; m_admin->main(2, argv, std_out, std_err); std::string result = std_out.str(); ASSERT_NE(std::string::npos, result.find("environment-default.json")); } TEST_F(AdminTest, two_actions) { GEOPM_EXPECT_THROW_MESSAGE(m_admin->run(true, true, false, -1), EINVAL, "must be used exclusively"); GEOPM_EXPECT_THROW_MESSAGE(m_admin->run(false, true, true, -1), EINVAL, "must be used exclusively"); GEOPM_EXPECT_THROW_MESSAGE(m_admin->run(true, false, true, -1), EINVAL, "must be used exclusively"); } TEST_F(AdminTest, config_default) { std::string result = m_admin->run(true, false, false, -1); ASSERT_NE(std::string::npos, result.find("environment-default.json")); } TEST_F(AdminTest, config_override) { std::string result = m_admin->run(false, true, false, -1); ASSERT_NE(std::string::npos, result.find("environment-override.json")); } TEST_F(AdminTest, allowlist) { std::string result_0 = m_admin->run(false, false, true, -1); ASSERT_EQ(0U, result_0.find("# MSR Write Mask # Comment\n")); std::string result_1 = m_admin->run(false, false, true, m_cpuid); ASSERT_EQ(result_0, result_1); } TEST_F(AdminTest, no_options) { GEOPM_EXPECT_THROW_MESSAGE(m_admin->check_node(), ENOENT, "Configuration files do not exist"); std::ofstream override_fid(m_override_path); override_fid << "{\"GEOPM_REPORT\":\"geopm_report\"}"; override_fid.close(); std::string expect = "GEOPM CONFIGURATION\n" "===================\n\n" " GEOPM_REPORT=geopm_report (override)\n"; std::string actual = m_admin->check_node(); ASSERT_EQ(expect, actual); } TEST_F(AdminTest, dup_keys) { std::map<std::string, std::string> map_a; std::map<std::string, std::string> map_b; std::vector<std::string> result; result = Admin::dup_keys(map_a, map_b); ASSERT_EQ(0U, result.size()); map_a["alpha"] = "one"; map_b["beta"] = "two"; result = Admin::dup_keys(map_a, map_b); ASSERT_EQ(0U, result.size()); map_a["beta"] = "three"; map_a["gamma"] = "five"; map_b["delta"] = "four"; result = Admin::dup_keys(map_a, map_b); std::vector<std::string> expect {"beta"}; ASSERT_EQ(expect, result); } TEST_F(AdminTest, dup_config) { std::ofstream override_fid(m_override_path); override_fid << "{\"GEOPM_REPORT\":\"geopm_report\"}"; override_fid.close(); std::ofstream default_fid(m_default_path); default_fid << "{\"GEOPM_REPORT\":\"geopm_report_other\"}"; default_fid.close(); GEOPM_EXPECT_THROW_MESSAGE(m_admin->check_node(), EINVAL, "defined in both the override and default"); } TEST_F(AdminTest, print_config) { std::map<std::string, std::string> default_map = {{"GEOPM_REPORT", "default_report"}}; std::map<std::string, std::string> override_map = {{"GEOPM_AGENT", "override_agent"}, {"GEOPM_POLICY", m_policy_path}}; std::vector<std::string> pol_names = {"pol1", "pol2"}; std::vector<double> pol_vals = {0.1, 0.2}; std::string expected = "\ GEOPM CONFIGURATION\n\ ===================\n\n\ GEOPM_AGENT=override_agent (override)\n\ GEOPM_POLICY=admin_test_policy.json (override)\n\ GEOPM_REPORT=default_report (default)\n\ \nAGENT POLICY\n\ ============\n\n\ pol1=0.1\n\ pol2=0.2\n"; EXPECT_EQ(expected, m_admin->print_config(default_map, override_map, pol_names, pol_vals)); } TEST_F(AdminTest, agent_no_policy) { std::ofstream override_fid(m_override_path); override_fid << "{\"GEOPM_AGENT\":\"monitor\"}"; override_fid.close(); m_admin->check_node(); override_fid.open(m_override_path); override_fid << "{\"GEOPM_AGENT\":\"monitor\"," " \"GEOPM_POLICY\":\"monitor_policy.json\"}"; override_fid.close(); std::ofstream policy_fid(m_policy_path); policy_fid << "{}"; policy_fid.close(); m_admin->check_node(); }
31.458763
95
0.628216
avilcheslopez
9e059be9da183e39b04f834641680fe3aadb2c67
1,672
cc
C++
application/go_server.cc
ZenLiuCN/zcef
dfa128963c05ec9e222c6da1119f96440b462a6c
[ "MIT" ]
1
2019-01-23T11:16:49.000Z
2019-01-23T11:16:49.000Z
application/go_server.cc
ZenLiuCN/zcef
dfa128963c05ec9e222c6da1119f96440b462a6c
[ "MIT" ]
null
null
null
application/go_server.cc
ZenLiuCN/zcef
dfa128963c05ec9e222c6da1119f96440b462a6c
[ "MIT" ]
2
2018-10-29T16:56:56.000Z
2020-01-08T14:54:24.000Z
// // Created by Zen Liu on 2018-10-6. // #include "go_server.h" #include "goserver.h" bool GoServer::start(std::string port) { return static_cast<bool>(goStartServer(const_cast<char *>(port.c_str()))); } int GoServer::enableHttpServer(std::string dir) { return int(goUseHttpServer(const_cast<char *>(dir.c_str()))); } void GoServer::close() { goStopServer(); } void GoServer::setDebug(int i) { goSetDebug(i); } GoServer::~GoServer() { this->close(); } void GoServer::closeAllDB() { goCloseAllDB(); } string GoServer::openDB(string name, string password) { return string(goOpenDB(const_cast<char *>(name.c_str()), const_cast<char *>(password.c_str()))); } string GoServer::queryDB(string name, string query) { return string(goQueryDB(const_cast<char *>(name.c_str()), const_cast<char *>(query.c_str()))); } string GoServer::execDB(string name, string query) { return string(goExecDB(const_cast<char *>(name.c_str()), const_cast<char *>(query.c_str()))); } string GoServer::execsDB(string name, string query) { return string(goExecsDB(const_cast<char *>(name.c_str()), const_cast<char *>(query.c_str()))); } string GoServer::querysDB(string name, string query) { return string(goQuerysDB(const_cast<char *>(name.c_str()), const_cast<char *>(query.c_str()))); } string GoServer::exportDB(string name) { return string(goExportDB(const_cast<char *>(name.c_str()))); } int GoServer::delDB(string name) { return goDelDB(const_cast<char *>(name.c_str())); } int GoServer::closeDB(string name) { return goCloseDB(const_cast<char *>(name.c_str())); } string GoServer::openedDB() { return goOpened(); }
23.885714
100
0.686005
ZenLiuCN
9e065de0207a060e30327b0b626810089886fc23
6,406
hpp
C++
third/include/atlas/transaction/detail/transaction_manager.hpp
galaxyeye/pioneer
cfc3aa3c4917b19000753ea3144bded79380d289
[ "Apache-2.0" ]
4
2017-05-12T07:37:17.000Z
2019-11-14T10:52:28.000Z
third/include/atlas/transaction/detail/transaction_manager.hpp
galaxyeye/pioneer
cfc3aa3c4917b19000753ea3144bded79380d289
[ "Apache-2.0" ]
null
null
null
third/include/atlas/transaction/detail/transaction_manager.hpp
galaxyeye/pioneer
cfc3aa3c4917b19000753ea3144bded79380d289
[ "Apache-2.0" ]
7
2017-06-21T03:35:51.000Z
2020-10-14T04:58:26.000Z
// Copyright Stefan Strasser 2010. // Copyright Vicente J. Botet Escriba 2010. // 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) #ifndef BOOST_TRANSACT_DETAIL_TAG_RESOURCE_PAIR_HPP #define BOOST_TRANSACT_DETAIL_TAG_RESOURCE_PAIR_HPP #include <boost/mpl/bool.hpp> #include <boost/type_traits/is_empty.hpp> #include <boost/optional/optional.hpp> #include <boost/transact/exception.hpp> #include <boost/noncopyable.hpp> #include <boost/assert.hpp> #include <boost/mpl/has_key.hpp> #include <boost/transact/resource_manager.hpp> #include <boost/transact/exception.hpp> namespace boost { namespace transact { namespace detail { template<class Tag, class Resource> class tag_resource_pair : noncopyable { public: typedef std::pair<Tag, Resource *> const *iterator; void connect(Tag const &tag, Resource &res) { if (this->pair) { if (this->tag_is_equal(tag)) throw resource_error(); else throw unsupported_operation(); } this->pair = std::make_pair(tag, &res); } void disconnect(Tag const &tag) { if (!this->pair || !this->tag_is_equal(tag)) throw resource_error(); this->pair = none; } Resource &get(Tag const &tag) const { if (!this->pair || !this->tag_is_equal(tag)) throw resource_error(); BOOST_ASSERT(this->pair->second); return *this->pair->second; } Resource &get(Tag const &tag, std::size_t &index) const { if (!this->pair || !this->tag_is_equal(tag)) throw resource_error(); BOOST_ASSERT(this->pair->second); index = 0; return *this->pair->second; } std::pair<iterator, iterator> range() const { if (this->pair) { return std::pair<iterator, iterator>(&*this->pair, &*this->pair + 1); } else { return std::pair<iterator, iterator>(0, 0); } } bool empty() const { return !this->pair; } std::size_t size() const { return this->pair ? 1 : 0; } const Tag& tag() const { BOOST_ASSERT(this->pair); return this->pair->first; } private: bool tag_is_equal(Tag const &o) const { return this->tag_is_equal(o, boost::is_empty<Tag>()); } bool tag_is_equal(Tag const &, mpl::true_ empty) const { return true; } bool tag_is_equal(Tag const &o, mpl::false_ empty) const { BOOST_ASSERT(this->pair); return this->pair->first == o; } optional<std::pair<Tag, Resource *> > pair; }; template<class Transaction, class Resources> struct beginner { beginner(Transaction *parent, Resources &ress) : parent(parent), ress(ress) { } template<class Tag, class Resource> void operator()(Tag const &tag, Resource &res, optional<typename Resource::transaction> &tx) { BOOST_ASSERT(!tx); if (this->parent) this->begin_nested(tag, res, tx, typename has_service<Resource, nested_transaction_service_tag>::type()); else tx = in_place(res.begin_transaction()); BOOST_ASSERT(tx); } private: template<class Tag, class Resource> void begin_nested(Tag const &tag, Resource &res, optional<typename Resource::transaction> &tx, mpl::true_ nestedservice) { BOOST_ASSERT(this->parent); typename Resource::transaction &parenttx = this->parent->resource_transaction(this->ress, tag); tx = in_place(res.begin_nested_transaction(parenttx)); } template<class Tag, class Resource> void begin_nested(Tag const &, Resource &, optional<typename Resource::transaction> &, mpl::false_ nestedservice) { throw unsupported_operation(); } Transaction *parent; Resources &ress; }; struct finisher { template<class Tag, class Resource> bool operator()(Tag const &, Resource &res, optional<typename Resource::transaction> &tx, bool repeat) { if (tx) { return this->finish(res, *tx, typename has_service<Resource, finish_transaction_service_tag>::type()) || repeat; } else return repeat; } private: template<class Resource> bool finish(Resource &res, typename Resource::transaction &tx, mpl::true_ finishservice) { return res.finish_transaction(tx); } template<class Resource> bool finish(Resource &res, typename Resource::transaction &tx, mpl::false_ finishservice) { return false; } }; struct committer { template<class Tag, class Resource> void operator()(Tag const &, Resource &res, optional<typename Resource::transaction> &tx) { if (tx) res.commit_transaction(*tx); } }; struct rollbacker { template<class Tag, class Resource> void operator()(Tag const &, Resource &res, optional<typename Resource::transaction> &tx) { if (tx) res.rollback_transaction(*tx); } }; template<class Beginner> struct restarter { explicit restarter(Beginner const &begin) : begin(begin) { } template<class Tag, class Resource> void operator()(Tag const &tag, Resource &res, optional<typename Resource::transaction> &tx) { if (tx) this->restart(tag, res, tx, typename has_service<Resource, restart_transaction_service_tag>::type()); } private: template<class Tag, class Resource> void restart(Tag const &, Resource &res, optional<typename Resource::transaction> &tx, mpl::true_ service) { BOOST_ASSERT(tx); res.restart_transaction(*tx); } template<class Tag, class Resource> void restart(Tag const &tag, Resource &res, optional<typename Resource::transaction> &tx, mpl::false_ service) { BOOST_ASSERT(tx); res.rollback_transaction(*tx); tx = none; this->begin(tag, res, tx); } Beginner begin; }; } } } #endif
31.870647
120
0.598814
galaxyeye
9e0b524886f94ebbe8d7a7279ac25eab9f5f4ce3
535
cpp
C++
src/bench/bench_arc_param.cpp
prateekma/FalconLibraryC-
11b45e96f0735fa5c668386ef0da6ebf80011998
[ "MIT" ]
2
2019-06-28T08:00:15.000Z
2019-06-29T02:42:51.000Z
src/bench/bench_arc_param.cpp
prateekma/FalconLibraryC-
11b45e96f0735fa5c668386ef0da6ebf80011998
[ "MIT" ]
null
null
null
src/bench/bench_arc_param.cpp
prateekma/FalconLibraryC-
11b45e96f0735fa5c668386ef0da6ebf80011998
[ "MIT" ]
1
2019-08-04T14:02:33.000Z
2019-08-04T14:02:33.000Z
#include <FalconLibrary.h> #include <benchmark/benchmark.h> static void BM_ArcParam(benchmark::State& state) { const fl::Pose2d initial{0.0, 0.0, fl::Rotation2d::FromDegrees(0.0)}; const fl::Pose2d final{10.0, 10.0, fl::Rotation2d::FromDegrees(45.0)}; const auto spline = std::make_shared<fl::ParametricQuinticHermiteSpline>(initial, final); for (auto _ : state) { fl::SplineGenerator::ParameterizeSpline(spline, 2.0, 0.05, 0.1); } } BENCHMARK(BM_ArcParam)->Arg(100)->Complexity()->Unit(benchmark::kMillisecond);
38.214286
97
0.71215
prateekma
9e19d40f52f3c9036579b96e536cb9f6b674affe
6,670
cc
C++
src/circuit/circuit_data.cc
hyraxZK/libpws
cc1b7dfdafb3d01b025cdb72ed83379d205a0147
[ "Apache-2.0" ]
null
null
null
src/circuit/circuit_data.cc
hyraxZK/libpws
cc1b7dfdafb3d01b025cdb72ed83379d205a0147
[ "Apache-2.0" ]
null
null
null
src/circuit/circuit_data.cc
hyraxZK/libpws
cc1b7dfdafb3d01b025cdb72ed83379d205a0147
[ "Apache-2.0" ]
1
2020-01-16T07:49:03.000Z
2020-01-16T07:49:03.000Z
#include <cassert> #include <sstream> #include <stdint.h> #include <iostream> #include <cerrno> #include <stdexcept> #include "circuit_data.hh" #include "debug_utils.hh" #include "mpnops.hh" #include "prng.hh" #include "utility.hh" using namespace std; static Prng &prng = Prng::global; #define RETURN_IF_FALSE(file, statement) { if (!statement) { fclose(f); return false; } } template<typename T> bool write(FILE* f, const T& val) { return fwrite(&val, sizeof(val), 1, f) == 1; } template<> bool write<mpz_t>(FILE* f, const mpz_t& val) { return mpz_out_raw(f, val) != 0; } template<> bool write<mpq_t>(FILE* f, const mpq_t& val) { return (mpz_out_raw(f, mpq_numref(val)) != 0) && (mpz_out_raw(f, mpq_denref(val)) != 0); } template<typename T> bool read(T& val, FILE* f) { return fread(&val, sizeof(val), 1, f) == 1; } template<> bool read<mpz_t>(mpz_t& val, FILE* f) { return mpz_inp_raw(val, f) != 0; } template<> bool read<mpq_t>(mpq_t& val, FILE* f) { return (mpz_inp_raw(mpq_numref(val), f) != 0) && (mpz_inp_raw(mpq_denref(val), f) != 0); } template<typename T> size_t sizeOf(const T& obj) { return sizeof(obj); } template<> size_t sizeOf<mpz_t>(const mpz_t& val) { return mpz_sizeinbase(val, 2) / 8 + sizeof(val); } template<> size_t sizeOf<mpq_t>(const mpq_t& val) { return sizeOf(mpq_numref(val)) + sizeOf(mpq_denref(val)); } template<typename T> T getRandom(Prng& prng) { T out; prng.get_randomb(reinterpret_cast<char*>(&out), sizeof(out) * 8); return out; } static FILE * open_file(const string& filename, const string& mode, const string& directory, bool createDir = true) { if (createDir) recursive_mkdir(directory); string fname(directory); fname += '/'; fname += filename; return fopen(fname.c_str(), mode.c_str()); } template<typename T> bool LayerData<T>:: save(const string& directory) const { if (shouldSave()) { string name = layerName(); FILE* f; if (!(f = open_file(layerName(), "wb", directory))) return false; RETURN_IF_FALSE(f, write(f, LAYER_DATA_HEADER)); RETURN_IF_FALSE(f, write(f, gates.size())); for (size_t i = 0; i < gates.size(); i++) RETURN_IF_FALSE(f, write(f, gates[i])); fflush(f); fclose(f); } return true; } template<typename T> bool LayerData<T>:: load(const string& directory) { string name = layerName(); FILE* f; uint32_t header; size_t size; if (!(f = open_file(layerName(), "rb", directory, false))) return false; RETURN_IF_FALSE(f, read(header, f)); RETURN_IF_FALSE(f, read(size, f)); gates.resize(size); isDirty = false; for (size_t i = 0; i < gates.size(); i++) RETURN_IF_FALSE(f, read(gates[i], f)); fclose(f); return true; } template<typename T> void LayerData<T>:: tryLoad(const string& directory, size_t size) { if (!load(directory)) { if (gates.size() != size) gates.resize(size); assert(gates.size() == size); for (size_t i = 0; i < size; i++) mpn_ops<T>::init(gates[i]); } } template<typename T> size_t LayerData<T>:: dataSize() const { double avg = 0; const uint32_t numSamples = 4; if (gates.size() > 0) { for (uint32_t i = 0; i < numSamples; i++) { size_t idx = getRandom<size_t>(prng) % gates.size(); avg = sizeOf(gates[idx]); } avg /= numSamples; } return size_t(avg * gates.size()) + sizeof(this); } template<typename T> string LayerData<T>:: layerName() const { stringstream ss; ss << "layer_" << index(); return ss.str(); } template<typename T> string circuitPrefix() { //TODO: Use static_assert. throw runtime_error("Does not work."); } template<> string circuitPrefix<mpz_t>() { return "circuit"; } template<> string circuitPrefix<mpq_t>() { return "circuitq"; } template<typename T> CircuitData<T>:: CircuitData(size_t memBudget, const std::vector<size_t>& sizes, const string& suffix) : blocks(), blockSizes(sizes), circuitDir(), budget(memBudget), usage(0) { stringstream ss; ss << FOLDER_STATE << "/" << circuitPrefix<T>() << "_"; if (suffix.empty()) { struct stat sb; do { stringstream testDir; uint64_t randNumber = getRandom<uint64_t>(prng); testDir << ss.str() << hex << randNumber; circuitDir = testDir.str(); } while (stat(circuitDir.c_str(), &sb) == 0); } else { ss << suffix; circuitDir = ss.str(); } // Reserve circuit directory. if (!recursive_mkdir(circuitDir)) throw runtime_error("Could not create new directory for circuit."); } template<typename T> LayerData<T>& CircuitData<T>:: operator [](int layerIdx) { assert(inRange<int>(layerIdx, 0, blockSizes.size())); typedef typename deque<LayerData<T> >::iterator LayerDataIt; for (LayerDataIt it = blocks.begin(); it != blocks.end(); ++it) { if (it->index() == layerIdx) return *it; } LayerData<T>& newLayer = load(layerIdx); assert(newLayer.index() == layerIdx); return newLayer; } template<typename T> void CircuitData<T>:: setBudget(size_t newBudget) { budget = newBudget; } template<typename T> void CircuitData<T>:: setSizes(const std::vector<size_t>& newSizes) { this->blockSizes = newSizes; } template<typename T> bool CircuitData<T>:: save() const { bool success = true; typedef typename deque<LayerData<T> >::const_iterator LayerDataCIt; for (LayerDataCIt it = blocks.begin(); it != blocks.end(); ++it) success = it->save(circuitDir) && success; return success; } template<typename T> LayerData<T>& CircuitData<T>:: load(int layerIdx) { assert(inRange<int>(layerIdx, 0, blockSizes.size())); updateUsage(); while (shouldEvict(true)) { LayerData<T>& layer = blocks.front(); assert(usage >= layer.dataSize()); //cout << "Evicting Layer: " << layer.index() << " Usage: " << usage << endl; layer.save(circuitDir); usage -= layer.dataSize(); blocks.pop_front(); } //cout << "Load Layer: " << layerIdx << " Usage: " << usage << endl; blocks.push_back(LayerData<T>(layerIdx)); LayerData<T>& newLayer = blocks.back(); newLayer.tryLoad(circuitDir, blockSizes[layerIdx]); usage += newLayer.dataSize(); return newLayer; } template<typename T> void CircuitData<T>:: updateUsage() { usage = 0; typedef typename deque<LayerData<T> >::const_iterator LayerDataCIt; for (LayerDataCIt it = blocks.begin(); it != blocks.end(); ++it) usage += it->dataSize(); } template<typename T> bool CircuitData<T>:: shouldEvict(bool evictToAdd) const { size_t minNumLayers = 2 + (evictToAdd ? -1 : 0); return (minNumLayers < blocks.size()) && (usage > budget); } template class CircuitData<mpz_t>; template class CircuitData<mpq_t>;
20.778816
101
0.651724
hyraxZK
9e1a6c046f4714f9791f3fe5c29602670e14269b
2,596
cpp
C++
engine/graphics/graphics_bootstrapper.cpp
JellevanCampen/pugvania
1f964f70b05565adea6c5c55c2c2bae5cac52d53
[ "MIT" ]
null
null
null
engine/graphics/graphics_bootstrapper.cpp
JellevanCampen/pugvania
1f964f70b05565adea6c5c55c2c2bae5cac52d53
[ "MIT" ]
24
2016-09-26T14:54:31.000Z
2017-02-16T14:01:58.000Z
engine/graphics/graphics_bootstrapper.cpp
JellevanCampen/pugvania
1f964f70b05565adea6c5c55c2c2bae5cac52d53
[ "MIT" ]
null
null
null
#include "graphics_bootstrapper.h" #include "engine.h" #include "graphics_glfw.h" namespace engine { void GraphicsBootstrapper::CameraMove(Point2Df position) { g_log("Calling bootstrapper function (graphics subsystem call before the graphics subsystem was bootstrapped): " __FUNCTION__, log::kError); } void GraphicsBootstrapper::Draw2DPoint(Point2Df point, float z, cRGBAf color) const { g_log("Calling bootstrapper function (graphics subsystem call before the graphics subsystem was bootstrapped): " __FUNCTION__, log::kError); } void GraphicsBootstrapper::Draw2DLine(Line2Df line, float z, cRGBAf color) const { g_log("Calling bootstrapper function (graphics subsystem call before the graphics subsystem was bootstrapped): " __FUNCTION__, log::kError); } void GraphicsBootstrapper::Draw2DRectangle(Rectangle2Df rectangle, float z, bool filled, cRGBAf color) const { g_log("Calling bootstrapper function (graphics subsystem call before the graphics subsystem was bootstrapped): " __FUNCTION__, log::kError); } void GraphicsBootstrapper::Draw2DCircle(Circle2Df circle, float z, bool filled, cRGBAf color) const { g_log("Calling bootstrapper function (graphics subsystem call before the graphics subsystem was bootstrapped): " __FUNCTION__, log::kError); } EngineSubsystem* GraphicsBootstrapper::Initialize() { std::string graphics_subsystem; ConfigFile engine_config((*g_engine->path)["config"] + "engine_config.ini", ConfigFile::WARN_COUT, ConfigFile::WARN_COUT); engine_config.ReadProperty<std::string>("subsystems.graphics", &graphics_subsystem, "glfw"); // Bootstrap a graphics subsystem implementation based on the config settings if (graphics_subsystem.compare("glfw") == 0) { Graphics* graphics = new GraphicsGLFW(); g_engine->graphics = graphics; return graphics->Initialize(); } g_log("The graphics subsystem specified in the config file was not recognized: " + graphics_subsystem, log::kError); return NULL; } void GraphicsBootstrapper::Terminate() { g_log("Calling bootstrapper terminator (graphics subsystem bootcaller is terminated, meaning it failed to bootstrap the graphics subsystem during initialization): " __FUNCTION__, log::kError); } void GraphicsBootstrapper::Update() { g_log("Calling bootstrapper function (graphics subsystem call before the graphics subsystem was bootstrapped): " __FUNCTION__, log::kError); } void GraphicsBootstrapper::Draw() { g_log("Calling bootstrapper function (graphics subsystem call before the graphics subsystem was bootstrapped): " __FUNCTION__, log::kError); } }; // namespace
39.938462
194
0.780046
JellevanCampen
9e1b8894754b1029452c597246b59617e6adb8fa
71
cpp
C++
src/streams/SentenceStringOutputStream.cpp
alesapin/rutok
808a88dd80f1cf03bbf459bec71b8655825b5391
[ "MIT" ]
null
null
null
src/streams/SentenceStringOutputStream.cpp
alesapin/rutok
808a88dd80f1cf03bbf459bec71b8655825b5391
[ "MIT" ]
8
2019-08-17T11:50:37.000Z
2019-08-17T20:28:31.000Z
src/streams/SentenceStringOutputStream.cpp
alesapin/rutok
808a88dd80f1cf03bbf459bec71b8655825b5391
[ "MIT" ]
null
null
null
#include <streams/SentenceStringOutputStream.h> namespace tokenize { }
14.2
47
0.816901
alesapin
9e23bf60256db25ca0e0d7bcff0e5d946ea581d3
2,262
cpp
C++
using-cpp-standard-template-libraries-master/Chapter 10/Ex10_02.cpp
ai-chen2050/book-code
74676efa50ef9e8a4a40b97978d9d42f18070102
[ "MIT" ]
null
null
null
using-cpp-standard-template-libraries-master/Chapter 10/Ex10_02.cpp
ai-chen2050/book-code
74676efa50ef9e8a4a40b97978d9d42f18070102
[ "MIT" ]
null
null
null
using-cpp-standard-template-libraries-master/Chapter 10/Ex10_02.cpp
ai-chen2050/book-code
74676efa50ef9e8a4a40b97978d9d42f18070102
[ "MIT" ]
null
null
null
// Ex10_02.cpp // Dropping bricks safely from a tall building using valarray objects #include <numeric> // For iota() #include <iostream> // For standard streams #include <iomanip> // For stream manipulators #include <algorithm> // For for_each() #include <valarray> // For valarray const static double g {32.0}; // Acceleration due to gravity ft/sec/sec int main() { double height {}; // Building height std::cout << "Enter the approximate height of the building in feet: "; std::cin >> height; // Calculate brick flight time in seconds double end_time {std::sqrt(2 * height / g)}; size_t max_time {1 + static_cast<size_t>(end_time + 0.5)}; std::valarray<double> times(max_time + 1); // Array to accommodate times std::iota(std::begin(times), std::end(times), 0); // Initialize: 0 to max_time *(std::end(times) - 1) = end_time; // Set the last time value // Calculate distances each second auto distances = times.apply([](double t) { return 0.5*g*t*t; }); // Calculate speed each second auto v_fps = sqrt(distances.apply([](double d) { return 2 * g*d; })); // Lambda expression to output results auto print = [](double v) { std::cout << std::setw(5) << static_cast<int>(std::round(v)); }; // Output the times - the last is a special case... std::cout << "Time (seconds): "; std::for_each(std::begin(times), std::end(times) - 1, print); std::cout << std::setw(5) << std::fixed << std::setprecision(2) << *(std::end(times) - 1); std::cout << "\nDistances(feet):"; std::for_each(std::begin(distances), std::end(distances), print); std::cout << "\nVelocity(fps): "; std::for_each(std::begin(v_fps), std::end(v_fps), print); // Get velocities in mph and output them auto v_mph = v_fps.apply([](double v) { return v * 60 / 88; }); std::cout << "\nVelocity(mph): "; std::for_each(std::begin(v_mph), std::end(v_mph), print); std::cout << std::endl; }
46.163265
98
0.549514
ai-chen2050
9e264e9ef33fb9bdd550611dcf4d365ca941ebe3
447
cpp
C++
Courses/Sams_Teach_Yourself_C++_in_One_Hour_a_Day/Chap_10/Lesson 10.8 A class CarRelated to class Motorvia private Inheritance.cpp
mccrudd3n/practise
26a65c0515c9bea7583bcb8f4c0022659b48dcf5
[ "Unlicense" ]
null
null
null
Courses/Sams_Teach_Yourself_C++_in_One_Hour_a_Day/Chap_10/Lesson 10.8 A class CarRelated to class Motorvia private Inheritance.cpp
mccrudd3n/practise
26a65c0515c9bea7583bcb8f4c0022659b48dcf5
[ "Unlicense" ]
null
null
null
Courses/Sams_Teach_Yourself_C++_in_One_Hour_a_Day/Chap_10/Lesson 10.8 A class CarRelated to class Motorvia private Inheritance.cpp
mccrudd3n/practise
26a65c0515c9bea7583bcb8f4c0022659b48dcf5
[ "Unlicense" ]
null
null
null
#include <iostream> using namespace std; class Motor { public: void SwitchIgnition() { cout << "Ignition On" << endl; } void PumpFuel() { cout << "Fuel in Cylinders" << endl; } void FireCylinders() { cout << "Boom" << endl; } }; class Car: private Motor { public: void Move() { SwitchIgnition(); PumpFuel(); FireCylinders(); } }; int main() { Car myDreamCar; myDreamCar.Move(); return 0; }
11.763158
40
0.577181
mccrudd3n
9e278f92c4dfe47b1b62a04badfa953a67cb3cb1
8,336
cpp
C++
SFMLTemplate/Model.cpp
Altelus/Monkey-Racers
421529bf4084f53485750041ccde6f6b96f6a861
[ "Xnet", "X11" ]
2
2015-10-27T08:36:36.000Z
2020-03-28T12:59:24.000Z
SFMLTemplate/Model.cpp
Altelus/Monkey-Racers
421529bf4084f53485750041ccde6f6b96f6a861
[ "Xnet", "X11" ]
null
null
null
SFMLTemplate/Model.cpp
Altelus/Monkey-Racers
421529bf4084f53485750041ccde6f6b96f6a861
[ "Xnet", "X11" ]
null
null
null
#include "Engine.h" #include <exception> Model::Model() { isLoaded = false; scale = Vec3 (1,1,1); originOffsetPos = Vec3 (0,0,0); forward = Vec3 (0,0,-1); strafe = Vec3 (1,0,0); up = Vec3 (0,1,0); azemuth = elevation = 0; vbo = new cbmini::cbfw::VertexBuffer; SetModelType(MODEL_TYPE_VTN); } Model::Model(const char* filename, const int type, bool compCollision) { isLoaded = false; scale = Vec3 (1,1,1); originOffsetPos = Vec3 (0,0,0); forward = Vec3 (0,0,-1); strafe = Vec3 (1,0,0); up = Vec3 (0,1,0); azemuth = elevation = 0; vbo = new cbmini::cbfw::VertexBuffer; SetModelType(type); loadObj(filename); if (compCollision) generateBoundingBox(); } void Model::SetModelType(int type) { if (0 <= type && type <= MODEL_TYPE_VTN) modelType = type; } bool Model::loadObj(const char* filename) { float tempSize = 3; bool result = false; float vertA, uvA, normA, vertB, uvB, normB, vertC, uvC, normC; vertA = uvA = normA = vertB = uvB = normB = vertC = uvC = normC = 0; float x, y, z, u, v, a, b, c; char line[255]; char header[3]; FILE* file = fopen(filename, "r"); if (file == nullptr) return false; try { while (!feof(file)) { readLine(file, line); sscanf (line, "%s", &header); if (strcmp(header, "v") == 0) { sscanf(line, "%*s %f %f %f", &x, &y, &z); tempVertices.push_back(x); tempVertices.push_back(y); tempVertices.push_back(z); } else if (strcmp(header, "vt") == 0) { sscanf(line, "%*s %f %f", &u, &v); tempUVs.push_back(u); tempUVs.push_back(v); } else if (strcmp(header, "vn") == 0) { sscanf(line, "%*s %f %f %f", &a, &b, &c); tempNormals.push_back(a); tempNormals.push_back(b); tempNormals.push_back(c); } else if(strcmp(header, "f") == 0) { if (modelType == MODEL_TYPE_V) { sscanf(line, "%*s %f %f %f", &vertA, &vertB, &vertC); } else if (modelType == MODEL_TYPE_VT) { sscanf(line, "%*s %f/%f %f/%f %f/%f", &vertA, &uvA, &vertB, &uvB, &vertC, &uvC); } else if (modelType == MODEL_TYPE_VTN) { sscanf(line, "%*s %f/%f/%f %f/%f/%f %f/%f/%f", &vertA, &uvA, &normA, &vertB, &uvB, &normB, &vertC, &uvC, &normC); } tempIndices.push_back(vertA); tempIndices.push_back(uvA); tempIndices.push_back(normA); tempIndices.push_back(vertB); tempIndices.push_back(uvB); tempIndices.push_back(normB); tempIndices.push_back(vertC); tempIndices.push_back(uvC); tempIndices.push_back(normC); } } fclose(file); setupVAO(); setupVBO(); isLoaded = result = true; } catch(...) { tempVertices.clear(); tempUVs.clear(); tempNormals.clear(); tempIndices.clear(); vertices.clear(); uvs.clear(); normals.clear(); } return result; } void Model::draw() { if (isLoaded) { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texture); glEnable(GL_RESCALE_NORMAL); vbo->ActivateAndRender(); glDisable(GL_RESCALE_NORMAL); glDisable(GL_TEXTURE_2D); } } void Model::drawNoTextures() { if (isLoaded) { glEnable(GL_RESCALE_NORMAL); vbo->ActivateAndRender(); glDisable(GL_RESCALE_NORMAL); } } void Model::drawBoundingBox() { if (isLoaded) { glPushMatrix(); glTranslatef(pos.x, pos.y, pos.z); glScalef(scale.x, scale.y, scale.z); //boundingBox.RotateX(rot.x); //boundingBox.RotateY(rot.y); //boundingBox.RotateZ(rot.z); glRotatef(rot.x, 1, 0, 0); glRotatef(rot.y, 0, 1, 0); glRotatef(rot.z, 0, 0, 1); glRotatef(-elevation, 1.0f, 0.0f, 0.0f); glRotatef(-azemuth, 0.0f, 1.0f, 0.0f); glEnable(GL_RESCALE_NORMAL); glBegin(GL_QUADS); glVertex3f(-boundingBox.x, -boundingBox.y, boundingBox.z); glVertex3f(-boundingBox.x, boundingBox.y, boundingBox.z); glVertex3f(boundingBox.x, boundingBox.y, boundingBox.z); glVertex3f(boundingBox.x, -boundingBox.y, boundingBox.z); glVertex3f(boundingBox.x, -boundingBox.y, -boundingBox.z); glVertex3f(boundingBox.x, boundingBox.y, -boundingBox.z); glVertex3f(-boundingBox.x, boundingBox.y, -boundingBox.z); glVertex3f(-boundingBox.x, -boundingBox.y, -boundingBox.z); glVertex3f(-boundingBox.x, boundingBox.y, boundingBox.z); glVertex3f(-boundingBox.x, -boundingBox.y, boundingBox.z); glVertex3f(-boundingBox.x, -boundingBox.y, -boundingBox.z); glVertex3f(-boundingBox.x, boundingBox.y, -boundingBox.z); glVertex3f(boundingBox.x, -boundingBox.y, boundingBox.z); glVertex3f(boundingBox.x, boundingBox.y, boundingBox.z); glVertex3f(boundingBox.x, boundingBox.y, -boundingBox.z); glVertex3f(boundingBox.x, -boundingBox.y, -boundingBox.z); glVertex3f(-boundingBox.x, -boundingBox.y, -boundingBox.z); glVertex3f(-boundingBox.x, -boundingBox.y, boundingBox.z); glVertex3f(boundingBox.x, -boundingBox.y, boundingBox.z); glVertex3f(boundingBox.x, -boundingBox.y, -boundingBox.z); glVertex3f(-boundingBox.x, boundingBox.y, -boundingBox.z); glVertex3f(boundingBox.x, boundingBox.y, -boundingBox.z); glVertex3f(boundingBox.x, boundingBox.y, boundingBox.z); glVertex3f(-boundingBox.x, boundingBox.y, boundingBox.z); glEnd(); glDisable(GL_RESCALE_NORMAL); glPopMatrix(); } } void Model::readLine(FILE * fp, char * string) { do { fgets(string, 255, fp); } while (string[0] == '\n'); return; } Model::~Model() { tempVertices.clear(); tempUVs.clear(); tempNormals.clear(); tempIndices.clear(); vertices.clear(); uvs.clear(); normals.clear(); vbo->Release(); delete vbo; } bool Model::generateBoundingBox() { bool result = false; if (isLoaded) { float minX, maxX; float minY, maxY; float minZ, maxZ; minX = maxX = tempVertices[0]; minY = maxY = tempVertices[1]; minZ = maxZ = tempVertices[2]; for(unsigned int i = 0; i < tempVertices.size(); i+=3) { if (tempVertices[i] < minX) minX = tempVertices[i]; else if (tempVertices[i] > maxX) maxX = tempVertices[i]; if (tempVertices[i+1] < minY) minY = tempVertices[i+1]; else if (tempVertices[i+1] > maxY) maxY = tempVertices[i+1]; if (tempVertices[i+2] < minZ) minZ = tempVertices[i+2]; else if (tempVertices[i+2] > maxZ) maxZ = tempVertices[i+2]; } // create bounding box based on min/max values of each axis boundingBox.x = ((maxX - minX) / 2)*scale.x; boundingBox.y = ((maxY - minY) / 2)*scale.y; boundingBox.z = ((maxZ - minZ) / 2)*scale.z; // calculate offset of object from origin 0,0,0 (for objs not in the center) originOffsetPos.x = minX + boundingBox.x; originOffsetPos.y = minY + boundingBox.y; originOffsetPos.z = minZ + boundingBox.z; result = true; } return result; } // lerp from cur model to target Model* Model::morph( Model* target, float dt) { Model* result; if (tempVertices.size() == target->tempVertices.size()) { result = new Model(); result->isLoaded = true; result->copyAllAttributes(target); for (unsigned int i = 0; i < tempVertices.size(); i++) { result->tempVertices.push_back(LERP(tempVertices[i], target->tempVertices[i], dt)); } result->tempUVs = tempUVs; result->tempNormals = tempNormals; result->tempIndices = tempIndices; result->setupVAO(); result->setupVBO(); } return result; } void Model::copyAllAttributes( Model* target ) { texture = target->texture; boundingBox = target->boundingBox; pos = target->pos; rot = target->rot; scale = target->scale; forward = target->forward; up = target->up; strafe = target->strafe; azemuth = target->azemuth; elevation = target->elevation; originOffsetPos = target->originOffsetPos; } void Model::setupVAO() { vertices.clear(); uvs.clear(); normals.clear(); for (unsigned int i = 0; i < tempIndices.size(); i+=3) { vertices.push_back(tempVertices[((tempIndices[i]-1)*3)]); vertices.push_back(tempVertices[((tempIndices[i]-1)*3)+1]); vertices.push_back(tempVertices[((tempIndices[i]-1)*3)+2]); uvs.push_back(tempUVs[((tempIndices[i+1]-1)*2)]); uvs.push_back(-tempUVs[((tempIndices[i+1]-1)*2)+1]); normals.push_back(tempNormals[((tempIndices[i+2]-1)*3)]); normals.push_back(tempNormals[((tempIndices[i+2]-1)*3)+1]); normals.push_back(tempNormals[((tempIndices[i+2]-1)*3)+2]); } } void Model::setupVBO() { vbo->Initialize(vertices.size()/3, true, true); vbo->AddVertices(&vertices[0]); vbo->AddNormals(&normals[0]); vbo->AddTexcoords(&uvs[0]); }
22.408602
118
0.65547
Altelus
9e27eff4653398d4b0f1275a816157112be950ae
2,540
hpp
C++
sm_value_store/include/sm/value_store/VerboseValueStore.hpp
christian-rauch/schweizer_messer
9b8f99f4387e7a8f4105e54b27f22ecee5ea0cd0
[ "BSD-3-Clause" ]
35
2017-12-07T15:13:02.000Z
2021-11-07T19:51:05.000Z
sm_value_store/include/sm/value_store/VerboseValueStore.hpp
christian-rauch/schweizer_messer
9b8f99f4387e7a8f4105e54b27f22ecee5ea0cd0
[ "BSD-3-Clause" ]
48
2015-01-01T21:18:18.000Z
2017-07-30T08:43:05.000Z
sm_value_store/include/sm/value_store/VerboseValueStore.hpp
christian-rauch/schweizer_messer
9b8f99f4387e7a8f4105e54b27f22ecee5ea0cd0
[ "BSD-3-Clause" ]
13
2015-02-03T15:54:40.000Z
2017-10-08T17:10:43.000Z
#ifndef VALUE_STORE_VERBOSEVALUESTORE_HPP_ #define VALUE_STORE_VERBOSEVALUESTORE_HPP_ #include <memory> #include <functional> #include "ValueStore.hpp" namespace sm { namespace value_store { namespace internal { template <typename Base> class VerboseValueStoreT : public Base { public: VerboseValueStoreT(std::shared_ptr<Base> vs, std::function<void(const std::string &)> log) : vs_(vs), log_(log) {} ValueHandle<bool> getBool(const std::string & path, boost::optional<bool> def = boost::optional<bool>()) const override; ValueHandle<int> getInt(const std::string & path, boost::optional<int> def = boost::optional<int>()) const override; ValueHandle<double> getDouble(const std::string & path, boost::optional<double> def = boost::optional<double>()) const override; ValueHandle<std::string> getString(const std::string & path, boost::optional<std::string> def = boost::optional<std::string>()) const override; bool hasKey(const std::string & path) const override; bool isChildSupported() const override; KeyValueStorePair getChild(const std::string & key) const override; std::vector<KeyValueStorePair> getChildren() const override; std::shared_ptr<Base> getUnderlyingValueStore() const { return vs_; } protected: std::shared_ptr<Base> vs_; std::function<void(const std::string &)> log_; private: template <typename T, typename O = bool> T logValue(const char * func, const std::string & path, T && v, O o = false) const; }; extern template class VerboseValueStoreT<ValueStore>; extern template class VerboseValueStoreT<ExtendibleValueStore>; } using VerboseValueStore = internal::VerboseValueStoreT<ValueStore>; class VerboseExtendibleValueStore : public internal::VerboseValueStoreT<ExtendibleValueStore> { public: using internal::VerboseValueStoreT<ExtendibleValueStore>::VerboseValueStoreT; ValueHandle<bool> addBool(const std::string & path, bool initialValue) override; ValueHandle<int> addInt(const std::string & path, int initialValue) override; ValueHandle<double> addDouble(const std::string & path, double initialValue) override; ValueHandle<std::string> addString(const std::string & path, std::string initialValue) override; ExtendibleKeyValueStorePair getExtendibleChild(const std::string & key) const override; std::vector<ExtendibleKeyValueStorePair> getExtendibleChildren() const override; private: template <typename T> T logAddValue(const char * func, const std::string & path, T && v) const; }; } } #endif /* VALUE_STORE_VERBOSEVALUESTORE_HPP_ */
39.076923
145
0.761811
christian-rauch
9e282e044ec6d27e32aa5dcb3ae7b62b9206c2cd
518
cpp
C++
Invocacion.cpp
mikeandino/Lab5-P3-MichaelAndino
142823d50127e926f06cf9bdfa8e0d02c35611b8
[ "MIT" ]
null
null
null
Invocacion.cpp
mikeandino/Lab5-P3-MichaelAndino
142823d50127e926f06cf9bdfa8e0d02c35611b8
[ "MIT" ]
null
null
null
Invocacion.cpp
mikeandino/Lab5-P3-MichaelAndino
142823d50127e926f06cf9bdfa8e0d02c35611b8
[ "MIT" ]
null
null
null
#include "Invocacion.h" Invocacion :: Invocacion(string pNombre,string pNivel,string pNombrem,string pEspecie,string pHabilidad, string pTipo) : Poder(pNombre,pNivel){ nombrem=pNombrem; especie=pEspecie; } string Invocacion::getNombrem(){ return nombrem; } string Invocacion::getEspecie(){ return especie; } string Invocacion::getHabilidad(){ return habilidad; } string Invocacion::getTipo(){ return tipo; } string Invocacion::toString(){ return "Test"; } Invocacion::~Invocacion(){ }
16.1875
143
0.722008
mikeandino
9e28b647d6be0108ec5cf3b748952e7cba7ccf33
1,184
cpp
C++
src/PeerPluginStatus.cpp
JoystreamClassic/joystream-node
2450382bb937abdd959b460791c25f2d8f127168
[ "MIT" ]
null
null
null
src/PeerPluginStatus.cpp
JoystreamClassic/joystream-node
2450382bb937abdd959b460791c25f2d8f127168
[ "MIT" ]
9
2017-11-14T06:05:50.000Z
2018-07-08T18:21:17.000Z
src/PeerPluginStatus.cpp
JoystreamClassic/joystream-node
2450382bb937abdd959b460791c25f2d8f127168
[ "MIT" ]
4
2017-11-14T06:04:17.000Z
2018-08-24T07:39:00.000Z
/** * Copyright (C) JoyStream - All Rights Reserved * Unauthorized copying of this file, via any medium is strictly prohibited * Proprietary and confidential * Written by Bedeho Mender <bedeho.mender@gmail.com>, February 3 2017 */ #include "PeerPluginStatus.hpp" #include "libtorrent-node/utils.hpp" #include "libtorrent-node/endpoint.hpp" #include "libtorrent-node/peer_id.hpp" #include "BEPSupportStatus.hpp" #include "Connection.hpp" namespace joystream { namespace node { namespace peer_plugin_status { NAN_MODULE_INIT(Init) { bep_support_status::Init(target); connection::Init(target); } v8::Local<v8::Object> encode(const extension::status::PeerPlugin & s) { v8::Local<v8::Object> o = Nan::New<v8::Object>(); SET_VAL(o, "pid", libtorrent::node::peer_id::encode(s.peerId)); SET_VAL(o, "endPoint", libtorrent::node::endpoint::encode(s.endPoint)); SET_VAL(o, "peerBEP10SupportStatus", bep_support_status::encode(s.peerBEP10SupportStatus)); SET_VAL(o, "peerBitSwaprBEPSupportStatus", bep_support_status::encode(s.peerBitSwaprBEPSupportStatus)); if(s.connection) SET_VAL(o, "connection", connection::encode(s.connection.get())); return o; } } } }
28.190476
105
0.743243
JoystreamClassic
9e2a2ebc48b598f7e024e3c514d81206030298da
1,046
cpp
C++
Rozi/UchitelskiSustav/main.cpp
slaviborisov/shu.bg
1ed9a65fff1512d18a3e4cde90030abb450f0d9f
[ "Apache-2.0" ]
null
null
null
Rozi/UchitelskiSustav/main.cpp
slaviborisov/shu.bg
1ed9a65fff1512d18a3e4cde90030abb450f0d9f
[ "Apache-2.0" ]
null
null
null
Rozi/UchitelskiSustav/main.cpp
slaviborisov/shu.bg
1ed9a65fff1512d18a3e4cde90030abb450f0d9f
[ "Apache-2.0" ]
null
null
null
#include "uchitelski-sustav.h" #include <iostream> using namespace std; int main() { system("chcp 1251"); CUSustav uchSustav; int c; do { cout <<endl; cout << "0. Изход от програмата"<<endl; cout << "1. Добавяне на нов учител"<<endl; cout << "2. Покажи учител"<<endl; cout << "3. Покажи учителския състав"<<endl; cout << "4. Изтриване на учител"<<endl; cout << "5. Показване всички учители по зададена дисциплина"<<endl; cout << "6. Показване на водената дисциплина на учителя с най-голям стаж"<<endl; cin >> c; switch(c) { case 0: break; case 1: uchSustav.AddUchitel(); break; case 2: uchSustav.PrintUchitel(); break; case 3: uchSustav.PrintUchSustav(); break; case 4: uchSustav.DeleteUchitel(); break; case 5: uchSustav.PrintUchiteliPoDisciplina(); break; case 6: uchSustav.PrintDiscplinaPoStaj(); break; default: cout << "Грешен избор!"<<endl; break; } } while(c); system("pause"); return 0; }
28.27027
85
0.607075
slaviborisov
9e2b0740604cd956f5aeffc304c43e1b9103fe20
18,125
cpp
C++
core/host_api/impl/host_api_impl.cpp
soramitsu/kagome
d66755924477f2818fcae30ba2e65681fce34264
[ "Apache-2.0" ]
110
2019-04-03T13:39:39.000Z
2022-03-09T11:54:42.000Z
core/host_api/impl/host_api_impl.cpp
soramitsu/kagome
d66755924477f2818fcae30ba2e65681fce34264
[ "Apache-2.0" ]
890
2019-03-22T21:33:30.000Z
2022-03-31T14:31:22.000Z
core/host_api/impl/host_api_impl.cpp
soramitsu/kagome
d66755924477f2818fcae30ba2e65681fce34264
[ "Apache-2.0" ]
27
2019-06-25T06:21:47.000Z
2021-11-01T14:12:10.000Z
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #include "host_api/impl/host_api_impl.hpp" #include "crypto/bip39/impl/bip39_provider_impl.hpp" #include "crypto/ed25519/ed25519_provider_impl.hpp" #include "crypto/hasher/hasher_impl.hpp" #include "crypto/pbkdf2/impl/pbkdf2_provider_impl.hpp" #include "crypto/random_generator/boost_generator.hpp" #include "crypto/secp256k1/secp256k1_provider_impl.hpp" #include "crypto/sr25519/sr25519_provider_impl.hpp" #include "host_api/impl/offchain_extension.hpp" #include "runtime/trie_storage_provider.hpp" namespace kagome::host_api { HostApiImpl::HostApiImpl( const OffchainExtensionConfig &offchain_config, std::shared_ptr<const runtime::MemoryProvider> memory_provider, std::shared_ptr<const runtime::CoreApiFactory> core_provider, std::shared_ptr<runtime::TrieStorageProvider> storage_provider, std::shared_ptr<storage::changes_trie::ChangesTracker> tracker, std::shared_ptr<const crypto::Sr25519Provider> sr25519_provider, std::shared_ptr<const crypto::Ed25519Provider> ed25519_provider, std::shared_ptr<const crypto::Secp256k1Provider> secp256k1_provider, std::shared_ptr<const crypto::Hasher> hasher, std::shared_ptr<crypto::CryptoStore> crypto_store, std::shared_ptr<const crypto::Bip39Provider> bip39_provider, std::shared_ptr<offchain::OffchainPersistentStorage> offchain_persistent_storage) : memory_provider_([&] { BOOST_ASSERT(memory_provider); return std::move(memory_provider); }()), storage_provider_([&] { BOOST_ASSERT(storage_provider); return std::move(storage_provider); }()), crypto_ext_(memory_provider_, std::move(sr25519_provider), std::move(ed25519_provider), std::move(secp256k1_provider), hasher, std::move(crypto_store), std::move(bip39_provider)), io_ext_(memory_provider_), memory_ext_(memory_provider_), misc_ext_{DEFAULT_CHAIN_ID, hasher, memory_provider_, std::move(core_provider)}, storage_ext_(storage_provider_, memory_provider_, std::move(tracker)), child_storage_ext_(storage_provider_, memory_provider_), offchain_ext_(offchain_config, memory_provider_, std::move(offchain_persistent_storage)) {} void HostApiImpl::reset() { storage_ext_.reset(); } runtime::WasmSpan HostApiImpl::ext_storage_read_version_1( runtime::WasmSpan key, runtime::WasmSpan value_out, runtime::WasmOffset offset) { return storage_ext_.ext_storage_read_version_1(key, value_out, offset); } runtime::WasmSpan HostApiImpl::ext_storage_next_key_version_1( runtime::WasmSpan key) const { return storage_ext_.ext_storage_next_key_version_1(key); } void HostApiImpl::ext_storage_append_version_1( runtime::WasmSpan key, runtime::WasmSpan value) const { return storage_ext_.ext_storage_append_version_1(key, value); } void HostApiImpl::ext_storage_set_version_1(runtime::WasmSpan key, runtime::WasmSpan value) { return storage_ext_.ext_storage_set_version_1(key, value); } runtime::WasmSpan HostApiImpl::ext_storage_get_version_1( runtime::WasmSpan key) { return storage_ext_.ext_storage_get_version_1(key); } void HostApiImpl::ext_storage_clear_version_1(runtime::WasmSpan key_data) { return storage_ext_.ext_storage_clear_version_1(key_data); } runtime::WasmSize HostApiImpl::ext_storage_exists_version_1( runtime::WasmSpan key_data) const { return storage_ext_.ext_storage_exists_version_1(key_data); } void HostApiImpl::ext_storage_clear_prefix_version_1( runtime::WasmSpan prefix) { return storage_ext_.ext_storage_clear_prefix_version_1(prefix); } runtime::WasmSpan HostApiImpl::ext_storage_clear_prefix_version_2( runtime::WasmSpan prefix, runtime::WasmSpan limit) { return storage_ext_.ext_storage_clear_prefix_version_2(prefix, limit); } runtime::WasmSpan HostApiImpl::ext_storage_root_version_1() { return storage_ext_.ext_storage_root_version_1(); } runtime::WasmSpan HostApiImpl::ext_storage_changes_root_version_1( runtime::WasmSpan parent_hash) { return storage_ext_.ext_storage_changes_root_version_1(parent_hash); } void HostApiImpl::ext_storage_start_transaction_version_1() { return storage_ext_.ext_storage_start_transaction_version_1(); } void HostApiImpl::ext_storage_rollback_transaction_version_1() { return storage_ext_.ext_storage_rollback_transaction_version_1(); } void HostApiImpl::ext_storage_commit_transaction_version_1() { return storage_ext_.ext_storage_commit_transaction_version_1(); } runtime::WasmPointer HostApiImpl::ext_trie_blake2_256_root_version_1( runtime::WasmSpan values_data) { return storage_ext_.ext_trie_blake2_256_root_version_1(values_data); } runtime::WasmPointer HostApiImpl::ext_trie_blake2_256_ordered_root_version_1( runtime::WasmSpan values_data) { return storage_ext_.ext_trie_blake2_256_ordered_root_version_1(values_data); } // ------------------------Memory extensions v1------------------------- runtime::WasmPointer HostApiImpl::ext_allocator_malloc_version_1( runtime::WasmSize size) { return memory_ext_.ext_allocator_malloc_version_1(size); } void HostApiImpl::ext_allocator_free_version_1(runtime::WasmPointer ptr) { return memory_ext_.ext_allocator_free_version_1(ptr); } void HostApiImpl::ext_logging_log_version_1(runtime::WasmEnum level, runtime::WasmSpan target, runtime::WasmSpan message) { io_ext_.ext_logging_log_version_1(level, target, message); } runtime::WasmEnum HostApiImpl::ext_logging_max_level_version_1() { return io_ext_.ext_logging_max_level_version_1(); } /// Crypto extensions v1 void HostApiImpl::ext_crypto_start_batch_verify_version_1() { return crypto_ext_.ext_crypto_start_batch_verify_version_1(); } int32_t HostApiImpl::ext_crypto_finish_batch_verify_version_1() { return crypto_ext_.ext_crypto_finish_batch_verify_version_1(); } runtime::WasmSpan HostApiImpl::ext_crypto_ed25519_public_keys_version_1( runtime::WasmSize key_type) { return crypto_ext_.ext_crypto_ed25519_public_keys_version_1(key_type); } runtime::WasmPointer HostApiImpl::ext_crypto_ed25519_generate_version_1( runtime::WasmSize key_type, runtime::WasmSpan seed) { return crypto_ext_.ext_crypto_ed25519_generate_version_1(key_type, seed); } runtime::WasmSpan HostApiImpl::ext_crypto_ed25519_sign_version_1( runtime::WasmSize key_type, runtime::WasmPointer key, runtime::WasmSpan msg_data) { return crypto_ext_.ext_crypto_ed25519_sign_version_1( key_type, key, msg_data); } runtime::WasmSize HostApiImpl::ext_crypto_ed25519_verify_version_1( runtime::WasmPointer sig_data, runtime::WasmSpan msg, runtime::WasmPointer pubkey_data) { return crypto_ext_.ext_crypto_ed25519_verify_version_1( sig_data, msg, pubkey_data); } runtime::WasmSpan HostApiImpl::ext_crypto_sr25519_public_keys_version_1( runtime::WasmSize key_type) { return crypto_ext_.ext_crypto_sr25519_public_keys_version_1(key_type); } runtime::WasmPointer HostApiImpl::ext_crypto_sr25519_generate_version_1( runtime::WasmSize key_type, runtime::WasmSpan seed) { return crypto_ext_.ext_crypto_sr25519_generate_version_1(key_type, seed); } runtime::WasmSpan HostApiImpl::ext_crypto_sr25519_sign_version_1( runtime::WasmSize key_type, runtime::WasmPointer key, runtime::WasmSpan msg_data) { return crypto_ext_.ext_crypto_sr25519_sign_version_1( key_type, key, msg_data); } int32_t HostApiImpl::ext_crypto_sr25519_verify_version_1( runtime::WasmPointer sig_data, runtime::WasmSpan msg, runtime::WasmPointer pubkey_data) { return crypto_ext_.ext_crypto_sr25519_verify_version_1( sig_data, msg, pubkey_data); } int32_t HostApiImpl::ext_crypto_sr25519_verify_version_2( runtime::WasmPointer sig_data, runtime::WasmSpan msg, runtime::WasmPointer pubkey_data) { return crypto_ext_.ext_crypto_sr25519_verify_version_2( sig_data, msg, pubkey_data); } // ------------------------- Hashing extension/crypto --------------- runtime::WasmPointer HostApiImpl::ext_hashing_keccak_256_version_1( runtime::WasmSpan data) { return crypto_ext_.ext_hashing_keccak_256_version_1(data); } runtime::WasmPointer HostApiImpl::ext_hashing_sha2_256_version_1( runtime::WasmSpan data) { return crypto_ext_.ext_hashing_sha2_256_version_1(data); } runtime::WasmPointer HostApiImpl::ext_hashing_blake2_128_version_1( runtime::WasmSpan data) { return crypto_ext_.ext_hashing_blake2_128_version_1(data); } runtime::WasmPointer HostApiImpl::ext_hashing_blake2_256_version_1( runtime::WasmSpan data) { return crypto_ext_.ext_hashing_blake2_256_version_1(data); } runtime::WasmPointer HostApiImpl::ext_hashing_twox_64_version_1( runtime::WasmSpan data) { return crypto_ext_.ext_hashing_twox_64_version_1(data); } runtime::WasmPointer HostApiImpl::ext_hashing_twox_128_version_1( runtime::WasmSpan data) { return crypto_ext_.ext_hashing_twox_128_version_1(data); } runtime::WasmPointer HostApiImpl::ext_hashing_twox_256_version_1( runtime::WasmSpan data) { return crypto_ext_.ext_hashing_twox_256_version_1(data); } runtime::WasmSpan HostApiImpl::ext_misc_runtime_version_version_1( runtime::WasmSpan data) const { return misc_ext_.ext_misc_runtime_version_version_1(data); } void HostApiImpl::ext_misc_print_hex_version_1(runtime::WasmSpan data) const { return misc_ext_.ext_misc_print_hex_version_1(data); } void HostApiImpl::ext_misc_print_num_version_1(uint64_t value) const { return misc_ext_.ext_misc_print_num_version_1(value); } void HostApiImpl::ext_misc_print_utf8_version_1( runtime::WasmSpan data) const { return misc_ext_.ext_misc_print_utf8_version_1(data); } runtime::WasmSpan HostApiImpl::ext_crypto_secp256k1_ecdsa_recover_version_1( runtime::WasmPointer sig, runtime::WasmPointer msg) { return crypto_ext_.ext_crypto_secp256k1_ecdsa_recover_version_1(sig, msg); } runtime::WasmSpan HostApiImpl::ext_crypto_secp256k1_ecdsa_recover_version_2( runtime::WasmPointer sig, runtime::WasmPointer msg) { return crypto_ext_.ext_crypto_secp256k1_ecdsa_recover_version_1(sig, msg); } runtime::WasmSpan HostApiImpl::ext_crypto_secp256k1_ecdsa_recover_compressed_version_1( runtime::WasmPointer sig, runtime::WasmPointer msg) { return crypto_ext_.ext_crypto_secp256k1_ecdsa_recover_compressed_version_1( sig, msg); } runtime::WasmSpan HostApiImpl::ext_crypto_secp256k1_ecdsa_recover_compressed_version_2( runtime::WasmPointer sig, runtime::WasmPointer msg) { return crypto_ext_.ext_crypto_secp256k1_ecdsa_recover_compressed_version_1( sig, msg); } // --------------------------- Offchain extension ---------------------------- runtime::WasmI8 HostApiImpl::ext_offchain_is_validator_version_1() { return offchain_ext_.ext_offchain_is_validator_version_1(); } runtime::WasmSpan HostApiImpl::ext_offchain_submit_transaction_version_1( runtime::WasmSpan data) { return offchain_ext_.ext_offchain_submit_transaction_version_1(data); } runtime::WasmSpan HostApiImpl::ext_offchain_network_state_version_1() { return offchain_ext_.ext_offchain_network_state_version_1(); } runtime::WasmU64 HostApiImpl::ext_offchain_timestamp_version_1() { return offchain_ext_.ext_offchain_timestamp_version_1(); } void HostApiImpl::ext_offchain_sleep_until_version_1( runtime::WasmU64 deadline) { return offchain_ext_.ext_offchain_sleep_until_version_1(deadline); } runtime::WasmPointer HostApiImpl::ext_offchain_random_seed_version_1() { return offchain_ext_.ext_offchain_random_seed_version_1(); } void HostApiImpl::ext_offchain_local_storage_set_version_1( runtime::WasmI32 kind, runtime::WasmSpan key, runtime::WasmSpan value) { return offchain_ext_.ext_offchain_local_storage_set_version_1( kind, key, value); } void HostApiImpl::ext_offchain_local_storage_clear_version_1( runtime::WasmI32 kind, runtime::WasmSpan key) { return offchain_ext_.ext_offchain_local_storage_clear_version_1(kind, key); } runtime::WasmI8 HostApiImpl::ext_offchain_local_storage_compare_and_set_version_1( runtime::WasmI32 kind, runtime::WasmSpan key, runtime::WasmSpan expected, runtime::WasmSpan value) { return offchain_ext_.ext_offchain_local_storage_compare_and_set_version_1( kind, key, expected, value); } runtime::WasmSpan HostApiImpl::ext_offchain_local_storage_get_version_1( runtime::WasmI32 kind, runtime::WasmSpan key) { return offchain_ext_.ext_offchain_local_storage_get_version_1(kind, key); } runtime::WasmSpan HostApiImpl::ext_offchain_http_request_start_version_1( runtime::WasmSpan method, runtime::WasmSpan uri, runtime::WasmSpan meta) { return offchain_ext_.ext_offchain_http_request_start_version_1( method, uri, meta); } runtime::WasmSpan HostApiImpl::ext_offchain_http_request_add_header_version_1( runtime::WasmI32 request_id, runtime::WasmSpan name, runtime::WasmSpan value) { return offchain_ext_.ext_offchain_http_request_add_header_version_1( request_id, name, value); } runtime::WasmSpan HostApiImpl::ext_offchain_http_request_write_body_version_1( runtime::WasmI32 request_id, runtime::WasmSpan chunk, runtime::WasmSpan deadline) { return offchain_ext_.ext_offchain_http_request_write_body_version_1( request_id, chunk, deadline); } runtime::WasmSpan HostApiImpl::ext_offchain_http_response_wait_version_1( runtime::WasmSpan ids, runtime::WasmSpan deadline) { return offchain_ext_.ext_offchain_http_response_wait_version_1(ids, deadline); } runtime::WasmSpan HostApiImpl::ext_offchain_http_response_headers_version_1( runtime::WasmI32 request_id) { return offchain_ext_.ext_offchain_http_response_headers_version_1( request_id); } runtime::WasmSpan HostApiImpl::ext_offchain_http_response_read_body_version_1( runtime::WasmI32 request_id, runtime::WasmSpan buffer, runtime::WasmSpan deadline) { return offchain_ext_.ext_offchain_http_response_read_body_version_1( request_id, buffer, deadline); } void HostApiImpl::ext_offchain_set_authorized_nodes_version_1( runtime::WasmSpan nodes, runtime::WasmI32 authorized_only) { return offchain_ext_.ext_offchain_set_authorized_nodes_version_1( nodes, authorized_only); } void HostApiImpl::ext_offchain_index_set_version_1(runtime::WasmSpan key, runtime::WasmSpan value) { return offchain_ext_.ext_offchain_index_set_version_1(key, value); } void HostApiImpl::ext_offchain_index_clear_version_1(runtime::WasmSpan key) { return offchain_ext_.ext_offchain_index_clear_version_1(key); } void HostApiImpl::ext_default_child_storage_set_version_1( runtime::WasmSpan child_storage_key, runtime::WasmSpan key, runtime::WasmSpan value) { child_storage_ext_.ext_default_child_storage_set_version_1( child_storage_key, key, value); } runtime::WasmSpan HostApiImpl::ext_default_child_storage_get_version_1( runtime::WasmSpan child_storage_key, runtime::WasmSpan key) const { return child_storage_ext_.ext_default_child_storage_get_version_1( child_storage_key, key); } void HostApiImpl::ext_default_child_storage_clear_version_1( runtime::WasmSpan child_storage_key, runtime::WasmSpan key) { child_storage_ext_.ext_default_child_storage_clear_version_1( child_storage_key, key); } runtime::WasmSpan HostApiImpl::ext_default_child_storage_next_key_version_1( runtime::WasmSpan child_storage_key, runtime::WasmSpan key) const { return child_storage_ext_.ext_default_child_storage_next_key_version_1( child_storage_key, key); } runtime::WasmSpan HostApiImpl::ext_default_child_storage_root_version_1( runtime::WasmSpan child_storage_key) const { return child_storage_ext_.ext_default_child_storage_root_version_1( child_storage_key); } void HostApiImpl::ext_default_child_storage_clear_prefix_version_1( runtime::WasmSpan child_storage_key, runtime::WasmSpan prefix) { return child_storage_ext_.ext_default_child_storage_clear_prefix_version_1( child_storage_key, prefix); } runtime::WasmSpan HostApiImpl::ext_default_child_storage_read_version_1( runtime::WasmSpan child_storage_key, runtime::WasmSpan key, runtime::WasmSpan value_out, runtime::WasmOffset offset) const { return child_storage_ext_.ext_default_child_storage_read_version_1( child_storage_key, key, value_out, offset); } uint32_t HostApiImpl::ext_default_child_storage_exists_version_1( runtime::WasmSpan child_storage_key, runtime::WasmSpan key) const { return child_storage_ext_.ext_default_child_storage_exists_version_1( child_storage_key, key); } void HostApiImpl::ext_default_child_storage_storage_kill_version_1( runtime::WasmSpan child_storage_key) { return child_storage_ext_.ext_default_child_storage_storage_kill_version_1( child_storage_key); } } // namespace kagome::host_api
37.603734
80
0.749297
soramitsu
9e2f7022a5c361fccb22e9da1eef03fc9bd9f980
570,872
cpp
C++
src/server/game/Entities/Unit/Unit.cpp
Zone-Emu/ZoneEmuCataclysm
6277efff6cb5adfe8b7a718bf376e81609fa9a6c
[ "OpenSSL" ]
1
2019-03-23T19:32:57.000Z
2019-03-23T19:32:57.000Z
src/server/game/Entities/Unit/Unit.cpp
Zone-Emu/ZoneEmuCataclysm
6277efff6cb5adfe8b7a718bf376e81609fa9a6c
[ "OpenSSL" ]
null
null
null
src/server/game/Entities/Unit/Unit.cpp
Zone-Emu/ZoneEmuCataclysm
6277efff6cb5adfe8b7a718bf376e81609fa9a6c
[ "OpenSSL" ]
null
null
null
/* * Copyright (C) 2005 - 2012 MaNGOS <http://www.getmangos.com/> * * Copyright (C) 2008 - 2012 Trinity <http://www.trinitycore.org/> * * Copyright (C) 2010 - 2012 ArkCORE <http://www.arkania.net/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "gamePCH.h" #include "Common.h" #include "CreatureAIImpl.h" #include "Log.h" #include "Opcodes.h" #include "WorldPacket.h" #include "WorldSession.h" #include "World.h" #include "ObjectMgr.h" #include "SpellMgr.h" #include "Unit.h" #include "QuestDef.h" #include "Player.h" #include "Creature.h" #include "Spell.h" #include "Group.h" #include "SpellAuras.h" #include "SpellAuraEffects.h" #include "MapManager.h" #include "ObjectAccessor.h" #include "CreatureAI.h" #include "Formulas.h" #include "Pet.h" #include "Util.h" #include "Totem.h" #include "Battleground.h" #include "OutdoorPvP.h" #include "InstanceSaveMgr.h" #include "GridNotifiersImpl.h" #include "CellImpl.h" #include "Path.h" #include "CreatureGroups.h" #include "PetAI.h" #include "PassiveAI.h" #include "Traveller.h" #include "TemporarySummon.h" #include "Vehicle.h" #include "Transport.h" #include <math.h> float baseMoveSpeed [MAX_MOVE_TYPE] = { 2.5f, // MOVE_WALK 7.0f, // MOVE_RUN 2.5f, // MOVE_RUN_BACK 4.722222f, // MOVE_SWIM 4.5f, // MOVE_SWIM_BACK 3.141594f, // MOVE_TURN_RATE 7.0f, // MOVE_FLIGHT 4.5f, // MOVE_FLIGHT_BACK 3.14f // MOVE_PITCH_RATE }; float playerBaseMoveSpeed [MAX_MOVE_TYPE] = { 2.5f, // MOVE_WALK 7.0f, // MOVE_RUN 2.5f, // MOVE_RUN_BACK 4.722222f, // MOVE_SWIM 4.5f, // MOVE_SWIM_BACK 3.141594f, // MOVE_TURN_RATE 7.0f, // MOVE_FLIGHT 4.5f, // MOVE_FLIGHT_BACK 3.14f // MOVE_PITCH_RATE }; // Used for prepare can/can`t triggr aura static bool InitTriggerAuraData(); // Define can trigger auras static bool isTriggerAura [TOTAL_AURAS]; // Define can`t trigger auras (need for disable second trigger) static bool isNonTriggerAura [TOTAL_AURAS]; // Triggered always, even from triggered spells static bool isAlwaysTriggeredAura [TOTAL_AURAS]; // Prepare lists static bool procPrepared = InitTriggerAuraData(); // 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 Unit::Unit() : WorldObject(), m_movedPlayer(NULL), IsAIEnabled(false), NeedChangeAI( false), m_ControlledByPlayer(false), i_AI(NULL), i_disabledAI( NULL), m_procDeep(0), m_removedAurasCount(0), i_motionMaster( this), m_ThreatManager(this), m_vehicle(NULL), m_vehicleKit( NULL), m_unitTypeMask(UNIT_MASK_NONE), m_HostileRefManager( this), m_lastSanctuaryTime(0) { #ifdef _MSC_VER #pragma warning(default:4355) #endif m_objectType |= TYPEMASK_UNIT; m_objectTypeId = TYPEID_UNIT; m_updateFlag = (UPDATEFLAG_LIVING | UPDATEFLAG_HAS_POSITION); DmgandHealDoneTimer = 0; m_attackTimer [BASE_ATTACK] = 0; m_attackTimer [OFF_ATTACK] = 0; m_attackTimer [RANGED_ATTACK] = 0; m_modAttackSpeedPct [BASE_ATTACK] = 1.0f; m_modAttackSpeedPct [OFF_ATTACK] = 1.0f; m_modAttackSpeedPct [RANGED_ATTACK] = 1.0f; m_extraAttacks = 0; m_canDualWield = false; m_rootTimes = 0; m_state = 0; m_deathState = ALIVE; for (uint8 i = 0; i < CURRENT_MAX_SPELL; ++i) m_currentSpells [i] = NULL; m_addDmgOnce = 0; for (uint8 i = 0; i < MAX_SUMMON_SLOT; ++i) m_SummonSlot [i] = 0; m_ObjectSlot [0] = m_ObjectSlot [1] = m_ObjectSlot [2] = m_ObjectSlot [3] = 0; m_auraUpdateIterator = m_ownedAuras.end(); m_interruptMask = 0; m_transform = 0; m_canModifyStats = false; for (uint8 i = 0; i < MAX_SPELL_IMMUNITY; ++i) m_spellImmune [i].clear(); for (uint8 i = 0; i < UNIT_MOD_END; ++i) { m_auraModifiersGroup [i] [BASE_VALUE] = 0.0f; m_auraModifiersGroup [i] [BASE_PCT] = 1.0f; m_auraModifiersGroup [i] [TOTAL_VALUE] = 0.0f; m_auraModifiersGroup [i] [TOTAL_PCT] = 1.0f; } // implement 50% base damage from offhand m_auraModifiersGroup [UNIT_MOD_DAMAGE_OFFHAND] [TOTAL_PCT] = 0.5f; for (uint8 i = 0; i < MAX_ATTACK; ++i) { m_weaponDamage [i] [MINDAMAGE] = BASE_MINDAMAGE; m_weaponDamage [i] [MAXDAMAGE] = BASE_MAXDAMAGE; } for (uint8 i = 0; i < MAX_STATS; ++i) m_createStats [i] = 0.0f; m_attacking = NULL; m_modMeleeHitChance = 0.0f; m_modRangedHitChance = 0.0f; m_modSpellHitChance = 0.0f; m_baseSpellCritChance = 5; m_CombatTimer = 0; m_lastManaUse = 0; //m_victimThreat = 0.0f; for (uint8 i = 0; i < MAX_SPELL_SCHOOL; ++i) m_threatModifier [i] = 1.0f; m_isSorted = true; for (uint8 i = 0; i < MAX_MOVE_TYPE; ++i) m_speed_rate [i] = 1.0f; m_charmInfo = NULL; //m_unit_movement_flags = 0; m_reducedThreatPercent = 0; m_misdirectionTargetGUID = 0; // remove aurastates allowing special moves for (uint8 i = 0; i < MAX_REACTIVE; ++i) m_reactiveTimer [i] = 0; m_cleanupDone = false; m_duringRemoveFromWorld = false; m_serverSideVisibility.SetValue(SERVERSIDE_VISIBILITY_GHOST, GHOST_VISIBILITY_ALIVE); for (uint32 i = 0; i < 120; ++i) m_damage_done [i] = 0; for (uint32 i = 0; i < 120; ++i) m_heal_done [i] = 0; for (uint32 i = 0; i < 120; ++i) m_damage_taken [i] = 0; m_AbsorbHeal = 0.0f; } Unit::~Unit() { // set current spells as deletable for (uint8 i = 0; i < CURRENT_MAX_SPELL; ++i) { if (m_currentSpells [i]) { m_currentSpells [i]->SetReferencedFromCurrent(false); m_currentSpells [i] = NULL; } } _DeleteRemovedAuras(); delete m_charmInfo; delete m_vehicleKit; ASSERT(!m_duringRemoveFromWorld); ASSERT(!m_attacking); ASSERT(m_attackers.empty()); ASSERT(m_sharedVision.empty()); ASSERT(m_Controlled.empty()); ASSERT(m_appliedAuras.empty()); ASSERT(m_ownedAuras.empty()); ASSERT(m_removedAuras.empty()); ASSERT(m_gameObj.empty()); ASSERT(m_dynObj.empty()); } void Unit::Update(uint32 p_time) { // WARNING! Order of execution here is important, do not change. // Spells must be processed with event system BEFORE they go to _UpdateSpells. // Or else we may have some SPELL_STATE_FINISHED spells stalled in pointers, that is bad. m_Events.Update(p_time); if (!IsInWorld()) return; // This is required for GetHealingDoneInPastSecs(), GetDamageDoneInPastSecs() and GetDamageTakenInPastSecs()! DmgandHealDoneTimer -= p_time; if (DmgandHealDoneTimer <= 0) { for (uint32 i = 119; i > 0; i--) { m_damage_done [i] = m_damage_done [i - 1]; } m_damage_done [0] = 0; for (uint32 i = 119; i > 0; i--) { m_heal_done [i] = m_heal_done [i - 1]; } m_heal_done [0] = 0; for (uint32 i = 119; i > 0; i--) { m_damage_taken [i] = m_damage_taken [i - 1]; } m_damage_taken [0] = 0; DmgandHealDoneTimer = 1000; } _UpdateSpells(p_time); // If this is set during update SetCantProc(false) call is missing somewhere in the code // Having this would prevent spells from being proced, so let's crash ASSERT(!m_procDeep); if (CanHaveThreatList() && getThreatManager().isNeedUpdateToClient(p_time)) SendThreatListUpdate(); // update combat timer only for players and pets (only pets with PetAI) if (isInCombat() && (GetTypeId() == TYPEID_PLAYER || (ToCreature()->isPet() && IsControlledByPlayer()))) { // Check UNIT_STAT_MELEE_ATTACKING or UNIT_STAT_CHASE (without UNIT_STAT_FOLLOW in this case) so pets can reach far away // targets without stopping half way there and running off. // These flags are reset after target dies or another command is given. if (m_HostileRefManager.isEmpty()) { // m_CombatTimer set at aura start and it will be freeze until aura removing if (m_CombatTimer <= p_time) ClearInCombat(); else m_CombatTimer -= p_time; } } //not implemented before 3.0.2 //if (!HasUnitState(UNIT_STAT_CASTING)) { if (uint32 base_att = getAttackTimer(BASE_ATTACK)) setAttackTimer( BASE_ATTACK, (p_time >= base_att ? 0 : base_att - p_time)); if (uint32 ranged_att = getAttackTimer(RANGED_ATTACK)) setAttackTimer( RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time)); if (uint32 off_att = getAttackTimer(OFF_ATTACK)) setAttackTimer( OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time)); } // update abilities available only for fraction of time UpdateReactives(p_time); if (isAlive()) { ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, HealthBelowPct(20)); ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, HealthBelowPct(35)); ModifyAuraState(AURA_STATE_HEALTH_ABOVE_75_PERCENT, HealthAbovePct(75)); } i_motionMaster.UpdateMotion(p_time); } bool Unit::haveOffhandWeapon() const { if (GetTypeId() == TYPEID_PLAYER) return this->ToPlayer()->GetWeaponForAttack( OFF_ATTACK, true); else return m_canDualWield; } void Unit::SendMonsterMoveWithSpeedToCurrentDestination(Player* player) { float x, y, z; if (GetMotionMaster()->GetDestination(x, y, z)) SendMonsterMoveWithSpeed(x, y, z, 0, player); } void Unit::SendMonsterMoveWithSpeed(float x, float y, float z, uint32 transitTime, Player* player) { if (!transitTime) { if (GetTypeId() == TYPEID_PLAYER) { Traveller <Player> traveller(*(Player*) this); transitTime = traveller.GetTotalTrevelTimeTo(x, y, z); } else { Traveller <Creature> traveller(*this->ToCreature()); transitTime = traveller.GetTotalTrevelTimeTo(x, y, z); } } //float orientation = (float)atan2((double)dy, (double)dx); SendMonsterMove(x, y, z, transitTime, player); } void Unit::SetFacing(float ori, WorldObject* obj) { SetOrientation(obj ? GetAngle(obj) : ori); WorldPacket data( SMSG_MONSTER_MOVE, (1 + 12 + 4 + 1 + (obj ? 8 : 4) + 4 + 4 + 4 + 12 + GetPackGUID().size())); data.append(GetPackGUID()); data << uint8(0); //unk data << GetPositionX() << GetPositionY() << GetPositionZ(); data << getMSTime(); if (obj) { data << uint8(SPLINETYPE_FACING_TARGET); data << uint64(obj->GetGUID()); } else { data << uint8(SPLINETYPE_FACING_ANGLE); data << ori; } data << uint32(SPLINEFLAG_NONE); data << uint32(0); //move time 0 data << uint32(1); //one point data << GetPositionX() << GetPositionY() << GetPositionZ(); SendMessageToSet(&data, true); } void Unit::SendMonsterStop(bool on_death) { WorldPacket data(SMSG_MONSTER_MOVE, (17 + GetPackGUID().size())); data.append(GetPackGUID()); data << uint8(0); // new in 3.1 data << GetPositionX() << GetPositionY() << GetPositionZ(); data << getMSTime(); if (on_death == true) { data << uint8(0); data << uint32( (GetUnitMovementFlags() & MOVEMENTFLAG_LEVITATING) ? SPLINEFLAG_FLYING : SPLINEFLAG_WALKING); data << uint32(0); // Time in between points data << uint32(1); // 1 single waypoint data << GetPositionX() << GetPositionY() << GetPositionZ(); } else data << uint8(1); SendMessageToSet(&data, true); ClearUnitState(UNIT_STAT_MOVE); } void Unit::SendMonsterMove(float NewPosX, float NewPosY, float NewPosZ, uint32 Time, Player* player) { WorldPacket data(SMSG_MONSTER_MOVE, 1 + 12 + 4 + 1 + 4 + 4 + 4 + 12 + GetPackGUID().size()); data.append(GetPackGUID()); data << uint8(0); // new in 3.1 data << GetPositionX() << GetPositionY() << GetPositionZ(); data << getMSTime(); data << uint8(0); data << uint32( (GetUnitMovementFlags() & MOVEMENTFLAG_LEVITATING) ? SPLINEFLAG_FLYING : SPLINEFLAG_WALKING); data << Time; // Time in between points data << uint32(1); // 1 single waypoint data << NewPosX << NewPosY << NewPosZ; // the single waypoint Point B if (player) player->GetSession()->SendPacket(&data); else SendMessageToSet(&data, true); AddUnitState(UNIT_STAT_MOVE); } void Unit::SendMonsterMove(float NewPosX, float NewPosY, float NewPosZ, uint32 MoveFlags, uint32 time, float speedZ, Player *player) { WorldPacket data(SMSG_MONSTER_MOVE, 12 + 4 + 1 + 4 + 4 + 4 + 12 + GetPackGUID().size()); data.append(GetPackGUID()); data << uint8(0); // new in 3.1 data << GetPositionX() << GetPositionY() << GetPositionZ(); data << getMSTime(); data << uint8(0); data << MoveFlags; if (MoveFlags & SPLINEFLAG_TRAJECTORY) { data << time; data << speedZ; data << (uint32) 0; // walk time after jump } else data << time; data << uint32(1); // 1 single waypoint data << NewPosX << NewPosY << NewPosZ; // the single waypoint Point B if (player) player->GetSession()->SendPacket(&data); else SendMessageToSet(&data, true); } void Unit::SendMonsterMove(MonsterMoveData const& moveData, Player* player) { WorldPacket data(SMSG_MONSTER_MOVE, GetPackGUID().size() + 1 + 12 + 4 + 1 + 4 + 8 + 4 + 4 + 12); data.append(GetPackGUID()); data << uint8(0); // new in 3.1 data << GetPositionX() << GetPositionY() << GetPositionZ(); data << getMSTime(); data << uint8(0); data << moveData.SplineFlag; if (moveData.SplineFlag & SPLINEFLAG_ANIMATIONTIER) { data << uint8(moveData.AnimationState); data << uint32(0); } data << moveData.Time; if (moveData.SplineFlag & SPLINEFLAG_TRAJECTORY) { data << moveData.SpeedZ; data << uint32(0); // walk time after jump } data << uint32(1); // waypoint count data << moveData.DestLocation.GetPositionX(); data << moveData.DestLocation.GetPositionY(); data << moveData.DestLocation.GetPositionZ(); if (player) player->GetSession()->SendPacket(&data); else SendMessageToSet(&data, true); } void Unit::SendMonsterMoveTransport(Unit *vehicleOwner) { // TODO: Turn into BuildMonsterMoveTransport packet and allow certain variables (for npc movement aboard vehicles) WorldPacket data(SMSG_MONSTER_MOVE_TRANSPORT, GetPackGUID().size() + vehicleOwner->GetPackGUID().size() + 47); data.append(GetPackGUID()); data.append(vehicleOwner->GetPackGUID()); data << int8(GetTransSeat()); data << uint8(0); // unk boolean data << GetPositionX() - vehicleOwner->GetPositionX(); data << GetPositionY() - vehicleOwner->GetPositionY(); data << GetPositionZ() - vehicleOwner->GetPositionZ(); data << uint32(getMSTime()); // should be an increasing constant that indicates movement packet count data << uint8(SPLINETYPE_FACING_ANGLE); data << GetOrientation(); // facing angle? data << uint32(SPLINEFLAG_TRANSPORT); data << uint32(GetTransTime()); // move time data << uint32(1); // amount of waypoints data << GetTransOffsetX(); data << GetTransOffsetY(); data << GetTransOffsetZ(); SendMessageToSet(&data, true); } void Unit::resetAttackTimer(WeaponAttackType type) { m_attackTimer [type] = uint32( GetAttackTime(type) * m_modAttackSpeedPct [type]); } bool Unit::IsWithinCombatRange(const Unit *obj, float dist2compare) const { if (!obj || !IsInMap(obj)) return false; float dx = GetPositionX() - obj->GetPositionX(); float dy = GetPositionY() - obj->GetPositionY(); float dz = GetPositionZ() - obj->GetPositionZ(); float distsq = dx * dx + dy * dy + dz * dz; float sizefactor = GetCombatReach() + obj->GetCombatReach(); float maxdist = dist2compare + sizefactor; return distsq < maxdist * maxdist; } bool Unit::IsWithinMeleeRange(const Unit *obj, float dist) const { if (!obj || !IsInMap(obj)) return false; float dx = GetPositionX() - obj->GetPositionX(); float dy = GetPositionY() - obj->GetPositionY(); float dz = GetPositionZ() - obj->GetPositionZ(); float distsq = dx * dx + dy * dy + dz * dz; float sizefactor = GetMeleeReach() + obj->GetMeleeReach(); float maxdist = dist + sizefactor; return distsq < maxdist * maxdist; } void Unit::GetRandomContactPoint(const Unit* obj, float &x, float &y, float &z, float distance2dMin, float distance2dMax) const { float combat_reach = GetCombatReach(); if (combat_reach < 0.1) // sometimes bugged for players { //sLog->outError("Unit %u (Type: %u) has invalid combat_reach %f", GetGUIDLow(), GetTypeId(), combat_reach); //if (GetTypeId() == TYPEID_UNIT) // sLog->outError("Creature entry %u has invalid combat_reach", this->ToCreature()->GetEntry()); combat_reach = DEFAULT_COMBAT_REACH; } uint32 attacker_number = getAttackers().size(); if (attacker_number > 0) --attacker_number; GetNearPoint( obj, x, y, z, obj->GetCombatReach(), distance2dMin + (distance2dMax - distance2dMin) * (float) rand_norm(), GetAngle(obj) + (attacker_number ? (static_cast <float>(M_PI / 2) - static_cast <float>(M_PI) * (float) rand_norm()) * float(attacker_number) / combat_reach * 0.3f : 0)); } void Unit::UpdateInterruptMask() { m_interruptMask = 0; for (AuraApplicationList::const_iterator i = m_interruptableAuras.begin(); i != m_interruptableAuras.end(); ++i) m_interruptMask |= (*i)->GetBase()->GetSpellProto()->AuraInterruptFlags; if (Spell* spell = m_currentSpells[CURRENT_CHANNELED_SPELL]) if (spell->getState() == SPELL_STATE_CASTING) m_interruptMask |= spell->m_spellInfo->ChannelInterruptFlags; } bool Unit::HasAuraTypeWithFamilyFlags(AuraType auraType, uint32 familyName, uint32 familyFlags) const { if (!HasAuraType(auraType)) return false; AuraEffectList const &auras = GetAuraEffectsByType(auraType); for (AuraEffectList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr) if (SpellEntry const *iterSpellProto = (*itr)->GetSpellProto()) if (iterSpellProto->SpellFamilyName == familyName && iterSpellProto->SpellFamilyFlags [0] & familyFlags) return true; return false; } void Unit::DealDamageMods(Unit *pVictim, uint32 &damage, uint32* absorb) { if (!pVictim->isAlive() || pVictim->HasUnitState(UNIT_STAT_IN_FLIGHT) || (pVictim->HasUnitState(UNIT_STAT_ONVEHICLE) && pVictim->GetVehicleBase() != this) || (pVictim->GetTypeId() == TYPEID_UNIT && pVictim->ToCreature()->IsInEvadeMode())) { if (absorb) *absorb += damage; damage = 0; return; } uint32 originalDamage = damage; if (absorb && originalDamage > damage) *absorb += (originalDamage - damage); } uint32 Unit::DealDamage(Unit *pVictim, uint32 damage, CleanDamage const* cleanDamage, DamageEffectType damagetype, SpellSchoolMask damageSchoolMask, SpellEntry const *spellProto, bool durabilityLoss) { if (pVictim->IsAIEnabled) pVictim->GetAI()->DamageTaken(this, damage); if (IsAIEnabled) GetAI()->DamageDealt(pVictim, damage, damagetype); if (damagetype == DIRECT_DAMAGE || damagetype == SPELL_DIRECT_DAMAGE) { m_damage_done [0] += damage; pVictim->m_damage_taken [0] += damage; } if (this->GetTypeId() == TYPEID_PLAYER) { if (pVictim->GetTypeId() == TYPEID_PLAYER) { Player *attacker = this->ToPlayer(); Player *victim = pVictim->ToPlayer(); sScriptMgr->OnPlayerDamageDealt(attacker, victim, damage, damagetype, spellProto); } else if (pVictim->GetTypeId() == TYPEID_UNIT) { Player *attacker = this->ToPlayer(); Creature *victim = pVictim->ToCreature(); sScriptMgr->OnPlayerDamageDealt(attacker, victim, damage, damagetype, spellProto); } } if (damagetype != NODAMAGE) { // interrupting auras with AURA_INTERRUPT_FLAG_DAMAGE before checking !damage (absorbed damage breaks that type of auras) pVictim->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TAKE_DAMAGE, spellProto ? spellProto->Id : 0); // We're going to call functions which can modify content of the list during iteration over it's elements // Let's copy the list so we can prevent iterator invalidation AuraEffectList vCopyDamageCopy( pVictim->GetAuraEffectsByType(SPELL_AURA_SHARE_DAMAGE_PCT)); // copy damage to casters of this aura for (AuraEffectList::iterator i = vCopyDamageCopy.begin(); i != vCopyDamageCopy.end(); ++i) { // Check if aura was removed during iteration - we don't need to work on such auras if (!((*i)->GetBase()->IsAppliedOnTarget(pVictim->GetGUID()))) continue; // check damage school mask if (((*i)->GetMiscValue() & damageSchoolMask) == 0) continue; Unit * shareDamageTarget = (*i)->GetCaster(); if (!shareDamageTarget) continue; SpellEntry const * spell = (*i)->GetSpellProto(); uint32 share = uint32(damage * (float((*i)->GetAmount()) / 100.0f)); // TODO: check packets if damage is done by pVictim, or by attacker of pVictim DealDamageMods(shareDamageTarget, share, NULL); DealDamage(shareDamageTarget, share, NULL, NODAMAGE, GetSpellSchoolMask(spell), spell, false); } } // Rage from Damage made (only from direct weapon damage) if (cleanDamage && damagetype == DIRECT_DAMAGE && this != pVictim && getPowerType() == POWER_RAGE) { uint32 weaponSpeedHitFactor; uint32 rage_damage = damage + cleanDamage->absorbed_damage; switch (cleanDamage->attackType) { case BASE_ATTACK: { weaponSpeedHitFactor = uint32( GetAttackTime(cleanDamage->attackType) / 1000.0f * 3.5f); if (cleanDamage->hitOutCome == MELEE_HIT_CRIT) weaponSpeedHitFactor *= 2; RewardRage(rage_damage, weaponSpeedHitFactor, true); break; } case OFF_ATTACK: { weaponSpeedHitFactor = uint32( GetAttackTime(cleanDamage->attackType) / 1000.0f * 1.75f); if (cleanDamage->hitOutCome == MELEE_HIT_CRIT) weaponSpeedHitFactor *= 2; RewardRage(rage_damage, weaponSpeedHitFactor, true); break; } case RANGED_ATTACK: break; default: break; } } if (!damage) { // Rage from absorbed damage if (cleanDamage && cleanDamage->absorbed_damage && pVictim->getPowerType() == POWER_RAGE) pVictim->RewardRage( cleanDamage->absorbed_damage, 0, false); return 0; } sLog->outStaticDebug("DealDamageStart"); uint32 health = pVictim->GetHealth(); sLog->outDetail("deal dmg:%d to health:%d ", damage, health); // duel ends when player has 1 or less hp bool duel_hasEnded = false; if (pVictim->GetTypeId() == TYPEID_PLAYER && pVictim->ToPlayer()->duel && damage >= (health - 1)) { // prevent kill only if killed in duel and killed by opponent or opponent controlled creature if (pVictim->ToPlayer()->duel->opponent == this || pVictim->ToPlayer()->duel->opponent->GetGUID() == GetOwnerGUID()) damage = health - 1; duel_hasEnded = true; } if (GetTypeId() == TYPEID_PLAYER && this != pVictim) { Player *killer = this->ToPlayer(); // in bg, count dmg if victim is also a player if (pVictim->GetTypeId() == TYPEID_PLAYER) if (Battleground *bg = killer->GetBattleground()) bg->UpdatePlayerScore( killer, SCORE_DAMAGE_DONE, damage); killer->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE, damage, 0, pVictim); killer->UpdateAchievementCriteria( ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_DEALT, damage); } if (pVictim->GetTypeId() == TYPEID_PLAYER) pVictim->ToPlayer()->UpdateAchievementCriteria( ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_RECEIVED, damage); else if (!pVictim->IsControlledByPlayer() || pVictim->IsVehicle()) { if (!pVictim->ToCreature()->hasLootRecipient()) pVictim->ToCreature()->SetLootRecipient( this); if (IsControlledByPlayer()) pVictim->ToCreature()->LowerPlayerDamageReq( health < damage ? health : damage); } if (health <= damage) { sLog->outStaticDebug("DealDamage: victim just died"); if (pVictim->GetTypeId() == TYPEID_PLAYER) { pVictim->ToPlayer()->UpdateAchievementCriteria( ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED, health); // call before auras are removed if (Player* killer = this->ToPlayer()) // keep the this-> for clarity killer->GetAchievementMgr().UpdateAchievementCriteria( ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL, 1, 0, pVictim); } if (this->ToPlayer() && this->isAlive()) // Trinkets Heirloom if (this->ToPlayer()->isHonorOrXPTarget(pVictim)) { AuraEffectList const& heirloom = GetAuraEffectsByType( SPELL_AURA_DUMMY); for (AuraEffectList::const_iterator j = heirloom.begin(); j != heirloom.end(); ++j) { if ((*j)->GetId() == 59915 && this->getPowerType() == POWER_MANA) this->CastSpell( this, 59914, true); if ((*j)->GetId() == 59906) { int32 bonushealth = this->GetMaxHealth() * this->GetAura(59906)->GetEffect(0)->GetAmount() / 100; this->CastCustomSpell(this, 59913, &bonushealth, 0, 0, true); } } } Kill(pVictim, durabilityLoss); } else { sLog->outStaticDebug("DealDamageAlive"); if (pVictim->GetTypeId() == TYPEID_PLAYER) pVictim->ToPlayer()->UpdateAchievementCriteria( ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED, damage); // Brain Freeze if (GetTypeId() == TYPEID_PLAYER) { if (damagetype == SPELL_DIRECT_DAMAGE) { if (GetSpellSchoolMask(spellProto) == SPELL_SCHOOL_MASK_FROST) { if (this->ToPlayer()->HasAura(44546)) if (roll_chance_f( 5.0f)) this->CastSpell(this, 57761, true); if (this->ToPlayer()->HasAura(44548)) if (roll_chance_f( 10.0f)) this->CastSpell(this, 57761, true); if (this->ToPlayer()->HasAura(44549)) if (roll_chance_f( 15.0f)) this->CastSpell(this, 57761, true); } } } // Maelstrom Weapon if (GetTypeId() == TYPEID_PLAYER) { if (damagetype == DIRECT_DAMAGE) { if (this->ToPlayer()->HasAura(51528)) if (roll_chance_f(10.0f)) this->CastSpell( this, 53817, true); if (this->ToPlayer()->HasAura(51529)) if (roll_chance_f(20.0f)) this->CastSpell( this, 53817, true); if (this->ToPlayer()->HasAura(51530)) if (roll_chance_f(30.0f)) this->CastSpell( this, 53817, true); } } pVictim->ModifyHealth(-(int32) damage); if (damagetype == DIRECT_DAMAGE || damagetype == SPELL_DIRECT_DAMAGE) pVictim->RemoveAurasWithInterruptFlags( AURA_INTERRUPT_FLAG_DIRECT_DAMAGE, spellProto ? spellProto->Id : 0); if (pVictim->GetTypeId() != TYPEID_PLAYER) { if (spellProto && IsDamageToThreatSpell(spellProto)) pVictim->AddThreat( this, damage * 2.0f, damageSchoolMask, spellProto); else pVictim->AddThreat(this, (float) damage, damageSchoolMask, spellProto); } else // victim is a player { // random durability for items (HIT TAKEN) if (roll_chance_f(sWorld->getRate(RATE_DURABILITY_LOSS_DAMAGE))) { EquipmentSlots slot = EquipmentSlots( urand(0, EQUIPMENT_SLOT_END - 1)); pVictim->ToPlayer()->DurabilityPointLossForEquipSlot(slot); } } // Rage from damage received if (this != pVictim && pVictim->getPowerType() == POWER_RAGE) { uint32 rage_damage = damage + (cleanDamage ? cleanDamage->absorbed_damage : 0); pVictim->RewardRage(rage_damage, 0, false); } if (GetTypeId() == TYPEID_PLAYER) { // random durability for items (HIT DONE) if (roll_chance_f(sWorld->getRate(RATE_DURABILITY_LOSS_DAMAGE))) { EquipmentSlots slot = EquipmentSlots( urand(0, EQUIPMENT_SLOT_END - 1)); this->ToPlayer()->DurabilityPointLossForEquipSlot(slot); } } if (damagetype != NODAMAGE && damage) { if (pVictim != this && pVictim->GetTypeId() == TYPEID_PLAYER) // does not support creature push_back { if (damagetype != DOT) { if (Spell* spell = pVictim->m_currentSpells[CURRENT_GENERIC_SPELL]) { if (spell->getState() == SPELL_STATE_PREPARING) { uint32 interruptFlags = spell->m_spellInfo->InterruptFlags; if (interruptFlags & SPELL_INTERRUPT_FLAG_ABORT_ON_DMG) pVictim->InterruptNonMeleeSpells( false); else if (interruptFlags & SPELL_INTERRUPT_FLAG_PUSH_BACK) spell->Delayed(); } } } if (Spell* spell = pVictim->m_currentSpells[CURRENT_CHANNELED_SPELL]) { if (spell->getState() == SPELL_STATE_CASTING) { uint32 channelInterruptFlags = spell->m_spellInfo->ChannelInterruptFlags; if (((channelInterruptFlags & CHANNEL_FLAG_DELAY) != 0) && (damagetype != DOT)) spell->DelayedChannel(); } } } } // last damage from duel opponent if (duel_hasEnded) { ASSERT(pVictim->GetTypeId() == TYPEID_PLAYER); Player *he = pVictim->ToPlayer(); ASSERT(he->duel); he->SetHealth(1); he->duel->opponent->CombatStopWithPets(true); he->CombatStopWithPets(true); he->CastSpell(he, 7267, true); // beg he->DuelComplete(DUEL_WON); } } sLog->outStaticDebug("DealDamageEnd returned %d damage", damage); return damage; } void Unit::CastStop(uint32 except_spellid) { for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++) if (m_currentSpells [i] && m_currentSpells [i]->m_spellInfo->Id != except_spellid) InterruptSpell( CurrentSpellTypes(i), false); } void Unit::CastSpell(Unit* Victim, uint32 spellId, bool triggered, Item *castItem, AuraEffect const * triggeredByAura, uint64 originalCaster) { SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId); if (!spellInfo) { sLog->outError( "CastSpell: unknown spell id %i by caster: %s %u)", spellId, (GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"), (GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry())); return; } CastSpell(Victim, spellInfo, triggered, castItem, triggeredByAura, originalCaster); } void Unit::CastSpell(Unit* Victim, SpellEntry const *spellInfo, bool triggered, Item *castItem, AuraEffect const * triggeredByAura, uint64 originalCaster) { if (!spellInfo) { sLog->outError( "CastSpell: unknown spell by caster: %s %u)", (GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"), (GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry())); return; } if (!originalCaster && GetTypeId() == TYPEID_UNIT && this->ToCreature()->isTotem() && IsControlledByPlayer()) if (Unit * owner = GetOwner()) originalCaster = owner->GetGUID(); SpellCastTargets targets; targets.setUnitTarget(Victim); if (castItem) sLog->outStaticDebug("WORLD: cast Item spellId - %i", spellInfo->Id); if (!originalCaster && triggeredByAura) originalCaster = triggeredByAura->GetCasterGUID(); Spell *spell = new Spell(this, spellInfo, triggered, originalCaster); spell->m_CastItem = castItem; spell->prepare(&targets, triggeredByAura); } void Unit::CastCustomSpell(Unit* target, uint32 spellId, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item *castItem, AuraEffect const * triggeredByAura, uint64 originalCaster) { CustomSpellValues values; if (bp0) values.AddSpellMod(SPELLVALUE_BASE_POINT0, *bp0); if (bp1) values.AddSpellMod(SPELLVALUE_BASE_POINT1, *bp1); if (bp2) values.AddSpellMod(SPELLVALUE_BASE_POINT2, *bp2); CastCustomSpell(spellId, values, target, triggered, castItem, triggeredByAura, originalCaster); } void Unit::CastCustomSpell(uint32 spellId, SpellValueMod mod, int32 value, Unit* target, bool triggered, Item *castItem, AuraEffect const * triggeredByAura, uint64 originalCaster) { CustomSpellValues values; values.AddSpellMod(mod, value); CastCustomSpell(spellId, values, target, triggered, castItem, triggeredByAura, originalCaster); } void Unit::CastCustomSpell(uint32 spellId, CustomSpellValues const &value, Unit* Victim, bool triggered, Item *castItem, AuraEffect const * triggeredByAura, uint64 originalCaster) { SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId); if (!spellInfo) { sLog->outError( "CastSpell: unknown spell id %i by caster: %s %u)", spellId, (GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"), (GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry())); return; } SpellCastTargets targets; targets.setUnitTarget(Victim); if (!originalCaster && triggeredByAura) originalCaster = triggeredByAura->GetCasterGUID(); Spell *spell = new Spell(this, spellInfo, triggered, originalCaster); if (castItem) { sLog->outStaticDebug("WORLD: cast Item spellId - %i", spellInfo->Id); spell->m_CastItem = castItem; } for (CustomSpellValues::const_iterator itr = value.begin(); itr != value.end(); ++itr) spell->SetSpellValue(itr->first, itr->second); spell->prepare(&targets, triggeredByAura); } // used for scripting void Unit::CastSpell(float x, float y, float z, uint32 spellId, bool triggered, Item *castItem, AuraEffect const * triggeredByAura, uint64 originalCaster, Unit* OriginalVictim) { SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId); if (!spellInfo) { sLog->outError( "CastSpell(x, y, z): unknown spell id %i by caster: %s %u)", spellId, (GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"), (GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry())); return; } if (castItem) sLog->outStaticDebug("WORLD: cast Item spellId - %i", spellInfo->Id); if (!originalCaster && triggeredByAura) originalCaster = triggeredByAura->GetCasterGUID(); Spell *spell = new Spell(this, spellInfo, triggered, originalCaster); SpellCastTargets targets; targets.setDst(x, y, z, GetOrientation()); if (OriginalVictim) targets.setUnitTarget(OriginalVictim); spell->m_CastItem = castItem; spell->prepare(&targets, triggeredByAura); } // used for scripting void Unit::CastSpell(GameObject *go, uint32 spellId, bool triggered, Item *castItem, AuraEffect* triggeredByAura, uint64 originalCaster) { if (!go) return; SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId); if (!spellInfo) { sLog->outError( "CastSpell(x, y, z): unknown spell id %i by caster: %s %u)", spellId, (GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"), (GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry())); return; } if (!(spellInfo->Targets & (TARGET_FLAG_OBJECT | TARGET_FLAG_OBJECT_CASTER))) { sLog->outError( "CastSpell: spell id %i by caster: %s %u) is not gameobject spell", spellId, (GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"), (GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry())); return; } if (castItem) sLog->outStaticDebug("WORLD: cast Item spellId - %i", spellInfo->Id); if (!originalCaster && triggeredByAura) originalCaster = triggeredByAura->GetCasterGUID(); Spell *spell = new Spell(this, spellInfo, triggered, originalCaster); SpellCastTargets targets; targets.setGOTarget(go); spell->m_CastItem = castItem; spell->prepare(&targets, triggeredByAura); } // Obsolete func need remove, here only for comotability vs another patches uint32 Unit::SpellNonMeleeDamageLog(Unit *pVictim, uint32 spellID, uint32 damage) { SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellID); SpellNonMeleeDamage damageInfo(this, pVictim, spellInfo->Id, spellInfo->SchoolMask); damage = SpellDamageBonus(pVictim, spellInfo, 0, damage, SPELL_DIRECT_DAMAGE); CalculateSpellDamageTaken(&damageInfo, damage, spellInfo); DealDamageMods(damageInfo.target, damageInfo.damage, &damageInfo.absorb); SendSpellNonMeleeDamageLog(&damageInfo); DealSpellDamage(&damageInfo, true); return damageInfo.damage; } void Unit::CalculateSpellDamageTaken(SpellNonMeleeDamage *damageInfo, int32 damage, SpellEntry const *spellInfo, WeaponAttackType attackType, bool crit) { if (damage < 0) return; if (spellInfo->AttributesEx4 & SPELL_ATTR4_FIXED_DAMAGE) { Unit *pVictim = damageInfo->target; if (!pVictim || !pVictim->isAlive()) return; SpellSchoolMask damageSchoolMask = SpellSchoolMask( damageInfo->schoolMask); // Calculate absorb resist if (damage > 0) { CalcAbsorbResist(pVictim, damageSchoolMask, SPELL_DIRECT_DAMAGE, damage, &damageInfo->absorb, &damageInfo->resist, spellInfo); damage -= damageInfo->absorb + damageInfo->resist; } else damage = 0; damageInfo->damage = damage; return; } Unit *pVictim = damageInfo->target; if (!pVictim || !pVictim->isAlive()) return; SpellSchoolMask damageSchoolMask = SpellSchoolMask(damageInfo->schoolMask); uint32 crTypeMask = pVictim->GetCreatureTypeMask(); if (IsDamageReducedByArmor(damageSchoolMask, spellInfo)) damage = CalcArmorReducedDamage(pVictim, damage, spellInfo, attackType); bool blocked = false; // Per-school calc switch (spellInfo->DmgClass) { // Melee and Ranged Spells case SPELL_DAMAGE_CLASS_RANGED: case SPELL_DAMAGE_CLASS_MELEE: { // Physical Damage if (damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL) { // Get blocked status blocked = isSpellBlocked(pVictim, spellInfo, attackType); } if (crit) { damageInfo->HitInfo |= SPELL_HIT_TYPE_CRIT; // Calculate crit bonus uint32 crit_bonus = damage; // Apply crit_damage bonus for melee spells if (Player* modOwner = GetSpellModOwner()) modOwner->ApplySpellMod( spellInfo->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus); damage += crit_bonus; // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE int32 critPctDamageMod = 0; if (attackType == RANGED_ATTACK) critPctDamageMod += pVictim->GetTotalAuraModifier( SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE); else { critPctDamageMod += pVictim->GetTotalAuraModifier( SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE); critPctDamageMod += GetTotalAuraModifier( SPELL_AURA_MOD_CRIT_DAMAGE_BONUS); } // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS critPctDamageMod += GetTotalAuraModifierByMiscMask( SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask); if (critPctDamageMod != 0) damage = int32( damage * float((100.0f + critPctDamageMod) / 100.0f)); } // Spell weapon based damage CAN BE crit & blocked at same time if (blocked) { damageInfo->blocked = pVictim->GetShieldBlockValue(); //double blocked amount if block is critical if (pVictim->isBlockCritical()) damageInfo->blocked += damageInfo->blocked; if (damage < int32(damageInfo->blocked)) damageInfo->blocked = uint32(damage); damage -= damageInfo->blocked; } ApplyResilience(pVictim, &damage); } break; // Magical Attacks case SPELL_DAMAGE_CLASS_NONE: case SPELL_DAMAGE_CLASS_MAGIC: { // If crit add critical bonus if (crit) { damageInfo->HitInfo |= SPELL_HIT_TYPE_CRIT; damage = SpellCriticalDamageBonus(spellInfo, damage, pVictim); } ApplyResilience(pVictim, &damage); } break; } // Calculate absorb resist if (damage > 0) { CalcAbsorbResist(pVictim, damageSchoolMask, SPELL_DIRECT_DAMAGE, damage, &damageInfo->absorb, &damageInfo->resist, spellInfo); damage -= damageInfo->absorb + damageInfo->resist; } else damage = 0; damageInfo->damage = damage; } void Unit::DealSpellDamage(SpellNonMeleeDamage *damageInfo, bool durabilityLoss) { if (damageInfo == 0) return; Unit *pVictim = damageInfo->target; if (!pVictim) return; if (!pVictim->isAlive() || pVictim->HasUnitState(UNIT_STAT_IN_FLIGHT) || (pVictim->HasUnitState(UNIT_STAT_ONVEHICLE) && pVictim->GetVehicleBase() != this) || (pVictim->GetTypeId() == TYPEID_UNIT && pVictim->ToCreature()->IsInEvadeMode())) return; SpellEntry const *spellProto = sSpellStore.LookupEntry(damageInfo->SpellID); if (spellProto == NULL) { sLog->outDebug(LOG_FILTER_UNITS, "Unit::DealSpellDamage have wrong damageInfo->SpellID: %u", damageInfo->SpellID); return; } // Call default DealDamage CleanDamage cleanDamage(damageInfo->cleanDamage, damageInfo->absorb, BASE_ATTACK, MELEE_HIT_NORMAL); DealDamage(pVictim, damageInfo->damage, &cleanDamage, SPELL_DIRECT_DAMAGE, SpellSchoolMask(damageInfo->schoolMask), spellProto, durabilityLoss); } //TODO for melee need create structure as in void Unit::CalculateMeleeDamage(Unit *pVictim, uint32 damage, CalcDamageInfo *damageInfo, WeaponAttackType attackType) { damageInfo->attacker = this; damageInfo->target = pVictim; damageInfo->damageSchoolMask = GetMeleeDamageSchoolMask(); damageInfo->attackType = attackType; damageInfo->damage = 0; damageInfo->cleanDamage = 0; damageInfo->absorb = 0; damageInfo->resist = 0; damageInfo->blocked_amount = 0; damageInfo->TargetState = 0; damageInfo->HitInfo = 0; damageInfo->procAttacker = PROC_FLAG_NONE; damageInfo->procVictim = PROC_FLAG_NONE; damageInfo->procEx = PROC_EX_NONE; damageInfo->hitOutCome = MELEE_HIT_EVADE; if (!pVictim) return; if (!isAlive() || !pVictim->isAlive()) return; // Select HitInfo/procAttacker/procVictim flag based on attack type switch (attackType) { case BASE_ATTACK: damageInfo->procAttacker = PROC_FLAG_DONE_MELEE_AUTO_ATTACK | PROC_FLAG_DONE_MAINHAND_ATTACK; damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_AUTO_ATTACK; damageInfo->HitInfo = HITINFO_NORMALSWING2; break; case OFF_ATTACK: damageInfo->procAttacker = PROC_FLAG_DONE_MELEE_AUTO_ATTACK | PROC_FLAG_DONE_OFFHAND_ATTACK; damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_AUTO_ATTACK; damageInfo->HitInfo = HITINFO_LEFTSWING; break; default: return; } // Physical Immune check if (damageInfo->target->IsImmunedToDamage( SpellSchoolMask(damageInfo->damageSchoolMask))) { damageInfo->HitInfo |= HITINFO_NORMALSWING; damageInfo->TargetState = VICTIMSTATE_IS_IMMUNE; damageInfo->procEx |= PROC_EX_IMMUNE; damageInfo->damage = 0; damageInfo->cleanDamage = 0; return; } damage += CalculateDamage(damageInfo->attackType, false, true); // Add melee damage bonus MeleeDamageBonus(damageInfo->target, &damage, damageInfo->attackType); // Calculate armor reduction if (IsDamageReducedByArmor( (SpellSchoolMask) (damageInfo->damageSchoolMask))) { damageInfo->damage = CalcArmorReducedDamage(damageInfo->target, damage, NULL, damageInfo->attackType); damageInfo->cleanDamage += damage - damageInfo->damage; } else damageInfo->damage = damage; damageInfo->hitOutCome = RollMeleeOutcomeAgainst(damageInfo->target, damageInfo->attackType); switch (damageInfo->hitOutCome) { case MELEE_HIT_EVADE: { damageInfo->HitInfo |= HITINFO_MISS | HITINFO_SWINGNOHITSOUND; damageInfo->TargetState = VICTIMSTATE_EVADES; damageInfo->procEx |= PROC_EX_EVADE; damageInfo->damage = 0; damageInfo->cleanDamage = 0; } return; case MELEE_HIT_MISS: { damageInfo->HitInfo |= HITINFO_MISS; damageInfo->TargetState = VICTIMSTATE_INTACT; damageInfo->procEx |= PROC_EX_MISS; damageInfo->damage = 0; damageInfo->cleanDamage = 0; } break; case MELEE_HIT_NORMAL: damageInfo->TargetState = VICTIMSTATE_HIT; damageInfo->procEx |= PROC_EX_NORMAL_HIT; break; case MELEE_HIT_CRIT: { damageInfo->HitInfo |= HITINFO_CRITICALHIT; damageInfo->TargetState = VICTIMSTATE_HIT; damageInfo->procEx |= PROC_EX_CRITICAL_HIT; // Crit bonus calc damageInfo->damage += damageInfo->damage; int32 mod = 0; // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE if (damageInfo->attackType == RANGED_ATTACK) mod += damageInfo->target->GetTotalAuraModifier( SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE); else { mod += damageInfo->target->GetTotalAuraModifier( SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE); mod += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS); } uint32 crTypeMask = damageInfo->target->GetCreatureTypeMask(); // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS mod += GetTotalAuraModifierByMiscMask( SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask); if (mod != 0) damageInfo->damage = int32( (damageInfo->damage) * float((100.0f + mod) / 100.0f)); } break; case MELEE_HIT_PARRY: damageInfo->TargetState = VICTIMSTATE_PARRY; damageInfo->procEx |= PROC_EX_PARRY; damageInfo->cleanDamage += damageInfo->damage; damageInfo->damage = 0; break; case MELEE_HIT_DODGE: damageInfo->TargetState = VICTIMSTATE_DODGE; damageInfo->procEx |= PROC_EX_DODGE; damageInfo->cleanDamage += damageInfo->damage; damageInfo->damage = 0; break; case MELEE_HIT_BLOCK: { damageInfo->TargetState = VICTIMSTATE_HIT; damageInfo->HitInfo |= HITINFO_BLOCK; damageInfo->procEx |= PROC_EX_BLOCK; damageInfo->blocked_amount = damageInfo->target->GetShieldBlockValue(); //double blocked amount if block is critical if (damageInfo->target->isBlockCritical()) damageInfo->blocked_amount += damageInfo->blocked_amount; if (damageInfo->blocked_amount >= damageInfo->damage) { damageInfo->TargetState = VICTIMSTATE_BLOCKS; damageInfo->blocked_amount = damageInfo->damage; damageInfo->procEx |= PROC_EX_FULL_BLOCK; } else damageInfo->procEx |= PROC_EX_NORMAL_HIT; damageInfo->damage -= damageInfo->blocked_amount; damageInfo->cleanDamage += damageInfo->blocked_amount; } break; case MELEE_HIT_GLANCING: { damageInfo->HitInfo |= HITINFO_GLANCING; damageInfo->TargetState = VICTIMSTATE_HIT; damageInfo->procEx |= PROC_EX_NORMAL_HIT; int32 leveldif = int32(pVictim->getLevel()) - int32(getLevel()); if (leveldif > 3) leveldif = 3; float reducePercent = 1 - leveldif * 0.1f; damageInfo->cleanDamage += damageInfo->damage - uint32(reducePercent * damageInfo->damage); damageInfo->damage = uint32(reducePercent * damageInfo->damage); } break; case MELEE_HIT_CRUSHING: { damageInfo->HitInfo |= HITINFO_CRUSHING; damageInfo->TargetState = VICTIMSTATE_HIT; damageInfo->procEx |= PROC_EX_NORMAL_HIT; // 150% normal damage damageInfo->damage += (damageInfo->damage / 2); } break; default: break; } int32 resilienceReduction = damageInfo->damage; ApplyResilience(pVictim, &resilienceReduction); resilienceReduction = damageInfo->damage - resilienceReduction; damageInfo->damage -= resilienceReduction; damageInfo->cleanDamage += resilienceReduction; // Calculate absorb resist if (int32(damageInfo->damage) > 0) { damageInfo->procVictim |= PROC_FLAG_TAKEN_DAMAGE; // Calculate absorb & resists CalcAbsorbResist(damageInfo->target, SpellSchoolMask(damageInfo->damageSchoolMask), DIRECT_DAMAGE, damageInfo->damage, &damageInfo->absorb, &damageInfo->resist); damageInfo->damage -= damageInfo->absorb + damageInfo->resist; if (damageInfo->absorb) { damageInfo->HitInfo |= HITINFO_ABSORB; damageInfo->procEx |= PROC_EX_ABSORB; } if (damageInfo->resist) damageInfo->HitInfo |= HITINFO_RESIST; } else // Impossible get negative result but.... damageInfo->damage = 0; } void Unit::DealMeleeDamage(CalcDamageInfo *damageInfo, bool durabilityLoss) { Unit *pVictim = damageInfo->target; if (!pVictim->isAlive() || pVictim->HasUnitState(UNIT_STAT_IN_FLIGHT) || (pVictim->HasUnitState(UNIT_STAT_ONVEHICLE) && pVictim->GetVehicleBase() != this) || (pVictim->GetTypeId() == TYPEID_UNIT && pVictim->ToCreature()->IsInEvadeMode())) return; // Hmmmm dont like this emotes client must by self do all animations if (damageInfo->HitInfo & HITINFO_CRITICALHIT) pVictim->HandleEmoteCommand( EMOTE_ONESHOT_WOUNDCRITICAL); if (damageInfo->blocked_amount && damageInfo->TargetState != VICTIMSTATE_BLOCKS) pVictim->HandleEmoteCommand( EMOTE_ONESHOT_PARRYSHIELD); if (damageInfo->TargetState == VICTIMSTATE_PARRY) { // Get attack timers float offtime = float(pVictim->getAttackTimer(OFF_ATTACK)); float basetime = float(pVictim->getAttackTimer(BASE_ATTACK)); // Reduce attack time if (pVictim->haveOffhandWeapon() && offtime < basetime) { float percent20 = pVictim->GetAttackTime(OFF_ATTACK) * 0.20f; float percent60 = 3.0f * percent20; if (offtime > percent20 && offtime <= percent60) pVictim->setAttackTimer( OFF_ATTACK, uint32(percent20)); else if (offtime > percent60) { offtime -= 2.0f * percent20; pVictim->setAttackTimer(OFF_ATTACK, uint32(offtime)); } } else { float percent20 = pVictim->GetAttackTime(BASE_ATTACK) * 0.20f; float percent60 = 3.0f * percent20; if (basetime > percent20 && basetime <= percent60) pVictim->setAttackTimer( BASE_ATTACK, uint32(percent20)); else if (basetime > percent60) { basetime -= 2.0f * percent20; pVictim->setAttackTimer(BASE_ATTACK, uint32(basetime)); } } } // Call default DealDamage CleanDamage cleanDamage(damageInfo->cleanDamage, damageInfo->absorb, damageInfo->attackType, damageInfo->hitOutCome); DealDamage(pVictim, damageInfo->damage, &cleanDamage, DIRECT_DAMAGE, SpellSchoolMask(damageInfo->damageSchoolMask), NULL, durabilityLoss); // If this is a creature and it attacks from behind it has a probability to daze it's victim if ((damageInfo->hitOutCome == MELEE_HIT_CRIT || damageInfo->hitOutCome == MELEE_HIT_CRUSHING || damageInfo->hitOutCome == MELEE_HIT_NORMAL || damageInfo->hitOutCome == MELEE_HIT_GLANCING) && GetTypeId() != TYPEID_PLAYER && !this->ToCreature()->IsControlledByPlayer() && !pVictim->HasInArc(M_PI, this) && (pVictim->GetTypeId() == TYPEID_PLAYER || !pVictim->ToCreature()->isWorldBoss())) { // -probability is between 0% and 40% // 20% base chance float Probability = 20.0f; //there is a newbie protection, at level 10 just 7% base chance; assuming linear function if (pVictim->getLevel() < 30) Probability = 0.65f * pVictim->getLevel() + 0.5f; uint32 VictimDefense = pVictim->GetDefenseSkillValue(); uint32 AttackerMeleeSkill = GetUnitMeleeSkill(); Probability *= AttackerMeleeSkill / (float) VictimDefense; if (Probability > 40.0f) Probability = 40.0f; if (roll_chance_f(Probability)) CastSpell(pVictim, 1604, true); } if (GetTypeId() == TYPEID_PLAYER) ToPlayer()->CastItemCombatSpell(pVictim, damageInfo->attackType, damageInfo->procVictim, damageInfo->procEx); // Do effect if any damage done to target if (damageInfo->damage) { // We're going to call functions which can modify content of the list during iteration over it's elements // Let's copy the list so we can prevent iterator invalidation AuraEffectList vDamageShieldsCopy( pVictim->GetAuraEffectsByType(SPELL_AURA_DAMAGE_SHIELD)); for (AuraEffectList::const_iterator dmgShieldItr = vDamageShieldsCopy.begin(); dmgShieldItr != vDamageShieldsCopy.end(); ++dmgShieldItr) { SpellEntry const *i_spellProto = (*dmgShieldItr)->GetSpellProto(); // Damage shield can be resisted... if (SpellMissInfo missInfo = pVictim->SpellHitResult(this, i_spellProto , false)) { pVictim->SendSpellMiss(this, i_spellProto->Id, missInfo); continue; } // ...or immuned if (IsImmunedToDamage(i_spellProto)) { pVictim->SendSpellDamageImmune(this, i_spellProto->Id); continue; } uint32 damage = (*dmgShieldItr)->GetAmount(); // No Unit::CalcAbsorbResist here - opcode doesn't send that data - this damage is probably not affected by that pVictim->DealDamageMods(this, damage, NULL); // TODO: Move this to a packet handler WorldPacket data(SMSG_SPELLDAMAGESHIELD, (8 + 8 + 4 + 4 + 4 + 4)); data << uint64(pVictim->GetGUID()); data << uint64(GetGUID()); data << uint32(i_spellProto->Id); data << uint32(damage); // Damage int32 overkill = int32(damage) - int32(GetHealth()); data << uint32(overkill > 0 ? overkill : 0); // Overkill data << uint32(i_spellProto->SchoolMask); data << uint32(0); // 4.0.6 pVictim->SendMessageToSet(&data, true); pVictim->DealDamage(this, damage, 0, SPELL_DIRECT_DAMAGE, GetSpellSchoolMask(i_spellProto), i_spellProto, true); } } } void Unit::HandleEmoteCommand(uint32 anim_id) { WorldPacket data(SMSG_EMOTE, 4 + 8); data << uint32(anim_id); data << uint64(GetGUID()); SendMessageToSet(&data, true); } bool Unit::IsDamageReducedByArmor(SpellSchoolMask schoolMask, SpellEntry const *spellInfo, uint8 effIndex) { // only physical spells damage gets reduced by armor if ((schoolMask & SPELL_SCHOOL_MASK_NORMAL) == 0) return false; if (spellInfo) { // there are spells with no specific attribute but they have "ignores armor" in tooltip if (sSpellMgr->GetSpellCustomAttr(spellInfo->Id) & SPELL_ATTR0_CU_IGNORE_ARMOR) return false; // bleeding effects are not reduced by armor if (effIndex != MAX_SPELL_EFFECTS && spellInfo->EffectApplyAuraName [effIndex] == SPELL_AURA_PERIODIC_DAMAGE) if (GetSpellMechanicMask( spellInfo, effIndex) & (1 << MECHANIC_BLEED)) return false; } return true; } uint32 Unit::CalcArmorReducedDamage(Unit* pVictim, const uint32 damage, SpellEntry const *spellInfo, WeaponAttackType /*attackType*/) { uint32 newdamage = 0; float armor = float(pVictim->GetArmor()); // decrease enemy armor effectiveness by SPELL_AURA_BYPASS_ARMOR_FOR_CASTER int32 auraEffectivenessReduction = 0; AuraEffectList const & reductionAuras = pVictim->GetAuraEffectsByType( SPELL_AURA_BYPASS_ARMOR_FOR_CASTER); for (AuraEffectList::const_iterator i = reductionAuras.begin(); i != reductionAuras.end(); ++i) if ((*i)->GetCasterGUID() == GetGUID()) auraEffectivenessReduction += (*i)->GetAmount(); armor = CalculatePctN(armor, 100 - std::min(auraEffectivenessReduction, 100)); // Ignore enemy armor by SPELL_AURA_MOD_TARGET_RESISTANCE aura armor += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, SPELL_SCHOOL_MASK_NORMAL); if (spellInfo) if (Player *modOwner = GetSpellModOwner()) modOwner->ApplySpellMod( spellInfo->Id, SPELLMOD_IGNORE_ARMOR, armor); AuraEffectList const& ResIgnoreAurasAb = GetAuraEffectsByType( SPELL_AURA_MOD_ABILITY_IGNORE_TARGET_RESIST); for (AuraEffectList::const_iterator j = ResIgnoreAurasAb.begin(); j != ResIgnoreAurasAb.end(); ++j) { if ((*j)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL && (*j)->IsAffectedOnSpell(spellInfo)) armor = floor( float(armor) * (float(100 - (*j)->GetAmount()) / 100.0f)); } AuraEffectList const& ResIgnoreAuras = GetAuraEffectsByType( SPELL_AURA_MOD_IGNORE_TARGET_RESIST); for (AuraEffectList::const_iterator j = ResIgnoreAuras.begin(); j != ResIgnoreAuras.end(); ++j) { if ((*j)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL) armor = floor( float(armor) * (float(100 - (*j)->GetAmount()) / 100.0f)); } if (GetTypeId() == TYPEID_PLAYER) { AuraEffectList const& ResIgnoreAuras = GetAuraEffectsByType( SPELL_AURA_MOD_ARMOR_PENETRATION_PCT); for (AuraEffectList::const_iterator itr = ResIgnoreAuras.begin(); itr != ResIgnoreAuras.end(); ++itr) { // item neutral spell if ((*itr)->GetSpellProto()->EquippedItemClass == -1) { armor = floor( float(armor) * (float(100 - (*itr)->GetAmount()) / 100.0f)); continue; } // item dependent spell - check curent weapons for (int i = 0; i < MAX_ATTACK; ++i) { Item *weapon = ToPlayer()->GetWeaponForAttack( WeaponAttackType(i), true); if (weapon && weapon->IsFitToSpellRequirements( (*itr)->GetSpellProto())) { armor = floor( float(armor) * (float(100 - (*itr)->GetAmount()) / 100.0f)); break; } } } } // Apply Player CR_ARMOR_PENETRATION rating if (GetTypeId() == TYPEID_PLAYER) { float maxArmorPen = 0; if (getLevel() < 60) maxArmorPen = float( 400 + 85 * pVictim->getLevel()); else maxArmorPen = 400 + 85 * pVictim->getLevel() + 4.5f * 85 * (pVictim->getLevel() - 59); // Cap armor penetration to this number maxArmorPen = std::min(((armor + maxArmorPen) / 3), armor); // Figure out how much armor do we ignore float armorPen = maxArmorPen * this->ToPlayer()->GetRatingBonusValue(CR_ARMOR_PENETRATION) / 100.0f; // Got the value, apply it armor -= armorPen; } if (armor < 0.0f) armor = 0.0f; float armorReduction = armor / (armor + 85.f * getLevel() + 400.f); if (getLevel() > 59) armorReduction = armor / (armor + 467.5f * getLevel() - 22167.5f); if (getLevel() > 80) armorReduction = armor / (armor + 2167.5f * getLevel() - 158167.5f); if (armorReduction < 0.0f) armorReduction = 0.0f; if (armorReduction > 0.75f) armorReduction = 0.75f; newdamage = uint32(damage - (damage * armorReduction)); return (newdamage > 1) ? newdamage : 1; } void Unit::CalcAbsorbResist(Unit *pVictim, SpellSchoolMask schoolMask, DamageEffectType damagetype, const uint32 damage, uint32 *absorb, uint32 *resist, SpellEntry const *spellInfo) { if (!pVictim || !pVictim->isAlive() || !damage) return; DamageInfo dmgInfo = DamageInfo(this, pVictim, damage, spellInfo, schoolMask, damagetype); // Magic damage, check for resists if ((schoolMask & SPELL_SCHOOL_MASK_NORMAL) == 0) { float baseVictimResistance = float(pVictim->GetResistance(GetFirstSchoolInMask(schoolMask))); float ignoredResistance = float(GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, schoolMask)); float victimResistance = baseVictimResistance + ignoredResistance; if (Player* player = ToPlayer()) ignoredResistance += float(player->GetSpellPenetrationItemMod()); if (Player* player = ToPlayer()) victimResistance -= float(player->GetSpellPenetrationItemMod()); // Resistance can't be lower then 0. if (victimResistance < 0.0f) victimResistance = 0.0f; static const uint32 BOSS_LEVEL = 88; static const float BOSS_RESISTANCE_CONSTANT = 510.0f; uint32 level = pVictim->getLevel(); float resistanceConstant = 0.0f; if (level == BOSS_LEVEL) resistanceConstant = BOSS_RESISTANCE_CONSTANT; else resistanceConstant = level * 5.0f; float averageResist = victimResistance / (victimResistance + resistanceConstant); float discreteResistProbability [11]; for (uint32 i = 0; i < 11; ++i) { discreteResistProbability [i] = 0.5f - 2.5f * fabs(0.1f * i - averageResist); if (discreteResistProbability [i] < 0.0f) discreteResistProbability [i] = 0.0f; } if (averageResist <= 0.1f) { discreteResistProbability [0] = 1.0f - 7.5f * averageResist; discreteResistProbability [1] = 5.0f * averageResist; discreteResistProbability [2] = 2.5f * averageResist; } float r = float(rand_norm()); uint32 i = 0; float probabilitySum = discreteResistProbability [0]; while (r >= probabilitySum && i < 10) probabilitySum += discreteResistProbability [++i]; float damageResisted = float(damage * i / 10); AuraEffectList const &ResIgnoreAurasAb = GetAuraEffectsByType( SPELL_AURA_MOD_ABILITY_IGNORE_TARGET_RESIST); for (AuraEffectList::const_iterator j = ResIgnoreAurasAb.begin(); j != ResIgnoreAurasAb.end(); ++j) if (((*j)->GetMiscValue() & schoolMask) && (*j)->IsAffectedOnSpell(spellInfo)) AddPctN( damageResisted, -(*j)->GetAmount()); AuraEffectList const &ResIgnoreAuras = GetAuraEffectsByType( SPELL_AURA_MOD_IGNORE_TARGET_RESIST); for (AuraEffectList::const_iterator j = ResIgnoreAuras.begin(); j != ResIgnoreAuras.end(); ++j) if ((*j)->GetMiscValue() & schoolMask) AddPctN(damageResisted, -(*j)->GetAmount()); dmgInfo.ResistDamage(uint32(damageResisted)); } // Ignore Absorption Auras float auraAbsorbMod = 0; AuraEffectList const & AbsIgnoreAurasA = GetAuraEffectsByType( SPELL_AURA_MOD_TARGET_ABSORB_SCHOOL); for (AuraEffectList::const_iterator itr = AbsIgnoreAurasA.begin(); itr != AbsIgnoreAurasA.end(); ++itr) { if (!((*itr)->GetMiscValue() & schoolMask)) continue; if ((*itr)->GetAmount() > auraAbsorbMod) auraAbsorbMod = float( (*itr)->GetAmount()); } AuraEffectList const & AbsIgnoreAurasB = GetAuraEffectsByType( SPELL_AURA_MOD_TARGET_ABILITY_ABSORB_SCHOOL); for (AuraEffectList::const_iterator itr = AbsIgnoreAurasB.begin(); itr != AbsIgnoreAurasB.end(); ++itr) { if (!((*itr)->GetMiscValue() & schoolMask)) continue; if (((*itr)->GetAmount() > auraAbsorbMod) && (*itr)->IsAffectedOnSpell(spellInfo)) auraAbsorbMod = float( (*itr)->GetAmount()); } RoundToInterval(auraAbsorbMod, 0.0f, 100.0f); // We're going to call functions which can modify content of the list during iteration over it's elements // Let's copy the list so we can prevent iterator invalidation AuraEffectList vSchoolAbsorbCopy( pVictim->GetAuraEffectsByType(SPELL_AURA_SCHOOL_ABSORB)); vSchoolAbsorbCopy.sort(Trinity::AbsorbAuraOrderPred()); // absorb without mana cost for (AuraEffectList::iterator itr = vSchoolAbsorbCopy.begin(); (itr != vSchoolAbsorbCopy.end()) && (dmgInfo.GetDamage() > 0); ++itr) { AuraEffect * absorbAurEff = (*itr); // Check if aura was removed during iteration - we don't need to work on such auras AuraApplication const * aurApp = absorbAurEff->GetBase()->GetApplicationOfTarget( pVictim->GetGUID()); if (!aurApp) continue; if (!(absorbAurEff->GetMiscValue() & schoolMask)) continue; // get amount which can be still absorbed by the aura int32 currentAbsorb = absorbAurEff->GetAmount(); // aura with infinite absorb amount - let the scripts handle absorbtion amount, set here to 0 for safety if (currentAbsorb < 0) currentAbsorb = 0; uint32 absorb = currentAbsorb; bool defaultPrevented = false; absorbAurEff->GetBase()->CallScriptEffectAbsorbHandlers(absorbAurEff, aurApp, dmgInfo, absorb, defaultPrevented); currentAbsorb = absorb; if (defaultPrevented) continue; // Apply absorb mod auras AddPctF(currentAbsorb, -auraAbsorbMod); // absorb must be smaller than the damage itself currentAbsorb = RoundToInterval(currentAbsorb, 0, int32(dmgInfo.GetDamage())); dmgInfo.AbsorbDamage(currentAbsorb); absorb = currentAbsorb; absorbAurEff->GetBase()->CallScriptEffectAfterAbsorbHandlers( absorbAurEff, aurApp, dmgInfo, absorb); // Check if our aura is using amount to count damage if (absorbAurEff->GetAmount() >= 0) { // Reduce shield amount absorbAurEff->SetAmount(absorbAurEff->GetAmount() - currentAbsorb); // Aura cannot absorb anything more - remove it if (absorbAurEff->GetAmount() <= 0) absorbAurEff->GetBase()->Remove( AURA_REMOVE_BY_ENEMY_SPELL); } } // absorb by mana cost AuraEffectList vManaShieldCopy( pVictim->GetAuraEffectsByType(SPELL_AURA_MANA_SHIELD)); for (AuraEffectList::const_iterator itr = vManaShieldCopy.begin(); (itr != vManaShieldCopy.end()) && (dmgInfo.GetDamage() > 0); ++itr) { AuraEffect * absorbAurEff = (*itr); // Check if aura was removed during iteration - we don't need to work on such auras AuraApplication const * aurApp = absorbAurEff->GetBase()->GetApplicationOfTarget( pVictim->GetGUID()); if (!aurApp) continue; // check damage school mask if (!(absorbAurEff->GetMiscValue() & schoolMask)) continue; // get amount which can be still absorbed by the aura int32 currentAbsorb = absorbAurEff->GetAmount(); // aura with infinite absorb amount - let the scripts handle absorbtion amount, set here to 0 for safety if (currentAbsorb < 0) currentAbsorb = 0; uint32 absorb = currentAbsorb; bool defaultPrevented = false; absorbAurEff->GetBase()->CallScriptEffectManaShieldHandlers( absorbAurEff, aurApp, dmgInfo, absorb, defaultPrevented); currentAbsorb = absorb; if (defaultPrevented) continue; AddPctF(currentAbsorb, -auraAbsorbMod); // absorb must be smaller than the damage itself currentAbsorb = RoundToInterval(currentAbsorb, 0, int32(dmgInfo.GetDamage())); int32 manaReduction = currentAbsorb; // lower absorb amount by talents if (float manaMultiplier = SpellMgr::CalculateSpellEffectValueMultiplier(absorbAurEff->GetSpellProto(), absorbAurEff->GetEffIndex(), absorbAurEff->GetCaster())) manaReduction = int32(float(manaReduction) * manaMultiplier); int32 manaTaken = -pVictim->ModifyPower(POWER_MANA, -manaReduction); // take case when mana has ended up into account currentAbsorb = currentAbsorb ? int32( float(currentAbsorb) * (float(manaTaken) / float(manaReduction))) : 0; dmgInfo.AbsorbDamage(currentAbsorb); absorb = currentAbsorb; absorbAurEff->GetBase()->CallScriptEffectAfterManaShieldHandlers( absorbAurEff, aurApp, dmgInfo, absorb); // Check if our aura is using amount to count damage if (absorbAurEff->GetAmount() >= 0) { absorbAurEff->SetAmount(absorbAurEff->GetAmount() - currentAbsorb); if ((absorbAurEff->GetAmount() <= 0)) absorbAurEff->GetBase()->Remove( AURA_REMOVE_BY_ENEMY_SPELL); } } // split damage auras - only when not damaging self if (pVictim != this) { // We're going to call functions which can modify content of the list during iteration over it's elements // Let's copy the list so we can prevent iterator invalidation AuraEffectList vSplitDamageFlatCopy( pVictim->GetAuraEffectsByType(SPELL_AURA_SPLIT_DAMAGE_FLAT)); for (AuraEffectList::iterator itr = vSplitDamageFlatCopy.begin(); (itr != vSplitDamageFlatCopy.end()) && (dmgInfo.GetDamage() > 0); ++itr) { // Check if aura was removed during iteration - we don't need to work on such auras if (!((*itr)->GetBase()->IsAppliedOnTarget(pVictim->GetGUID()))) continue; // check damage school mask if (!((*itr)->GetMiscValue() & schoolMask)) continue; // Damage can be splitted only if aura has an alive caster Unit * caster = (*itr)->GetCaster(); if (!caster || (caster == pVictim) || !caster->IsInWorld() || !caster->isAlive()) continue; int32 splitDamage = (*itr)->GetAmount(); // absorb must be smaller than the damage itself splitDamage = RoundToInterval(splitDamage, 0, int32(dmgInfo.GetDamage())); dmgInfo.ModifyDamage(splitDamage); uint32 splitted = splitDamage; uint32 splitted_absorb = 0; DealDamageMods(caster, splitted, &splitted_absorb); SendSpellNonMeleeDamageLog(caster, (*itr)->GetSpellProto()->Id, splitted, schoolMask, splitted_absorb, 0, false, 0, false); CleanDamage cleanDamage = CleanDamage(splitted, 0, BASE_ATTACK, MELEE_HIT_NORMAL); DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*itr)->GetSpellProto(), false); } // We're going to call functions which can modify content of the list during iteration over it's elements // Let's copy the list so we can prevent iterator invalidation AuraEffectList vSplitDamagePctCopy( pVictim->GetAuraEffectsByType(SPELL_AURA_SPLIT_DAMAGE_PCT)); for (AuraEffectList::iterator itr = vSplitDamagePctCopy.begin(), next; (itr != vSplitDamagePctCopy.end()) && (dmgInfo.GetDamage() > 0); ++itr) { // Check if aura was removed during iteration - we don't need to work on such auras if (!((*itr)->GetBase()->IsAppliedOnTarget(pVictim->GetGUID()))) continue; // check damage school mask if (!((*itr)->GetMiscValue() & schoolMask)) continue; // Damage can be splitted only if aura has an alive caster Unit * caster = (*itr)->GetCaster(); if (!caster || (caster == pVictim) || !caster->IsInWorld() || !caster->isAlive()) continue; int32 splitDamage = CalculatePctN(dmgInfo.GetDamage(), (*itr)->GetAmount()); // absorb must be smaller than the damage itself splitDamage = RoundToInterval(splitDamage, 0, int32(dmgInfo.GetDamage())); dmgInfo.ModifyDamage(splitDamage); uint32 splitted = splitDamage; uint32 split_absorb = 0; DealDamageMods(caster, splitted, &split_absorb); SendSpellNonMeleeDamageLog(caster, (*itr)->GetSpellProto()->Id, splitted, schoolMask, split_absorb, 0, false, 0, false); CleanDamage cleanDamage = CleanDamage(splitted, 0, BASE_ATTACK, MELEE_HIT_NORMAL); DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*itr)->GetSpellProto(), false); } } *resist = dmgInfo.GetResist(); *absorb = dmgInfo.GetAbsorb(); } void Unit::CalcHealAbsorb(Unit *pVictim, const SpellEntry *healSpell, uint32 &healAmount, uint32 &absorb) { if (!healAmount) return; int32 RemainingHeal = healAmount; // Need remove expired auras after bool existExpired = false; // absorb without mana cost AuraEffectList const& vHealAbsorb = pVictim->GetAuraEffectsByType( SPELL_AURA_SCHOOL_HEAL_ABSORB); for (AuraEffectList::const_iterator i = vHealAbsorb.begin(); i != vHealAbsorb.end() && RemainingHeal > 0; ++i) { if (!((*i)->GetMiscValue() & healSpell->SchoolMask)) continue; // Max Amount can be absorbed by this aura int32 currentAbsorb = (*i)->GetAmount(); // Found empty aura (impossible but..) if (currentAbsorb <= 0) { existExpired = true; continue; } // currentAbsorb - damage can be absorbed by shield // If need absorb less damage if (RemainingHeal < currentAbsorb) currentAbsorb = RemainingHeal; RemainingHeal -= currentAbsorb; // Reduce shield amount (*i)->SetAmount((*i)->GetAmount() - currentAbsorb); // Need remove it later if ((*i)->GetAmount() <= 0) existExpired = true; } // Necrotic Strike if (pVictim->HasAura(73975)) { int32 heal = int32(pVictim->GetAbsorbHeal()); RemainingHeal -= heal; } // No negative heal if (RemainingHeal < 0) RemainingHeal = 0; // Remove all expired absorb auras if (existExpired) { for (AuraEffectList::const_iterator i = vHealAbsorb.begin(); i != vHealAbsorb.end();) { AuraEffect *auraEff = *i; ++i; if (auraEff->GetAmount() <= 0) { uint32 removedAuras = pVictim->m_removedAurasCount; auraEff->GetBase()->Remove(AURA_REMOVE_BY_ENEMY_SPELL); if (removedAuras + 1 < pVictim->m_removedAurasCount) i = vHealAbsorb.begin(); } } } absorb = RemainingHeal > 0 ? (healAmount - RemainingHeal) : healAmount; healAmount = RemainingHeal; } void Unit::AttackerStateUpdate(Unit *pVictim, WeaponAttackType attType, bool extra) { if (HasUnitState(UNIT_STAT_CANNOT_AUTOATTACK) || HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED)) return; if (!pVictim->isAlive()) return; if ((attType == BASE_ATTACK || attType == OFF_ATTACK) && !IsWithinLOSInMap(pVictim) && !isPet()) return; CombatStart(pVictim); RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MELEE_ATTACK); uint32 hitInfo; if (attType == BASE_ATTACK) hitInfo = HITINFO_NORMALSWING2; else if (attType == OFF_ATTACK) hitInfo = HITINFO_LEFTSWING; else return; // ignore ranged case // melee attack spell casted at main hand attack only - no normal melee dmg dealt if (attType == BASE_ATTACK && m_currentSpells [CURRENT_MELEE_SPELL]) m_currentSpells [CURRENT_MELEE_SPELL]->cast(); else { // attack can be redirected to another target pVictim = SelectMagnetTarget(pVictim); CalcDamageInfo damageInfo; CalculateMeleeDamage(pVictim, 0, &damageInfo, attType); // Send log damage message to client DealDamageMods(pVictim, damageInfo.damage, &damageInfo.absorb); SendAttackStateUpdate(&damageInfo); ProcDamageAndSpell(damageInfo.target, damageInfo.procAttacker, damageInfo.procVictim, damageInfo.procEx, damageInfo.damage, damageInfo.attackType); DealMeleeDamage(&damageInfo, true); if (GetTypeId() == TYPEID_PLAYER) sLog->outStaticDebug( "AttackerStateUpdate: (Player) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.", GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist); else sLog->outStaticDebug( "AttackerStateUpdate: (NPC) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.", GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist); } if (!extra && m_extraAttacks) { while (m_extraAttacks) { AttackerStateUpdate(pVictim, BASE_ATTACK, true); if (m_extraAttacks > 0) --m_extraAttacks; } } } MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit *pVictim, WeaponAttackType attType) const { // This is only wrapper // Miss chance based on melee //float miss_chance = MeleeMissChanceCalc(pVictim, attType); float miss_chance = MeleeSpellMissChance( pVictim, attType, int32(GetWeaponSkillValue(attType, pVictim)) - int32(pVictim->GetDefenseSkillValue(this)), 0); // Critical hit chance float crit_chance = GetUnitCriticalChance(attType, pVictim); // stunned target cannot dodge and this is check in GetUnitDodgeChance() (returned 0 in this case) float dodge_chance = pVictim->GetUnitDodgeChance(); float block_chance = pVictim->GetUnitBlockChance(); float parry_chance = pVictim->GetUnitParryChance(); // Useful if want to specify crit & miss chances for melee, else it could be removed sLog->outStaticDebug( "MELEE OUTCOME: miss %f crit %f dodge %f parry %f block %f", miss_chance, crit_chance, dodge_chance, parry_chance, block_chance); return RollMeleeOutcomeAgainst(pVictim, attType, int32(crit_chance * 100), int32(miss_chance * 100), int32(dodge_chance * 100), int32(parry_chance * 100), int32(block_chance * 100)); } MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit *pVictim, WeaponAttackType attType, int32 crit_chance, int32 miss_chance, int32 dodge_chance, int32 parry_chance, int32 block_chance) const { if (pVictim->GetTypeId() == TYPEID_UNIT && pVictim->ToCreature()->IsInEvadeMode()) return MELEE_HIT_EVADE; int32 attackerMaxSkillValueForLevel = GetMaxSkillValueForLevel(pVictim); int32 victimMaxSkillValueForLevel = pVictim->GetMaxSkillValueForLevel(this); int32 attackerWeaponSkill = GetWeaponSkillValue(attType, pVictim); int32 victimDefenseSkill = pVictim->GetDefenseSkillValue(this); // bonus from skills is 0.04% int32 skillBonus = 4 * (attackerWeaponSkill - victimMaxSkillValueForLevel); int32 sum = 0, tmp = 0; int32 roll = urand(0, 10000); sLog->outStaticDebug( "RollMeleeOutcomeAgainst: skill bonus of %d for attacker", skillBonus); sLog->outStaticDebug( "RollMeleeOutcomeAgainst: rolled %d, miss %d, dodge %d, parry %d, block %d, crit %d", roll, miss_chance, dodge_chance, parry_chance, block_chance, crit_chance); tmp = miss_chance; if (tmp > 0 && roll < (sum += tmp)) { sLog->outStaticDebug("RollMeleeOutcomeAgainst: MISS"); return MELEE_HIT_MISS; } // always crit against a sitting target (except 0 crit chance) if (pVictim->GetTypeId() == TYPEID_PLAYER && crit_chance > 0 && !pVictim->IsStandState()) { sLog->outStaticDebug("RollMeleeOutcomeAgainst: CRIT (sitting victim)"); return MELEE_HIT_CRIT; } // Dodge chance // only players can't dodge if attacker is behind if (pVictim->GetTypeId() == TYPEID_PLAYER && !pVictim->HasInArc(M_PI, this) && !pVictim->HasAuraType(SPELL_AURA_IGNORE_HIT_DIRECTION)) { sLog->outStaticDebug( "RollMeleeOutcomeAgainst: attack came from behind and victim was a player."); } else { // Reduce dodge chance by attacker expertise rating if (GetTypeId() == TYPEID_PLAYER) dodge_chance -= int32( this->ToPlayer()->GetExpertiseDodgeOrParryReduction(attType) * 100); else dodge_chance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE) * 25; // Modify dodge chance by attacker SPELL_AURA_MOD_COMBAT_RESULT_CHANCE dodge_chance += GetTotalAuraModifierByMiscValue( SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE) * 100; dodge_chance = int32( float(dodge_chance) * GetTotalAuraMultiplier(SPELL_AURA_MOD_ENEMY_DODGE)); tmp = dodge_chance; if ((tmp > 0) // check if unit _can_ dodge && ((tmp -= skillBonus) > 0) && roll < (sum += tmp)) { sLog->outStaticDebug("RollMeleeOutcomeAgainst: DODGE <%d, %d)", sum - tmp, sum); return MELEE_HIT_DODGE; } } // parry & block chances // check if attack comes from behind, nobody can parry or block if attacker is behind if (!pVictim->HasInArc(M_PI, this) && !pVictim->HasAuraType(SPELL_AURA_IGNORE_HIT_DIRECTION)) sLog->outStaticDebug("RollMeleeOutcomeAgainst: attack came from behind."); else { // Reduce parry chance by attacker expertise rating if (GetTypeId() == TYPEID_PLAYER) parry_chance -= int32( this->ToPlayer()->GetExpertiseDodgeOrParryReduction(attType) * 100); else parry_chance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE) * 25; if (pVictim->GetTypeId() == TYPEID_PLAYER || !(pVictim->ToCreature()->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_PARRY)) { int32 tmp2 = int32(parry_chance); if (tmp2 > 0 // check if unit _can_ parry && (tmp2 -= skillBonus) > 0 && roll < (sum += tmp2)) { sLog->outStaticDebug("RollMeleeOutcomeAgainst: PARRY <%d, %d)", sum - tmp2, sum); return MELEE_HIT_PARRY; } } if (pVictim->GetTypeId() == TYPEID_PLAYER || !(pVictim->ToCreature()->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK)) { tmp = block_chance; if (tmp > 0 // check if unit _can_ block && (tmp -= skillBonus) > 0 && roll < (sum += tmp)) { sLog->outStaticDebug("RollMeleeOutcomeAgainst: BLOCK <%d, %d)", sum - tmp, sum); return MELEE_HIT_BLOCK; } } } // Critical chance tmp = crit_chance; if (tmp > 0 && roll < (sum += tmp)) { sLog->outStaticDebug("RollMeleeOutcomeAgainst: CRIT <%d, %d)", sum - tmp, sum); if (GetTypeId() == TYPEID_UNIT && (this->ToCreature()->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_CRIT)) sLog->outStaticDebug("RollMeleeOutcomeAgainst: CRIT DISABLED)"); else return MELEE_HIT_CRIT; } // Max 40% chance to score a glancing blow against mobs that are higher level (can do only players and pets and not with ranged weapon) if (attType != RANGED_ATTACK && (GetTypeId() == TYPEID_PLAYER || this->ToCreature()->isPet()) && pVictim->GetTypeId() != TYPEID_PLAYER && !pVictim->ToCreature()->isPet() && getLevel() < pVictim->getLevelForTarget(this)) { // cap possible value (with bonuses > max skill) int32 skill = attackerWeaponSkill; int32 maxskill = attackerMaxSkillValueForLevel; skill = (skill > maxskill) ? maxskill : skill; tmp = (10 + (victimDefenseSkill - skill)) * 100; tmp = tmp > 4000 ? 4000 : tmp; if (roll < (sum += tmp)) { sLog->outStaticDebug("RollMeleeOutcomeAgainst: GLANCING <%d, %d)", sum - 4000, sum); return MELEE_HIT_GLANCING; } } // mobs can score crushing blows if they're 4 or more levels above victim if (getLevelForTarget(pVictim) >= pVictim->getLevelForTarget(this) + 4 && // can be from by creature (if can) or from controlled player that considered as creature !IsControlledByPlayer() && !(GetTypeId() == TYPEID_UNIT && this->ToCreature()->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_CRUSH)) { // when their weapon skill is 15 or more above victim's defense skill tmp = victimDefenseSkill; int32 tmpmax = victimMaxSkillValueForLevel; // having defense above your maximum (from items, talents etc.) has no effect tmp = tmp > tmpmax ? tmpmax : tmp; // tmp = mob's level * 5 - player's current defense skill tmp = attackerMaxSkillValueForLevel - tmp; if (tmp >= 15) { // add 2% chance per lacking skill point, min. is 15% tmp = tmp * 200 - 1500; if (roll < (sum += tmp)) { sLog->outStaticDebug( "RollMeleeOutcomeAgainst: CRUSHING <%d, %d)", sum - tmp, sum); return MELEE_HIT_CRUSHING; } } } sLog->outStaticDebug("RollMeleeOutcomeAgainst: NORMAL"); return MELEE_HIT_NORMAL; } uint32 Unit::CalculateDamage(WeaponAttackType attType, bool normalized, bool addTotalPct) { float min_damage, max_damage; if (GetTypeId() == TYPEID_PLAYER && (normalized || !addTotalPct)) this->ToPlayer()->CalculateMinMaxDamage( attType, normalized, addTotalPct, min_damage, max_damage); else { switch (attType) { case RANGED_ATTACK: min_damage = GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE); max_damage = GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE); break; case BASE_ATTACK: min_damage = GetFloatValue(UNIT_FIELD_MINDAMAGE); max_damage = GetFloatValue(UNIT_FIELD_MAXDAMAGE); break; case OFF_ATTACK: min_damage = GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE); max_damage = GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE); break; // Just for good manner default: min_damage = 0.0f; max_damage = 0.0f; break; } } if (min_damage > max_damage) std::swap(min_damage, max_damage); if (max_damage == 0.0f) max_damage = 5.0f; return urand((uint32) min_damage, (uint32) max_damage); } float Unit::CalculateLevelPenalty(SpellEntry const* spellProto) const { if (spellProto->spellLevel <= 0 || spellProto->spellLevel >= spellProto->maxLevel) return 1.0f; float LvlPenalty = 0.0f; if (spellProto->spellLevel < 20) LvlPenalty = 20.0f - spellProto->spellLevel * 3.75f; float LvlFactor = (float(spellProto->spellLevel) + 6.0f) / float(getLevel()); if (LvlFactor > 1.0f) LvlFactor = 1.0f; return (100.0f - LvlPenalty) * LvlFactor / 100.0f; } void Unit::SendMeleeAttackStart(Unit* pVictim) { WorldPacket data(SMSG_ATTACKSTART, 8 + 8); data << uint64(GetGUID()); data << uint64(pVictim->GetGUID()); SendMessageToSet(&data, true); sLog->outStaticDebug("WORLD: Sent SMSG_ATTACKSTART"); } void Unit::SendMeleeAttackStop(Unit* victim) { if (!victim) return; WorldPacket data(SMSG_ATTACKSTOP, (8 + 8 + 4)); // we guess size data.append(GetPackGUID()); data.append(victim->GetPackGUID()); // can be 0x00... data << uint32(0); // can be 0x1 SendMessageToSet(&data, true); sLog->outDetail("%s %u stopped attacking %s %u", (GetTypeId() == TYPEID_PLAYER ? "player" : "creature"), GetGUIDLow(), (victim->GetTypeId() == TYPEID_PLAYER ? "player" : "creature"), victim->GetGUIDLow()); } bool Unit::isSpellBlocked(Unit *pVictim, SpellEntry const * spellProto, WeaponAttackType attackType) { if (pVictim->HasInArc(M_PI, this) || pVictim->HasAuraType(SPELL_AURA_IGNORE_HIT_DIRECTION)) { // Check creatures flags_extra for disable block if (pVictim->GetTypeId() == TYPEID_UNIT && pVictim->ToCreature()->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK) return false; // These spells shouldn't be blocked if (spellProto && spellProto->Attributes & SPELL_ATTR0_IMPOSSIBLE_DODGE_PARRY_BLOCK) return false; float blockChance = pVictim->GetUnitBlockChance(); blockChance += (int32(GetWeaponSkillValue(attackType)) - int32(pVictim->GetMaxSkillValueForLevel())) * 0.04f; if (roll_chance_f(blockChance)) return true; } return false; } bool Unit::isBlockCritical() { if (roll_chance_i(GetTotalAuraModifier(SPELL_AURA_MOD_BLOCK_CRIT_CHANCE))) return true; return false; } int32 Unit::GetMechanicResistChance(const SpellEntry *spell) { if (!spell) return 0; int32 resist_mech = 0; for (uint8 eff = 0; eff < MAX_SPELL_EFFECTS; ++eff) { if (spell->Effect [eff] == 0) break; int32 effect_mech = GetEffectMechanic(spell, eff); if (effect_mech) { int32 temp = GetTotalAuraModifierByMiscValue( SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech); if (resist_mech < temp) resist_mech = temp; } } return resist_mech; } // Melee based spells hit result calculations SpellMissInfo Unit::MeleeSpellHitResult(Unit *pVictim, SpellEntry const *spell) { WeaponAttackType attType = BASE_ATTACK; // Check damage class instead of attack type to correctly handle judgements // - they are meele, but can't be dodged/parried/deflected because of ranged dmg class if (spell->DmgClass == SPELL_DAMAGE_CLASS_RANGED) attType = RANGED_ATTACK; int32 attackerWeaponSkill; // skill value for these spells (for example judgements) is 5* level if (spell->DmgClass == SPELL_DAMAGE_CLASS_RANGED && !IsRangedWeaponSpell(spell)) attackerWeaponSkill = getLevel() * 5; // bonus from skills is 0.04% per skill Diff else attackerWeaponSkill = int32(GetWeaponSkillValue(attType, pVictim)); int32 skillDiff = attackerWeaponSkill - int32(pVictim->GetMaxSkillValueForLevel(this)); int32 fullSkillDiff = attackerWeaponSkill - int32(pVictim->GetDefenseSkillValue(this)); uint32 roll = urand(0, 10000); uint32 missChance = uint32( MeleeSpellMissChance(pVictim, attType, fullSkillDiff, spell->Id) * 100.0f); // Roll miss uint32 tmp = missChance; if (roll < tmp) return SPELL_MISS_MISS; // Chance resist mechanic (select max value from every mechanic spell effect) int32 resist_mech = 0; // Get effects mechanic and chance for (uint8 eff = 0; eff < MAX_SPELL_EFFECTS; ++eff) { int32 effect_mech = GetEffectMechanic(spell, eff); if (effect_mech) { int32 temp = pVictim->GetTotalAuraModifierByMiscValue( SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech); if (resist_mech < temp * 100) resist_mech = temp * 100; } } // Roll chance tmp += resist_mech; if (roll < tmp) return SPELL_MISS_RESIST; bool canDodge = true; bool canParry = true; bool canBlock = spell->AttributesEx3 & SPELL_ATTR3_BLOCKABLE_SPELL; // Same spells cannot be parry/dodge if (spell->Attributes & SPELL_ATTR0_IMPOSSIBLE_DODGE_PARRY_BLOCK) return SPELL_MISS_NONE; // Chance resist mechanic int32 resist_chance = pVictim->GetMechanicResistChance(spell) * 100; tmp += resist_chance; if (roll < tmp) return SPELL_MISS_RESIST; // Ranged attacks can only miss, resist and deflect if (attType == RANGED_ATTACK) { // only if in front if (pVictim->HasInArc(M_PI, this) || pVictim->HasAuraType(SPELL_AURA_IGNORE_HIT_DIRECTION)) { int32 deflect_chance = pVictim->GetTotalAuraModifier( SPELL_AURA_DEFLECT_SPELLS) * 100; tmp += deflect_chance; if (roll < tmp) return SPELL_MISS_DEFLECT; } return SPELL_MISS_NONE; } // Check for attack from behind if (!pVictim->HasInArc(M_PI, this) && !pVictim->HasAuraType(SPELL_AURA_IGNORE_HIT_DIRECTION)) { // Can`t dodge from behind in PvP (but its possible in PvE) if (pVictim->GetTypeId() == TYPEID_PLAYER) canDodge = false; // Can`t parry or block canParry = false; canBlock = false; } // Check creatures flags_extra for disable parry if (pVictim->GetTypeId() == TYPEID_UNIT) { uint32 flagEx = pVictim->ToCreature()->GetCreatureInfo()->flags_extra; if (flagEx & CREATURE_FLAG_EXTRA_NO_PARRY) canParry = false; // Check creatures flags_extra for disable block if (flagEx & CREATURE_FLAG_EXTRA_NO_BLOCK) canBlock = false; } // Ignore combat result aura AuraEffectList const &ignore = GetAuraEffectsByType( SPELL_AURA_IGNORE_COMBAT_RESULT); for (AuraEffectList::const_iterator i = ignore.begin(); i != ignore.end(); ++i) { if (!(*i)->IsAffectedOnSpell(spell)) continue; switch ((*i)->GetMiscValue()) { case MELEE_HIT_DODGE: canDodge = false; break; case MELEE_HIT_BLOCK: canBlock = false; break; case MELEE_HIT_PARRY: canParry = false; break; default: sLog->outStaticDebug( "Spell %u SPELL_AURA_IGNORE_COMBAT_RESULT have unhandled state %d", (*i)->GetId(), (*i)->GetMiscValue()); break; } } if (canDodge) { // Roll dodge int32 dodgeChance = int32(pVictim->GetUnitDodgeChance() * 100.0f) - skillDiff * 4; // Reduce enemy dodge chance by SPELL_AURA_MOD_COMBAT_RESULT_CHANCE dodgeChance += GetTotalAuraModifierByMiscValue( SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE) * 100; dodgeChance = int32( float(dodgeChance) * GetTotalAuraMultiplier(SPELL_AURA_MOD_ENEMY_DODGE)); // Reduce dodge chance by attacker expertise rating if (GetTypeId() == TYPEID_PLAYER) dodgeChance -= int32( this->ToPlayer()->GetExpertiseDodgeOrParryReduction(attType) * 100.0f); else dodgeChance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE) * 25; if (dodgeChance < 0) dodgeChance = 0; if (roll < (tmp += dodgeChance)) return SPELL_MISS_DODGE; } if (canParry) { // Roll parry int32 parryChance = int32(pVictim->GetUnitParryChance() * 100.0f) - skillDiff * 4; // Reduce parry chance by attacker expertise rating if (GetTypeId() == TYPEID_PLAYER) parryChance -= int32( this->ToPlayer()->GetExpertiseDodgeOrParryReduction(attType) * 100.0f); else parryChance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE) * 25; if (parryChance < 0) parryChance = 0; tmp += parryChance; if (roll < tmp) return SPELL_MISS_PARRY; } if (canBlock) { int32 blockChance = int32(pVictim->GetUnitBlockChance() * 100.0f) - skillDiff * 4; if (blockChance < 0) blockChance = 0; tmp += blockChance; if (roll < tmp) return SPELL_MISS_BLOCK; } return SPELL_MISS_NONE; } // TODO need use unit spell resistances in calculations SpellMissInfo Unit::MagicSpellHitResult(Unit *pVictim, SpellEntry const *spell) { // Can`t miss on dead target (on skinning for example) if (!pVictim->isAlive() && pVictim->GetTypeId() != TYPEID_PLAYER) return SPELL_MISS_NONE; SpellSchoolMask schoolMask = GetSpellSchoolMask(spell); // PvP - PvE spell misschances per leveldif > 2 int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 7 : 11; int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim)); // Base hit chance from attacker and victim levels int32 modHitChance; if (leveldif < 3) modHitChance = 96 - leveldif; else modHitChance = 94 - (leveldif - 2) * lchance; // Spellmod from SPELLMOD_RESIST_MISS_CHANCE if (Player *modOwner = GetSpellModOwner()) modOwner->ApplySpellMod( spell->Id, SPELLMOD_RESIST_MISS_CHANCE, modHitChance); // Increase from attacker SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT auras modHitChance += GetTotalAuraModifierByMiscMask( SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT, schoolMask); // Chance hit from victim SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE auras modHitChance += pVictim->GetTotalAuraModifierByMiscMask( SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE, schoolMask); // Reduce spell hit chance for Area of effect spells from victim SPELL_AURA_MOD_AOE_AVOIDANCE aura if (IsAreaOfEffectSpell(spell)) modHitChance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_AOE_AVOIDANCE); int32 HitChance = modHitChance * 100; // Increase hit chance from attacker SPELL_AURA_MOD_SPELL_HIT_CHANCE and attacker ratings HitChance += int32(m_modSpellHitChance * 100.0f); // Decrease hit chance from victim rating bonus if (pVictim->GetTypeId() == TYPEID_PLAYER) HitChance -= int32( pVictim->ToPlayer()->GetRatingBonusValue(CR_HIT_TAKEN_SPELL) * 100.0f); if (HitChance < 100) HitChance = 100; else if (HitChance > 10000) HitChance = 10000; int32 tmp = 10000 - HitChance; int32 rand = irand(0, 10000); if (rand < tmp) return SPELL_MISS_MISS; // Chance resist mechanic (select max value from every mechanic spell effect) int32 resist_chance = pVictim->GetMechanicResistChance(spell) * 100; tmp += resist_chance; // Chance resist debuff if (!IsPositiveSpell(spell->Id)) { bool bNegativeAura = false; for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (spell->EffectApplyAuraName [i] != 0) { bNegativeAura = true; break; } } if (bNegativeAura) { tmp += pVictim->GetMaxPositiveAuraModifierByMiscValue( SPELL_AURA_MOD_DEBUFF_RESISTANCE, int32(spell->Dispel)) * 100; tmp += pVictim->GetMaxNegativeAuraModifierByMiscValue( SPELL_AURA_MOD_DEBUFF_RESISTANCE, int32(spell->Dispel)) * 100; } } // Roll chance if (rand < tmp) return SPELL_MISS_RESIST; // cast by caster in front of victim if (pVictim->HasInArc(M_PI, this) || pVictim->HasAuraType(SPELL_AURA_IGNORE_HIT_DIRECTION)) { int32 deflect_chance = pVictim->GetTotalAuraModifier( SPELL_AURA_DEFLECT_SPELLS) * 100; tmp += deflect_chance; if (rand < tmp) return SPELL_MISS_DEFLECT; } return SPELL_MISS_NONE; } // Calculate spell hit result can be: // Every spell can: Evade/Immune/Reflect/Sucesful hit // For melee based spells: // Miss // Dodge // Parry // For spells // Resist SpellMissInfo Unit::SpellHitResult(Unit *pVictim, SpellEntry const *spell, bool CanReflect) { // Return evade for units in evade mode if (pVictim->GetTypeId() == TYPEID_UNIT && pVictim->ToCreature()->IsInEvadeMode() && this != pVictim) return SPELL_MISS_EVADE; // Check for immune if (pVictim->IsImmunedToSpell(spell)) return SPELL_MISS_IMMUNE; // All positive spells can`t miss // TODO: client not show miss log for this spells - so need find info for this in dbc and use it! if (IsPositiveSpell(spell->Id) && (!IsHostileTo(pVictim))) //prevent from affecting enemy by "positive" spell return SPELL_MISS_NONE; // Check for immune if (pVictim->IsImmunedToDamage(spell)) return SPELL_MISS_IMMUNE; if (this == pVictim) return SPELL_MISS_NONE; // Try victim reflect spell if (CanReflect) { int32 reflectchance = pVictim->GetTotalAuraModifier( SPELL_AURA_REFLECT_SPELLS); Unit::AuraEffectList const& mReflectSpellsSchool = pVictim->GetAuraEffectsByType(SPELL_AURA_REFLECT_SPELLS_SCHOOL); for (Unit::AuraEffectList::const_iterator i = mReflectSpellsSchool.begin(); i != mReflectSpellsSchool.end(); ++i) if ((*i)->GetMiscValue() & GetSpellSchoolMask(spell)) reflectchance += (*i)->GetAmount(); if (reflectchance > 0 && roll_chance_i(reflectchance)) { // Start triggers for remove charges if need (trigger only for victim, and mark as active spell) ProcDamageAndSpell(pVictim, PROC_FLAG_NONE, PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_NEG, PROC_EX_REFLECT, 1, BASE_ATTACK, spell); return SPELL_MISS_REFLECT; } } switch (spell->DmgClass) { case SPELL_DAMAGE_CLASS_RANGED: case SPELL_DAMAGE_CLASS_MELEE: return MeleeSpellHitResult(pVictim, spell); case SPELL_DAMAGE_CLASS_NONE: return SPELL_MISS_NONE; case SPELL_DAMAGE_CLASS_MAGIC: return MagicSpellHitResult(pVictim, spell); } return SPELL_MISS_NONE; } uint32 Unit::GetDefenseSkillValue(Unit const* target) const { if (GetTypeId() == TYPEID_PLAYER) { // in PvP use full skill instead current skill value uint32 value = (target && target->GetTypeId() == TYPEID_PLAYER) ? this->ToPlayer()->GetMaxSkillValue(SKILL_DEFENSE) : this->ToPlayer()->GetSkillValue(SKILL_DEFENSE); value += uint32( this->ToPlayer()->GetRatingBonusValue(CR_DEFENSE_SKILL)); return value; } else return GetUnitMeleeSkill(target); } float Unit::GetUnitDodgeChance() const { if (IsNonMeleeSpellCasted(false) || HasUnitState(UNIT_STAT_STUNNED)) return 0.0f; if (GetTypeId() == TYPEID_PLAYER) return GetFloatValue( PLAYER_DODGE_PERCENTAGE); else { if (((Creature const*) this)->isTotem()) return 0.0f; else { float dodge = 5.0f; dodge += GetTotalAuraModifier(SPELL_AURA_MOD_DODGE_PERCENT); return dodge > 0.0f ? dodge : 0.0f; } } } float Unit::GetUnitParryChance() const { if (IsNonMeleeSpellCasted(false) || HasUnitState(UNIT_STAT_STUNNED)) return 0.0f; float chance = 0.0f; if (GetTypeId() == TYPEID_PLAYER) { Player const* player = (Player const*) this; if (player->CanParry()) { Item *tmpitem = player->GetWeaponForAttack(BASE_ATTACK, true); if (!tmpitem) tmpitem = player->GetWeaponForAttack(OFF_ATTACK, true); if (tmpitem) chance = GetFloatValue(PLAYER_PARRY_PERCENTAGE); } } else if (GetTypeId() == TYPEID_UNIT) { if (GetCreatureType() == CREATURE_TYPE_HUMANOID) { chance = 5.0f; chance += GetTotalAuraModifier(SPELL_AURA_MOD_PARRY_PERCENT); } } return chance > 0.0f ? chance : 0.0f; } float Unit::GetUnitBlockChance() const { if (IsNonMeleeSpellCasted(false) || HasUnitState(UNIT_STAT_STUNNED)) return 0.0f; if (GetTypeId() == TYPEID_PLAYER) { Player const* player = (Player const*) this; if (player->CanBlock()) { Item *tmpitem = player->GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND); if (tmpitem && !tmpitem->IsBroken()) return GetFloatValue( PLAYER_BLOCK_PERCENTAGE); } // is player but has no block ability or no not broken shield equipped return 0.0f; } else { if (((Creature const*) this)->isTotem()) return 0.0f; else { float block = 5.0f; block += GetTotalAuraModifier(SPELL_AURA_MOD_BLOCK_PERCENT); return block > 0.0f ? block : 0.0f; } } } float Unit::GetUnitCriticalChance(WeaponAttackType attackType, const Unit *pVictim) const { float crit; if (GetTypeId() == TYPEID_PLAYER) { switch (attackType) { case BASE_ATTACK: crit = GetFloatValue(PLAYER_CRIT_PERCENTAGE); break; case OFF_ATTACK: crit = GetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE); break; case RANGED_ATTACK: crit = GetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE); break; // Just for good manner default: crit = 0.0f; break; } } else { crit = 5.0f; crit += GetTotalAuraModifier(SPELL_AURA_MOD_WEAPON_CRIT_PERCENT); crit += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_PCT); } // flat aura mods if (attackType == RANGED_ATTACK) crit += pVictim->GetTotalAuraModifier( SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_CHANCE); else crit += pVictim->GetTotalAuraModifier( SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE); crit += pVictim->GetTotalAuraModifier( SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE); // reduce crit chance from Rating for players if (attackType != RANGED_ATTACK) { // Glyph of barkskin if (pVictim->HasAura(63057) && pVictim->HasAura(22812)) crit -= 25.0f; } // Apply crit chance from defence skill crit += (int32(GetMaxSkillValueForLevel(pVictim)) - int32(pVictim->GetDefenseSkillValue(this))) * 0.04f; if (crit < 0.0f) crit = 0.0f; return crit; } uint32 Unit::GetWeaponSkillValue(WeaponAttackType attType, Unit const* target) const { uint32 value = 0; if (GetTypeId() == TYPEID_PLAYER) { Item* item = this->ToPlayer()->GetWeaponForAttack(attType, true); // feral or unarmed skill only for base attack if (attType != BASE_ATTACK && !item) return 0; if (IsInFeralForm()) return GetMaxSkillValueForLevel(); // always maximized SKILL_FERAL_COMBAT in fact // weapon skill or (unarmed for base attack and fist weapons) uint32 skill; if (item && item->GetSkill() != SKILL_FIST_WEAPONS) skill = item->GetSkill(); else skill = SKILL_UNARMED; // in PvP use full skill instead current skill value value = (target && target->IsControlledByPlayer()) ? this->ToPlayer()->GetMaxSkillValue(skill) : this->ToPlayer()->GetSkillValue(skill); // Modify value from ratings value += uint32(this->ToPlayer()->GetRatingBonusValue(CR_WEAPON_SKILL)); switch (attType) { case BASE_ATTACK: value += uint32( this->ToPlayer()->GetRatingBonusValue( CR_WEAPON_SKILL_MAINHAND)); break; case OFF_ATTACK: value += uint32( this->ToPlayer()->GetRatingBonusValue( CR_WEAPON_SKILL_OFFHAND)); break; case RANGED_ATTACK: value += uint32( this->ToPlayer()->GetRatingBonusValue( CR_WEAPON_SKILL_RANGED)); break; default: break; } } else value = GetUnitMeleeSkill(target); return value; } void Unit::_DeleteRemovedAuras() { while (!m_removedAuras.empty()) { delete m_removedAuras.front(); m_removedAuras.pop_front(); } } void Unit::_UpdateSpells(uint32 time) { if (m_currentSpells [CURRENT_AUTOREPEAT_SPELL]) _UpdateAutoRepeatSpell(); // remove finished spells from current pointers for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i) { if (m_currentSpells [i] && m_currentSpells [i]->getState() == SPELL_STATE_FINISHED) { m_currentSpells [i]->SetReferencedFromCurrent(false); m_currentSpells [i] = NULL; // remove pointer } } // m_auraUpdateIterator can be updated in indirect called code at aura remove to skip next planned to update but removed auras for (m_auraUpdateIterator = m_ownedAuras.begin(); m_auraUpdateIterator != m_ownedAuras.end();) { Aura * i_aura = m_auraUpdateIterator->second; ++m_auraUpdateIterator; // need shift to next for allow update if need into aura update i_aura->UpdateOwner(time, this); } // remove expired auras - do that after updates(used in scripts?) for (AuraMap::iterator i = m_ownedAuras.begin(); i != m_ownedAuras.end();) { if (i->second->IsExpired()) RemoveOwnedAura(i, AURA_REMOVE_BY_EXPIRE); else ++i; } for (VisibleAuraMap::iterator itr = m_visibleAuras.begin(); itr != m_visibleAuras.end(); ++itr) if (itr->second->IsNeedClientUpdate()) itr->second->ClientUpdate(); _DeleteRemovedAuras(); if (!m_gameObj.empty()) { GameObjectList::iterator itr; for (itr = m_gameObj.begin(); itr != m_gameObj.end();) { if (!(*itr)->isSpawned()) { (*itr)->SetOwnerGUID(0); (*itr)->SetRespawnTime(0); (*itr)->Delete(); m_gameObj.erase(itr++); } else ++itr; } } } void Unit::_UpdateAutoRepeatSpell() { //check "realtime" interrupts if ((GetTypeId() == TYPEID_PLAYER && ((Player*) this)->isMoving()) || IsNonMeleeSpellCasted( false, false, true, m_currentSpells [CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id == 75)) { // cancel wand shoot if (m_currentSpells [CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != 75) InterruptSpell( CURRENT_AUTOREPEAT_SPELL); m_AutoRepeatFirstCast = true; return; } //apply delay (Auto Shot (spellID 75) not affected) if (m_AutoRepeatFirstCast && getAttackTimer(RANGED_ATTACK) < 500 && m_currentSpells [CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != 75) setAttackTimer( RANGED_ATTACK, 500); m_AutoRepeatFirstCast = false; //castroutine if (isAttackReady(RANGED_ATTACK)) { // Check if able to cast if (m_currentSpells [CURRENT_AUTOREPEAT_SPELL]->CheckCast(true) != SPELL_CAST_OK) { InterruptSpell(CURRENT_AUTOREPEAT_SPELL); return; } // we want to shoot Spell* spell = new Spell(this, m_currentSpells [CURRENT_AUTOREPEAT_SPELL]->m_spellInfo, true); spell->prepare( &(m_currentSpells [CURRENT_AUTOREPEAT_SPELL]->m_targets)); // all went good, reset attack resetAttackTimer(RANGED_ATTACK); } } void Unit::SetCurrentCastedSpell(Spell * pSpell) { ASSERT(pSpell); // NULL may be never passed here, use InterruptSpell or InterruptNonMeleeSpells CurrentSpellTypes CSpellType = pSpell->GetCurrentContainer(); if (pSpell == m_currentSpells [CSpellType]) return; // avoid breaking self // break same type spell if it is not delayed InterruptSpell(CSpellType, false); // special breakage effects: switch (CSpellType) { case CURRENT_GENERIC_SPELL: { // generic spells always break channeled not delayed spells InterruptSpell(CURRENT_CHANNELED_SPELL, false); // autorepeat breaking if (m_currentSpells [CURRENT_AUTOREPEAT_SPELL]) { // break autorepeat if not Auto Shot if (m_currentSpells [CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != 75) InterruptSpell(CURRENT_AUTOREPEAT_SPELL); m_AutoRepeatFirstCast = true; } AddUnitState(UNIT_STAT_CASTING); } break; case CURRENT_CHANNELED_SPELL: { // channel spells always break generic non-delayed and any channeled spells InterruptSpell(CURRENT_GENERIC_SPELL, false); InterruptSpell(CURRENT_CHANNELED_SPELL); // it also does break autorepeat if not Auto Shot if (m_currentSpells [CURRENT_AUTOREPEAT_SPELL] && m_currentSpells [CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != 75) InterruptSpell(CURRENT_AUTOREPEAT_SPELL); AddUnitState(UNIT_STAT_CASTING); } break; case CURRENT_AUTOREPEAT_SPELL: { // only Auto Shoot does not break anything if (pSpell->m_spellInfo->Id != 75) { // generic autorepeats break generic non-delayed and channeled non-delayed spells InterruptSpell(CURRENT_GENERIC_SPELL, false); InterruptSpell(CURRENT_CHANNELED_SPELL, false); } // special action: set first cast flag m_AutoRepeatFirstCast = true; } break; default: { // other spell types don't break anything now } break; } // current spell (if it is still here) may be safely deleted now if (m_currentSpells [CSpellType]) m_currentSpells [CSpellType]->SetReferencedFromCurrent( false); // set new current spell m_currentSpells [CSpellType] = pSpell; pSpell->SetReferencedFromCurrent(true); pSpell->m_selfContainer = &(m_currentSpells [pSpell->GetCurrentContainer()]); } void Unit::InterruptSpell(CurrentSpellTypes spellType, bool withDelayed, bool withInstant) { ASSERT(spellType < CURRENT_MAX_SPELL); //sLog->outDebug(LOG_FILTER_UNITS, "Interrupt spell for unit %u.", GetEntry()); Spell *spell = m_currentSpells [spellType]; if (spell && (withDelayed || spell->getState() != SPELL_STATE_DELAYED) && (withInstant || spell->GetCastTime() > 0)) { // for example, do not let self-stun aura interrupt itself if (!spell->IsInterruptable()) return; // send autorepeat cancel message for autorepeat spells if (spellType == CURRENT_AUTOREPEAT_SPELL) if (GetTypeId() == TYPEID_PLAYER) ToPlayer()->SendAutoRepeatCancel( this); if (spell->getState() != SPELL_STATE_FINISHED) spell->cancel(); m_currentSpells [spellType] = NULL; spell->SetReferencedFromCurrent(false); } } void Unit::FinishSpell(CurrentSpellTypes spellType, bool ok /*= true*/) { Spell* spell = m_currentSpells [spellType]; if (!spell) return; if (spellType == CURRENT_CHANNELED_SPELL) spell->SendChannelUpdate(0); spell->finish(ok); } bool Unit::IsNonMeleeSpellCasted(bool withDelayed, bool skipChanneled, bool skipAutorepeat, bool isAutoshoot, bool skipInstant) const { // We don't do loop here to explicitly show that melee spell is excluded. // Maybe later some special spells will be excluded too. // if checkInstant then instant spells shouldn't count as being casted if (!skipInstant && m_currentSpells [CURRENT_GENERIC_SPELL] && !m_currentSpells [CURRENT_GENERIC_SPELL]->GetCastTime()) return false; // generic spells are casted when they are not finished and not delayed if (m_currentSpells [CURRENT_GENERIC_SPELL] && (m_currentSpells [CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_FINISHED) && (withDelayed || m_currentSpells [CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_DELAYED)) { if (!isAutoshoot || !(m_currentSpells [CURRENT_GENERIC_SPELL]->m_spellInfo->AttributesEx2 & SPELL_ATTR2_NOT_RESET_AUTO_ACTIONS)) return (true); } // channeled spells may be delayed, but they are still considered casted else if (!skipChanneled && m_currentSpells [CURRENT_CHANNELED_SPELL] && (m_currentSpells [CURRENT_CHANNELED_SPELL]->getState() != SPELL_STATE_FINISHED)) { if (!isAutoshoot || !(m_currentSpells [CURRENT_CHANNELED_SPELL]->m_spellInfo->AttributesEx2 & SPELL_ATTR2_NOT_RESET_AUTO_ACTIONS)) return (true); } // autorepeat spells may be finished or delayed, but they are still considered casted else if (!skipAutorepeat && m_currentSpells [CURRENT_AUTOREPEAT_SPELL]) return (true); return (false); } void Unit::InterruptNonMeleeSpells(bool withDelayed, uint32 spell_id, bool withInstant) { // generic spells are interrupted if they are not finished or delayed if (m_currentSpells [CURRENT_GENERIC_SPELL] && (!spell_id || m_currentSpells [CURRENT_GENERIC_SPELL]->m_spellInfo->Id == spell_id)) InterruptSpell(CURRENT_GENERIC_SPELL, withDelayed, withInstant); // autorepeat spells are interrupted if they are not finished or delayed if (m_currentSpells [CURRENT_AUTOREPEAT_SPELL] && (!spell_id || m_currentSpells [CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id == spell_id)) InterruptSpell( CURRENT_AUTOREPEAT_SPELL, withDelayed, withInstant); // channeled spells are interrupted if they are not finished, even if they are delayed if (m_currentSpells [CURRENT_CHANNELED_SPELL] && (!spell_id || m_currentSpells [CURRENT_CHANNELED_SPELL]->m_spellInfo->Id == spell_id)) InterruptSpell( CURRENT_CHANNELED_SPELL, true, true); } bool Unit::CanCastWhileWalking(const SpellEntry * const sp) { AuraEffectList alist = GetAuraEffectsByType(SPELL_AURA_CAST_WHILE_WALKING); for (AuraEffectList::const_iterator i = alist.begin(); i != alist.end(); ++i) { // check that spell mask matches if (!((*i)->GetSpellProto()->EffectSpellClassMask [(*i)->GetEffIndex()] & sp->SpellFamilyFlags)) continue; return true; } return false; } Spell* Unit::FindCurrentSpellBySpellId(uint32 spell_id) const { for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++) if (m_currentSpells [i] && m_currentSpells [i]->m_spellInfo->Id == spell_id) return m_currentSpells [i]; return NULL; } int32 Unit::GetCurrentSpellCastTime(uint32 spell_id) const { if (Spell const * spell = FindCurrentSpellBySpellId(spell_id)) return spell->GetCastTime(); return 0; } bool Unit::isInFrontInMap(Unit const* target, float distance, float arc) const { return IsWithinDistInMap(target, distance) && HasInArc(arc, target); } bool Unit::isInBackInMap(Unit const* target, float distance, float arc) const { return IsWithinDistInMap(target, distance) && !HasInArc(2 * M_PI - arc, target); } void Unit::SetFacingToObject(WorldObject* pObject) { // update orientation at server SetOrientation(GetAngle(pObject)); // and client WorldPacket data; BuildHeartBeatMsg(&data); SendMessageToSet(&data, false); } bool Unit::isInAccessiblePlaceFor(Creature const* c) const { if (IsInWater()) return c->canSwim(); else return c->canWalk() || c->canFly(); } bool Unit::IsInWater() const { return GetBaseMap()->IsInWater(GetPositionX(), GetPositionY(), GetPositionZ()); } bool Unit::IsUnderWater() const { return GetBaseMap()->IsUnderWater(GetPositionX(), GetPositionY(), GetPositionZ()); } void Unit::DeMorph() { SetDisplayId(GetNativeDisplayId()); } void Unit::_AddAura(UnitAura * aura, Unit * caster) { ASSERT(!m_cleanupDone); m_ownedAuras.insert(AuraMap::value_type(aura->GetId(), aura)); // passive and Incanter's Absorption and auras with different type can stack with themselves any number of times if (!aura->IsPassive() && aura->GetId() != 44413) { // find current aura from spell and change it's stackamount if (Aura * foundAura = GetOwnedAura(aura->GetId(), aura->GetCasterGUID(), (sSpellMgr->GetSpellCustomAttr(aura->GetId()) & SPELL_ATTR0_CU_ENCHANT_PROC) ? aura->GetCastItemGUID() : 0, 0, aura)) { if (aura->GetSpellProto()->StackAmount) { aura->ModStackAmount(foundAura->GetStackAmount()); } // Update periodic timers from the previous aura // ToDo Fix me /*for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { AuraEffect *existingEff = foundAura->GetEffect(i); AuraEffect *newEff = aura->GetEffect(i); if (!existingEff || !newEff) continue; newEff->SetPeriodicTimer(existingEff->GetPeriodicTimer()); }*/ // Use the new one to replace the old one // This is the only place where AURA_REMOVE_BY_STACK should be used RemoveOwnedAura(foundAura, AURA_REMOVE_BY_STACK); } } _RemoveNoStackAurasDueToAura(aura); if (aura->IsRemoved()) return; aura->SetIsSingleTarget( caster && IsSingleTargetSpell(aura->GetSpellProto())); if (aura->IsSingleTarget()) { ASSERT((IsInWorld() && !IsDuringRemoveFromWorld()) || (aura->GetCasterGUID() == GetGUID())); // register single target aura caster->GetSingleCastAuras().push_back(aura); // remove other single target auras Unit::AuraList& scAuras = caster->GetSingleCastAuras(); for (Unit::AuraList::iterator itr = scAuras.begin(); itr != scAuras.end();) { if ((*itr) != aura && IsSingleTargetSpells((*itr)->GetSpellProto(), aura->GetSpellProto())) { (*itr)->Remove(); itr = scAuras.begin(); } else ++itr; } } } // creates aura application instance and registers it in lists // aura application effects are handled separately to prevent aura list corruption AuraApplication * Unit::_CreateAuraApplication(Aura * aura, uint8 effMask) { // can't apply aura on unit which is going to be deleted - to not create a memory leak ASSERT(!m_cleanupDone); // aura musn't be removed ASSERT(!aura->IsRemoved()); SpellEntry const* aurSpellInfo = aura->GetSpellProto(); uint32 aurId = aurSpellInfo->Id; // ghost spell check, allow apply any auras at player loading in ghost mode (will be cleanup after load) if (!isAlive() && !IsDeathPersistentSpell(aurSpellInfo) && (GetTypeId() != TYPEID_PLAYER || !this->ToPlayer()->GetSession()->PlayerLoading())) return NULL; Unit * caster = aura->GetCaster(); AuraApplication * aurApp = new AuraApplication(this, caster, aura, effMask); m_appliedAuras.insert(AuraApplicationMap::value_type(aurId, aurApp)); if (aurSpellInfo->AuraInterruptFlags) { m_interruptableAuras.push_back(aurApp); AddInterruptMask(aurSpellInfo->AuraInterruptFlags); } if (AuraState aState = GetSpellAuraState(aura->GetSpellProto())) m_auraStateAuras.insert( AuraStateAurasMap::value_type(aState, aurApp)); aura->_ApplyForTarget(this, caster, aurApp); return aurApp; } void Unit::_ApplyAuraEffect(Aura * aura, uint8 effIndex) { ASSERT(aura); ASSERT(aura->HasEffect(effIndex)); AuraApplication * aurApp = aura->GetApplicationOfTarget(GetGUID()); ASSERT(aurApp); if (!aurApp->GetEffectMask()) _ApplyAura(aurApp, 1 << effIndex); else aurApp->_HandleEffect(effIndex, true); } // handles effects of aura application // should be done after registering aura in lists void Unit::_ApplyAura(AuraApplication * aurApp, uint8 effMask) { Aura * aura = aurApp->GetBase(); _RemoveNoStackAurasDueToAura(aura); if (aurApp->GetRemoveMode()) return; // Update target aura state flag if (AuraState aState = GetSpellAuraState(aura->GetSpellProto())) ModifyAuraState( aState, true); if (aurApp->GetRemoveMode()) return; // Sitdown on apply aura req seated if (aura->GetSpellProto()->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED && !IsSitState()) SetStandState( UNIT_STAND_STATE_SIT); Unit * caster = aura->GetCaster(); if (aurApp->GetRemoveMode()) return; aura->HandleAuraSpecificMods(aurApp, caster, true, false); // apply effects of the aura for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (effMask & 1 << i && (!aurApp->GetRemoveMode())) aurApp->_HandleEffect( i, true); } } // removes aura application from lists and unapplies effects void Unit::_UnapplyAura(AuraApplicationMap::iterator &i, AuraRemoveMode removeMode) { AuraApplication * aurApp = i->second; ASSERT(aurApp); ASSERT(!aurApp->GetRemoveMode()); ASSERT(aurApp->GetTarget() == this); aurApp->SetRemoveMode(removeMode); Aura * aura = aurApp->GetBase(); sLog->outDebug(LOG_FILTER_UNITS, "Aura %u now is remove mode %d", aura->GetId(), removeMode); // dead loop is killing the server probably ASSERT(m_removedAurasCount < 0xFFFFFFFF); ++m_removedAurasCount; Unit * caster = aura->GetCaster(); // Remove all pointers from lists here to prevent possible pointer invalidation on spellcast/auraapply/auraremove m_appliedAuras.erase(i); if (aura->GetSpellProto()->AuraInterruptFlags) { m_interruptableAuras.remove(aurApp); UpdateInterruptMask(); } bool auraStateFound = false; AuraState auraState = GetSpellAuraState(aura->GetSpellProto()); if (auraState) { bool canBreak = false; // Get mask of all aurastates from remaining auras for (AuraStateAurasMap::iterator itr = m_auraStateAuras.lower_bound( auraState); itr != m_auraStateAuras.upper_bound(auraState) && !(auraStateFound && canBreak);) { if (itr->second == aurApp) { m_auraStateAuras.erase(itr); itr = m_auraStateAuras.lower_bound(auraState); canBreak = true; continue; } auraStateFound = true; ++itr; } } aurApp->_Remove(); aura->_UnapplyForTarget(this, caster, aurApp); // remove effects of the spell - needs to be done after removing aura from lists for (uint8 itr = 0; itr < MAX_SPELL_EFFECTS; ++itr) { if (aurApp->HasEffect(itr)) aurApp->_HandleEffect(itr, false); } // all effect mustn't be applied ASSERT(!aurApp->GetEffectMask()); // Remove totem at next update if totem looses its aura if (aurApp->GetRemoveMode() == AURA_REMOVE_BY_EXPIRE && GetTypeId() == TYPEID_UNIT && this->ToCreature()->isTotem() && this->ToTotem()->GetSummonerGUID() == aura->GetCasterGUID()) { if (this->ToTotem()->GetSpell() == aura->GetId() && this->ToTotem()->GetTotemType() == TOTEM_PASSIVE) this->ToTotem()->setDeathState( JUST_DIED); } // Remove aurastates only if were not found if (!auraStateFound) ModifyAuraState(auraState, false); aura->HandleAuraSpecificMods(aurApp, caster, false, false); // only way correctly remove all auras from list //if (removedAuras != m_removedAurasCount) new aura may be added i = m_appliedAuras.begin(); } void Unit::_UnapplyAura(AuraApplication * aurApp, AuraRemoveMode removeMode) { // aura can be removed from unit only if it's applied on it, shouldn't happen ASSERT(aurApp->GetBase()->GetApplicationOfTarget(GetGUID()) == aurApp); uint32 spellId = aurApp->GetBase()->GetId(); for (AuraApplicationMap::iterator iter = m_appliedAuras.lower_bound( spellId); iter != m_appliedAuras.upper_bound(spellId);) { if (iter->second == aurApp) { _UnapplyAura(iter, removeMode); return; } else ++iter; } ASSERT(false); } void Unit::_RemoveNoStackAuraApplicationsDueToAura(Aura * aura) { // dynobj auras can stack infinite number of times if (aura->GetType() == DYNOBJ_AURA_TYPE) return; SpellEntry const* spellProto = aura->GetSpellProto(); uint32 spellId = spellProto->Id; // passive spell special case (only non stackable with ranks) if (IsPassiveSpell(spellId) && IsPassiveSpellStackableWithRanks(spellProto)) return; bool remove = false; for (AuraApplicationMap::iterator i = m_appliedAuras.begin(); i != m_appliedAuras.end(); ++i) { if (remove) { remove = false; i = m_appliedAuras.begin(); } if (!_IsNoStackAuraDueToAura(aura, i->second->GetBase())) continue; RemoveAura(i, AURA_REMOVE_BY_DEFAULT); if (i == m_appliedAuras.end()) break; remove = true; } } void Unit::_RemoveNoStackAurasDueToAura(Aura * aura) { SpellEntry const* spellProto = aura->GetSpellProto(); uint32 spellId = spellProto->Id; // passive spell special case (only non stackable with ranks) if (IsPassiveSpell(spellId) && IsPassiveSpellStackableWithRanks(spellProto)) return; bool remove = false; for (AuraMap::iterator i = m_ownedAuras.begin(); i != m_ownedAuras.end(); ++i) { if (remove) { remove = false; i = m_ownedAuras.begin(); } if (!_IsNoStackAuraDueToAura(aura, i->second)) continue; RemoveOwnedAura(i, AURA_REMOVE_BY_DEFAULT); if (i == m_ownedAuras.end()) break; remove = true; } } bool Unit::_IsNoStackAuraDueToAura(Aura * appliedAura, Aura * existingAura) const { SpellEntry const* spellProto = appliedAura->GetSpellProto(); // Do not check already applied aura if (existingAura == appliedAura) return false; // Do not check dynobj auras for stacking if (existingAura->GetType() != UNIT_AURA_TYPE) return false; SpellEntry const* i_spellProto = existingAura->GetSpellProto(); uint32 i_spellId = i_spellProto->Id; bool sameCaster = appliedAura->GetCasterGUID() == existingAura->GetCasterGUID(); if (IsPassiveSpell(i_spellId)) { // passive non-stackable spells not stackable only for same caster if (!sameCaster) return false; // passive non-stackable spells not stackable only with another rank of same spell if (!sSpellMgr->IsRankSpellDueToSpell(spellProto, i_spellId)) return false; } bool is_triggered_by_spell = false; // prevent triggering aura of removing aura that triggered it // prevent triggered aura of removing aura that triggering it (triggered effect early some aura of parent spell for (uint8 j = 0; j < MAX_SPELL_EFFECTS; ++j) { if (i_spellProto->EffectTriggerSpell [j] == spellProto->Id || spellProto->EffectTriggerSpell [j] == i_spellProto->Id) // I do not know what is this for { is_triggered_by_spell = true; break; } } if (is_triggered_by_spell) return false; if (sSpellMgr->CanAurasStack(appliedAura, existingAura, sameCaster)) return false; return true; } void Unit::_RegisterAuraEffect(AuraEffect * aurEff, bool apply) { if (apply) m_modAuras [aurEff->GetAuraType()].push_back(aurEff); else m_modAuras [aurEff->GetAuraType()].remove(aurEff); } // All aura base removes should go threw this function! void Unit::RemoveOwnedAura(AuraMap::iterator &i, AuraRemoveMode removeMode) { Aura * aura = i->second; ASSERT(!aura->IsRemoved()); // if unit currently update aura list then make safe update iterator shift to next if (m_auraUpdateIterator == i) ++m_auraUpdateIterator; m_ownedAuras.erase(i); m_removedAuras.push_back(aura); // Unregister single target aura if (aura->IsSingleTarget()) aura->UnregisterSingleTarget(); aura->_Remove(removeMode); i = m_ownedAuras.begin(); } void Unit::RemoveOwnedAura(uint32 spellId, uint64 caster, uint8 reqEffMask, AuraRemoveMode removeMode) { for (AuraMap::iterator itr = m_ownedAuras.lower_bound(spellId); itr != m_ownedAuras.upper_bound(spellId);) if (((itr->second->GetEffectMask() & reqEffMask) == reqEffMask) && (!caster || itr->second->GetCasterGUID() == caster)) { RemoveOwnedAura(itr, removeMode); itr = m_ownedAuras.lower_bound(spellId); } else ++itr; } void Unit::RemoveOwnedAura(Aura * aura, AuraRemoveMode removeMode) { if (aura->IsRemoved()) return; ASSERT(aura->GetOwner() == this); uint32 spellId = aura->GetId(); for (AuraMap::iterator itr = m_ownedAuras.lower_bound(spellId); itr != m_ownedAuras.upper_bound(spellId); ++itr) if (itr->second == aura) { RemoveOwnedAura(itr, removeMode); return; } ASSERT(false); } Aura * Unit::GetOwnedAura(uint32 spellId, uint64 casterGUID, uint64 itemCasterGUID, uint8 reqEffMask, Aura* except) const { for (AuraMap::const_iterator itr = m_ownedAuras.lower_bound(spellId); itr != m_ownedAuras.upper_bound(spellId); ++itr) if (((itr->second->GetEffectMask() & reqEffMask) == reqEffMask) && (!casterGUID || itr->second->GetCasterGUID() == casterGUID) && (!itemCasterGUID || itr->second->GetCastItemGUID() == itemCasterGUID) && (!except || except != itr->second)) return itr->second; return NULL; } void Unit::RemoveAura(AuraApplicationMap::iterator &i, AuraRemoveMode mode) { AuraApplication * aurApp = i->second; // Do not remove aura which is already being removed if (aurApp->GetRemoveMode()) return; Aura * aura = aurApp->GetBase(); _UnapplyAura(i, mode); // Remove aura - for Area and Target auras if (aura->GetOwner() == this) aura->Remove(mode); } void Unit::RemoveAura(uint32 spellId, uint64 caster, uint8 reqEffMask, AuraRemoveMode removeMode) { for (AuraApplicationMap::iterator iter = m_appliedAuras.lower_bound( spellId); iter != m_appliedAuras.upper_bound(spellId);) { Aura const * aura = iter->second->GetBase(); if (((aura->GetEffectMask() & reqEffMask) == reqEffMask) && (!caster || aura->GetCasterGUID() == caster)) { RemoveAura(iter, removeMode); return; } else ++iter; } } void Unit::RemoveAura(AuraApplication * aurApp, AuraRemoveMode mode) { ASSERT(aurApp->GetBase()->GetApplicationOfTarget(GetGUID()) == aurApp); // no need to remove if (aurApp->GetRemoveMode() || aurApp->GetBase()->IsRemoved()) return; uint32 spellId = aurApp->GetBase()->GetId(); for (AuraApplicationMap::iterator iter = m_appliedAuras.lower_bound( spellId); iter != m_appliedAuras.upper_bound(spellId);) { if (aurApp == iter->second) { RemoveAura(iter, mode); return; } else ++iter; } } void Unit::RemoveAura(Aura * aura, AuraRemoveMode mode) { if (aura->IsRemoved()) return; if (AuraApplication * aurApp = aura->GetApplicationOfTarget(GetGUID())) RemoveAura( aurApp, mode); else ASSERT(false); } void Unit::RemoveAurasDueToSpell(uint32 spellId, uint64 caster, uint8 reqEffMask, AuraRemoveMode removeMode) { for (AuraApplicationMap::iterator iter = m_appliedAuras.lower_bound( spellId); iter != m_appliedAuras.upper_bound(spellId);) { Aura const * aura = iter->second->GetBase(); if (((aura->GetEffectMask() & reqEffMask) == reqEffMask) && (!caster || aura->GetCasterGUID() == caster)) { RemoveAura(iter, removeMode); iter = m_appliedAuras.lower_bound(spellId); } else ++iter; } } void Unit::RemoveAuraFromStack(uint32 spellId, uint64 caster, AuraRemoveMode removeMode) { for (AuraMap::iterator iter = m_ownedAuras.lower_bound(spellId); iter != m_ownedAuras.upper_bound(spellId);) { Aura const * aura = iter->second; if ((aura->GetType() == UNIT_AURA_TYPE) && (!caster || aura->GetCasterGUID() == caster)) { RemoveAuraFromStack(iter, removeMode); return; } else ++iter; } } inline void Unit::RemoveAuraFromStack(AuraMap::iterator &iter, AuraRemoveMode removeMode) { if (iter->second->ModStackAmount(-1)) RemoveOwnedAura(iter, removeMode); } void Unit::RemoveAurasDueToSpellByDispel(uint32 spellId, uint64 casterGUID, Unit *dispeller) { for (AuraMap::iterator iter = m_ownedAuras.lower_bound(spellId); iter != m_ownedAuras.upper_bound(spellId);) { Aura * aura = iter->second; if (aura->GetCasterGUID() == casterGUID) { if (aura->GetSpellProto()->AttributesEx7 & SPELL_ATTR7_DISPEL_CHARGES) aura->DropCharge(); else RemoveAuraFromStack(iter, AURA_REMOVE_BY_ENEMY_SPELL); // Unstable Affliction (crash if before removeaura?) if (aura->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK && (aura->GetSpellProto()->SpellFamilyFlags [1] & 0x0100)) { if (AuraEffect const * aurEff = aura->GetEffect(0)) { int32 damage = aurEff->GetAmount() * 9; // backfire damage and silence dispeller->CastCustomSpell(dispeller, 31117, &damage, NULL, NULL, true, NULL, NULL, aura->GetCasterGUID()); } } // Flame Shock if (aura->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN && (aura->GetSpellProto()->SpellFamilyFlags [0] & 0x10000000)) { Unit * caster = aura->GetCaster(); if (caster) { uint32 triggeredSpellId = 0; // Lava Flows if (AuraEffect const * aurEff = caster->GetDummyAuraEffect(SPELLFAMILY_SHAMAN, 3087, 0)) { switch (aurEff->GetId()) { case 51482: // Rank 3 triggeredSpellId = 65264; break; case 51481: // Rank 2 triggeredSpellId = 65263; break; case 51480: // Rank 1 triggeredSpellId = 64694; break; default: sLog->outError( "Aura::HandleAuraSpecificMods: Unknown rank of Lava Flows (%d) found", aurEff->GetId()); } } if (triggeredSpellId) caster->CastSpell(caster, triggeredSpellId, true); } } // Wyvern Sting if (aura->GetSpellProto()->SpellFamilyName == SPELLFAMILY_HUNTER && (aura->GetSpellProto()->SpellFamilyFlags [1] & 0x1000)) { Unit * caster = aura->GetCaster(); if (caster && !(dispeller->GetTypeId() == TYPEID_UNIT && dispeller->ToCreature()->isTotem())) // Noxious Stings if (AuraEffect * auraEff = caster->GetAuraEffect(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS, SPELLFAMILY_HUNTER, 3521, 1)) if (Aura * newAura = caster->AddAura(aura->GetId(), dispeller)) newAura->SetDuration( aura->GetDuration() / 100 * auraEff->GetAmount()); } return; } else ++iter; } } void Unit::RemoveAurasDueToSpellBySteal(uint32 spellId, uint64 casterGUID, Unit *stealer) { for (AuraMap::iterator iter = m_ownedAuras.lower_bound(spellId); iter != m_ownedAuras.upper_bound(spellId);) { Aura * aura = iter->second; if (aura->GetCasterGUID() == casterGUID) { int32 damage [MAX_SPELL_EFFECTS]; int32 baseDamage [MAX_SPELL_EFFECTS]; uint8 effMask = 0; uint8 recalculateMask = 0; Unit * caster = aura->GetCaster(); for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (aura->GetEffect(i)) { baseDamage [i] = aura->GetEffect(i)->GetBaseAmount(); damage [i] = aura->GetEffect(i)->GetAmount(); effMask |= (1 << i); if (aura->GetEffect(i)->CanBeRecalculated()) recalculateMask |= (1 << i); } else { baseDamage [i] = NULL; damage [i] = NULL; } } bool stealCharge = aura->GetSpellProto()->AttributesEx7 & SPELL_ATTR7_DISPEL_CHARGES; bool stealStack = aura->GetSpellProto()->StackAmount > 1; int32 dur = (2 * MINUTE * IN_MILLISECONDS < aura->GetDuration() || aura->GetDuration() < 0) ? 2 * MINUTE * IN_MILLISECONDS : aura->GetDuration(); if (Aura * newAura = (stealCharge || stealStack) ? stealer->GetAura(aura->GetId(), aura->GetCasterGUID()) : NULL) { if (stealCharge) { uint8 newCharges = newAura->GetCharges() + 1; uint8 maxCharges = newAura->GetSpellProto()->procCharges; // We must be able to steal as much charges as original caster can have if (caster) if (Player* modOwner = caster->GetSpellModOwner()) modOwner->ApplySpellMod( aura->GetId(), SPELLMOD_CHARGES, maxCharges); newAura->SetCharges( maxCharges < newCharges ? maxCharges : newCharges); } else { uint8 newStacks = newAura->GetStackAmount() + 1; uint8 maxStacks = newAura->GetSpellProto()->StackAmount; newAura->SetStackAmount( maxStacks < newStacks ? maxStacks : newStacks); } newAura->SetDuration(dur); } else { bool isSingleTarget = aura->IsSingleTarget() && caster; if (isSingleTarget) aura->UnregisterSingleTarget(); newAura = Aura::TryCreate(aura->GetSpellProto(), effMask, stealer, NULL, &baseDamage [0], NULL, aura->GetCasterGUID()); // strange but intended behaviour: Stolen single target auras won't be treated as single targeted if (newAura && isSingleTarget) { aura->SetIsSingleTarget(true); caster->GetSingleCastAuras().push_back(aura); newAura->UnregisterSingleTarget(); } if (!newAura) return; newAura->SetLoadedState(dur, dur, stealCharge ? 1 : aura->GetCharges(), 1, recalculateMask, &damage [0]); newAura->ApplyForTargets(); } if (stealCharge) aura->DropCharge(); else RemoveAuraFromStack(iter, AURA_REMOVE_BY_ENEMY_SPELL); return; } else ++iter; } } void Unit::RemoveAurasDueToItemSpell(Item* castItem, uint32 spellId) { for (AuraApplicationMap::iterator iter = m_appliedAuras.lower_bound( spellId); iter != m_appliedAuras.upper_bound(spellId);) { if (!castItem || iter->second->GetBase()->GetCastItemGUID() == castItem->GetGUID()) { RemoveAura(iter); iter = m_appliedAuras.upper_bound(spellId); // overwrite by more appropriate } else ++iter; } } void Unit::RemoveAurasByType(AuraType auraType, uint64 casterGUID, Aura * except, bool negative, bool positive) { for (AuraEffectList::iterator iter = m_modAuras [auraType].begin(); iter != m_modAuras [auraType].end();) { Aura * aura = (*iter)->GetBase(); AuraApplication * aurApp = aura->GetApplicationOfTarget(GetGUID()); ++iter; if (aura != except && (!casterGUID || aura->GetCasterGUID() == casterGUID) && ((negative && !aurApp->IsPositive()) || (positive && aurApp->IsPositive()))) { uint32 removedAuras = m_removedAurasCount; RemoveAura(aurApp); if (m_removedAurasCount > removedAuras + 1) iter = m_modAuras [auraType].begin(); } } } void Unit::RemoveAurasWithAttribute(uint32 flags) { for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();) { SpellEntry const *spell = iter->second->GetBase()->GetSpellProto(); if (spell->Attributes & flags) RemoveAura(iter); else ++iter; } } void Unit::RemoveNotOwnSingleTargetAuras(uint32 newPhase) { // single target auras from other casters for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();) { AuraApplication const * aurApp = iter->second; Aura const * aura = aurApp->GetBase(); if (aura->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(aura->GetSpellProto())) { if (!newPhase) RemoveAura(iter); else { Unit* caster = aura->GetCaster(); if (!caster || !caster->InSamePhase(newPhase)) RemoveAura(iter); else ++iter; } } else ++iter; } // single target auras at other targets AuraList& scAuras = GetSingleCastAuras(); for (AuraList::iterator iter = scAuras.begin(); iter != scAuras.end();) { Aura * aura = *iter; if (aura->GetUnitOwner() != this && !aura->GetUnitOwner()->InSamePhase(newPhase)) { aura->Remove(); iter = scAuras.begin(); } else ++iter; } } void Unit::RemoveAurasWithInterruptFlags(uint32 flag, uint32 except) { if (!(m_interruptMask & flag)) return; // interrupt auras for (AuraApplicationList::iterator iter = m_interruptableAuras.begin(); iter != m_interruptableAuras.end();) { Aura * aura = (*iter)->GetBase(); ++iter; if ((aura->GetSpellProto()->AuraInterruptFlags & flag) && (!except || aura->GetId() != except)) { uint32 removedAuras = m_removedAurasCount; RemoveAura(aura); if (m_removedAurasCount > removedAuras + 1) iter = m_interruptableAuras.begin(); } } // interrupt channeled spell if (Spell* spell = m_currentSpells[CURRENT_CHANNELED_SPELL]) if (spell->getState() == SPELL_STATE_CASTING && (spell->m_spellInfo->ChannelInterruptFlags & flag) && spell->m_spellInfo->Id != except) InterruptNonMeleeSpells(false); UpdateInterruptMask(); } void Unit::RemoveAurasWithFamily(SpellFamilyNames family, uint32 familyFlag1, uint32 familyFlag2, uint32 familyFlag3, uint64 casterGUID) { for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();) { Aura const * aura = iter->second->GetBase(); if (!casterGUID || aura->GetCasterGUID() == casterGUID) { SpellEntry const *spell = aura->GetSpellProto(); if (spell->SpellFamilyName == uint32(family) && spell->SpellFamilyFlags.HasFlag(familyFlag1, familyFlag2, familyFlag3)) { RemoveAura(iter); continue; } } ++iter; } } void Unit::RemoveMovementImpairingAuras() { RemoveAurasWithMechanic((1 << MECHANIC_SNARE) | (1 << MECHANIC_ROOT)); } void Unit::RemoveAurasWithMechanic(uint32 mechanic_mask, AuraRemoveMode removemode, uint32 except, int32 count) { int32 auracount = 0; for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();) { Aura const * aura = iter->second->GetBase(); if (!except || aura->GetId() != except) { if (GetAllSpellMechanicMask(aura->GetSpellProto()) & mechanic_mask) { RemoveAura(iter, removemode); auracount++; if (count && auracount == count) break; continue; } } ++iter; } } void Unit::RemoveAreaAurasDueToLeaveWorld() { // make sure that all area auras not applied on self are removed - prevent access to deleted pointer later for (AuraMap::iterator iter = m_ownedAuras.begin(); iter != m_ownedAuras.end();) { Aura * aura = iter->second; ++iter; Aura::ApplicationMap const & appMap = aura->GetApplicationMap(); for (Aura::ApplicationMap::const_iterator itr = appMap.begin(); itr != appMap.end();) { AuraApplication * aurApp = itr->second; ++itr; Unit * target = aurApp->GetTarget(); if (target == this) continue; target->RemoveAura(aurApp); // things linked on aura remove may apply new area aura - so start from the beginning iter = m_ownedAuras.begin(); } } // remove area auras owned by others for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();) { if (iter->second->GetBase()->GetOwner() != this) { RemoveAura(iter); } else ++iter; } } void Unit::RemoveAllAuras() { // this may be a dead loop if some events on aura remove will continiously apply aura on remove // we want to have all auras removed, so use your brain when linking events while (!m_appliedAuras.empty() || !m_ownedAuras.empty()) { AuraApplicationMap::iterator aurAppIter; for (aurAppIter = m_appliedAuras.begin(); aurAppIter != m_appliedAuras.end();) _UnapplyAura(aurAppIter, AURA_REMOVE_BY_DEFAULT); AuraMap::iterator aurIter; for (aurIter = m_ownedAuras.begin(); aurIter != m_ownedAuras.end();) RemoveOwnedAura(aurIter); } } void Unit::RemoveArenaAuras(bool onleave) { // in join, remove positive buffs, on end, remove negative // used to remove positive visible auras in arenas for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();) { AuraApplication const * aurApp = iter->second; Aura const * aura = aurApp->GetBase(); if (!(aura->GetSpellProto()->AttributesEx4 & SPELL_ATTR4_UNK21) // don't remove stances, shadowform, pally/hunter auras && !aura->IsPassive() // don't remove passive auras && (!(aura->GetSpellProto()->Attributes & SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY) || !(aura->GetSpellProto()->Attributes & SPELL_ATTR0_UNK8)) // not unaffected by invulnerability auras or not having that unknown flag (that seemed the most probable) && (aurApp->IsPositive() ^ onleave)) // remove positive buffs on enter, negative buffs on leave RemoveAura(iter); else ++iter; } } void Unit::RemoveAllAurasOnDeath() { // used just after dieing to remove all visible auras // and disable the mods for the passive ones for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();) { Aura const * aura = iter->second->GetBase(); if (!aura->IsPassive() && !aura->IsDeathPersistent()) _UnapplyAura(iter, AURA_REMOVE_BY_DEATH); else ++iter; } for (AuraMap::iterator iter = m_ownedAuras.begin(); iter != m_ownedAuras.end();) { Aura * aura = iter->second; if (!aura->IsPassive() && !aura->IsDeathPersistent()) RemoveOwnedAura( iter, AURA_REMOVE_BY_DEATH); else ++iter; } } void Unit::RemoveAllAurasRequiringDeadTarget() { for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();) { Aura const * aura = iter->second->GetBase(); if (!aura->IsPassive() && IsRequiringDeadTargetSpell(aura->GetSpellProto())) _UnapplyAura( iter, AURA_REMOVE_BY_DEFAULT); else ++iter; } for (AuraMap::iterator iter = m_ownedAuras.begin(); iter != m_ownedAuras.end();) { Aura * aura = iter->second; if (!aura->IsPassive() && IsRequiringDeadTargetSpell(aura->GetSpellProto())) RemoveOwnedAura( iter, AURA_REMOVE_BY_DEFAULT); else ++iter; } } void Unit::DelayOwnedAuras(uint32 spellId, uint64 caster, int32 delaytime) { for (AuraMap::iterator iter = m_ownedAuras.lower_bound(spellId); iter != m_ownedAuras.upper_bound(spellId); ++iter) { Aura * aura = iter->second; if (!caster || aura->GetCasterGUID() == caster) { if (aura->GetDuration() < delaytime) aura->SetDuration(0); else aura->SetDuration(aura->GetDuration() - delaytime); // update for out of range group members (on 1 slot use) aura->SetNeedClientUpdateForTargets(); sLog->outDebug( LOG_FILTER_UNITS, "Aura %u partially interrupted on unit %u, new duration: %u ms", aura->GetId(), GetGUIDLow(), aura->GetDuration()); } } } void Unit::_RemoveAllAuraStatMods() { for (AuraApplicationMap::iterator i = m_appliedAuras.begin(); i != m_appliedAuras.end(); ++i) (*i).second->GetBase()->HandleAllEffects(i->second, AURA_EFFECT_HANDLE_STAT, false); } void Unit::_ApplyAllAuraStatMods() { for (AuraApplicationMap::iterator i = m_appliedAuras.begin(); i != m_appliedAuras.end(); ++i) (*i).second->GetBase()->HandleAllEffects(i->second, AURA_EFFECT_HANDLE_STAT, true); } AuraEffect * Unit::GetAuraEffect(uint32 spellId, uint8 effIndex, uint64 caster) const { for (AuraApplicationMap::const_iterator itr = m_appliedAuras.lower_bound( spellId); itr != m_appliedAuras.upper_bound(spellId); ++itr) if (itr->second->HasEffect(effIndex) && (!caster || itr->second->GetBase()->GetCasterGUID() == caster)) return itr->second->GetBase()->GetEffect( effIndex); return NULL; } AuraEffect * Unit::GetAuraEffectOfRankedSpell(uint32 spellId, uint8 effIndex, uint64 caster) const { uint32 rankSpell = sSpellMgr->GetFirstSpellInChain(spellId); while (true) { if (AuraEffect * aurEff = GetAuraEffect(rankSpell, effIndex, caster)) return aurEff; SpellChainNode const * chainNode = sSpellMgr->GetSpellChainNode( rankSpell); if (!chainNode) break; else rankSpell = chainNode->next; } return NULL; } AuraEffect* Unit::GetAuraEffect(AuraType type, SpellFamilyNames name, uint32 iconId, uint8 effIndex) const { AuraEffectList const& auras = GetAuraEffectsByType(type); for (Unit::AuraEffectList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr) { if (effIndex != (*itr)->GetEffIndex()) continue; SpellEntry const * spell = (*itr)->GetSpellProto(); if (spell->SpellIconID == iconId && spell->SpellFamilyName == uint32(name) && !spell->SpellFamilyFlags) return *itr; } return NULL; } AuraEffect* Unit::GetAuraEffect(AuraType type, SpellFamilyNames family, uint32 familyFlag1, uint32 familyFlag2, uint32 familyFlag3, uint64 casterGUID) { AuraEffectList const& auras = GetAuraEffectsByType(type); for (AuraEffectList::const_iterator i = auras.begin(); i != auras.end(); ++i) { SpellEntry const *spell = (*i)->GetSpellProto(); if (spell->SpellFamilyName == uint32(family) && spell->SpellFamilyFlags.HasFlag(familyFlag1, familyFlag2, familyFlag3)) { if (casterGUID && (*i)->GetCasterGUID() != casterGUID) continue; return (*i); } } return NULL; } AuraApplication * Unit::GetAuraApplication(uint32 spellId, uint64 casterGUID, uint64 itemCasterGUID, uint8 reqEffMask, AuraApplication * except) const { for (AuraApplicationMap::const_iterator itr = m_appliedAuras.lower_bound( spellId); itr != m_appliedAuras.upper_bound(spellId); ++itr) { Aura const * aura = itr->second->GetBase(); if (((aura->GetEffectMask() & reqEffMask) == reqEffMask) && (!casterGUID || aura->GetCasterGUID() == casterGUID) && (!itemCasterGUID || aura->GetCastItemGUID() == itemCasterGUID) && (!except || except != itr->second)) return itr->second; } return NULL; } Aura * Unit::GetAura(uint32 spellId, uint64 casterGUID, uint64 itemCasterGUID, uint8 reqEffMask) const { AuraApplication * aurApp = GetAuraApplication(spellId, casterGUID, itemCasterGUID, reqEffMask); return aurApp ? aurApp->GetBase() : NULL; } AuraApplication * Unit::GetAuraApplicationOfRankedSpell(uint32 spellId, uint64 casterGUID, uint64 itemCasterGUID, uint8 reqEffMask, AuraApplication* except) const { uint32 rankSpell = sSpellMgr->GetFirstSpellInChain(spellId); while (true) { if (AuraApplication * aurApp = GetAuraApplication(rankSpell, casterGUID, itemCasterGUID, reqEffMask, except)) return aurApp; SpellChainNode const * chainNode = sSpellMgr->GetSpellChainNode( rankSpell); if (!chainNode) break; else rankSpell = chainNode->next; } return NULL; } Aura * Unit::GetAuraOfRankedSpell(uint32 spellId, uint64 casterGUID, uint64 itemCasterGUID, uint8 reqEffMask) const { AuraApplication * aurApp = GetAuraApplicationOfRankedSpell(spellId, casterGUID, itemCasterGUID, reqEffMask); return aurApp ? aurApp->GetBase() : NULL; } bool Unit::HasAuraEffect(uint32 spellId, uint8 effIndex, uint64 caster) const { for (AuraApplicationMap::const_iterator itr = m_appliedAuras.lower_bound( spellId); itr != m_appliedAuras.upper_bound(spellId); ++itr) if (itr->second->HasEffect(effIndex) && (!caster || itr->second->GetBase()->GetCasterGUID() == caster)) return true; return false; } uint32 Unit::GetAuraCount(uint32 spellId) const { uint32 count = 0; for (AuraApplicationMap::const_iterator itr = m_appliedAuras.lower_bound( spellId); itr != m_appliedAuras.upper_bound(spellId); ++itr) { if (!itr->second->GetBase()->GetStackAmount()) count++; else count += (uint32) itr->second->GetBase()->GetStackAmount(); } return count; } bool Unit::HasAura(uint32 spellId, uint64 casterGUID, uint64 itemCasterGUID, uint8 reqEffMask) const { if (GetAuraApplication(spellId, casterGUID, itemCasterGUID, reqEffMask)) return true; return false; } bool Unit::HasAuraType(AuraType auraType) const { return (!m_modAuras [auraType].empty()); } bool Unit::HasAuraTypeWithCaster(AuraType auratype, uint64 caster) const { AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype); for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) if (caster == (*i)->GetCasterGUID()) return true; return false; } bool Unit::HasAuraTypeWithMiscvalue(AuraType auratype, int32 miscvalue) const { AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype); for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) if (miscvalue == (*i)->GetMiscValue()) return true; return false; } bool Unit::HasAuraTypeWithAffectMask(AuraType auratype, SpellEntry const * affectedSpell) const { AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype); for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) if ((*i)->IsAffectedOnSpell(affectedSpell)) return true; return false; } bool Unit::HasAuraTypeWithValue(AuraType auratype, int32 value) const { AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype); for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) if (value == (*i)->GetAmount()) return true; return false; } bool Unit::HasNegativeAuraWithInterruptFlag(uint32 flag, uint64 guid) { if (!(m_interruptMask & flag)) return false; for (AuraApplicationList::iterator iter = m_interruptableAuras.begin(); iter != m_interruptableAuras.end(); ++iter) { if (!(*iter)->IsPositive() && (*iter)->GetBase()->GetSpellProto()->AuraInterruptFlags & flag && (!guid || (*iter)->GetBase()->GetCasterGUID() == guid)) return true; } return false; } bool Unit::HasNegativeAuraWithAttribute(uint32 flag, uint64 guid) { for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end(); ++iter) { Aura const *aura = iter->second->GetBase(); if (!iter->second->IsPositive() && aura->GetSpellProto()->Attributes & flag && (!guid || aura->GetCasterGUID() == guid)) return true; } return false; } bool Unit::HasAuraWithMechanic(uint32 mechanicMask) { for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end(); ++iter) { SpellEntry const* spellInfo = iter->second->GetBase()->GetSpellProto(); if (spellInfo->Mechanic && (mechanicMask & (1 << spellInfo->Mechanic))) return true; for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (iter->second->HasEffect(i) && spellInfo->Effect[i] && spellInfo->EffectMechanic[i]) if (mechanicMask & (1 << spellInfo->EffectMechanic[i])) return true; } return false; } AuraEffect * Unit::IsScriptOverriden(SpellEntry const * spell, int32 script) const { AuraEffectList const& auras = GetAuraEffectsByType( SPELL_AURA_OVERRIDE_CLASS_SCRIPTS); for (AuraEffectList::const_iterator i = auras.begin(); i != auras.end(); ++i) { if ((*i)->GetMiscValue() == script) if ((*i)->IsAffectedOnSpell(spell)) return (*i); } return NULL; } uint32 Unit::GetDiseasesByCaster(uint64 casterGUID, bool remove) { static const AuraType diseaseAuraTypes [] = { SPELL_AURA_PERIODIC_DAMAGE, // Frost Fever and Blood Plague SPELL_AURA_LINKED, // Crypt Fever and Ebon Plague SPELL_AURA_NONE }; uint32 diseases = 0; for (AuraType const* itr = &diseaseAuraTypes [0]; itr && itr [0] != SPELL_AURA_NONE; ++itr) { for (AuraEffectList::iterator i = m_modAuras [*itr].begin(); i != m_modAuras [*itr].end();) { // Get auras with disease dispel type by caster if ((*i)->GetSpellProto()->Dispel == DISPEL_DISEASE && (*i)->GetCasterGUID() == casterGUID) { ++diseases; if (remove) { RemoveAura((*i)->GetId(), (*i)->GetCasterGUID()); i = m_modAuras [*itr].begin(); continue; } } ++i; } } return diseases; } uint32 Unit::GetDoTsByCaster(uint64 casterGUID) const { static const AuraType diseaseAuraTypes [] = { SPELL_AURA_PERIODIC_DAMAGE, SPELL_AURA_PERIODIC_DAMAGE_PERCENT, SPELL_AURA_NONE }; uint32 dots = 0; for (AuraType const* itr = &diseaseAuraTypes [0]; itr && itr [0] != SPELL_AURA_NONE; ++itr) { Unit::AuraEffectList const& auras = GetAuraEffectsByType(*itr); for (AuraEffectList::const_iterator i = auras.begin(); i != auras.end(); ++i) { // Get auras by caster if ((*i)->GetCasterGUID() == casterGUID) ++dots; } } return dots; } int32 Unit::GetTotalAuraModifier(AuraType auratype) const { int32 modifier = 0; AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype); for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) modifier += (*i)->GetAmount(); return modifier; } float Unit::GetTotalAuraMultiplier(AuraType auratype) const { float multiplier = 1.0f; AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype); for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) multiplier *= (100.0f + (*i)->GetAmount()) / 100.0f; return multiplier; } int32 Unit::GetMaxPositiveAuraModifier(AuraType auratype) { int32 modifier = 0; AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype); for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) { if ((*i)->GetAmount() > modifier) modifier = (*i)->GetAmount(); } return modifier; } int32 Unit::GetMaxNegativeAuraModifier(AuraType auratype) const { int32 modifier = 0; AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype); for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) if ((*i)->GetAmount() < modifier) modifier = (*i)->GetAmount(); return modifier; } int32 Unit::GetTotalAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const { int32 modifier = 0; AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype); for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) { if ((*i)->GetMiscValue() & misc_mask) modifier += (*i)->GetAmount(); } return modifier; } float Unit::GetTotalAuraMultiplierByMiscMask(AuraType auratype, uint32 misc_mask) const { float multiplier = 1.0f; AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype); for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) { if ((*i)->GetMiscValue() & misc_mask) multiplier *= (100.0f + (*i)->GetAmount()) / 100.0f; } return multiplier; } int32 Unit::GetMaxPositiveAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask, const AuraEffect* except) const { int32 modifier = 0; AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype); for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) { if (except != (*i) && (*i)->GetMiscValue() & misc_mask && (*i)->GetAmount() > modifier) modifier = (*i)->GetAmount(); } return modifier; } int32 Unit::GetMaxNegativeAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const { int32 modifier = 0; AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype); for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) { if ((*i)->GetMiscValue() & misc_mask && (*i)->GetAmount() < modifier) modifier = (*i)->GetAmount(); } return modifier; } int32 Unit::GetTotalAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const { int32 modifier = 0; AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype); for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) { if ((*i)->GetMiscValue() == misc_value) modifier += (*i)->GetAmount(); } return modifier; } float Unit::GetTotalAuraMultiplierByMiscValue(AuraType auratype, int32 misc_value) const { float multiplier = 1.0f; AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype); for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) { if ((*i)->GetMiscValue() == misc_value) multiplier *= (100.0f + (*i)->GetAmount()) / 100.0f; } return multiplier; } int32 Unit::GetMaxPositiveAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const { int32 modifier = 0; AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype); for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) { if ((*i)->GetMiscValue() == misc_value && (*i)->GetAmount() > modifier) modifier = (*i)->GetAmount(); } return modifier; } int32 Unit::GetMaxNegativeAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const { int32 modifier = 0; AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype); for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) { if ((*i)->GetMiscValue() == misc_value && (*i)->GetAmount() < modifier) modifier = (*i)->GetAmount(); } return modifier; } int32 Unit::GetTotalAuraModifierByAffectMask(AuraType auratype, SpellEntry const * affectedSpell) const { int32 modifier = 0; AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype); for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) { if ((*i)->IsAffectedOnSpell(affectedSpell)) modifier += (*i)->GetAmount(); } return modifier; } float Unit::GetTotalAuraMultiplierByAffectMask(AuraType auratype, SpellEntry const * affectedSpell) const { float multiplier = 1.0f; AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype); for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) { if ((*i)->IsAffectedOnSpell(affectedSpell)) multiplier *= (100.0f + (*i)->GetAmount()) / 100.0f; } return multiplier; } int32 Unit::GetMaxPositiveAuraModifierByAffectMask(AuraType auratype, SpellEntry const * affectedSpell) const { int32 modifier = 0; AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype); for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) { if ((*i)->IsAffectedOnSpell(affectedSpell) && (*i)->GetAmount() > modifier) modifier = (*i)->GetAmount(); } return modifier; } int32 Unit::GetMaxNegativeAuraModifierByAffectMask(AuraType auratype, SpellEntry const * affectedSpell) const { int32 modifier = 0; AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype); for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) { if ((*i)->IsAffectedOnSpell(affectedSpell) && (*i)->GetAmount() < modifier) modifier = (*i)->GetAmount(); } return modifier; } void Unit::_RegisterDynObject(DynamicObject* dynObj) { m_dynObj.push_back(dynObj); } void Unit::_UnregisterDynObject(DynamicObject* dynObj) { m_dynObj.remove(dynObj); } DynamicObject * Unit::GetDynObject(uint32 spellId) { if (m_dynObj.empty()) return NULL; for (DynObjectList::const_iterator i = m_dynObj.begin(); i != m_dynObj.end(); ++i) { DynamicObject* dynObj = *i; if (dynObj->GetSpellId() == spellId) return dynObj; } return NULL; } void Unit::RemoveDynObject(uint32 spellId) { if (m_dynObj.empty()) return; for (DynObjectList::iterator i = m_dynObj.begin(); i != m_dynObj.end();) { DynamicObject* dynObj = *i; if (dynObj->GetSpellId() == spellId) { dynObj->Remove(); i = m_dynObj.begin(); } else ++i; } } void Unit::RemoveAllDynObjects() { while (!m_dynObj.empty()) m_dynObj.front()->Remove(); } GameObject* Unit::GetGameObject(uint32 spellId) const { for (GameObjectList::const_iterator i = m_gameObj.begin(); i != m_gameObj.end(); ++i) if ((*i)->GetSpellId() == spellId) return *i; return NULL; } void Unit::AddGameObject(GameObject* gameObj) { if (!gameObj || !gameObj->GetOwnerGUID() == 0) return; m_gameObj.push_back(gameObj); gameObj->SetOwnerGUID(GetGUID()); if (GetTypeId() == TYPEID_PLAYER && gameObj->GetSpellId()) { SpellEntry const* createBySpell = sSpellStore.LookupEntry( gameObj->GetSpellId()); // Need disable spell use for owner if (createBySpell && createBySpell->Attributes & SPELL_ATTR0_DISABLED_WHILE_ACTIVE) // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existed cases) this->ToPlayer()->AddSpellAndCategoryCooldowns(createBySpell, 0, NULL, true); } } void Unit::RemoveGameObject(GameObject* gameObj, bool del) { if (!gameObj || !gameObj->GetOwnerGUID() == GetGUID()) return; gameObj->SetOwnerGUID(0); for (uint32 i = 0; i < 4; ++i) { if (m_ObjectSlot [i] == gameObj->GetGUID()) { m_ObjectSlot [i] = 0; break; } } // GO created by some spell if (uint32 spellid = gameObj->GetSpellId()) { RemoveAurasDueToSpell(spellid); if (GetTypeId() == TYPEID_PLAYER) { SpellEntry const* createBySpell = sSpellStore.LookupEntry(spellid); // Need activate spell use for owner if (createBySpell && createBySpell->Attributes & SPELL_ATTR0_DISABLED_WHILE_ACTIVE) // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existed cases) this->ToPlayer()->SendCooldownEvent(createBySpell); } } m_gameObj.remove(gameObj); if (del) { gameObj->SetRespawnTime(0); gameObj->Delete(); } } void Unit::RemoveGameObject(uint32 spellid, bool del) { if (m_gameObj.empty()) return; GameObjectList::iterator i, next; for (i = m_gameObj.begin(); i != m_gameObj.end(); i = next) { next = i; if (spellid == 0 || (*i)->GetSpellId() == spellid) { (*i)->SetOwnerGUID(0); if (del) { (*i)->SetRespawnTime(0); (*i)->Delete(); } next = m_gameObj.erase(i); } else ++next; } } void Unit::RemoveAllGameObjects() { // remove references to unit for (GameObjectList::iterator i = m_gameObj.begin(); i != m_gameObj.end();) { (*i)->SetOwnerGUID(0); (*i)->SetRespawnTime(0); (*i)->Delete(); i = m_gameObj.erase(i); } } void Unit::SendSpellNonMeleeDamageLog(SpellNonMeleeDamage *log) { WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16 + 4 + 4 + 4 + 1 + 4 + 4 + 1 + 1 + 4 + 4 + 1)); // we guess size data.append(log->target->GetPackGUID()); data.append(log->attacker->GetPackGUID()); data << uint32(log->SpellID); data << uint32(log->damage); // damage amount int32 overkill = log->damage - log->target->GetHealth(); data << uint32(overkill > 0 ? overkill : 0); // overkill data << uint8(log->schoolMask); // damage school data << uint32(log->absorb); // AbsorbedDamage data << uint32(log->resist); // resist data << uint8(log->physicalLog); // if 1, then client show spell name (example: %s's ranged shot hit %s for %u school or %s suffers %u school damage from %s's spell_name data << uint8(log->unused); // unused data << uint32(log->blocked); // blocked data << uint32(log->HitInfo); data << uint8(0); // flag to use extend data SendMessageToSet(&data, true); } void Unit::SendSpellNonMeleeDamageLog(Unit *target, uint32 SpellID, uint32 Damage, SpellSchoolMask damageSchoolMask, uint32 AbsorbedDamage, uint32 Resist, bool PhysicalDamage, uint32 Blocked, bool CriticalHit) { SpellNonMeleeDamage log(this, target, SpellID, damageSchoolMask); log.damage = Damage - AbsorbedDamage - Resist - Blocked; log.absorb = AbsorbedDamage; log.resist = Resist; log.physicalLog = PhysicalDamage; log.blocked = Blocked; log.HitInfo = SPELL_HIT_TYPE_UNK1 | SPELL_HIT_TYPE_UNK3 | SPELL_HIT_TYPE_UNK6; if (CriticalHit) log.HitInfo |= SPELL_HIT_TYPE_CRIT; SendSpellNonMeleeDamageLog(&log); } void Unit::ProcDamageAndSpell(Unit *pVictim, uint32 procAttacker, uint32 procVictim, uint32 procExtra, uint32 amount, WeaponAttackType attType, SpellEntry const *procSpell, SpellEntry const * procAura) { // Not much to do if no flags are set. if (procAttacker) ProcDamageAndSpellFor(false, pVictim, procAttacker, procExtra, attType, procSpell, amount, procAura); // Now go on with a victim's events'n'auras // Not much to do if no flags are set or there is no victim if (pVictim && pVictim->isAlive() && procVictim) pVictim->ProcDamageAndSpellFor( true, this, procVictim, procExtra, attType, procSpell, amount, procAura); } void Unit::SendPeriodicAuraLog(SpellPeriodicAuraLogInfo *pInfo) { AuraEffect const * aura = pInfo->auraEff; WorldPacket data(SMSG_PERIODICAURALOG, 8 + 8 + 4 + 4 + 4 + 4 * 5 + 1); data.append(GetPackGUID()); data.appendPackGUID(aura->GetCasterGUID()); data << uint32(aura->GetId()); // spellId data << uint32(1); // count data << uint32(aura->GetAuraType()); // auraId switch (aura->GetAuraType()) { case SPELL_AURA_PERIODIC_DAMAGE: case SPELL_AURA_PERIODIC_DAMAGE_PERCENT: data << uint32(pInfo->damage); // damage data << uint32(pInfo->overDamage); // overkill? data << uint32(GetSpellSchoolMask(aura->GetSpellProto())); data << uint32(pInfo->absorb); // absorb data << uint32(pInfo->resist); // resist data << uint8(pInfo->critical); // new 3.1.2 critical tick break; case SPELL_AURA_PERIODIC_HEAL: case SPELL_AURA_OBS_MOD_HEALTH: data << uint32(pInfo->damage); // damage data << uint32(pInfo->overDamage); // overheal data << uint32(pInfo->absorb); // absorb data << uint8(pInfo->critical); // new 3.1.2 critical tick break; case SPELL_AURA_OBS_MOD_POWER: case SPELL_AURA_PERIODIC_ENERGIZE: data << uint32(aura->GetMiscValue()); // power type data << uint32(pInfo->damage); // damage break; case SPELL_AURA_PERIODIC_MANA_LEECH: data << uint32(aura->GetMiscValue()); // power type data << uint32(pInfo->damage); // amount data << float(pInfo->multiplier); // gain multiplier break; default: sLog->outError("Unit::SendPeriodicAuraLog: unknown aura %u", uint32(aura->GetAuraType())); return; } SendMessageToSet(&data, true); } void Unit::SendSpellMiss(Unit *target, uint32 spellID, SpellMissInfo missInfo) { WorldPacket data(SMSG_SPELLLOGMISS, 4 + 8 + 1 + 4 + 8 + 1); data << uint32(spellID); data << uint64(GetGUID()); data << uint8(0); // can be 0 or 1 data << uint32(1); // target count // for (i = 0; i < target count; ++i) data << uint64(target->GetGUID()); // target GUID data << uint8(missInfo); // end loop SendMessageToSet(&data, true); } void Unit::SendSpellDamageImmune(Unit * target, uint32 spellId) { WorldPacket data(SMSG_SPELLORDAMAGE_IMMUNE, 8 + 8 + 4 + 1); data << uint64(GetGUID()); data << uint64(target->GetGUID()); data << uint32(spellId); data << uint8(0); // bool - log format: 0-default, 1-debug SendMessageToSet(&data, true); } void Unit::SendAttackStateUpdate(CalcDamageInfo *damageInfo) { sLog->outDebug(LOG_FILTER_UNITS, "WORLD: Sending SMSG_ATTACKERSTATEUPDATE"); uint32 count = 1; size_t maxsize = 4 + 5 + 5 + 4 + 4 + 1 + 4 + 4 + 4 + 4 + 4 + 1 + 4 + 4 + 4 + 4 + 4 * 12; WorldPacket data(SMSG_ATTACKERSTATEUPDATE, maxsize); // we guess size data << uint32(damageInfo->HitInfo); data.append(damageInfo->attacker->GetPackGUID()); data.append(damageInfo->target->GetPackGUID()); data << uint32(damageInfo->damage); // Full damage int32 overkill = damageInfo->damage - damageInfo->target->GetHealth(); data << uint32(overkill < 0 ? 0 : overkill); // Overkill data << uint8(count); // Sub damage count for (uint32 i = 0; i < count; ++i) { data << uint32(damageInfo->damageSchoolMask); // School of sub damage data << float(damageInfo->damage); // sub damage data << uint32(damageInfo->damage); // Sub Damage } if (damageInfo->HitInfo & (HITINFO_ABSORB | HITINFO_ABSORB2)) { for (uint32 i = 0; i < count; ++i) data << uint32(damageInfo->absorb); // Absorb } if (damageInfo->HitInfo & (HITINFO_RESIST | HITINFO_RESIST2)) { for (uint32 i = 0; i < count; ++i) data << uint32(damageInfo->resist); // Resist } data << uint8(damageInfo->TargetState); data << uint32(0); data << uint32(0); if (damageInfo->HitInfo & HITINFO_BLOCK) data << uint32(damageInfo->blocked_amount); if (damageInfo->HitInfo & HITINFO_UNK3) data << uint32(0); if (damageInfo->HitInfo & HITINFO_UNK1) { data << uint32(0); data << float(0); data << float(0); data << float(0); data << float(0); data << float(0); data << float(0); data << float(0); data << float(0); data << float(0); // Found in a loop with 1 iteration data << float(0); // ditto ^ data << uint32(0); } SendMessageToSet(&data, true); } void Unit::SendAttackStateUpdate(uint32 HitInfo, Unit *target, uint8 /*SwingType*/, SpellSchoolMask damageSchoolMask, uint32 Damage, uint32 AbsorbDamage, uint32 Resist, VictimState TargetState, uint32 BlockedAmount) { CalcDamageInfo dmgInfo; dmgInfo.HitInfo = HitInfo; dmgInfo.attacker = this; dmgInfo.target = target; dmgInfo.damage = Damage - AbsorbDamage - Resist - BlockedAmount; dmgInfo.damageSchoolMask = damageSchoolMask; dmgInfo.absorb = AbsorbDamage; dmgInfo.resist = Resist; dmgInfo.TargetState = TargetState; dmgInfo.blocked_amount = BlockedAmount; SendAttackStateUpdate(&dmgInfo); } bool Unit::HandleModPowerRegenAuraProc(Unit *pVictim, uint32 damage, AuraEffect* triggeredByAura, SpellEntry const * /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown) { SpellEntry const *hasteSpell = triggeredByAura->GetSpellProto(); Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER ? this->ToPlayer()->GetItemByGuid( triggeredByAura->GetBase()->GetCastItemGUID()) : NULL; uint32 triggered_spell_id = 0; Unit* target = pVictim; int32 basepoints0 = 0; switch (hasteSpell->SpellFamilyName) { case SPELLFAMILY_ROGUE: { switch (hasteSpell->Id) { // Blade Flurry case 13877: //case 33735: { target = SelectNearbyTarget(); if (!target || target == pVictim) return false; basepoints0 = damage; triggered_spell_id = 22482; break; } } break; } } // processed charge only counting case if (!triggered_spell_id) return true; SpellEntry const* triggerEntry = sSpellStore.LookupEntry( triggered_spell_id); if (!triggerEntry) { sLog->outError( "Unit::HandleHasteAuraProc: Spell %u have not existed triggered spell %u", hasteSpell->Id, triggered_spell_id); return false; } // default case if ((!target && !sSpellMgr->IsSrcTargetSpell(triggerEntry)) || (target && target != this && !target->isAlive())) return false; if (cooldown && GetTypeId() == TYPEID_PLAYER && this->ToPlayer()->HasSpellCooldown(triggered_spell_id)) return false; if (basepoints0) CastCustomSpell(target, triggered_spell_id, &basepoints0, NULL, NULL, true, castItem, triggeredByAura); else CastSpell(target, triggered_spell_id, true, castItem, triggeredByAura); if (cooldown && target->GetTypeId() == TYPEID_PLAYER) target->ToPlayer()->AddSpellCooldown( triggered_spell_id, 0, time(NULL) + cooldown); return true; } bool Unit::HandleSpellCritChanceAuraProc(Unit *pVictim, uint32 /*damage*/, AuraEffect* triggeredByAura, SpellEntry const * /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown) { SpellEntry const *triggeredByAuraSpell = triggeredByAura->GetSpellProto(); Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER ? this->ToPlayer()->GetItemByGuid( triggeredByAura->GetBase()->GetCastItemGUID()) : NULL; uint32 triggered_spell_id = 0; Unit* target = pVictim; int32 basepoints0 = 0; switch (triggeredByAuraSpell->SpellFamilyName) { case SPELLFAMILY_MAGE: { switch (triggeredByAuraSpell->Id) { // Focus Magic case 54646: { Unit* caster = triggeredByAura->GetCaster(); if (!caster) return false; triggered_spell_id = 54648; target = caster; break; } } } } // processed charge only counting case if (!triggered_spell_id) return true; SpellEntry const* triggerEntry = sSpellStore.LookupEntry( triggered_spell_id); if (!triggerEntry) { sLog->outError( "Unit::HandleHasteAuraProc: Spell %u have not existed triggered spell %u", triggeredByAuraSpell->Id, triggered_spell_id); return false; } // default case if (!target || (target != this && !target->isAlive())) return false; if (cooldown && GetTypeId() == TYPEID_PLAYER && this->ToPlayer()->HasSpellCooldown(triggered_spell_id)) return false; if (basepoints0) CastCustomSpell(target, triggered_spell_id, &basepoints0, NULL, NULL, true, castItem, triggeredByAura); else CastSpell(target, triggered_spell_id, true, castItem, triggeredByAura); if (cooldown && GetTypeId() == TYPEID_PLAYER) this->ToPlayer()->AddSpellCooldown( triggered_spell_id, 0, time(NULL) + cooldown); return true; } bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* triggeredByAura, SpellEntry const * procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown) { SpellEntry const *dummySpell = triggeredByAura->GetSpellProto(); uint32 effIndex = triggeredByAura->GetEffIndex(); int32 triggerAmount = triggeredByAura->GetAmount(); Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER ? this->ToPlayer()->GetItemByGuid( triggeredByAura->GetBase()->GetCastItemGUID()) : NULL; uint32 triggered_spell_id = 0; uint32 cooldown_spell_id = 0; // for random trigger, will be one of the triggered spell to avoid repeatable triggers // otherwise, it's the triggered_spell_id by default Unit* target = pVictim; int32 basepoints0 = 0; uint64 originalCaster = 0; switch (dummySpell->SpellFamilyName) { case SPELLFAMILY_GENERIC: { switch (dummySpell->Id) { // Bloodworms Health Leech case 50453: { if (Unit *owner = this->GetOwner()) { basepoints0 = int32(damage * 1.50); target = owner; triggered_spell_id = 50454; break; } return false; } // Eye for an Eye case 9799: case 25988: { // return damage % to attacker but < 50% own total health basepoints0 = int32((triggerAmount * damage) / 100); int32 halfMaxHealth = int32(CountPctFromMaxHealth(50)); if (basepoints0 > halfMaxHealth) basepoints0 = halfMaxHealth; triggered_spell_id = 25997; break; } // Sweeping Strikes case 18765: case 35429: { target = SelectNearbyTarget(); if (!target) return false; triggered_spell_id = 26654; break; } // Unstable Power case 24658: { if (!procSpell || procSpell->Id == 24659) return false; // Need remove one 24659 aura RemoveAuraFromStack(24659); return true; } // Restless Strength case 24661: { // Need remove one 24662 aura RemoveAuraFromStack(24662); return true; } // Adaptive Warding (Frostfire Regalia set) case 28764: { if (!procSpell) return false; // find Mage Armor if (!GetAuraEffect(SPELL_AURA_MOD_MANA_REGEN_INTERRUPT, SPELLFAMILY_MAGE, 0x10000000, 0, 0)) return false; switch (GetFirstSchoolInMask(GetSpellSchoolMask(procSpell))) { case SPELL_SCHOOL_NORMAL: case SPELL_SCHOOL_HOLY: return false; // ignored case SPELL_SCHOOL_FIRE: triggered_spell_id = 28765; break; case SPELL_SCHOOL_NATURE: triggered_spell_id = 28768; break; case SPELL_SCHOOL_FROST: triggered_spell_id = 28766; break; case SPELL_SCHOOL_SHADOW: triggered_spell_id = 28769; break; case SPELL_SCHOOL_ARCANE: triggered_spell_id = 28770; break; default: return false; } target = this; break; } // Obsidian Armor (Justice Bearer`s Pauldrons shoulder) case 27539: { if (!procSpell) return false; switch (GetFirstSchoolInMask(GetSpellSchoolMask(procSpell))) { case SPELL_SCHOOL_NORMAL: return false; // ignore case SPELL_SCHOOL_HOLY: triggered_spell_id = 27536; break; case SPELL_SCHOOL_FIRE: triggered_spell_id = 27533; break; case SPELL_SCHOOL_NATURE: triggered_spell_id = 27538; break; case SPELL_SCHOOL_FROST: triggered_spell_id = 27534; break; case SPELL_SCHOOL_SHADOW: triggered_spell_id = 27535; break; case SPELL_SCHOOL_ARCANE: triggered_spell_id = 27540; break; default: return false; } target = this; break; } // Mana Leech (Passive) (Priest Pet Aura) case 28305: { // Cast on owner target = GetOwner(); if (!target) return false; triggered_spell_id = 34650; break; } // Mark of Malice case 33493: { // Cast finish spell at last charge if (triggeredByAura->GetBase()->GetCharges() > 1) return false; target = this; triggered_spell_id = 33494; break; } // Twisted Reflection (boss spell) case 21063: triggered_spell_id = 21064; break; // Vampiric Aura (boss spell) case 38196: { basepoints0 = 3 * damage; // 300% if (basepoints0 < 0) return false; triggered_spell_id = 31285; target = this; break; } // Aura of Madness (Darkmoon Card: Madness trinket) //===================================================== // 39511 Sociopath: +35 strength (Paladin, Rogue, Druid, Warrior) // 40997 Delusional: +70 attack power (Rogue, Hunter, Paladin, Warrior, Druid) // 40998 Kleptomania: +35 agility (Warrior, Rogue, Paladin, Hunter, Druid) // 40999 Megalomania: +41 damage/healing (Druid, Shaman, Priest, Warlock, Mage, Paladin) // 41002 Paranoia: +35 spell/melee/ranged crit strike rating (All classes) // 41005 Manic: +35 haste (spell, melee and ranged) (All classes) // 41009 Narcissism: +35 intellect (Druid, Shaman, Priest, Warlock, Mage, Paladin, Hunter) // 41011 Martyr Complex: +35 stamina (All classes) // 41406 Dementia: Every 5 seconds either gives you +5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin) // 41409 Dementia: Every 5 seconds either gives you -5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin) case 39446: { if (GetTypeId() != TYPEID_PLAYER || !this->isAlive()) return false; // Select class defined buff switch (getClass()) { case CLASS_PALADIN: // 39511, 40997, 40998, 40999, 41002, 41005, 41009, 41011, 41409 case CLASS_DRUID: // 39511, 40997, 40998, 40999, 41002, 41005, 41009, 41011, 41409 triggered_spell_id = RAND(39511, 40997, 40998, 40999, 41002, 41005, 41009, 41011, 41409); cooldown_spell_id = 39511; break; case CLASS_ROGUE: // 39511, 40997, 40998, 41002, 41005, 41011 case CLASS_WARRIOR: // 39511, 40997, 40998, 41002, 41005, 41011 triggered_spell_id = RAND(39511, 40997, 40998, 41002, 41005, 41011); cooldown_spell_id = 39511; break; case CLASS_PRIEST: // 40999, 41002, 41005, 41009, 41011, 41406, 41409 case CLASS_SHAMAN: // 40999, 41002, 41005, 41009, 41011, 41406, 41409 case CLASS_MAGE: // 40999, 41002, 41005, 41009, 41011, 41406, 41409 case CLASS_WARLOCK: // 40999, 41002, 41005, 41009, 41011, 41406, 41409 triggered_spell_id = RAND(40999, 41002, 41005, 41009, 41011, 41406, 41409); cooldown_spell_id = 40999; break; case CLASS_HUNTER: // 40997, 40999, 41002, 41005, 41009, 41011, 41406, 41409 triggered_spell_id = RAND(40997, 40999, 41002, 41005, 41009, 41011, 41406, 41409); cooldown_spell_id = 40997; break; default: return false; } target = this; if (roll_chance_i(10)) this->ToPlayer()->Say( "This is Madness!", LANG_UNIVERSAL); // TODO: It should be moved to database, shouldn't it? break; } // Sunwell Exalted Caster Neck (??? neck) // cast ??? Light's Wrath if Exalted by Aldor // cast ??? Arcane Bolt if Exalted by Scryers case 46569: return false; // old unused version // Sunwell Exalted Caster Neck (Shattered Sun Pendant of Acumen neck) // cast 45479 Light's Wrath if Exalted by Aldor // cast 45429 Arcane Bolt if Exalted by Scryers case 45481: { if (GetTypeId() != TYPEID_PLAYER) return false; // Get Aldor reputation rank if (ToPlayer()->GetReputationRank(932) == REP_EXALTED) { target = this; triggered_spell_id = 45479; break; } // Get Scryers reputation rank if (ToPlayer()->GetReputationRank(934) == REP_EXALTED) { // triggered at positive/self casts also, current attack target used then if (IsFriendlyTo(target)) { target = getVictim(); if (!target) { uint64 selected_guid = ToPlayer()->GetSelection(); target = ObjectAccessor::GetUnit(*this, selected_guid); if (!target) return false; } if (IsFriendlyTo(target)) return false; } triggered_spell_id = 45429; break; } return false; } // Sunwell Exalted Melee Neck (Shattered Sun Pendant of Might neck) // cast 45480 Light's Strength if Exalted by Aldor // cast 45428 Arcane Strike if Exalted by Scryers case 45482: { if (GetTypeId() != TYPEID_PLAYER) return false; // Get Aldor reputation rank if (ToPlayer()->GetReputationRank(932) == REP_EXALTED) { target = this; triggered_spell_id = 45480; break; } // Get Scryers reputation rank if (ToPlayer()->GetReputationRank(934) == REP_EXALTED) { triggered_spell_id = 45428; break; } return false; } // Sunwell Exalted Tank Neck (Shattered Sun Pendant of Resolve neck) // cast 45431 Arcane Insight if Exalted by Aldor // cast 45432 Light's Ward if Exalted by Scryers case 45483: { if (GetTypeId() != TYPEID_PLAYER) return false; // Get Aldor reputation rank if (ToPlayer()->GetReputationRank(932) == REP_EXALTED) { target = this; triggered_spell_id = 45432; break; } // Get Scryers reputation rank if (ToPlayer()->GetReputationRank(934) == REP_EXALTED) { target = this; triggered_spell_id = 45431; break; } return false; } // Sunwell Exalted Healer Neck (Shattered Sun Pendant of Restoration neck) // cast 45478 Light's Salvation if Exalted by Aldor // cast 45430 Arcane Surge if Exalted by Scryers case 45484: { if (GetTypeId() != TYPEID_PLAYER) return false; // Get Aldor reputation rank if (ToPlayer()->GetReputationRank(932) == REP_EXALTED) { target = this; triggered_spell_id = 45478; break; } // Get Scryers reputation rank if (ToPlayer()->GetReputationRank(934) == REP_EXALTED) { triggered_spell_id = 45430; break; } return false; } // Living Seed case 48504: { triggered_spell_id = 48503; basepoints0 = triggerAmount; target = this; break; } // Kill command case 58914: { // Remove aura stack from pet RemoveAuraFromStack(58914); Unit* owner = GetOwner(); if (!owner) return true; // reduce the owner's aura stack owner->RemoveAuraFromStack(34027); return true; } // Vampiric Touch (generic, used by some boss) case 52723: case 60501: { triggered_spell_id = 52724; basepoints0 = damage / 2; target = this; break; } // Shadowfiend Death (Gain mana if pet dies with Glyph of Shadowfiend) case 57989: { Unit *owner = GetOwner(); if (!owner || owner->GetTypeId() != TYPEID_PLAYER) return false; // Glyph of Shadowfiend (need cast as self cast for owner, no hidden cooldown) owner->CastSpell(owner, 58227, true, castItem, triggeredByAura); return true; } // Glyph of Life Tap case 63320: { triggered_spell_id = 63321; // Life Tap break; } case 71519: // Deathbringer's Will Normal { if (GetTypeId() != TYPEID_PLAYER) return false; std::vector <uint32> RandomSpells; switch (getClass()) { case CLASS_WARRIOR: case CLASS_PALADIN: case CLASS_DEATH_KNIGHT: RandomSpells.push_back(71484); RandomSpells.push_back(71491); RandomSpells.push_back(71492); break; case CLASS_SHAMAN: case CLASS_ROGUE: RandomSpells.push_back(71486); RandomSpells.push_back(71485); RandomSpells.push_back(71492); break; case CLASS_DRUID: RandomSpells.push_back(71484); RandomSpells.push_back(71485); RandomSpells.push_back(71486); break; case CLASS_HUNTER: RandomSpells.push_back(71486); RandomSpells.push_back(71491); RandomSpells.push_back(71485); break; default: return false; } if (RandomSpells.empty()) //shouldn't happen return false; uint8 rand_spell = irand(0, (RandomSpells.size() - 1)); CastSpell(target, RandomSpells [rand_spell], true, castItem, triggeredByAura, originalCaster); for (std::vector <uint32>::iterator itr = RandomSpells.begin(); itr != RandomSpells.end(); ++itr) { if (!ToPlayer()->HasSpellCooldown(*itr)) ToPlayer()->AddSpellCooldown( *itr, 0, time(NULL) + cooldown); } break; } case 71562: // Deathbringer's Will Heroic { if (GetTypeId() != TYPEID_PLAYER) return false; std::vector <uint32> RandomSpells; switch (getClass()) { case CLASS_WARRIOR: case CLASS_PALADIN: case CLASS_DEATH_KNIGHT: RandomSpells.push_back(71561); RandomSpells.push_back(71559); RandomSpells.push_back(71560); break; case CLASS_SHAMAN: case CLASS_ROGUE: RandomSpells.push_back(71558); RandomSpells.push_back(71556); RandomSpells.push_back(71560); break; case CLASS_DRUID: RandomSpells.push_back(71561); RandomSpells.push_back(71556); RandomSpells.push_back(71558); break; case CLASS_HUNTER: RandomSpells.push_back(71558); RandomSpells.push_back(71559); RandomSpells.push_back(71556); break; default: return false; } if (RandomSpells.empty()) //shouldn't happen return false; uint8 rand_spell = irand(0, (RandomSpells.size() - 1)); CastSpell(target, RandomSpells [rand_spell], true, castItem, triggeredByAura, originalCaster); for (std::vector <uint32>::iterator itr = RandomSpells.begin(); itr != RandomSpells.end(); ++itr) { if (!ToPlayer()->HasSpellCooldown(*itr)) ToPlayer()->AddSpellCooldown( *itr, 0, time(NULL) + cooldown); } break; } // Item - Shadowmourne Legendary case 71903: { if (!pVictim || !pVictim->isAlive() || HasAura(73422)) // cant collect shards while under effect of Chaos Bane buff return false; CastSpell(this, 71905, true, NULL, triggeredByAura); // this can't be handled in AuraScript because we need to know pVictim Aura const* dummy = GetAura(71905); if (!dummy || dummy->GetStackAmount() < 10) return false; RemoveAurasDueToSpell(71905); triggered_spell_id = 71904; target = pVictim; break; } // Shadow's Fate (Shadowmourne questline) case 71169: { target = triggeredByAura->GetCaster(); Player* player = target->ToPlayer(); if (!player) return false; // not checking Infusion auras because its in targetAuraSpell of credit spell if (player->GetQuestStatus(24749) == QUEST_STATUS_INCOMPLETE) // Unholy Infusion { if (GetEntry() != 36678) // Professor Putricide return false; CastSpell(target, 71518, true); // Quest Credit return true; } else if (player->GetQuestStatus(24756) == QUEST_STATUS_INCOMPLETE) // Blood Infusion { if (GetEntry() != 37955) // Blood-Queen Lana'thel return false; CastSpell(target, 72934, true); // Quest Credit return true; } else if (player->GetQuestStatus(24757) == QUEST_STATUS_INCOMPLETE) // Frost Infusion { if (GetEntry() != 36853) // Sindragosa return false; CastSpell(target, 72289, true); // Quest Credit return true; } else if (player->GetQuestStatus(24547) == QUEST_STATUS_INCOMPLETE) // A Feast of Souls triggered_spell_id = 71203; break; } // Gaseous Bloat (Professor Putricide add) case 70215: case 72858: case 72859: case 72860: { target = getVictim(); triggered_spell_id = 70701; break; } // Item - Icecrown 25 Normal Heartpiece case 71880: { switch (getPowerType()) { case POWER_MANA: triggered_spell_id = 71881; break; case POWER_RAGE: triggered_spell_id = 71883; break; case POWER_ENERGY: triggered_spell_id = 71882; break; case POWER_RUNIC_POWER: triggered_spell_id = 71884; break; default: return false; } break; } // Item - Icecrown 25 Heroic Heartpiece case 71892: { switch (getPowerType()) { case POWER_MANA: triggered_spell_id = 71888; break; case POWER_RAGE: triggered_spell_id = 71886; break; case POWER_ENERGY: triggered_spell_id = 71887; break; case POWER_RUNIC_POWER: triggered_spell_id = 71885; break; default: return false; } break; } } break; } case SPELLFAMILY_MAGE: { // Magic Absorption if (dummySpell->SpellIconID == 459) // only this spell have SpellIconID == 459 and dummy aura { if (getPowerType() != POWER_MANA) return false; // mana reward basepoints0 = (triggerAmount * GetMaxPower(POWER_MANA) / 100); target = this; triggered_spell_id = 29442; break; } // Master of Elements if (dummySpell->SpellIconID == 1920) { if (!procSpell) return false; // mana cost save int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100; basepoints0 = cost * triggerAmount / 100; if (basepoints0 <= 0) return false; target = this; triggered_spell_id = 29077; break; } // Arcane Potency if (dummySpell->SpellIconID == 2120) { if (!procSpell) return false; target = this; switch (dummySpell->Id) { case 31571: triggered_spell_id = 57529; break; case 31572: triggered_spell_id = 57531; break; default: sLog->outError( "Unit::HandleDummyAuraProc: non handled spell id: %u", dummySpell->Id); return false; } break; } // Hot Streak if (dummySpell->SpellIconID == 2999) { if (effIndex != 0) return false; AuraEffect *counter = triggeredByAura->GetBase()->GetEffect(1); if (!counter) return true; // Count spell criticals in a row in second aura if (procEx & PROC_EX_CRITICAL_HIT) { counter->SetAmount(counter->GetAmount() * 2); if (counter->GetAmount() < 100) // not enough return true; // Crititcal counted -> roll chance if (roll_chance_i(triggerAmount)) CastSpell(this, 48108, true, castItem, triggeredByAura); } counter->SetAmount(25); return true; } // Burnout if (dummySpell->SpellIconID == 2998) { if (!procSpell) return false; int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100; basepoints0 = cost * triggerAmount / 100; if (basepoints0 <= 0) return false; triggered_spell_id = 44450; target = this; break; } // Incanter's Regalia set (add trigger chance to Mana Shield) if (dummySpell->SpellFamilyFlags [0] & 0x8000) { if (GetTypeId() != TYPEID_PLAYER) return false; target = this; triggered_spell_id = 37436; break; } switch (dummySpell->Id) { //Nether Vortex case 86181: case 86209: { AuraMap const &slowAura = GetOwnedAuras(); for (Unit::AuraMap::const_iterator itr = slowAura.begin(); itr != slowAura.end();) if ((*itr).second->GetId() == 31589) // Found Slow, dont proc break; else itr++; target = this; triggered_spell_id = 86262; if (pVictim) CastSpell(pVictim, 31589, false); break; } // Glyph of Polymorph case 56375: { if (!target) return false; target->RemoveAurasByType(SPELL_AURA_PERIODIC_DAMAGE, 0, target->GetAura(32409)); // SW:D shall not be removed. target->RemoveAurasByType( SPELL_AURA_PERIODIC_DAMAGE_PERCENT); target->RemoveAurasByType(SPELL_AURA_PERIODIC_LEECH); return true; } // Glyph of Icy Veins case 56374: { RemoveAurasByType(SPELL_AURA_HASTE_SPELLS, 0, 0, true, false); RemoveAurasByType(SPELL_AURA_MOD_DECREASE_SPEED); return true; } // Ignite case 11119: case 11120: case 12846: case 12847: case 12848: { switch (dummySpell->Id) { case 11119: basepoints0 = int32(0.04f * damage); break; case 11120: basepoints0 = int32(0.08f * damage); break; case 12846: basepoints0 = int32(0.12f * damage); break; case 12847: basepoints0 = int32(0.16f * damage); break; case 12848: basepoints0 = int32(0.20f * damage); break; default: sLog->outError( "Unit::HandleDummyAuraProc: non handled spell id: %u (IG)", dummySpell->Id); return false; } triggered_spell_id = 12654; basepoints0 += pVictim->GetRemainingDotDamage(GetGUID(), triggered_spell_id); break; } // Glyph of Ice Block case 56372: { if (GetTypeId() != TYPEID_PLAYER) return false; SpellCooldowns const cooldowns = this->ToPlayer()->GetSpellCooldowns(); // remove cooldowns on all ranks of Frost Nova for (SpellCooldowns::const_iterator itr = cooldowns.begin(); itr != cooldowns.end(); ++itr) { SpellEntry const* cdSpell = sSpellStore.LookupEntry( itr->first); // Frost Nova if (cdSpell && cdSpell->SpellFamilyName == SPELLFAMILY_MAGE && cdSpell->SpellFamilyFlags [0] & 0x00000040) this->ToPlayer()->RemoveSpellCooldown( cdSpell->Id, true); } break; } } break; } // Blessing of Ancient Kings (Val'anyr, Hammer of Ancient Kings) case 64411: { if (!pVictim) return false; basepoints0 = int32(CalculatePctN(damage, 15)); if (AuraEffect* aurEff = pVictim->GetAuraEffect(64413, 0, GetGUID())) { // The shield can grow to a maximum size of 20, 000 damage absorbtion aurEff->SetAmount( std::max < int32 > (aurEff->GetAmount() + basepoints0, 20000)); // Refresh and return to prevent replacing the aura aurEff->GetBase()->RefreshDuration(); return true; } target = pVictim; triggered_spell_id = 64413; break; } case SPELLFAMILY_WARRIOR: { switch (dummySpell->Id) { // Sweeping Strikes case 12328: { target = SelectNearbyTarget(); if (!target) return false; triggered_spell_id = 26654; break; } // Victorious case 32216: { RemoveAura(dummySpell->Id); return false; } // Improved Spell Reflection case 59088: case 59089: { triggered_spell_id = 59725; target = this; break; } } // Retaliation if (dummySpell->SpellFamilyFlags [1] & 0x8) { // check attack comes not from behind if (!HasInArc(M_PI, pVictim)) return false; triggered_spell_id = 22858; break; } // Second Wind if (dummySpell->SpellIconID == 1697) { // only for spells and hit/crit (trigger start always) and not start from self casted spells (5530 Mace Stun Effect for example) if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT | PROC_EX_CRITICAL_HIT)) || this == pVictim) return false; // Need stun or root mechanic if (!(GetAllSpellMechanicMask(procSpell) & ((1 << MECHANIC_ROOT) | (1 << MECHANIC_STUN)))) return false; switch (dummySpell->Id) { case 29838: triggered_spell_id = 29842; break; case 29834: triggered_spell_id = 29841; break; case 42770: triggered_spell_id = 42771; break; default: sLog->outError( "Unit::HandleDummyAuraProc: non handled spell id: %u (SW)", dummySpell->Id); return false; } target = this; break; } /* // Damage Shield if (dummySpell->SpellIconID == 3214) { triggered_spell_id = 59653; // % of amount blocked basepoints0 = GetShieldBlockValue() * triggerAmount / 100; break; }*/ // Glyph of Blocking if (dummySpell->Id == 58375) { triggered_spell_id = 58374; break; } // Glyph of Sunder Armor if (dummySpell->Id == 58387) { if (!pVictim || !pVictim->isAlive() || !procSpell) return false; target = SelectNearbyTarget(); if (!target || target == pVictim) return false; CastSpell(target, 58567, true); return true; } break; } case SPELLFAMILY_WARLOCK: { // Seed of Corruption if (dummySpell->SpellFamilyFlags [1] & 0x00000010) { if (procSpell && procSpell->SpellFamilyFlags [1] & 0x8000) return false; // if damage is more than need or target die from damage deal finish spell if (triggeredByAura->GetAmount() <= int32(damage) || GetHealth() <= damage) { // remember guid before aura delete uint64 casterGuid = triggeredByAura->GetCasterGUID(); // Remove aura (before cast for prevent infinite loop handlers) RemoveAurasDueToSpell(triggeredByAura->GetId()); uint32 spell = sSpellMgr->GetSpellWithRank(27285, sSpellMgr->GetSpellRank(dummySpell->Id)); // Cast finish spell (triggeredByAura already not exist!) if (Unit* caster = GetUnit(*this, casterGuid)) caster->CastSpell( this, spell, true, castItem); return true; // no hidden cooldown } // Damage counting triggeredByAura->SetAmount( triggeredByAura->GetAmount() - damage); return true; } // Seed of Corruption (Mobs cast) - no die req if (dummySpell->SpellFamilyFlags.IsEqual(0, 0, 0) && dummySpell->SpellIconID == 1932) { // if damage is more than need deal finish spell if (triggeredByAura->GetAmount() <= int32(damage)) { // remember guid before aura delete uint64 casterGuid = triggeredByAura->GetCasterGUID(); // Remove aura (before cast for prevent infinite loop handlers) RemoveAurasDueToSpell(triggeredByAura->GetId()); // Cast finish spell (triggeredByAura already not exist!) if (Unit* caster = GetUnit(*this, casterGuid)) caster->CastSpell( this, 32865, true, castItem); return true; // no hidden cooldown } // Damage counting triggeredByAura->SetAmount( triggeredByAura->GetAmount() - damage); return true; } // Fel Synergy if (dummySpell->SpellIconID == 3222) { target = GetGuardianPet(); if (!target) return false; basepoints0 = damage * triggerAmount / 100; triggered_spell_id = 54181; break; } switch (dummySpell->Id) { // Siphon Life case 63108: { // Glyph of Siphon Life if (HasAura(56216)) triggerAmount += triggerAmount / 4; triggered_spell_id = 63106; target = this; basepoints0 = int32(damage * triggerAmount / 100); break; } // Glyph of Shadowflame case 63310: { triggered_spell_id = 63311; break; } // Nightfall case 18094: case 18095: // Glyph of corruption case 56218: { target = this; triggered_spell_id = 17941; break; } //Soul Leech case 30293: case 30295: case 30296: { // Improved Soul Leech AuraEffectList const& SoulLeechAuras = GetAuraEffectsByType( SPELL_AURA_DUMMY); for (Unit::AuraEffectList::const_iterator i = SoulLeechAuras.begin(); i != SoulLeechAuras.end(); ++i) { if ((*i)->GetId() == 54117 || (*i)->GetId() == 54118) { if ((*i)->GetEffIndex() != 0) continue; basepoints0 = int32((*i)->GetAmount()); target = GetGuardianPet(); if (target) { // regen mana for pet CastCustomSpell(target, 54607, &basepoints0, NULL, NULL, true, castItem, triggeredByAura); } // regen mana for caster CastCustomSpell(this, 59117, &basepoints0, NULL, NULL, true, castItem, triggeredByAura); // Get second aura of spell for replenishment effect on party if (AuraEffect const * aurEff = (*i)->GetBase()->GetEffect(1)) { // Replenishment - roll chance if (roll_chance_i(aurEff->GetAmount())) { CastSpell(this, 57669, true, castItem, triggeredByAura); } } break; } } // health basepoints0 = int32(GetHealth() * triggerAmount / 100); target = this; triggered_spell_id = 30294; break; } // Shadowflame (Voidheart Raiment set bonus) case 37377: { triggered_spell_id = 37379; break; } // Pet Healing (Corruptor Raiment or Rift Stalker Armor) case 37381: { target = GetGuardianPet(); if (!target) return false; // heal amount basepoints0 = damage * triggerAmount / 100; triggered_spell_id = 37382; break; } // Shadowflame Hellfire (Voidheart Raiment set bonus) case 39437: { triggered_spell_id = 37378; break; } // Fel Armor case 28176: { basepoints0 = int32(damage * triggerAmount / 100); triggered_spell_id = 96379; break; } } break; } case SPELLFAMILY_PRIEST: { // Vampiric Touch if (dummySpell->SpellFamilyFlags [1] & 0x00000400) { if (!pVictim || !pVictim->isAlive()) return false; if (effIndex != 0) return false; // pVictim is caster of aura if (triggeredByAura->GetCasterGUID() != pVictim->GetGUID()) return false; // Energize 0.25% of max. mana pVictim->CastSpell(pVictim, 57669, true, castItem, triggeredByAura); return true; // no hidden cooldown } // Divine Aegis if (dummySpell->SpellIconID == 2820) { if (!target) return false; // Multiple effects stack, so let's try to find this aura. int32 bonus = 0; if (AuraEffect *aurEff = target->GetAuraEffect(47753, 0)) bonus = aurEff->GetAmount(); basepoints0 = damage * triggerAmount / 100 + bonus; if (basepoints0 > target->getLevel() * 125) basepoints0 = target->getLevel() * 125; triggered_spell_id = 47753; break; } // Body and Soul if (dummySpell->SpellIconID == 2218) { // Proc only from Abolish desease on self cast if (procSpell->Id != 552 || pVictim != this || !roll_chance_i(triggerAmount)) return false; triggered_spell_id = 64136; target = this; break; } switch (dummySpell->Id) { // Vampiric Embrace case 15286: { if (!pVictim || !pVictim->isAlive() || procSpell->SpellFamilyFlags [1] & 0x80000) return false; // heal amount int32 team = triggerAmount * damage / 500; int32 self = triggerAmount * damage / 100 - team; CastCustomSpell(this, 15290, &team, &self, NULL, true, castItem, triggeredByAura); return true; // no hidden cooldown } // Priest Tier 6 Trinket (Ashtongue Talisman of Acumen) case 40438: { // Shadow Word: Pain if (procSpell->SpellFamilyFlags [0] & 0x8000) triggered_spell_id = 40441; // Renew else if (procSpell->SpellFamilyFlags [0] & 0x40) triggered_spell_id = 40440; else return false; target = this; break; } // Glyph of Prayer of Healing case 55680: { triggered_spell_id = 56161; SpellEntry const* GoPoH = sSpellStore.LookupEntry( triggered_spell_id); if (!GoPoH) return false; int EffIndex = 0; for (uint8 i = 0; i < MAX_SPELL_EFFECTS; i++) { if (GoPoH->Effect [i] == SPELL_EFFECT_APPLY_AURA) { EffIndex = i; break; } } int32 tickcount = GetSpellMaxDuration(GoPoH) / GoPoH->EffectAmplitude [EffIndex]; if (!tickcount) return false; basepoints0 = damage * triggerAmount / tickcount / 100; break; } // Improved Shadowform case 47570: case 47569: { if (!roll_chance_i(triggerAmount)) return false; RemoveMovementImpairingAuras(); break; } // Glyph of Dispel Magic case 55677: { // Dispel Magic shares spellfamilyflag with abolish disease if (procSpell->SpellIconID != 74) return false; if (!target || !target->IsFriendlyTo(this)) return false; basepoints0 = int32( target->CountPctFromMaxHealth(triggerAmount)); triggered_spell_id = 56131; break; } // Oracle Healing Bonus ("Garments of the Oracle" set) case 26169: { // heal amount basepoints0 = int32(damage * 10 / 100); target = this; triggered_spell_id = 26170; break; } // Frozen Shadoweave (Shadow's Embrace set) warning! its not only priest set case 39372: { if (!procSpell || (GetSpellSchoolMask(procSpell) & (SPELL_SCHOOL_MASK_FROST | SPELL_SCHOOL_MASK_SHADOW)) == 0) return false; // heal amount basepoints0 = damage * triggerAmount / 100; target = this; triggered_spell_id = 39373; break; } // Greater Heal (Vestments of Faith (Priest Tier 3) - 4 pieces bonus) case 28809: { triggered_spell_id = 28810; break; } // Priest T10 Healer 2P Bonus case 70770: { // Flash Heal if (procSpell->SpellFamilyFlags [0] & 0x800) { triggered_spell_id = 70772; SpellEntry const* blessHealing = sSpellStore.LookupEntry(triggered_spell_id); if (!blessHealing) return false; basepoints0 = int32( triggerAmount * damage / 100 / (GetSpellMaxDuration( blessHealing) / blessHealing->EffectAmplitude [0])); } break; } //Mind Melt case 87160: case 81292: { if (procSpell->Id != 73510) return false; break; } // Atonement case 14523: case 81749: { basepoints0 = int32(CalculatePctN(damage, triggerAmount)); triggered_spell_id = 81751; target = this; break; } // Train of Thought case 92295: case 92297: if (procSpell->Id == 585) { if (Player* caster = triggeredByAura->GetCaster()->ToPlayer()) { if (caster->HasSpellCooldown(47540)) { uint32 newCooldownDelay = caster->GetSpellCooldownDelay(47540); if (newCooldownDelay <= 0.5) newCooldownDelay = 0; else newCooldownDelay -= 0.5; caster->AddSpellCooldown(47540, 0, uint32(time(NULL) + newCooldownDelay)); WorldPacket data(SMSG_MODIFY_COOLDOWN, 4 + 8 + 4); data << uint32(47540); data << uint64(caster->GetGUID()); data << int32(-500); caster->GetSession()->SendPacket(&data); } } } if (procSpell->Id == 2060) { if (Player* caster = triggeredByAura->GetCaster()->ToPlayer()) { if (caster->HasSpellCooldown(89485)) { uint32 newCooldownDelay = caster->GetSpellCooldownDelay(89485); if (newCooldownDelay <= 5) newCooldownDelay = 0; else newCooldownDelay -= 5; caster->AddSpellCooldown(89485, 0, uint32(time(NULL) + newCooldownDelay)); WorldPacket data(SMSG_MODIFY_COOLDOWN, 4 + 8 + 4); data << uint32(89485); // Spell ID data << uint64(caster->GetGUID()); // Player GUID data << int32(-5000); // Cooldown mod in milliseconds caster->GetSession()->SendPacket(&data); } } } break; } break; } case SPELLFAMILY_DRUID: { switch (dummySpell->Id) { // Glyph of Innervate case 54832: { if (procSpell->SpellIconID != 62) return false; int32 mana_perc = SpellMgr::CalculateSpellEffectAmount( triggeredByAura->GetSpellProto(), triggeredByAura->GetEffIndex()); basepoints0 = uint32( (GetCreatePowers(POWER_MANA) * mana_perc / 100) / 10); triggered_spell_id = 54833; target = this; break; } // Glyph of Starfire case 54845: { triggered_spell_id = 54846; break; } // Glyph of Shred case 54815: { if (!target) return false; // try to find spell Rip on the target if (AuraEffect const *AurEff = target->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x00800000, 0x0, 0x0, GetGUID())) { // Rip's max duration, note: spells which modifies Rip's duration also counted like Glyph of Rip uint32 CountMin = AurEff->GetBase()->GetMaxDuration(); // just Rip's max duration without other spells uint32 CountMax = GetSpellMaxDuration( AurEff->GetSpellProto()); // add possible auras' and Glyph of Shred's max duration CountMax += 3 * triggerAmount * 1000; // Glyph of Shred -> +6 seconds CountMax += HasAura(54818) ? 4 * 1000 : 0; // Glyph of Rip -> +4 seconds CountMax += HasAura(60141) ? 4 * 1000 : 0; // Rip Duration/Lacerate Damage -> +4 seconds // if min < max -> that means caster didn't cast 3 shred yet // so set Rip's duration and max duration if (CountMin < CountMax) { AurEff->GetBase()->SetDuration( AurEff->GetBase()->GetDuration() + triggerAmount * 1000); AurEff->GetBase()->SetMaxDuration( CountMin + triggerAmount * 1000); return true; } } // if not found Rip return false; } // Glyph of Rake case 54821: { if (procSpell->SpellVisual [0] == 750 && procSpell->EffectApplyAuraName [1] == 3) { if (target && target->GetTypeId() == TYPEID_UNIT) { triggered_spell_id = 54820; break; } } return false; } // Leader of the Pack case 24932: { if (triggerAmount <= 0) return false; basepoints0 = int32(CountPctFromMaxHealth(triggerAmount)); target = this; triggered_spell_id = 34299; if (triggeredByAura->GetCasterGUID() != GetGUID()) break; int32 basepoints1 = triggerAmount * 2; // Mana Part CastCustomSpell(this, 68285, &basepoints1, 0, 0, true, 0, triggeredByAura); break; } // Healing Touch (Dreamwalker Raiment set) case 28719: { // mana back basepoints0 = int32(procSpell->manaCost * 30 / 100); target = this; triggered_spell_id = 28742; break; } // Glyph of Rejuvenation case 54754: { if (!pVictim || !pVictim->HealthBelowPct(uint32(triggerAmount))) return false; basepoints0 = int32(triggerAmount * damage / 100); triggered_spell_id = 54755; break; } // Healing Touch Refund (Idol of Longevity trinket) case 28847: { target = this; triggered_spell_id = 28848; break; } // Mana Restore (Malorne Raiment set / Malorne Regalia set) case 37288: case 37295: { target = this; triggered_spell_id = 37238; break; } // Druid Tier 6 Trinket case 40442: { float chance; // Starfire if (procSpell->SpellFamilyFlags [0] & 0x4) { triggered_spell_id = 40445; chance = 25.0f; } // Rejuvenation else if (procSpell->SpellFamilyFlags [0] & 0x10) { triggered_spell_id = 40446; chance = 25.0f; } // Mangle (Bear) and Mangle (Cat) else if (procSpell->SpellFamilyFlags [1] & 0x00000440) { triggered_spell_id = 40452; chance = 40.0f; } else return false; if (!roll_chance_f(chance)) return false; target = this; break; } // Maim Interrupt case 44835: { // Deadly Interrupt Effect triggered_spell_id = 32747; break; } // Tricks of the Trade case 57934: { if (Unit* unitTarget = GetMisdirectionTarget()) { RemoveAura(dummySpell->Id, GetGUID(), 0, AURA_REMOVE_BY_DEFAULT); CastSpell(this, 59628, true); CastSpell(unitTarget, 57933, true); return true; } return false; } // Item - Druid T10 Balance 4P Bonus case 70723: { // Wrath & Starfire if ((procSpell->SpellFamilyFlags [0] & 0x5) && (procEx & PROC_EX_CRITICAL_HIT)) { triggered_spell_id = 71023; SpellEntry const* triggeredSpell = sSpellStore.LookupEntry(triggered_spell_id); if (!triggeredSpell) return false; basepoints0 = int32( triggerAmount * damage / 100 / (GetSpellMaxDuration( triggeredSpell) / triggeredSpell->EffectAmplitude [0])); // Add remaining ticks to damage done basepoints0 += pVictim->GetRemainingDotDamage(GetGUID(), triggered_spell_id); } break; } // Item - Druid T10 Restoration 4P Bonus (Rejuvenation) case 70664: { // Proc only from normal Rejuvenation if (procSpell->SpellVisual [0] != 32) return false; Player* caster = ToPlayer(); if (!caster) return false; if (!caster->GetGroup() && pVictim == this) return false; CastCustomSpell(70691, SPELLVALUE_BASE_POINT0, damage, pVictim, true); return true; } } // Living Seed if (dummySpell->SpellIconID == 2860) { triggered_spell_id = 48504; basepoints0 = triggerAmount * damage / 100; break; } // King of the Jungle else if (dummySpell->SpellIconID == 2850) { // Effect 0 - mod damage while having Enrage if (effIndex == 0) { if (!(procSpell->SpellFamilyFlags [0] & 0x00080000)) return false; triggered_spell_id = 51185; basepoints0 = triggerAmount; target = this; break; } // Effect 1 - Tiger's Fury restore energy else if (effIndex == 1) { if (!(procSpell->SpellFamilyFlags [2] & 0x00000800)) return false; triggered_spell_id = 51178; basepoints0 = triggerAmount; target = this; break; } } break; } case SPELLFAMILY_ROGUE: { switch (dummySpell->Id) { // Glyph of Backstab case 56800: { triggered_spell_id = 63975; break; } // Deadly Throw Interrupt case 32748: { // Prevent cast Deadly Throw Interrupt on self from last effect (apply dummy) of Deadly Throw if (this == pVictim) return false; triggered_spell_id = 32747; break; } case 51698: // Honor Among Thieves case 51700: case 51701: { if (Player* pTarget = triggeredByAura->GetCaster()->ToPlayer()) { if (pTarget->HasSpellCooldown(51699)) break; Unit* spellTarget = ObjectAccessor::GetUnit(*pTarget, pTarget->GetComboTarget()); if (!spellTarget) spellTarget = pTarget->GetSelectedUnit(); if (spellTarget && pTarget->canAttack(spellTarget)) pTarget->CastSpell(spellTarget, 51699, true); } break; } } // Cut to the Chase if (dummySpell->SpellIconID == 2909) { // "refresh your Slice and Dice duration to its 5 combo point maximum" // lookup Slice and Dice if (AuraEffect const* aur = GetAuraEffect(SPELL_AURA_MOD_MELEE_HASTE, SPELLFAMILY_ROGUE, 0x40000, 0, 0)) { aur->GetBase()->SetDuration( GetSpellMaxDuration(aur->GetSpellProto()), true); return true; } return false; } // Deadly Brew else if (dummySpell->SpellIconID == 2963) { triggered_spell_id = 3409; break; } // Quick Recovery else if (dummySpell->SpellIconID == 2116) { if (!procSpell) return false; // energy cost save basepoints0 = procSpell->manaCost * triggerAmount / 100; if (basepoints0 <= 0) return false; target = this; triggered_spell_id = 31663; break; } break; } case SPELLFAMILY_HUNTER: { // Thrill of the Hunt if (dummySpell->SpellIconID == 2236) { if (!procSpell) return false; Spell * spell = ToPlayer()->m_spellModTakingSpell; // Disable charge drop because of Lock and Load ToPlayer()->SetSpellModTakingSpell(spell, false); // Explosive Shot if (procSpell->SpellFamilyFlags [2] & 0x200) { if (!pVictim) return false; if (AuraEffect const* pEff = pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_DUMMY, SPELLFAMILY_HUNTER, 0x0, 0x80000000, 0x0, GetGUID())) basepoints0 = CalculatePowerCost( pEff->GetSpellProto(), this, SpellSchoolMask( pEff->GetSpellProto()->SchoolMask)) * 4 / 10 / 3; } else basepoints0 = CalculatePowerCost(procSpell, this, SpellSchoolMask(procSpell->SchoolMask)) * 4 / 10; ToPlayer()->SetSpellModTakingSpell(spell, true); if (basepoints0 <= 0) return false; target = this; triggered_spell_id = 34720; break; } // Hunting Party if (dummySpell->SpellIconID == 3406) { triggered_spell_id = 57669; target = this; break; } // Improved Mend Pet if (dummySpell->SpellIconID == 267) { int32 chance = SpellMgr::CalculateSpellEffectAmount( triggeredByAura->GetSpellProto(), triggeredByAura->GetEffIndex()); if (!roll_chance_i(chance)) return false; triggered_spell_id = 24406; break; } // Lock and Load if (dummySpell->SpellIconID == 3579) { // Proc only from periodic (from trap activation proc another aura of this spell) if (!(procFlag & PROC_FLAG_DONE_PERIODIC) || !roll_chance_i(triggerAmount)) return false; triggered_spell_id = 56453; target = this; break; } // Rapid Recuperation if (dummySpell->SpellIconID == 3560) { // This effect only from Rapid Killing (mana regen) if (!(procSpell->SpellFamilyFlags [1] & 0x01000000)) return false; target = this; switch (dummySpell->Id) { case 53228: // Rank 1 triggered_spell_id = 56654; break; case 53232: // Rank 2 triggered_spell_id = 58882; break; } break; } // Glyph of Mend Pet if (dummySpell->Id == 57870) { pVictim->CastSpell(pVictim, 57894, true, NULL, NULL, GetGUID()); return true; } // Misdirection if (dummySpell->Id == 34477) { RemoveAura(dummySpell->Id, GetGUID(), 0, AURA_REMOVE_BY_DEFAULT); CastSpell(this, 35079, true); return true; } break; } case SPELLFAMILY_PALADIN: { // Seal of Righteousness - melee proc dummy (addition ${$MWS*(0.011*$AP+0.022*$SPH)} damage) if (dummySpell->Id == 20154) { if (effIndex != 0) return false; triggered_spell_id = 25742; float ap = GetTotalAttackPowerValue(BASE_ATTACK); int32 holy = SpellBaseDamageBonus(SPELL_SCHOOL_MASK_HOLY) + SpellBaseDamageBonusForVictim(SPELL_SCHOOL_MASK_HOLY, pVictim); basepoints0 = (int32) GetAttackTime(BASE_ATTACK) * int32(ap * 0.011f + 0.022f * holy) / 1000; break; } // Light's Beacon - Beacon of Light if (dummySpell->Id == 53651) { // Get target of beacon of light if (Unit * beaconTarget = triggeredByAura->GetBase()->GetCaster()) { // do not proc when target of beacon of light is healed if (beaconTarget == this) return false; // check if it was heal by paladin which casted this beacon of light if (beaconTarget->GetAura(53563, pVictim->GetGUID())) { if (beaconTarget->IsWithinLOSInMap(pVictim)) { basepoints0 = damage; triggered_spell_id = 53652; target = beaconTarget; break; } } } return false; } // Righteous Vengeance if (dummySpell->SpellIconID == 3025) { // 4 damage tick basepoints0 = triggerAmount * damage / 400; triggered_spell_id = 61840; // Add remaining ticks to damage done basepoints0 += pVictim->GetRemainingDotDamage(GetGUID(), triggered_spell_id); break; } // Sheath of Light if (dummySpell->SpellIconID == 3030) { // 4 healing tick basepoints0 = triggerAmount * damage / 400; triggered_spell_id = 54203; break; } switch (dummySpell->Id) { // Judgements of the Bold case 89901: { target = this; triggered_spell_id = 89906; break; } // Selfless Healer case 85803: case 85804: { if (pVictim == this) return false; break; } // Ancient Healer case 86674: { int32 bp0 = damage; int32 bp1 = ((bp0 * 10) / 100); if (!bp0 || !bp1) return false; if (pVictim && pVictim->IsFriendlyTo(this)) CastCustomSpell( pVictim, 86678, &bp0, &bp1, 0, true, NULL, triggeredByAura, 0); else CastCustomSpell(this, 86678, &bp0, &bp1, 0, true, NULL, triggeredByAura, 0); return true; } // Ancient Crusader - Player case 86701: { target = this; triggered_spell_id = 86700; break; } // Uncomment this once the guardian is receiving the aura via // creature template addon and redirect aura procs to the owner // Ancient Crusader - Guardian /* case 86703: { Unit* owner = this->GetOwner(); if (!owner) return false; owner->CastSpell(owner, 86700, true); return true; }*/ // Long Arm of The law case 87168: case 87172: { if (roll_chance_f(triggerAmount) && !this->IsWithinDistInMap(pVictim, 15.0f)) { target = this; triggered_spell_id = 87173; break; } } // Divine purpose case 85117: case 86172: { if (roll_chance_f(triggerAmount)) { target = this; triggered_spell_id = 90174; break; } } // Judgement of Light case 20185: { if (!pVictim) // Crash Fix in Unit::HandleDummyAuraProc. return false; // 2% of base mana basepoints0 = int32(pVictim->CountPctFromMaxHealth(2)); pVictim->CastCustomSpell(pVictim, 20267, &basepoints0, 0, 0, true, 0, triggeredByAura); return true; } // Judgement of Wisdom case 20186: { if (pVictim && pVictim->isAlive() && pVictim->getPowerType() == POWER_MANA) { // 2% of base mana basepoints0 = int32(pVictim->GetCreateMana() * 2 / 100); pVictim->CastCustomSpell(pVictim, 20268, &basepoints0, NULL, NULL, true, 0, triggeredByAura); } return true; } // Holy Power (Redemption Armor set) case 28789: { if (!pVictim) return false; // Set class defined buff switch (pVictim->getClass()) { case CLASS_PALADIN: case CLASS_PRIEST: case CLASS_SHAMAN: case CLASS_DRUID: triggered_spell_id = 28795; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d. break; case CLASS_MAGE: case CLASS_WARLOCK: triggered_spell_id = 28793; // Increases the friendly target's spell damage and healing by up to $s1 for $d. break; case CLASS_HUNTER: case CLASS_ROGUE: triggered_spell_id = 28791; // Increases the friendly target's attack power by $s1 for $d. break; case CLASS_WARRIOR: triggered_spell_id = 28790; // Increases the friendly target's armor break; default: return false; } break; } case 25899: // Greater Blessing of Sanctuary case 20911: // Blessing of Sanctuary { target = this; switch (target->getPowerType()) { case POWER_MANA: triggered_spell_id = 57319; break; default: return false; } break; } // Seal of Vengeance (damage calc on apply aura) case 31801: { if (effIndex != 0) // effect 1, 2 used by seal unleashing code return false; // At melee attack or Hammer of the Righteous spell damage considered as melee attack bool stacker = !procSpell || procSpell->Id == 53595; // spells with SPELL_DAMAGE_CLASS_MELEE excluding Judgements bool damager = procSpell && procSpell->EquippedItemClass != -1; if (!stacker && !damager) return false; triggered_spell_id = 31803; // On target with 5 stacks of Holy Vengeance direct damage is done if (Aura * aur = pVictim->GetAura(triggered_spell_id, GetGUID())) { if (aur->GetStackAmount() == 5) { if (stacker) aur->RefreshDuration(); CastSpell(pVictim, 42463, true); return true; } } if (!stacker) return false; break; } // Seal of Corruption case 53736: { if (effIndex != 0) // effect 1, 2 used by seal unleashing code return false; // At melee attack or Hammer of the Righteous spell damage considered as melee attack bool stacker = !procSpell || procSpell->Id == 53595; // spells with SPELL_DAMAGE_CLASS_MELEE excluding Judgements bool damager = procSpell && procSpell->EquippedItemClass != -1; if (!stacker && !damager) return false; triggered_spell_id = 31803; // On target with 5 stacks of Blood Corruption direct damage is done if (Aura * aur = pVictim->GetAura(triggered_spell_id, GetGUID())) { if (aur->GetStackAmount() == 5) { if (stacker) aur->RefreshDuration(); CastSpell(pVictim, 53739, true); return true; } } if (!stacker) return false; break; } // Spiritual Attunement case 31785: case 33776: { // if healed by another unit (pVictim) if (this == pVictim) return false; // heal amount basepoints0 = triggerAmount * (std::min(damage, GetMaxHealth() - GetHealth())) / 100; target = this; if (basepoints0) triggered_spell_id = 31786; break; } // Paladin Tier 6 Trinket (Ashtongue Talisman of Zeal) case 40470: { if (!procSpell) return false; float chance; // Flash of light/Holy light if (procSpell->SpellFamilyFlags [0] & 0xC0000000) { triggered_spell_id = 40471; chance = 15.0f; } // Judgement (any) else if (GetSpellSpecific(procSpell) == SPELL_SPECIFIC_JUDGEMENT) { triggered_spell_id = 40472; chance = 50.0f; } else return false; if (!roll_chance_f(chance)) return false; break; } // Glyph of Flash of Light case 54936: { triggered_spell_id = 54957; basepoints0 = triggerAmount * damage / 100; break; } // Glyph of Holy Light case 54937: { triggered_spell_id = 54968; basepoints0 = triggerAmount * damage / 100; break; } case 71406: // Tiny Abomination in a Jar { if (!pVictim || !pVictim->isAlive()) return false; CastSpell(this, 71432, true, NULL, triggeredByAura); Aura const* dummy = GetAura(71432); if (!dummy || dummy->GetStackAmount() < 8) return false; RemoveAurasDueToSpell(71432); triggered_spell_id = 71433; // default main hand attack // roll if offhand if (Player const* player = ToPlayer()) if (player->GetWeaponForAttack( OFF_ATTACK, true) && urand(0, 1)) triggered_spell_id = 71434; target = pVictim; break; } case 71545: // Tiny Abomination in a Jar (Heroic) { if (!pVictim || !pVictim->isAlive()) return false; CastSpell(this, 71432, true, NULL, triggeredByAura); Aura const* dummy = GetAura(71432); if (!dummy || dummy->GetStackAmount() < 7) return false; RemoveAurasDueToSpell(71432); triggered_spell_id = 71433; // default main hand attack // roll if offhand if (Player const* player = ToPlayer()) if (player->GetWeaponForAttack( OFF_ATTACK, true) && urand(0, 1)) triggered_spell_id = 71434; target = pVictim; break; } } break; } case SPELLFAMILY_SHAMAN: { switch (dummySpell->Id) { // Earthen Power (Rank 1, 2) case 51523: case 51524: { // Totem itself must be a caster of this spell Unit* caster = NULL; for (ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr) { if ((*itr)->GetEntry() != 2630) continue; caster = (*itr); break; } if (!caster) return false; caster->CastSpell(caster, 59566, true, castItem, triggeredByAura, originalCaster); return true; } // Tidal Force case 55198: { // Remove aura stack from caster RemoveAuraFromStack(55166); // drop charges return false; } // Totemic Power (The Earthshatterer set) case 28823: { if (!pVictim) return false; // Set class defined buff switch (pVictim->getClass()) { case CLASS_PALADIN: case CLASS_PRIEST: case CLASS_SHAMAN: case CLASS_DRUID: triggered_spell_id = 28824; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d. break; case CLASS_MAGE: case CLASS_WARLOCK: triggered_spell_id = 28825; // Increases the friendly target's spell damage and healing by up to $s1 for $d. break; case CLASS_HUNTER: case CLASS_ROGUE: triggered_spell_id = 28826; // Increases the friendly target's attack power by $s1 for $d. break; case CLASS_WARRIOR: triggered_spell_id = 28827; // Increases the friendly target's armor break; default: return false; } break; } // Lesser Healing Wave (Totem of Flowing Water Relic) case 28849: { target = this; triggered_spell_id = 28850; break; } // Windfury Weapon (Passive) 1-5 Ranks case 33757: { if (GetTypeId() != TYPEID_PLAYER || !castItem || !castItem->IsEquipped() || !pVictim || !pVictim->isAlive()) return false; // custom cooldown processing case if (cooldown && ToPlayer()->HasSpellCooldown(dummySpell->Id)) return false; if (triggeredByAura->GetBase() && castItem->GetGUID() != triggeredByAura->GetBase()->GetCastItemGUID()) return false; WeaponAttackType attType = WeaponAttackType( this->ToPlayer()->GetAttackBySlot( castItem->GetSlot())); if ((attType != BASE_ATTACK && attType != OFF_ATTACK) || !isAttackReady(attType)) return false; // Now compute real proc chance... uint32 chance = 20; this->ToPlayer()->ApplySpellMod(dummySpell->Id, SPELLMOD_CHANCE_OF_SUCCESS, chance); Item* addWeapon = this->ToPlayer()->GetWeaponForAttack( attType == BASE_ATTACK ? OFF_ATTACK : BASE_ATTACK, true); uint32 enchant_id_add = addWeapon ? addWeapon->GetEnchantmentId( EnchantmentSlot( TEMP_ENCHANTMENT_SLOT)) : 0; SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry( enchant_id_add); if (pEnchant && pEnchant->spellid [0] == dummySpell->Id) chance += 14; if (!roll_chance_i(chance)) return false; // Now amount of extra power stored in 1 effect of Enchant spell // Get it by item enchant id uint32 spellId; switch (castItem->GetEnchantmentId( EnchantmentSlot(TEMP_ENCHANTMENT_SLOT))) { case 283: spellId = 8232; break; default: { sLog->outError( "Unit::HandleDummyAuraProc: non handled item enchantment (rank?) %u for spell id: %u (Windfury)", castItem->GetEnchantmentId( EnchantmentSlot( TEMP_ENCHANTMENT_SLOT)), dummySpell->Id); return false; } } SpellEntry const* windfurySpellEntry = sSpellStore.LookupEntry(spellId); if (!windfurySpellEntry) { sLog->outError( "Unit::HandleDummyAuraProc: non existed spell id: %u (Windfury)", spellId); return false; } int32 extra_attack_power = CalculateSpellDamage(pVictim, windfurySpellEntry, 1); // Value gained from additional AP basepoints0 = int32( extra_attack_power / 14.0f * GetAttackTime(BASE_ATTACK) / 1000); triggered_spell_id = 25504; // apply cooldown before cast to prevent processing itself if (cooldown) ToPlayer()->AddSpellCooldown(dummySpell->Id, 0, time(NULL) + cooldown); // triggering three extra attacks for (uint32 i = 0; i < 3; ++i) CastCustomSpell(pVictim, triggered_spell_id, &basepoints0, NULL, NULL, true, castItem, triggeredByAura); return true; } // Shaman Tier 6 Trinket case 40463: { if (!procSpell) return false; float chance; if (procSpell->SpellFamilyFlags [0] & 0x1) { triggered_spell_id = 40465; // Lightning Bolt chance = 15.0f; } else if (procSpell->SpellFamilyFlags [0] & 0x80) { triggered_spell_id = 40465; // Lesser Healing Wave chance = 10.0f; } else if (procSpell->SpellFamilyFlags [1] & 0x00000010) { triggered_spell_id = 40466; // Stormstrike chance = 50.0f; } else return false; if (!roll_chance_f(chance)) return false; target = this; break; } // Glyph of Healing Wave case 55440: { // Not proc from self heals if (this == pVictim) return false; basepoints0 = triggerAmount * damage / 100; target = this; triggered_spell_id = 55533; break; } // Spirit Hunt case 58877: { // Cast on owner target = GetOwner(); if (!target) return false; basepoints0 = triggerAmount * damage / 100; triggered_spell_id = 58879; break; } // Shaman T8 Elemental 4P Bonus case 64928: { basepoints0 = int32(triggerAmount * damage / 100); triggered_spell_id = 64930; // Electrified break; } // Shaman T9 Elemental 4P Bonus case 67228: { // Lava Burst if (procSpell->SpellFamilyFlags [1] & 0x1000) { triggered_spell_id = 71824; SpellEntry const* triggeredSpell = sSpellStore.LookupEntry(triggered_spell_id); if (!triggeredSpell) return false; basepoints0 = int32( triggerAmount * damage / 100 / (GetSpellMaxDuration( triggeredSpell) / triggeredSpell->EffectAmplitude [0])); } break; } // Item - Shaman T10 Restoration 4P Bonus case 70808: { // Chain Heal if ((procSpell->SpellFamilyFlags [0] & 0x100) && (procEx & PROC_EX_CRITICAL_HIT)) { triggered_spell_id = 70809; SpellEntry const* triggeredSpell = sSpellStore.LookupEntry(triggered_spell_id); if (!triggeredSpell) return false; basepoints0 = int32( triggerAmount * damage / 100 / (GetSpellMaxDuration( triggeredSpell) / triggeredSpell->EffectAmplitude [0])); } break; } // Item - Shaman T10 Elemental 2P Bonus case 70811: { // Lightning Bolt & Chain Lightning if (procSpell->SpellFamilyFlags [0] & 0x3) { if (ToPlayer()->HasSpellCooldown(16166)) { uint32 newCooldownDelay = ToPlayer()->GetSpellCooldownDelay(16166); if (newCooldownDelay < 3) newCooldownDelay = 0; else newCooldownDelay -= 2; ToPlayer()->AddSpellCooldown(16166, 0, uint32(time(NULL) + newCooldownDelay)); WorldPacket data(SMSG_MODIFY_COOLDOWN, 4 + 8 + 4); data << uint32(16166); // Spell ID data << uint64(GetGUID()); // Player GUID data << int32(-2000); // Cooldown mod in milliseconds ToPlayer()->GetSession()->SendPacket(&data); return true; } } return false; } // Item - Shaman T10 Elemental 4P Bonus case 70817: { if (!target) return false; // try to find spell Flame Shock on the target if (AuraEffect const* aurEff = target->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_SHAMAN, 0x10000000, 0x0, 0x0, GetGUID())) { Aura* flameShock = aurEff->GetBase(); int32 maxDuration = flameShock->GetMaxDuration(); int32 newDuration = flameShock->GetDuration() + 2 * aurEff->GetAmplitude(); flameShock->SetDuration(newDuration); // is it blizzlike to change max duration for FS? if (newDuration > maxDuration) flameShock->SetMaxDuration( newDuration); return true; } // if not found Flame Shock return false; } case 63280: // Glyph of Totem of Wrath { if (procSpell->SpellIconID != 2019) return false; AuraEffect * aurEffA = NULL; AuraEffectList const& auras = GetAuraEffectsByType( SPELL_AURA_MOD_DAMAGE_DONE); for (AuraEffectList::const_iterator i = auras.begin(); i != auras.end(); ++i) { SpellEntry const *spell = (*i)->GetSpellProto(); if (spell->SpellFamilyName == uint32(SPELLFAMILY_SHAMAN) && spell->SpellFamilyFlags.HasFlag(0, 0x02000000, 0)) { if ((*i)->GetCasterGUID() != GetGUID()) continue; if (spell->Id == 63283) continue; aurEffA = (*i); break; } } if (aurEffA) { int32 bp0 = 0, bp1 = 0; bp0 = aurEffA->GetAmount() * triggerAmount / 100; if (AuraEffect * aurEffB = aurEffA->GetBase()->GetEffect(EFFECT_1)) bp1 = aurEffB->GetAmount() * triggerAmount / 100; CastCustomSpell(this, 63283, &bp0, &bp1, NULL, true, NULL, triggeredByAura); return true; } return false; } break; } // Frozen Power if (dummySpell->SpellIconID == 3780) { if (this->GetDistance(target) < 15.0f) return false; float chance = (float) triggerAmount; if (!roll_chance_f(chance)) return false; triggered_spell_id = 63685; break; } // Storm, Earth and Fire if (dummySpell->SpellIconID == 3063) { // Earthbind Totem summon only if (procSpell->Id != 2484) return false; float chance = (float) triggerAmount; if (!roll_chance_f(chance)) return false; triggered_spell_id = 64695; break; } // Ancestral Awakening if (dummySpell->SpellIconID == 3065) { triggered_spell_id = 52759; basepoints0 = triggerAmount * damage / 100; target = this; break; } // Earth Shield if (dummySpell->SpellFamilyFlags [1] & 0x00000400) { // 3.0.8: Now correctly uses the Shaman's own spell critical strike chance to determine the chance of a critical heal. originalCaster = triggeredByAura->GetCasterGUID(); target = this; basepoints0 = triggerAmount; // Glyph of Earth Shield if (AuraEffect* aur = GetAuraEffect(63279, 0)) { int32 aur_mod = aur->GetAmount(); basepoints0 = int32( basepoints0 * (aur_mod + 100.0f) / 100.0f); } triggered_spell_id = 379; break; } // Flametongue Weapon (Passive) if (dummySpell->SpellFamilyFlags [0] & 0x200000) { if (GetTypeId() != TYPEID_PLAYER || !pVictim || !pVictim->isAlive() || !castItem || !castItem->IsEquipped()) return false; float fire_onhit = (float) (SpellMgr::CalculateSpellEffectAmount( dummySpell, 0) / 100.0); float add_spellpower = (float) (SpellBaseDamageBonus( SPELL_SCHOOL_MASK_FIRE) + SpellBaseDamageBonusForVictim(SPELL_SCHOOL_MASK_FIRE, pVictim)); // 1.3speed = 5%, 2.6speed = 10%, 4.0 speed = 15%, so, 1.0speed = 3.84% add_spellpower = add_spellpower / 100.0f * 3.84f; // Enchant on Off-Hand and ready? if (castItem->GetSlot() == EQUIPMENT_SLOT_OFFHAND && isAttackReady(OFF_ATTACK)) { float BaseWeaponSpeed = GetAttackTime(OFF_ATTACK) / 1000.0f; // Value1: add the tooltip damage by swingspeed + Value2: add spelldmg by swingspeed basepoints0 = int32( (fire_onhit * BaseWeaponSpeed) + (add_spellpower * BaseWeaponSpeed)); triggered_spell_id = 10444; } // Enchant on Main-Hand and ready? else if (castItem->GetSlot() == EQUIPMENT_SLOT_MAINHAND && isAttackReady(BASE_ATTACK)) { float BaseWeaponSpeed = GetAttackTime(BASE_ATTACK) / 1000.0f; // Value1: add the tooltip damage by swingspeed + Value2: add spelldmg by swingspeed basepoints0 = int32( (fire_onhit * BaseWeaponSpeed) + (add_spellpower * BaseWeaponSpeed)); triggered_spell_id = 10444; } // If not ready, we should return, shouldn't we?! else return false; CastCustomSpell(pVictim, triggered_spell_id, &basepoints0, NULL, NULL, true, castItem, triggeredByAura); return true; } // Improved Water Shield if (dummySpell->SpellIconID == 2287) { // Default chance for Healing Wave and Riptide float chance = (float) triggeredByAura->GetAmount(); if (procSpell->SpellFamilyFlags [0] & 0x80) // Lesser Healing Wave - 0.6 of default chance *= 0.6f; else if (procSpell->SpellFamilyFlags [0] & 0x100) // Chain heal - 0.3 of default chance *= 0.3f; if (!roll_chance_f(chance)) return false; // Water Shield if (AuraEffect const * aurEff = GetAuraEffect(SPELL_AURA_PROC_TRIGGER_SPELL, SPELLFAMILY_SHAMAN, 0, 0x00000020, 0)) { uint32 spell = aurEff->GetSpellProto()->EffectTriggerSpell [aurEff->GetEffIndex()]; CastSpell(this, spell, true, castItem, triggeredByAura); return true; } return false; } // Lightning Overload if (dummySpell->SpellIconID == 2018) // only this spell have SpellFamily Shaman SpellIconID == 2018 and dummy aura { if (!procSpell || GetTypeId() != TYPEID_PLAYER || !pVictim) return false; // custom cooldown processing case if (cooldown && GetTypeId() == TYPEID_PLAYER && ToPlayer()->HasSpellCooldown(dummySpell->Id)) return false; uint32 spellId = 0; // Every Lightning Bolt and Chain Lightning spell have duplicate vs half damage and zero cost switch (procSpell->Id) { // Lightning Bolt case 403: spellId = 45284; break; // Rank 1 case 529: spellId = 45286; break; // Rank 2 case 548: spellId = 45287; break; // Rank 3 case 915: spellId = 45288; break; // Rank 4 case 943: spellId = 45289; break; // Rank 5 case 6041: spellId = 45290; break; // Rank 6 case 10391: spellId = 45291; break; // Rank 7 case 10392: spellId = 45292; break; // Rank 8 case 15207: spellId = 45293; break; // Rank 9 case 15208: spellId = 45294; break; // Rank 10 case 25448: spellId = 45295; break; // Rank 11 case 25449: spellId = 45296; break; // Rank 12 case 49237: spellId = 49239; break; // Rank 13 case 49238: spellId = 49240; break; // Rank 14 // Chain Lightning case 421: spellId = 45297; break; // Rank 1 case 930: spellId = 45298; break; // Rank 2 case 2860: spellId = 45299; break; // Rank 3 case 10605: spellId = 45300; break; // Rank 4 case 25439: spellId = 45301; break; // Rank 5 case 25442: spellId = 45302; break; // Rank 6 case 49270: spellId = 49268; break; // Rank 7 case 49271: spellId = 49269; break; // Rank 8 default: sLog->outError( "Unit::HandleDummyAuraProc: non handled spell id: %u (LO)", procSpell->Id); return false; } // Chain Lightning if (procSpell->SpellFamilyFlags [0] & 0x2) { // Chain lightning has [LightOverload_Proc_Chance] / [Max_Number_of_Targets] chance to proc of each individual target hit. // A maxed LO would have a 33% / 3 = 11% chance to proc of each target. // LO chance was already "accounted" at the proc chance roll, now need to divide the chance by [Max_Number_of_Targets] float chance = 100.0f / procSpell->EffectChainTarget [effIndex]; if (!roll_chance_f(chance)) return false; // Remove cooldown (Chain Lightning - have Category Recovery time) ToPlayer()->RemoveSpellCooldown(spellId); } CastSpell(pVictim, spellId, true, castItem, triggeredByAura); if (cooldown && GetTypeId() == TYPEID_PLAYER) ToPlayer()->AddSpellCooldown( dummySpell->Id, 0, time(NULL) + cooldown); return true; } // Static Shock if (dummySpell->SpellIconID == 3059) { // Lightning Shield if (AuraEffect const * aurEff = GetAuraEffect(SPELL_AURA_PROC_TRIGGER_SPELL, SPELLFAMILY_SHAMAN, 0x400, 0, 0)) { uint32 spell = sSpellMgr->GetSpellWithRank(26364, sSpellMgr->GetSpellRank(aurEff->GetId())); // custom cooldown processing case if (GetTypeId() == TYPEID_PLAYER && ToPlayer()->HasSpellCooldown(spell)) ToPlayer()->RemoveSpellCooldown( spell); CastSpell(target, spell, true, castItem, triggeredByAura); aurEff->GetBase()->DropCharge(); return true; } return false; } break; } case SPELLFAMILY_DEATHKNIGHT: { // Blood-Caked Strike - Blood-Caked Blade if (dummySpell->SpellIconID == 138) { if (!target || !target->isAlive()) return false; triggered_spell_id = dummySpell->EffectTriggerSpell [effIndex]; break; } // Improved Blood Presence if (dummySpell->SpellIconID == 2636) { if (GetTypeId() != TYPEID_PLAYER) return false; basepoints0 = triggerAmount * damage / 100; break; } // Butchery if (dummySpell->SpellIconID == 2664) { basepoints0 = triggerAmount; triggered_spell_id = 50163; target = this; break; } // Dancing Rune Weapon if (dummySpell->Id == 49028) { // 1 dummy aura for dismiss rune blade if (effIndex != 1) return false; Unit* pPet = NULL; for (ControlList::const_iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr) //Find Rune Weapon if ((*itr)->GetEntry() == 27893) { pPet = (*itr); break; } if (pPet && pPet->getVictim() && damage && procSpell) { uint32 procDmg = damage / 2; pPet->SendSpellNonMeleeDamageLog(pPet->getVictim(), procSpell->Id, procDmg, GetSpellSchoolMask(procSpell), 0, 0, false, 0, false); pPet->DealDamage(pPet->getVictim(), procDmg, NULL, SPELL_DIRECT_DAMAGE, GetSpellSchoolMask(procSpell), procSpell, true); break; } else return false; } // Mark of Blood if (dummySpell->Id == 49005) { // TODO: need more info (cooldowns/PPM) triggered_spell_id = 61607; break; } // Unholy Blight if (dummySpell->Id == 49194) { basepoints0 = triggerAmount * damage / 100; // Glyph of Unholy Blight if (AuraEffect *glyph=GetAuraEffect(63332, 0)) AddPctN( basepoints0, glyph->GetAmount()); triggered_spell_id = 50536; basepoints0 += pVictim->GetRemainingDotDamage(GetGUID(), triggered_spell_id, SPELL_AURA_PERIODIC_DAMAGE); break; } // Vendetta if (dummySpell->SpellFamilyFlags [0] & 0x10000) { basepoints0 = int32(CountPctFromMaxHealth(triggerAmount)); triggered_spell_id = 50181; target = this; break; } // Necrosis if (dummySpell->SpellIconID == 2709) { basepoints0 = triggerAmount * damage / 100; triggered_spell_id = 51460; break; } // Threat of Thassarian if (dummySpell->SpellIconID == 2023) { // Must Dual Wield if (!procSpell || !haveOffhandWeapon()) return false; // Chance as basepoints for dummy aura if (!roll_chance_i(triggerAmount)) return false; switch (procSpell->Id) { // Obliterate case 49020: triggered_spell_id = 66198; break; // Frost Strike case 49143: triggered_spell_id = 66196; break; // Plague Strike case 45462: triggered_spell_id = 66216; break; // Death Strike case 49998: triggered_spell_id = 66188; break; // Rune Strike case 56815: triggered_spell_id = 66217; break; // Blood Strike case 45902: triggered_spell_id = 66215; break; default: return false; } break; } // Runic Power Back on Snare/Root if (dummySpell->Id == 61257) { // only for spells and hit/crit (trigger start always) and not start from self casted spells if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT | PROC_EX_CRITICAL_HIT)) || this == pVictim) return false; // Need snare or root mechanic if (!(GetAllSpellMechanicMask(procSpell) & ((1 << MECHANIC_ROOT) | (1 << MECHANIC_SNARE)))) return false; triggered_spell_id = 61258; target = this; break; } // Wandering Plague if (dummySpell->SpellIconID == 1614) { if (!roll_chance_f(GetUnitCriticalChance(BASE_ATTACK, pVictim))) return false; basepoints0 = triggerAmount * damage / 100; triggered_spell_id = 50526; break; } // Sudden Doom if (dummySpell->SpellIconID == 1939 && GetTypeId() == TYPEID_PLAYER) { SpellChainNode const* chain = NULL; // get highest rank of the Death Coil spell const PlayerSpellMap& sp_list = this->ToPlayer()->GetSpellMap(); for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr) { // check if shown in spell book if (!itr->second->active || itr->second->disabled || itr->second->state == PLAYERSPELL_REMOVED) continue; SpellEntry const *spellProto = sSpellStore.LookupEntry( itr->first); if (!spellProto) continue; if (spellProto->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && spellProto->SpellFamilyFlags [0] & 0x2000) { SpellChainNode const* newChain = sSpellMgr->GetSpellChainNode(itr->first); // No chain entry or entry lower than found entry if (!chain || !newChain || (chain->rank < newChain->rank)) { triggered_spell_id = itr->first; chain = newChain; } else continue; // Found spell is last in chain - do not need to look more // Optimisation for most common case if (chain && chain->last == itr->first) break; } } } // Item - Death Knight T10 Melee 4P Bonus if (dummySpell->Id == 70656) { if (!this->ToPlayer()) return false; for (uint32 i = 0; i < MAX_RUNES; ++i) if (this->ToPlayer()->GetRuneCooldown(i) == 0) return false; } break; } case SPELLFAMILY_POTION: { // alchemist's stone if (dummySpell->Id == 17619) { if (procSpell->SpellFamilyName == SPELLFAMILY_POTION) { for (uint8 i = 0; i < MAX_SPELL_EFFECTS; i++) { if (procSpell->Effect [i] == SPELL_EFFECT_HEAL) { triggered_spell_id = 21399; } else if (procSpell->Effect [i] == SPELL_EFFECT_ENERGIZE) { triggered_spell_id = 21400; } else continue; basepoints0 = int32( CalculateSpellDamage(this, procSpell, i) * 0.4f); CastCustomSpell(this, triggered_spell_id, &basepoints0, NULL, NULL, true, NULL, triggeredByAura); } return true; } } break; } case SPELLFAMILY_PET: { switch (dummySpell->SpellIconID) { // Guard Dog case 201: { triggered_spell_id = 54445; target = this; float addThreat = SpellMgr::CalculateSpellEffectAmount( procSpell, 0, this) * triggerAmount / 100.0f; pVictim->AddThreat(this, addThreat); break; } // Silverback case 1582: triggered_spell_id = dummySpell->Id == 62765 ? 62801 : 62800; target = this; break; } break; } default: break; } // if not handled by custom case, get triggered spell from dummySpell proto if (!triggered_spell_id) triggered_spell_id = dummySpell->EffectTriggerSpell [triggeredByAura->GetEffIndex()]; // processed charge only counting case if (!triggered_spell_id) return true; SpellEntry const* triggerEntry = sSpellStore.LookupEntry( triggered_spell_id); if (!triggerEntry) { sLog->outError( "Unit::HandleDummyAuraProc: Spell %u have not existed triggered spell %u", dummySpell->Id, triggered_spell_id); return false; } // default case if ((!target && !sSpellMgr->IsSrcTargetSpell(triggerEntry)) || (target && target != this && !target->isAlive())) return false; if (cooldown_spell_id == 0) cooldown_spell_id = triggered_spell_id; if (cooldown && GetTypeId() == TYPEID_PLAYER && ToPlayer()->HasSpellCooldown(cooldown_spell_id)) return false; if (basepoints0) CastCustomSpell(target, triggered_spell_id, &basepoints0, NULL, NULL, true, castItem, triggeredByAura, originalCaster); else CastSpell(target, triggered_spell_id, true, castItem, triggeredByAura, originalCaster); if (cooldown && GetTypeId() == TYPEID_PLAYER) ToPlayer()->AddSpellCooldown( cooldown_spell_id, 0, time(NULL) + cooldown); return true; } bool Unit::HandleObsModEnergyAuraProc(Unit *pVictim, uint32 /*damage*/, AuraEffect* triggeredByAura, SpellEntry const * /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown) { SpellEntry const *dummySpell = triggeredByAura->GetSpellProto(); //uint32 effIndex = triggeredByAura->GetEffIndex(); //int32 triggerAmount = triggeredByAura->GetAmount(); Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER ? this->ToPlayer()->GetItemByGuid( triggeredByAura->GetBase()->GetCastItemGUID()) : NULL; uint32 triggered_spell_id = 0; Unit* target = pVictim; int32 basepoints0 = 0; switch (dummySpell->SpellFamilyName) { case SPELLFAMILY_HUNTER: { // Aspect of the Viper if (dummySpell->SpellFamilyFlags [1] & 0x40000) { uint32 maxmana = GetMaxPower(POWER_MANA); basepoints0 = uint32( maxmana * GetAttackTime(RANGED_ATTACK) / 1000.0f / 100.0f); target = this; triggered_spell_id = 34075; break; } break; } } // processed charge only counting case if (!triggered_spell_id) return true; SpellEntry const* triggerEntry = sSpellStore.LookupEntry( triggered_spell_id); // Try handle unknown trigger spells if (!triggerEntry) { sLog->outError( "Unit::HandleObsModEnergyAuraProc: Spell %u have not existed triggered spell %u", dummySpell->Id, triggered_spell_id); return false; } // default case if ((!target && !sSpellMgr->IsSrcTargetSpell(triggerEntry)) || (target && target != this && !target->isAlive())) return false; if (cooldown && GetTypeId() == TYPEID_PLAYER && this->ToPlayer()->HasSpellCooldown(triggered_spell_id)) return false; if (basepoints0) CastCustomSpell(target, triggered_spell_id, &basepoints0, NULL, NULL, true, castItem, triggeredByAura); else CastSpell(target, triggered_spell_id, true, castItem, triggeredByAura); if (cooldown && GetTypeId() == TYPEID_PLAYER) this->ToPlayer()->AddSpellCooldown( triggered_spell_id, 0, time(NULL) + cooldown); return true; } bool Unit::HandleModDamagePctTakenAuraProc(Unit *pVictim, uint32 /*damage*/, AuraEffect* triggeredByAura, SpellEntry const * /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown) { SpellEntry const *dummySpell = triggeredByAura->GetSpellProto(); //uint32 effIndex = triggeredByAura->GetEffIndex(); //int32 triggerAmount = triggeredByAura->GetAmount(); Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER ? this->ToPlayer()->GetItemByGuid( triggeredByAura->GetBase()->GetCastItemGUID()) : NULL; uint32 triggered_spell_id = 0; Unit* target = pVictim; int32 basepoints0 = 0; switch (dummySpell->SpellFamilyName) { case SPELLFAMILY_PALADIN: { // Blessing of Sanctuary if (dummySpell->SpellFamilyFlags [0] & 0x10000000) { switch (getPowerType()) { case POWER_MANA: triggered_spell_id = 57319; break; default: return false; } } break; } } // processed charge only counting case if (!triggered_spell_id) return true; SpellEntry const* triggerEntry = sSpellStore.LookupEntry( triggered_spell_id); if (!triggerEntry) { sLog->outError( "Unit::HandleModDamagePctTakenAuraProc: Spell %u have not existed triggered spell %u", dummySpell->Id, triggered_spell_id); return false; } // default case if ((!target && !sSpellMgr->IsSrcTargetSpell(triggerEntry)) || (target && target != this && !target->isAlive())) return false; if (cooldown && GetTypeId() == TYPEID_PLAYER && this->ToPlayer()->HasSpellCooldown(triggered_spell_id)) return false; if (basepoints0) CastCustomSpell(target, triggered_spell_id, &basepoints0, NULL, NULL, true, castItem, triggeredByAura); else CastSpell(target, triggered_spell_id, true, castItem, triggeredByAura); if (cooldown && GetTypeId() == TYPEID_PLAYER) this->ToPlayer()->AddSpellCooldown( triggered_spell_id, 0, time(NULL) + cooldown); return true; } // Used in case when access to whole aura is needed // All procs should be handled like this... bool Unit::HandleAuraProc(Unit * pVictim, uint32 damage, Aura * triggeredByAura, SpellEntry const * procSpell, uint32 /*procFlag*/, uint32 procEx, uint32 cooldown, bool * handled) { SpellEntry const *dummySpell = triggeredByAura->GetSpellProto(); switch (dummySpell->SpellFamilyName) { case SPELLFAMILY_GENERIC: switch (dummySpell->Id) { // Pursuit of Justice //case 26022: //case 26023: { // *handled = true; // Hack, we need the new spell dbcs implemented in // order to add the missing spell 32733 wich i suppose, // is the cooldown marker used by blizz to share the cd // of Pursuit of justice and Blessed life proc. //if (!HasAura(31828) && !HasAura(31829) && (GetAllSpellMechanicMask(procSpell) && ((1 << MECHANIC_ROOT) | (1 << MECHANIC_STUN) | (1 << MECHANIC_FEAR)))) { // CastSpell(pVictim, 89024, true); // return true; //} //break; //} // Bone Shield cooldown case 49222: { *handled = true; if (cooldown && GetTypeId() == TYPEID_PLAYER) { if (ToPlayer()->HasSpellCooldown(100000)) return false; ToPlayer()->AddSpellCooldown(100000, 0, time(NULL) + cooldown); } return true; } // Nevermelting Ice Crystal case 71564: RemoveAuraFromStack(71564); *handled = true; break; case 71756: case 72782: case 72783: case 72784: RemoveAuraFromStack(dummySpell->Id); *handled = true; break; // Discerning Eye of the Beast case 59915: { CastSpell(this, 59914, true); // 59914 already has correct basepoints in DBC, no need for custom bp *handled = true; break; } // Swift Hand of Justice case 59906: { int32 bp0 = CalculatePctN( GetMaxHealth(), SpellMgr::CalculateSpellEffectAmount(dummySpell, 0)); CastCustomSpell(this, 59913, &bp0, NULL, NULL, true); *handled = true; break; } } break; case SPELLFAMILY_PALADIN: { // Judgements of the Just if (dummySpell->SpellIconID == 3015) { *handled = true; if (procSpell->Category == SPELLCATEGORY_JUDGEMENT) { CastSpell(pVictim, 68055, true); return true; } } // Light's Grace (temp solution) else if (dummySpell->Id == 31834) { *handled = true; int32 removeChance = 0; if (AuraEffect* aurEff = GetAuraEffect(SPELL_AURA_PROC_TRIGGER_SPELL, SPELLFAMILY_PALADIN, 2141, 0)) removeChance = aurEff->GetSpellProto()->procChance; if (!roll_chance_i(removeChance)) return true; break; } // Glyph of Divinity else if (dummySpell->Id == 54939) { *handled = true; // Check if we are the target and prevent mana gain if (triggeredByAura->GetCasterGUID() == pVictim->GetGUID()) return false; // Lookup base amount mana restore for (uint8 i = 0; i < MAX_SPELL_EFFECTS; i++) { if (procSpell->Effect [i] == SPELL_EFFECT_ENERGIZE) { // value multiplied by 2 because you should get twice amount int32 mana = SpellMgr::CalculateSpellEffectAmount( procSpell, i) * 2; CastCustomSpell(this, 54986, 0, &mana, NULL, true); } } return true; } break; } case SPELLFAMILY_MAGE: { // Combustion switch (dummySpell->Id) { case 11129: { *handled = true; Unit *caster = triggeredByAura->GetCaster(); if (!caster || !damage) return false; //last charge and crit if (triggeredByAura->GetCharges() <= 1 && (procEx & PROC_EX_CRITICAL_HIT)) { RemoveAurasDueToSpell(28682); //-> remove Combustion auras return true; // charge counting (will removed) } // This function can be called twice during one spell hit (Area of Effect spells) // Make sure 28682 wasn't already removed by previous call if (HasAura(28682)) this->CastSpell(this, 28682, true); return false; // ordinary chrages will be removed during crit chance computations. } // Empowered Fire case 31656: case 31657: case 31658: { *handled = true; SpellEntry const *spInfo = sSpellStore.LookupEntry(67545); if (!spInfo) return false; int32 bp0 = this->GetCreateMana() * SpellMgr::CalculateSpellEffectAmount(spInfo, 0) / 100; this->CastCustomSpell(this, 67545, &bp0, NULL, NULL, true, NULL, triggeredByAura->GetEffect(0), this->GetGUID()); return true; } } break; } case SPELLFAMILY_DEATHKNIGHT: { // Blood of the North // Reaping // Death Rune Mastery if (dummySpell->SpellIconID == 3041 || dummySpell->SpellIconID == 22 || dummySpell->SpellIconID == 2622) { *handled = true; // Convert recently used Blood Rune to Death Rune if (GetTypeId() == TYPEID_PLAYER) { if (this->ToPlayer()->getClass() != CLASS_DEATH_KNIGHT) return false; RuneType rune = this->ToPlayer()->GetLastUsedRune(); AuraEffect * aurEff = triggeredByAura->GetEffect(0); if (!aurEff) return false; // Reset amplitude - set death rune remove timer to 30s aurEff->ResetPeriodic(true); uint32 runesLeft; if (dummySpell->SpellIconID == 2622) runesLeft = 2; else runesLeft = 1; for (uint8 i = 0; i < MAX_RUNES && runesLeft; ++i) { if (dummySpell->SpellIconID == 2622) { if (((Player*) this)->GetCurrentRune(i) == RUNE_DEATH || ((Player*) this)->GetBaseRune(i) == RUNE_BLOOD) continue; } else { if (((Player*) this)->GetCurrentRune(i) == RUNE_DEATH || ((Player*) this)->GetBaseRune(i) != RUNE_BLOOD) continue; } if (((Player*) this)->GetRuneCooldown(i) != ((Player*) this)->GetRuneBaseCooldown(i)) continue; --runesLeft; // Mark aura as used ((Player*) this)->AddRuneByAuraEffect(i, RUNE_DEATH, aurEff); } return true; } return false; } switch (dummySpell->Id) { // Hungering Cold aura drop case 51209: *handled = true; // Drop only in not disease case if (procSpell && procSpell->Dispel == DISPEL_DISEASE) return false; return true; } break; } } return false; } bool Unit::HandleProcTriggerSpell(Unit *pVictim, uint32 damage, AuraEffect* triggeredByAura, SpellEntry const *procSpell, uint32 procFlags, uint32 procEx, uint32 cooldown) { // Get triggered aura spell info SpellEntry const* auraSpellInfo = triggeredByAura->GetSpellProto(); // Basepoints of trigger aura int32 triggerAmount = triggeredByAura->GetAmount(); // Set trigger spell id, target, custom basepoints uint32 trigger_spell_id = auraSpellInfo->EffectTriggerSpell [triggeredByAura->GetEffIndex()]; Unit* target = NULL; int32 basepoints0 = 0; if (triggeredByAura->GetAuraType() == SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE) basepoints0 = triggerAmount; Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER ? this->ToPlayer()->GetItemByGuid( triggeredByAura->GetBase()->GetCastItemGUID()) : NULL; // Try handle unknown trigger spells if (sSpellStore.LookupEntry(trigger_spell_id) == NULL) { switch (auraSpellInfo->SpellFamilyName) { case SPELLFAMILY_GENERIC: switch (auraSpellInfo->Id) { case 56614: // Wrecking Crew trigger_spell_id = 57522; target = this; break; case 23780: // Aegis of Preservation (Aegis of Preservation trinket) trigger_spell_id = 23781; break; case 33896: // Desperate Defense (Stonescythe Whelp, Stonescythe Alpha, Stonescythe Ambusher) trigger_spell_id = 33898; break; case 43820: // Charm of the Witch Doctor (Amani Charm of the Witch Doctor trinket) // Pct value stored in dummy basepoints0 = pVictim->GetCreateHealth() * SpellMgr::CalculateSpellEffectAmount( auraSpellInfo, 1) / 100; target = pVictim; break; case 57345: // Darkmoon Card: Greatness { float stat = 0.0f; // strength if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 60229; stat = GetStat(STAT_STRENGTH); } // agility if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 60233; stat = GetStat(STAT_AGILITY); } // intellect if (GetStat(STAT_INTELLECT) > stat) { trigger_spell_id = 60234; stat = GetStat(STAT_INTELLECT); } // spirit if (GetStat(STAT_SPIRIT) > stat) { trigger_spell_id = 60235; } break; } case 64568: // Blood Reserve { if (GetHealth() - damage < GetMaxHealth() * 0.35) { basepoints0 = triggerAmount; trigger_spell_id = 64569; RemoveAura(64568); } break; } case 67702: // Death's Choice, Item - Coliseum 25 Normal Melee Trinket { float stat = 0.0f; // strength if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 67708; stat = GetStat(STAT_STRENGTH); } // agility if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 67703; } break; } case 67771: // Death's Choice (heroic), Item - Coliseum 25 Heroic Melee Trinket { float stat = 0.0f; // strength if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 67773; stat = GetStat(STAT_STRENGTH); } // agility if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 67772; } break; } // Mana Drain Trigger case 27522: case 40336: { // On successful melee or ranged attack gain $29471s1 mana and if possible drain $27526s1 mana from the target. if (this && this->isAlive()) CastSpell(this, 29471, true, castItem, triggeredByAura); if (pVictim && pVictim->isAlive()) CastSpell(pVictim, 27526, true, castItem, triggeredByAura); return true; } } break; case SPELLFAMILY_MAGE: if (auraSpellInfo->SpellIconID == 2127) // Blazing Speed { switch (auraSpellInfo->Id) { case 31641: // Rank 1 case 31642: // Rank 2 trigger_spell_id = 31643; break; default: sLog->outError( "Unit::HandleProcTriggerSpell: Spell %u miss posibly Blazing Speed", auraSpellInfo->Id); return false; } } break; case SPELLFAMILY_WARRIOR: switch (auraSpellInfo->Id) { case 50421: // Scent of Blood trigger_spell_id = 50422; break; case 80128: // Impending Victory Rank 1 case 80129: // Impending Victory Rank 2 if (!pVictim->HealthBelowPct(20)) return false; case 93098: if (damage > 0) { int bp = damage * 0.05f; //5% from damage CastCustomSpell(this, 76691, &bp, &bp, &bp, true, 0, 0, GetGUID()); } break; } break; case SPELLFAMILY_WARLOCK: { // Drain Soul if (auraSpellInfo->SpellFamilyFlags [0] & 0x4000) { // Improved Drain Soul Unit::AuraEffectList const& mAddFlatModifier = GetAuraEffectsByType(SPELL_AURA_DUMMY); for (Unit::AuraEffectList::const_iterator i = mAddFlatModifier.begin(); i != mAddFlatModifier.end(); ++i) { if ((*i)->GetMiscValue() == SPELLMOD_CHANCE_OF_SUCCESS && (*i)->GetSpellProto()->SpellIconID == 113) { int32 value2 = CalculateSpellDamage(this, (*i)->GetSpellProto(), 2); basepoints0 = value2 * GetMaxPower(POWER_MANA) / 100; // Drain Soul CastCustomSpell(this, 18371, &basepoints0, NULL, NULL, true, castItem, triggeredByAura); break; } } // Not remove charge (aura removed on death in any cases) // Need for correct work Drain Soul SPELL_AURA_CHANNEL_DEATH_ITEM aura return false; } // Nether Protection else if (auraSpellInfo->SpellIconID == 1985) { if (!procSpell) return false; switch (GetFirstSchoolInMask(GetSpellSchoolMask(procSpell))) { case SPELL_SCHOOL_NORMAL: return false; // ignore case SPELL_SCHOOL_HOLY: trigger_spell_id = 54370; break; case SPELL_SCHOOL_FIRE: trigger_spell_id = 54371; break; case SPELL_SCHOOL_NATURE: trigger_spell_id = 54375; break; case SPELL_SCHOOL_FROST: trigger_spell_id = 54372; break; case SPELL_SCHOOL_SHADOW: trigger_spell_id = 54374; break; case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break; default: return false; } } break; } case SPELLFAMILY_PRIEST: { // Greater Heal Refund if (auraSpellInfo->Id == 37594) trigger_spell_id = 37595; // Blessed Recovery else if (auraSpellInfo->SpellIconID == 1875) { switch (auraSpellInfo->Id) { case 27811: trigger_spell_id = 27813; break; case 27815: trigger_spell_id = 27817; break; case 27816: trigger_spell_id = 27818; break; default: sLog->outError( "Unit::HandleProcTriggerSpell: Spell %u not handled in BR", auraSpellInfo->Id); return false; } basepoints0 = CalculatePctN(int32(damage), triggerAmount) / 3; target = this; if (AuraEffect * aurEff = target->GetAuraEffect(trigger_spell_id, 0)) basepoints0 += aurEff->GetAmount(); } break; } case SPELLFAMILY_DRUID: { switch (auraSpellInfo->Id) { // Druid Forms Trinket case 37336: { switch (GetShapeshiftForm()) { case FORM_NONE: trigger_spell_id = 37344; break; case FORM_CAT: trigger_spell_id = 37341; break; case FORM_BEAR: case FORM_DIREBEAR: trigger_spell_id = 37340; break; case FORM_TREE: trigger_spell_id = 37342; break; case FORM_MOONKIN: trigger_spell_id = 37343; break; default: return false; } break; } // Druid T9 Feral Relic (Lacerate, Swipe, Mangle, and Shred) case 67353: { switch (GetShapeshiftForm()) { case FORM_CAT: trigger_spell_id = 67355; break; case FORM_BEAR: case FORM_DIREBEAR: trigger_spell_id = 67354; break; default: return false; } break; } // Shooting Stars case 93398: // Rank 1 case 93399: // Rank 2 { if (GetTypeId() == TYPEID_PLAYER) ToPlayer()->RemoveSpellCooldown(78674, true); // Remove cooldown of Starsurge break; } default: break; } break; } case SPELLFAMILY_HUNTER: { if (auraSpellInfo->SpellIconID == 3247) // Piercing Shots 1, 2, 3 { trigger_spell_id = 63468; SpellEntry const *TriggerPS = sSpellStore.LookupEntry( trigger_spell_id); if (!TriggerPS) return false; basepoints0 = int32( (damage * (auraSpellInfo->EffectBasePoints [0] / 100)) / (GetSpellMaxDuration(TriggerPS) / 1000)); basepoints0 += pVictim->GetRemainingDotDamage(GetGUID(), trigger_spell_id); break; } if (auraSpellInfo->SpellIconID == 2225) // Serpent Spread 1, 2 { if (!(auraSpellInfo->procFlags == 0x1140)) return false; switch (auraSpellInfo->Id) { case 87934: trigger_spell_id = 88453; break; case 87935: trigger_spell_id = 88466; break; default: return false; } break; } if (auraSpellInfo->Id == 82661) // Aspect of the Fox: Focus bonus { if (!((auraSpellInfo->procFlags & PROC_FLAG_TAKEN_MELEE_AUTO_ATTACK) || (auraSpellInfo->procFlags & PROC_FLAG_TAKEN_SPELL_MELEE_DMG_CLASS))) return false; target = this; basepoints0 = auraSpellInfo->EffectBasePoints [0]; trigger_spell_id = 82716; break; } break; } case SPELLFAMILY_PALADIN: { switch (auraSpellInfo->Id) { // Healing Discount case 37705: { trigger_spell_id = 37706; target = this; break; } // Soul Preserver case 60510: { switch (getClass()) { case CLASS_DRUID: trigger_spell_id = 60512; break; case CLASS_PALADIN: trigger_spell_id = 60513; break; case CLASS_PRIEST: trigger_spell_id = 60514; break; case CLASS_SHAMAN: trigger_spell_id = 60515; break; } target = this; break; } case 37657: // Lightning Capacitor case 54841: // Thunder Capacitor case 67712: // Item - Coliseum 25 Normal Caster Trinket case 67758: // Item - Coliseum 25 Heroic Caster Trinket { if (!pVictim || !pVictim->isAlive() || GetTypeId() != TYPEID_PLAYER) return false; uint32 stack_spell_id = 0; switch (auraSpellInfo->Id) { case 37657: stack_spell_id = 37658; trigger_spell_id = 37661; break; case 54841: stack_spell_id = 54842; trigger_spell_id = 54843; break; case 67712: stack_spell_id = 67713; trigger_spell_id = 67714; break; case 67758: stack_spell_id = 67759; trigger_spell_id = 67760; break; } CastSpell(this, stack_spell_id, true, NULL, triggeredByAura); Aura* dummy = GetAura(stack_spell_id); if (!dummy || dummy->GetStackAmount() < triggerAmount) return false; RemoveAurasDueToSpell(stack_spell_id); target = pVictim; break; } default: // Illumination if (auraSpellInfo->SpellIconID == 241) { if (!procSpell) return false; // procspell is triggered spell but we need mana cost of original casted spell uint32 originalSpellId = procSpell->Id; // Holy Shock heal if (procSpell->SpellFamilyFlags [1] & 0x00010000) { switch (procSpell->Id) { case 25914: originalSpellId = 20473; break; default: sLog->outError( "Unit::HandleProcTriggerSpell: Spell %u not handled in HShock", procSpell->Id); return false; } } SpellEntry const *originalSpell = sSpellStore.LookupEntry(originalSpellId); if (!originalSpell) { sLog->outError( "Unit::HandleProcTriggerSpell: Spell %u unknown but selected as original in Illu", originalSpellId); return false; } // percent stored in effect 1 (class scripts) base points int32 cost = originalSpell->manaCost + originalSpell->ManaCostPercentage * GetCreateMana() / 100; basepoints0 = cost * SpellMgr::CalculateSpellEffectAmount( auraSpellInfo, 1) / 100; trigger_spell_id = 20272; target = this; } break; } break; } case SPELLFAMILY_SHAMAN: { switch (auraSpellInfo->Id) { // Lightning Shield (The Ten Storms set) case 23551: { trigger_spell_id = 23552; target = pVictim; break; } // Damage from Lightning Shield (The Ten Storms set) case 23552: { trigger_spell_id = 27635; break; } // Mana Surge (The Earthfury set) case 23572: { if (!procSpell) return false; basepoints0 = procSpell->manaCost * 35 / 100; trigger_spell_id = 23571; target = this; break; } default: { // Lightning Shield (overwrite non existing triggered spell call in spell.dbc if (auraSpellInfo->SpellFamilyFlags [0] & 0x400) { trigger_spell_id = sSpellMgr->GetSpellWithRank( 26364, sSpellMgr->GetSpellRank(auraSpellInfo->Id)); } // Nature's Guardian else if (auraSpellInfo->SpellIconID == 2013) { // Check health condition - should drop to less 30% (damage deal after this!) if (!HealthBelowPctDamaged(30, damage)) return false; if (pVictim && pVictim->isAlive()) pVictim->getThreatManager().modifyThreatPercent( this, -10); basepoints0 = int32( CountPctFromMaxHealth(triggerAmount)); trigger_spell_id = 31616; target = this; } } } break; } case SPELLFAMILY_DEATHKNIGHT: { // Acclimation if (auraSpellInfo->SpellIconID == 1930) { if (!procSpell) return false; switch (GetFirstSchoolInMask(GetSpellSchoolMask(procSpell))) { case SPELL_SCHOOL_NORMAL: return false; // ignore case SPELL_SCHOOL_HOLY: trigger_spell_id = 50490; break; case SPELL_SCHOOL_FIRE: trigger_spell_id = 50362; break; case SPELL_SCHOOL_NATURE: trigger_spell_id = 50488; break; case SPELL_SCHOOL_FROST: trigger_spell_id = 50485; break; case SPELL_SCHOOL_SHADOW: trigger_spell_id = 50489; break; case SPELL_SCHOOL_ARCANE: trigger_spell_id = 50486; break; default: return false; } } // Blood Presence (Improved) else if (auraSpellInfo->Id == 63611) { if (GetTypeId() != TYPEID_PLAYER) return false; trigger_spell_id = 50475; basepoints0 = damage * triggerAmount / 100; } break; } default: break; } } // All ok. Check current trigger spell SpellEntry const* triggerEntry = sSpellStore.LookupEntry(trigger_spell_id); if (triggerEntry == NULL) { // Not cast unknown spell // sLog->outError("Unit::HandleProcTriggerSpell: Spell %u have 0 in EffectTriggered[%d], not handled custom case?", auraSpellInfo->Id, triggeredByAura->GetEffIndex()); return false; } // not allow proc extra attack spell at extra attack if (m_extraAttacks && IsSpellHaveEffect(triggerEntry, SPELL_EFFECT_ADD_EXTRA_ATTACKS)) return false; // Custom requirements (not listed in procEx) Warning! damage dealing after this // Custom triggered spells switch (auraSpellInfo->Id) { // Persistent Shield (Scarab Brooch trinket) // This spell originally trigger 13567 - Dummy Trigger (vs dummy efect) case 26467: { basepoints0 = damage * 15 / 100; target = pVictim; trigger_spell_id = 26470; break; } // Unyielding Knights (item exploit 29108\29109) case 38164: { if (!pVictim || pVictim->GetEntry() != 19457) // Proc only if your target is Grillok return false; break; } // Deflection case 52420: { if (!HealthBelowPct(35)) return false; break; } // Sacred Shield case 85285: { if (!HealthBelowPct(30)) return false; break; } // Improved Hamstring case 12289: case 12668: { if (!pVictim->HasAura(1715)) return false; break; } // Brambles case 50419: { if (!roll_chance_i(triggerAmount)) return false; break; } // Cheat Death case 28845: { // When your health drops below 20% if (HealthBelowPctDamaged(20, damage) || HealthBelowPct(20)) return false; break; } // Protector of the Innocent case 20138: case 20139: case 20140: { if (pVictim == this) return false; break; } // Deadly Swiftness (Rank 1) case 31255: { // whenever you deal damage to a target who is below 20% health. if (!pVictim || !pVictim->isAlive() || pVictim->HealthAbovePct(20)) return false; target = this; trigger_spell_id = 22588; } // Glyph of Shadow Word: Pain case 55681: { // Shadow Word: Pain if (!(procSpell->SpellFamilyFlags [0] & 0x8000)) return false; break; } // Greater Heal Refund (Avatar Raiment set) case 37594: { if (!pVictim || !pVictim->isAlive()) return false; // Not give if target already have full health if (pVictim->IsFullHealth()) return false; // If your Greater Heal brings the target to full health, you gain $37595s1 mana. if (pVictim->GetHealth() + damage < pVictim->GetMaxHealth()) return false; break; } // Bonus Healing (Crystal Spire of Karabor mace) case 40971: { // If your target is below $s1% health if (!pVictim || !pVictim->isAlive() || pVictim->HealthAbovePct(triggerAmount)) return false; break; } // Evasive Maneuvers (Commendation of Kael`thas trinket) case 45057: { // reduce you below $s1% health if (GetHealth() - damage > GetMaxHealth() * triggerAmount / 100) return false; break; } // Rapid Recuperation case 53228: case 53232: { // This effect only from Rapid Fire (ability cast) if (!(procSpell->SpellFamilyFlags [0] & 0x20)) return false; break; } // Decimation case 63156: case 63158: // Can proc only if target has hp below 35% if (!pVictim || !pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, procSpell, this)) return false; break; // Deathbringer Saurfang - Rune of Blood case 72408: // can proc only if target is marked with rune if (!pVictim->HasAura(72410)) return false; break; // Deathbringer Saurfang - Blood Beast's Blood Link case 72176: basepoints0 = 3; break; case 15337: // Improved Spirit Tap (Rank 1) case 15338: // Improved Spirit Tap (Rank 2) { if (procSpell->SpellFamilyFlags [0] & 0x800000) if ((procSpell->Id != 58381) || !roll_chance_i(50)) return false; target = pVictim; break; } default: break; } // Sword Specialization if (auraSpellInfo->SpellFamilyName == SPELLFAMILY_GENERIC && auraSpellInfo->SpellIconID == 1462 && procSpell) if (Player * plr = ToPlayer()) { if (cooldown && plr->HasSpellCooldown(16459)) return false; // this required for attacks like Mortal Strike plr->RemoveSpellCooldown(procSpell->Id); CastSpell(pVictim, procSpell->Id, true); if (cooldown) plr->AddSpellCooldown(16459, 0, time(NULL) + cooldown); return true; } // Blade Barrier if (auraSpellInfo->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && auraSpellInfo->SpellIconID == 85) { Player * plr = this->ToPlayer(); if (this->GetTypeId() != TYPEID_PLAYER || !plr || plr->getClass() != CLASS_DEATH_KNIGHT) return false; if (!plr->IsBaseRuneSlotsOnCooldown(RUNE_BLOOD)) return false; } // Rime else if (auraSpellInfo->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && auraSpellInfo->SpellIconID == 56) { if (GetTypeId() != TYPEID_PLAYER) return false; // Howling Blast this->ToPlayer()->RemoveSpellCategoryCooldown(1248, true); } // Death's Advance if (auraSpellInfo->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && auraSpellInfo->SpellIconID == 3315) { Player* player = ToPlayer(); if (!player || player->getClass() != CLASS_DEATH_KNIGHT) return false; if (!player->IsBaseRuneSlotsOnCooldown(RUNE_UNHOLY)) return false; } // Custom basepoints/target for exist spell // dummy basepoints or other customs switch (trigger_spell_id) { // Strength of Soul case 89490: if (procSpell->Id == 2050 || procSpell->Id == 2060 || procSpell->Id == 2061) { if (pVictim->HasAura(6788)) { uint32 newCooldownDelay = pVictim->GetAura(6788)->GetDuration(); if (newCooldownDelay <= (triggeredByAura->GetSpellProto()->GetSpellEffect(0)->EffectBasePoints)*1000) newCooldownDelay = 0; else newCooldownDelay -= ((triggeredByAura->GetSpellProto()->GetSpellEffect(0)->EffectBasePoints)*1000); pVictim->GetAura(6788)->SetDuration(newCooldownDelay, true); } } break; // Will of Necropolis case 81162: if (HealthBelowPct(29) || (!HealthBelowPctDamaged(30, damage))) return false; else { if (!ToPlayer()->HasSpellCooldown(trigger_spell_id)) { AddAura(trigger_spell_id, this); ToPlayer()->AddSpellCooldown(trigger_spell_id, 0, time(NULL) + 15); } } break; case 92184: // Lead Plating case 92233: // Tectonic Shift case 92355: // Turn of the Worm case 92235: // Turn of the Worm case 90996: // Crescendo of Suffering case 91002: // Crescendo of Suffering case 75477: // Scale Nimbleness case 75480: // Scaly Nimbleness case 71633: // Thick Skin case 71639: // Thick Skin if (HealthBelowPct(34) || (!HealthBelowPctDamaged(35, damage))) return false; else { if (!ToPlayer()->HasSpellCooldown(trigger_spell_id)) { AddAura(trigger_spell_id, this); ToPlayer()->AddSpellCooldown(trigger_spell_id, 0, time(NULL) + 30); } } break; // Die by the Sword case 85386: case 86624: if (HealthBelowPct(19) || (!HealthBelowPctDamaged(20, damage))) return false; else { if (!ToPlayer()->HasSpellCooldown(trigger_spell_id)) { AddAura(trigger_spell_id, this); ToPlayer()->AddSpellCooldown(trigger_spell_id, 0, time(NULL) + 120); } } break; // Auras which should proc on area aura source (caster in this case): // Turn the Tables case 52914: case 52915: case 52910: // Cast positive spell on enemy target case 7099: // Curse of Mending case 39703: // Curse of Mending case 29494: // Temptation case 20233: // Improved Lay on Hands (cast on target) { target = pVictim; break; } // Combo points add triggers (need add combopoint only for main target, and after possible combopoints reset) case 15250: // Rogue Setup { if (!pVictim || pVictim != getVictim()) // applied only for main target return false; break; // continue normal case } // Finish movies that add combo case 14189: // Seal Fate (Netherblade set) case 14157: // Ruthlessness { if (!pVictim || pVictim == this) return false; // Need add combopoint AFTER finish movie (or they dropped in finish phase) break; } // Bloodthirst (($m/100)% of max health) case 23880: { basepoints0 = int32(CountPctFromMaxHealth(triggerAmount) / 1000); break; } // Shamanistic Rage triggered spell case 30824: { basepoints0 = int32( GetTotalAttackPowerValue(BASE_ATTACK) * triggerAmount / 100); break; } // Enlightenment (trigger only from mana cost spells) case 35095: { if (!procSpell || procSpell->powerType != POWER_MANA || (procSpell->manaCost == 0 && procSpell->ManaCostPercentage == 0 && procSpell->manaCostPerlevel == 0)) return false; break; } // Demonic Pact case 48090: { // Get talent aura from owner if (isPet()) if (Unit * owner = GetOwner()) { if (AuraEffect * aurEff = owner->GetDummyAuraEffect(SPELLFAMILY_WARLOCK, 3220, 0)) { basepoints0 = int32( (aurEff->GetAmount() * owner->SpellBaseDamageBonus( SpellSchoolMask( SPELL_SCHOOL_MASK_MAGIC)) + 100.0f) / 100.0f); CastCustomSpell(this, trigger_spell_id, &basepoints0, &basepoints0, NULL, true, castItem, triggeredByAura); return true; } } break; } // Sword and Board case 50227: { // Remove cooldown on Shield Slam if (GetTypeId() == TYPEID_PLAYER) this->ToPlayer()->RemoveSpellCategoryCooldown( 1209, true); break; } // Maelstrom Weapon case 53817: { // Item - Shaman T10 Enhancement 4P Bonus if (AuraEffect const* aurEff = GetAuraEffect(70832, 0)) if (Aura const* maelstrom = GetAura(53817)) if ((maelstrom->GetStackAmount() == maelstrom->GetSpellProto()->StackAmount) && roll_chance_i(aurEff->GetAmount())) CastSpell(this, 70831, true, castItem, triggeredByAura); // have rank dependent proc chance, ignore too often cases // PPM = 2.5 * (rank of talent), uint32 rank = sSpellMgr->GetSpellRank(auraSpellInfo->Id); // 5 rank -> 100% 4 rank -> 80% and etc from full rate if (!roll_chance_i(20 * rank) + 1) return false; break; } // Rolling Thunder case 88765: { if (Aura * lightningShield = GetAura(324)) { uint8 lsCharges = lightningShield->GetCharges(); if (lsCharges < 9) { lightningShield->SetCharges(lsCharges + 1); } } break; } // Astral Shift case 52179: { if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT | PROC_EX_CRITICAL_HIT)) || this == pVictim) return false; // Need stun, fear or silence mechanic if (!(GetAllSpellMechanicMask(procSpell) & ((1 << MECHANIC_SILENCE) | (1 << MECHANIC_STUN) | (1 << MECHANIC_FEAR)))) return false; break; } // Burning Determination case 54748: { if (!procSpell) return false; // Need Interrupt or Silenced mechanic if (!(GetAllSpellMechanicMask(procSpell) & ((1 << MECHANIC_INTERRUPT) | (1 << MECHANIC_SILENCE)))) return false; break; } // Lock and Load case 56453: { // Proc only from Frost/Freezing trap activation or from Freezing Arrow (the periodic dmg proc handled elsewhere) if (!(procFlags & PROC_FLAG_DONE_TRAP_ACTIVATION) || !procSpell || !(procSpell->SchoolMask & SPELL_SCHOOL_MASK_FROST) || !roll_chance_i(triggerAmount)) return false; break; } // Glyph of Death's Embrace case 58679: { // Proc only from healing part of Death Coil. Check is essential as all Death Coil spells have 0x2000 mask in SpellFamilyFlags if (!procSpell || !(procSpell->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && procSpell->SpellFamilyFlags [0] == 0x80002000)) return false; break; } // Glyph of Death Grip case 58628: { // remove cooldown of Death Grip if (GetTypeId() == TYPEID_PLAYER) this->ToPlayer()->RemoveSpellCooldown( 49576, true); return true; } // Savage Defense case 62606: { basepoints0 = int32( GetTotalAttackPowerValue(BASE_ATTACK) * triggerAmount / 100.0f); break; } // Body and Soul case 64128: case 65081: { // Proc only from PW:S cast if (!(procSpell->SpellFamilyFlags [0] & 0x00000001)) return false; break; } // Culling the Herd case 70893: { // check if we're doing a critical hit if (!(procSpell->SpellFamilyFlags [1] & 0x10000000) && (procEx != PROC_EX_CRITICAL_HIT)) return false; // check if we're procced by Claw, Bite or Smack (need to use the spell icon ID to detect it) if (!(procSpell->SpellIconID == 262 || procSpell->SpellIconID == 1680 || procSpell->SpellIconID == 473)) return false; break; } // Deathbringer Saurfang - Blood Link case 72202: target = FindNearestCreature(37813, 75.0f); // NPC_DEATHBRINGER_SAURFANG = 37813 break; // Shadow's Fate (Shadowmourne questline) case 71169: { if (GetTypeId() != TYPEID_PLAYER) return false; Player* player = this->ToPlayer(); if (player->GetQuestStatus(24749) == QUEST_STATUS_INCOMPLETE) // Unholy Infusion { if (!player->HasAura(71516) || pVictim->GetEntry() != 36678) // Shadow Infusion && Professor Putricide return false; } else if (player->GetQuestStatus(24756) == QUEST_STATUS_INCOMPLETE) // Blood Infusion { if (!player->HasAura(72154) || pVictim->GetEntry() != 37955) // Thirst Quenched && Blood-Queen Lana'thel return false; } else if (player->GetQuestStatus(24757) == QUEST_STATUS_INCOMPLETE) // Frost Infusion { if (!player->HasAura(72290) || pVictim->GetEntry() != 36853) // Frost-Imbued Blade && Sindragosa return false; } else if (player->GetQuestStatus(24547) != QUEST_STATUS_INCOMPLETE) // A Feast of Souls return false; if (pVictim->GetTypeId() != TYPEID_UNIT) return false; // critters are not allowed if (pVictim->GetCreatureType() == CREATURE_TYPE_CRITTER) return false; break; } // Incite: // gives your Heroic Strike criticals a 100% chance to cause the next Heroic Strike to also be a critical strike. // These guaranteed criticals cannot re-trigger the Incite effect. case 86627: { if (HasAura(86627)) return false; break; } // Demonic Circle: Summon case 48018: { if (HasAura(48018)) target->RemoveAura(48018); return false; break; } // Seal of Insight // giving each single-target melee attack a chance to heal the Paladin for (0.15 * AP + 0.15 * holy power) and restore 4% of the Paladin's base mana. // Unleashing this Seal's energy will ... restore 15% of the Paladin's base mana. case 20167: { int32 triggerAmount1 = 0; if (procSpell && procSpell->Id == 54158) // Judgment, unleashing case { basepoints0 = 0; // no heal effect when unleashing Seal of Insight triggerAmount1 = triggerAmount; // restore 15% base mana } else { basepoints0 = triggerAmount; // actual heal amount will be calculated in Spell::EffectHeal if (SpellEntry const* triggeredSpellInfo = sSpellStore.LookupEntry(trigger_spell_id)) triggerAmount1 = triggeredSpellInfo->EffectBasePoints[1]; // restore 4% base mana } int32 basepoints1 = GetCreatePowers(POWER_MANA) * triggerAmount1 / 100; CastCustomSpell(target, trigger_spell_id, &basepoints0, &basepoints1, NULL, true, castItem, triggeredByAura); return true; } } if (cooldown && GetTypeId() == TYPEID_PLAYER && ToPlayer()->HasSpellCooldown(trigger_spell_id)) return false; // try detect target manually if not set if (target == NULL) target = !(procFlags & (PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS | PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_POS)) && IsPositiveSpell(trigger_spell_id) ? this : pVictim; // default case if ((!target && !sSpellMgr->IsSrcTargetSpell(triggerEntry)) || (target && target != this && !target->isAlive())) return false; if (basepoints0) CastCustomSpell(target, trigger_spell_id, &basepoints0, NULL, NULL, true, castItem, triggeredByAura); else CastSpell(target, trigger_spell_id, true, castItem, triggeredByAura); if (cooldown && GetTypeId() == TYPEID_PLAYER) ToPlayer()->AddSpellCooldown( trigger_spell_id, 0, time(NULL) + cooldown); return true; } bool Unit::HandleOverrideClassScriptAuraProc(Unit *pVictim, uint32 /*damage*/, AuraEffect *triggeredByAura, SpellEntry const *procSpell, uint32 cooldown) { int32 scriptId = triggeredByAura->GetMiscValue(); if (!pVictim || !pVictim->isAlive()) return false; Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER ? this->ToPlayer()->GetItemByGuid( triggeredByAura->GetBase()->GetCastItemGUID()) : NULL; uint32 triggered_spell_id = 0; switch (scriptId) { case 836: // Improved Blizzard (Rank 1) { if (!procSpell || procSpell->SpellVisual [0] != 9487) return false; triggered_spell_id = 12484; break; } case 988: // Improved Blizzard (Rank 2) { if (!procSpell || procSpell->SpellVisual [0] != 9487) return false; triggered_spell_id = 12485; break; } case 989: // Improved Blizzard (Rank 3) { if (!procSpell || procSpell->SpellVisual [0] != 9487) return false; triggered_spell_id = 12486; break; } case 4533: // Dreamwalker Raiment 2 pieces bonus { // Chance 50% if (!roll_chance_i(50)) return false; switch (pVictim->getPowerType()) { case POWER_MANA: triggered_spell_id = 28722; break; case POWER_RAGE: triggered_spell_id = 28723; break; case POWER_ENERGY: triggered_spell_id = 28724; break; default: return false; } break; } case 4537: // Dreamwalker Raiment 6 pieces bonus triggered_spell_id = 28750; // Blessing of the Claw break; case 5497: // Improved Mana Gems triggered_spell_id = 37445; // Mana Surge break; case 7010: // Revitalize - can proc on full hp target case 7011: case 7012: { if (!roll_chance_i(triggeredByAura->GetAmount())) return false; switch (pVictim->getPowerType()) { case POWER_MANA: triggered_spell_id = 48542; break; case POWER_RAGE: triggered_spell_id = 48541; break; case POWER_ENERGY: triggered_spell_id = 48540; break; case POWER_RUNIC_POWER: triggered_spell_id = 48543; break; default: break; } break; } default: break; } // not processed if (!triggered_spell_id) return false; // standard non-dummy case SpellEntry const* triggerEntry = sSpellStore.LookupEntry( triggered_spell_id); if (!triggerEntry) { sLog->outError( "Unit::HandleOverrideClassScriptAuraProc: Spell %u triggering for class script id %u", triggered_spell_id, scriptId); return false; } if (cooldown && GetTypeId() == TYPEID_PLAYER && this->ToPlayer()->HasSpellCooldown(triggered_spell_id)) return false; CastSpell(pVictim, triggered_spell_id, true, castItem, triggeredByAura); if (cooldown && GetTypeId() == TYPEID_PLAYER) this->ToPlayer()->AddSpellCooldown( triggered_spell_id, 0, time(NULL) + cooldown); return true; } void Unit::setPowerType(Powers new_powertype) { SetByteValue(UNIT_FIELD_BYTES_0, 3, new_powertype); if (GetTypeId() == TYPEID_PLAYER) { if (this->ToPlayer()->GetGroup()) this->ToPlayer()->SetGroupUpdateFlag( GROUP_UPDATE_FLAG_POWER_TYPE); } else if (this->ToCreature()->isPet()) { Pet *pet = ((Pet*) this); if (pet->isControlled()) { Unit *owner = GetOwner(); if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && owner->ToPlayer()->GetGroup()) owner->ToPlayer()->SetGroupUpdateFlag( GROUP_UPDATE_FLAG_PET_POWER_TYPE); } } switch (new_powertype) { default: case POWER_MANA: break; case POWER_RAGE: SetMaxPower(POWER_RAGE, GetCreatePowers(POWER_RAGE)); SetPower(POWER_RAGE, 0); break; case POWER_FOCUS: SetMaxPower(POWER_FOCUS, GetCreatePowers(POWER_FOCUS)); SetPower(POWER_FOCUS, GetCreatePowers(POWER_FOCUS)); break; case POWER_ENERGY: SetMaxPower(POWER_ENERGY, GetCreatePowers(POWER_ENERGY)); break; case POWER_HAPPINESS: SetMaxPower(POWER_HAPPINESS, GetCreatePowers(POWER_HAPPINESS)); SetPower(POWER_HAPPINESS, GetCreatePowers(POWER_HAPPINESS)); break; } } FactionTemplateEntry const* Unit::getFactionTemplateEntry() const { FactionTemplateEntry const* entry = sFactionTemplateStore.LookupEntry( getFaction()); if (!entry) { static uint64 guid = 0; // prevent repeating spam same faction problem if (GetGUID() != guid) { if (const Player *player = ToPlayer()) sLog->outError( "Player %s has invalid faction (faction template id) #%u", player->GetName(), getFaction()); else if (const Creature *creature = ToCreature()) sLog->outError( "Creature (template id: %u) has invalid faction (faction template id) #%u", creature->GetCreatureInfo()->Entry, getFaction()); else sLog->outError( "Unit (name=%s, type=%u) has invalid faction (faction template id) #%u", GetName(), uint32(GetTypeId()), getFaction()); guid = GetGUID(); } } return entry; } // function based on function Unit::UnitReaction from 13850 client ReputationRank Unit::GetReactionTo(Unit const* target) const { // always friendly to self if (this == target) return REP_FRIENDLY; // always friendly to charmer or owner if (GetCharmerOrOwnerOrSelf() == target->GetCharmerOrOwnerOrSelf()) return REP_FRIENDLY; if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE)) { if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE)) { Player const* selfPlayerOwner = GetAffectingPlayer(); Player const* targetPlayerOwner = target->GetAffectingPlayer(); if (selfPlayerOwner && targetPlayerOwner) { // always friendly to other unit controlled by player, or to the player himself if (selfPlayerOwner == targetPlayerOwner) return REP_FRIENDLY; // duel - always hostile to opponent if (selfPlayerOwner->duel && selfPlayerOwner->duel->opponent == targetPlayerOwner && selfPlayerOwner->duel->startTime != 0) return REP_HOSTILE; // same group - checks dependant only on our faction - skip FFA_PVP for example if (selfPlayerOwner->IsInRaidWith(targetPlayerOwner)) return REP_FRIENDLY; // return true to allow config option AllowTwoSide.Interaction.Group to work // however client seems to allow mixed group parties, because in 13850 client it works like: // return GetFactionReactionTo(getFactionTemplateEntry(), target); } // check FFA_PVP if (GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_FFA_PVP && target->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_FFA_PVP) return REP_HOSTILE; if (selfPlayerOwner) { if (FactionTemplateEntry const* targetFactionTemplateEntry = target->getFactionTemplateEntry()) { if (ReputationRank const* repRank = selfPlayerOwner->GetReputationMgr().GetForcedRankIfAny(targetFactionTemplateEntry)) return *repRank; if (!selfPlayerOwner->HasFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_IGNORE_REPUTATION)) { if (FactionEntry const* targetFactionEntry = sFactionStore.LookupEntry(targetFactionTemplateEntry->faction)) { if (targetFactionEntry->CanHaveReputation()) { // check contested flags if (targetFactionTemplateEntry->factionFlags & FACTION_TEMPLATE_FLAG_CONTESTED_GUARD && selfPlayerOwner->HasFlag( PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP)) return REP_HOSTILE; // if faction have reputation then hostile state dependent only from at_war state if (selfPlayerOwner->GetReputationMgr().IsAtWar( targetFactionEntry)) return REP_HOSTILE; return REP_FRIENDLY; } } } } } } } // do checks dependant only on our faction return GetFactionReactionTo(getFactionTemplateEntry(), target); } ReputationRank Unit::GetFactionReactionTo( FactionTemplateEntry const* factionTemplateEntry, Unit const* target) { // always neutral when no template entry found if (!factionTemplateEntry) return REP_NEUTRAL; FactionTemplateEntry const* targetFactionTemplateEntry = target->getFactionTemplateEntry(); if (!targetFactionTemplateEntry) return REP_NEUTRAL; if (Player const* targetPlayerOwner = target->GetAffectingPlayer()) { // check contested flags if (factionTemplateEntry->factionFlags & FACTION_TEMPLATE_FLAG_CONTESTED_GUARD && targetPlayerOwner->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP)) return REP_HOSTILE; if (ReputationRank const* repRank = targetPlayerOwner->GetReputationMgr().GetForcedRankIfAny(factionTemplateEntry)) return *repRank; if (!target->HasFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_IGNORE_REPUTATION)) { if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction)) { if (factionEntry->CanHaveReputation()) { // CvP case - check reputation, don't allow state higher than neutral when at war ReputationRank repRank = targetPlayerOwner->GetReputationMgr().GetRank( factionEntry); if (targetPlayerOwner->GetReputationMgr().IsAtWar( factionEntry)) repRank = std::min(REP_NEUTRAL, repRank); return repRank; } } } } // common faction based check if (factionTemplateEntry->IsHostileTo(*targetFactionTemplateEntry)) return REP_HOSTILE; if (factionTemplateEntry->IsFriendlyTo(*targetFactionTemplateEntry)) return REP_FRIENDLY; if (targetFactionTemplateEntry->IsFriendlyTo(*factionTemplateEntry)) return REP_FRIENDLY; if (factionTemplateEntry->factionFlags & FACTION_TEMPLATE_FLAG_HOSTILE_BY_DEFAULT) return REP_HOSTILE; // neutral by default return REP_NEUTRAL; } bool Unit::IsHostileTo(Unit const* unit) const { if (!unit) return false; // always non-hostile to self if (unit == this) return false; // always non-hostile to GM in GM mode if (unit->GetTypeId() == TYPEID_PLAYER && ((Player const*) unit)->isGameMaster()) return false; // always hostile to enemy if (getVictim() == unit || unit->getVictim() == this) return true; // test pet/charm masters instead pers/charmeds Unit const* testerOwner = GetCharmerOrOwner(); Unit const* targetOwner = unit->GetCharmerOrOwner(); // always hostile to owner's enemy if (testerOwner && (testerOwner->getVictim() == unit || unit->getVictim() == testerOwner)) return true; // always hostile to enemy owner if (targetOwner && (getVictim() == targetOwner || targetOwner->getVictim() == this)) return true; // always hostile to owner of owner's enemy if (testerOwner && targetOwner && (testerOwner->getVictim() == targetOwner || targetOwner->getVictim() == testerOwner)) return true; Unit const* tester = testerOwner ? testerOwner : this; Unit const* target = targetOwner ? targetOwner : unit; // always non-hostile to target with common owner, or to owner/pet if (tester == target) return false; // special cases (Duel, etc) if (tester->GetTypeId() == TYPEID_PLAYER && target->GetTypeId() == TYPEID_PLAYER) { Player const* pTester = (Player const*) tester; Player const* pTarget = (Player const*) target; // Duel if (pTester->duel && pTester->duel->opponent == pTarget && pTester->duel->startTime != 0) return true; // Group if (pTester->GetGroup() && pTester->GetGroup() == pTarget->GetGroup()) return false; // Sanctuary if (pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY)) return false; // PvP FFA state if (pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP)) return true; //= PvP states // Green/Blue (can't attack) if (!pTester->HasAuraType(SPELL_AURA_MOD_FACTION) && !pTarget->HasAuraType(SPELL_AURA_MOD_FACTION)) { if (pTester->GetTeam() == pTarget->GetTeam()) return false; // Red (can attack) if true, Blue/Yellow (can't attack) in another case return pTester->IsPvP() && pTarget->IsPvP(); } } // faction base cases FactionTemplateEntry const*tester_faction = tester->getFactionTemplateEntry(); FactionTemplateEntry const*target_faction = target->getFactionTemplateEntry(); if (!tester_faction || !target_faction) return false; if (target->isAttackingPlayer() && tester->IsContestedGuard()) return true; // PvC forced reaction and reputation case if (tester->GetTypeId() == TYPEID_PLAYER && !tester->HasAuraType(SPELL_AURA_MOD_FACTION)) { // forced reaction if (target_faction->faction) { if (ReputationRank const* force =tester->ToPlayer()->GetReputationMgr().GetForcedRankIfAny(target_faction)) return *force <= REP_HOSTILE; // if faction have reputation then hostile state for tester at 100% dependent from at_war state if (FactionEntry const* raw_target_faction = sFactionStore.LookupEntry(target_faction->faction)) if (FactionState const* factionState = tester->ToPlayer()->GetReputationMgr().GetState(raw_target_faction)) return (factionState->Flags & FACTION_FLAG_AT_WAR); } } // CvP forced reaction and reputation case else if (target->GetTypeId() == TYPEID_PLAYER && !target->HasAuraType(SPELL_AURA_MOD_FACTION)) { // forced reaction if (tester_faction->faction) { if (ReputationRank const* force = target->ToPlayer()->GetReputationMgr().GetForcedRankIfAny(tester_faction)) return *force <= REP_HOSTILE; // apply reputation state FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry( tester_faction->faction); if (raw_tester_faction && raw_tester_faction->reputationListID >= 0) return ((Player const*) target)->GetReputationMgr().GetRank( raw_tester_faction) <= REP_HOSTILE; } } // common faction based case (CvC, PvC, CvP) return tester_faction->IsHostileTo(*target_faction); } bool Unit::IsFriendlyTo(Unit const* unit) const { // always friendly to self if (unit == this) return true; // always friendly to GM in GM mode if (unit->GetTypeId() == TYPEID_PLAYER && ((Player const*) unit)->isGameMaster()) return true; // always non-friendly to enemy if (getVictim() == unit || unit->getVictim() == this) return false; // test pet/charm masters instead pers/charmeds Unit const* testerOwner = GetCharmerOrOwner(); Unit const* targetOwner = unit->GetCharmerOrOwner(); // always non-friendly to owner's enemy if (testerOwner && (testerOwner->getVictim() == unit || unit->getVictim() == testerOwner)) return false; // always non-friendly to enemy owner if (targetOwner && (getVictim() == targetOwner || targetOwner->getVictim() == this)) return false; // always non-friendly to owner of owner's enemy if (testerOwner && targetOwner && (testerOwner->getVictim() == targetOwner || targetOwner->getVictim() == testerOwner)) return false; Unit const* tester = testerOwner ? testerOwner : this; Unit const* target = targetOwner ? targetOwner : unit; // always friendly to target with common owner, or to owner/pet if (tester == target) return true; // special cases (Duel) if (tester->GetTypeId() == TYPEID_PLAYER && target->GetTypeId() == TYPEID_PLAYER) { Player const* pTester = (Player const*) tester; Player const* pTarget = (Player const*) target; // Duel if (pTester->duel && pTester->duel->opponent == target && pTester->duel->startTime != 0) return false; // Group if (pTester->GetGroup() && pTester->GetGroup() == pTarget->GetGroup()) return true; // Sanctuary if (pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY)) return true; // PvP FFA state if (pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP)) return false; //= PvP states // Green/Blue (non-attackable) if (!pTester->HasAuraType(SPELL_AURA_MOD_FACTION) && !pTarget->HasAuraType(SPELL_AURA_MOD_FACTION)) { if (pTester->GetTeam() == pTarget->GetTeam()) return true; // Blue (friendly/non-attackable) if not PVP, or Yellow/Red in another case (attackable) return !pTarget->IsPvP(); } } // faction base cases FactionTemplateEntry const *tester_faction = tester->getFactionTemplateEntry(); FactionTemplateEntry const *target_faction = target->getFactionTemplateEntry(); if (!tester_faction || !target_faction) return false; if (target->isAttackingPlayer() && tester->IsContestedGuard()) return false; // PvC forced reaction and reputation case if (tester->GetTypeId() == TYPEID_PLAYER && !tester->HasAuraType(SPELL_AURA_MOD_FACTION)) { // forced reaction if (target_faction->faction) { if (ReputationRank const *force =tester->ToPlayer()->GetReputationMgr().GetForcedRankIfAny(target_faction)) return *force >= REP_FRIENDLY; // if faction have reputation then friendly state for tester at 100% dependent from at_war state if (FactionEntry const *raw_target_faction = sFactionStore.LookupEntry(target_faction->faction)) if (FactionState const *factionState = tester->ToPlayer()->GetReputationMgr().GetState(raw_target_faction)) return !(factionState->Flags & FACTION_FLAG_AT_WAR); } } // CvP forced reaction and reputation case else if (target->GetTypeId() == TYPEID_PLAYER && !target->HasAuraType(SPELL_AURA_MOD_FACTION)) { // forced reaction if (tester_faction->faction) { if (ReputationRank const *force =target->ToPlayer()->GetReputationMgr().GetForcedRankIfAny(tester_faction)) return *force >= REP_FRIENDLY; // apply reputation state if (FactionEntry const *raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction)) if (raw_tester_faction->reputationListID >= 0) return ((Player const*) target)->GetReputationMgr().GetRank( raw_tester_faction) >= REP_FRIENDLY; } } // common faction based case (CvC, PvC, CvP) return tester_faction->IsFriendlyTo(*target_faction); } bool Unit::IsHostileToPlayers() const { FactionTemplateEntry const *my_faction = getFactionTemplateEntry(); if (!my_faction || !my_faction->faction) return false; FactionEntry const *raw_faction = sFactionStore.LookupEntry( my_faction->faction); if (raw_faction && raw_faction->reputationListID >= 0) return false; return my_faction->IsHostileToPlayers(); } bool Unit::IsNeutralToAll() const { FactionTemplateEntry const *my_faction = getFactionTemplateEntry(); if (!my_faction || !my_faction->faction) return true; FactionEntry const *raw_faction = sFactionStore.LookupEntry( my_faction->faction); if (raw_faction && raw_faction->reputationListID >= 0) return false; return my_faction->IsNeutralToAll(); } bool Unit::Attack(Unit *victim, bool meleeAttack) { if (!victim || victim == this) return false; // dead units can neither attack nor be attacked if (!isAlive() || !victim->IsInWorld() || !victim->isAlive()) return false; // player cannot attack in mount state if (GetTypeId() == TYPEID_PLAYER && IsMounted()) return false; // nobody can attack GM in GM-mode if (victim->GetTypeId() == TYPEID_PLAYER) { if (victim->ToPlayer()->isGameMaster()) return false; } else { //!creature -> WHO ARE U?? if (!victim->ToCreature() || victim->ToCreature()->IsInEvadeMode()) return false; } // remove SPELL_AURA_MOD_UNATTACKABLE at attack (in case non-interruptible spells stun aura applied also that not let attack) if (HasAuraType(SPELL_AURA_MOD_UNATTACKABLE)) RemoveAurasByType( SPELL_AURA_MOD_UNATTACKABLE); if (m_attacking) { if (m_attacking == victim) { // switch to melee attack from ranged/magic if (meleeAttack) { if (!HasUnitState(UNIT_STAT_MELEE_ATTACKING)) { AddUnitState(UNIT_STAT_MELEE_ATTACKING); SendMeleeAttackStart(victim); return true; } } else if (HasUnitState(UNIT_STAT_MELEE_ATTACKING)) { ClearUnitState(UNIT_STAT_MELEE_ATTACKING); SendMeleeAttackStop(victim); return true; } return false; } //switch target InterruptSpell(CURRENT_MELEE_SPELL); if (!meleeAttack) ClearUnitState(UNIT_STAT_MELEE_ATTACKING); } if (m_attacking) m_attacking->_removeAttacker(this); m_attacking = victim; m_attacking->_addAttacker(this); // Set our target SetUInt64Value(UNIT_FIELD_TARGET, victim->GetGUID()); if (meleeAttack) AddUnitState(UNIT_STAT_MELEE_ATTACKING); // set position before any AI calls/assistance //if (GetTypeId() == TYPEID_UNIT) // this->ToCreature()->SetCombatStartPosition(GetPositionX(), GetPositionY(), GetPositionZ()); if (GetTypeId() == TYPEID_UNIT && !this->ToCreature()->isPet()) { // should not let player enter combat by right clicking target SetInCombatWith(victim); if (victim->GetTypeId() == TYPEID_PLAYER) victim->SetInCombatWith(this); AddThreat(victim, 0.0f); this->ToCreature()->SendAIReaction(AI_REACTION_HOSTILE); this->ToCreature()->CallAssistance(); } if (GetTypeId() == TYPEID_PLAYER && ToPlayer()->GetEmoteState() != 0) ToPlayer()->SetEmoteState( 0); // delay offhand weapon attack to next attack time if (haveOffhandWeapon()) resetAttackTimer(OFF_ATTACK); if (meleeAttack) SendMeleeAttackStart(victim); return true; } bool Unit::AttackStop() { if (!m_attacking) return false; Unit* victim = m_attacking; m_attacking->_removeAttacker(this); m_attacking = NULL; // Clear our target SetUInt64Value(UNIT_FIELD_TARGET, 0); ClearUnitState(UNIT_STAT_MELEE_ATTACKING); InterruptSpell(CURRENT_MELEE_SPELL); // reset only at real combat stop if (GetTypeId() == TYPEID_UNIT) { this->ToCreature()->SetNoCallAssistance(false); if (this->ToCreature()->HasSearchedAssistance()) { this->ToCreature()->SetNoSearchAssistance(false); UpdateSpeed(MOVE_RUN, false); } } SendMeleeAttackStop(victim); if (GetTypeId() == TYPEID_PLAYER && ToPlayer()->GetEmoteState() != 0) ToPlayer()->SetEmoteState( 0); return true; } void Unit::CombatStop(bool includingCast) { if (includingCast && IsNonMeleeSpellCasted(false)) InterruptNonMeleeSpells( false); AttackStop(); RemoveAllAttackers(); if (GetTypeId() == TYPEID_PLAYER) this->ToPlayer()->SendAttackSwingCancelAttack(); // melee and ranged forced attack cancel ClearInCombat(); } void Unit::CombatStopWithPets(bool includingCast) { CombatStop(includingCast); for (ControlList::const_iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr) (*itr)->CombatStop(includingCast); } bool Unit::isAttackingPlayer() const { if (HasUnitState(UNIT_STAT_ATTACK_PLAYER)) return true; for (ControlList::const_iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr) if ((*itr)->isAttackingPlayer()) return true; for (uint8 i = 0; i < MAX_SUMMON_SLOT; ++i) if (m_SummonSlot [i]) if (Creature *summon = GetMap()->GetCreature(m_SummonSlot[i])) if (summon->isAttackingPlayer()) return true; return false; } void Unit::RemoveAllAttackers() { while (!m_attackers.empty()) { AttackerSet::iterator iter = m_attackers.begin(); if (!(*iter)->AttackStop()) { sLog->outError( "WORLD: Unit has an attacker that isn't attacking it!"); m_attackers.erase(iter); } } } void Unit::ModifyAuraState(AuraState flag, bool apply) { if (apply) { if (!HasFlag(UNIT_FIELD_AURASTATE, 1 << (flag - 1))) { SetFlag(UNIT_FIELD_AURASTATE, 1 << (flag - 1)); if (GetTypeId() == TYPEID_PLAYER) { PlayerSpellMap const& sp_list = this->ToPlayer()->GetSpellMap(); for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr) { if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled) continue; SpellEntry const *spellInfo = sSpellStore.LookupEntry( itr->first); if (!spellInfo || !IsPassiveSpell(itr->first)) continue; if (spellInfo->CasterAuraState == uint32(flag)) CastSpell( this, itr->first, true, NULL); } } else if (this->ToCreature()->isPet()) { Pet *pet = ((Pet*) this); for (PetSpellMap::const_iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr) { if (itr->second.state == PETSPELL_REMOVED) continue; SpellEntry const *spellInfo = sSpellStore.LookupEntry( itr->first); if (!spellInfo || !IsPassiveSpell(itr->first)) continue; if (spellInfo->CasterAuraState == uint32(flag)) CastSpell( this, itr->first, true, NULL); } } } } else { if (HasFlag(UNIT_FIELD_AURASTATE, 1 << (flag - 1))) { RemoveFlag(UNIT_FIELD_AURASTATE, 1 << (flag - 1)); if (flag != AURA_STATE_ENRAGE) // enrage aura state triggering continues auras { Unit::AuraApplicationMap& tAuras = GetAppliedAuras(); for (Unit::AuraApplicationMap::iterator itr = tAuras.begin(); itr != tAuras.end();) { SpellEntry const* spellProto = (*itr).second->GetBase()->GetSpellProto(); if (spellProto->CasterAuraState == uint32(flag)) RemoveAura( itr); else ++itr; } } } } } uint32 Unit::BuildAuraStateUpdateForTarget(Unit * target) const { uint32 auraStates = GetUInt32Value(UNIT_FIELD_AURASTATE) & ~(PER_CASTER_AURA_STATE_MASK); for (AuraStateAurasMap::const_iterator itr = m_auraStateAuras.begin(); itr != m_auraStateAuras.end(); ++itr) if ((1 << (itr->first - 1)) & PER_CASTER_AURA_STATE_MASK) if (itr->second->GetBase()->GetCasterGUID() == target->GetGUID()) auraStates |= (1 << (itr->first - 1)); return auraStates; } bool Unit::HasAuraState(AuraState flag, SpellEntry const *spellProto, Unit const * Caster) const { if (Caster) { if (spellProto) { AuraEffectList const& stateAuras = Caster->GetAuraEffectsByType( SPELL_AURA_ABILITY_IGNORE_AURASTATE); for (AuraEffectList::const_iterator j = stateAuras.begin(); j != stateAuras.end(); ++j) if ((*j)->IsAffectedOnSpell(spellProto)) return true; } // Check per caster aura state // If aura with aurastate by caster not found return false if ((1 << (flag - 1)) & PER_CASTER_AURA_STATE_MASK) { for (AuraStateAurasMap::const_iterator itr = m_auraStateAuras.lower_bound(flag); itr != m_auraStateAuras.upper_bound(flag); ++itr) if (itr->second->GetBase()->GetCasterGUID() == Caster->GetGUID()) return true; return false; } } return HasFlag(UNIT_FIELD_AURASTATE, 1 << (flag - 1)); } Unit *Unit::GetOwner() const { if (uint64 ownerid = GetOwnerGUID()) { return ObjectAccessor::GetUnit(*this, ownerid); } return NULL; } Unit *Unit::GetCharmer() const { if (uint64 charmerid = GetCharmerGUID()) return ObjectAccessor::GetUnit( *this, charmerid); return NULL; } Player* Unit::GetCharmerOrOwnerPlayerOrPlayerItself() const { uint64 guid = GetCharmerOrOwnerGUID(); if (IS_PLAYER_GUID(guid)) return ObjectAccessor::GetPlayer(*this, guid); return GetTypeId() == TYPEID_PLAYER ? (Player*) this : NULL; } Player* Unit::GetAffectingPlayer() const { if (!GetCharmerOrOwnerGUID()) return GetTypeId() == TYPEID_PLAYER ? (Player*) this : NULL; if (Unit* owner = GetCharmerOrOwner()) return owner->GetCharmerOrOwnerPlayerOrPlayerItself(); return NULL; } Minion *Unit::GetFirstMinion() const { if (uint64 pet_guid = GetMinionGUID()) { if (Creature* pet = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, pet_guid)) if (pet->HasUnitTypeMask( UNIT_MASK_MINION)) return (Minion*) pet; sLog->outError("Unit::GetFirstMinion: Minion %u not exist.", GUID_LOPART(pet_guid)); const_cast <Unit*>(this)->SetMinionGUID(0); } return NULL; } Guardian* Unit::GetGuardianPet() const { if (uint64 pet_guid = GetPetGUID()) { if (Creature* pet = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, pet_guid)) if (pet->HasUnitTypeMask( UNIT_MASK_GUARDIAN)) return (Guardian*) pet; sLog->outCrash("Unit::GetGuardianPet: Guardian " UI64FMTD " not exist.", pet_guid); const_cast <Unit*>(this)->SetPetGUID(0); } return NULL; } Unit* Unit::GetCharm() const { if (uint64 charm_guid = GetCharmGUID()) { if (Unit* pet = ObjectAccessor::GetUnit(*this, charm_guid)) return pet; sLog->outError("Unit::GetCharm: Charmed creature %u not exist.", GUID_LOPART(charm_guid)); const_cast <Unit*>(this)->SetUInt64Value(UNIT_FIELD_CHARM, 0); } return NULL; } void Unit::SetMinion(Minion *minion, bool apply, PetSlot slot) { sLog->outDebug(LOG_FILTER_UNITS, "SetMinion %u for %u, apply %u", minion->GetEntry(), GetEntry(), apply); if (apply) { if (!minion->AddUInt64Value(UNIT_FIELD_SUMMONEDBY, GetGUID())) { sLog->outCrash("SetMinion: Minion %u is not the minion of owner %u", minion->GetEntry(), GetEntry()); return; } m_Controlled.insert(minion); if (GetTypeId() == TYPEID_PLAYER) { minion->m_ControlledByPlayer = true; minion->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE); } // Can only have one pet. If a new one is summoned, dismiss the old one. if (minion->IsGuardianPet()) { if (Guardian* oldPet = GetGuardianPet()) { if (oldPet != minion && (oldPet->isPet() || minion->isPet() || oldPet->GetEntry() != minion->GetEntry())) { // remove existing minion pet if (oldPet->isPet()) ((Pet*) oldPet)->Remove( PET_SLOT_ACTUAL_PET_SLOT); else oldPet->UnSummon(); SetPetGUID(minion->GetGUID()); SetMinionGUID(0); } } else { SetPetGUID(minion->GetGUID()); SetMinionGUID(0); } if (slot == PET_SLOT_UNK_SLOT) { if (minion->isPet() && minion->ToPet()->getPetType() == HUNTER_PET) assert( false); slot = PET_SLOT_OTHER_PET; } if (GetTypeId() == TYPEID_PLAYER) { if (!minion->isHunterPet()) //If its not a Hunter Pet, well lets not try to use it for hunters then. { ToPlayer()->m_currentPetSlot = slot; ToPlayer()->m_petSlotUsed = 3452816845; // the same as 100 so that the pet is only that and nothing more // ToPlayer()->setPetSlotUsed(slot, true); } if (slot >= PET_SLOT_HUNTER_FIRST && slot <= PET_SLOT_HUNTER_LAST) // Always save thoose spots where hunter is correct { ToPlayer()->m_currentPetSlot = slot; ToPlayer()->setPetSlotUsed(slot, true); } } } if (minion->HasUnitTypeMask(UNIT_MASK_CONTROLABLE_GUARDIAN)) { if (AddUInt64Value(UNIT_FIELD_SUMMON, minion->GetGUID())) { } } if (minion->m_Properties && minion->m_Properties->Type == SUMMON_TYPE_MINIPET) { SetCritterGUID(minion->GetGUID()); } // PvP, FFAPvP minion->SetByteValue(UNIT_FIELD_BYTES_2, 1, GetByteValue(UNIT_FIELD_BYTES_2, 1)); // FIXME: hack, speed must be set only at follow if (GetTypeId() == TYPEID_PLAYER && minion->isPet()) for (uint8 i = 0; i < MAX_MOVE_TYPE; ++i) minion->SetSpeed(UnitMoveType(i), m_speed_rate [i], true); // Ghoul pets have energy instead of mana (is anywhere better place for this code?) if (minion->IsPetGhoul()) minion->setPowerType(POWER_ENERGY); if (GetTypeId() == TYPEID_PLAYER) { // Send infinity cooldown - client does that automatically but after relog cooldown needs to be set again SpellEntry const *spellInfo = sSpellStore.LookupEntry( minion->GetUInt32Value(UNIT_CREATED_BY_SPELL)); if (spellInfo && (spellInfo->Attributes & SPELL_ATTR0_DISABLED_WHILE_ACTIVE)) this->ToPlayer()->AddSpellAndCategoryCooldowns( spellInfo, 0, NULL, true); } } else { if (minion->GetOwnerGUID() != GetGUID()) { sLog->outCrash("SetMinion: Minion %u is not the minion of owner %u", minion->GetEntry(), GetEntry()); return; } m_Controlled.erase(minion); if (minion->m_Properties && minion->m_Properties->Type == SUMMON_TYPE_MINIPET) { if (GetCritterGUID() == minion->GetGUID()) SetCritterGUID(0); } if (minion->IsGuardianPet()) { if (GetPetGUID() == minion->GetGUID()) SetPetGUID(0); } else if (minion->isTotem()) { // All summoned by totem minions must disappear when it is removed. if (const SpellEntry* spInfo = sSpellStore.LookupEntry(minion->ToTotem()->GetSpell())) for (int i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (spInfo->Effect [i] != SPELL_EFFECT_SUMMON) continue; this->RemoveAllMinionsByEntry(spInfo->EffectMiscValue [i]); } } if (GetTypeId() == TYPEID_PLAYER) { SpellEntry const *spellInfo = sSpellStore.LookupEntry( minion->GetUInt32Value(UNIT_CREATED_BY_SPELL)); // Remove infinity cooldown if (spellInfo && (spellInfo->Attributes & SPELL_ATTR0_DISABLED_WHILE_ACTIVE)) this->ToPlayer()->SendCooldownEvent( spellInfo); } //if (minion->HasUnitTypeMask(UNIT_MASK_GUARDIAN)) { if (RemoveUInt64Value(UNIT_FIELD_SUMMON, minion->GetGUID())) { //Check if there is another minion for (ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr) { // do not use this check, creature do not have charm guid //if (GetCharmGUID() == (*itr)->GetGUID()) if (GetGUID() == (*itr)->GetCharmerGUID()) continue; //ASSERT((*itr)->GetOwnerGUID() == GetGUID()); if ((*itr)->GetOwnerGUID() != GetGUID()) { OutDebugInfo(); (*itr)->OutDebugInfo(); ASSERT(false); } ASSERT((*itr)->GetTypeId() == TYPEID_UNIT); if (!(*itr)->HasUnitTypeMask( UNIT_MASK_CONTROLABLE_GUARDIAN)) continue; if (AddUInt64Value(UNIT_FIELD_SUMMON, (*itr)->GetGUID())) { //show another pet bar if there is no charm bar if (GetTypeId() == TYPEID_PLAYER && !GetCharmGUID()) { if ((*itr)->isPet()) this->ToPlayer()->PetSpellInitialize(); else this->ToPlayer()->CharmSpellInitialize(); } } break; } } } } } void Unit::GetAllMinionsByEntry(std::list <Unit*>& Minions, uint32 entry) { for (Unit::ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end();) { Unit *unit = *itr; ++itr; if (unit->GetEntry() == entry && unit->GetTypeId() == TYPEID_UNIT && unit->ToCreature()->isSummon()) // minion, actually Minions.push_back(unit); } } void Unit::RemoveAllMinionsByEntry(uint32 entry) { for (Unit::ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end();) { Unit *unit = *itr; ++itr; if (unit->GetEntry() == entry && unit->GetTypeId() == TYPEID_UNIT && unit->ToCreature()->isSummon()) // minion, actually unit->ToTempSummon()->UnSummon(); // i think this is safe because i have never heard that a despawned minion will trigger a same minion } } void Unit::SetCharm(Unit* charm, bool apply) { if (apply) { if (GetTypeId() == TYPEID_PLAYER) { if (!AddUInt64Value(UNIT_FIELD_CHARM, charm->GetGUID())) sLog->outCrash( "Player %s is trying to charm unit %u, but it already has a charmed unit " UI64FMTD "", GetName(), charm->GetEntry(), GetCharmGUID()); charm->m_ControlledByPlayer = true; // TODO: maybe we can use this flag to check if controlled by player charm->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE); } else charm->m_ControlledByPlayer = false; // PvP, FFAPvP charm->SetByteValue(UNIT_FIELD_BYTES_2, 1, GetByteValue(UNIT_FIELD_BYTES_2, 1)); if (!charm->AddUInt64Value(UNIT_FIELD_CHARMEDBY, GetGUID())) sLog->outCrash( "Unit %u is being charmed, but it already has a charmer " UI64FMTD "", charm->GetEntry(), charm->GetCharmerGUID()); if (charm->HasUnitMovementFlag(MOVEMENTFLAG_WALKING)) { charm->RemoveUnitMovementFlag(MOVEMENTFLAG_WALKING); charm->SendMovementFlagUpdate(); } m_Controlled.insert(charm); } else { if (GetTypeId() == TYPEID_PLAYER) { if (!RemoveUInt64Value(UNIT_FIELD_CHARM, charm->GetGUID())) sLog->outCrash( "Player %s is trying to uncharm unit %u, but it has another charmed unit " UI64FMTD "", GetName(), charm->GetEntry(), GetCharmGUID()); } if (!charm->RemoveUInt64Value(UNIT_FIELD_CHARMEDBY, GetGUID())) sLog->outCrash( "Unit %u is being uncharmed, but it has another charmer " UI64FMTD "", charm->GetEntry(), charm->GetCharmerGUID()); if (charm->GetTypeId() == TYPEID_PLAYER) { charm->m_ControlledByPlayer = true; charm->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE); charm->ToPlayer()->UpdatePvPState(); } else if (Player *player = charm->GetCharmerOrOwnerPlayerOrPlayerItself()) { charm->m_ControlledByPlayer = true; charm->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE); charm->SetByteValue(UNIT_FIELD_BYTES_2, 1, player->GetByteValue(UNIT_FIELD_BYTES_2, 1)); } else { charm->m_ControlledByPlayer = false; charm->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE); charm->SetByteValue(UNIT_FIELD_BYTES_2, 1, 0); } if (charm->GetTypeId() == TYPEID_PLAYER || !charm->ToCreature()->HasUnitTypeMask(UNIT_MASK_MINION) || charm->GetOwnerGUID() != GetGUID()) m_Controlled.erase( charm); } } int32 Unit::DealHeal(Unit *pVictim, uint32 addhealth) { int32 gain = 0; if (pVictim->IsAIEnabled) pVictim->GetAI()->HealReceived(this, addhealth); if (IsAIEnabled) GetAI()->HealDone(pVictim, addhealth); if (addhealth) gain = pVictim->ModifyHealth(int32(addhealth)); Unit* unit = this; m_heal_done [0] += addhealth; if (GetTypeId() == TYPEID_UNIT && this->ToCreature()->isTotem()) unit = GetOwner(); if (unit->GetTypeId() == TYPEID_PLAYER) { if (Battleground *bg = unit->ToPlayer()->GetBattleground()) bg->UpdatePlayerScore( (Player*) unit, SCORE_HEALING_DONE, gain); // use the actual gain, as the overheal shall not be counted, skip gain 0 (it ignored anyway in to criteria) if (gain) unit->ToPlayer()->GetAchievementMgr().UpdateAchievementCriteria( ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE, gain, 0, pVictim); unit->ToPlayer()->GetAchievementMgr().UpdateAchievementCriteria( ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEAL_CASTED, addhealth); } if (pVictim->GetTypeId() == TYPEID_PLAYER) { pVictim->ToPlayer()->GetAchievementMgr().UpdateAchievementCriteria( ACHIEVEMENT_CRITERIA_TYPE_TOTAL_HEALING_RECEIVED, gain); pVictim->ToPlayer()->GetAchievementMgr().UpdateAchievementCriteria( ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALING_RECEIVED, addhealth); } return gain; } Unit* Unit::SelectMagnetTarget(Unit *victim, SpellEntry const *spellInfo) { if (!victim) return NULL; // Magic case if (spellInfo && (spellInfo->DmgClass == SPELL_DAMAGE_CLASS_NONE || spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC)) { //I am not sure if this should be redirected. if (spellInfo->DmgClass == SPELL_DAMAGE_CLASS_NONE) return victim; Unit::AuraEffectList const& magnetAuras = victim->GetAuraEffectsByType( SPELL_AURA_SPELL_MAGNET); for (Unit::AuraEffectList::const_iterator itr = magnetAuras.begin(); itr != magnetAuras.end(); ++itr) if (Unit* magnet = (*itr)->GetBase()->GetUnitOwner()) if (magnet->isAlive()) if (Spell* spell = FindCurrentSpellBySpellId(spellInfo->Id)) { // Store magnet aura to drop charge on hit spell->SetMagnetingAura((*itr)->GetBase()); return magnet; } } // Melee && ranged case else { AuraEffectList const& hitTriggerAuras = victim->GetAuraEffectsByType( SPELL_AURA_ADD_CASTER_HIT_TRIGGER); for (AuraEffectList::const_iterator i = hitTriggerAuras.begin(); i != hitTriggerAuras.end(); ++i) if (Unit* magnet = (*i)->GetBase()->GetCaster()) if (magnet->isAlive() && magnet->IsWithinLOSInMap(this)) if (roll_chance_i( (*i)->GetAmount())) { (*i)->GetBase()->DropCharge(); return magnet; } } return victim; } Unit* Unit::GetFirstControlled() const { //Sequence: charmed, pet, other guardians Unit *unit = GetCharm(); if (!unit) if (uint64 guid = GetUInt64Value(UNIT_FIELD_SUMMON)) unit = ObjectAccessor::GetUnit(*this, guid); return unit; } void Unit::RemoveAllControlled() { //possessed pet and vehicle if (GetTypeId() == TYPEID_PLAYER) this->ToPlayer()->StopCastingCharm(); while (!m_Controlled.empty()) { Unit *target = *m_Controlled.begin(); m_Controlled.erase(m_Controlled.begin()); if (target->GetCharmerGUID() == GetGUID()) target->RemoveCharmAuras(); else if (target->GetOwnerGUID() == GetGUID() && target->isSummon()) target->ToTempSummon()->UnSummon(); else sLog->outError( "Unit %u is trying to release unit %u which is neither charmed nor owned by it", GetEntry(), target->GetEntry()); } if (GetPetGUID()) sLog->outCrash("Unit %u is not able to release its pet " UI64FMTD, GetEntry(), GetPetGUID()); if (GetMinionGUID()) sLog->outCrash("Unit %u is not able to release its minion " UI64FMTD, GetEntry(), GetMinionGUID()); if (GetCharmGUID()) sLog->outCrash("Unit %u is not able to release its charm " UI64FMTD, GetEntry(), GetCharmGUID()); } Unit* Unit::GetNextRandomRaidMemberOrPet(float radius) { Player* player = NULL; if (GetTypeId() == TYPEID_PLAYER) player = (Player*) this; // Should we enable this also for charmed units? else if (GetTypeId() == TYPEID_UNIT && this->ToCreature()->isPet()) player = (Player*) GetOwner(); if (!player) return NULL; Group *pGroup = player->GetGroup(); //When there is no group check pet presence if (!pGroup) { // We are pet now, return owner if (player != this) return IsWithinDistInMap(player, radius) ? player : NULL; Unit * pet = GetGuardianPet(); //No pet, no group, nothing to return if (!pet) return NULL; // We are owner now, return pet return IsWithinDistInMap(pet, radius) ? pet : NULL; } std::vector <Unit*> nearMembers; //reserve place for players and pets because resizing vector every unit push is unefficient (vector is reallocated then) nearMembers.reserve(pGroup->GetMembersCount() * 2); for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next()) if (Player *Target = itr->getSource()) { // IsHostileTo check duel and controlled by enemy if (Target != this && Target->isAlive() && IsWithinDistInMap(Target, radius) && !IsHostileTo(Target)) nearMembers.push_back(Target); // Push player's pet to vector if (Unit *pet = Target->GetGuardianPet()) if (pet != this && pet->isAlive() && IsWithinDistInMap(pet, radius) && !IsHostileTo(pet)) nearMembers.push_back(pet); } if (nearMembers.empty()) return NULL; uint32 randTarget = urand(0, nearMembers.size() - 1); return nearMembers [randTarget]; } //only called in Player::SetSeer // so move it to Player? void Unit::AddPlayerToVision(Player* plr) { if (m_sharedVision.empty()) { setActive(true); SetWorldObject(true); } m_sharedVision.push_back(plr); } //only called in Player::SetSeer void Unit::RemovePlayerFromVision(Player* plr) { m_sharedVision.remove(plr); if (m_sharedVision.empty()) { setActive(false); SetWorldObject(false); } } void Unit::RemoveBindSightAuras() { RemoveAurasByType(SPELL_AURA_BIND_SIGHT); } void Unit::RemoveCharmAuras() { RemoveAurasByType(SPELL_AURA_MOD_CHARM); RemoveAurasByType(SPELL_AURA_MOD_POSSESS_PET); RemoveAurasByType(SPELL_AURA_MOD_POSSESS); RemoveAurasByType(SPELL_AURA_AOE_CHARM); } void Unit::UnsummonAllTotems() { for (uint8 i = 0; i < MAX_SUMMON_SLOT; ++i) { if (!m_SummonSlot [i]) continue; if (Creature *OldTotem = GetMap()->GetCreature(m_SummonSlot[i])) if (OldTotem->isSummon()) OldTotem->ToTempSummon()->UnSummon(); } } void Unit::SendHealSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, uint32 OverHeal, uint32 Absorb, bool critical) { // we guess size WorldPacket data(SMSG_SPELLHEALLOG, 8 + 8 + 4 + 4 + 4 + 4 + 1 + 1); data.append(pVictim->GetPackGUID()); data.append(GetPackGUID()); data << uint32(SpellID); data << uint32(Damage); data << uint32(OverHeal); data << uint32(Absorb); // Absorb amount data << uint8(critical ? 1 : 0); data << uint8(0); // unused SendMessageToSet(&data, true); } int32 Unit::HealBySpell(Unit * pVictim, SpellEntry const * spellInfo, uint32 addHealth, bool critical) { uint32 absorb = 0; // calculate heal absorb and reduce healing CalcHealAbsorb(pVictim, spellInfo, addHealth, absorb); int32 gain = DealHeal(pVictim, addHealth); SendHealSpellLog(pVictim, spellInfo->Id, addHealth, uint32(addHealth - gain), absorb, critical); return gain; } void Unit::SendEnergizeSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype) { WorldPacket data(SMSG_SPELLENERGIZELOG, 8 + 8 + 4 + 4 + 4 + 1); data.append(pVictim->GetPackGUID()); data.append(GetPackGUID()); data << uint32(SpellID); data << uint32(powertype); data << uint32(Damage); SendMessageToSet(&data, true); } void Unit::EnergizeBySpell(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype) { SendEnergizeSpellLog(pVictim, SpellID, Damage, powertype); // needs to be called after sending spell log pVictim->ModifyPower(powertype, Damage); } uint32 Unit::SpellDamageBonus(Unit *pVictim, SpellEntry const *spellProto, uint32 effIndex, uint32 pdamage, DamageEffectType damagetype, uint32 stack) { if (!spellProto || !pVictim || damagetype == DIRECT_DAMAGE) return pdamage; // For totems get damage bonus from owner if (GetTypeId() == TYPEID_UNIT && this->ToCreature()->isTotem()) if (Unit *owner = GetOwner()) return owner->SpellDamageBonus( pVictim, spellProto, effIndex, pdamage, damagetype); // Taken/Done total percent damage auras float DoneTotalMod = 1.0f; float ApCoeffMod = 1.0f; int32 DoneTotal = 0; int32 TakenTotal = 0; // ..done // Pet damage if (GetTypeId() == TYPEID_UNIT && !this->ToCreature()->isPet()) DoneTotalMod *= this->ToCreature()->GetSpellDamageMod( this->ToCreature()->GetCreatureInfo()->rank); AuraEffectList const &mModDamagePercentDone = GetAuraEffectsByType( SPELL_AURA_MOD_DAMAGE_PERCENT_DONE); for (AuraEffectList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i) if (((*i)->GetMiscValue() & GetSpellSchoolMask(spellProto)) && (*i)->GetSpellProto()->EquippedItemClass == -1 && // -1 == any item class (not wand) (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0) // 0 == any inventory type (not wand) DoneTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f; uint32 creatureTypeMask = pVictim->GetCreatureTypeMask(); // Add flat bonus from spell damage versus DoneTotal += GetTotalAuraModifierByMiscMask( SPELL_AURA_MOD_FLAT_SPELL_DAMAGE_VERSUS, creatureTypeMask); AuraEffectList const &mDamageDoneVersus = GetAuraEffectsByType( SPELL_AURA_MOD_DAMAGE_DONE_VERSUS); for (AuraEffectList::const_iterator i = mDamageDoneVersus.begin(); i != mDamageDoneVersus.end(); ++i) if (creatureTypeMask & uint32((*i)->GetMiscValue())) DoneTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f; // bonus against aurastate AuraEffectList const &mDamageDoneVersusAurastate = GetAuraEffectsByType( SPELL_AURA_MOD_DAMAGE_DONE_VERSUS_AURASTATE); for (AuraEffectList::const_iterator i = mDamageDoneVersusAurastate.begin(); i != mDamageDoneVersusAurastate.end(); ++i) if (pVictim->HasAuraState(AuraState((*i)->GetMiscValue()))) DoneTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f; // done scripted mod (take it from owner) Unit * owner = GetOwner() ? GetOwner() : this; AuraEffectList const &mOverrideClassScript = owner->GetAuraEffectsByType( SPELL_AURA_OVERRIDE_CLASS_SCRIPTS); for (AuraEffectList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i) { if (!(*i)->IsAffectedOnSpell(spellProto)) continue; switch ((*i)->GetMiscValue()) { case 4920: // Molten Fury case 4919: case 6917: // Death's Embrace case 6926: case 6928: { if (pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, spellProto, this)) DoneTotalMod *= (100.0f + (*i)->GetAmount()) / 100.0f; break; } // Soul Siphon case 4992: case 4993: { // effect 1 m_amount int32 maxPercent = (*i)->GetAmount(); // effect 0 m_amount int32 stepPercent = CalculateSpellDamage(this, (*i)->GetSpellProto(), 0); // count affliction effects and calc additional damage in percentage int32 modPercent = 0; AuraApplicationMap const &victimAuras = pVictim->GetAppliedAuras(); for (AuraApplicationMap::const_iterator itr = victimAuras.begin(); itr != victimAuras.end(); ++itr) { Aura const * aura = itr->second->GetBase(); SpellEntry const *m_spell = aura->GetSpellProto(); if (m_spell->SpellFamilyName != SPELLFAMILY_WARLOCK || !(m_spell->SpellFamilyFlags [1] & 0x0004071B || m_spell->SpellFamilyFlags [0] & 0x8044C402)) continue; modPercent += stepPercent * aura->GetStackAmount(); if (modPercent >= maxPercent) { modPercent = maxPercent; break; } } DoneTotalMod *= (modPercent + 100.0f) / 100.0f; break; } case 6916: // Death's Embrace case 6925: case 6927: if (HasAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, spellProto, this)) DoneTotalMod *= (100.0f + (*i)->GetAmount()) / 100.0f; break; case 5481: // Starfire Bonus { if (pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x200002, 0, 0)) DoneTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f; break; } case 4418: // Increased Shock Damage case 4554: // Increased Lightning Damage case 4555: // Improved Moonfire case 5142: // Increased Lightning Damage case 5147: // Improved Consecration / Libram of Resurgence case 5148: // Idol of the Shooting Star case 6008: // Increased Lightning Damage case 8627: // Totem of Hex { DoneTotal += (*i)->GetAmount(); break; } // Tundra Stalker // Merciless Combat case 7277: { // Merciless Combat if ((*i)->GetSpellProto()->SpellIconID == 2656) { if (!pVictim->HealthAbovePct(35)) DoneTotalMod *= (100.0f + (*i)->GetAmount()) / 100.0f; } // Tundra Stalker else { // Frost Fever (target debuff) if (pVictim->HasAura(55095)) DoneTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f; break; } break; } // Rage of Rivendare case 7293: { if (pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, 0, 0x02000000, 0)) { if (SpellChainNode const *chain = sSpellMgr->GetSpellChainNode((*i)->GetId())) DoneTotalMod *= (chain->rank * 2.0f + 100.0f) / 100.0f; } break; } // Twisted Faith case 7377: { if (pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, 0x8000, 0, 0, GetGUID())) DoneTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f; break; } } } // Custom scripted damage switch (spellProto->SpellFamilyName) { case SPELLFAMILY_MAGE: // Ice Lance if (spellProto->SpellIconID == 186) { if (pVictim->HasAuraState(AURA_STATE_FROZEN, spellProto, this)) { // Glyph of Ice Lance if (owner->HasAura(56377) && pVictim->getLevel() > owner->getLevel()) DoneTotalMod *= 1.05f; // Damages doubled against frozen targets. DoneTotalMod *= 2.0f; } } // Torment the weak if (spellProto->SpellFamilyFlags [0] & 0x20200021 || spellProto->SpellFamilyFlags [1] & 0x9000) if (pVictim->HasAuraType( SPELL_AURA_MOD_DECREASE_SPEED)) { AuraEffectList const& mDumyAuras = GetAuraEffectsByType( SPELL_AURA_DUMMY); for (AuraEffectList::const_iterator i = mDumyAuras.begin(); i != mDumyAuras.end(); ++i) if ((*i)->GetSpellProto()->SpellIconID == 3263) { DoneTotalMod *= float((*i)->GetAmount() + 100.f) / 100.f; break; } } break; case SPELLFAMILY_PRIEST: // Mind Flay if (spellProto->SpellFamilyFlags [0] & 0x800000) { // Glyph of Shadow Word: Pain if (AuraEffect * aurEff = GetAuraEffect(55687, 0)) // Increase Mind Flay damage if Shadow Word: Pain present on target if (pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, 0x8000, 0, 0, GetGUID())) DoneTotalMod *= (aurEff->GetAmount() + 100.0f) / 100.f; // Twisted Faith - Mind Flay part if (AuraEffect * aurEff = GetAuraEffect(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS, SPELLFAMILY_PRIEST, 2848, 1)) // Increase Mind Flay damage if Shadow Word: Pain present on target if (pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, 0x8000, 0, 0, GetGUID())) DoneTotalMod *= (aurEff->GetAmount() + 100.0f) / 100.f; } // Smite else if (spellProto->SpellFamilyFlags [0] & 0x80) { // Glyph of Smite if (AuraEffect * aurEff = GetAuraEffect(55692, 0)) if (pVictim->GetAuraEffect( SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, 0x100000, 0, 0, GetGUID())) AddPctN(DoneTotalMod, aurEff->GetAmount()); } break; case SPELLFAMILY_PALADIN: // Judgement of Vengeance/Judgement of Corruption if ((spellProto->SpellFamilyFlags [1] & 0x400000) && spellProto->SpellIconID == 2292) { // Get stack of Holy Vengeance/Blood Corruption on the target added by caster uint32 stacks = 0; Unit::AuraEffectList const& auras = pVictim->GetAuraEffectsByType( SPELL_AURA_PERIODIC_DAMAGE); for (Unit::AuraEffectList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr) if (((*itr)->GetId() == 31803 || (*itr)->GetId() == 53742) && (*itr)->GetCasterGUID() == GetGUID()) { stacks = (*itr)->GetBase()->GetStackAmount(); break; } // + 10% for each application of Holy Vengeance/Blood Corruption on the target if (stacks) DoneTotalMod *= (10.0f + float(stacks)) / 10.0f; } break; case SPELLFAMILY_WARLOCK: //Fire and Brimstone if (spellProto->SpellFamilyFlags [1] & 0x00020040) if (pVictim->HasAuraState( AURA_STATE_CONFLAGRATE)) { AuraEffectList const& mDumyAuras = GetAuraEffectsByType( SPELL_AURA_DUMMY); for (AuraEffectList::const_iterator i = mDumyAuras.begin(); i != mDumyAuras.end(); ++i) if ((*i)->GetSpellProto()->SpellIconID == 3173) { DoneTotalMod *= float((*i)->GetAmount() + 100.f) / 100.f; break; } } // Drain Soul - increased damage for targets under 25 % HP if (spellProto->SpellFamilyFlags [0] & 0x00004000) if (HasAura( 200000)) DoneTotalMod *= 2; // Shadow Bite (15% increase from each dot) if (spellProto->SpellFamilyFlags [1] & 0x00400000 && isPet() && GetOwner()) if (uint8 count = pVictim->GetDoTsByCaster(GetOwnerGUID())) AddPctN( DoneTotalMod, 15 * count); break; case SPELLFAMILY_HUNTER: // Steady Shot if (spellProto->SpellFamilyFlags [1] & 0x1) if (AuraEffect * aurEff = GetAuraEffect(56826, 0)) // Glyph of Steady Shot if (pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_HUNTER, 0x00004000, 0, 0, GetGUID())) AddPctN( DoneTotalMod, aurEff->GetAmount()); break; case SPELLFAMILY_DEATHKNIGHT: // Improved Icy Touch if (spellProto->SpellFamilyFlags [0] & 0x2) if (AuraEffect * aurEff = GetDummyAuraEffect(SPELLFAMILY_DEATHKNIGHT, 2721, 0)) DoneTotalMod *= (100.0f + aurEff->GetAmount()) / 100.0f; // Sigil of the Vengeful Heart if (spellProto->SpellFamilyFlags [0] & 0x2000) if (AuraEffect* aurEff = GetAuraEffect(64962, EFFECT_1)) AddPctN( DoneTotal, aurEff->GetAmount()); // Glacier Rot if (spellProto->SpellFamilyFlags [0] & 0x2 || spellProto->SpellFamilyFlags [1] & 0x6) if (AuraEffect * aurEff = GetDummyAuraEffect(SPELLFAMILY_DEATHKNIGHT, 196, 0)) if (pVictim->GetDiseasesByCaster( owner->GetGUID()) > 0) DoneTotalMod *= (100.0f + aurEff->GetAmount()) / 100.0f; // Rune Strike if (spellProto->SpellFamilyFlags [1] & 0x20000000) { float ApCoeffMod = 1.0f; // Impurity (dummy effect) if (GetTypeId() == TYPEID_PLAYER) { PlayerSpellMap playerSpells = this->ToPlayer()->GetSpellMap(); for (PlayerSpellMap::const_iterator itr = playerSpells.begin(); itr != playerSpells.end(); ++itr) { if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled) continue; switch (itr->first) { case 49220: case 49633: case 49635: case 49636: case 49638: { if (const SpellEntry *proto=sSpellStore.LookupEntry(itr->first)) AddPctN( ApCoeffMod, SpellMgr::CalculateSpellEffectAmount( proto, 0)); } break; } } } DoneTotalMod += GetTotalAttackPowerValue(BASE_ATTACK) * 0.2 * ApCoeffMod; } // Impurity (dummy effect) if (GetTypeId() == TYPEID_PLAYER) { PlayerSpellMap playerSpells = this->ToPlayer()->GetSpellMap(); for (PlayerSpellMap::const_iterator itr = playerSpells.begin(); itr != playerSpells.end(); ++itr) { if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled) continue; switch (itr->first) { case 49220: case 49633: case 49635: case 49636: case 49638: { if (const SpellEntry *proto=sSpellStore.LookupEntry(itr->first)) ApCoeffMod *= (100.0f + SpellMgr::CalculateSpellEffectAmount( proto, 0)) / 100.0f; } break; } } } break; } if (damagetype == SPELL_DIRECT_DAMAGE && spellProto->powerType == POWER_RAGE && HasAuraType(SPELL_AURA_MASTERY) && GetTypeId() == TYPEID_PLAYER && ToPlayer()->GetTalentBranchSpec(ToPlayer()->GetActiveSpec()) == BS_WARRIOR_FURY) DoneTotalMod *= float( 1.0f + (0.45f + (ToPlayer()->GetMasteryPoints() * 0.056f))); // ..taken int32 maxPositiveMod = 0; // max of the positive amount aura (that increase the damage taken) int32 sumNegativeMod = 0; // sum the negative amount aura (that reduce the damage taken) AuraEffectList const& mModDamagePercentTaken = pVictim->GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN); for (AuraEffectList::const_iterator i = mModDamagePercentTaken.begin(); i != mModDamagePercentTaken.end(); ++i) if ((*i)->GetMiscValue() & GetSpellSchoolMask(spellProto)) { if ((*i)->GetAmount() > 0) { if ((*i)->GetAmount() > maxPositiveMod) maxPositiveMod = (*i)->GetAmount(); } else sumNegativeMod += (*i)->GetAmount(); } // .. taken pct: dummy auras AuraEffectList const& mDummyAuras = pVictim->GetAuraEffectsByType( SPELL_AURA_DUMMY); for (AuraEffectList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i) { switch ((*i)->GetSpellProto()->SpellIconID) { // Cheat Death case 2109: if ((*i)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL) { // needs rework 4.0.6 /*if (pVictim->GetTypeId() != TYPEID_PLAYER) continue; float mod = pVictim->ToPlayer()->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*(-8.0f); if (mod < (*i)->GetAmount()) mod = (float)(*i)->GetAmount(); sumNegativeMod += int32(mod);*/ } break; // Ebon Plague case 1933: if ((*i)->GetMiscValue() & (spellProto ? GetSpellSchoolMask(spellProto) : 0)) { if ((*i)->GetAmount() > maxPositiveMod) maxPositiveMod = (*i)->GetAmount(); } break; } } // From caster spells AuraEffectList const& mOwnerTaken = pVictim->GetAuraEffectsByType( SPELL_AURA_MOD_DAMAGE_FROM_CASTER); for (AuraEffectList::const_iterator i = mOwnerTaken.begin(); i != mOwnerTaken.end(); ++i) if ((*i)->GetCasterGUID() == GetGUID() && (*i)->IsAffectedOnSpell(spellProto)) sumNegativeMod += (*i)->GetAmount(); // Mod damage from spell mechanic if (uint32 mechanicMask = GetAllSpellMechanicMask(spellProto)) { AuraEffectList const& mDamageDoneMechanic = pVictim->GetAuraEffectsByType( SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT); for (AuraEffectList::const_iterator i = mDamageDoneMechanic.begin(); i != mDamageDoneMechanic.end(); ++i) if (mechanicMask & uint32(1 << ((*i)->GetMiscValue()))) sumNegativeMod += (*i)->GetAmount(); } float TakenTotalMod = (sumNegativeMod + maxPositiveMod + 100.0f) / 100.0f; // Taken/Done fixed damage bonus auras int32 DoneAdvertisedBenefit = SpellBaseDamageBonus( GetSpellSchoolMask(spellProto)); int32 TakenAdvertisedBenefit = SpellBaseDamageBonusForVictim( GetSpellSchoolMask(spellProto), pVictim); // Pets just add their bonus damage to their spell damage // note that their spell damage is just gain of their own auras if (HasUnitTypeMask(UNIT_MASK_GUARDIAN)) if (!(GetSpellSchoolMask( spellProto) & SPELL_SCHOOL_MASK_NORMAL)) // Do not add Spellpower to melee abilities DoneAdvertisedBenefit += ((Guardian*) this)->GetBonusDamage(); else if (((Guardian*) this)->GetBonusDamage()) // Instead add a fixed amount of AP DoneAdvertisedBenefit += GetTotalAttackPowerValue(BASE_ATTACK) * 0.2f; // Check for table values float coeff = 0; SpellBonusEntry const *bonus = sSpellMgr->GetSpellBonusData(spellProto->Id); if (bonus) { if (damagetype == DOT) { coeff = bonus->dot_damage; if (bonus->ap_dot_bonus > 0) { WeaponAttackType attType = (IsRangedWeaponSpell(spellProto) && spellProto->DmgClass != SPELL_DAMAGE_CLASS_MELEE) ? RANGED_ATTACK : BASE_ATTACK; float APbonus = attType == BASE_ATTACK ? pVictim->GetTotalAuraModifier( SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS) : pVictim->GetTotalAuraModifier( SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS); APbonus += GetTotalAttackPowerValue(attType); DoneTotal += int32( bonus->ap_dot_bonus * stack * ApCoeffMod * APbonus); } } else { coeff = bonus->direct_damage; if (bonus->ap_bonus > 0) { WeaponAttackType attType = (IsRangedWeaponSpell(spellProto) && spellProto->DmgClass != SPELL_DAMAGE_CLASS_MELEE) ? RANGED_ATTACK : BASE_ATTACK; float APbonus = attType == BASE_ATTACK ? pVictim->GetTotalAuraModifier( SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS) : pVictim->GetTotalAuraModifier( SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS); APbonus += GetTotalAttackPowerValue(attType); DoneTotal += int32( bonus->ap_bonus * stack * ApCoeffMod * APbonus); } } } // Default calculation if (DoneAdvertisedBenefit || TakenAdvertisedBenefit) { if (coeff <= 0) { if (effIndex < 4) { coeff = spellProto->EffectBonusCoefficient [effIndex]; } else { // should never happen coeff = 0; } } // Formula based SP coefficient calculation is disabled cause all coeffs should be present in the DBC // A few custom cases go into spell_bonus_data table /*if (!bonus || coeff < 0) { // Damage Done from spell damage bonus int32 CastingTime = IsChanneledSpell(spellProto) ? GetSpellDuration(spellProto) : GetSpellCastTime(spellProto); // Damage over Time spells bonus calculation float DotFactor = 1.0f; if (damagetype == DOT) { int32 DotDuration = GetSpellDuration(spellProto); // 200% limit if (DotDuration > 0) { if (DotDuration > 30000) DotDuration = 30000; if (!IsChanneledSpell(spellProto)) DotFactor = DotDuration / 15000.0f; uint8 x = 0; for (uint8 j = 0; j < MAX_SPELL_EFFECTS; ++j) { if (spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && ( spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_DAMAGE || spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH)) { x = j; break; } } int32 DotTicks = 6; if (spellProto->EffectAmplitude[x] != 0) DotTicks = DotDuration / spellProto->EffectAmplitude[x]; if (DotTicks) { DoneAdvertisedBenefit /= DotTicks; TakenAdvertisedBenefit /= DotTicks; } } } // Distribute Damage over multiple effects, reduce by AoE CastingTime = GetCastingTimeForBonus(spellProto, damagetype, CastingTime); // 50% for damage and healing spells for leech spells from damage bonus and 0% from healing for (uint8 j = 0; j < MAX_SPELL_EFFECTS; ++j) { if (spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH || (spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH)) { CastingTime /= 2; break; } } if (spellProto->SchoolMask != SPELL_SCHOOL_MASK_NORMAL) coeff = (CastingTime / 3500.0f) * DotFactor; else coeff = DotFactor; }*/ float coeff2 = CalculateLevelPenalty(spellProto) * stack; if (spellProto->SpellFamilyName) //TODO: fix this TakenTotal += int32(TakenAdvertisedBenefit * coeff * coeff2); if (Player* modOwner = GetSpellModOwner()) { coeff *= 100.0f; modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_BONUS_MULTIPLIER, coeff); coeff /= 100.0f; // DoneAdvertisedBenefit should be modified by owner auras if (isPet()) modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_ALL_EFFECTS, DoneAdvertisedBenefit); } DoneTotal += int32(DoneAdvertisedBenefit * coeff * coeff2); } // Some spells don't benefit from done mods if (spellProto->AttributesEx3 & SPELL_ATTR3_NO_DONE_BONUS) { DoneTotal = 0; DoneTotalMod = 1.0f; } float tmpDamage = (int32(pdamage) + DoneTotal) * DoneTotalMod; // apply spellmod to Done damage (flat and pct) if (Player* modOwner = GetSpellModOwner()) modOwner->ApplySpellMod( spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, tmpDamage); tmpDamage = (tmpDamage + TakenTotal) * TakenTotalMod; return uint32(std::max(tmpDamage, 0.0f)); } int32 Unit::SpellBaseDamageBonus(SpellSchoolMask schoolMask) { int32 DoneAdvertisedBenefit = 0; // ..done AuraEffectList const& mDamageDone = GetAuraEffectsByType( SPELL_AURA_MOD_DAMAGE_DONE); for (AuraEffectList::const_iterator i = mDamageDone.begin(); i != mDamageDone.end(); ++i) if (((*i)->GetMiscValue() & schoolMask) != 0 && (*i)->GetSpellProto()->EquippedItemClass == -1 && // -1 == any item class (not wand then) (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0) // 0 == any inventory type (not wand then) DoneAdvertisedBenefit += (*i)->GetAmount(); if (GetTypeId() == TYPEID_PLAYER) { // Base value DoneAdvertisedBenefit += this->ToPlayer()->GetBaseSpellPowerBonus(); // Damage bonus from stats AuraEffectList const& mDamageDoneOfStatPercent = GetAuraEffectsByType( SPELL_AURA_MOD_SPELL_DAMAGE_OF_STAT_PERCENT); for (AuraEffectList::const_iterator i = mDamageDoneOfStatPercent.begin(); i != mDamageDoneOfStatPercent.end(); ++i) { if ((*i)->GetMiscValue() & schoolMask) { // stat used stored in miscValueB for this aura Stats usedStat = Stats((*i)->GetMiscValueB()); DoneAdvertisedBenefit += int32( GetStat(usedStat) * (*i)->GetAmount() / 100.0f); } } // ... and attack power AuraEffectList const& mDamageDonebyAP = GetAuraEffectsByType( SPELL_AURA_MOD_SPELL_DAMAGE_OF_ATTACK_POWER); for (AuraEffectList::const_iterator i = mDamageDonebyAP.begin(); i != mDamageDonebyAP.end(); ++i) if ((*i)->GetMiscValue() & schoolMask) DoneAdvertisedBenefit += int32( GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetAmount() / 100.0f); // TODO this should modify PLAYER_FIELD_MOD_SPELL_POWER_PCT instead of all the separate power fields int32 spModPct = GetMaxPositiveAuraModifier( SPELL_AURA_MOD_SPELL_POWER_PCT); // should it apply to non players as well? DoneAdvertisedBenefit += DoneAdvertisedBenefit * spModPct / 100; } return DoneAdvertisedBenefit > 0 ? DoneAdvertisedBenefit : 0; } int32 Unit::SpellBaseDamageBonusForVictim(SpellSchoolMask schoolMask, Unit *pVictim) { uint32 creatureTypeMask = pVictim->GetCreatureTypeMask(); int32 TakenAdvertisedBenefit = 0; // ..done (for creature type by mask) in taken AuraEffectList const& mDamageDoneCreature = GetAuraEffectsByType( SPELL_AURA_MOD_DAMAGE_DONE_CREATURE); for (AuraEffectList::const_iterator i = mDamageDoneCreature.begin(); i != mDamageDoneCreature.end(); ++i) if (creatureTypeMask & uint32((*i)->GetMiscValue())) TakenAdvertisedBenefit += (*i)->GetAmount(); // ..taken AuraEffectList const& mDamageTaken = pVictim->GetAuraEffectsByType( SPELL_AURA_MOD_DAMAGE_TAKEN); for (AuraEffectList::const_iterator i = mDamageTaken.begin(); i != mDamageTaken.end(); ++i) if (((*i)->GetMiscValue() & schoolMask) != 0) TakenAdvertisedBenefit += (*i)->GetAmount(); return TakenAdvertisedBenefit > 0 ? TakenAdvertisedBenefit : 0; } bool Unit::isSpellCrit(Unit *pVictim, SpellEntry const *spellProto, SpellSchoolMask schoolMask, WeaponAttackType attackType) const { // Mobs can't crit with spells. if (IS_CREATURE_GUID(GetGUID())) if (!((m_unitTypeMask & (UNIT_MASK_SUMMON | UNIT_MASK_MINION | UNIT_MASK_GUARDIAN | UNIT_MASK_TOTEM | UNIT_MASK_PET | UNIT_MASK_HUNTER_PET)) && IS_PLAYER_GUID(GetOwnerGUID()))) return false; // not critting spell if ((spellProto->AttributesEx2 & SPELL_ATTR2_CANT_CRIT)) return false; float crit_chance = 0.0f; switch (spellProto->DmgClass) { case SPELL_DAMAGE_CLASS_NONE: // We need more spells to find a general way (if there is any) switch (spellProto->Id) { case 379: // Earth Shield case 33778: // Lifebloom Final Bloom case 64844: // Divine Hymn break; default: return false; } case SPELL_DAMAGE_CLASS_MAGIC: { if (schoolMask & SPELL_SCHOOL_MASK_NORMAL) crit_chance = 0.0f; // For other schools else if (GetTypeId() == TYPEID_PLAYER) crit_chance = GetFloatValue( PLAYER_SPELL_CRIT_PERCENTAGE1 + GetFirstSchoolInMask(schoolMask)); else { crit_chance = (float) m_baseSpellCritChance; crit_chance += GetTotalAuraModifierByMiscMask( SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask); } // taken if (pVictim) { if (!IsPositiveSpell(spellProto->Id)) { // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE crit_chance += pVictim->GetTotalAuraModifierByMiscMask( SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE, schoolMask); // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE crit_chance += pVictim->GetTotalAuraModifier( SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE); } // scripted (increase crit chance ... against ... target by x% AuraEffectList const& mOverrideClassScript = GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS); for (AuraEffectList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i) { if (!((*i)->IsAffectedOnSpell(spellProto))) continue; int32 modChance = 0; switch ((*i)->GetMiscValue()) { // Shatter case 911: modChance += 16; case 910: modChance += 17; case 849: modChance += 17; if (!pVictim->HasAuraState(AURA_STATE_FROZEN, spellProto, this)) break; crit_chance += modChance; break; case 7917: // Glyph of Shadowburn if (pVictim->HasAuraState( AURA_STATE_HEALTHLESS_35_PERCENT, spellProto, this)) crit_chance += (*i)->GetAmount(); break; case 7997: // Renewed Hope case 7998: if (pVictim->HasAura(6788)) crit_chance += (*i)->GetAmount(); break; case 21: // Test of Faith case 6935: case 6918: if (pVictim->HealthBelowPct(50)) crit_chance += (*i)->GetAmount(); break; default: break; } } // Custom crit by class switch (spellProto->SpellFamilyName) { case SPELLFAMILY_MAGE: // Glyph of Fire Blast if ((spellProto->SpellFamilyFlags[0] & 0x2) == 0x2 && spellProto->SpellIconID == 12) if (pVictim->HasAuraWithMechanic((1<<MECHANIC_STUN) | (1<<MECHANIC_KNOCKOUT))) if (AuraEffect const* aurEff = GetAuraEffect(56369, EFFECT_0)) crit_chance += aurEff->GetAmount(); break; case SPELLFAMILY_DRUID: // Improved Faerie Fire if (pVictim->HasAuraState(AURA_STATE_FAERIE_FIRE)) if (AuraEffect const * aurEff = GetDummyAuraEffect(SPELLFAMILY_DRUID, 109, 0)) crit_chance += aurEff->GetAmount(); // cumulative effect - don't break // Starfire if (spellProto->SpellFamilyFlags [0] & 0x4 && spellProto->SpellIconID == 1485) { // Improved Insect Swarm if (AuraEffect const * aurEff = GetDummyAuraEffect(SPELLFAMILY_DRUID, 1771, 0)) if (pVictim->GetAuraEffect( SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x00000002, 0, 0)) crit_chance += aurEff->GetAmount(); break; } break; case SPELLFAMILY_ROGUE: // Shiv-applied poisons can't crit if (FindCurrentSpellBySpellId(5938)) crit_chance = 0.0f; break; case SPELLFAMILY_PALADIN: // Exorcism if (spellProto->Category == 19) { if (pVictim->GetCreatureTypeMask() & CREATURE_TYPEMASK_DEMON_OR_UNDEAD) return true; break; } break; case SPELLFAMILY_SHAMAN: // Lava Burst if (spellProto->SpellFamilyFlags [1] & 0x00001000) { if (pVictim->GetAuraEffect( SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_SHAMAN, 0x10000000, 0, 0, GetGUID())) if (pVictim->GetTotalAuraModifier( SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE) > -100) return true; break; } break; } } break; } case SPELL_DAMAGE_CLASS_MELEE: if (pVictim) { // Custom crit by class switch (spellProto->SpellFamilyName) { case SPELLFAMILY_DRUID: // Rend and Tear - bonus crit chance for Ferocious Bite on bleeding targets if (spellProto->SpellFamilyFlags [0] & 0x00800000 && spellProto->SpellIconID == 1680 && pVictim->HasAuraState(AURA_STATE_BLEEDING)) { if (AuraEffect const *rendAndTear = GetDummyAuraEffect(SPELLFAMILY_DRUID, 2859, 1)) crit_chance += rendAndTear->GetAmount(); break; } break; case SPELLFAMILY_PALADIN: // Judgement of Command proc always crits on stunned target if (spellProto->SpellFamilyName == SPELLFAMILY_PALADIN) if (spellProto->SpellFamilyFlags [0] & 0x0000000000800000LL && spellProto->SpellIconID == 561) if (pVictim->HasUnitState( UNIT_STAT_STUNNED)) return true; } } case SPELL_DAMAGE_CLASS_RANGED: { if (pVictim) { crit_chance += GetUnitCriticalChance(attackType, pVictim); crit_chance += GetTotalAuraModifierByMiscMask( SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask); } break; } default: return false; } // percent done // only players use intelligence for critical chance computations if (Player* modOwner = GetSpellModOwner()) modOwner->ApplySpellMod( spellProto->Id, SPELLMOD_CRITICAL_CHANCE, crit_chance); crit_chance = crit_chance > 0.0f ? crit_chance : 0.0f; if (roll_chance_f(crit_chance)) return true; return false; } uint32 Unit::SpellCriticalDamageBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim) { // Calculate critical bonus int32 crit_bonus; Player* modOwner = GetSpellModOwner(); switch (spellProto->DmgClass) { case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100% case SPELL_DAMAGE_CLASS_RANGED: // TODO: write here full calculation for melee/ranged spells crit_bonus = damage; break; default: if (modOwner && (modOwner->getClass() == CLASS_MAGE || modOwner->getClass() == CLASS_WARLOCK)) { crit_bonus = damage; // 100% bonus for Mages and Warlocks in Cataclysm } else { crit_bonus = damage / 2; // for spells is 50% } break; } // adds additional damage to crit_bonus (from talents) if (modOwner) modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus); if (pVictim) { uint32 creatureTypeMask = pVictim->GetCreatureTypeMask(); crit_bonus = int32( crit_bonus * GetTotalAuraMultiplierByMiscMask( SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask)); } if (crit_bonus > 0) damage += crit_bonus; return damage; } uint32 Unit::SpellCriticalHealingBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim) { // Calculate critical bonus int32 crit_bonus; switch (spellProto->DmgClass) { case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100% case SPELL_DAMAGE_CLASS_RANGED: // TODO: write here full calculation for melee/ranged spells crit_bonus = damage; break; default: crit_bonus = damage / 2; // for spells is 50% break; } if (pVictim) { uint32 creatureTypeMask = pVictim->GetCreatureTypeMask(); crit_bonus = int32( crit_bonus * GetTotalAuraMultiplierByMiscMask( SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask)); } if (crit_bonus > 0) damage += crit_bonus; damage = int32( float(damage) * GetTotalAuraMultiplier( SPELL_AURA_MOD_CRITICAL_HEALING_AMOUNT)); return damage; } uint32 Unit::SpellHealingBonus(Unit *pVictim, SpellEntry const *spellProto, uint32 effIndex, uint32 healamount, DamageEffectType damagetype, uint32 stack) { // For totems get healing bonus from owner (statue isn't totem in fact) if (GetTypeId() == TYPEID_UNIT && this->ToCreature()->isTotem()) if (Unit* owner = GetOwner()) return owner->SpellHealingBonus( pVictim, spellProto, effIndex, healamount, damagetype, stack); // no bonus for heal potions/bandages if (spellProto->SpellFamilyName == SPELLFAMILY_POTION) return healamount; // and Warlock's Healthstones if (spellProto->SpellFamilyName == SPELLFAMILY_WARLOCK && (spellProto->SpellFamilyFlags [0] & 0x10000)) { healamount = 0.45 * (GetMaxHealth() - 10 * (STAT_STAMINA - 180)); return healamount; } // Healing Done // Taken/Done total percent damage auras float DoneTotalMod = 1.0f; float TakenTotalMod = 1.0f; int32 DoneTotal = 0; int32 TakenTotal = 0; // Healing done percent AuraEffectList const& mHealingDonePct = GetAuraEffectsByType( SPELL_AURA_MOD_HEALING_DONE_PERCENT); for (AuraEffectList::const_iterator i = mHealingDonePct.begin(); i != mHealingDonePct.end(); ++i) DoneTotalMod *= (100.0f + (*i)->GetAmount()) / 100.0f; // done scripted mod (take it from owner) Unit *owner = GetOwner() ? GetOwner() : this; AuraEffectList const &mOverrideClassScript = owner->GetAuraEffectsByType( SPELL_AURA_OVERRIDE_CLASS_SCRIPTS); for (AuraEffectList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i) { if (!(*i)->IsAffectedOnSpell(spellProto)) continue; switch ((*i)->GetMiscValue()) { case 4415: // Increased Rejuvenation Healing case 4953: case 3736: // Hateful Totem of the Third Wind / Increased Lesser Healing Wave / LK Arena (4/5/6) Totem of the Third Wind / Savage Totem of the Third Wind DoneTotal += (*i)->GetAmount(); break; case 7997: // Renewed Hope case 7998: if (pVictim->HasAura(6788)) DoneTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f; break; case 21: // Test of Faith case 6935: case 6918: if (pVictim->HealthBelowPct(50)) DoneTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f; break; case 7798: // Glyph of Regrowth { if (pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_HEAL, SPELLFAMILY_DRUID, 0x40, 0, 0)) DoneTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f; break; } case 8477: // Nourish Heal Boost { int32 stepPercent = (*i)->GetAmount(); int32 modPercent = 0; AuraApplicationMap const& victimAuras = pVictim->GetAppliedAuras(); for (AuraApplicationMap::const_iterator itr = victimAuras.begin(); itr != victimAuras.end(); ++itr) { Aura const * aura = itr->second->GetBase(); if (aura->GetCasterGUID() != GetGUID()) continue; SpellEntry const* m_spell = aura->GetSpellProto(); if (m_spell->SpellFamilyName != SPELLFAMILY_DRUID || !(m_spell->SpellFamilyFlags [1] & 0x00000010 || m_spell->SpellFamilyFlags [0] & 0x50)) continue; modPercent += stepPercent * aura->GetStackAmount(); } DoneTotalMod *= (modPercent + 100.0f) / 100.0f; break; } case 7871: // Glyph of Lesser Healing Wave { if (pVictim->GetAuraEffect(SPELL_AURA_DUMMY, SPELLFAMILY_SHAMAN, 0, 0x00000400, 0, GetGUID())) DoneTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f; break; } default: break; } } // Taken/Done fixed damage bonus auras int32 DoneAdvertisedBenefit = SpellBaseHealingBonus( GetSpellSchoolMask(spellProto)); int32 TakenAdvertisedBenefit = SpellBaseHealingBonusForVictim( GetSpellSchoolMask(spellProto), pVictim); // ignored now cause DBC should have the right info for nearly all effects // delte if all goes well bool scripted = false; for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { switch (spellProto->EffectApplyAuraName [i]) { // These auras do not use healing coeff case SPELL_AURA_PERIODIC_LEECH: case SPELL_AURA_PERIODIC_HEALTH_FUNNEL: scripted = true; break; } } // Check for table values SpellBonusEntry const* bonus = !scripted ? sSpellMgr->GetSpellBonusData(spellProto->Id) : NULL; float coeff = 0; float factorMod = 1.0f; if (bonus) { if (damagetype == DOT) { coeff = bonus->dot_damage; if (bonus->ap_dot_bonus > 0) DoneTotal += int32( bonus->ap_dot_bonus * stack * GetTotalAttackPowerValue( (IsRangedWeaponSpell(spellProto) && spellProto->DmgClass != SPELL_DAMAGE_CLASS_MELEE) ? RANGED_ATTACK : BASE_ATTACK)); } else { coeff = bonus->direct_damage; if (bonus->ap_bonus > 0) DoneTotal += int32( bonus->ap_bonus * stack * GetTotalAttackPowerValue( (IsRangedWeaponSpell(spellProto) && spellProto->DmgClass != SPELL_DAMAGE_CLASS_MELEE) ? RANGED_ATTACK : BASE_ATTACK)); } } else // scripted bonus { // Gift of the Naaru if (spellProto->SpellFamilyFlags [2] & 0x80000000 && spellProto->SpellIconID == 329) { scripted = true; int32 apBonus = int32( std::max(GetTotalAttackPowerValue(BASE_ATTACK), GetTotalAttackPowerValue(RANGED_ATTACK))); if (apBonus > DoneAdvertisedBenefit) DoneTotal += int32( apBonus * 0.22f); // 22% of AP per tick else DoneTotal += int32(DoneAdvertisedBenefit * 0.377f); //37.7% of BH per tick } // Earthliving - 0.45% of normal hot coeff else if (spellProto->SpellFamilyName == SPELLFAMILY_SHAMAN && spellProto->SpellFamilyFlags [1] & 0x80000) factorMod *= 0.45f; // Already set to scripted? so not uses healing bonus coefficient // No heal coeff for SPELL_DAMAGE_CLASS_NONE class spells by default else if (scripted || spellProto->DmgClass == SPELL_DAMAGE_CLASS_NONE) { scripted = true; coeff = 0.0f; } } // Default calculation if (DoneAdvertisedBenefit || TakenAdvertisedBenefit) { if (coeff <= 0) { if (effIndex < 4) { coeff = spellProto->EffectBonusCoefficient [effIndex]; } else { // should never happen coeff = 0; } } // Formula based SP coefficient calculation is disabled cause all coeffs should be present in the DBC // A few custom cases go into spell_bonus_data table /*if ((!bonus && !scripted) || coeff < 0) { // Damage Done from spell damage bonus int32 CastingTime = !IsChanneledSpell(spellProto) ? GetSpellCastTime(spellProto) : GetSpellDuration(spellProto); // Damage over Time spells bonus calculation float DotFactor = 1.0f; if (damagetype == DOT) { int32 DotDuration = GetSpellDuration(spellProto); // 200% limit if (DotDuration > 0) { if (DotDuration > 30000) DotDuration = 30000; if (!IsChanneledSpell(spellProto)) DotFactor = DotDuration / 15000.0f; uint32 x = 0; for (uint8 j = 0; j < MAX_SPELL_EFFECTS; j++) { if (spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && ( spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_DAMAGE || spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH)) { x = j; break; } } int32 DotTicks = 6; if (spellProto->EffectAmplitude[x] != 0) DotTicks = DotDuration / spellProto->EffectAmplitude[x]; if (DotTicks) { DoneAdvertisedBenefit = DoneAdvertisedBenefit * int32(stack) / DotTicks; TakenAdvertisedBenefit = TakenAdvertisedBenefit * int32(stack) / DotTicks; } } } // Distribute Damage over multiple effects, reduce by AoE CastingTime = GetCastingTimeForBonus(spellProto, damagetype, CastingTime); // 50% for damage and healing spells for leech spells from damage bonus and 0% from healing for (uint8 j = 0; j < MAX_SPELL_EFFECTS; ++j) { if (spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH || (spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH)) { CastingTime /= 2; break; } } // As wowwiki says: C = (Cast Time / 3.5) * 1.88 (for healing spells) coeff = (CastingTime / 3500.0f) * DotFactor * 1.88f; }*/ factorMod *= CalculateLevelPenalty(spellProto) * stack; TakenTotal += int32(TakenAdvertisedBenefit * coeff * factorMod); if (Player* modOwner = GetSpellModOwner()) { coeff *= 100.0f; modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_BONUS_MULTIPLIER, coeff); coeff /= 100.0f; } DoneTotal += int32(DoneAdvertisedBenefit * coeff * factorMod); } // use float as more appropriate for negative values and percent applying float heal = (int32(healamount) + DoneTotal) * DoneTotalMod; // apply spellmod to Done amount if (Player* modOwner = GetSpellModOwner()) modOwner->ApplySpellMod( spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, heal); // Nourish cast if (spellProto->SpellFamilyName == SPELLFAMILY_DRUID && spellProto->SpellFamilyFlags [1] & 0x2000000) { // Rejuvenation, Regrowth, Lifebloom, or Wild Growth if (pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_HEAL, SPELLFAMILY_DRUID, 0x50, 0x4000010, 0)) //increase healing by 20% TakenTotalMod *= 1.2f; } // Taken mods // Healing Wave if (spellProto->SpellFamilyName == SPELLFAMILY_SHAMAN && spellProto->SpellFamilyFlags [0] & 0x40) { // Search for Healing Way on Victim if (AuraEffect const* HealingWay = pVictim->GetAuraEffect(29203, 0)) TakenTotalMod *= (HealingWay->GetAmount() + 100.0f) / 100.0f; } // Tenacity increase healing % taken if (AuraEffect const* Tenacity = pVictim->GetAuraEffect(58549, 0)) TakenTotalMod *= (Tenacity->GetAmount() + 100.0f) / 100.0f; // Healing taken percent float minval = (float) pVictim->GetMaxNegativeAuraModifier( SPELL_AURA_MOD_HEALING_PCT); if (minval) TakenTotalMod *= (100.0f + minval) / 100.0f; float maxval = (float) pVictim->GetMaxPositiveAuraModifier( SPELL_AURA_MOD_HEALING_PCT); if (maxval) TakenTotalMod *= (100.0f + maxval) / 100.0f; if (damagetype == DOT) { // Healing over time taken percent float minval_hot = (float) pVictim->GetMaxNegativeAuraModifier( SPELL_AURA_MOD_HOT_PCT); if (minval_hot) TakenTotalMod *= (100.0f + minval_hot) / 100.0f; float maxval_hot = (float) pVictim->GetMaxPositiveAuraModifier( SPELL_AURA_MOD_HOT_PCT); if (maxval_hot) TakenTotalMod *= (100.0f + maxval_hot) / 100.0f; } AuraEffectList const& mHealingGet = pVictim->GetAuraEffectsByType( SPELL_AURA_MOD_HEALING_RECEIVED); for (AuraEffectList::const_iterator i = mHealingGet.begin(); i != mHealingGet.end(); ++i) if (GetGUID() == (*i)->GetCasterGUID() && (*i)->IsAffectedOnSpell(spellProto)) TakenTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f; heal = (int32(heal) + TakenTotal) * TakenTotalMod; return uint32(std::max(heal, 0.0f)); } int32 Unit::SpellBaseHealingBonus(SpellSchoolMask schoolMask) { int32 AdvertisedBenefit = 0; AuraEffectList const& mHealingDone = GetAuraEffectsByType( SPELL_AURA_MOD_HEALING_DONE); for (AuraEffectList::const_iterator i = mHealingDone.begin(); i != mHealingDone.end(); ++i) if (!(*i)->GetMiscValue() || ((*i)->GetMiscValue() & schoolMask) != 0) AdvertisedBenefit += (*i)->GetAmount(); // Healing bonus of spirit, intellect and strength if (GetTypeId() == TYPEID_PLAYER) { // Base value AdvertisedBenefit += this->ToPlayer()->GetBaseSpellPowerBonus(); // Healing bonus from stats AuraEffectList const& mHealingDoneOfStatPercent = GetAuraEffectsByType( SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT); for (AuraEffectList::const_iterator i = mHealingDoneOfStatPercent.begin(); i != mHealingDoneOfStatPercent.end(); ++i) { // stat used dependent from misc value (stat index) Stats usedStat = Stats( (*i)->GetSpellProto()->EffectMiscValue [(*i)->GetEffIndex()]); AdvertisedBenefit += int32( GetStat(usedStat) * (*i)->GetAmount() / 100.0f); } // ... and attack power AuraEffectList const& mHealingDonebyAP = GetAuraEffectsByType( SPELL_AURA_MOD_SPELL_HEALING_OF_ATTACK_POWER); for (AuraEffectList::const_iterator i = mHealingDonebyAP.begin(); i != mHealingDonebyAP.end(); ++i) if ((*i)->GetMiscValue() & schoolMask) AdvertisedBenefit += int32( GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetAmount() / 100.0f); // TODO this should modify PLAYER_FIELD_MOD_SPELL_POWER_PCT instead of all the separate power fields int32 spModPct = GetMaxPositiveAuraModifier( SPELL_AURA_MOD_SPELL_POWER_PCT); // should it apply to non players as well? AdvertisedBenefit += AdvertisedBenefit * spModPct / 100; } return AdvertisedBenefit; } int32 Unit::SpellBaseHealingBonusForVictim(SpellSchoolMask schoolMask, Unit *pVictim) { int32 AdvertisedBenefit = 0; AuraEffectList const& mDamageTaken = pVictim->GetAuraEffectsByType( SPELL_AURA_MOD_HEALING); for (AuraEffectList::const_iterator i = mDamageTaken.begin(); i != mDamageTaken.end(); ++i) if (((*i)->GetMiscValue() & schoolMask) != 0) AdvertisedBenefit += (*i)->GetAmount(); return AdvertisedBenefit; } bool Unit::IsImmunedToDamage(SpellSchoolMask shoolMask) { //If m_immuneToSchool type contain this school type, IMMUNE damage. SpellImmuneList const& schoolList = m_spellImmune [IMMUNITY_SCHOOL]; for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr) if (itr->type & shoolMask) return true; //If m_immuneToDamage type contain magic, IMMUNE damage. SpellImmuneList const& damageList = m_spellImmune [IMMUNITY_DAMAGE]; for (SpellImmuneList::const_iterator itr = damageList.begin(); itr != damageList.end(); ++itr) if (itr->type & shoolMask) return true; return false; } bool Unit::IsImmunedToDamage(SpellEntry const* spellInfo) { if (spellInfo->Attributes & SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY) return false; uint32 shoolMask = GetSpellSchoolMask(spellInfo); if (spellInfo->Id != 42292 && spellInfo->Id != 59752) { //If m_immuneToSchool type contain this school type, IMMUNE damage. SpellImmuneList const& schoolList = m_spellImmune [IMMUNITY_SCHOOL]; for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr) if (itr->type & shoolMask && !CanSpellPierceImmuneAura(spellInfo, sSpellStore.LookupEntry(itr->spellId))) return true; } //If m_immuneToDamage type contain magic, IMMUNE damage. SpellImmuneList const& damageList = m_spellImmune [IMMUNITY_DAMAGE]; for (SpellImmuneList::const_iterator itr = damageList.begin(); itr != damageList.end(); ++itr) if (itr->type & shoolMask) return true; return false; } bool Unit::IsImmunedToSpell(SpellEntry const* spellInfo) { if (!spellInfo) return false; // Single spell immunity. SpellImmuneList const& idList = m_spellImmune [IMMUNITY_ID]; for (SpellImmuneList::const_iterator itr = idList.begin(); itr != idList.end(); ++itr) if (itr->type == spellInfo->Id) return true; if (spellInfo->Attributes & SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY) return false; if (spellInfo->Dispel) { SpellImmuneList const& dispelList = m_spellImmune [IMMUNITY_DISPEL]; for (SpellImmuneList::const_iterator itr = dispelList.begin(); itr != dispelList.end(); ++itr) if (itr->type == spellInfo->Dispel) return true; } if (spellInfo->Mechanic) { SpellImmuneList const& mechanicList = m_spellImmune [IMMUNITY_MECHANIC]; for (SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr) if (itr->type == spellInfo->Mechanic) return true; } for (int i = 0; i < MAX_SPELL_EFFECTS; ++i) { // State/effect immunities applied by aura expect full spell immunity // Ignore effects with mechanic, they are supposed to be checked separately if (!spellInfo->EffectMechanic [i] && spellInfo->Effect [i] != SPELL_EFFECT_KNOCK_BACK) if (IsImmunedToSpellEffect( spellInfo, i)) return true; } if (spellInfo->Id != 42292 && spellInfo->Id != 59752) { SpellImmuneList const& schoolList = m_spellImmune [IMMUNITY_SCHOOL]; for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr) if ((itr->type & GetSpellSchoolMask(spellInfo)) && !(IsPositiveSpell(itr->spellId) && IsPositiveSpell(spellInfo->Id)) && !CanSpellPierceImmuneAura(spellInfo, sSpellStore.LookupEntry(itr->spellId))) return true; } return false; } bool Unit::IsImmunedToSpellEffect(SpellEntry const* spellInfo, uint32 index) const { if (!spellInfo) return false; //If m_immuneToEffect type contain this effect type, IMMUNE effect. uint32 effect = spellInfo->Effect [index]; SpellImmuneList const& effectList = m_spellImmune [IMMUNITY_EFFECT]; for (SpellImmuneList::const_iterator itr = effectList.begin(); itr != effectList.end(); ++itr) if (itr->type == effect) return true; if (uint32 mechanic = spellInfo->EffectMechanic[index]) { SpellImmuneList const& mechanicList = m_spellImmune [IMMUNITY_MECHANIC]; for (SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr) if (itr->type == mechanic) return true; } if (uint32 aura = spellInfo->EffectApplyAuraName[index]) { SpellImmuneList const& list = m_spellImmune [IMMUNITY_STATE]; for (SpellImmuneList::const_iterator itr = list.begin(); itr != list.end(); ++itr) if (itr->type == aura) return true; // Check for immune to application of harmful magical effects AuraEffectList const& immuneAuraApply = GetAuraEffectsByType( SPELL_AURA_MOD_IMMUNE_AURA_APPLY_SCHOOL); for (AuraEffectList::const_iterator iter = immuneAuraApply.begin(); iter != immuneAuraApply.end(); ++iter) if ((spellInfo->Dispel == DISPEL_MAGIC || spellInfo->Dispel == DISPEL_CURSE || // Magical debuff spellInfo->Dispel == DISPEL_DISEASE || spellInfo->Dispel == DISPEL_POISON) && ((*iter)->GetMiscValue() & GetSpellSchoolMask(spellInfo)) && // Check school !IsPositiveEffect(spellInfo->Id, index)) // Harmful return true; } return false; } bool Unit::IsDamageToThreatSpell(SpellEntry const * spellInfo) const { if (!spellInfo) return false; switch (spellInfo->SpellFamilyName) { case SPELLFAMILY_WARLOCK: if (spellInfo->SpellFamilyFlags [0] == 0x100) // Searing Pain return true; break; case SPELLFAMILY_SHAMAN: if (spellInfo->SpellFamilyFlags [0] == SPELLFAMILYFLAG_SHAMAN_FROST_SHOCK) return true; break; case SPELLFAMILY_DEATHKNIGHT: if (spellInfo->SpellFamilyFlags [1] == 0x20000000) // Rune Strike return true; if (spellInfo->SpellFamilyFlags [2] == 0x8) // Death and Decay return true; break; case SPELLFAMILY_WARRIOR: if (spellInfo->SpellFamilyFlags [0] == 0x80) // Thunder Clap return true; break; } return false; } void Unit::MeleeDamageBonus(Unit *pVictim, uint32 *pdamage, WeaponAttackType attType, SpellEntry const *spellProto) { if (!pVictim) return; if (*pdamage == 0) return; uint32 creatureTypeMask = pVictim->GetCreatureTypeMask(); // Taken/Done fixed damage bonus auras int32 DoneFlatBenefit = 0; int32 TakenFlatBenefit = 0; // ..done (for creature type by mask) in taken AuraEffectList const& mDamageDoneCreature = GetAuraEffectsByType( SPELL_AURA_MOD_DAMAGE_DONE_CREATURE); for (AuraEffectList::const_iterator i = mDamageDoneCreature.begin(); i != mDamageDoneCreature.end(); ++i) if (creatureTypeMask & uint32((*i)->GetMiscValue())) DoneFlatBenefit += (*i)->GetAmount(); // ..done // SPELL_AURA_MOD_DAMAGE_DONE included in weapon damage // ..done (base at attack power for marked target and base at attack power for creature type) int32 APbonus = 0; if (attType == RANGED_ATTACK) { APbonus += pVictim->GetTotalAuraModifier( SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS); // ..done (base at attack power and creature type) AuraEffectList const& mCreatureAttackPower = GetAuraEffectsByType( SPELL_AURA_MOD_RANGED_ATTACK_POWER_VERSUS); for (AuraEffectList::const_iterator i = mCreatureAttackPower.begin(); i != mCreatureAttackPower.end(); ++i) if (creatureTypeMask & uint32((*i)->GetMiscValue())) APbonus += (*i)->GetAmount(); } else { APbonus += pVictim->GetTotalAuraModifier( SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS); // ..done (base at attack power and creature type) AuraEffectList const& mCreatureAttackPower = GetAuraEffectsByType( SPELL_AURA_MOD_MELEE_ATTACK_POWER_VERSUS); for (AuraEffectList::const_iterator i = mCreatureAttackPower.begin(); i != mCreatureAttackPower.end(); ++i) if (creatureTypeMask & uint32((*i)->GetMiscValue())) APbonus += (*i)->GetAmount(); } if (APbonus != 0) // Can be negative { bool normalized = false; if (spellProto) for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (spellProto->Effect [i] == SPELL_EFFECT_NORMALIZED_WEAPON_DMG) { normalized = true; break; } DoneFlatBenefit += int32( APbonus / 14.0f * GetAPMultiplier(attType, normalized)); } // ..taken AuraEffectList const& mDamageTaken = pVictim->GetAuraEffectsByType( SPELL_AURA_MOD_DAMAGE_TAKEN); for (AuraEffectList::const_iterator i = mDamageTaken.begin(); i != mDamageTaken.end(); ++i) if ((*i)->GetMiscValue() & GetMeleeDamageSchoolMask()) TakenFlatBenefit += (*i)->GetAmount(); if (attType != RANGED_ATTACK) TakenFlatBenefit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN); else TakenFlatBenefit += pVictim->GetTotalAuraModifier( SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN); // Done/Taken total percent damage auras float DoneTotalMod = 1.0f; float TakenTotalMod = 1.0f; // ..done // SPELL_AURA_MOD_DAMAGE_PERCENT_DONE included in weapon damage // SPELL_AURA_MOD_OFFHAND_DAMAGE_PCT included in weapon damage // SPELL_AURA_MOD_DAMAGE_PERCENT_DONE for non-physical spells like Scourge Strike, Frost Strike, this is NOT included in weapon damage if (spellProto) if (GetSpellSchoolMask(spellProto) != SPELL_SCHOOL_MASK_NORMAL) { AuraEffectList const &mModDamagePercentDone = GetAuraEffectsByType( SPELL_AURA_MOD_DAMAGE_PERCENT_DONE); for (AuraEffectList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i) if (((*i)->GetMiscValue() & GetSpellSchoolMask(spellProto)) && !((*i)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL)) DoneTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f; } AuraEffectList const &mDamageDoneVersus = GetAuraEffectsByType( SPELL_AURA_MOD_DAMAGE_DONE_VERSUS); for (AuraEffectList::const_iterator i = mDamageDoneVersus.begin(); i != mDamageDoneVersus.end(); ++i) if (creatureTypeMask & uint32((*i)->GetMiscValue())) DoneTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f; // bonus against aurastate AuraEffectList const &mDamageDoneVersusAurastate = GetAuraEffectsByType( SPELL_AURA_MOD_DAMAGE_DONE_VERSUS_AURASTATE); for (AuraEffectList::const_iterator i = mDamageDoneVersusAurastate.begin(); i != mDamageDoneVersusAurastate.end(); ++i) if (pVictim->HasAuraState(AuraState((*i)->GetMiscValue()))) DoneTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f; // done scripted mod (take it from owner) Unit * owner = GetOwner() ? GetOwner() : this; AuraEffectList const &mOverrideClassScript = owner->GetAuraEffectsByType( SPELL_AURA_OVERRIDE_CLASS_SCRIPTS); for (AuraEffectList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i) { if (!(*i)->IsAffectedOnSpell(spellProto)) continue; switch ((*i)->GetMiscValue()) { // Tundra Stalker // Merciless Combat case 7277: { // Merciless Combat if ((*i)->GetSpellProto()->SpellIconID == 2656) { if (!pVictim->HealthAbovePct(35)) DoneTotalMod *= (100.0f + (*i)->GetAmount()) / 100.0f; } // Tundra Stalker else { // Frost Fever (target debuff) if (pVictim->HasAura(55095)) DoneTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f; } break; } // Rage of Rivendare case 7293: { if (pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, 0, 0x02000000, 0)) if (SpellChainNode const *chain = sSpellMgr->GetSpellChainNode((*i)->GetId())) DoneTotalMod *= (chain->rank * 2.0f + 100.0f) / 100.0f; break; } } } // Custom scripted damage if (spellProto) switch (spellProto->SpellFamilyName) { case SPELLFAMILY_DEATHKNIGHT: // Glacier Rot if (spellProto->SpellFamilyFlags [0] & 0x2 || spellProto->SpellFamilyFlags [1] & 0x6) if (AuraEffect * aurEff = GetDummyAuraEffect(SPELLFAMILY_DEATHKNIGHT, 196, 0)) if (pVictim->GetDiseasesByCaster( owner->GetGUID()) > 0) DoneTotalMod *= (100.0f + aurEff->GetAmount()) / 100.0f; break; } // ..taken AuraEffectList const& mModDamagePercentTaken = pVictim->GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN); for (AuraEffectList::const_iterator i = mModDamagePercentTaken.begin(); i != mModDamagePercentTaken.end(); ++i) if ((*i)->GetMiscValue() & GetMeleeDamageSchoolMask()) TakenTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f; // From caster spells AuraEffectList const& mOwnerTaken = pVictim->GetAuraEffectsByType( SPELL_AURA_MOD_DAMAGE_FROM_CASTER); for (AuraEffectList::const_iterator i = mOwnerTaken.begin(); i != mOwnerTaken.end(); ++i) if ((*i)->GetCasterGUID() == GetGUID() && (*i)->IsAffectedOnSpell(spellProto)) TakenTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f; // .. taken pct (special attacks) if (spellProto) { // Mod damage from spell mechanic uint32 mechanicMask = GetAllSpellMechanicMask(spellProto); // Shred, Maul - "Effects which increase Bleed damage also increase Shred damage" if (spellProto->SpellFamilyName == SPELLFAMILY_DRUID && spellProto->SpellFamilyFlags [0] & 0x00008800) mechanicMask |= (1 << MECHANIC_BLEED); if (mechanicMask) { AuraEffectList const& mDamageDoneMechanic = pVictim->GetAuraEffectsByType( SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT); for (AuraEffectList::const_iterator i = mDamageDoneMechanic.begin(); i != mDamageDoneMechanic.end(); ++i) if (mechanicMask & uint32(1 << ((*i)->GetMiscValue()))) TakenTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f; } } // .. taken pct: dummy auras AuraEffectList const& mDummyAuras = pVictim->GetAuraEffectsByType( SPELL_AURA_DUMMY); for (AuraEffectList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i) { switch ((*i)->GetSpellProto()->SpellIconID) { //Cheat Death case 2109: if ((*i)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL) { // needs rework 4.0.6 /*if (pVictim->GetTypeId() != TYPEID_PLAYER) continue; float mod = pVictim->ToPlayer()->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*(-8.0f); if (mod < (*i)->GetAmount()) mod = (float)(*i)->GetAmount(); TakenTotalMod *= (mod+100.0f)/100.0f;*/ } break; // Blessing of Sanctuary // Greater Blessing of Sanctuary case 19: case 1804: { if ((*i)->GetSpellProto()->SpellFamilyName != SPELLFAMILY_PALADIN) continue; if ((*i)->GetMiscValue() & (spellProto ? GetSpellSchoolMask(spellProto) : 0)) TakenTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f; break; } // Ebon Plague case 1933: if ((*i)->GetMiscValue() & (spellProto ? GetSpellSchoolMask(spellProto) : 0)) TakenTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f; break; } } // .. taken pct: class scripts AuraEffectList const& mclassScritAuras = GetAuraEffectsByType( SPELL_AURA_OVERRIDE_CLASS_SCRIPTS); for (AuraEffectList::const_iterator i = mclassScritAuras.begin(); i != mclassScritAuras.end(); ++i) { switch ((*i)->GetMiscValue()) { case 6427: case 6428: // Dirty Deeds if (pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, spellProto, this)) { AuraEffect* eff0 = (*i)->GetBase()->GetEffect(0); if (!eff0 || (*i)->GetEffIndex() != 1) { sLog->outError("Spell structure of DD (%u) changed.", (*i)->GetId()); continue; } // effect 0 have expected value but in negative state TakenTotalMod *= (-eff0->GetAmount() + 100.0f) / 100.0f; } break; } } if (attType != RANGED_ATTACK) { AuraEffectList const& mModMeleeDamageTakenPercent = pVictim->GetAuraEffectsByType( SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN_PCT); for (AuraEffectList::const_iterator i = mModMeleeDamageTakenPercent.begin(); i != mModMeleeDamageTakenPercent.end(); ++i) TakenTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f; } else { AuraEffectList const& mModRangedDamageTakenPercent = pVictim->GetAuraEffectsByType( SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN_PCT); for (AuraEffectList::const_iterator i = mModRangedDamageTakenPercent.begin(); i != mModRangedDamageTakenPercent.end(); ++i) TakenTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f; } float tmpDamage = float(int32(*pdamage) + DoneFlatBenefit) * DoneTotalMod; // apply spellmod to Done damage if (spellProto) if (Player* modOwner = GetSpellModOwner()) modOwner->ApplySpellMod( spellProto->Id, SPELLMOD_DAMAGE, tmpDamage); tmpDamage = (tmpDamage + TakenFlatBenefit) * TakenTotalMod; // bonus result can be negative *pdamage = uint32(std::max(tmpDamage, 0.0f)); } void Unit::ApplySpellImmune(uint32 spellId, uint32 op, uint32 type, bool apply) { if (apply) { for (SpellImmuneList::iterator itr = m_spellImmune [op].begin(), next; itr != m_spellImmune [op].end(); itr = next) { next = itr; ++next; if (itr->type == type) { m_spellImmune [op].erase(itr); next = m_spellImmune [op].begin(); } } SpellImmune Immune; Immune.spellId = spellId; Immune.type = type; m_spellImmune [op].push_back(Immune); } else { for (SpellImmuneList::iterator itr = m_spellImmune [op].begin(); itr != m_spellImmune [op].end(); ++itr) { if (itr->spellId == spellId) { m_spellImmune [op].erase(itr); break; } } } } void Unit::ApplySpellDispelImmunity(const SpellEntry * spellProto, DispelType type, bool apply) { ApplySpellImmune(spellProto->Id, IMMUNITY_DISPEL, type, apply); if (apply && spellProto->AttributesEx & SPELL_ATTR1_DISPEL_AURAS_ON_IMMUNITY) { // Create dispel mask by dispel type uint32 dispelMask = GetDispellMask(type); // Dispel all existing auras vs current dispel type AuraApplicationMap& auras = GetAppliedAuras(); for (AuraApplicationMap::iterator itr = auras.begin(); itr != auras.end();) { SpellEntry const* spell = itr->second->GetBase()->GetSpellProto(); if ((1 << spell->Dispel) & dispelMask) { // Dispel aura RemoveAura(itr); } else ++itr; } } } float Unit::GetWeaponProcChance() const { // normalized proc chance for weapon attack speed // (odd formula...) if (isAttackReady(BASE_ATTACK)) return (GetAttackTime(BASE_ATTACK) * 1.8f / 1000.0f); else if (haveOffhandWeapon() && isAttackReady(OFF_ATTACK)) return (GetAttackTime( OFF_ATTACK) * 1.6f / 1000.0f); return 0; } float Unit::GetPPMProcChance(uint32 WeaponSpeed, float PPM, const SpellEntry * spellProto) const { // proc per minute chance calculation if (PPM <= 0) return 0.0f; // Apply chance modifer aura if (spellProto) if (Player* modOwner = GetSpellModOwner()) modOwner->ApplySpellMod( spellProto->Id, SPELLMOD_PROC_PER_MINUTE, PPM); return floor((WeaponSpeed * PPM) / 600.0f); // result is chance in percents (probability = Speed_in_sec * (PPM / 60)) } void Unit::Mount(uint32 mount, uint32 VehicleId, uint32 creatureEntry) { RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOUNT); if (mount) SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, mount); SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT); // unsummon pet if (Player* plr = ToPlayer()) { Pet* pet = plr->GetPet(); if (pet) { Battleground *bg = ToPlayer()->GetBattleground(); // don't unsummon pet in arena but SetFlag UNIT_FLAG_STUNNED to disable pet's interface if (bg && bg->isArena()) pet->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED); else plr->UnsummonPetTemporaryIfAny(); } if (plr->GetEmoteState()) plr->SetEmoteState(0); if (VehicleId) { if (CreateVehicleKit(VehicleId)) { GetVehicleKit()->Reset(); // Send others that we now have a vehicle WorldPacket data(SMSG_PLAYER_VEHICLE_DATA, GetPackGUID().size() + 4); data.appendPackGUID(GetGUID()); data << uint32(VehicleId); SendMessageToSet(&data, true); data.Initialize(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0); plr->GetSession()->SendPacket(&data); // mounts can also have accessories GetVehicleKit()->InstallAllAccessories(creatureEntry); } } } } void Unit::Unmount() { if (!IsMounted()) return; RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_MOUNTED); SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0); RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT); WorldPacket data(SMSG_DISMOUNT, 8); data.appendPackGUID(GetGUID()); SendMessageToSet(&data, true); // only resummon old pet if the player is already added to a map // this prevents adding a pet to a not created map which would otherwise cause a crash // (it could probably happen when logging in after a previous crash) if (GetTypeId() == TYPEID_PLAYER) { if (Pet *pPet = this->ToPlayer()->GetPet()) { if (pPet && pPet->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED) && !pPet->HasUnitState(UNIT_STAT_STUNNED)) pPet->RemoveFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED); } else this->ToPlayer()->ResummonPetTemporaryUnSummonedIfAny(); } if (GetTypeId() == TYPEID_PLAYER && GetVehicleKit()) { // Send other players that we are no longer a vehicle WorldPacket data(SMSG_PLAYER_VEHICLE_DATA, 8 + 4); data.appendPackGUID(GetGUID()); data << uint32(0); this->ToPlayer()->SendMessageToSet(&data, true); // Remove vehicle class from player RemoveVehicleKit(); } } void Unit::SetInCombatWith(Unit* enemy) { Unit* eOwner = enemy->GetCharmerOrOwnerOrSelf(); if (eOwner->IsPvP()) { SetInCombatState(true, enemy); return; } //check for duel if (eOwner->GetTypeId() == TYPEID_PLAYER && eOwner->ToPlayer()->duel) { Unit const* myOwner = GetCharmerOrOwnerOrSelf(); if (((Player const*) eOwner)->duel->opponent == myOwner) { SetInCombatState(true, enemy); return; } } SetInCombatState(false, enemy); } void Unit::CombatStart(Unit* target, bool initialAggro) { if (initialAggro) { if (!target->IsStandState()) target->SetStandState( UNIT_STAND_STATE_STAND); if (!target->isInCombat() && target->GetTypeId() != TYPEID_PLAYER && !target->ToCreature()->HasReactState(REACT_PASSIVE) && target->ToCreature()->IsAIEnabled) { target->ToCreature()->AI()->AttackStart(this); } SetInCombatWith(target); target->SetInCombatWith(this); } Unit *who = target->GetCharmerOrOwnerOrSelf(); if (who->GetTypeId() == TYPEID_PLAYER) SetContestedPvP(who->ToPlayer()); Player *me = GetCharmerOrOwnerPlayerOrPlayerItself(); if (me && who->IsPvP() && (who->GetTypeId() != TYPEID_PLAYER || !me->duel || me->duel->opponent != who)) { me->UpdatePvP(true); me->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT); } } void Unit::SetInCombatState(bool PvP, Unit* enemy) { // only alive units can be in combat if (!isAlive()) return; if (PvP) m_CombatTimer = 5000; if (isInCombat() || HasUnitState(UNIT_STAT_EVADE)) return; SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT); if (GetTypeId() != TYPEID_PLAYER) { // Set home position at place of engaging combat for escorted creatures if ((IsAIEnabled && this->ToCreature()->AI()->IsEscorted()) || GetMotionMaster()->GetCurrentMovementGeneratorType() == WAYPOINT_MOTION_TYPE || GetMotionMaster()->GetCurrentMovementGeneratorType() == POINT_MOTION_TYPE) this->ToCreature()->SetHomePosition( GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation()); if (enemy) { if (IsAIEnabled) { this->ToCreature()->AI()->EnterCombat(enemy); RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE); //always remove Out of Combat Non Attackable flag if we enter combat and AI is enabled } if (this->ToCreature()->GetFormation()) this->ToCreature()->GetFormation()->MemberAttackStart( this->ToCreature(), enemy); } if (isPet()) { UpdateSpeed(MOVE_RUN, true); UpdateSpeed(MOVE_SWIM, true); UpdateSpeed(MOVE_FLIGHT, true); } if (!(ToCreature()->GetCreatureInfo()->type_flags & CREATURE_TYPEFLAGS_MOUNTED_COMBAT)) Unmount(); } if (GetTypeId() == TYPEID_PLAYER && ToPlayer()->getRace() == RACE_WORGEN && HasAura(94293)) { //TODO: make a hackfix for worgen starting zone. ToPlayer()->setInWorgenForm(UNIT_FLAG2_WORGEN_TRANSFORM3); } for (Unit::ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr) { (*itr)->SetInCombatState(PvP, enemy); (*itr)->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT); } } void Unit::ClearInCombat() { m_CombatTimer = 0; RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT); // Player's state will be cleared in Player::UpdateContestedPvP if (GetTypeId() != TYPEID_PLAYER) { Creature* creature = this->ToCreature(); if (creature->GetCreatureInfo() && creature->GetCreatureInfo()->unit_flags & UNIT_FLAG_OOC_NOT_ATTACKABLE) SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE); //re-apply Out of Combat Non Attackable flag if we leave combat, can be overriden in scripts in EnterEvadeMode() ClearUnitState(UNIT_STAT_ATTACK_PLAYER); if (HasFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_TAPPED)) SetUInt32Value( UNIT_DYNAMIC_FLAGS, ((Creature*) this)->GetCreatureInfo()->dynamicflags); } else this->ToPlayer()->UpdatePotionCooldown(); if (GetTypeId() != TYPEID_PLAYER && ((Creature*) this)->isPet()) { if (Unit *owner = GetOwner()) for (uint8 i = 0; i < MAX_MOVE_TYPE; ++i) if (owner->GetSpeedRate(UnitMoveType(i)) > GetSpeedRate(UnitMoveType(i))) SetSpeed(UnitMoveType(i), owner->GetSpeedRate(UnitMoveType(i)), true); } else if (!isCharmed()) return; RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT); } bool Unit::isTargetableForAttack(bool checkFakeDeath) const { if (!isAlive()) return false; if (HasFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_OOC_NOT_ATTACKABLE)) return false; if (GetTypeId() == TYPEID_PLAYER && ToPlayer()->isGameMaster()) return false; return !HasUnitState(UNIT_STAT_UNATTACKABLE) && (!checkFakeDeath || !HasUnitState(UNIT_STAT_DIED)); } bool Unit::IsValidAttackTarget(Unit const* target) const { return canAttack(target, NULL); } bool Unit::canAttack(Unit const* target, bool force) const { ASSERT(target); // can't attack self if (this == target) return false; if (force) { if (IsFriendlyTo(target)) return false; if (GetTypeId() != TYPEID_PLAYER) { if (isPet()) { if (Unit *owner = GetOwner()) if (!(owner->canAttack(target))) return false; } else if (!IsHostileTo(target)) return false; } } else if (!IsHostileTo(target)) return false; if (!target->isAttackableByAOE()) return false; // can't attack unattackable units or GMs if (target->HasUnitState(UNIT_STAT_UNATTACKABLE) || (target->GetTypeId() == TYPEID_PLAYER && target->ToPlayer()->isGameMaster())) return false; // check flags if (target->HasFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_TAXI_FLIGHT | UNIT_FLAG_NOT_ATTACKABLE_1 | UNIT_FLAG_UNK_16) || (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) && target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PASSIVE)) || (!target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PASSIVE)) || (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) && target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE)) || (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE))) return false; // CvC case - can attack each other only when one of them is hostile if (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) && !target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE)) return GetReactionTo( target) <= REP_HOSTILE || target->GetReactionTo(this) <= REP_HOSTILE; // PvP, PvC, CvP case // can't attack friendly targets if (GetReactionTo(target) > REP_NEUTRAL || target->GetReactionTo(this) > REP_NEUTRAL) return false; if (target->HasUnitState(UNIT_STAT_DIED)) { if (!ToCreature() || !ToCreature()->isGuard()) return false; Player const* playerAffectingAttacker = HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) ? GetAffectingPlayer() : NULL; Player const* playerAffectingTarget = target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) ? target->GetAffectingPlayer() : NULL; // check duel - before sanctuary checks if (playerAffectingAttacker && playerAffectingTarget) if (playerAffectingAttacker->duel && playerAffectingAttacker->duel->opponent == playerAffectingTarget && playerAffectingAttacker->duel->startTime != 0) return true; // additional checks - only PvP case if (playerAffectingAttacker && playerAffectingTarget) { if (target->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_PVP) return true; if (GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_FFA_PVP && target->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_FFA_PVP) return true; return (GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_UNK1) || (target->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_UNK1); } return true; // PvP case - can't attack when attacker or target are in sanctuary // however, 13850 client doesn't allow to attack when one of the unit's has sanctuary flag and is pvp if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) && ((target->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_SANCTUARY) || (GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_SANCTUARY))) return false; // guards can detect fake death if (!target->HasFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FEIGN_DEATH)) return false; } // can't attack own vehicle or passenger if (m_vehicle) if (IsOnVehicle(target) || m_vehicle->GetBase()->IsOnVehicle(target)) return false; if (!canSeeOrDetect(target)) return false; return true; } bool Unit::isAttackableByAOE(bool requireDeadTarget) const { if (isAlive() == requireDeadTarget) return false; if (HasFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_OOC_NOT_ATTACKABLE)) return false; if (GetTypeId() == TYPEID_PLAYER && ToPlayer()->isGameMaster()) return false; return !HasUnitState(UNIT_STAT_UNATTACKABLE); } int32 Unit::ModifyHealth(int32 dVal) { int32 gain = 0; if (dVal == 0) return 0; int32 curHealth = (int32) GetHealth(); int32 val = dVal + curHealth; if (val <= 0) { SetHealth(0); return -curHealth; } int32 maxHealth = (int32) GetMaxHealth(); if (val < maxHealth) { SetHealth(val); gain = val - curHealth; } else if (curHealth != maxHealth) { SetHealth(maxHealth); gain = maxHealth - curHealth; } return gain; } int32 Unit::GetHealthGain(int32 dVal) { int32 gain = 0; if (dVal == 0) return 0; int32 curHealth = (int32) GetHealth(); int32 val = dVal + curHealth; if (val <= 0) { return -curHealth; } int32 maxHealth = (int32) GetMaxHealth(); if (val < maxHealth) gain = dVal; else if (curHealth != maxHealth) gain = maxHealth - curHealth; return gain; } int32 Unit::ModifyPower(Powers power, int32 dVal) { int32 gain = 0; if (dVal == 0) return 0; int32 curPower = (int32) GetPower(power); int32 val = dVal + curPower; if (val <= 0) { SetPower(power, 0); return -curPower; } int32 maxPower = (int32) GetMaxPower(power); if (val < maxPower) { SetPower(power, val); gain = val - curPower; } else if (curPower != maxPower) { SetPower(power, maxPower); gain = maxPower - curPower; } return gain; } // returns negative amount on power reduction int32 Unit::ModifyPowerPct(Powers power, float pct, bool apply) { float amount = (float) GetMaxPower(power); ApplyPercentModFloatVar(amount, pct, apply); return ModifyPower(power, (int32) amount - (int32) GetMaxPower(power)); } bool Unit::isAlwaysVisibleFor(WorldObject const* seer) const { if (WorldObject::isAlwaysVisibleFor(seer)) return true; // Always seen by owner if (uint64 guid = GetCharmerOrOwnerGUID()) if (seer->GetGUID() == guid) return true; return false; } bool Unit::isAlwaysDetectableFor(WorldObject const* seer) const { if (WorldObject::isAlwaysDetectableFor(seer)) return true; if (HasAuraTypeWithCaster(SPELL_AURA_MOD_STALKED, seer->GetGUID())) return true; return false; } void Unit::SetVisible(bool x) { if (!x) m_serverSideVisibility.SetValue(SERVERSIDE_VISIBILITY_GM, SEC_GAMEMASTER); else m_serverSideVisibility.SetValue(SERVERSIDE_VISIBILITY_GM, SEC_PLAYER); UpdateObjectVisibility(); } void Unit::UpdateSpeed(UnitMoveType mtype, bool forced) { int32 main_speed_mod = 0; float stack_bonus = 1.0f; float non_stack_bonus = 1.0f; switch (mtype) { // Only apply debuffs case MOVE_FLIGHT_BACK: case MOVE_RUN_BACK: case MOVE_SWIM_BACK: break; case MOVE_WALK: return; case MOVE_RUN: { if (IsMounted()) // Use on mount auras { main_speed_mod = GetMaxPositiveAuraModifier( SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED); stack_bonus = GetTotalAuraMultiplier( SPELL_AURA_MOD_MOUNTED_SPEED_ALWAYS); non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier( SPELL_AURA_MOD_MOUNTED_SPEED_NOT_STACK)) / 100.0f; } else { main_speed_mod = GetMaxPositiveAuraModifier( SPELL_AURA_MOD_INCREASE_SPEED); stack_bonus = GetTotalAuraMultiplier( SPELL_AURA_MOD_SPEED_ALWAYS); non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier( SPELL_AURA_MOD_SPEED_NOT_STACK)) / 100.0f; } break; } case MOVE_SWIM: { main_speed_mod = GetMaxPositiveAuraModifier( SPELL_AURA_MOD_INCREASE_SWIM_SPEED); break; } case MOVE_FLIGHT: { if (GetTypeId() == TYPEID_UNIT && IsControlledByPlayer()) // not sure if good for pet { main_speed_mod = GetMaxPositiveAuraModifier( SPELL_AURA_MOD_INCREASE_VEHICLE_FLIGHT_SPEED); stack_bonus = GetTotalAuraMultiplier( SPELL_AURA_MOD_VEHICLE_SPEED_ALWAYS); // for some spells this mod is applied on vehicle owner int32 owner_speed_mod = 0; if (Unit * owner = GetCharmer()) owner_speed_mod = owner->GetMaxPositiveAuraModifier( SPELL_AURA_MOD_INCREASE_VEHICLE_FLIGHT_SPEED); main_speed_mod = std::max(main_speed_mod, owner_speed_mod); } else if (IsMounted()) { main_speed_mod = GetMaxPositiveAuraModifier( SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED); stack_bonus = GetTotalAuraMultiplier( SPELL_AURA_MOD_MOUNTED_FLIGHT_SPEED_ALWAYS); } else // Use not mount (shapeshift for example) auras (should stack) main_speed_mod = GetTotalAuraModifier( SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) + GetTotalAuraModifier( SPELL_AURA_MOD_INCREASE_VEHICLE_FLIGHT_SPEED); non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier( SPELL_AURA_MOD_FLIGHT_SPEED_NOT_STACK)) / 100.0f; // Update speed for vehicle if available if (GetTypeId() == TYPEID_PLAYER && GetVehicle()) GetVehicleBase()->UpdateSpeed( MOVE_FLIGHT, true); break; } default: sLog->outError("Unit::UpdateSpeed: Unsupported move type (%d)", mtype); return; } float bonus = non_stack_bonus > stack_bonus ? non_stack_bonus : stack_bonus; // now we ready for speed calculation float speed = main_speed_mod ? bonus * (100.0f + main_speed_mod) / 100.0f : bonus; switch (mtype) { case MOVE_RUN: case MOVE_SWIM: case MOVE_FLIGHT: { // Set creature speed rate from CreatureInfo if (GetTypeId() == TYPEID_UNIT) speed *= this->ToCreature()->GetCreatureInfo()->speed_walk; // Normalize speed by 191 aura SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED if need // TODO: possible affect only on MOVE_RUN if (int32 normalization = GetMaxPositiveAuraModifier(SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED)) { // Use speed from aura float max_speed = normalization / (IsControlledByPlayer() ? playerBaseMoveSpeed [mtype] : baseMoveSpeed [mtype]); if (speed > max_speed) speed = max_speed; } break; } default: break; } // for creature case, we check explicit if mob searched for assistance if (GetTypeId() == TYPEID_UNIT) { if (this->ToCreature()->HasSearchedAssistance()) speed *= 0.66f; // best guessed value, so this will be 33% reduction. Based off initial speed, mob can then "run", "walk fast" or "walk". } // Apply strongest slow aura mod to speed int32 slow = GetMaxNegativeAuraModifier(SPELL_AURA_MOD_DECREASE_SPEED); if (slow) { speed *= (100.0f + slow) / 100.0f; if (float minSpeedMod = (float)GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MINIMUM_SPEED)) { float min_speed = minSpeedMod / 100.0f; if (speed < min_speed) speed = min_speed; } } SetSpeed(mtype, speed, forced); } float Unit::GetSpeed(UnitMoveType mtype) const { return m_speed_rate [mtype] * (IsControlledByPlayer() ? playerBaseMoveSpeed [mtype] : baseMoveSpeed [mtype]); } void Unit::SetSpeed(UnitMoveType mtype, float rate, bool forced) { if (rate < 0) rate = 0.0f; // Update speed only on change if (m_speed_rate [mtype] == rate) return; m_speed_rate [mtype] = rate; propagateSpeedChange(); WorldPacket data; if (!forced) { switch (mtype) { case MOVE_WALK: data.Initialize(MSG_MOVE_SET_WALK_SPEED, 8 + 4 + 2 + 4 + 4 + 4 + 4 + 4 + 4 + 4); break; case MOVE_RUN: data.Initialize(MSG_MOVE_SET_RUN_SPEED, 8 + 4 + 2 + 4 + 4 + 4 + 4 + 4 + 4 + 4); break; case MOVE_RUN_BACK: data.Initialize(MSG_MOVE_SET_RUN_BACK_SPEED, 8 + 4 + 2 + 4 + 4 + 4 + 4 + 4 + 4 + 4); break; case MOVE_SWIM: data.Initialize(MSG_MOVE_SET_SWIM_SPEED, 8 + 4 + 2 + 4 + 4 + 4 + 4 + 4 + 4 + 4); break; case MOVE_SWIM_BACK: data.Initialize(MSG_MOVE_SET_SWIM_BACK_SPEED, 8 + 4 + 2 + 4 + 4 + 4 + 4 + 4 + 4 + 4); break; case MOVE_TURN_RATE: data.Initialize(MSG_MOVE_SET_TURN_RATE, 8 + 4 + 2 + 4 + 4 + 4 + 4 + 4 + 4 + 4); break; case MOVE_FLIGHT: data.Initialize(MSG_MOVE_SET_FLIGHT_SPEED, 8 + 4 + 2 + 4 + 4 + 4 + 4 + 4 + 4 + 4); break; case MOVE_FLIGHT_BACK: data.Initialize(MSG_MOVE_SET_FLIGHT_BACK_SPEED, 8 + 4 + 2 + 4 + 4 + 4 + 4 + 4 + 4 + 4); break; case MOVE_PITCH_RATE: data.Initialize(MSG_MOVE_SET_PITCH_RATE, 8 + 4 + 2 + 4 + 4 + 4 + 4 + 4 + 4 + 4); break; default: sLog->outError( "Unit::SetSpeed: Unsupported move type (%d), data not sent to client.", mtype); return; } data.append(GetPackGUID()); data << uint32(0); // movement flags data << uint16(0); // unk flags data << uint32(getMSTime()); data << float(GetPositionX()); data << float(GetPositionY()); data << float(GetPositionZ()); data << float(GetOrientation()); data << uint32(0); // fall time data << float(GetSpeed(mtype)); SendMessageToSet(&data, true); } else { if (GetTypeId() == TYPEID_PLAYER) { // register forced speed changes for WorldSession::HandleForceSpeedChangeAck // and do it only for real sent packets and use run for run/mounted as client expected ++this->ToPlayer()->m_forced_speed_changes [mtype]; if (!isInCombat()) if (Pet* pet = this->ToPlayer()->GetPet()) pet->SetSpeed( mtype, m_speed_rate [mtype], forced); } switch (mtype) { case MOVE_WALK: data.Initialize(SMSG_FORCE_WALK_SPEED_CHANGE, 16); break; case MOVE_RUN: data.Initialize(SMSG_FORCE_RUN_SPEED_CHANGE, 17); break; case MOVE_RUN_BACK: data.Initialize(SMSG_FORCE_RUN_BACK_SPEED_CHANGE, 16); break; case MOVE_SWIM: data.Initialize(SMSG_FORCE_SWIM_SPEED_CHANGE, 16); break; case MOVE_SWIM_BACK: data.Initialize(SMSG_FORCE_SWIM_BACK_SPEED_CHANGE, 16); break; case MOVE_TURN_RATE: data.Initialize(SMSG_FORCE_TURN_RATE_CHANGE, 16); break; case MOVE_FLIGHT: data.Initialize(SMSG_FORCE_FLIGHT_SPEED_CHANGE, 16); break; case MOVE_FLIGHT_BACK: data.Initialize(SMSG_FORCE_FLIGHT_BACK_SPEED_CHANGE, 16); break; case MOVE_PITCH_RATE: data.Initialize(SMSG_FORCE_PITCH_RATE_CHANGE, 16); break; default: sLog->outError( "Unit::SetSpeed: Unsupported move type (%d), data not sent to client.", mtype); return; } data.append(GetPackGUID()); data << (uint32) 0; // moveEvent, NUM_PMOVE_EVTS = 0x39 if (mtype == MOVE_RUN) data << uint8(0); // new 2.1.0 data << float(GetSpeed(mtype)); SendMessageToSet(&data, true); } } void Unit::SetHover(bool on) { if (on) CastSpell(this, 11010, true); else RemoveAurasDueToSpell(11010); } void Unit::setDeathState(DeathState s) { // death state needs to be updated before RemoveAllAurasOnDeath() calls HandleChannelDeathItem(..) so that // it can be used to check creation of death items (such as soul shards). DeathState oldDeathState = m_deathState; m_deathState = s; if (s != ALIVE && s != JUST_ALIVED) { CombatStop(); DeleteThreatList(); getHostileRefManager().deleteReferences(); ClearComboPointHolders(); // any combo points pointed to unit lost at it death if (IsNonMeleeSpellCasted(false)) InterruptNonMeleeSpells(false); UnsummonAllTotems(); RemoveAllControlled(); RemoveAllAurasOnDeath(); ExitVehicle(); } if (s == JUST_DIED) { ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, false); ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, false); // remove aurastates allowing special moves ClearAllReactives(); ClearDiminishings(); GetMotionMaster()->Clear(false); GetMotionMaster()->MoveIdle(); if (m_vehicleKit) m_vehicleKit->Die(); SendMonsterStop(true); //without this when removing IncreaseMaxHealth aura player may stuck with 1 hp //do not why since in IncreaseMaxHealth currenthealth is checked SetHealth(0); SetPower(getPowerType(), 0); } else if (s == JUST_ALIVED) RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); // clear skinnable for creature and player (at battleground) if (oldDeathState != ALIVE && s == ALIVE) { // Reset display id on resurection - needed by corpse explosion to cleanup after display change // TODO: fix this if (!HasAuraType(SPELL_AURA_TRANSFORM)) SetDisplayId( GetNativeDisplayId()); } } /*######################################## ######## ######## ######## AGGRO SYSTEM ######## ######## ######## ########################################*/ bool Unit::CanHaveThreatList() const { // only creatures can have threat list if (GetTypeId() != TYPEID_UNIT) return false; // only alive units can have threat list if (!isAlive() || isDying()) return false; // totems can not have threat list if (this->ToCreature()->isTotem()) return false; // vehicles can not have threat list //if (this->ToCreature()->IsVehicle()) // return false; // summons can not have a threat list, unless they are controlled by a creature if (HasUnitTypeMask(UNIT_MASK_MINION)) { assert(dynamic_cast <Minion*>(const_cast <Unit*>(this))); if (IS_PLAYER_GUID(((Minion*)this)->GetOwnerGUID())) return false; } if (HasUnitTypeMask(UNIT_MASK_GUARDIAN | UNIT_MASK_CONTROLABLE_GUARDIAN)) { assert(dynamic_cast <Guardian*>(const_cast <Unit*>(this))); if (IS_PLAYER_GUID(((Guardian*)this)->GetOwnerGUID())) return false; } if (this->ToCreature()->isPet()) { assert(dynamic_cast <Pet*>(const_cast <Unit*>(this))); if (IS_PLAYER_GUID(((Pet*)this)->GetOwnerGUID())) return false; } return true; } //====================================================================== float Unit::ApplyTotalThreatModifier(float fThreat, SpellSchoolMask schoolMask) { if (!HasAuraType(SPELL_AURA_MOD_THREAT) || fThreat < 0) return fThreat; SpellSchools school = GetFirstSchoolInMask(schoolMask); return fThreat * m_threatModifier [school]; } //====================================================================== void Unit::AddThreat(Unit* pVictim, float fThreat, SpellSchoolMask schoolMask, SpellEntry const *threatSpell) { // Only mobs can manage threat lists if (CanHaveThreatList()) m_ThreatManager.addThreat(pVictim, fThreat, schoolMask, threatSpell); } //====================================================================== void Unit::DeleteThreatList() { if (CanHaveThreatList() && !m_ThreatManager.isThreatListEmpty()) SendClearThreatListOpcode(); m_ThreatManager.clearReferences(); } //====================================================================== void Unit::TauntApply(Unit* taunter) { ASSERT(GetTypeId() == TYPEID_UNIT); if (!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && taunter->ToPlayer()->isGameMaster())) return; if (!CanHaveThreatList()) return; if (this->ToCreature()->HasReactState(REACT_PASSIVE)) return; Unit *target = getVictim(); if (target && target == taunter) return; SetInFront(taunter); if (this->ToCreature()->IsAIEnabled) this->ToCreature()->AI()->AttackStart( taunter); //m_ThreatManager.tauntApply(taunter); } //====================================================================== void Unit::TauntFadeOut(Unit *taunter) { ASSERT(GetTypeId() == TYPEID_UNIT); if (!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && taunter->ToPlayer()->isGameMaster())) return; if (!CanHaveThreatList()) return; if (this->ToCreature()->HasReactState(REACT_PASSIVE)) return; Unit *target = getVictim(); if (!target || target != taunter) return; if (m_ThreatManager.isThreatListEmpty()) { if (this->ToCreature()->IsAIEnabled) this->ToCreature()->AI()->EnterEvadeMode(); return; } //m_ThreatManager.tauntFadeOut(taunter); target = m_ThreatManager.getHostilTarget(); if (target && target != taunter) { SetInFront(target); if (this->ToCreature()->IsAIEnabled) this->ToCreature()->AI()->AttackStart( target); } } //====================================================================== Unit* Creature::SelectVictim() { //function provides main threat functionality //next-victim-selection algorithm and evade mode are called //threat list sorting etc. Unit* target = NULL; // First checking if we have some taunt on us const AuraEffectList& tauntAuras = GetAuraEffectsByType( SPELL_AURA_MOD_TAUNT); if (!tauntAuras.empty()) { Unit* caster = tauntAuras.back()->GetCaster(); // The last taunt aura caster is alive an we are happy to attack him if (caster && caster->isAlive()) return getVictim(); else if (tauntAuras.size() > 1) { // We do not have last taunt aura caster but we have more taunt auras, // so find first available target // Auras are pushed_back, last caster will be on the end AuraEffectList::const_iterator aura = --tauntAuras.end(); do { --aura; caster = (*aura)->GetCaster(); if (caster && caster->IsInMap(this) && canAttack(caster) && caster->isInAccessiblePlaceFor(this->ToCreature())) { target = caster; break; } } while (aura != tauntAuras.begin()); } else target = getVictim(); } if (CanHaveThreatList()) { if (!target && !m_ThreatManager.isThreatListEmpty()) // No taunt aura or taunt aura caster is dead standard target selection target = m_ThreatManager.getHostilTarget(); } else if (!HasReactState(REACT_PASSIVE)) { // We have player pet probably target = getAttackerForHelper(); if (!target && isSummon()) { if (Unit * owner = this->ToTempSummon()->GetOwner()) { if (owner->isInCombat()) target = owner->getAttackerForHelper(); if (!target) { for (ControlList::const_iterator itr = owner->m_Controlled.begin(); itr != owner->m_Controlled.end(); ++itr) { if ((*itr)->isInCombat()) { target = (*itr)->getAttackerForHelper(); if (target) break; } } } } } } else return NULL; if (target && _IsTargetAcceptable(target)) { SetInFront(target); return target; } // last case when creature don't must go to evade mode: // it in combat but attacker not make any damage and not enter to aggro radius to have record in threat list // for example at owner command to pet attack some far away creature // Note: creature not have targeted movement generator but have attacker in this case for (AttackerSet::const_iterator itr = m_attackers.begin(); itr != m_attackers.end(); ++itr) { if ((*itr) && !canCreatureAttack(*itr) && (*itr)->GetTypeId() != TYPEID_PLAYER && !(*itr)->ToCreature()->HasUnitTypeMask( UNIT_MASK_CONTROLABLE_GUARDIAN)) return NULL; } // TODO: a vehicle may eat some mob, so mob should not evade if (GetVehicle()) return NULL; // search nearby enemy before enter evade mode if (HasReactState(REACT_AGGRESSIVE)) { target = SelectNearestTargetInAttackDistance(); if (target && _IsTargetAcceptable(target)) return target; } Unit::AuraEffectList const& iAuras = GetAuraEffectsByType( SPELL_AURA_MOD_INVISIBILITY); if (!iAuras.empty()) { for (Unit::AuraEffectList::const_iterator itr = iAuras.begin(); itr != iAuras.end(); ++itr) { if ((*itr)->GetBase()->IsPermanent()) { AI()->EnterEvadeMode(); break; } } return NULL; } // enter in evade mode in other case AI()->EnterEvadeMode(); return NULL; } //====================================================================== //====================================================================== //====================================================================== int32 Unit::ApplyEffectModifiers(SpellEntry const* spellProto, uint8 effect_index, int32 value) const { if (Player* modOwner = GetSpellModOwner()) { modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_ALL_EFFECTS, value); switch (effect_index) { case 0: modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_EFFECT1, value); break; case 1: modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_EFFECT2, value); break; case 2: modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_EFFECT3, value); break; } } return value; } // function uses real base points (typically value - 1) int32 Unit::CalculateSpellDamage(Unit const* target, SpellEntry const* spellProto, uint8 effect_index, int32 const* basePoints) const { return SpellMgr::CalculateSpellEffectAmount(spellProto, effect_index, this, basePoints, target); } int32 Unit::CalcSpellDuration(SpellEntry const* spellProto) { uint8 comboPoints = m_movedPlayer ? m_movedPlayer->GetComboPoints() : 0; int32 minduration = GetSpellDuration(spellProto); int32 maxduration = GetSpellMaxDuration(spellProto); int32 duration; if (comboPoints && minduration != -1 && minduration != maxduration) duration = minduration + int32((maxduration - minduration) * comboPoints / 5); else duration = minduration; return duration; } int32 Unit::ModSpellDuration(SpellEntry const* spellProto, Unit const* target, int32 duration, bool positive) { //don't mod permament auras duration if (duration < 0) return duration; //cut duration only of negative effects if (!positive) { int32 mechanic = GetAllSpellMechanicMask(spellProto); int32 durationMod; int32 durationMod_always = 0; int32 durationMod_not_stack = 0; for (uint8 i = 1; i <= MECHANIC_ENRAGED; ++i) { if (!(mechanic & 1 << i)) continue; // Find total mod value (negative bonus) int32 new_durationMod_always = target->GetTotalAuraModifierByMiscValue( SPELL_AURA_MECHANIC_DURATION_MOD, i); // Find max mod (negative bonus) int32 new_durationMod_not_stack = target->GetMaxNegativeAuraModifierByMiscValue( SPELL_AURA_MECHANIC_DURATION_MOD_NOT_STACK, i); // Check if mods applied before were weaker if (new_durationMod_always < durationMod_always) durationMod_always = new_durationMod_always; if (new_durationMod_not_stack < durationMod_not_stack) durationMod_not_stack = new_durationMod_not_stack; } // Select strongest negative mod if (durationMod_always > durationMod_not_stack) durationMod = durationMod_not_stack; else durationMod = durationMod_always; if (durationMod != 0) duration = int32( float(duration) * float(100.0f + durationMod) / 100.0f); // there are only negative mods currently durationMod_always = target->GetTotalAuraModifierByMiscValue( SPELL_AURA_MOD_AURA_DURATION_BY_DISPEL, spellProto->Dispel); durationMod_not_stack = target->GetMaxNegativeAuraModifierByMiscValue( SPELL_AURA_MOD_AURA_DURATION_BY_DISPEL_NOT_STACK, spellProto->Dispel); durationMod = 0; if (durationMod_always > durationMod_not_stack) durationMod += durationMod_not_stack; else durationMod += durationMod_always; if (durationMod != 0) duration = int32( float(duration) * float(100.0f + durationMod) / 100.0f); } else { //else positive mods here, there are no currently //when there will be, change GetTotalAuraModifierByMiscValue to GetTotalPositiveAuraModifierByMiscValue // Mixology - duration boost if (target->GetTypeId() == TYPEID_PLAYER) { if (spellProto->SpellFamilyName == SPELLFAMILY_POTION && (sSpellMgr->IsSpellMemberOfSpellGroup(spellProto->Id, SPELL_GROUP_ELIXIR_BATTLE) || sSpellMgr->IsSpellMemberOfSpellGroup( spellProto->Id, SPELL_GROUP_ELIXIR_GUARDIAN))) { if (target->HasAura(53042) && target->HasSpell(spellProto->EffectTriggerSpell [0])) duration *= 2; } } } // Glyphs which increase duration of selfcasted buffs if (target == this) { switch (spellProto->SpellFamilyName) { case SPELLFAMILY_DRUID: if (spellProto->SpellFamilyFlags [0] & 0x100) { // Glyph of Thorns if (AuraEffect * aurEff = GetAuraEffect(57862, 0)) duration += aurEff->GetAmount() * MINUTE * IN_MILLISECONDS; } break; case SPELLFAMILY_PALADIN: if (spellProto->SpellFamilyFlags [0] & 0x00000002) { // Glyph of Blessing of Might if (AuraEffect * aurEff = GetAuraEffect(57958, 0)) duration += aurEff->GetAmount() * MINUTE * IN_MILLISECONDS; } else if (spellProto->SpellFamilyFlags [0] & 0x00010000) { // Glyph of Blessing of Wisdom if (AuraEffect * aurEff = GetAuraEffect(57979, 0)) duration += aurEff->GetAmount() * MINUTE * IN_MILLISECONDS; } break; } } return duration > 0 ? duration : 0; } void Unit::ModSpellCastTime(SpellEntry const* spellProto, int32 & castTime, Spell * spell) { if (!spellProto || castTime < 0) return; //called from caster if (Player* modOwner = GetSpellModOwner()) modOwner->ApplySpellMod( spellProto->Id, SPELLMOD_CASTING_TIME, castTime, spell); if (!(spellProto->Attributes & (SPELL_ATTR0_UNK4 | SPELL_ATTR0_TRADESPELL)) && spellProto->SpellFamilyName) castTime = int32( float(castTime) * GetFloatValue(UNIT_MOD_CAST_SPEED)); else if (spellProto->Attributes & SPELL_ATTR0_REQ_AMMO && !(spellProto->AttributesEx2 & SPELL_ATTR2_AUTOREPEAT_FLAG)) castTime = int32(float(castTime) * m_modAttackSpeedPct [RANGED_ATTACK]); else if (spellProto->SpellVisual [0] == 3881 && HasAura(67556)) // cooking with Chef Hat. castTime = 500; } DiminishingLevels Unit::GetDiminishing(DiminishingGroup group) { for (Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i) { if (i->DRGroup != group) continue; if (!i->hitCount) return DIMINISHING_LEVEL_1; if (!i->hitTime) return DIMINISHING_LEVEL_1; // If last spell was casted more than 15 seconds ago - reset the count. if (i->stack == 0 && getMSTimeDiff(i->hitTime, getMSTime()) > 15000) { i->hitCount = DIMINISHING_LEVEL_1; return DIMINISHING_LEVEL_1; } // or else increase the count. else return DiminishingLevels(i->hitCount); } return DIMINISHING_LEVEL_1; } void Unit::IncrDiminishing(DiminishingGroup group) { // Checking for existing in the table for (Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i) { if (i->DRGroup != group) continue; if (int32(i->hitCount) < GetDiminishingReturnsMaxLevel(group)) i->hitCount += 1; return; } m_Diminishing.push_back( DiminishingReturn(group, getMSTime(), DIMINISHING_LEVEL_2)); } float Unit::ApplyDiminishingToDuration(DiminishingGroup group, int32 &duration, Unit *caster, DiminishingLevels Level, int32 limitduration) { if (duration == -1 || group == DIMINISHING_NONE) return 1.0f; // test pet/charm masters instead pets/charmeds Unit const* targetOwner = GetCharmerOrOwner(); Unit const* casterOwner = caster->GetCharmerOrOwner(); // Duration of crowd control abilities on pvp target is limited by 10 sec. (2.2.0) if (limitduration > 0 && duration > limitduration) { Unit const* target = targetOwner ? targetOwner : this; Unit const* source = casterOwner ? casterOwner : caster; if ((target->GetTypeId() == TYPEID_PLAYER || ((Creature*) target)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_ALL_DIMINISH) && source->GetTypeId() == TYPEID_PLAYER) duration = limitduration; } float mod = 1.0f; if (group == DIMINISHING_TAUNT) { if (GetTypeId() == TYPEID_UNIT && (((Creature*) this)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_TAUNT_DIMINISH)) { DiminishingLevels diminish = Level; switch (diminish) { case DIMINISHING_LEVEL_1: break; case DIMINISHING_LEVEL_2: mod = 0.65f; break; case DIMINISHING_LEVEL_3: mod = 0.4225f; break; case DIMINISHING_LEVEL_4: mod = 0.274625f; break; case DIMINISHING_LEVEL_TAUNT_IMMUNE: mod = 0.0f; break; default: break; } } } // Some diminishings applies to mobs too (for example, Stun) else if ((GetDiminishingReturnsGroupType(group) == DRTYPE_PLAYER && ((targetOwner ? (targetOwner->GetTypeId() == TYPEID_PLAYER) : (GetTypeId() == TYPEID_PLAYER)) || (GetTypeId() == TYPEID_UNIT && ((Creature*) this)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_ALL_DIMINISH))) || GetDiminishingReturnsGroupType(group) == DRTYPE_ALL) { DiminishingLevels diminish = Level; switch (diminish) { case DIMINISHING_LEVEL_1: break; case DIMINISHING_LEVEL_2: mod = 0.5f; break; case DIMINISHING_LEVEL_3: mod = 0.25f; break; case DIMINISHING_LEVEL_IMMUNE: mod = 0.0f; break; default: break; } } duration = int32(duration * mod); return mod; } void Unit::ApplyDiminishingAura(DiminishingGroup group, bool apply) { // Checking for existing in the table for (Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i) { if (i->DRGroup != group) continue; if (apply) i->stack += 1; else if (i->stack) { i->stack -= 1; // Remember time after last aura from group removed if (i->stack == 0) i->hitTime = getMSTime(); } break; } } uint32 Unit::GetSpellMaxRangeForTarget(Unit* target, const SpellRangeEntry * rangeEntry) { if (!rangeEntry) return 0; if (rangeEntry->maxRangeHostile == rangeEntry->maxRangeFriend) return uint32( rangeEntry->maxRangeFriend); if (IsHostileTo(target)) return uint32(rangeEntry->maxRangeHostile); return uint32(rangeEntry->maxRangeFriend); } ; uint32 Unit::GetSpellMinRangeForTarget(Unit* target, const SpellRangeEntry * rangeEntry) { if (!rangeEntry) return 0; if (rangeEntry->minRangeHostile == rangeEntry->minRangeFriend) return uint32( rangeEntry->minRangeFriend); if (IsHostileTo(target)) return uint32(rangeEntry->minRangeHostile); return uint32(rangeEntry->minRangeFriend); } ; uint32 Unit::GetSpellRadiusForTarget(Unit* target, const SpellRadiusEntry * radiusEntry) { if (!radiusEntry) return 0; if (radiusEntry->radiusHostile == radiusEntry->radiusFriend) return uint32( radiusEntry->radiusFriend); if (IsHostileTo(target)) return uint32(radiusEntry->radiusHostile); return uint32(radiusEntry->radiusFriend); } ; Unit* Unit::GetUnit(WorldObject& object, uint64 guid) { return ObjectAccessor::GetUnit(object, guid); } Player* Unit::GetPlayer(WorldObject& object, uint64 guid) { return ObjectAccessor::GetPlayer(object, guid); } Creature* Unit::GetCreature(WorldObject& object, uint64 guid) { return object.GetMap()->GetCreature(guid); } uint32 Unit::GetCreatureType() const { if (GetTypeId() == TYPEID_PLAYER) { ShapeshiftForm form = GetShapeshiftForm(); SpellShapeshiftFormEntry const* ssEntry = sSpellShapeshiftFormStore.LookupEntry(form); if (ssEntry && ssEntry->creatureType > 0) return ssEntry->creatureType; else return CREATURE_TYPE_HUMANOID; } else return this->ToCreature()->GetCreatureInfo()->type; } /*####################################### ######## ######## ######## STAT SYSTEM ######## ######## ######## #######################################*/ bool Unit::HandleStatModifier(UnitMods unitMod, UnitModifierType modifierType, float amount, bool apply) { if (unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END) { sLog->outError( "ERROR in HandleStatModifier(): non existed UnitMods or wrong UnitModifierType!"); return false; } switch (modifierType) { case BASE_VALUE: case TOTAL_VALUE: m_auraModifiersGroup [unitMod] [modifierType] += apply ? amount : -amount; break; case BASE_PCT: case TOTAL_PCT: m_auraModifiersGroup [unitMod] [modifierType] += ( apply ? amount : -amount) / 100.0f; break; default: break; } if (!CanModifyStats()) return false; switch (unitMod) { case UNIT_MOD_STAT_STRENGTH: case UNIT_MOD_STAT_AGILITY: case UNIT_MOD_STAT_STAMINA: case UNIT_MOD_STAT_INTELLECT: case UNIT_MOD_STAT_SPIRIT: UpdateStats(GetStatByAuraGroup(unitMod)); break; case UNIT_MOD_ARMOR: UpdateArmor(); break; case UNIT_MOD_HEALTH: UpdateMaxHealth(); break; case UNIT_MOD_MANA: case UNIT_MOD_RAGE: case UNIT_MOD_FOCUS: case UNIT_MOD_ENERGY: case UNIT_MOD_HAPPINESS: case UNIT_MOD_RUNE: case UNIT_MOD_RUNIC_POWER: UpdateMaxPower(GetPowerTypeByAuraGroup(unitMod)); break; case UNIT_MOD_RESISTANCE_HOLY: case UNIT_MOD_RESISTANCE_FIRE: case UNIT_MOD_RESISTANCE_NATURE: case UNIT_MOD_RESISTANCE_FROST: case UNIT_MOD_RESISTANCE_SHADOW: case UNIT_MOD_RESISTANCE_ARCANE: UpdateResistances(GetSpellSchoolByAuraGroup(unitMod)); break; case UNIT_MOD_ATTACK_POWER_POS: case UNIT_MOD_ATTACK_POWER_NEG: UpdateAttackPowerAndDamage(); break; case UNIT_MOD_ATTACK_POWER_RANGED_POS: case UNIT_MOD_ATTACK_POWER_RANGED_NEG: UpdateAttackPowerAndDamage(true); break; case UNIT_MOD_DAMAGE_MAINHAND: UpdateDamagePhysical(BASE_ATTACK); break; case UNIT_MOD_DAMAGE_OFFHAND: UpdateDamagePhysical(OFF_ATTACK); break; case UNIT_MOD_DAMAGE_RANGED: UpdateDamagePhysical(RANGED_ATTACK); break; default: break; } return true; } float Unit::GetModifierValue(UnitMods unitMod, UnitModifierType modifierType) const { if (unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END) { sLog->outError( "trial to access non existed modifier value from UnitMods!"); return 0.0f; } if (modifierType == TOTAL_PCT && m_auraModifiersGroup [unitMod] [modifierType] <= 0.0f) return 0.0f; return m_auraModifiersGroup [unitMod] [modifierType]; } float Unit::GetTotalStatValue(Stats stat) const { UnitMods unitMod = UnitMods(UNIT_MOD_STAT_START + stat); if (m_auraModifiersGroup [unitMod] [TOTAL_PCT] <= 0.0f) return 0.0f; // value = ((base_value * base_pct) + total_value) * total_pct float value = m_auraModifiersGroup [unitMod] [BASE_VALUE] + GetCreateStat(stat); value *= m_auraModifiersGroup [unitMod] [BASE_PCT]; value += m_auraModifiersGroup [unitMod] [TOTAL_VALUE]; value *= m_auraModifiersGroup [unitMod] [TOTAL_PCT]; return value; } float Unit::GetTotalAuraModValue(UnitMods unitMod) const { if (unitMod >= UNIT_MOD_END) { sLog->outError( "trial to access non existed UnitMods in GetTotalAuraModValue()!"); return 0.0f; } if (m_auraModifiersGroup [unitMod] [TOTAL_PCT] <= 0.0f) return 0.0f; float value = m_auraModifiersGroup [unitMod] [BASE_VALUE]; value *= m_auraModifiersGroup [unitMod] [BASE_PCT]; value += m_auraModifiersGroup [unitMod] [TOTAL_VALUE]; value *= m_auraModifiersGroup [unitMod] [TOTAL_PCT]; return value; } SpellSchools Unit::GetSpellSchoolByAuraGroup(UnitMods unitMod) const { SpellSchools school = SPELL_SCHOOL_NORMAL; switch (unitMod) { case UNIT_MOD_RESISTANCE_HOLY: school = SPELL_SCHOOL_HOLY; break; case UNIT_MOD_RESISTANCE_FIRE: school = SPELL_SCHOOL_FIRE; break; case UNIT_MOD_RESISTANCE_NATURE: school = SPELL_SCHOOL_NATURE; break; case UNIT_MOD_RESISTANCE_FROST: school = SPELL_SCHOOL_FROST; break; case UNIT_MOD_RESISTANCE_SHADOW: school = SPELL_SCHOOL_SHADOW; break; case UNIT_MOD_RESISTANCE_ARCANE: school = SPELL_SCHOOL_ARCANE; break; default: break; } return school; } Stats Unit::GetStatByAuraGroup(UnitMods unitMod) const { Stats stat = STAT_STRENGTH; switch (unitMod) { case UNIT_MOD_STAT_STRENGTH: stat = STAT_STRENGTH; break; case UNIT_MOD_STAT_AGILITY: stat = STAT_AGILITY; break; case UNIT_MOD_STAT_STAMINA: stat = STAT_STAMINA; break; case UNIT_MOD_STAT_INTELLECT: stat = STAT_INTELLECT; break; case UNIT_MOD_STAT_SPIRIT: stat = STAT_SPIRIT; break; default: break; } return stat; } Powers Unit::GetPowerTypeByAuraGroup(UnitMods unitMod) const { switch (unitMod) { case UNIT_MOD_RAGE: return POWER_RAGE; case UNIT_MOD_FOCUS: return POWER_FOCUS; case UNIT_MOD_ENERGY: return POWER_ENERGY; case UNIT_MOD_HAPPINESS: return POWER_HAPPINESS; case UNIT_MOD_RUNE: return POWER_RUNE; case UNIT_MOD_RUNIC_POWER: return POWER_RUNIC_POWER; default: case UNIT_MOD_MANA: return POWER_MANA; } } float Unit::GetTotalAttackPowerValue(WeaponAttackType attType) const { if (attType == RANGED_ATTACK) { int32 ap = GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MOD_POS) - GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MOD_NEG); if (ap < 0) return 0.0f; return ap * (1.0f + GetFloatValue( UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER)); } else { int32 ap = GetInt32Value(UNIT_FIELD_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_ATTACK_POWER_MOD_POS) - GetInt32Value(UNIT_FIELD_ATTACK_POWER_MOD_NEG); if (ap < 0) return 0.0f; return ap * (1.0f + GetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER)); } } float Unit::GetWeaponDamageRange(WeaponAttackType attType, WeaponDamageRange type) const { if (attType == OFF_ATTACK && !haveOffhandWeapon()) return 0.0f; return m_weaponDamage [attType] [type]; } void Unit::SetLevel(uint8 lvl) { SetUInt32Value(UNIT_FIELD_LEVEL, lvl); // group update if (GetTypeId() == TYPEID_PLAYER && this->ToPlayer()->GetGroup()) this->ToPlayer()->SetGroupUpdateFlag( GROUP_UPDATE_FLAG_LEVEL); } void Unit::SetHealth(uint32 val) { if (getDeathState() == JUST_DIED) val = 0; else if (GetTypeId() == TYPEID_PLAYER && (getDeathState() == DEAD || getDeathState() == DEAD_FALLING)) val = 1; else { uint32 maxHealth = GetMaxHealth(); if (maxHealth < val) val = maxHealth; } SetUInt32Value(UNIT_FIELD_HEALTH, val); // group update if (GetTypeId() == TYPEID_PLAYER) { if (this->ToPlayer()->GetGroup()) this->ToPlayer()->SetGroupUpdateFlag( GROUP_UPDATE_FLAG_CUR_HP); } else if (this->ToCreature()->isPet()) { Pet *pet = ((Pet*) this); if (pet->isControlled()) { Unit *owner = GetOwner(); if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && owner->ToPlayer()->GetGroup()) owner->ToPlayer()->SetGroupUpdateFlag( GROUP_UPDATE_FLAG_PET_CUR_HP); } } } void Unit::SetMaxHealth(uint32 val) { if (!val) val = 1; uint32 health = GetHealth(); SetUInt32Value(UNIT_FIELD_MAXHEALTH, val); // group update if (GetTypeId() == TYPEID_PLAYER) { if (this->ToPlayer()->GetGroup()) this->ToPlayer()->SetGroupUpdateFlag( GROUP_UPDATE_FLAG_MAX_HP); } else if (this->ToCreature()->isPet()) { Pet *pet = ((Pet*) this); if (pet->isControlled()) { Unit *owner = GetOwner(); if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && owner->ToPlayer()->GetGroup()) owner->ToPlayer()->SetGroupUpdateFlag( GROUP_UPDATE_FLAG_PET_MAX_HP); } } if (val < health) SetHealth(val); } void Unit::SetPower(Powers power, uint32 val) { if (GetPower(power) == val) return; uint32 maxPower = GetMaxPower(power); if (maxPower < val) val = maxPower; SetStatInt32Value(UNIT_FIELD_POWER1 + power, val); WorldPacket data(SMSG_POWER_UPDATE); data.append(GetPackGUID()); data << uint32(1); // count of updates. uint8 and uint32 for each data << uint8(power); data << uint32(val); SendMessageToSet(&data, GetTypeId() == TYPEID_PLAYER ? true : false); // group update if (GetTypeId() == TYPEID_PLAYER) { if (this->ToPlayer()->GetGroup()) this->ToPlayer()->SetGroupUpdateFlag( GROUP_UPDATE_FLAG_CUR_POWER); } else if (this->ToCreature()->isPet()) { Pet *pet = ((Pet*) this); if (pet->isControlled()) { Unit *owner = GetOwner(); if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && owner->ToPlayer()->GetGroup()) owner->ToPlayer()->SetGroupUpdateFlag( GROUP_UPDATE_FLAG_PET_CUR_POWER); } // Update the pet's character sheet with happiness damage bonus if (pet->getPetType() == HUNTER_PET && power == POWER_HAPPINESS) pet->UpdateDamagePhysical( BASE_ATTACK); } } void Unit::SetMaxPower(Powers power, uint32 val) { uint32 cur_power = GetPower(power); SetStatInt32Value(UNIT_FIELD_MAXPOWER1 + power, val); // group update if (GetTypeId() == TYPEID_PLAYER) { if (this->ToPlayer()->GetGroup()) this->ToPlayer()->SetGroupUpdateFlag( GROUP_UPDATE_FLAG_MAX_POWER); } else if (this->ToCreature()->isPet()) { Pet *pet = ((Pet*) this); if (pet->isControlled()) { Unit *owner = GetOwner(); if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && owner->ToPlayer()->GetGroup()) owner->ToPlayer()->SetGroupUpdateFlag( GROUP_UPDATE_FLAG_PET_MAX_POWER); } } if (val < cur_power) SetPower(power, val); } uint32 Unit::GetCreatePowers(Powers power) const { // POWER_FOCUS and POWER_HAPPINESS only have hunter pet switch (power) { case POWER_MANA: if (getClass() == CLASS_HUNTER || getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE || getClass() == CLASS_DEATH_KNIGHT) return false; else return GetCreateMana(); case POWER_RAGE: return 1000; case POWER_FOCUS: if (GetTypeId() == TYPEID_PLAYER && (ToPlayer()->getClass() == CLASS_HUNTER)) return 100; return (GetTypeId() == TYPEID_PLAYER || !((Creature const*) this)->isPet() || ((Pet const*) this)->getPetType() != HUNTER_PET ? 0 : 100); case POWER_ENERGY: return 100; case POWER_HAPPINESS: return (GetTypeId() == TYPEID_PLAYER || !((Creature const*) this)->isPet() || ((Pet const*) this)->getPetType() != HUNTER_PET ? 0 : 1050000); case POWER_RUNE: return (GetTypeId() == TYPEID_PLAYER && ((Player const*) this)->getClass() == CLASS_DEATH_KNIGHT ? 8 : 0); case POWER_RUNIC_POWER: return (GetTypeId() == TYPEID_PLAYER && ((Player const*) this)->getClass() == CLASS_DEATH_KNIGHT ? 1000 : 0); case POWER_SOUL_SHARDS: return (GetTypeId() == TYPEID_PLAYER && ((Player const*) this)->getClass() == CLASS_WARLOCK ? 3 : 0); case POWER_ECLIPSE: return (GetTypeId() == TYPEID_PLAYER && ((Player const*) this)->getClass() == CLASS_DRUID ? 100 : 0); case POWER_HOLY_POWER: return (GetTypeId() == TYPEID_PLAYER && ((Player const*) this)->getClass() == CLASS_PALADIN ? 3 : 0); case POWER_HEALTH: return 0; default: break; } return 0; } void Unit::AddToWorld() { if (!IsInWorld()) { WorldObject::AddToWorld(); } } void Unit::RemoveFromWorld() { // cleanup ASSERT(GetGUID()); if (IsInWorld()) { m_duringRemoveFromWorld = true; if (IsVehicle()) GetVehicleKit()->Uninstall(); RemoveCharmAuras(); RemoveBindSightAuras(); RemoveNotOwnSingleTargetAuras(); RemoveAllGameObjects(); RemoveAllDynObjects(); ExitVehicle(); UnsummonAllTotems(); RemoveAllControlled(); RemoveAreaAurasDueToLeaveWorld(); if (GetCharmerGUID()) { sLog->outCrash("Unit %u has charmer guid when removed from world", GetEntry()); ASSERT(false); } if (Unit *owner = GetOwner()) { if (owner->m_Controlled.find(this) != owner->m_Controlled.end()) { sLog->outCrash( "Unit %u is in controlled list of %u when removed from world", GetEntry(), owner->GetEntry()); ASSERT(false); } } WorldObject::RemoveFromWorld(); m_duringRemoveFromWorld = false; } } void Unit::CleanupsBeforeDelete(bool finalCleanup) { // This needs to be before RemoveFromWorld to make GetCaster() return a valid pointer on aura removal InterruptNonMeleeSpells(true); if (IsInWorld()) RemoveFromWorld(); ASSERT(GetGUID()); //A unit may be in removelist and not in world, but it is still in grid //and may have some references during delete RemoveAllAuras(); RemoveAllGameObjects(); if (finalCleanup) m_cleanupDone = true; m_Events.KillAllEvents(false); // non-delatable (currently casted spells) will not deleted now but it will deleted at call in Map::RemoveAllObjectsInRemoveList CombatStop(); ClearComboPointHolders(); DeleteThreatList(); getHostileRefManager().setOnlineOfflineState(false); GetMotionMaster()->Clear(false); // remove different non-standard movement generators. if (Creature* thisCreature = ToCreature()) if (GetTransport()) GetTransport()->RemovePassenger( thisCreature); } void Unit::UpdateCharmAI() { if (GetTypeId() == TYPEID_PLAYER) return; if (i_disabledAI) // disabled AI must be primary AI { if (!isCharmed()) { delete i_AI; i_AI = i_disabledAI; i_disabledAI = NULL; } } else { if (isCharmed()) { i_disabledAI = i_AI; if (isPossessed() || IsVehicle()) i_AI = new PossessedAI( this->ToCreature()); else i_AI = new PetAI(this->ToCreature()); } } } CharmInfo* Unit::InitCharmInfo() { if (!m_charmInfo) m_charmInfo = new CharmInfo(this); return m_charmInfo; } void Unit::DeleteCharmInfo() { if (!m_charmInfo) return; m_charmInfo->RestoreState(); delete m_charmInfo; m_charmInfo = NULL; } CharmInfo::CharmInfo(Unit* unit) : m_unit(unit), m_CommandState(COMMAND_FOLLOW), m_petnumber(0), m_barInit( false), m_isCommandAttack(false), m_isAtStay(false), m_isFollowing( false), m_isReturning(false) { for (uint8 i = 0; i < MAX_SPELL_CHARM; ++i) m_charmspells [i].SetActionAndType(0, ACT_DISABLED); if (m_unit->GetTypeId() == TYPEID_UNIT) { m_oldReactState = m_unit->ToCreature()->GetReactState(); m_unit->ToCreature()->SetReactState(REACT_PASSIVE); } } CharmInfo::~CharmInfo() { } void CharmInfo::RestoreState() { if (m_unit->GetTypeId() == TYPEID_UNIT) if (Creature *pCreature = m_unit->ToCreature()) pCreature->SetReactState( m_oldReactState); } void CharmInfo::InitPetActionBar() { // the first 3 SpellOrActions are attack, follow and stay for (uint32 i = 0; i < ACTION_BAR_INDEX_PET_SPELL_START - ACTION_BAR_INDEX_START; ++i) SetActionBar(ACTION_BAR_INDEX_START + i, COMMAND_ATTACK - i, ACT_COMMAND); // middle 4 SpellOrActions are spells/special attacks/abilities for (uint32 i = 0; i < ACTION_BAR_INDEX_PET_SPELL_END - ACTION_BAR_INDEX_PET_SPELL_START; ++i) SetActionBar(ACTION_BAR_INDEX_PET_SPELL_START + i, 0, ACT_PASSIVE); // last 3 SpellOrActions are reactions for (uint32 i = 0; i < ACTION_BAR_INDEX_END - ACTION_BAR_INDEX_PET_SPELL_END; ++i) SetActionBar(ACTION_BAR_INDEX_PET_SPELL_END + i, COMMAND_ATTACK - i, ACT_REACTION); } void CharmInfo::InitEmptyActionBar(bool withAttack) { if (withAttack) SetActionBar(ACTION_BAR_INDEX_START, COMMAND_ATTACK, ACT_COMMAND); else SetActionBar(ACTION_BAR_INDEX_START, 0, ACT_PASSIVE); for (uint32 x = ACTION_BAR_INDEX_START + 1; x < ACTION_BAR_INDEX_END; ++x) SetActionBar(x, 0, ACT_PASSIVE); } void CharmInfo::InitPossessCreateSpells() { InitEmptyActionBar(); if (m_unit->GetTypeId() == TYPEID_UNIT) { for (uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i) { uint32 spellId = m_unit->ToCreature()->m_spells [i]; SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId); if (spellInfo && spellInfo->Attributes & SPELL_ATTR0_CASTABLE_WHILE_DEAD) spellId = 0; if (IsPassiveSpell(spellId)) m_unit->CastSpell(m_unit, spellId, true); else AddSpellToActionBar(m_unit->ToCreature()->m_spells [i], ACT_PASSIVE); } } } void CharmInfo::InitCharmCreateSpells() { if (m_unit->GetTypeId() == TYPEID_PLAYER) //charmed players don't have spells { InitEmptyActionBar(); return; } InitPetActionBar(); for (uint32 x = 0; x < MAX_SPELL_CHARM; ++x) { uint32 spellId = m_unit->ToCreature()->m_spells [x]; SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId); if (spellInfo && spellInfo->Attributes & SPELL_ATTR0_CASTABLE_WHILE_DEAD) spellId = 0; if (!spellId) { m_charmspells [x].SetActionAndType(spellId, ACT_DISABLED); continue; } if (IsPassiveSpell(spellId)) { m_unit->CastSpell(m_unit, spellId, true); m_charmspells [x].SetActionAndType(spellId, ACT_PASSIVE); } else { m_charmspells [x].SetActionAndType(spellId, ACT_DISABLED); ActiveStates newstate = ACT_PASSIVE; if (spellInfo) { if (!IsAutocastableSpell(spellId)) newstate = ACT_PASSIVE; else { bool autocast = false; for (uint32 i = 0; i < MAX_SPELL_EFFECTS && !autocast; ++i) if (SpellTargetType [spellInfo->EffectImplicitTargetA [i]] == TARGET_TYPE_UNIT_TARGET) autocast = true; if (autocast) { newstate = ACT_ENABLED; ToggleCreatureAutocast(spellId, true); } else newstate = ACT_DISABLED; } } AddSpellToActionBar(spellId, newstate); } } } bool CharmInfo::AddSpellToActionBar(uint32 spell_id, ActiveStates newstate) { uint32 first_id = sSpellMgr->GetFirstSpellInChain(spell_id); // new spell rank can be already listed for (uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i) { if (uint32 action = PetActionBar[i].GetAction()) { if (PetActionBar [i].IsActionBarForSpell() && sSpellMgr->GetFirstSpellInChain(action) == first_id) { PetActionBar [i].SetAction(spell_id); return true; } } } // or use empty slot in other case for (uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i) { if (!PetActionBar [i].GetAction() && PetActionBar [i].IsActionBarForSpell()) { SetActionBar( i, spell_id, newstate == ACT_DECIDE ? IsAutocastableSpell(spell_id) ? ACT_DISABLED : ACT_PASSIVE : newstate); return true; } } return false; } bool CharmInfo::RemoveSpellFromActionBar(uint32 spell_id) { uint32 first_id = sSpellMgr->GetFirstSpellInChain(spell_id); for (uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i) { if (uint32 action = PetActionBar[i].GetAction()) { if (PetActionBar [i].IsActionBarForSpell() && sSpellMgr->GetFirstSpellInChain(action) == first_id) { SetActionBar(i, 0, ACT_PASSIVE); return true; } } } return false; } void CharmInfo::ToggleCreatureAutocast(uint32 spellid, bool apply) { if (IsPassiveSpell(spellid)) return; for (uint32 x = 0; x < MAX_SPELL_CHARM; ++x) if (spellid == m_charmspells [x].GetAction()) m_charmspells [x].SetType( apply ? ACT_ENABLED : ACT_DISABLED); } void CharmInfo::SetPetNumber(uint32 petnumber, bool statwindow) { m_petnumber = petnumber; if (statwindow) m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, m_petnumber); else m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, 0); } void CharmInfo::LoadPetActionBar(const std::string& data) { InitPetActionBar(); Tokens tokens(data, ' '); if (tokens.size() != (ACTION_BAR_INDEX_END - ACTION_BAR_INDEX_START) * 2) return; // non critical, will reset to default uint8 index; Tokens::iterator iter; for (iter = tokens.begin(), index = ACTION_BAR_INDEX_START; index < ACTION_BAR_INDEX_END; ++iter, ++index) { // use unsigned cast to avoid sign negative format use at long-> ActiveStates (int) conversion ActiveStates type = ActiveStates(atol(*iter)); ++iter; uint32 action = uint32(atol(*iter)); PetActionBar [index].SetActionAndType(action, type); // check correctness if (PetActionBar [index].IsActionBarForSpell()) { if (!sSpellStore.LookupEntry(PetActionBar [index].GetAction())) SetActionBar( index, 0, ACT_PASSIVE); else if (!IsAutocastableSpell(PetActionBar [index].GetAction())) SetActionBar( index, PetActionBar [index].GetAction(), ACT_PASSIVE); } } } void CharmInfo::BuildActionBar(WorldPacket* data) { for (uint32 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i) *data << uint32(PetActionBar [i].packedData); } void CharmInfo::SetSpellAutocast(uint32 spell_id, bool state) { for (uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i) { if (spell_id == PetActionBar [i].GetAction() && PetActionBar [i].IsActionBarForSpell()) { PetActionBar [i].SetType(state ? ACT_ENABLED : ACT_DISABLED); break; } } } bool Unit::isFrozen() const { return HasAuraState(AURA_STATE_FROZEN); } struct ProcTriggeredData { ProcTriggeredData(Aura* _aura) : aura(_aura) { effMask = 0; spellProcEvent = NULL; } SpellProcEventEntry const *spellProcEvent; Aura * aura; uint32 effMask; }; typedef std::list <ProcTriggeredData> ProcTriggeredList; // List of auras that CAN be trigger but may not exist in spell_proc_event // in most case need for drop charges // in some types of aura need do additional check // for example SPELL_AURA_MECHANIC_IMMUNITY - need check for mechanic bool InitTriggerAuraData() { for (uint16 i = 0; i < TOTAL_AURAS; ++i) { isTriggerAura [i] = false; isNonTriggerAura [i] = false; isAlwaysTriggeredAura [i] = false; } isTriggerAura [SPELL_AURA_DUMMY] = true; isTriggerAura [SPELL_AURA_MOD_CONFUSE] = true; isTriggerAura [SPELL_AURA_MOD_THREAT] = true; isTriggerAura [SPELL_AURA_MOD_STUN] = true; // Aura not have charges but need remove him on trigger isTriggerAura [SPELL_AURA_MOD_DAMAGE_DONE] = true; isTriggerAura [SPELL_AURA_MOD_DAMAGE_TAKEN] = true; isTriggerAura [SPELL_AURA_MOD_RESISTANCE] = true; isTriggerAura [SPELL_AURA_MOD_STEALTH] = true; isTriggerAura [SPELL_AURA_MOD_FEAR] = true; // Aura not have charges but need remove him on trigger isTriggerAura [SPELL_AURA_MOD_ROOT] = true; isTriggerAura [SPELL_AURA_TRANSFORM] = true; isTriggerAura [SPELL_AURA_REFLECT_SPELLS] = true; isTriggerAura [SPELL_AURA_DAMAGE_IMMUNITY] = true; isTriggerAura [SPELL_AURA_PROC_TRIGGER_SPELL] = true; isTriggerAura [SPELL_AURA_PROC_TRIGGER_DAMAGE] = true; isTriggerAura [SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK] = true; isTriggerAura [SPELL_AURA_SCHOOL_ABSORB] = true; // Savage Defense untested isTriggerAura [SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT] = true; isTriggerAura [SPELL_AURA_MOD_POWER_COST_SCHOOL] = true; isTriggerAura [SPELL_AURA_REFLECT_SPELLS_SCHOOL] = true; isTriggerAura [SPELL_AURA_MECHANIC_IMMUNITY] = true; isTriggerAura [SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN] = true; isTriggerAura [SPELL_AURA_SPELL_MAGNET] = true; isTriggerAura [SPELL_AURA_MOD_ATTACK_POWER] = true; isTriggerAura [SPELL_AURA_ADD_CASTER_HIT_TRIGGER] = true; isTriggerAura [SPELL_AURA_OVERRIDE_CLASS_SCRIPTS] = true; isTriggerAura [SPELL_AURA_MOD_MECHANIC_RESISTANCE] = true; isTriggerAura [SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS] = true; isTriggerAura [SPELL_AURA_MOD_MELEE_HASTE] = true; isTriggerAura [SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE] = true; isTriggerAura [SPELL_AURA_RAID_PROC_FROM_CHARGE] = true; isTriggerAura [SPELL_AURA_RAID_PROC_FROM_CHARGE_WITH_VALUE] = true; isTriggerAura [SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE] = true; isTriggerAura [SPELL_AURA_MOD_DAMAGE_FROM_CASTER] = true; isTriggerAura [SPELL_AURA_MOD_SPELL_CRIT_CHANCE] = true; isTriggerAura [SPELL_AURA_ABILITY_IGNORE_AURASTATE] = true; isNonTriggerAura [SPELL_AURA_MOD_POWER_REGEN] = true; isNonTriggerAura [SPELL_AURA_REDUCE_PUSHBACK] = true; isAlwaysTriggeredAura [SPELL_AURA_OVERRIDE_CLASS_SCRIPTS] = true; isAlwaysTriggeredAura [SPELL_AURA_MOD_FEAR] = true; isAlwaysTriggeredAura [SPELL_AURA_MOD_ROOT] = true; isAlwaysTriggeredAura [SPELL_AURA_MOD_STUN] = true; isAlwaysTriggeredAura [SPELL_AURA_TRANSFORM] = true; isAlwaysTriggeredAura [SPELL_AURA_SPELL_MAGNET] = true; isAlwaysTriggeredAura [SPELL_AURA_SCHOOL_ABSORB] = true; isAlwaysTriggeredAura [SPELL_AURA_MOD_STEALTH] = true; return true; } uint32 createProcExtendMask(SpellNonMeleeDamage *damageInfo, SpellMissInfo missCondition) { uint32 procEx = PROC_EX_NONE; // Check victim state if (missCondition != SPELL_MISS_NONE) switch (missCondition) { case SPELL_MISS_MISS: procEx |= PROC_EX_MISS; break; case SPELL_MISS_RESIST: procEx |= PROC_EX_RESIST; break; case SPELL_MISS_DODGE: procEx |= PROC_EX_DODGE; break; case SPELL_MISS_PARRY: procEx |= PROC_EX_PARRY; break; case SPELL_MISS_BLOCK: procEx |= PROC_EX_BLOCK; break; case SPELL_MISS_EVADE: procEx |= PROC_EX_EVADE; break; case SPELL_MISS_IMMUNE: procEx |= PROC_EX_IMMUNE; break; case SPELL_MISS_IMMUNE2: procEx |= PROC_EX_IMMUNE; break; case SPELL_MISS_DEFLECT: procEx |= PROC_EX_DEFLECT; break; case SPELL_MISS_ABSORB: procEx |= PROC_EX_ABSORB; break; case SPELL_MISS_REFLECT: procEx |= PROC_EX_REFLECT; break; default: break; } else { // On block if (damageInfo->blocked) procEx |= PROC_EX_BLOCK; // On absorb if (damageInfo->absorb) procEx |= PROC_EX_ABSORB; // On crit if (damageInfo->HitInfo & SPELL_HIT_TYPE_CRIT) procEx |= PROC_EX_CRITICAL_HIT; else procEx |= PROC_EX_NORMAL_HIT; } return procEx; } void Unit::ProcDamageAndSpellFor(bool isVictim, Unit * pTarget, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, SpellEntry const * procSpell, uint32 damage, SpellEntry const * procAura) { // Player is loading now - do not allow passive spell casts to proc if (GetTypeId() == TYPEID_PLAYER && this->ToPlayer()->GetSession()->PlayerLoading()) return; // For melee/ranged based attack need update skills and set some Aura states if victim present if (procFlag & MELEE_BASED_TRIGGER_MASK && pTarget) { // Update skills here for players if (GetTypeId() == TYPEID_PLAYER) { // On melee based hit/miss/resist need update skill (for victim and attacker) if (procExtra & (PROC_EX_NORMAL_HIT | PROC_EX_MISS | PROC_EX_RESIST)) { if (pTarget->GetTypeId() != TYPEID_PLAYER && pTarget->GetCreatureType() != CREATURE_TYPE_CRITTER) this->ToPlayer()->UpdateCombatSkills( pTarget, attType, isVictim); } // Update defence if player is victim and parry/dodge/block else if (isVictim && procExtra & (PROC_EX_DODGE | PROC_EX_PARRY | PROC_EX_BLOCK)) this->ToPlayer()->UpdateCombatSkills( pTarget, attType, true); } // If exist crit/parry/dodge/block need update aura state (for victim and attacker) if (procExtra & (PROC_EX_CRITICAL_HIT | PROC_EX_PARRY | PROC_EX_DODGE | PROC_EX_BLOCK)) { // for victim if (isVictim) { // if victim and dodge attack if (procExtra & PROC_EX_DODGE) { //Update AURA_STATE on dodge if (getClass() != CLASS_ROGUE) // skip Rogue Riposte { ModifyAuraState(AURA_STATE_DEFENSE, true); StartReactiveTimer(REACTIVE_DEFENSE); } } // if victim and parry attack if (procExtra & PROC_EX_PARRY) { // For Hunters only Counterattack (skip Mongoose bite) if (getClass() == CLASS_HUNTER) { ModifyAuraState(AURA_STATE_HUNTER_PARRY, true); StartReactiveTimer(REACTIVE_HUNTER_PARRY); } else { ModifyAuraState(AURA_STATE_DEFENSE, true); StartReactiveTimer(REACTIVE_DEFENSE); } } // if and victim block attack if (procExtra & PROC_EX_BLOCK) { ModifyAuraState(AURA_STATE_DEFENSE, true); StartReactiveTimer(REACTIVE_DEFENSE); } } else //For attacker { // Overpower on victim dodge if (procExtra & PROC_EX_DODGE && GetTypeId() == TYPEID_PLAYER && getClass() == CLASS_WARRIOR) { this->ToPlayer()->AddComboPoints(pTarget, 1); StartReactiveTimer(REACTIVE_OVERPOWER); } } } } ProcTriggeredList procTriggered; // Fill procTriggered list for (AuraApplicationMap::const_iterator itr = GetAppliedAuras().begin(); itr != GetAppliedAuras().end(); ++itr) { // Do not allow auras to proc from effect triggered by itself if (procAura && procAura->Id == itr->first) continue; ProcTriggeredData triggerData(itr->second->GetBase()); // Defensive procs are active on absorbs (so absorption effects are not a hindrance) bool active = (damage > 0) || (procExtra & (PROC_EX_ABSORB | PROC_EX_BLOCK) && isVictim); if (isVictim) procExtra &= ~PROC_EX_INTERNAL_REQ_FAMILY; SpellEntry const* spellProto = itr->second->GetBase()->GetSpellProto(); if (!IsTriggeredAtSpellProcEvent(pTarget, triggerData.aura, procSpell, procFlag, procExtra, attType, isVictim, active, triggerData.spellProcEvent)) continue; // Triggered spells not triggering additional spells bool triggered = !(spellProto->AttributesEx3 & SPELL_ATTR3_CAN_PROC_WITH_TRIGGERED) ? (procExtra & PROC_EX_INTERNAL_TRIGGERED && !(procFlag & PROC_FLAG_DONE_TRAP_ACTIVATION)) : false; for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (itr->second->HasEffect(i)) { AuraEffect * aurEff = itr->second->GetBase()->GetEffect(i); // Skip this auras if (isNonTriggerAura [aurEff->GetAuraType()]) continue; // If not trigger by default and spellProcEvent == NULL - skip if (!isTriggerAura [aurEff->GetAuraType()] && triggerData.spellProcEvent == NULL) continue; // Some spells must always trigger if (!triggered || isAlwaysTriggeredAura [aurEff->GetAuraType()]) triggerData.effMask |= 1 << i; } } if (triggerData.effMask) procTriggered.push_front(triggerData); } // Nothing found if (procTriggered.empty()) return; if (procExtra & (PROC_EX_INTERNAL_TRIGGERED | PROC_EX_INTERNAL_CANT_PROC)) SetCantProc( true); // Handle effects proceed this time for (ProcTriggeredList::const_iterator i = procTriggered.begin(); i != procTriggered.end(); ++i) { // look for aura in auras list, it may be removed while proc event processing if (i->aura->IsRemoved()) continue; bool useCharges = i->aura->GetCharges() > 0; bool takeCharges = false; SpellEntry const *spellInfo = i->aura->GetSpellProto(); uint32 Id = i->aura->GetId(); // For players set spell cooldown if need uint32 cooldown = 0; if (GetTypeId() == TYPEID_PLAYER && i->spellProcEvent && i->spellProcEvent->cooldown) cooldown = i->spellProcEvent->cooldown; if (spellInfo->AttributesEx3 & SPELL_ATTR3_DISABLE_PROC) SetCantProc( true); // This bool is needed till separate aura effect procs are still here bool handled = false; if (HandleAuraProc(pTarget, damage, i->aura, procSpell, procFlag, procExtra, cooldown, &handled)) { sLog->outDebug( LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell %u (triggered with value by %s aura of spell %u)", spellInfo->Id, (isVictim ? "a victim's" : "an attacker's"), Id); takeCharges = true; } if (!handled) for (uint8 effIndex = 0; effIndex < MAX_SPELL_EFFECTS; ++effIndex) { if (!(i->effMask & (1 << effIndex))) continue; AuraEffect *triggeredByAura = i->aura->GetEffect(effIndex); ASSERT(triggeredByAura); switch (triggeredByAura->GetAuraType()) { case SPELL_AURA_PROC_TRIGGER_SPELL: { sLog->outDebug( LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell %u (triggered by %s aura of spell %u)", spellInfo->Id, (isVictim ? "a victim's" : "an attacker's"), triggeredByAura->GetId()); // Don`t drop charge or add cooldown for not started trigger if (HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown)) takeCharges = true; break; } case SPELL_AURA_PROC_TRIGGER_DAMAGE: { if (!pTarget) return; sLog->outDebug( LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: doing %u damage from spell id %u (triggered by %s aura of spell %u)", triggeredByAura->GetAmount(), spellInfo->Id, (isVictim ? "a victim's" : "an attacker's"), triggeredByAura->GetId()); SpellNonMeleeDamage damageInfo(this, pTarget, spellInfo->Id, spellInfo->SchoolMask); uint32 damage = SpellDamageBonus(pTarget, spellInfo, triggeredByAura->GetEffIndex(), triggeredByAura->GetAmount(), SPELL_DIRECT_DAMAGE); CalculateSpellDamageTaken(&damageInfo, damage, spellInfo); DealDamageMods(damageInfo.target, damageInfo.damage, &damageInfo.absorb); SendSpellNonMeleeDamageLog(&damageInfo); DealSpellDamage(&damageInfo, true); takeCharges = true; break; } case SPELL_AURA_MANA_SHIELD: case SPELL_AURA_DUMMY: { sLog->outDebug( LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell id %u (triggered by %s dummy aura of spell %u)", spellInfo->Id, (isVictim ? "a victim's" : "an attacker's"), triggeredByAura->GetId()); if (HandleDummyAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown)) takeCharges = true; break; } case SPELL_AURA_OBS_MOD_POWER: sLog->outDebug( LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell id %u (triggered by %s aura of spell %u)", spellInfo->Id, (isVictim ? "a victim's" : "an attacker's"), triggeredByAura->GetId()); if (HandleObsModEnergyAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown)) takeCharges = true; break; case SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN: sLog->outDebug( LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell id %u (triggered by %s aura of spell %u)", spellInfo->Id, (isVictim ? "a victim's" : "an attacker's"), triggeredByAura->GetId()); if (HandleModDamagePctTakenAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown)) takeCharges = true; break; case SPELL_AURA_MOD_POWER_REGEN_PERCENT: { sLog->outDebug( LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell id %u (triggered by %s ModPowerRegenPCT of spell %u)", spellInfo->Id, (isVictim ? "a victim's" : "an attacker's"), triggeredByAura->GetId()); if (HandleModPowerRegenAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown)) takeCharges = true; break; } case SPELL_AURA_OVERRIDE_CLASS_SCRIPTS: { sLog->outDebug( LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell id %u (triggered by %s aura of spell %u)", spellInfo->Id, (isVictim ? "a victim's" : "an attacker's"), triggeredByAura->GetId()); if (HandleOverrideClassScriptAuraProc(pTarget, damage, triggeredByAura, procSpell, cooldown)) takeCharges = true; break; } case SPELL_AURA_RAID_PROC_FROM_CHARGE_WITH_VALUE: { sLog->outDebug( LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting mending (triggered by %s dummy aura of spell %u)", (isVictim ? "a victim's" : "an attacker's"), triggeredByAura->GetId()); HandleAuraRaidProcFromChargeWithValue(triggeredByAura); takeCharges = true; break; } case SPELL_AURA_RAID_PROC_FROM_CHARGE: { sLog->outDebug( LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting mending (triggered by %s dummy aura of spell %u)", (isVictim ? "a victim's" : "an attacker's"), triggeredByAura->GetId()); HandleAuraRaidProcFromCharge(triggeredByAura); takeCharges = true; break; } case SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE: { sLog->outDebug( LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell %u (triggered with value by %s aura of spell %u)", spellInfo->Id, (isVictim ? "a victim's" : "an attacker's"), triggeredByAura->GetId()); if (HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown)) takeCharges = true; break; } case SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK: // Skip melee hits or instant cast spells if (procSpell && GetSpellCastTime(procSpell) != 0) takeCharges = true; break; case SPELL_AURA_REFLECT_SPELLS_SCHOOL: // Skip Melee hits and spells ws wrong school if (procSpell && (triggeredByAura->GetMiscValue() & procSpell->SchoolMask)) // School check takeCharges = true; break; case SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT: case SPELL_AURA_MOD_POWER_COST_SCHOOL: // Skip melee hits and spells ws wrong school or zero cost if (procSpell && (procSpell->manaCost != 0 || procSpell->ManaCostPercentage != 0) && // Cost check (triggeredByAura->GetMiscValue() & procSpell->SchoolMask)) // School check takeCharges = true; break; case SPELL_AURA_MECHANIC_IMMUNITY: // Compare mechanic if (procSpell && procSpell->Mechanic == uint32(triggeredByAura->GetMiscValue())) takeCharges = true; break; case SPELL_AURA_MOD_MECHANIC_RESISTANCE: // Compare mechanic if (procSpell && procSpell->Mechanic == uint32(triggeredByAura->GetMiscValue())) takeCharges = true; break; case SPELL_AURA_MOD_DAMAGE_FROM_CASTER: // Compare casters if (triggeredByAura->GetCasterGUID() == pTarget->GetGUID()) takeCharges = true; break; case SPELL_AURA_MOD_SPELL_CRIT_CHANCE: sLog->outDebug( LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell id %u (triggered by %s spell crit chance aura of spell %u)", spellInfo->Id, (isVictim ? "a victim's" : "an attacker's"), triggeredByAura->GetId()); if (procSpell && HandleSpellCritChanceAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown)) takeCharges = true; break; // CC Auras which use their amount amount to drop // Are there any more auras which need this? case SPELL_AURA_MOD_CONFUSE: case SPELL_AURA_MOD_FEAR: case SPELL_AURA_MOD_STUN: case SPELL_AURA_MOD_ROOT: case SPELL_AURA_TRANSFORM: { // chargeable mods are breaking on hit if (useCharges) takeCharges = true; else { // Spell own direct damage at apply wont break the CC if (procSpell && (procSpell->Id == triggeredByAura->GetId())) { Aura * aura = triggeredByAura->GetBase(); // called from spellcast, should not have ticked yet if (aura->GetDuration() == aura->GetMaxDuration()) break; } int32 damageLeft = triggeredByAura->GetAmount(); // No damage left if (damageLeft < int32(damage)) i->aura->Remove(); else triggeredByAura->SetAmount(damageLeft - damage); } break; } //case SPELL_AURA_ADD_FLAT_MODIFIER: //case SPELL_AURA_ADD_PCT_MODIFIER: // HandleSpellModAuraProc //break; default: // nothing do, just charges counter takeCharges = true; break; } } // Remove charge (aura can be removed by triggers) if (useCharges && takeCharges) i->aura->DropCharge(); if (spellInfo->AttributesEx3 & SPELL_ATTR3_DISABLE_PROC) SetCantProc( false); } // Cleanup proc requirements if (procExtra & (PROC_EX_INTERNAL_TRIGGERED | PROC_EX_INTERNAL_CANT_PROC)) SetCantProc( false); } SpellSchoolMask Unit::GetMeleeDamageSchoolMask() const { return SPELL_SCHOOL_MASK_NORMAL; } Player* Unit::GetSpellModOwner() const { if (GetTypeId() == TYPEID_PLAYER) return (Player*) this; if (this->ToCreature()->isPet() || this->ToCreature()->isTotem()) { Unit* owner = GetOwner(); if (owner && owner->GetTypeId() == TYPEID_PLAYER) return (Player*) owner; } return NULL; } ///----------Pet responses methods----------------- void Unit::SendPetCastFail(uint32 spellid, SpellCastResult msg) { if (msg == SPELL_CAST_OK) return; Unit *owner = GetCharmerOrOwner(); if (!owner || owner->GetTypeId() != TYPEID_PLAYER) return; WorldPacket data(SMSG_PET_CAST_FAILED, 1 + 4 + 1); data << uint8(0); // cast count? data << uint32(spellid); data << uint8(msg); // uint32 for some reason // uint32 for some reason owner->ToPlayer()->GetSession()->SendPacket(&data); } void Unit::SendPetActionFeedback(uint8 msg) { Unit* owner = GetOwner(); if (!owner || owner->GetTypeId() != TYPEID_PLAYER) return; WorldPacket data(SMSG_PET_ACTION_FEEDBACK, 1); data << uint8(msg); owner->ToPlayer()->GetSession()->SendPacket(&data); } void Unit::SendPetTalk(uint32 pettalk) { Unit* owner = GetOwner(); if (!owner || owner->GetTypeId() != TYPEID_PLAYER) return; WorldPacket data(SMSG_PET_ACTION_SOUND, 8 + 4); data << uint64(GetGUID()); data << uint32(pettalk); owner->ToPlayer()->GetSession()->SendPacket(&data); } void Unit::SendPetAIReaction(uint64 guid) { Unit* owner = GetOwner(); if (!owner || owner->GetTypeId() != TYPEID_PLAYER) return; WorldPacket data(SMSG_AI_REACTION, 8 + 4); data << uint64(guid); data << uint32(AI_REACTION_HOSTILE); owner->ToPlayer()->GetSession()->SendPacket(&data); } ///----------End of Pet responses methods---------- void Unit::StopMoving() { ClearUnitState(UNIT_STAT_MOVING); // send explicit stop packet // rely on vmaps here because for example stormwind is in air //float z = sMapMgr->GetBaseMap(GetMapId())->GetHeight(GetPositionX(), GetPositionY(), GetPositionZ(), true); //if (fabs(GetPositionZ() - z) < 2.0f) // Relocate(GetPositionX(), GetPositionY(), z); //Relocate(GetPositionX(), GetPositionY(), GetPositionZ()); if (!(GetUnitMovementFlags() & MOVEMENTFLAG_ONTRANSPORT)) SendMonsterStop(); } void Unit::SendMovementFlagUpdate() { WorldPacket data; BuildHeartBeatMsg(&data); SendMessageToSet(&data, false); } bool Unit::IsSitState() const { uint8 s = getStandState(); return s == UNIT_STAND_STATE_SIT_CHAIR || s == UNIT_STAND_STATE_SIT_LOW_CHAIR || s == UNIT_STAND_STATE_SIT_MEDIUM_CHAIR || s == UNIT_STAND_STATE_SIT_HIGH_CHAIR || s == UNIT_STAND_STATE_SIT; } bool Unit::IsStandState() const { uint8 s = getStandState(); return !IsSitState() && s != UNIT_STAND_STATE_SLEEP && s != UNIT_STAND_STATE_KNEEL; } void Unit::SetStandState(uint8 state) { SetByteValue(UNIT_FIELD_BYTES_1, 0, state); if (IsStandState()) RemoveAurasWithInterruptFlags( AURA_INTERRUPT_FLAG_NOT_SEATED); if (GetTypeId() == TYPEID_PLAYER) { WorldPacket data(SMSG_STANDSTATE_UPDATE, 1); data << (uint8) state; this->ToPlayer()->GetSession()->SendPacket(&data); } } bool Unit::IsPolymorphed() const { uint32 transformId = getTransForm(); if (!transformId) return false; const SpellEntry *spellInfo = sSpellStore.LookupEntry(transformId); if (!spellInfo) return false; return GetSpellSpecific(spellInfo) == SPELL_SPECIFIC_MAGE_POLYMORPH; } void Unit::SetDisplayId(uint32 modelId) { SetUInt32Value(UNIT_FIELD_DISPLAYID, modelId); if (GetTypeId() == TYPEID_UNIT && this->ToCreature()->isPet()) { Pet *pet = ((Pet*) this); if (!pet->isControlled()) return; Unit *owner = GetOwner(); if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && owner->ToPlayer()->GetGroup()) owner->ToPlayer()->SetGroupUpdateFlag( GROUP_UPDATE_FLAG_PET_MODEL_ID); } } void Unit::RestoreDisplayId() { AuraEffect* handledAura = NULL; // try to receive model from transform auras Unit::AuraEffectList const& transforms = GetAuraEffectsByType( SPELL_AURA_TRANSFORM); if (!transforms.empty()) { // iterate over already applied transform auras - from newest to oldest for (Unit::AuraEffectList::const_reverse_iterator i = transforms.rbegin(); i != transforms.rend(); ++i) { if (AuraApplication const * aurApp = (*i)->GetBase()->GetApplicationOfTarget(GetGUID())) { if (!handledAura) handledAura = (*i); // prefer negative auras if (!aurApp->IsPositive()) { handledAura = (*i); break; } } } } // transform aura was found if (handledAura) handledAura->HandleEffect(this, AURA_EFFECT_HANDLE_SEND_FOR_CLIENT, true); // we've found shapeshift else if (uint32 modelId = GetModelForForm(GetShapeshiftForm())) SetDisplayId( modelId); // no auras found - set modelid to default else SetDisplayId(GetNativeDisplayId()); } void Unit::ClearComboPointHolders() { while (!m_ComboPointHolders.empty()) { uint32 lowguid = *m_ComboPointHolders.begin(); Player* plr = sObjectMgr->GetPlayer( MAKE_NEW_GUID(lowguid, 0, HIGHGUID_PLAYER)); if (plr && plr->GetComboTarget() == GetGUID()) // recheck for safe plr->ClearComboPoints(); // remove also guid from m_ComboPointHolders; else m_ComboPointHolders.erase(lowguid); // or remove manually } } void Unit::ClearAllReactives() { for (uint8 i = 0; i < MAX_REACTIVE; ++i) m_reactiveTimer [i] = 0; if (HasAuraState(AURA_STATE_DEFENSE)) ModifyAuraState(AURA_STATE_DEFENSE, false); if (getClass() == CLASS_HUNTER && HasAuraState(AURA_STATE_HUNTER_PARRY)) ModifyAuraState( AURA_STATE_HUNTER_PARRY, false); if (getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER) this->ToPlayer()->ClearComboPoints(); } void Unit::UpdateReactives(uint32 p_time) { for (uint8 i = 0; i < MAX_REACTIVE; ++i) { ReactiveType reactive = ReactiveType(i); if (!m_reactiveTimer [reactive]) continue; if (m_reactiveTimer [reactive] <= p_time) { m_reactiveTimer [reactive] = 0; switch (reactive) { case REACTIVE_DEFENSE: if (HasAuraState(AURA_STATE_DEFENSE)) ModifyAuraState( AURA_STATE_DEFENSE, false); break; case REACTIVE_HUNTER_PARRY: if (getClass() == CLASS_HUNTER && HasAuraState(AURA_STATE_HUNTER_PARRY)) ModifyAuraState( AURA_STATE_HUNTER_PARRY, false); break; case REACTIVE_OVERPOWER: if (getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER) this->ToPlayer()->ClearComboPoints(); break; default: break; } } else { m_reactiveTimer [reactive] -= p_time; } } } Unit* Unit::SelectNearbyTarget(float dist) const { std::list <Unit *> targets; Trinity::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, this, dist); Trinity::UnitListSearcher <Trinity::AnyUnfriendlyUnitInObjectRangeCheck> searcher( this, targets, u_check); VisitNearbyObject(dist, searcher); // remove current target if (getVictim()) targets.remove(getVictim()); // remove not LoS targets for (std::list <Unit*>::iterator tIter = targets.begin(); tIter != targets.end();) { if (!IsWithinLOSInMap(*tIter) || (*tIter)->isTotem() || (*tIter)->isSpiritService() || (*tIter)->GetCreatureType() == CREATURE_TYPE_CRITTER) targets.erase( tIter++); else ++tIter; } // no appropriate targets if (targets.empty()) return NULL; // select random std::list <Unit*>::const_iterator tcIter = targets.begin(); std::advance(tcIter, urand(0, targets.size() - 1)); return *tcIter; } void Unit::ApplyAttackTimePercentMod(WeaponAttackType att, float val, bool apply) { float remainingTimePct = (float) m_attackTimer [att] / (GetAttackTime(att) * m_modAttackSpeedPct [att]); if (val > 0) { ApplyPercentModFloatVar(m_modAttackSpeedPct [att], val, !apply); ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME + att, val, !apply); } else { ApplyPercentModFloatVar(m_modAttackSpeedPct [att], -val, apply); ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME + att, -val, apply); } m_attackTimer [att] = uint32( GetAttackTime(att) * m_modAttackSpeedPct [att] * remainingTimePct); } void Unit::ApplyCastTimePercentMod(float val, bool apply) { if (val > 0) ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED, val, !apply); else ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED, -val, apply); } uint32 Unit::GetCastingTimeForBonus(SpellEntry const *spellProto, DamageEffectType damagetype, uint32 CastingTime) { // Not apply this to creature casted spells with casttime == 0 if (CastingTime == 0 && GetTypeId() == TYPEID_UNIT && !this->ToCreature()->isPet()) return 3500; if (CastingTime > 7000) CastingTime = 7000; if (CastingTime < 1500) CastingTime = 1500; if (damagetype == DOT && !IsChanneledSpell(spellProto)) CastingTime = 3500; int32 overTime = 0; uint8 effects = 0; bool DirectDamage = false; bool AreaEffect = false; for (uint32 i = 0; i < MAX_SPELL_EFFECTS; i++) { switch (spellProto->Effect [i]) { case SPELL_EFFECT_SCHOOL_DAMAGE: case SPELL_EFFECT_POWER_DRAIN: case SPELL_EFFECT_HEALTH_LEECH: case SPELL_EFFECT_ENVIRONMENTAL_DAMAGE: case SPELL_EFFECT_POWER_BURN: case SPELL_EFFECT_HEAL: DirectDamage = true; break; case SPELL_EFFECT_APPLY_AURA: switch (spellProto->EffectApplyAuraName [i]) { case SPELL_AURA_PERIODIC_DAMAGE: case SPELL_AURA_PERIODIC_HEAL: case SPELL_AURA_PERIODIC_LEECH: if (GetSpellDuration(spellProto)) overTime = GetSpellDuration(spellProto); break; default: // -5% per additional effect ++effects; break; } default: break; } if (IsAreaEffectTarget [spellProto->EffectImplicitTargetA [i]] || IsAreaEffectTarget [spellProto->EffectImplicitTargetB [i]]) AreaEffect = true; } // Combined Spells with Both Over Time and Direct Damage if (overTime > 0 && CastingTime > 0 && DirectDamage) { // mainly for DoTs which are 3500 here otherwise uint32 OriginalCastTime = GetSpellCastTime(spellProto); if (OriginalCastTime > 7000) OriginalCastTime = 7000; if (OriginalCastTime < 1500) OriginalCastTime = 1500; // Portion to Over Time float PtOT = (overTime / 15000.0f) / ((overTime / 15000.0f) + (OriginalCastTime / 3500.0f)); if (damagetype == DOT) CastingTime = uint32(CastingTime * PtOT); else if (PtOT < 1.0f) CastingTime = uint32(CastingTime * (1 - PtOT)); else CastingTime = 0; } // Area Effect Spells receive only half of bonus if (AreaEffect) CastingTime /= 2; // -5% of total per any additional effect for (uint8 i = 0; i < effects; ++i) { if (CastingTime > 175) { CastingTime -= 175; } else { CastingTime = 0; break; } } return CastingTime; } void Unit::UpdateAuraForGroup(uint8 slot) { if (slot >= MAX_AURAS) // slot not found, return return; if (GetTypeId() == TYPEID_PLAYER) { Player* player = (Player*) this; if (player->GetGroup()) { player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_AURAS); player->SetAuraUpdateMaskForRaid(slot); } } else if (GetTypeId() == TYPEID_UNIT && this->ToCreature()->isPet()) { Pet *pet = ((Pet*) this); if (pet->isControlled()) { Unit *owner = GetOwner(); if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && owner->ToPlayer()->GetGroup()) { owner->ToPlayer()->SetGroupUpdateFlag( GROUP_UPDATE_FLAG_PET_AURAS); pet->SetAuraUpdateMaskForRaid(slot); } } } } float Unit::GetAPMultiplier(WeaponAttackType attType, bool normalized) { if (!normalized || GetTypeId() != TYPEID_PLAYER) return float( GetAttackTime(attType)) / 1000.0f; Item *Weapon = this->ToPlayer()->GetWeaponForAttack(attType, true); if (!Weapon) return 2.4f; // fist attack switch (Weapon->GetProto()->InventoryType) { case INVTYPE_2HWEAPON: return 3.3f; case INVTYPE_RANGED: case INVTYPE_RANGEDRIGHT: case INVTYPE_THROWN: return 2.8f; case INVTYPE_WEAPON: case INVTYPE_WEAPONMAINHAND: case INVTYPE_WEAPONOFFHAND: default: return Weapon->GetProto()->SubClass == ITEM_SUBCLASS_WEAPON_DAGGER ? 1.7f : 2.4f; } } bool Unit::IsUnderLastManaUseEffect() const { return getMSTimeDiff(m_lastManaUse, getMSTime()) < 5000; } void Unit::SetContestedPvP(Player *attackedPlayer) { Player* player = GetCharmerOrOwnerPlayerOrPlayerItself(); if (!player || (attackedPlayer && (attackedPlayer == player || (player->duel && player->duel->opponent == attackedPlayer)))) return; player->SetContestedPvPTimer(30000); if (!player->HasUnitState(UNIT_STAT_ATTACK_PLAYER)) { player->AddUnitState(UNIT_STAT_ATTACK_PLAYER); player->SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP); // call MoveInLineOfSight for nearby contested guards UpdateObjectVisibility(); } if (!HasUnitState(UNIT_STAT_ATTACK_PLAYER)) { AddUnitState(UNIT_STAT_ATTACK_PLAYER); // call MoveInLineOfSight for nearby contested guards UpdateObjectVisibility(); } } void Unit::AddPetAura(PetAura const* petSpell) { if (GetTypeId() != TYPEID_PLAYER) return; m_petAuras.insert(petSpell); if (Pet* pet = this->ToPlayer()->GetPet()) pet->CastPetAura(petSpell); } void Unit::RemovePetAura(PetAura const* petSpell) { if (GetTypeId() != TYPEID_PLAYER) return; m_petAuras.erase(petSpell); if (Pet* pet = this->ToPlayer()->GetPet()) pet->RemoveAurasDueToSpell( petSpell->GetAura(pet->GetEntry())); } Pet* Unit::CreateTamedPetFrom(Creature* creatureTarget, uint32 spell_id) { if (GetTypeId() != TYPEID_PLAYER) return NULL; Pet* pet = new Pet((Player*) this, HUNTER_PET); if (!pet->CreateBaseAtCreature(creatureTarget)) { delete pet; return NULL; } uint8 level = creatureTarget->getLevel() + 5 < getLevel() ? (getLevel() - 5) : creatureTarget->getLevel(); InitTamedPet(pet, level, spell_id); return pet; } Pet* Unit::CreateTamedPetFrom(uint32 creatureEntry, uint32 spell_id) { if (GetTypeId() != TYPEID_PLAYER) return NULL; CreatureInfo const* creatureInfo = ObjectMgr::GetCreatureTemplate( creatureEntry); if (!creatureInfo) return NULL; Pet* pet = new Pet((Player*) this, HUNTER_PET); if (!pet->CreateBaseAtCreatureInfo(creatureInfo, this) || !InitTamedPet(pet, getLevel(), spell_id)) { delete pet; return NULL; } return pet; } bool Unit::InitTamedPet(Pet * pet, uint8 level, uint32 spell_id) { pet->SetCreatorGUID(GetGUID()); pet->setFaction(getFaction()); pet->SetUInt32Value(UNIT_CREATED_BY_SPELL, spell_id); if (GetTypeId() == TYPEID_PLAYER) pet->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE); if (!pet->InitStatsForLevel(level)) { sLog->outError( "Pet::InitStatsForLevel() failed for creature (Entry: %u)!", pet->GetEntry()); return false; } pet->GetCharmInfo()->SetPetNumber(sObjectMgr->GeneratePetNumber(), true); // this enables pet details window (Shift+P) pet->InitPetCreateSpells(); //pet->InitLevelupSpellsForLevel(); pet->SetFullHealth(); return true; } bool Unit::IsTriggeredAtSpellProcEvent(Unit *pVictim, Aura * aura, SpellEntry const* procSpell, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, bool isVictim, bool active, SpellProcEventEntry const *& spellProcEvent) { SpellEntry const *spellProto = aura->GetSpellProto(); // Get proc Event Entry spellProcEvent = sSpellMgr->GetSpellProcEvent(spellProto->Id); // Get EventProcFlag uint32 EventProcFlag; if (spellProcEvent && spellProcEvent->procFlags) // if exist get custom spellProcEvent->procFlags EventProcFlag = spellProcEvent->procFlags; else EventProcFlag = spellProto->procFlags; // else get from spell proto // Continue if no trigger exist if (!EventProcFlag) return false; // Additional checks for triggered spells (ignore trap casts) if (procExtra & PROC_EX_INTERNAL_TRIGGERED && !(procFlag & PROC_FLAG_DONE_TRAP_ACTIVATION)) { if (!(spellProto->AttributesEx3 & SPELL_ATTR3_CAN_PROC_WITH_TRIGGERED)) return false; } // Check spellProcEvent data requirements if (!sSpellMgr->IsSpellProcEventCanTriggeredBy(spellProcEvent, EventProcFlag, procSpell, procFlag, procExtra, active)) return false; // In most cases req get honor or XP from kill if (EventProcFlag & PROC_FLAG_KILL && GetTypeId() == TYPEID_PLAYER) { bool allow = false; if (pVictim) allow = ToPlayer()->isHonorOrXPTarget(pVictim); // Shadow Word: Death - can trigger from every kill if (aura->GetId() == 32409) allow = true; if (!allow) return false; } // Aura added by spell can`t trigger from self (prevent drop charges/do triggers) // But except periodic and kill triggers (can triggered from self) if (procSpell && procSpell->Id == spellProto->Id && !(spellProto->procFlags & (PROC_FLAG_TAKEN_PERIODIC | PROC_FLAG_KILL))) return false; // Check if current equipment allows aura to proc if (!isVictim && GetTypeId() == TYPEID_PLAYER) { if (spellProto->EquippedItemClass == ITEM_CLASS_WEAPON) { Item *item = NULL; if (attType == BASE_ATTACK) item = this->ToPlayer()->GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND); else if (attType == OFF_ATTACK) item = this->ToPlayer()->GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND); else item = this->ToPlayer()->GetUseableItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED); if (this->ToPlayer()->IsInFeralForm()) return false; if (!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_WEAPON || !((1 << item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask)) return false; } else if (spellProto->EquippedItemClass == ITEM_CLASS_ARMOR) { // Check if player is wearing shield Item *item = this->ToPlayer()->GetUseableItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND); if (!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_ARMOR || !((1 << item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask)) return false; } } // Get chance from spell float chance = float(spellProto->procChance); // If in spellProcEvent exist custom chance, chance = spellProcEvent->customChance; if (spellProcEvent && spellProcEvent->customChance) chance = spellProcEvent->customChance; // Missile Barrage if (spellProto->SpellFamilyName == SPELLFAMILY_MAGE && spellProto->SpellIconID == 3261) if (!(procSpell->SpellFamilyFlags [0] & 0x20000000)) chance /= 2.0; // If PPM exist calculate chance from PPM if (spellProcEvent && spellProcEvent->ppmRate != 0) { if (!isVictim) { uint32 WeaponSpeed = GetAttackTime(attType); chance = GetPPMProcChance(WeaponSpeed, spellProcEvent->ppmRate, spellProto); } else { uint32 WeaponSpeed = pVictim->GetAttackTime(attType); chance = pVictim->GetPPMProcChance(WeaponSpeed, spellProcEvent->ppmRate, spellProto); } } // Apply chance modifer aura if (Player* modOwner = GetSpellModOwner()) { modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CHANCE_OF_SUCCESS, chance); } return roll_chance_f(chance); } bool Unit::HandleAuraRaidProcFromChargeWithValue(AuraEffect *triggeredByAura) { // aura can be deleted at casts SpellEntry const *spellProto = triggeredByAura->GetSpellProto(); uint32 effIdx = triggeredByAura->GetEffIndex(); int32 heal = triggeredByAura->GetAmount(); uint64 caster_guid = triggeredByAura->GetCasterGUID(); //Currently only Prayer of Mending if (!(spellProto->SpellFamilyName == SPELLFAMILY_PRIEST && spellProto->SpellFamilyFlags [1] & 0x20)) { sLog->outDebug( LOG_FILTER_UNITS, "Unit::HandleAuraRaidProcFromChargeWithValue, received not handled spell: %u", spellProto->Id); return false; } // jumps int32 jumps = triggeredByAura->GetBase()->GetCharges() - 1; // current aura expire triggeredByAura->GetBase()->SetCharges(1); // will removed at next charges decrease // next target selection if (jumps > 0) { float radius; if (spellProto->EffectRadiusIndex [effIdx]) radius = (float) GetSpellRadiusForTarget( triggeredByAura->GetCaster(), sSpellRadiusStore.LookupEntry( spellProto->EffectRadiusIndex [effIdx])); else radius = (float) GetSpellMaxRangeForTarget( triggeredByAura->GetCaster(), sSpellRangeStore.LookupEntry(spellProto->rangeIndex)); if (Unit * caster = triggeredByAura->GetCaster()) { if (Player * modOwner = caster->GetSpellModOwner()) modOwner->ApplySpellMod( spellProto->Id, SPELLMOD_RADIUS, radius, NULL); if (Unit *target = GetNextRandomRaidMemberOrPet(radius)) { CastCustomSpell(target, spellProto->Id, &heal, NULL, NULL, true, NULL, triggeredByAura, caster_guid); if (Aura * aura = target->GetAura(spellProto->Id, caster->GetGUID())) aura->SetCharges( jumps); } } } // heal CastCustomSpell(this, 33110, &heal, NULL, NULL, true, NULL, NULL, caster_guid); return true; } bool Unit::HandleAuraRaidProcFromCharge(AuraEffect* triggeredByAura) { // aura can be deleted at casts SpellEntry const* spellProto = triggeredByAura->GetSpellProto(); uint32 damageSpellId; switch (spellProto->Id) { case 57949: //shiver damageSpellId = 57952; //animationSpellId = 57951; dummy effects for jump spell have unknown use (see also 41637) break; case 59978: //shiver damageSpellId = 59979; break; case 43593: //Cold Stare damageSpellId = 43594; break; default: sLog->outError( "Unit::HandleAuraRaidProcFromCharge, received not handled spell: %u", spellProto->Id); return false; } uint64 caster_guid = triggeredByAura->GetCasterGUID(); uint32 effIdx = triggeredByAura->GetEffIndex(); // jumps int32 jumps = triggeredByAura->GetBase()->GetCharges() - 1; // current aura expire triggeredByAura->GetBase()->SetCharges(1); // will removed at next charges decrease // next target selection if (jumps > 0) { float radius; if (spellProto->EffectRadiusIndex [effIdx]) radius = (float) GetSpellRadiusForTarget( triggeredByAura->GetCaster(), sSpellRadiusStore.LookupEntry( spellProto->EffectRadiusIndex [effIdx])); else radius = (float) GetSpellMaxRangeForTarget( triggeredByAura->GetCaster(), sSpellRangeStore.LookupEntry(spellProto->rangeIndex)); if (Unit * caster = triggeredByAura->GetCaster()) { if (Player * modOwner = caster->GetSpellModOwner()) modOwner->ApplySpellMod( spellProto->Id, SPELLMOD_RADIUS, radius, NULL); if (Unit* target= GetNextRandomRaidMemberOrPet(radius)) { CastSpell(target, spellProto, true, NULL, triggeredByAura, caster_guid); if (Aura * aura = target->GetAura(spellProto->Id, caster->GetGUID())) aura->SetCharges( jumps); } } } CastSpell(this, damageSpellId, true, NULL, triggeredByAura, caster_guid); return true; } void Unit::Kill(Unit *pVictim, bool durabilityLoss) { // Prevent killing unit twice (and giving reward from kill twice) if (!pVictim->GetHealth()) return; // Inform pets (if any) when player kills target) if (this->ToPlayer()) { Pet *pPet = this->ToPlayer()->GetPet(); if (pPet && pPet->isAlive() && pPet->isControlled()) pPet->AI()->KilledUnit( pVictim); } // find player: owner of controlled `this` or `this` itself maybe Player *player = GetCharmerOrOwnerPlayerOrPlayerItself(); Creature *creature = pVictim->ToCreature(); bool bRewardIsAllowed = true; if (creature) { bRewardIsAllowed = creature->IsDamageEnoughForLootingAndReward(); if (!bRewardIsAllowed) creature->SetLootRecipient(NULL); } if (bRewardIsAllowed && creature && creature->GetLootRecipient()) player = creature->GetLootRecipient(); // Reward player, his pets, and group/raid members // call kill spell proc event (before real die and combat stop to triggering auras removed at death/combat stop) if (bRewardIsAllowed && player && player != pVictim) { WorldPacket data(SMSG_PARTYKILLLOG, (8 + 8)); //send event PARTY_KILL data << uint64(player->GetGUID()); //player with killing blow data << uint64(pVictim->GetGUID()); //victim Player* pLooter = player; if (Group *group = player->GetGroup()) { group->BroadcastPacket(&data, group->GetMemberGroup(player->GetGUID())); if (creature) { group->UpdateLooterGuid(creature, true); if (group->GetLooterGuid()) { pLooter = sObjectMgr->GetPlayer(group->GetLooterGuid()); if (pLooter) { creature->SetLootRecipient(pLooter); // update creature loot recipient to the allowed looter. group->SendLooter(creature, pLooter); } else group->SendLooter(creature, NULL); } else group->SendLooter(creature, NULL); group->UpdateLooterGuid(creature); } } else { player->SendDirectMessage(&data); if (creature) { WorldPacket data2(SMSG_LOOT_LIST, (8 + 1 + 1)); data2 << uint64(creature->GetGUID()); data2 << uint8(0); // unk1 data2 << uint8(0); // no group looter player->SendMessageToSet(&data2, true); } } if (creature) { Loot* loot = &creature->loot; if (creature->lootForPickPocketed) creature->lootForPickPocketed = false; loot->clear(); if (uint32 lootid = creature->GetCreatureInfo()->lootid) loot->FillLoot( lootid, LootTemplates_Creature, pLooter, false, false, creature->GetLootMode()); loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold, creature->GetCreatureInfo()->maxgold); } player->RewardPlayerAndGroupAtKill(pVictim, false); } // Do KILL and KILLED procs. KILL proc is called only for the unit who landed the killing blow (and its owner - for pets and totems) regardless of who tapped the victim if (isPet() || isTotem()) if (Unit *owner = GetOwner()) owner->ProcDamageAndSpell( pVictim, PROC_FLAG_KILL, PROC_FLAG_NONE, PROC_EX_NONE, 0); if (pVictim->GetCreatureType() != CREATURE_TYPE_CRITTER) ProcDamageAndSpell( pVictim, PROC_FLAG_KILL, PROC_FLAG_KILLED, PROC_EX_NONE, 0); // Proc auras on death - must be before aura/combat remove pVictim->ProcDamageAndSpell(NULL, PROC_FLAG_DEATH, PROC_FLAG_NONE, PROC_EX_NONE, 0, BASE_ATTACK, 0); // if talent known but not triggered (check priest class for speedup check) bool SpiritOfRedemption = false; if (pVictim->GetTypeId() == TYPEID_PLAYER && pVictim->getClass() == CLASS_PRIEST) { AuraEffectList const& vDummyAuras = pVictim->GetAuraEffectsByType( SPELL_AURA_DUMMY); for (AuraEffectList::const_iterator itr = vDummyAuras.begin(); itr != vDummyAuras.end(); ++itr) { if ((*itr)->GetSpellProto()->SpellIconID == 1654) { AuraEffect * aurEff = *itr; // save value before aura remove uint32 ressSpellId = pVictim->GetUInt32Value( PLAYER_SELF_RES_SPELL); if (!ressSpellId) ressSpellId = pVictim->ToPlayer()->GetResurrectionSpellId(); //Remove all expected to remove at death auras (most important negative case like DoT or periodic triggers) pVictim->RemoveAllAurasOnDeath(); // restore for use at real death pVictim->SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId); // FORM_SPIRITOFREDEMPTION and related auras pVictim->CastSpell(pVictim, 27827, true, NULL, aurEff); SpiritOfRedemption = true; break; } } } if (!SpiritOfRedemption) { sLog->outStaticDebug("SET JUST_DIED"); pVictim->setDeathState(JUST_DIED); } // 10% durability loss on death // clean InHateListOf if (pVictim->GetTypeId() == TYPEID_PLAYER) { // remember victim PvP death for corpse type and corpse reclaim delay // at original death (not at SpiritOfRedemtionTalent timeout) pVictim->ToPlayer()->SetPvPDeath(player != NULL); // only if not player and not controlled by player pet. And not at BG if ((durabilityLoss && !player && !pVictim->ToPlayer()->InBattleground()) || (player && sWorld->getBoolConfig(CONFIG_DURABILITY_LOSS_IN_PVP))) { sLog->outStaticDebug("We are dead, losing %f percent durability", sWorld->getRate(RATE_DURABILITY_LOSS_ON_DEATH)); pVictim->ToPlayer()->DurabilityLossAll( sWorld->getRate(RATE_DURABILITY_LOSS_ON_DEATH), false); // durability lost message WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0); pVictim->ToPlayer()->GetSession()->SendPacket(&data); } // Call KilledUnit for creatures if (GetTypeId() == TYPEID_UNIT && this->ToCreature()->IsAIEnabled) this->ToCreature()->AI()->KilledUnit( pVictim); // last damage from non duel opponent or opponent controlled creature if (pVictim->ToPlayer()->duel) { pVictim->ToPlayer()->duel->opponent->CombatStopWithPets(true); pVictim->ToPlayer()->CombatStopWithPets(true); pVictim->ToPlayer()->DuelComplete(DUEL_INTERRUPTED); } } else // creature died { sLog->outStaticDebug("DealDamageNotPlayer"); if (!creature->isPet()) { creature->DeleteThreatList(); CreatureInfo const* cInfo = creature->GetCreatureInfo(); if (cInfo && (cInfo->lootid || cInfo->maxgold > 0)) creature->SetFlag( UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE); } // Call KilledUnit for creatures, this needs to be called after the lootable flag is set if (GetTypeId() == TYPEID_UNIT && this->ToCreature()->IsAIEnabled) this->ToCreature()->AI()->KilledUnit( pVictim); // Call creature just died function if (creature->IsAIEnabled) creature->AI()->JustDied(this); if (creature->ToTempSummon()) { if (Unit* pSummoner = creature->ToTempSummon()->GetSummoner()) { if (pSummoner->ToCreature() && pSummoner->ToCreature()->IsAIEnabled) pSummoner->ToCreature()->AI()->SummonedCreatureDies( creature, this); } } // Dungeon specific stuff, only applies to players killing creatures if (creature->GetInstanceId()) { Map *m = creature->GetMap(); Player *creditedPlayer = GetCharmerOrOwnerPlayerOrPlayerItself(); // TODO: do instance binding anyway if the charmer/owner is offline if (m->IsDungeon() && creditedPlayer) { if (m->IsRaidOrHeroicDungeon()) { if (creature->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND) ((InstanceMap *) m)->PermBindAllPlayers( creditedPlayer); } else { // the reset time is set but not added to the scheduler // until the players leave the instance time_t resettime = creature->GetRespawnTimeEx() + 2 * HOUR; if (InstanceSave * save = sInstanceSaveMgr->GetInstanceSave( creature->GetInstanceId())) if (save->GetResetTime() < resettime) save->SetResetTime(resettime); } } } } // outdoor pvp things, do these after setting the death state, else the player activity notify won't work... doh... // handle player kill only if not suicide (spirit of redemption for example) if (player && this != pVictim) if (OutdoorPvP * pvp = player->GetOutdoorPvP()) pvp->HandleKill( player, pVictim); //if (pVictim->GetTypeId() == TYPEID_PLAYER) // if (OutdoorPvP * pvp = pVictim->ToPlayer()->GetOutdoorPvP()) // pvp->HandlePlayerActivityChangedpVictim->ToPlayer(); // battleground things (do this at the end, so the death state flag will be properly set to handle in the bg->handlekill) if (player && player->InBattleground()) { if (Battleground *bg = player->GetBattleground()) { if (pVictim->GetTypeId() == TYPEID_PLAYER) bg->HandleKillPlayer( (Player*) pVictim, player); else bg->HandleKillUnit(pVictim->ToCreature(), player); } } // achievement stuff if (pVictim->GetTypeId() == TYPEID_PLAYER) { if (GetTypeId() == TYPEID_UNIT) pVictim->ToPlayer()->GetAchievementMgr().UpdateAchievementCriteria( ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE, GetEntry()); else if (GetTypeId() == TYPEID_PLAYER && pVictim != this) pVictim->ToPlayer()->GetAchievementMgr().UpdateAchievementCriteria( ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER, 1, this->ToPlayer()->GetTeam()); } //Hook for OnPVPKill Event if (this->GetTypeId() == TYPEID_PLAYER) { if (pVictim->GetTypeId() == TYPEID_PLAYER) { Player *killer = this->ToPlayer(); Player *killed = pVictim->ToPlayer(); sScriptMgr->OnPVPKill(killer, killed); } else if (pVictim->GetTypeId() == TYPEID_UNIT) { Player *killer = this->ToPlayer(); Creature *killed = pVictim->ToCreature(); sScriptMgr->OnCreatureKill(killer, killed); } } else if (this->GetTypeId() == TYPEID_UNIT) { if (pVictim->GetTypeId() == TYPEID_PLAYER) { Creature *killer = this->ToCreature(); Player *killed = pVictim->ToPlayer(); sScriptMgr->OnPlayerKilledByCreature(killer, killed); } } } void Unit::SetControlled(bool apply, UnitState state) { if (apply) { if (HasUnitState(state)) return; AddUnitState(state); switch (state) { case UNIT_STAT_STUNNED: SetStunned(true); CastStop(); break; case UNIT_STAT_ROOT: if (!HasUnitState(UNIT_STAT_STUNNED)) SetRooted(true); break; case UNIT_STAT_CONFUSED: if (!HasUnitState(UNIT_STAT_STUNNED)) { SetConfused(true); CastStop(); } break; case UNIT_STAT_FLEEING: if (!HasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_CONFUSED)) { SetFeared(true); CastStop(); } break; default: break; } } else { switch (state) { case UNIT_STAT_STUNNED: if (HasAuraType(SPELL_AURA_MOD_STUN)) return; else SetStunned(false); break; case UNIT_STAT_ROOT: if (HasAuraType(SPELL_AURA_MOD_ROOT) || GetVehicle()) return; else SetRooted(false); break; case UNIT_STAT_CONFUSED: if (HasAuraType(SPELL_AURA_MOD_CONFUSE)) return; else SetConfused(false); break; case UNIT_STAT_FLEEING: if (HasAuraType(SPELL_AURA_MOD_FEAR)) return; else SetFeared(false); break; default: return; } ClearUnitState(state); if (HasUnitState(UNIT_STAT_STUNNED)) SetStunned(true); else { if (HasUnitState(UNIT_STAT_ROOT)) SetRooted(true); if (HasUnitState(UNIT_STAT_CONFUSED)) SetConfused(true); else if (HasUnitState(UNIT_STAT_FLEEING)) SetFeared(true); } } } void Unit::SetStunned(bool apply) { if (apply) { SetUInt64Value(UNIT_FIELD_TARGET, 0); SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED); CastStop(); // AddUnitMovementFlag(MOVEMENTFLAG_ROOT); // Creature specific if (GetTypeId() != TYPEID_PLAYER) this->ToCreature()->StopMoving(); else SetStandState(UNIT_STAND_STATE_STAND); if (Player * plr = ToPlayer()) plr->SetMovement(MOVE_ROOT); } else { if (isAlive() && getVictim()) SetUInt64Value(UNIT_FIELD_TARGET, getVictim()->GetGUID()); // don't remove UNIT_FLAG_STUNNED for pet when owner is mounted (disabled pet's interface) Unit *pOwner = GetOwner(); if (!pOwner || (pOwner->GetTypeId() == TYPEID_PLAYER && !pOwner->ToPlayer()->IsMounted())) RemoveFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED); if (!HasUnitState(UNIT_STAT_ROOT)) // prevent allow move if have also root effect { if (Player * plr = ToPlayer()) plr->SetMovement(MOVE_UNROOT); } } } void Unit::SetRooted(bool apply) { if (apply) { if (m_rootTimes > 0) //blizzard internal check? m_rootTimes++; // AddUnitMovementFlag(MOVEMENTFLAG_ROOT); if (Player *plr = ToPlayer()) { WorldPacket data(SMSG_FORCE_MOVE_ROOT, 10); data.append(GetPackGUID()); data << m_rootTimes; plr->GetSession()->SendPacket(&data); } else ToCreature()->StopMoving(); } else { if (!HasUnitState(UNIT_STAT_STUNNED)) // prevent allow move if have also stun effect { m_rootTimes++; //blizzard internal check? if (Player* plr = ToPlayer()) { WorldPacket data(SMSG_FORCE_MOVE_UNROOT, 10); data.append(GetPackGUID()); data << m_rootTimes; plr->GetSession()->SendPacket(&data); } } } } void Unit::SetFeared(bool apply) { if (apply) { SetUInt64Value(UNIT_FIELD_TARGET, 0); Unit *caster = NULL; Unit::AuraEffectList const& fearAuras = GetAuraEffectsByType( SPELL_AURA_MOD_FEAR); if (!fearAuras.empty()) caster = ObjectAccessor::GetUnit(*this, fearAuras.front()->GetCasterGUID()); if (!caster) caster = getAttackerForHelper(); GetMotionMaster()->MoveFleeing( caster, fearAuras.empty() ? sWorld->getIntConfig( CONFIG_CREATURE_FAMILY_FLEE_DELAY) : 0); // caster == NULL processed in MoveFleeing } else { if (isAlive()) { if (GetMotionMaster()->GetCurrentMovementGeneratorType() == FLEEING_MOTION_TYPE) GetMotionMaster()->MovementExpired(); if (getVictim()) SetUInt64Value(UNIT_FIELD_TARGET, getVictim()->GetGUID()); } } if (GetTypeId() == TYPEID_PLAYER) this->ToPlayer()->SetClientControl(this, !apply); } void Unit::SetConfused(bool apply) { if (apply) { SetUInt64Value(UNIT_FIELD_TARGET, 0); GetMotionMaster()->MoveConfused(); } else { if (isAlive()) { if (GetMotionMaster()->GetCurrentMovementGeneratorType() == CONFUSED_MOTION_TYPE) GetMotionMaster()->MovementExpired(); if (getVictim()) SetUInt64Value(UNIT_FIELD_TARGET, getVictim()->GetGUID()); } } if (GetTypeId() == TYPEID_PLAYER) this->ToPlayer()->SetClientControl(this, !apply); } bool Unit::SetCharmedBy(Unit* charmer, CharmType type, AuraApplication const * aurApp) { if (!charmer) return false; // unmount players when charmed if (GetTypeId() == TYPEID_PLAYER) Unmount(); ASSERT(type != CHARM_TYPE_POSSESS || charmer->GetTypeId() == TYPEID_PLAYER); ASSERT((type == CHARM_TYPE_VEHICLE) == IsVehicle()); sLog->outDebug( LOG_FILTER_UNITS, "SetCharmedBy: charmer %u (GUID %u), charmed %u (GUID %u), type %u.", charmer->GetEntry(), charmer->GetGUIDLow(), GetEntry(), GetGUIDLow(), uint32(type)); if (this == charmer) { sLog->outCrash( "Unit::SetCharmedBy: Unit %u (GUID %u) is trying to charm itself!", GetEntry(), GetGUIDLow()); return false; } //if (HasUnitState(UNIT_STAT_UNATTACKABLE)) // return false; if (GetTypeId() == TYPEID_PLAYER && this->ToPlayer()->GetTransport()) { sLog->outCrash( "Unit::SetCharmedBy: Player on transport is trying to charm %u (GUID %u)", GetEntry(), GetGUIDLow()); return false; } // Already charmed if (GetCharmerGUID()) { sLog->outCrash( "Unit::SetCharmedBy: %u (GUID %u) has already been charmed but %u (GUID %u) is trying to charm it!", GetEntry(), GetGUIDLow(), charmer->GetEntry(), charmer->GetGUIDLow()); return false; } CastStop(); CombatStop(); //TODO: CombatStop(true) may cause crash (interrupt spells) DeleteThreatList(); // Charmer stop charming if (charmer->GetTypeId() == TYPEID_PLAYER) { charmer->ToPlayer()->StopCastingCharm(); charmer->ToPlayer()->StopCastingBindSight(); } // Charmed stop charming if (GetTypeId() == TYPEID_PLAYER) { this->ToPlayer()->StopCastingCharm(); this->ToPlayer()->StopCastingBindSight(); } // StopCastingCharm may remove a possessed pet? if (!IsInWorld()) { sLog->outCrash( "Unit::SetCharmedBy: %u (GUID %u) is not in world but %u (GUID %u) is trying to charm it!", GetEntry(), GetGUIDLow(), charmer->GetEntry(), charmer->GetGUIDLow()); return false; } // charm is set by aura, and aura effect remove handler was called during apply handler execution // prevent undefined behaviour if (aurApp && aurApp->GetRemoveMode()) return false; // Set charmed Map* pMap = GetMap(); if (!IsVehicle() || (IsVehicle() && pMap && !pMap->IsBattleground())) setFaction( charmer->getFaction()); charmer->SetCharm(this, true); if (GetTypeId() == TYPEID_UNIT) { this->ToCreature()->AI()->OnCharmed(true); GetMotionMaster()->MoveIdle(); } else { if (this->ToPlayer()->isAFK()) this->ToPlayer()->ToggleAFK(); this->ToPlayer()->SetClientControl(this, 0); } // charm is set by aura, and aura effect remove handler was called during apply handler execution // prevent undefined behaviour if (aurApp && aurApp->GetRemoveMode()) return false; // Pets already have a properly initialized CharmInfo, don't overwrite it. if (type != CHARM_TYPE_VEHICLE && !GetCharmInfo()) { CharmInfo *charmInfo = InitCharmInfo(); if (type == CHARM_TYPE_POSSESS) charmInfo->InitPossessCreateSpells(); else charmInfo->InitCharmCreateSpells(); } if (charmer->GetTypeId() == TYPEID_PLAYER) { switch (type) { case CHARM_TYPE_VEHICLE: SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED); charmer->ToPlayer()->SetClientControl(this, 1); charmer->ToPlayer()->SetViewpoint(this, true); charmer->ToPlayer()->VehicleSpellInitialize(); break; case CHARM_TYPE_POSSESS: AddUnitState(UNIT_STAT_POSSESSED); SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED); charmer->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE); charmer->ToPlayer()->SetClientControl(this, 1); charmer->ToPlayer()->SetViewpoint(this, true); charmer->ToPlayer()->PossessSpellInitialize(); break; case CHARM_TYPE_CHARM: if (GetTypeId() == TYPEID_UNIT && charmer->getClass() == CLASS_WARLOCK) { CreatureInfo const *cinfo = this->ToCreature()->GetCreatureInfo(); if (cinfo && cinfo->type == CREATURE_TYPE_DEMON) { //to prevent client crash SetByteValue(UNIT_FIELD_BYTES_0, 1, (uint8) CLASS_MAGE); //just to enable stat window if (GetCharmInfo()) GetCharmInfo()->SetPetNumber( sObjectMgr->GeneratePetNumber(), true); //if charmed two demons the same session, the 2nd gets the 1st one's name SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, uint32(time(NULL))); // cast can't be helped } } charmer->ToPlayer()->CharmSpellInitialize(); break; default: case CHARM_TYPE_CONVERT: break; } } return true; } void Unit::RemoveCharmedBy(Unit *charmer) { if (!isCharmed()) return; if (!charmer) charmer = GetCharmer(); if (charmer != GetCharmer()) // one aura overrides another? { // sLog->outCrash("Unit::RemoveCharmedBy: this: " UI64FMTD " true charmer: " UI64FMTD " false charmer: " UI64FMTD, // GetGUID(), GetCharmerGUID(), charmer->GetGUID()); // ASSERT(false); return; } CharmType type; if (HasUnitState(UNIT_STAT_POSSESSED)) type = CHARM_TYPE_POSSESS; else if (charmer->IsOnVehicle(this)) type = CHARM_TYPE_VEHICLE; else type = CHARM_TYPE_CHARM; CastStop(); CombatStop(); //TODO: CombatStop(true) may cause crash (interrupt spells) getHostileRefManager().deleteReferences(); DeleteThreatList(); Map* pMap = GetMap(); if (!IsVehicle() || (IsVehicle() && pMap && !pMap->IsBattleground())) RestoreFaction(); GetMotionMaster()->InitDefault(); if (type == CHARM_TYPE_POSSESS) { ClearUnitState(UNIT_STAT_POSSESSED); RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED); } if (GetTypeId() == TYPEID_UNIT) { this->ToCreature()->AI()->OnCharmed(false); if (type != CHARM_TYPE_VEHICLE) //Vehicles' AI is never modified { this->ToCreature()->AIM_Initialize(); if (this->ToCreature()->AI() && charmer && charmer->isAlive()) this->ToCreature()->AI()->AttackStart( charmer); } } else this->ToPlayer()->SetClientControl(this, 1); // If charmer still exists if (!charmer) return; ASSERT(type != CHARM_TYPE_POSSESS || charmer->GetTypeId() == TYPEID_PLAYER); ASSERT(type != CHARM_TYPE_VEHICLE || (GetTypeId() == TYPEID_UNIT && IsVehicle())); charmer->SetCharm(this, false); if (charmer->GetTypeId() == TYPEID_PLAYER) { switch (type) { case CHARM_TYPE_VEHICLE: charmer->ToPlayer()->SetClientControl(charmer, 1); charmer->ToPlayer()->SetViewpoint(this, false); break; case CHARM_TYPE_POSSESS: charmer->ToPlayer()->SetClientControl(charmer, 1); charmer->ToPlayer()->SetViewpoint(this, false); charmer->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE); break; case CHARM_TYPE_CHARM: if (GetTypeId() == TYPEID_UNIT && charmer->getClass() == CLASS_WARLOCK) { CreatureInfo const *cinfo = this->ToCreature()->GetCreatureInfo(); if (cinfo && cinfo->type == CREATURE_TYPE_DEMON) { SetByteValue(UNIT_FIELD_BYTES_0, 1, uint8(cinfo->unit_class)); if (GetCharmInfo()) GetCharmInfo()->SetPetNumber(0, true); else sLog->outError( "Aura::HandleModCharm: target="UI64FMTD" with typeid=%d has a charm aura but no charm info!", GetGUID(), GetTypeId()); } } break; default: case CHARM_TYPE_CONVERT: break; } } //a guardian should always have charminfo if (charmer->GetTypeId() == TYPEID_PLAYER && this != charmer->GetFirstControlled()) charmer->ToPlayer()->SendRemoveControlBar(); else if (GetTypeId() == TYPEID_PLAYER || (GetTypeId() == TYPEID_UNIT && !this->ToCreature()->isGuardian())) DeleteCharmInfo(); } void Unit::RestoreFaction() { if (GetTypeId() == TYPEID_PLAYER) this->ToPlayer()->setFactionForRace( getRace()); else { if (HasUnitTypeMask(UNIT_MASK_MINION)) { if (Unit* owner = GetOwner()) { setFaction(owner->getFaction()); return; } } if (CreatureInfo const *cinfo = this->ToCreature()->GetCreatureInfo()) // normal creature { FactionTemplateEntry const *faction = getFactionTemplateEntry(); setFaction( (faction && faction->friendlyMask & 0x004) ? cinfo->faction_H : cinfo->faction_A); } } } bool Unit::CreateVehicleKit(uint32 id) { VehicleEntry const *vehInfo = sVehicleStore.LookupEntry(id); if (!vehInfo) return false; m_vehicleKit = new Vehicle(this, vehInfo); m_updateFlag |= UPDATEFLAG_VEHICLE; m_unitTypeMask |= UNIT_MASK_VEHICLE; return true; } void Unit::RemoveVehicleKit() { if (!m_vehicleKit) return; m_vehicleKit->Uninstall(); delete m_vehicleKit; m_vehicleKit = NULL; m_updateFlag &= ~UPDATEFLAG_VEHICLE; m_unitTypeMask &= ~UNIT_MASK_VEHICLE; RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK); RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_PLAYER_VEHICLE); } Unit *Unit::GetVehicleBase() const { return m_vehicle ? m_vehicle->GetBase() : NULL; } Creature *Unit::GetVehicleCreatureBase() const { if (Unit *veh = GetVehicleBase()) if (Creature *c = veh->ToCreature()) return c; return NULL; } uint64 Unit::GetTransGUID() const { if (GetVehicle()) return GetVehicle()->GetBase()->GetGUID(); if (GetTransport()) return GetTransport()->GetGUID(); return 0; } bool Unit::IsInPartyWith(Unit const *unit) const { if (this == unit) return true; const Unit *u1 = GetCharmerOrOwnerOrSelf(); const Unit *u2 = unit->GetCharmerOrOwnerOrSelf(); if (u1 == u2) return true; if (u1->GetTypeId() == TYPEID_PLAYER && u2->GetTypeId() == TYPEID_PLAYER) return u1->ToPlayer()->IsInSameGroupWith( u2->ToPlayer()); else return false; } bool Unit::IsInRaidWith(Unit const *unit) const { if (this == unit) return true; const Unit *u1 = GetCharmerOrOwnerOrSelf(); const Unit *u2 = unit->GetCharmerOrOwnerOrSelf(); if (u1 == u2) return true; if (u1->GetTypeId() == TYPEID_PLAYER && u2->GetTypeId() == TYPEID_PLAYER) return u1->ToPlayer()->IsInSameRaidWith( u2->ToPlayer()); else return false; } void Unit::GetRaidMember(std::list <Unit*> &nearMembers, float radius) { Player *owner = GetCharmerOrOwnerPlayerOrPlayerItself(); if (!owner) return; Group *pGroup = owner->GetGroup(); if (pGroup) { for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next()) { Player* Target = itr->getSource(); if (Target && !IsHostileTo(Target)) { if (Target->isAlive() && IsWithinDistInMap(Target, radius)) nearMembers.push_back( Target); if (Guardian* pet = Target->GetGuardianPet()) if (pet->isAlive() && IsWithinDistInMap(pet, radius)) nearMembers.push_back( pet); } } } else { if (owner->isAlive() && (owner == this || IsWithinDistInMap(owner, radius))) nearMembers.push_back( owner); if (Guardian* pet = owner->GetGuardianPet()) if (pet->isAlive() && (pet == this && IsWithinDistInMap(pet, radius))) nearMembers.push_back( pet); } } void Unit::GetPartyMemberInDist(std::list <Unit*> &TagUnitMap, float radius) { Unit *owner = GetCharmerOrOwnerOrSelf(); Group *pGroup = NULL; if (owner->GetTypeId() == TYPEID_PLAYER) pGroup = owner->ToPlayer()->GetGroup(); if (pGroup) { uint8 subgroup = owner->ToPlayer()->GetSubGroup(); for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next()) { Player* Target = itr->getSource(); // IsHostileTo check duel and controlled by enemy if (Target && Target->GetSubGroup() == subgroup && !IsHostileTo(Target)) { if (Target->isAlive() && IsWithinDistInMap(Target, radius)) TagUnitMap.push_back( Target); if (Guardian* pet = Target->GetGuardianPet()) if (pet->isAlive() && IsWithinDistInMap(pet, radius)) TagUnitMap.push_back( pet); } } } else { if (owner->isAlive() && (owner == this || IsWithinDistInMap(owner, radius))) TagUnitMap.push_back( owner); if (Guardian* pet = owner->GetGuardianPet()) if (pet->isAlive() && (pet == this && IsWithinDistInMap(pet, radius))) TagUnitMap.push_back( pet); } } void Unit::GetPartyMembers(std::list <Unit*> &TagUnitMap) { Unit *owner = GetCharmerOrOwnerOrSelf(); Group *pGroup = NULL; if (owner->GetTypeId() == TYPEID_PLAYER) pGroup = owner->ToPlayer()->GetGroup(); if (pGroup) { uint8 subgroup = owner->ToPlayer()->GetSubGroup(); for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next()) { Player* Target = itr->getSource(); // IsHostileTo check duel and controlled by enemy if (Target && Target->GetSubGroup() == subgroup && !IsHostileTo(Target)) { if (Target->isAlive() && IsInMap(Target)) TagUnitMap.push_back( Target); if (Guardian* pet = Target->GetGuardianPet()) if (pet->isAlive() && IsInMap(Target)) TagUnitMap.push_back(pet); } } } else { if (owner->isAlive() && (owner == this || IsInMap(owner))) TagUnitMap.push_back( owner); if (Guardian* pet = owner->GetGuardianPet()) if (pet->isAlive() && (pet == this || IsInMap(pet))) TagUnitMap.push_back(pet); } } Aura * Unit::AddAura(uint32 spellId, Unit *target) { if (!target) return NULL; SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId); if (!spellInfo) return NULL; if (!target->isAlive() && !(spellInfo->Attributes & SPELL_ATTR0_PASSIVE) && !(spellInfo->AttributesEx2 & SPELL_ATTR2_ALLOW_DEAD_TARGET)) return NULL; return AddAura(spellInfo, MAX_EFFECT_MASK, target); } Aura * Unit::AddAura(SpellEntry const *spellInfo, uint8 effMask, Unit *target) { if (!spellInfo) return NULL; if (target->IsImmunedToSpell(spellInfo)) return NULL; for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (!(effMask & (1 << i))) continue; if (target->IsImmunedToSpellEffect(spellInfo, i)) effMask &= ~(1 << i); } if (Aura * aura = Aura::TryCreate(spellInfo, effMask, target, this)) { aura->ApplyForTargets(); return aura; } return NULL; } void Unit::SetAuraStack(uint32 spellId, Unit *target, uint32 stack) { Aura *aura = target->GetAura(spellId, GetGUID()); if (!aura) aura = AddAura(spellId, target); if (aura && stack) aura->SetStackAmount(stack); } void Unit::ApplyResilience(const Unit *pVictim, int32 *damage) const { if (IsVehicle() || pVictim->IsVehicle()) return; const Unit *source = ToPlayer(); if (!source) { source = ToCreature(); if (source) { source = source->ToCreature()->GetOwner(); if (source) source = source->ToPlayer(); } } const Unit *target = pVictim->ToPlayer(); if (!target) { target = pVictim->ToCreature(); if (target) { target = target->ToCreature()->GetOwner(); if (target) target = target->ToPlayer(); } } if (!target) return; if (source && damage) { *damage -= target->ToPlayer()->GetPlayerDamageReduction(*damage); } } // Melee based spells can be miss, parry or dodge on this step // Crit or block - determined on damage calculation phase! (and can be both in some time) float Unit::MeleeSpellMissChance(const Unit *pVictim, WeaponAttackType attType, int32 skillDiff, uint32 spellId) const { // Calculate hit chance (more correct for chance mod) int32 HitChance; // PvP - PvE melee chances if (spellId || attType == RANGED_ATTACK || !haveOffhandWeapon()) HitChance = 95; else HitChance = 76; // Hit chance depends from victim auras if (attType == RANGED_ATTACK) HitChance += pVictim->GetTotalAuraModifier( SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE); else HitChance += pVictim->GetTotalAuraModifier( SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE); // Spellmod from SPELLMOD_RESIST_MISS_CHANCE if (spellId) { if (Player *modOwner = GetSpellModOwner()) modOwner->ApplySpellMod( spellId, SPELLMOD_RESIST_MISS_CHANCE, HitChance); } // Miss = 100 - hit float miss_chance = 100.0f - HitChance; // Bonuses from attacker aura and ratings if (attType == RANGED_ATTACK) miss_chance -= m_modRangedHitChance; else miss_chance -= m_modMeleeHitChance; // bonus from skills is 0.04% //miss_chance -= skillDiff * 0.04f; int32 diff = -skillDiff; if (pVictim->GetTypeId() == TYPEID_PLAYER) miss_chance += diff > 0 ? diff * 0.04f : diff * 0.02f; else miss_chance += diff > 10 ? 2 + (diff - 10) * 0.4f : diff * 0.1f; // Limit miss chance from 0 to 60% if (miss_chance < 0.0f) return 0.0f; if (miss_chance > 60.0f) return 60.0f; return miss_chance; } void Unit::SetPhaseMask(uint32 newPhaseMask, bool update) { if (newPhaseMask == GetPhaseMask()) return; if (IsInWorld()) RemoveNotOwnSingleTargetAuras(newPhaseMask); // we can lost access to caster or target WorldObject::SetPhaseMask(newPhaseMask, update); if (!IsInWorld()) return; for (ControlList::const_iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr) if ((*itr)->GetTypeId() == TYPEID_UNIT) (*itr)->SetPhaseMask( newPhaseMask, true); for (uint8 i = 0; i < MAX_SUMMON_SLOT; ++i) if (m_SummonSlot [i]) if (Creature *summon = GetMap()->GetCreature(m_SummonSlot[i])) summon->SetPhaseMask( newPhaseMask, true); } void Unit::UpdateObjectVisibility(bool forced) { if (!forced) AddToNotify(NOTIFY_VISIBILITY_CHANGED); else { WorldObject::UpdateObjectVisibility(true); // call MoveInLineOfSight for nearby creatures Trinity::AIRelocationNotifier notifier(*this); VisitNearbyObject(GetVisibilityRange(), notifier); } } void Unit::KnockbackFrom(float x, float y, float speedXY, float speedZ) { Player *player = NULL; if (GetTypeId() == TYPEID_PLAYER) player = (Player*) this; else { player = dynamic_cast <Player*>(GetCharmer()); if (player && player->m_mover != this) player = NULL; } if (!player) { GetMotionMaster()->MoveKnockbackFrom(x, y, speedXY, speedZ); } else { float vcos, vsin; GetSinCos(x, y, vsin, vcos); WorldPacket data(SMSG_MULTIPLE_PACKETS, (2 + 8 + 4 + 4 + 4 + 4 + 4)); //WorldPacket data(/*SMSG_MOVE_KNOCK_BACK*/, (8+4+4+4+4+4)); data << uint16(SMSG_MOVE_KNOCK_BACK); data.append(GetPackGUID()); data << uint32(0); // Sequence data << float(vcos); // x direction data << float(vsin); // y direction data << float(speedXY); // Horizontal speed data << float(-speedZ); // Z Movement speed (vertical) player->GetSession()->SendPacket(&data); } } float Unit::GetCombatRatingReduction(CombatRating cr) const { if (GetTypeId() == TYPEID_PLAYER) return ((Player const*) this)->GetRatingBonusValue( cr); else if (((Creature const*) this)->isPet()) { // Player's pet get resilience from owner if (Unit* owner = GetOwner()) if (owner->GetTypeId() == TYPEID_PLAYER) return ((Player*) owner)->GetRatingBonusValue( cr); } return 0.0f; } uint32 Unit::GetCombatRatingDamageReduction(CombatRating cr, float rate, float cap, uint32 damage) const { float percent = GetCombatRatingReduction(cr) * rate; if (percent > cap) percent = cap; return uint32(percent * damage / 100.0f); } uint32 Unit::GetModelForForm(ShapeshiftForm form) { switch (form) { case FORM_CAT: // Based on Hair color if (getRace() == RACE_NIGHTELF) { uint8 hairColor = GetByteValue(PLAYER_BYTES, 3); switch (hairColor) { case 7: // Violet case 8: return 29405; case 3: // Light Blue return 29406; case 0: // Green case 1: // Light Green case 2: // Dark Green return 29407; case 4: // White return 29408; default: // original - Dark Blue return 892; } } else if (getRace() == RACE_TROLL) { uint8 hairColor = GetByteValue(PLAYER_BYTES, 3); switch (hairColor) { case 0: // Red case 1: return 33668; case 2: // Yellow case 3: return 33667; case 4: // Blue case 5: case 6: return 33666; case 7: // Purple case 10: return 33665; default: // original - white return 33669; } } else if (getRace() == RACE_WORGEN) { // Based on Skin color uint8 skinColor = GetByteValue(PLAYER_BYTES, 0); // Male if (getGender() == GENDER_MALE) { switch (skinColor) { case 1: // Brown return 33662; case 2: // Black case 7: return 33661; case 4: // yellow return 33664; case 3: // White case 5: return 33663; default: // original - Gray return 33660; } } // Female else { switch (skinColor) { case 5: // Brown case 6: return 33662; case 7: // Black case 8: return 33661; case 3: // yellow case 4: return 33664; case 2: // White return 33663; default: // original - Gray return 33660; } } } // Based on Skin color else if (getRace() == RACE_TAUREN) { uint8 skinColor = GetByteValue(PLAYER_BYTES, 0); // Male if (getGender() == GENDER_MALE) { switch (skinColor) { case 12: // White case 13: case 14: case 18: // Completly White return 29409; case 9: // Light Brown case 10: case 11: return 29410; case 6: // Brown case 7: case 8: return 29411; case 0: // Dark case 1: case 2: case 3: // Dark Grey case 4: case 5: return 29412; default: // original - Grey return 8571; } } // Female else { switch (skinColor) { case 10: // White return 29409; case 6: // Light Brown case 7: return 29410; case 4: // Brown case 5: return 29411; case 0: // Dark case 1: case 2: case 3: return 29412; default: // original - Grey return 8571; } } } else if (Player::TeamForRace(getRace()) == ALLIANCE) return 892; else return 8571; case FORM_DIREBEAR: case FORM_BEAR: // Based on Hair color if (getRace() == RACE_NIGHTELF) { uint8 hairColor = GetByteValue(PLAYER_BYTES, 3); switch (hairColor) { case 0: // Green case 1: // Light Green case 2: // Dark Green return 29413; // 29415? case 6: // Dark Blue return 29414; case 4: // White return 29416; case 3: // Light Blue return 29417; default: // original - Violet return 2281; } } else if (getRace() == RACE_TROLL) { uint8 hairColor = GetByteValue(PLAYER_BYTES, 3); switch (hairColor) { case 0: // Red case 1: return 33657; case 2: // Yellow case 3: return 33659; case 7: // Purple case 10: return 33656; case 8: // White case 9: case 11: case 12: return 33658; default: // original - Blue return 33655; } } else if (getRace() == RACE_WORGEN) { // Based on Skin color uint8 skinColor = GetByteValue(PLAYER_BYTES, 0); // Male if (getGender() == GENDER_MALE) { switch (skinColor) { case 1: // Brown return 33652; case 2: // Black case 7: return 33651; case 4: // Yellow return 33653; case 3: // White case 5: return 33654; default: // original - Gray return 33650; } } // Female else { switch (skinColor) { case 5: // Brown case 6: return 33652; case 7: // Black case 8: return 33651; case 3: // yellow case 4: return 33654; case 2: // White return 33653; default: // original - Gray return 33650; } } } // Based on Skin color else if (getRace() == RACE_TAUREN) { uint8 skinColor = GetByteValue(PLAYER_BYTES, 0); // Male if (getGender() == GENDER_MALE) { switch (skinColor) { case 0: // Dark (Black) case 1: case 2: return 29418; case 3: // White case 4: case 5: case 12: case 13: case 14: return 29419; case 9: // Light Brown/Grey case 10: case 11: case 15: case 16: case 17: return 29420; case 18: // Completly White return 29421; default: // original - Brown return 2289; } } // Female else { switch (skinColor) { case 0: // Dark (Black) case 1: return 29418; case 2: // White case 3: return 29419; case 6: // Light Brown/Grey case 7: case 8: case 9: return 29420; case 10: // Completly White return 29421; default: // original - Brown return 2289; } } } else if (Player::TeamForRace(getRace()) == ALLIANCE) return 2281; else return 2289; case FORM_FLIGHT: switch (getRace()) { case RACE_NIGHTELF: return 20857; case RACE_WORGEN: return 37727; case RACE_TROLL: return 37728; default: // RACE_TAUREN return 20872; } case FORM_FLIGHT_EPIC: switch (getRace()) { case RACE_NIGHTELF: return 21243; case RACE_WORGEN: return 37729; case RACE_TROLL: return 37730; default: // RACE_TAUREN return 21244; } default: { uint32 modelid = 0; SpellShapeshiftFormEntry const* formEntry = sSpellShapeshiftFormStore.LookupEntry(form); if (formEntry && formEntry->modelID_A) { // Take the alliance modelid as default if (GetTypeId() != TYPEID_PLAYER) return formEntry->modelID_A; else { if (Player::TeamForRace(getRace()) == ALLIANCE) modelid = formEntry->modelID_A; else modelid = formEntry->modelID_H; // If the player is horde but there are no values for the horde modelid - take the alliance modelid if (!modelid && Player::TeamForRace(getRace()) == HORDE) modelid = formEntry->modelID_A; } } return modelid; } } return 0; } uint32 Unit::GetModelForTotem(PlayerTotemType totemType) { switch (getRace()) { case RACE_ORC: { switch (totemType) { case SUMMON_TYPE_TOTEM_FIRE: //fire return 30758; case SUMMON_TYPE_TOTEM_EARTH: //earth return 30757; case SUMMON_TYPE_TOTEM_WATER: //water return 30759; case SUMMON_TYPE_TOTEM_AIR: //air return 30756; } break; } case RACE_DWARF: { switch (totemType) { case SUMMON_TYPE_TOTEM_FIRE: //fire return 30754; case SUMMON_TYPE_TOTEM_EARTH: //earth return 30753; case SUMMON_TYPE_TOTEM_WATER: //water return 30755; case SUMMON_TYPE_TOTEM_AIR: //air return 30736; } break; } case RACE_TROLL: { switch (totemType) { case SUMMON_TYPE_TOTEM_FIRE: //fire return 30762; case SUMMON_TYPE_TOTEM_EARTH: //earth return 30761; case SUMMON_TYPE_TOTEM_WATER: //water return 30763; case SUMMON_TYPE_TOTEM_AIR: //air return 30760; } break; } case RACE_TAUREN: { switch (totemType) { case SUMMON_TYPE_TOTEM_FIRE: //fire return 4589; case SUMMON_TYPE_TOTEM_EARTH: //earth return 4588; case SUMMON_TYPE_TOTEM_WATER: //water return 4587; case SUMMON_TYPE_TOTEM_AIR: //air return 4590; } break; } case RACE_DRAENEI: { switch (totemType) { case SUMMON_TYPE_TOTEM_FIRE: //fire return 19074; case SUMMON_TYPE_TOTEM_EARTH: //earth return 19073; case SUMMON_TYPE_TOTEM_WATER: //water return 19075; case SUMMON_TYPE_TOTEM_AIR: //air return 19071; } break; } case RACE_GOBLIN: { switch (totemType) { case SUMMON_TYPE_TOTEM_FIRE: //fire return 30783; case SUMMON_TYPE_TOTEM_EARTH: //earth return 30782; case SUMMON_TYPE_TOTEM_WATER: //water return 30784; case SUMMON_TYPE_TOTEM_AIR: //air return 30781; } break; } } return 0; } void Unit::JumpTo(float speedXY, float speedZ, bool forward) { float angle = forward ? 0 : M_PI; if (GetTypeId() == TYPEID_UNIT) GetMotionMaster()->MoveJumpTo(angle, speedXY, speedZ); else { float vcos = cos(angle + GetOrientation()); float vsin = sin(angle + GetOrientation()); WorldPacket data(SMSG_MULTIPLE_PACKETS, (2 + 8 + 4 + 4 + 4 + 4 + 4)); //WorldPacket data(SMSG_MOVE_KNOCK_BACK, (8+4+4+4+4+4)); data << uint16(SMSG_MOVE_KNOCK_BACK); data.append(GetPackGUID()); data << uint32(0); // Sequence data << float(vcos); // x direction data << float(vsin); // y direction data << float(speedXY); // Horizontal speed data << float(-speedZ); // Z Movement speed (vertical) this->ToPlayer()->GetSession()->SendPacket(&data); } } void Unit::JumpTo(WorldObject *obj, float speedZ) { float x, y, z; obj->GetContactPoint(this, x, y, z); float speedXY = GetExactDist2d(x, y) * 10.0f / speedZ; GetMotionMaster()->MoveJump(x, y, z, speedXY, speedZ); } bool Unit::CheckPlayerCondition(Player* pPlayer) { switch (GetEntry()) { case 35644: //Argent Warhorse case 36558: //Argent Battleworg if (!pPlayer->HasItemOrGemWithIdEquipped(46106, 1)) //Check item Argent Lance return false; default: return true; } } void Unit::EnterVehicle(Vehicle *vehicle, int8 seatId, bool byAura) { if (!isAlive() || GetVehicleKit() == vehicle) return; if (m_vehicle) { if (m_vehicle == vehicle) { if (seatId >= 0 && seatId != GetTransSeat()) { sLog->outDebug( LOG_FILTER_UNITS, "EnterVehicle: %u leave vehicle %u seat %d and enter %d.", GetEntry(), m_vehicle->GetBase()->GetEntry(), GetTransSeat(), seatId); ChangeSeat(seatId, byAura); } return; } else { sLog->outDebug(LOG_FILTER_UNITS, "EnterVehicle: %u exit %u and enter %u.", GetEntry(), m_vehicle->GetBase()->GetEntry(), vehicle->GetBase()->GetEntry()); ExitVehicle(); } } if (Player* plr = ToPlayer()) { if (vehicle->GetBase()->GetTypeId() == TYPEID_PLAYER && plr->isInCombat()) return; InterruptNonMeleeSpells(false); plr->StopCastingCharm(); plr->StopCastingBindSight(); Unmount(); RemoveAurasByType(SPELL_AURA_MOUNTED); // drop flag at invisible in bg if (Battleground *bg = plr->GetBattleground()) bg->EventPlayerDroppedFlag( plr); } ASSERT(!m_vehicle); m_vehicle = vehicle; if (!m_vehicle->AddPassenger(this, seatId, byAura)) { m_vehicle = NULL; return; } if (Player* thisPlr = this->ToPlayer()) { WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0); thisPlr->GetSession()->SendPacket(&data); thisPlr->SendClearFocus(vehicle->GetBase()); } SetControlled(true, UNIT_STAT_ROOT); //movementInfo is set in AddPassenger //packets are sent in AddPassenger } void Unit::ChangeSeat(int8 seatId, bool next, bool byAura) { if (!m_vehicle) return; if (seatId < 0) { seatId = m_vehicle->GetNextEmptySeat(GetTransSeat(), next, byAura); if (seatId < 0) return; } else if (seatId == GetTransSeat() || !m_vehicle->HasEmptySeat(seatId)) return; m_vehicle->RemovePassenger(this); if (!m_vehicle->AddPassenger(this, seatId, byAura)) ASSERT(false); } void Unit::ExitVehicle() { if (!m_vehicle) return; Unit *vehicleBase = m_vehicle->GetBase(); const AuraEffectList &modAuras = vehicleBase->GetAuraEffectsByType( SPELL_AURA_CONTROL_VEHICLE); for (AuraEffectList::const_iterator itr = modAuras.begin(); itr != modAuras.end(); ++itr) { if ((*itr)->GetBase()->GetOwner() == this) { vehicleBase->RemoveAura((*itr)->GetBase()); break; // there should be no case that a vehicle has two auras for one owner } } if (!m_vehicle) return; //sLog->outError("exit vehicle"); m_vehicle->RemovePassenger(this); // This should be done before dismiss, because there may be some aura removal Vehicle *vehicle = m_vehicle; m_vehicle = NULL; SetControlled(false, UNIT_STAT_ROOT); RemoveUnitMovementFlag(MOVEMENTFLAG_ONTRANSPORT | MOVEMENTFLAG_ROOT); m_movementInfo.t_pos.Relocate(0, 0, 0, 0); m_movementInfo.t_time = 0; m_movementInfo.t_seat = 0; Relocate(vehicle->GetBase()); //Send leave vehicle, not correct if (GetTypeId() == TYPEID_PLAYER) { //this->ToPlayer()->SetClientControl(this, 1); this->ToPlayer()->SendTeleportAckPacket(); this->ToPlayer()->SetFallInformation(0, GetPositionZ()); } WorldPacket data; BuildHeartBeatMsg(&data); SendMessageToSet(&data, false); if (vehicle->GetBase()->HasUnitTypeMask(UNIT_MASK_MINION)) if (((Minion*) vehicle->GetBase())->GetOwner() == this) vehicle->Dismiss(); } void Unit::BuildMovementPacket(ByteBuffer *data) const { switch (GetTypeId()) { case TYPEID_UNIT: if (canFly()) const_cast <Unit*>(this)->AddUnitMovementFlag( MOVEMENTFLAG_LEVITATING); if (IsVehicle()) const_cast <Unit*>(this)->AddExtraUnitMovementFlag( GetVehicleKit()->GetExtraMovementFlagsForBase()); break; case TYPEID_PLAYER: // remove unknown, unused etc flags for now const_cast <Unit*>(this)->RemoveUnitMovementFlag( MOVEMENTFLAG_SPLINE_ENABLED); if (isInFlight()) { WPAssert( const_cast<Unit*>(this)->GetMotionMaster()->GetCurrentMovementGeneratorType() == FLIGHT_MOTION_TYPE); const_cast <Unit*>(this)->AddUnitMovementFlag( MOVEMENTFLAG_FORWARD | MOVEMENTFLAG_SPLINE_ENABLED); } break; default: break; } if (Vehicle* pVehicle = GetVehicle()) if (!HasUnitMovementFlag( MOVEMENTFLAG_ROOT)) sLog->outError( "Unit (GUID: " UI64FMTD ", entry: %u) does not have MOVEMENTFLAG_ROOT but is in vehicle (ID: %u)!", GetGUID(), GetEntry(), pVehicle->GetVehicleInfo()->m_ID); *data << uint32(GetUnitMovementFlags()); // movement flags *data << uint16(m_movementInfo.flags2); // 2.3.0 *data << uint32(getMSTime()); // time *data << GetPositionX(); *data << GetPositionY(); *data << GetPositionZ(); *data << GetOrientation(); // 0x00000200 if (GetUnitMovementFlags() & MOVEMENTFLAG_ONTRANSPORT) { if (m_vehicle) data->append(m_vehicle->GetBase()->GetPackGUID()); else if (GetTransport()) data->append(GetTransport()->GetPackGUID()); else *data << (uint8) 0; *data << float(GetTransOffsetX()); *data << float(GetTransOffsetY()); *data << float(GetTransOffsetZ()); *data << float(GetTransOffsetO()); *data << uint32(GetTransTime()); *data << uint8(GetTransSeat()); if (m_movementInfo.flags2 & MOVEMENTFLAG2_INTERPOLATED_MOVEMENT) // & 0x400, 4.0.3 *data << uint32(m_movementInfo.t_time2); } // 0x02200000 if ((GetUnitMovementFlags() & (MOVEMENTFLAG_SWIMMING | MOVEMENTFLAG_FLYING)) || (m_movementInfo.flags2 & MOVEMENTFLAG2_ALWAYS_ALLOW_PITCHING)) *data << (float) m_movementInfo.pitch; //4.0.6 if (m_movementInfo.flags2 & MOVEMENTFLAG2_INTERPOLATED_TURNING) // & 0x800, 4.0.6 { *data << (uint32) m_movementInfo.fallTime; *data << (float) m_movementInfo.j_zspeed; // 0x00001000 if (GetUnitMovementFlags() & MOVEMENTFLAG_JUMPING) { *data << (float) m_movementInfo.j_sinAngle; *data << (float) m_movementInfo.j_cosAngle; *data << (float) m_movementInfo.j_xyspeed; } } // 0x04000000 if (GetUnitMovementFlags() & MOVEMENTFLAG_SPLINE_ELEVATION) *data << (float) m_movementInfo.splineElevation; } void Unit::SetFlying(bool apply) { if (apply) { SetByteFlag(UNIT_FIELD_BYTES_1, 3, 0x02); AddUnitMovementFlag(MOVEMENTFLAG_CAN_FLY | MOVEMENTFLAG_FLYING); } else { RemoveByteFlag(UNIT_FIELD_BYTES_1, 3, 0x02); RemoveUnitMovementFlag(MOVEMENTFLAG_CAN_FLY | MOVEMENTFLAG_FLYING); } } void Unit::NearTeleportTo(float x, float y, float z, float orientation, bool casting /*= false*/) { if (GetTypeId() == TYPEID_PLAYER) this->ToPlayer()->TeleportTo( GetMapId(), x, y, z, orientation, TELE_TO_NOT_LEAVE_TRANSPORT | TELE_TO_NOT_LEAVE_COMBAT | TELE_TO_NOT_UNSUMMON_PET | (casting ? TELE_TO_SPELL : 0)); else { // FIXME: this interrupts spell visual DestroyForNearbyPlayers(); SetPosition(x, y, z, orientation, true); } } bool Unit::SetPosition(float x, float y, float z, float orientation, bool teleport) { // prevent crash when a bad coord is sent by the client if (!Trinity::IsValidMapCoord(x, y, z, orientation)) { sLog->outDebug(LOG_FILTER_UNITS, "Unit::SetPosition(%f, %f, %f) .. bad coordinates!", x, y, z); return false; } bool turn = (GetOrientation() != orientation); bool relocated = (teleport || GetPositionX() != x || GetPositionY() != y || GetPositionZ() != z); if (turn) RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING); if (relocated) { RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE); // move and update visible state if need if (GetTypeId() == TYPEID_PLAYER) GetMap()->PlayerRelocation( (Player*) this, x, y, z, orientation); else GetMap()->CreatureRelocation(this->ToCreature(), x, y, z, orientation); } else if (turn) SetOrientation(orientation); if ((relocated || turn) && IsVehicle()) GetVehicleKit()->RelocatePassengers( x, y, z, orientation); return (relocated || turn); } bool Unit::UpdatePosition(float x, float y, float z, float orientation, bool teleport) { // prevent crash when a bad coord is sent by the client if (!Trinity::IsValidMapCoord(x, y, z, orientation)) { sLog->outDebug(LOG_FILTER_UNITS, "Unit::UpdatePosition(%f, %f, %f) .. bad coordinates!", x, y, z); return false; } bool turn = (GetOrientation() != orientation); bool relocated = (teleport || GetPositionX() != x || GetPositionY() != y || GetPositionZ() != z); if (turn) RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING); if (relocated) { RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE); // move and update visible state if need if (GetTypeId() == TYPEID_PLAYER) GetMap()->PlayerRelocation(ToPlayer(), x, y, z, orientation); else GetMap()->CreatureRelocation(ToCreature(), x, y, z, orientation); } else if (turn) SetOrientation(orientation); if ((relocated || turn) && IsVehicle()) GetVehicleKit()->RelocatePassengers( x, y, z, orientation); return (relocated || turn); } void Unit::SendThreatListUpdate() { if (uint32 count = getThreatManager().getThreatList().size()) { //sLog->outDebug(LOG_FILTER_UNITS, "WORLD: Send SMSG_THREAT_UPDATE Message"); WorldPacket data(SMSG_THREAT_UPDATE, 8 + count * 8); data.append(GetPackGUID()); data << uint32(count); std::list <HostileReference*>& tlist = getThreatManager().getThreatList(); for (std::list <HostileReference*>::const_iterator itr = tlist.begin(); itr != tlist.end(); ++itr) { data.appendPackGUID((*itr)->getUnitGuid()); data << uint32((*itr)->getThreat() * 100); } SendMessageToSet(&data, false); } } void Unit::SendChangeCurrentVictimOpcode(HostileReference* pHostileReference) { if (uint32 count = getThreatManager().getThreatList().size()) { sLog->outDebug(LOG_FILTER_UNITS, "WORLD: Send SMSG_HIGHEST_THREAT_UPDATE Message"); WorldPacket data(SMSG_HIGHEST_THREAT_UPDATE, 8 + 8 + count * 8); data.append(GetPackGUID()); data.appendPackGUID(pHostileReference->getUnitGuid()); data << uint32(count); std::list <HostileReference*>& tlist = getThreatManager().getThreatList(); for (std::list <HostileReference*>::const_iterator itr = tlist.begin(); itr != tlist.end(); ++itr) { data.appendPackGUID((*itr)->getUnitGuid()); data << uint32((*itr)->getThreat()); } SendMessageToSet(&data, false); } } void Unit::SendClearThreatListOpcode() { sLog->outDebug(LOG_FILTER_UNITS, "WORLD: Send SMSG_THREAT_CLEAR Message"); WorldPacket data(SMSG_THREAT_CLEAR, 8); data.append(GetPackGUID()); SendMessageToSet(&data, false); } void Unit::SendRemoveFromThreatListOpcode(HostileReference* pHostileReference) { sLog->outDebug(LOG_FILTER_UNITS, "WORLD: Send SMSG_THREAT_REMOVE Message"); WorldPacket data(SMSG_THREAT_REMOVE, 8 + 8); data.append(GetPackGUID()); data.appendPackGUID(pHostileReference->getUnitGuid()); SendMessageToSet(&data, false); } void Unit::RewardRage(uint32 damage, uint32 weaponSpeedHitFactor, bool attacker) { float addRage; float rageconversion = ((0.0091107836f * getLevel() * getLevel()) + 3.225598133f * getLevel()) + 4.2652911f; // Unknown if correct, but lineary adjust rage conversion above level 70 if (getLevel() > 70) rageconversion += 13.27f * (getLevel() - 70); if (attacker) { addRage = ((damage / rageconversion * 7.5f + weaponSpeedHitFactor) / 2); // talent who gave more rage on attack addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f; } else { addRage = damage / rageconversion * 2.5f; // Berserker Rage effect if (HasAura(18499)) addRage *= 2.0f; } addRage *= sWorld->getRate(RATE_POWER_RAGE_INCOME); ModifyPower(POWER_RAGE, uint32(addRage * 10)); } void Unit::StopAttackFaction(uint32 faction_id) { if (Unit* victim = getVictim()) { if (victim->getFactionTemplateEntry()->faction == faction_id) { AttackStop(); if (IsNonMeleeSpellCasted(false)) InterruptNonMeleeSpells(false); // melee and ranged forced attack cancel if (GetTypeId() == TYPEID_PLAYER) this->ToPlayer()->SendAttackSwingCancelAttack(); } } AttackerSet const& attackers = getAttackers(); for (AttackerSet::const_iterator itr = attackers.begin(); itr != attackers.end();) { if ((*itr)->getFactionTemplateEntry()->faction == faction_id) { (*itr)->AttackStop(); itr = attackers.begin(); } else ++itr; } getHostileRefManager().deleteReferencesForFaction(faction_id); for (ControlList::const_iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr) (*itr)->StopAttackFaction(faction_id); } void Unit::OutDebugInfo() const { sLog->outError("Unit::OutDebugInfo"); sLog->outString("GUID "UI64FMTD", entry %u, type %u, name %s", GetGUID(), GetEntry(), (uint32) GetTypeId(), GetName()); sLog->outString( "OwnerGUID "UI64FMTD", MinionGUID "UI64FMTD", CharmerGUID "UI64FMTD", CharmedGUID "UI64FMTD, GetOwnerGUID(), GetMinionGUID(), GetCharmerGUID(), GetCharmGUID()); sLog->outString("In world %u, unit type mask %u", (uint32) (IsInWorld() ? 1 : 0), m_unitTypeMask); if (IsInWorld()) sLog->outString("Mapid %u", GetMapId()); sLog->outStringInLine("Summon Slot: "); for (uint32 i = 0; i < MAX_SUMMON_SLOT; ++i) sLog->outStringInLine(UI64FMTD", ", m_SummonSlot [i]); sLog->outString(); sLog->outStringInLine("Controlled List: "); for (ControlList::const_iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr) sLog->outStringInLine(UI64FMTD", ", (*itr)->GetGUID()); sLog->outString(); sLog->outStringInLine("Aura List: "); for (AuraApplicationMap::const_iterator itr = m_appliedAuras.begin(); itr != m_appliedAuras.end(); ++itr) sLog->outStringInLine("%u, ", itr->first); sLog->outString(); if (IsVehicle()) { sLog->outStringInLine("Passenger List: "); for (SeatMap::iterator itr = GetVehicleKit()->m_Seats.begin(); itr != GetVehicleKit()->m_Seats.end(); ++itr) if (Unit *passenger = itr->second.passenger) sLog->outStringInLine(UI64FMTD", ", passenger->GetGUID()); sLog->outString(); } if (GetVehicle()) sLog->outString("On vehicle %u.", GetVehicleBase()->GetEntry()); } void Unit::SendClearTarget() { WorldPacket data(SMSG_BREAK_TARGET, GetPackGUID().size()); data.append(GetPackGUID()); SendMessageToSet(&data, false); } uint32 Unit::GetResistance(SpellSchoolMask mask) const { int32 resist = -1; for (int i = SPELL_SCHOOL_NORMAL; i < MAX_SPELL_SCHOOL; ++i) if (mask & (1 << i) && (resist < 0 || resist > int32(GetResistance(SpellSchools(i))))) resist = int32(GetResistance(SpellSchools(i))); // resist value will never be negative here return uint32(resist); } uint32 Unit::GetRemainingDotDamage(uint64 caster, uint32 spellId, uint8 effectIndex) const { uint32 amount = 0; AuraEffectList const& DoTAuras = GetAuraEffectsByType( SPELL_AURA_PERIODIC_DAMAGE); for (AuraEffectList::const_iterator i = DoTAuras.begin(); i != DoTAuras.end(); ++i) { if ((*i)->GetCasterGUID() != caster || (*i)->GetId() != spellId || (*i)->GetEffIndex() != effectIndex) continue; amount += ((*i)->GetAmount() * ((*i)->GetTotalTicks() - ((*i)->GetTickNumber()))) / (*i)->GetTotalTicks(); break; } return amount; } bool Unit::IsVisionObscured(Unit* pVictim) { Aura* victimAura = NULL; Aura* myAura = NULL; Unit* victimCaster = NULL; Unit* myCaster = NULL; AuraEffectList const& vAuras = pVictim->GetAuraEffectsByType( SPELL_AURA_INTERFERE_TARGETTING); for (AuraEffectList::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i) { victimAura = (*i)->GetBase(); victimCaster = victimAura->GetCaster(); break; } AuraEffectList const& myAuras = GetAuraEffectsByType( SPELL_AURA_INTERFERE_TARGETTING); for (AuraEffectList::const_iterator i = myAuras.begin(); i != myAuras.end(); ++i) { myAura = (*i)->GetBase(); myCaster = myAura->GetCaster(); break; } if ((myAura != NULL && myCaster == NULL) || (victimAura != NULL && victimCaster == NULL)) return false; // Failed auras, will result in crash // E.G. Victim is in smoke bomb, and I'm not // Spells fail unless I'm friendly to the caster of victim's smoke bomb if (victimAura != NULL && myAura == NULL) { if (IsFriendlyTo(victimCaster)) return false; else return true; } // Victim is not in smoke bomb, while I am // Spells fail if my smoke bomb aura's caster is my enemy else if (myAura != NULL && victimAura == NULL) { if (IsFriendlyTo(myCaster)) return false; else return true; } return false; } void CharmInfo::SetIsCommandAttack(bool val) { m_isCommandAttack = val; } bool CharmInfo::IsCommandAttack() { return m_isCommandAttack; } void CharmInfo::SaveStayPosition() { m_unit->GetPosition(m_stayX, m_stayY, m_stayZ); } void CharmInfo::GetStayPosition(float &x, float &y, float &z) { x = m_stayX; y = m_stayY; z = m_stayZ; } void CharmInfo::SetIsAtStay(bool val) { m_isAtStay = val; } bool CharmInfo::IsAtStay() { return m_isAtStay; } void CharmInfo::SetIsFollowing(bool val) { m_isFollowing = val; } bool CharmInfo::IsFollowing() { return m_isFollowing; } void CharmInfo::SetIsReturning(bool val) { m_isReturning = val; } bool CharmInfo::IsReturning() { return m_isReturning; } // Living Seed void Unit::SetEclipsePower(int32 power) { eclipse = power; if (eclipse == 0) { if (HasAura(67483)) RemoveAurasDueToSpell(67483); if (HasAura(67484)) RemoveAurasDueToSpell(67484); } if (eclipse >= 100) { if (HasAura(48518)) RemoveAurasDueToSpell(48518); eclipse = 100; AddAura(48517, ToPlayer()); } if (eclipse <= -100) { if (HasAura(48517)) RemoveAurasDueToSpell(48517); eclipse = -100; AddAura(48518, ToPlayer()); } WorldPacket data(SMSG_POWER_UPDATE); data.append(GetPackGUID()); data << int32(1); data << int8(POWER_ECLIPSE); data << int32(eclipse); SendMessageToSet(&data, GetTypeId() == TYPEID_PLAYER ? true : false); } uint32 Unit::GetHealingDoneInPastSecs(uint32 secs) { uint32 heal = 0; if (secs > 120) secs = 120; for (uint32 i = 0; i < secs; i++) heal += m_heal_done [i]; if (heal < 0) return 0; return heal; } ; uint32 Unit::GetDamageDoneInPastSecs(uint32 secs) { uint32 damage = 0; if (secs > 120) secs = 120; for (uint32 i = 0; i < secs; i++) damage += m_damage_done [i]; if (damage < 0) return 0; return damage; } ; uint32 Unit::GetDamageTakenInPastSecs(uint32 secs) { uint32 tdamage = 0; if (secs > 120) secs = 120; for (uint32 i = 0; i < secs; i++) tdamage += m_damage_taken [i]; if (tdamage < 0) return 0; return tdamage; } ; void Unit::ResetDamageDoneInPastSecs(uint32 secs) { if (secs > 120) secs = 120; for (uint32 i = 0; i < secs; i++) m_damage_done [i] = 0; } ; void Unit::ResetHealingDoneInPastSecs(uint32 secs) { if (secs > 120) secs = 120; for (uint32 i = 0; i < secs; i++) m_heal_done [i] = 0; } ;
29.441568
236
0.67334
Zone-Emu
9e34d01349b16f9e2820ca49771f3456afea1baa
4,632
cpp
C++
shirabeengine/shirabeengine/modules/core/code/source/serialization/jsonobjectserializer.cpp
BoneCrasher/ShirabeEngine
39b3aa2c5173084d59b96b7f60c15207bff0ad04
[ "MIT" ]
5
2019-12-02T12:28:57.000Z
2021-04-07T21:21:13.000Z
shirabeengine/shirabeengine/modules/core/code/source/serialization/jsonobjectserializer.cpp
BoneCrasher/ShirabeEngine
39b3aa2c5173084d59b96b7f60c15207bff0ad04
[ "MIT" ]
null
null
null
shirabeengine/shirabeengine/modules/core/code/source/serialization/jsonobjectserializer.cpp
BoneCrasher/ShirabeEngine
39b3aa2c5173084d59b96b7f60c15207bff0ad04
[ "MIT" ]
1
2020-01-09T14:25:42.000Z
2020-01-09T14:25:42.000Z
#include <iostream> #include "SEPUtil/Documents/JSON.h" #include "SEPCore/ObjectModel/SR_SEPCore_Object.h" #include "SEPCore/ObjectModel/SR_SEPCore_Property.h" #include "SEPCore/ObjectModel/Serialization/SR_SEPCore_JSONObjectSerializer.h" namespace sr { namespace serialization { using namespace sr::documents; /**********************************************************************************************//** * \fn template <typename TCollection> static bool serializeCollection( Shared<IObjectSerializer> &serializer, std::string const&name, TCollection const&collection) * * \brief Serialize collection * * \tparam TCollection Type of the collection. * \param [in,out] serializer The serializer. * \param name The name. * \param collection The collection. * * \return True if it succeeds, false if it fails. **************************************************************************************************/ template <typename TCollection> static bool serializeCollection( Shared<IObjectSerializer> &serializer, std::string const&name, TCollection const&collection) { for(typename TCollection::value_type const&item : collection) { item.second->acceptSerializer(serializer); } return true; } /**********************************************************************************************//** * \fn bool XMLSerializer::serializeObject(Shared<Object> const&object) * * \brief Serialize object * * \param object The object. * * \return True if it succeeds, false if it fails. **************************************************************************************************/ bool JSONSerializer::serializeObject(Shared<Object> const&object) { Shared<IObjectSerializer> serializer = SharedFromThis<IObjectSerializer>(this); // // Serialize an object at this point, applying the subsequent format: // // Serialize all it's properties! Object::Properties const&properties = object->properties(); if(!serializeCollection<Object::Properties>(serializer, "properties", properties)) { // Log return false; } // Serialize all children Object::Children const&children = object->children(); if(!serializeCollection<Object::Children>(serializer, "children", children)) { // Log return false; } return true; } /**********************************************************************************************//** * \fn bool XMLSerializer::serializeProperty(Shared<Object> const&property) * * \brief Serialize property * * \param property The property. * * \return True if it succeeds, false if it fails. **************************************************************************************************/ bool JSONSerializer::serializeProperty(Shared<Object> const&property) { return true; } /**********************************************************************************************//** * \fn bool XMLSerializer::deserializeObject(Shared<Object> &object) * * \brief Deserialize object/ * * \param [in,out] object The object. * * \return True if it succeeds, false if it fails. **************************************************************************************************/ bool JSONSerializer::deserializeObject(Shared<Object> &object) { return true; } /**********************************************************************************************//** * \fn bool XMLSerializer::deserializeProperty(Shared<Object> &property) * * \brief Deserialize property * * \param [in,out] property The property. * * \return True if it succeeds, false if it fails. **************************************************************************************************/ bool JSONSerializer::deserializeProperty(Shared<Object> &property) { return true; } /**********************************************************************************************//** * \fn std::string XMLSerializer::serializeResultToString() * * \brief Serialize result to string * * \return A std::string. **************************************************************************************************/ std::string JSONSerializer::serializeResultToString() { return ""; } } }
37.658537
169
0.470207
BoneCrasher
9e371bc0d64da0306dd467deaeadf69b31eff9fa
8,200
cc
C++
extensions/gen/mojo/public/interfaces/bindings/tests/new_endpoint_types.test-mojom-shared.cc
blockspacer/chromium_base_conan
b4749433cf34f54d2edff52e2f0465fec8cb9bad
[ "Apache-2.0", "BSD-3-Clause" ]
6
2020-12-22T05:48:31.000Z
2022-02-08T19:49:49.000Z
extensions/gen/mojo/public/interfaces/bindings/tests/new_endpoint_types.test-mojom-shared.cc
blockspacer/chromium_base_conan
b4749433cf34f54d2edff52e2f0465fec8cb9bad
[ "Apache-2.0", "BSD-3-Clause" ]
4
2020-05-22T18:36:43.000Z
2021-05-19T10:20:23.000Z
extensions/gen/mojo/public/interfaces/bindings/tests/new_endpoint_types.test-mojom-shared.cc
blockspacer/chromium_base_conan
b4749433cf34f54d2edff52e2f0465fec8cb9bad
[ "Apache-2.0", "BSD-3-Clause" ]
2
2019-12-06T11:48:16.000Z
2021-09-16T04:44:47.000Z
// mojo/public/interfaces/bindings/tests/new_endpoint_types.test-mojom-shared.cc is auto generated by mojom_bindings_generator.py, do not edit // 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 "mojo/public/interfaces/bindings/tests/new_endpoint_types.test-mojom-shared.h" #include <utility> #include "base/stl_util.h" // for base::size() #include "base/strings/stringprintf.h" #include "mojo/public/cpp/bindings/lib/validate_params.h" #include "mojo/public/cpp/bindings/lib/validation_context.h" #include "mojo/public/cpp/bindings/lib/validation_errors.h" #include "mojo/public/cpp/bindings/lib/validation_util.h" #include "third_party/perfetto/include/perfetto/tracing/traced_value.h" #include "mojo/public/interfaces/bindings/tests/new_endpoint_types.test-mojom-params-data.h" namespace mojo { namespace test { namespace new_endpoint_types { namespace mojom { namespace internal { // static bool WidgetObserver_OnClick_Params_Data::Validate( const void* data, mojo::internal::ValidationContext* validation_context) { if (!data) return true; if (!ValidateUnversionedStructHeaderAndSizeAndClaimMemory( data, 8, validation_context)) { return false; } // NOTE: The memory backing |object| may be smaller than |sizeof(*object)| if // the message comes from an older version. const WidgetObserver_OnClick_Params_Data* object = static_cast<const WidgetObserver_OnClick_Params_Data*>(data); ALLOW_UNUSED_LOCAL(object); return true; } WidgetObserver_OnClick_Params_Data::WidgetObserver_OnClick_Params_Data() : header_({sizeof(*this), 0}) {} // static bool Widget_Click_Params_Data::Validate( const void* data, mojo::internal::ValidationContext* validation_context) { if (!data) return true; if (!ValidateUnversionedStructHeaderAndSizeAndClaimMemory( data, 8, validation_context)) { return false; } // NOTE: The memory backing |object| may be smaller than |sizeof(*object)| if // the message comes from an older version. const Widget_Click_Params_Data* object = static_cast<const Widget_Click_Params_Data*>(data); ALLOW_UNUSED_LOCAL(object); return true; } Widget_Click_Params_Data::Widget_Click_Params_Data() : header_({sizeof(*this), 0}) {} // static bool Widget_AddObserver_Params_Data::Validate( const void* data, mojo::internal::ValidationContext* validation_context) { if (!data) return true; if (!ValidateUnversionedStructHeaderAndSizeAndClaimMemory( data, 16, validation_context)) { return false; } // NOTE: The memory backing |object| may be smaller than |sizeof(*object)| if // the message comes from an older version. const Widget_AddObserver_Params_Data* object = static_cast<const Widget_AddObserver_Params_Data*>(data); ALLOW_UNUSED_LOCAL(object); if (!mojo::internal::ValidateHandleOrInterfaceNonNullable( object->observer, 1, validation_context)) { return false; } if (!mojo::internal::ValidateHandleOrInterface(object->observer, validation_context)) { return false; } return true; } Widget_AddObserver_Params_Data::Widget_AddObserver_Params_Data() : header_({sizeof(*this), 0}) {} // static bool WidgetClient_OnInitialized_Params_Data::Validate( const void* data, mojo::internal::ValidationContext* validation_context) { if (!data) return true; if (!ValidateUnversionedStructHeaderAndSizeAndClaimMemory( data, 8, validation_context)) { return false; } // NOTE: The memory backing |object| may be smaller than |sizeof(*object)| if // the message comes from an older version. const WidgetClient_OnInitialized_Params_Data* object = static_cast<const WidgetClient_OnInitialized_Params_Data*>(data); ALLOW_UNUSED_LOCAL(object); return true; } WidgetClient_OnInitialized_Params_Data::WidgetClient_OnInitialized_Params_Data() : header_({sizeof(*this), 0}) {} // static bool WidgetFactory_CreateWidget_Params_Data::Validate( const void* data, mojo::internal::ValidationContext* validation_context) { if (!data) return true; if (!ValidateUnversionedStructHeaderAndSizeAndClaimMemory( data, 24, validation_context)) { return false; } // NOTE: The memory backing |object| may be smaller than |sizeof(*object)| if // the message comes from an older version. const WidgetFactory_CreateWidget_Params_Data* object = static_cast<const WidgetFactory_CreateWidget_Params_Data*>(data); ALLOW_UNUSED_LOCAL(object); if (!mojo::internal::ValidateHandleOrInterfaceNonNullable( object->receiver, 1, validation_context)) { return false; } if (!mojo::internal::ValidateHandleOrInterface(object->receiver, validation_context)) { return false; } if (!mojo::internal::ValidateHandleOrInterfaceNonNullable( object->client, 2, validation_context)) { return false; } if (!mojo::internal::ValidateHandleOrInterface(object->client, validation_context)) { return false; } return true; } WidgetFactory_CreateWidget_Params_Data::WidgetFactory_CreateWidget_Params_Data() : header_({sizeof(*this), 0}) {} // static bool Pinger_Ping_Params_Data::Validate( const void* data, mojo::internal::ValidationContext* validation_context) { if (!data) return true; if (!ValidateUnversionedStructHeaderAndSizeAndClaimMemory( data, 8, validation_context)) { return false; } // NOTE: The memory backing |object| may be smaller than |sizeof(*object)| if // the message comes from an older version. const Pinger_Ping_Params_Data* object = static_cast<const Pinger_Ping_Params_Data*>(data); ALLOW_UNUSED_LOCAL(object); return true; } Pinger_Ping_Params_Data::Pinger_Ping_Params_Data() : header_({sizeof(*this), 0}) {} // static bool Pinger_Ping_ResponseParams_Data::Validate( const void* data, mojo::internal::ValidationContext* validation_context) { if (!data) return true; if (!ValidateUnversionedStructHeaderAndSizeAndClaimMemory( data, 8, validation_context)) { return false; } // NOTE: The memory backing |object| may be smaller than |sizeof(*object)| if // the message comes from an older version. const Pinger_Ping_ResponseParams_Data* object = static_cast<const Pinger_Ping_ResponseParams_Data*>(data); ALLOW_UNUSED_LOCAL(object); return true; } Pinger_Ping_ResponseParams_Data::Pinger_Ping_ResponseParams_Data() : header_({sizeof(*this), 0}) {} // static bool AssociatedPingerHost_AddEndpoints_Params_Data::Validate( const void* data, mojo::internal::ValidationContext* validation_context) { if (!data) return true; if (!ValidateUnversionedStructHeaderAndSizeAndClaimMemory( data, 24, validation_context)) { return false; } // NOTE: The memory backing |object| may be smaller than |sizeof(*object)| if // the message comes from an older version. const AssociatedPingerHost_AddEndpoints_Params_Data* object = static_cast<const AssociatedPingerHost_AddEndpoints_Params_Data*>(data); ALLOW_UNUSED_LOCAL(object); if (!mojo::internal::ValidateHandleOrInterfaceNonNullable( object->receiver, 1, validation_context)) { return false; } if (!mojo::internal::ValidateHandleOrInterface(object->receiver, validation_context)) { return false; } if (!mojo::internal::ValidateHandleOrInterfaceNonNullable( object->remote, 2, validation_context)) { return false; } if (!mojo::internal::ValidateHandleOrInterface(object->remote, validation_context)) { return false; } return true; } AssociatedPingerHost_AddEndpoints_Params_Data::AssociatedPingerHost_AddEndpoints_Params_Data() : header_({sizeof(*this), 0}) {} } // namespace internal } // namespace mojom } // namespace new_endpoint_types } // namespace test } // namespace mojo
31.417625
142
0.721585
blockspacer
9e3dee3c83418b383fa2f716ac4e8937f64ca1ca
720
cpp
C++
Rotor.cpp
FreddieLindsey/ic_year_2_cpp_enigma
d7efebed5a135e46c09e18873f2ba2630c2e1701
[ "MIT" ]
null
null
null
Rotor.cpp
FreddieLindsey/ic_year_2_cpp_enigma
d7efebed5a135e46c09e18873f2ba2630c2e1701
[ "MIT" ]
null
null
null
Rotor.cpp
FreddieLindsey/ic_year_2_cpp_enigma
d7efebed5a135e46c09e18873f2ba2630c2e1701
[ "MIT" ]
null
null
null
#include "Rotor.hpp" Rotor::Rotor(string file_content) : map_encode(ALPHABET_SIZE), map_decode(ALPHABET_SIZE), offset(0) { // Initialise istringstream content(file_content); string num; // Set map to input file given for (int i = 0; i < ALPHABET_SIZE; i++) { getline(content, num, INPUT_DELIM); int diff = stoi(num) - i; map_encode[i] = diff; map_decode[i + diff] = -diff; } } void Rotor::encode_decode(int& c, bool encode_decode) { vector<int>& map = encode_decode ? map_encode : map_decode; c = (c + map[(c + offset) % ALPHABET_SIZE] + ALPHABET_SIZE) % ALPHABET_SIZE; } bool Rotor::rotate(void) { offset = (offset + 1 + ALPHABET_SIZE) % ALPHABET_SIZE; return offset == 0; }
26.666667
78
0.665278
FreddieLindsey
9e408d4df0fd4111a458ded0a89c558489b9122e
334
cpp
C++
Orbitersdk/stackEditor/OrbiterDockingPort.cpp
meson800/orbiter-stackEditor
01955f87ad6116ed07279e2bfab9636514a418f1
[ "MIT" ]
null
null
null
Orbitersdk/stackEditor/OrbiterDockingPort.cpp
meson800/orbiter-stackEditor
01955f87ad6116ed07279e2bfab9636514a418f1
[ "MIT" ]
2
2015-05-28T14:46:19.000Z
2015-07-20T23:15:04.000Z
Orbitersdk/stackEditor/OrbiterDockingPort.cpp
meson800/orbiter-stackEditor
01955f87ad6116ed07279e2bfab9636514a418f1
[ "MIT" ]
null
null
null
//Copyright (c) 2015 Christopher Johnstone(meson800) and Benedict Haefeli(jedidia) //The MIT License - See ../../LICENSE for more info #include "OrbiterDockingPort.h" DockingPortStatus OrbiterDockingPort::returnStatus() { DockingPortStatus output; output.docked = docked; output.dockedTo = dockedTo; return output; }
27.833333
82
0.745509
meson800
9e42884e0698160bbc26ccae14a3370f02f46f7c
10,188
cpp
C++
src/Boring32/src/WinHttp/AsyncWebSocket.StatusCallback.cpp
yottaawesome/boring32
ecf843c200b133a4fad711dcf52419c0c88af49c
[ "MIT" ]
3
2021-11-25T13:44:57.000Z
2022-02-22T05:50:34.000Z
src/Boring32/src/WinHttp/AsyncWebSocket.StatusCallback.cpp
yottaawesome/boring32
ecf843c200b133a4fad711dcf52419c0c88af49c
[ "MIT" ]
3
2021-10-13T10:58:30.000Z
2021-12-21T05:46:41.000Z
src/Boring32/src/WinHttp/AsyncWebSocket.StatusCallback.cpp
yottaawesome/boring32
ecf843c200b133a4fad711dcf52419c0c88af49c
[ "MIT" ]
null
null
null
#include "pch.hpp" #include <future> #include <algorithm> #include "include/Strings/Strings.hpp" #include "include/Error/Error.hpp" #include "include/WinHttp/WebSockets/AsyncWebSocket.hpp" namespace Boring32::WinHttp::WebSockets { void AsyncWebSocket::StatusCallback( HINTERNET hInternet, DWORD_PTR dwContext, DWORD dwInternetStatus, LPVOID lpvStatusInformation, DWORD dwStatusInformationLength ) { // https://docs.microsoft.com/en-us/windows/win32/api/winhttp/nf-winhttp-winhttpsetstatuscallback switch (dwInternetStatus) { case WINHTTP_CALLBACK_STATUS_RESOLVING_NAME: { std::wcout << L"WINHTTP_CALLBACK_STATUS_RESOLVING_NAME" << std::endl; break; } case WINHTTP_CALLBACK_STATUS_NAME_RESOLVED: { std::wcout << L"WINHTTP_CALLBACK_STATUS_NAME_RESOLVED" << std::endl; break; } case WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER: { std::wcout << L"WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER" << std::endl; break; } case WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER: { std::wcout << L"WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER" << std::endl; break; } case WINHTTP_CALLBACK_STATUS_SENDING_REQUEST: { std::wcout << L"WINHTTP_CALLBACK_STATUS_SENDING_REQUEST" << std::endl; break; } case WINHTTP_CALLBACK_STATUS_REQUEST_SENT: { std::wcout << L"WINHTTP_CALLBACK_STATUS_REQUEST_SENT" << std::endl; AsyncWebSocket* socket = (AsyncWebSocket*)dwContext; if(socket) std::wcout << L"WINHTTP_CALLBACK_STATUS_REQUEST_SENT: socket available" << std::endl; const bool success = WinHttpReceiveResponse(hInternet, 0); if (success == false) { Error::Win32Error ex( __FUNCSIG__ ": WinHttpReceiveResponse() failed on initial connection", GetLastError() ); std::wcout << ex.what() << std::endl; } break; } case WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE: { std::wcout << L"WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE" << std::endl; break; } case WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED: { std::wcout << L"WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED" << std::endl; break; } case WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION: { std::wcout << L"WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION" << std::endl; break; } case WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED: { std::wcout << L"WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED" << std::endl; break; } case WINHTTP_CALLBACK_STATUS_HANDLE_CREATED: { std::wcout << L"WINHTTP_CALLBACK_STATUS_HANDLE_CREATED" << std::endl; break; } case WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING: { std::wcout << L"WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING" << std::endl; break; } case WINHTTP_CALLBACK_STATUS_DETECTING_PROXY: { std::wcout << L"WINHTTP_CALLBACK_STATUS_DETECTING_PROXY" << std::endl; break; } case WINHTTP_CALLBACK_STATUS_REDIRECT: { std::wcout << L"WINHTTP_CALLBACK_STATUS_REDIRECT" << std::endl; break; } case WINHTTP_CALLBACK_STATUS_INTERMEDIATE_RESPONSE: { std::wcout << L"WINHTTP_CALLBACK_STATUS_INTERMEDIATE_RESPONSE" << std::endl; break; } case WINHTTP_CALLBACK_STATUS_SECURE_FAILURE: { std::wcout << L"WINHTTP_CALLBACK_STATUS_SECURE_FAILURE" << std::endl; break; } case WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE: { std::wcout << L"WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE" << std::endl; break; } case WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE: { std::wcout << L"WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE" << std::endl; try { DWORD statusCode = 0; DWORD statusCodeSize = sizeof(statusCode); // https://docs.microsoft.com/en-us/windows/win32/api/winhttp/nf-winhttp-winhttpqueryheaders bool success = WinHttpQueryHeaders( hInternet, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &statusCode, &statusCodeSize, WINHTTP_NO_HEADER_INDEX ); if (success == false) throw Error::Win32Error(__FUNCSIG__ ": WinHttpQueryHeaders() failed", GetLastError()); switch (statusCode) { case 101: // Switching protocol break; case 301: // Redirect responses case 302: case 303: case 307: case 308: std::wcout << "Redirected" << std::endl; return; default: // Unexpected responses throw std::runtime_error( __FUNCSIG__ ": Received unexpected HTTP response code while upgrading to websocket: " + std::to_string(statusCode) ); } AsyncWebSocket* socket = (AsyncWebSocket*)dwContext; socket->m_winHttpWebSocket = WinHttpWebSocketCompleteUpgrade( socket->m_requestHandle.Get(), 0 ); if (socket->m_winHttpWebSocket == nullptr) throw Error::Win32Error( __FUNCSIG__ ": WinHttpWebSocketCompleteUpgrade() failed", GetLastError() ); bool succeeded = WinHttpSetOption( socket->m_winHttpWebSocket.Get(), WINHTTP_OPTION_CONTEXT_VALUE, (void*)&dwContext, sizeof(DWORD_PTR) ); if (succeeded == false) throw Error::Win32Error( __FUNCSIG__ ": WinHttpSetOption() failed when setting context value", GetLastError() ); socket->m_status = WebSocketStatus::Connected; socket->m_requestHandle = nullptr; } catch (const std::exception& ex) { std::wcout << ex.what() << std::endl; } break; } case WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE: { std::wcout << L"WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE" << std::endl; break; } case WINHTTP_CALLBACK_STATUS_READ_COMPLETE: { std::wcout << L"WINHTTP_CALLBACK_STATUS_READ_COMPLETE" << std::endl; try { AsyncWebSocket* socket = (AsyncWebSocket*)dwContext; WINHTTP_WEB_SOCKET_STATUS* status = (WINHTTP_WEB_SOCKET_STATUS*)lpvStatusInformation; WebSocketReadResult& read = socket->m_currentResult; if (read.Status != WebSocketReadResultStatus::Initiated && read.Status != WebSocketReadResultStatus::PartialRead) { std::wcerr << L"read in an unexpected status" << std::endl; return; } read.TotalBytesRead += status->dwBytesTransferred; switch (status->eBufferType) { case WINHTTP_WEB_SOCKET_BINARY_FRAGMENT_BUFFER_TYPE: case WINHTTP_WEB_SOCKET_UTF8_FRAGMENT_BUFFER_TYPE: read.Status = WebSocketReadResultStatus::PartialRead; socket->Receive(read); break; case WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE: case WINHTTP_WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE: read.Status = WebSocketReadResultStatus::Finished; read.Data.resize(read.TotalBytesRead); read.Complete.Signal(); break; case WINHTTP_WEB_SOCKET_CLOSE_BUFFER_TYPE: read.Status = WebSocketReadResultStatus::Finished; socket->m_status = WebSocketStatus::Closed; read.Complete.Signal(); break; default: throw std::runtime_error("Unknown eBufferType"); } } catch (const std::exception& ex) { std::wcerr << ex.what() << std::endl; } break; } case WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE: { std::wcout << L"WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE" << std::endl; break; } case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR: { std::wcout << L"WINHTTP_CALLBACK_STATUS_REQUEST_ERROR" << std::endl; WINHTTP_ASYNC_RESULT* requestError = (WINHTTP_ASYNC_RESULT*)lpvStatusInformation; AsyncWebSocket* socket = (AsyncWebSocket*)dwContext; socket->m_status = WebSocketStatus::Error; Error::Win32Error err("", (DWORD)requestError->dwError); switch (requestError->dwResult) { case API_RECEIVE_RESPONSE: std::wcerr << "The error occurred during a call to WinHttpReceiveResponse: " << err.what() << std::endl; break; case API_QUERY_DATA_AVAILABLE: std::wcerr << "The error occurred during a call to WinHttpQueryDataAvailable: " << err.what() << std::endl; break; case API_READ_DATA: std::wcerr << "The error occurred during a call to WinHttpReadData: " << err.what() << std::endl; break; case API_WRITE_DATA: std::wcerr << "The error occurred during a call to WinHttpWriteData: " << err.what() << std::endl; break; case API_SEND_REQUEST: std::wcerr << "The error occurred during a call to WinHttpSendRequest: " << err.what() << std::endl; break; default: std::wcerr << "Unknown error: " << err.what() << std::endl; break; } break; } case WINHTTP_CALLBACK_STATUS_GETPROXYFORURL_COMPLETE: { std::wcout << L"WINHTTP_CALLBACK_STATUS_GETPROXYFORURL_COMPLETE" << std::endl; break; } case WINHTTP_CALLBACK_STATUS_CLOSE_COMPLETE: { std::wcout << L"WINHTTP_CALLBACK_STATUS_CLOSE_COMPLETE" << std::endl; AsyncWebSocket* socket = (AsyncWebSocket*)dwContext; socket->Release(); socket->m_status = WebSocketStatus::Closed; break; } case WINHTTP_CALLBACK_STATUS_SHUTDOWN_COMPLETE: { std::wcout << L"WINHTTP_CALLBACK_STATUS_SHUTDOWN_COMPLETE" << std::endl; break; } case WINHTTP_CALLBACK_STATUS_SETTINGS_WRITE_COMPLETE: { std::wcout << L"WINHTTP_CALLBACK_STATUS_SETTINGS_WRITE_COMPLETE" << std::endl; break; } case WINHTTP_CALLBACK_STATUS_SETTINGS_READ_COMPLETE: { std::wcout << L"WINHTTP_CALLBACK_STATUS_SETTINGS_READ_COMPLETE" << std::endl; break; } default: { std::wcout << L"Default" << std::endl; } } } }
26.881266
114
0.647723
yottaawesome
9e47ccaf7a7e2f41444b1879b89d0d60f96a3852
2,037
cpp
C++
Pinball_Project/ModuleWindow.cpp
rastabrandy02/Pinball_Project_Physics_2
60de6903882e29f7fb919ebc4eb0f92130a15afb
[ "MIT" ]
null
null
null
Pinball_Project/ModuleWindow.cpp
rastabrandy02/Pinball_Project_Physics_2
60de6903882e29f7fb919ebc4eb0f92130a15afb
[ "MIT" ]
null
null
null
Pinball_Project/ModuleWindow.cpp
rastabrandy02/Pinball_Project_Physics_2
60de6903882e29f7fb919ebc4eb0f92130a15afb
[ "MIT" ]
1
2022-02-09T19:46:39.000Z
2022-02-09T19:46:39.000Z
#include "Globals.h" #include "Application.h" #include "ModuleWindow.h" ModuleWindow::ModuleWindow(Application* app, bool start_enabled) : Module(app, start_enabled) { window = NULL; screen_surface = NULL; } // Destructor ModuleWindow::~ModuleWindow() { } // Called before render is available bool ModuleWindow::Init() { LOG("Init SDL window & surface"); bool ret = true; if(SDL_Init(SDL_INIT_VIDEO) < 0) { LOG("SDL_VIDEO could not initialize! SDL_Error: %s\n", SDL_GetError()); ret = false; } else { //Create window float width = SCREEN_WIDTH * SCREEN_SIZE; float height = SCREEN_HEIGHT * SCREEN_SIZE; Uint32 flags = SDL_WINDOW_SHOWN; if(WIN_FULLSCREEN == true) { flags |= SDL_WINDOW_FULLSCREEN; } if(WIN_RESIZABLE == true) { flags |= SDL_WINDOW_RESIZABLE; } if(WIN_BORDERLESS == true) { flags |= SDL_WINDOW_BORDERLESS; } if(WIN_FULLSCREEN_DESKTOP == true) { flags |= SDL_WINDOW_FULLSCREEN_DESKTOP; } window = SDL_CreateWindow(TITLE, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, flags); if(window == NULL) { LOG("Window could not be created! SDL_Error: %s\n", SDL_GetError()); ret = false; } else { //Get window surface screen_surface = SDL_GetWindowSurface(window); } const char* image_path = "pinball/UI_elements/icon.bmp"; SDL_Surface* image = IMG_Load(image_path); /* Let the user know if the file failed to load */ if (!image) { printf("Failed to load image at %s: %s\n", image_path, SDL_GetError()); } //SDL_Surface* iconSurface = SDL_LoadBMP("pinball/UI_elements/icon.bmp"); SDL_SetWindowIcon(window, image); SDL_FreeSurface(image); } return ret; } // Called before quitting bool ModuleWindow::CleanUp() { LOG("Destroying SDL window and quitting all SDL systems"); //Destroy window if(window != NULL) { SDL_DestroyWindow(window); } //Quit SDL subsystems SDL_Quit(); return true; } void ModuleWindow::SetTitle(const char* title) { SDL_SetWindowTitle(window, title); }
19.037383
107
0.693667
rastabrandy02
eafc3169eba604acdb2d92cceed49073fc30be40
6,958
cpp
C++
packages/+GT/GenericTargetCode/source/GenericTarget/SignalObjectDoubles.cpp
RobertDamerius/GenericTarget
6b26793c2d580797ac8104ca5368987cbb570ef8
[ "MIT" ]
1
2021-02-02T09:01:24.000Z
2021-02-02T09:01:24.000Z
packages/+GT/GenericTargetCode/source/GenericTarget/SignalObjectDoubles.cpp
RobertDamerius/GenericTarget
6b26793c2d580797ac8104ca5368987cbb570ef8
[ "MIT" ]
null
null
null
packages/+GT/GenericTargetCode/source/GenericTarget/SignalObjectDoubles.cpp
RobertDamerius/GenericTarget
6b26793c2d580797ac8104ca5368987cbb570ef8
[ "MIT" ]
2
2021-02-02T09:01:45.000Z
2021-10-02T13:08:16.000Z
#include <SignalObjectDoubles.hpp> #include <Console.hpp> #include <SimulinkInterface.hpp> #include <SignalManager.hpp> #include <Common.hpp> SignalObjectDoubles::SignalObjectDoubles(){ this->numSamplesPerFile = 0; this->numSignals = 0; this->labels = ""; this->started = false; this->filename = ""; this->notified = false; this->terminate = false; this->threadLog = nullptr; this->currentFileNumber = 0; this->numSamplesWritten = 0; this->currentFileStarted = false; } SignalObjectDoubles::~SignalObjectDoubles(){ Stop(); } bool SignalObjectDoubles::Start(std::string filename){ // Make sure that the signal object is stopped Stop(); // Set filename and start log thread this->filename = filename; threadLog = new std::thread(SignalObjectDoubles::ThreadLog, this); struct sched_param param; param.sched_priority = SimulinkInterface::priorityLog; if(0 != pthread_setschedparam(threadLog->native_handle(), SCHED_FIFO, &param)){ LogE("[SIGNAL MANAGER] Could not set thread priority %d for logger thread\n", SimulinkInterface::priorityLog); } // Started, return success return (this->started = true); } void SignalObjectDoubles::Stop(void){ // Stop thread terminate = true; if(threadLog){ this->Notify(); threadLog->join(); delete threadLog; threadLog = nullptr; } terminate = false; // If the signal object was started, check if there're remaining values in the buffer and write/append them to data files if(this->started){ this->mtxBuffer.lock(); WriteBufferToDataFiles(std::ref(this->buffer)); if(this->buffer.size()){ std::string currentFileName = this->filename + std::string("_") + std::to_string(this->currentFileNumber); LogW("[SIGNAL MANAGER] Some signal data is in the buffer (%ull samples) but could not be written to the data file \"%s\"!\n", this->buffer.size() / (size_t)(1 + this->numSignals), currentFileName.c_str()); this->buffer.clear(); } this->mtxBuffer.unlock(); } this->started = false; this->currentFileNumber = 0; this->numSamplesWritten = 0; this->currentFileStarted = false; } void SignalObjectDoubles::Write(double simulationTime, double* values, uint32_t numValues){ // Just append data to buffer if(this->numSignals == numValues){ this->mtxBuffer.lock(); this->buffer.push_back(simulationTime); this->buffer.insert(this->buffer.end(), &values[0], &values[0] + this->numSignals); this->mtxBuffer.unlock(); } // Notify file logging thread that new data is available this->Notify(); } bool SignalObjectDoubles::WriteHeader(std::string name){ // Open file FILE *file = fopen(name.c_str(), "wb"); if(!file) return false; // Header: "GTDBL" (5 bytes) const uint8_t header[] = {'G','T', 'D', 'B', 'L'}; fwrite(&header[0], 1, 5, file); // Zero-based offset to SampleData (4 bytes) uint8_t bytes[4]; uint32_t offset = 15 + uint32_t(this->labels.length()); bytes[0] = uint8_t((offset >> 24) & 0x000000FF); bytes[1] = uint8_t((offset >> 16) & 0x000000FF); bytes[2] = uint8_t((offset >> 8) & 0x000000FF); bytes[3] = uint8_t(offset & 0x000000FF); fwrite(&bytes[0], 1, 4, file); // numSignals (4 bytes) bytes[0] = uint8_t((this->numSignals >> 24) & 0x000000FF); bytes[1] = uint8_t((this->numSignals >> 16) & 0x000000FF); bytes[2] = uint8_t((this->numSignals >> 8) & 0x000000FF); bytes[3] = uint8_t(this->numSignals & 0x000000FF); fwrite(&bytes[0], 1, 4, file); // Labels + 0x00 (L + 1 bytes) fwrite(&this->labels[0], 1, this->labels.length(), file); bytes[0] = 0; fwrite(&bytes[0], 1, 1, file); // endianess (1 byte): litte endian (0x01) or big endian (0x80) union { uint16_t value; uint8_t bytes[2]; } endian = {0x0100}; uint8_t byte = endian.bytes[0] ? 0x80 : 0x01; fwrite(&byte, 1, 1, file); // Close file and return success fclose(file); return true; } void SignalObjectDoubles::ThreadLog(SignalObjectDoubles* obj){ std::vector<double> localBuffer; while(!obj->terminate){ // Wait for notification { std::unique_lock<std::mutex> lock(obj->mtxNotify); obj->cvNotify.wait(lock, [obj](){ return (obj->notified || obj->terminate); }); obj->notified = false; } if(obj->terminate){ break; } // Copy to local buffer obj->mtxBuffer.lock(); if(obj->buffer.size()){ localBuffer.insert(localBuffer.end(), obj->buffer.begin(), obj->buffer.end()); obj->buffer.clear(); } obj->mtxBuffer.unlock(); // Write buffer data to files obj->WriteBufferToDataFiles(std::ref(localBuffer)); } // If there's data in the local buffer copy it to the beginning of the main buffer if(localBuffer.size()){ obj->mtxBuffer.lock(); obj->buffer.insert(obj->buffer.begin(), localBuffer.begin(), localBuffer.end()); obj->mtxBuffer.unlock(); } } void SignalObjectDoubles::WriteBufferToDataFiles(std::vector<double>& values){ while(values.size()){ // The current file name of the active data file std::string currentFileName = this->filename + std::string("_") + std::to_string(this->currentFileNumber); // Check if new file should be started if(!this->currentFileStarted){ if(!WriteHeader(currentFileName)){ return; } this->currentFileStarted = true; this->numSamplesWritten = 0; Log("[SIGNAL MANAGER] Created data log file \"%s\".\n", currentFileName.c_str()); } // We have a started file, write samples size_t numSamplesToWrite = values.size() / (size_t)(1 + this->numSignals); if(this->numSamplesPerFile){ numSamplesToWrite = std::min(numSamplesToWrite, this->numSamplesPerFile); } if(!numSamplesToWrite){ return; } size_t numValuesToWrite = numSamplesToWrite * (size_t)(1 + this->numSignals); std::fstream fs(currentFileName, std::ios::out | std::ios::app | std::ios::binary); if(!fs.is_open()){ return; } fs.write(reinterpret_cast<const char*>(&values[0]), numValuesToWrite * 8); fs.close(); this->numSamplesWritten += numSamplesToWrite; values.erase(values.begin(), values.begin() + numValuesToWrite); // File has been finished successfully, set markers to indicate that a new file should be started if(this->numSamplesPerFile && (this->numSamplesWritten >= this->numSamplesPerFile)){ this->currentFileStarted = false; this->currentFileNumber++; } } }
34.445545
217
0.617275
RobertDamerius
eafd77087c1c81b106f4c7fcc8b6ced67bfdbc1d
16,496
cpp
C++
src/zimg/depth/dither_avx2.cpp
dubhater/zimg
59ca0556789656a439f32b4cdfc8e26db32b8252
[ "WTFPL" ]
null
null
null
src/zimg/depth/dither_avx2.cpp
dubhater/zimg
59ca0556789656a439f32b4cdfc8e26db32b8252
[ "WTFPL" ]
null
null
null
src/zimg/depth/dither_avx2.cpp
dubhater/zimg
59ca0556789656a439f32b4cdfc8e26db32b8252
[ "WTFPL" ]
null
null
null
#ifdef ZIMG_X86 #include <cstdint> #include <immintrin.h> #ifdef __clang__ #include <x86intrin.h> #endif #include "common/align.h" #include "common/ccdep.h" #define HAVE_CPU_SSE2 #define HAVE_CPU_AVX2 #include "common/x86util.h" #undef HAVE_CPU_SSE2 #undef HAVE_CPU_AVX2 namespace zimg { namespace depth { namespace { struct LoadF16 { typedef uint16_t type; static __m256 load(const uint16_t *ptr) { return _mm256_cvtph_ps(_mm_load_si128((const __m128i *)ptr)); } }; struct LoadF32 { typedef float type; static __m256 load(const float *ptr) { return _mm256_load_ps(ptr); } }; inline FORCE_INLINE void mm_store_left_epi8(uint8_t *dst, __m128i x, unsigned count) { mm_store_left_si128((__m128i *)dst, x, count); } inline FORCE_INLINE void mm_store_right_epi8(uint8_t *dst, __m128i x, unsigned count) { mm_store_right_si128((__m128i *)dst, x, count); } inline FORCE_INLINE void mm256_store_left_epi16(uint16_t *dst, __m256i x, unsigned count) { mm256_store_left_si256((__m256i *)dst, x, count * 2); } inline FORCE_INLINE void mm256_store_right_epi16(uint16_t *dst, __m256i x, unsigned count) { mm256_store_right_si256((__m256i *)dst, x, count * 2); } inline FORCE_INLINE __m256i mm256_zeroextend_epi8(__m128i y) { __m256i x; x = _mm256_permute4x64_epi64(_mm256_castsi128_si256(y), _MM_SHUFFLE(1, 1, 0, 0)); x = _mm256_unpacklo_epi8(x, _mm256_setzero_si256()); return x; } inline FORCE_INLINE __m128i mm256_packus_epi16_si256_si128(__m256i x) { x = _mm256_packus_epi16(x, x); x = _mm256_permute4x64_epi64(x, _MM_SHUFFLE(3, 1, 2, 0)); return _mm256_castsi256_si128(x); } inline FORCE_INLINE void mm256_cvtepu16_ps(__m256i x, __m256 &lo, __m256 &hi) { __m256i lo_dw, hi_dw; x = _mm256_permute4x64_epi64(x, _MM_SHUFFLE(3, 1, 2, 0)); lo_dw = _mm256_unpacklo_epi16(x, _mm256_setzero_si256()); hi_dw = _mm256_unpackhi_epi16(x, _mm256_setzero_si256()); lo = _mm256_cvtepi32_ps(lo_dw); hi = _mm256_cvtepi32_ps(hi_dw); } inline FORCE_INLINE __m256i mm256_cvtps_epu16(__m256 lo, __m256 hi) { __m256i lo_dw = _mm256_cvtps_epi32(lo); __m256i hi_dw = _mm256_cvtps_epi32(hi); __m256i x; x = _mm256_packus_epi32(lo_dw, hi_dw); // 0 1 2 3 8 9 a b | 4 5 6 7 c d e f x = _mm256_permute4x64_epi64(x, _MM_SHUFFLE(3, 1, 2, 0)); return x; } inline FORCE_INLINE __m128i ordered_dither_b2b_avx2_xiter(unsigned j, const float *dither, unsigned dither_offset, unsigned dither_mask, const uint8_t *src_p, __m256 scale, __m256 offset, __m128i out_max) { __m128i y = _mm_load_si128((const __m128i *)(src_p + j)); __m256i x = mm256_zeroextend_epi8(y); __m256 lo, hi; __m256 dith; mm256_cvtepu16_ps(x, lo, hi); dith = _mm256_load_ps(dither + ((dither_offset + j + 0) & dither_mask)); lo = _mm256_fmadd_ps(scale, lo, offset); lo = _mm256_add_ps(lo, dith); dith = _mm256_load_ps(dither + ((dither_offset + j + 8) & dither_mask)); hi = _mm256_fmadd_ps(scale, hi, offset); hi = _mm256_add_ps(hi, dith); x = mm256_cvtps_epu16(lo, hi); y = mm256_packus_epi16_si256_si128(x); y = _mm_min_epu8(y, out_max); return y; } inline FORCE_INLINE __m256i ordered_dither_b2w_avx2_xiter(unsigned j, const float *dither, unsigned dither_offset, unsigned dither_mask, const uint8_t *src_p, __m256 scale, __m256 offset, __m256i out_max) { __m128i y = _mm_load_si128((const __m128i *)(src_p + j)); __m256i x = mm256_zeroextend_epi8(y); __m256 lo, hi; __m256 dith; mm256_cvtepu16_ps(x, lo, hi); dith = _mm256_load_ps(dither + ((dither_offset + j + 0) & dither_mask)); lo = _mm256_fmadd_ps(scale, lo, offset); lo = _mm256_add_ps(lo, dith); dith = _mm256_load_ps(dither + ((dither_offset + j + 8) & dither_mask)); hi = _mm256_fmadd_ps(scale, hi, offset); hi = _mm256_add_ps(hi, dith); x = mm256_cvtps_epu16(lo, hi); x = _mm256_min_epu16(x, out_max); return x; } inline FORCE_INLINE __m128i ordered_dither_w2b_avx2_xiter(unsigned j, const float *dither, unsigned dither_offset, unsigned dither_mask, const uint16_t *src_p, __m256 scale, __m256 offset, __m128i out_max) { __m256i x = _mm256_load_si256((const __m256i *)(src_p + j)); __m128i y; __m256 lo, hi; __m256 dith; mm256_cvtepu16_ps(x, lo, hi); dith = _mm256_load_ps(dither + ((dither_offset + j + 0) & dither_mask)); lo = _mm256_fmadd_ps(scale, lo, offset); lo = _mm256_add_ps(lo, dith); dith = _mm256_load_ps(dither + ((dither_offset + j + 8) & dither_mask)); hi = _mm256_fmadd_ps(scale, hi, offset); hi = _mm256_add_ps(hi, dith); x = mm256_cvtps_epu16(lo, hi); y = mm256_packus_epi16_si256_si128(x); y = _mm_min_epu8(y, out_max); return y; } inline FORCE_INLINE __m256i ordered_dither_w2w_avx2_xiter(unsigned j, const float *dither, unsigned dither_offset, unsigned dither_mask, const uint16_t *src_p, __m256 scale, __m256 offset, __m256i out_max) { __m256i x = _mm256_load_si256((const __m256i *)(src_p + j)); __m256 lo, hi; __m256 dith; mm256_cvtepu16_ps(x, lo, hi); dith = _mm256_load_ps(dither + ((dither_offset + j + 0) & dither_mask)); lo = _mm256_fmadd_ps(scale, lo, offset); lo = _mm256_add_ps(lo, dith); dith = _mm256_load_ps(dither + ((dither_offset + j + 8) & dither_mask)); hi = _mm256_fmadd_ps(scale, hi, offset); hi = _mm256_add_ps(hi, dith); x = mm256_cvtps_epu16(lo, hi); x = _mm256_min_epu16(x, out_max); return x; } template <class Load> inline FORCE_INLINE __m128i ordered_dither_f2b_avx2_xiter(unsigned j, const float *dither, unsigned dither_offset, unsigned dither_mask, const typename Load::type *src_p, __m256 scale, __m256 offset, __m128i out_max) { __m256 lo = Load::load(src_p + j + 0); __m256 hi = Load::load(src_p + j + 8); __m256 dith; __m256i x; __m128i y; dith = _mm256_load_ps(dither + ((dither_offset + j + 0) & dither_mask)); lo = _mm256_fmadd_ps(scale, lo, offset); lo = _mm256_add_ps(lo, dith); dith = _mm256_load_ps(dither + ((dither_offset + j + 8) & dither_mask)); hi = _mm256_fmadd_ps(scale, hi, offset); hi = _mm256_add_ps(hi, dith); x = mm256_cvtps_epu16(lo, hi); y = mm256_packus_epi16_si256_si128(x); y = _mm_min_epu8(y, out_max); return y; } template <class Load> inline FORCE_INLINE __m256i ordered_dither_f2w_avx2_xiter(unsigned j, const float *dither, unsigned dither_offset, unsigned dither_mask, const typename Load::type *src_p, __m256 scale, __m256 offset, __m256i out_max) { __m256 lo = Load::load(src_p + j + 0); __m256 hi = Load::load(src_p + j + 8); __m256 dith; __m256i x; dith = _mm256_load_ps(dither + ((dither_offset + j + 0) & dither_mask)); lo = _mm256_fmadd_ps(scale, lo, offset); lo = _mm256_add_ps(lo, dith); dith = _mm256_load_ps(dither + ((dither_offset + j + 8) & dither_mask)); hi = _mm256_fmadd_ps(scale, hi, offset); hi = _mm256_add_ps(hi, dith); x = mm256_cvtps_epu16(lo, hi); x = _mm256_min_epu16(x, out_max); return x; } } // namespace void ordered_dither_b2b_avx2(const float *dither, unsigned dither_offset, unsigned dither_mask, const void *src, void *dst, float scale, float offset, unsigned bits, unsigned left, unsigned right) { const uint8_t *src_p = static_cast<const uint8_t *>(src); uint8_t *dst_p = static_cast<uint8_t *>(dst); unsigned vec_left = ceil_n(left, 16); unsigned vec_right = floor_n(right, 16); const __m256 scale_ps = _mm256_set1_ps(scale); const __m256 offset_ps = _mm256_set1_ps(offset); const __m128i out_max = _mm_set1_epi8((uint8_t)((1 << bits) - 1)); #define XITER ordered_dither_b2b_avx2_xiter #define XARGS dither, dither_offset, dither_mask, src_p, scale_ps, offset_ps, out_max if (left != vec_left) { __m128i x = XITER(vec_left - 16, XARGS); mm_store_left_epi8(dst_p + vec_left - 16, x, vec_left - left); } for (unsigned j = vec_left; j < vec_right; j += 16) { __m128i x = XITER(j, XARGS); _mm_store_si128((__m128i *)(dst_p + j), x); } if (right != vec_right) { __m128i x = XITER(vec_right, XARGS); mm_store_right_epi8(dst_p + vec_right, x, right - vec_right); } #undef XITER #undef XARGS } void ordered_dither_b2w_avx2(const float *dither, unsigned dither_offset, unsigned dither_mask, const void *src, void *dst, float scale, float offset, unsigned bits, unsigned left, unsigned right) { const uint8_t *src_p = static_cast<const uint8_t *>(src); uint16_t *dst_p = static_cast<uint16_t *>(dst); unsigned vec_left = ceil_n(left, 16); unsigned vec_right = floor_n(right, 16); const __m256 scale_ps = _mm256_set1_ps(scale); const __m256 offset_ps = _mm256_set1_ps(offset); const __m256i out_max = _mm256_set1_epi16((uint16_t)((1 << bits) - 1)); #define XITER ordered_dither_b2w_avx2_xiter #define XARGS dither, dither_offset, dither_mask, src_p, scale_ps, offset_ps, out_max if (left != vec_left) { __m256i x = XITER(vec_left - 16, XARGS); mm256_store_left_epi16(dst_p + vec_left - 16, x, vec_left - left); } for (unsigned j = vec_left; j < vec_right; j += 16) { __m256i x = XITER(j, XARGS); _mm256_store_si256((__m256i *)(dst_p + j), x); } if (right != vec_right) { __m256i x = XITER(vec_right, XARGS); mm256_store_right_epi16(dst_p + vec_right, x, right - vec_right); } #undef XITER #undef XARGS } void ordered_dither_w2b_avx2(const float *dither, unsigned dither_offset, unsigned dither_mask, const void *src, void *dst, float scale, float offset, unsigned bits, unsigned left, unsigned right) { const uint16_t *src_p = static_cast<const uint16_t *>(src); uint8_t *dst_p = static_cast<uint8_t *>(dst); unsigned vec_left = ceil_n(left, 16); unsigned vec_right = floor_n(right, 16); const __m256 scale_ps = _mm256_set1_ps(scale); const __m256 offset_ps = _mm256_set1_ps(offset); const __m128i out_max = _mm_set1_epi8((uint8_t)((1 << bits) - 1)); #define XITER ordered_dither_w2b_avx2_xiter #define XARGS dither, dither_offset, dither_mask, src_p, scale_ps, offset_ps, out_max if (left != vec_left) { __m128i x = XITER(vec_left - 16, XARGS); mm_store_left_epi8(dst_p + vec_left - 16, x, vec_left - left); } for (unsigned j = vec_left; j < vec_right; j += 16) { __m128i x = XITER(j, XARGS); _mm_store_si128((__m128i *)(dst_p + j), x); } if (right != vec_right) { __m128i x = XITER(vec_right, XARGS); mm_store_right_epi8(dst_p + vec_right, x, right - vec_right); } #undef XITER #undef XARGS } void ordered_dither_w2w_avx2(const float *dither, unsigned dither_offset, unsigned dither_mask, const void *src, void *dst, float scale, float offset, unsigned bits, unsigned left, unsigned right) { const uint16_t *src_p = static_cast<const uint16_t *>(src); uint16_t *dst_p = static_cast<uint16_t *>(dst); unsigned vec_left = ceil_n(left, 16); unsigned vec_right = floor_n(right, 16); const __m256 scale_ps = _mm256_set1_ps(scale); const __m256 offset_ps = _mm256_set1_ps(offset); const __m256i out_max = _mm256_set1_epi16((uint16_t)((1 << bits) - 1)); #define XITER ordered_dither_w2w_avx2_xiter #define XARGS dither, dither_offset, dither_mask, src_p, scale_ps, offset_ps, out_max if (left != vec_left) { __m256i x = XITER(vec_left - 16, XARGS); mm256_store_left_epi16(dst_p + vec_left - 16, x, vec_left - left); } for (unsigned j = vec_left; j < vec_right; j += 16) { __m256i x = XITER(j, XARGS); _mm256_store_si256((__m256i *)(dst_p + j), x); } if (right != vec_right) { __m256i x = XITER(vec_right, XARGS); mm256_store_right_epi16(dst_p + vec_right, x, right - vec_right); } #undef XITER #undef XARGS } void ordered_dither_h2b_avx2(const float *dither, unsigned dither_offset, unsigned dither_mask, const void *src, void *dst, float scale, float offset, unsigned bits, unsigned left, unsigned right) { const uint16_t *src_p = static_cast<const uint16_t *>(src); uint8_t *dst_p = static_cast<uint8_t *>(dst); unsigned vec_left = ceil_n(left, 16); unsigned vec_right = floor_n(right, 16); const __m256 scale_ps = _mm256_set1_ps(scale); const __m256 offset_ps = _mm256_set1_ps(offset); const __m128i out_max = _mm_set1_epi8((uint8_t)((1 << bits) - 1)); #define XITER ordered_dither_f2b_avx2_xiter<LoadF16> #define XARGS dither, dither_offset, dither_mask, src_p, scale_ps, offset_ps, out_max if (left != vec_left) { __m128i x = XITER(vec_left - 16, XARGS); mm_store_left_epi8(dst_p + vec_left - 16, x, vec_left - left); } for (unsigned j = vec_left; j < vec_right; j += 16) { __m128i x = XITER(j, XARGS); _mm_store_si128((__m128i *)(dst_p + j), x); } if (right != vec_right) { __m128i x = XITER(vec_right, XARGS); mm_store_right_epi8(dst_p + vec_right, x, right - vec_right); } #undef XITER #undef XARGS } void ordered_dither_h2w_avx2(const float *dither, unsigned dither_offset, unsigned dither_mask, const void *src, void *dst, float scale, float offset, unsigned bits, unsigned left, unsigned right) { const uint16_t *src_p = static_cast<const uint16_t *>(src); uint16_t *dst_p = static_cast<uint16_t *>(dst); unsigned vec_left = ceil_n(left, 16); unsigned vec_right = floor_n(right, 16); const __m256 scale_ps = _mm256_set1_ps(scale); const __m256 offset_ps = _mm256_set1_ps(offset); const __m256i out_max = _mm256_set1_epi16((uint16_t)((1 << bits) - 1)); #define XITER ordered_dither_f2w_avx2_xiter<LoadF16> #define XARGS dither, dither_offset, dither_mask, src_p, scale_ps, offset_ps, out_max if (left != vec_left) { __m256i x = XITER(vec_left - 16, XARGS); mm256_store_left_epi16(dst_p + vec_left - 16, x, vec_left - left); } for (unsigned j = vec_left; j < vec_right; j += 16) { __m256i x = XITER(j, XARGS); _mm256_store_si256((__m256i *)(dst_p + j), x); } if (right != vec_right) { __m256i x = XITER(vec_right, XARGS); mm256_store_right_epi16(dst_p + vec_right, x, right - vec_right); } #undef XITER #undef XARGS } void ordered_dither_f2b_avx2(const float *dither, unsigned dither_offset, unsigned dither_mask, const void *src, void *dst, float scale, float offset, unsigned bits, unsigned left, unsigned right) { const float *src_p = static_cast<const float *>(src); uint8_t *dst_p = static_cast<uint8_t *>(dst); unsigned vec_left = ceil_n(left, 16); unsigned vec_right = floor_n(right, 16); const __m256 scale_ps = _mm256_set1_ps(scale); const __m256 offset_ps = _mm256_set1_ps(offset); const __m128i out_max = _mm_set1_epi8((uint8_t)((1 << bits) - 1)); #define XITER ordered_dither_f2b_avx2_xiter<LoadF32> #define XARGS dither, dither_offset, dither_mask, src_p, scale_ps, offset_ps, out_max if (left != vec_left) { __m128i x = XITER(vec_left - 16, XARGS); mm_store_left_epi8(dst_p + vec_left - 16, x, vec_left - left); } for (unsigned j = vec_left; j < vec_right; j += 16) { __m128i x = XITER(j, XARGS); _mm_store_si128((__m128i *)(dst_p + j), x); } if (right != vec_right) { __m128i x = XITER(vec_right, XARGS); mm_store_right_epi8(dst_p + vec_right, x, right - vec_right); } #undef XITER #undef XARGS } void ordered_dither_f2w_avx2(const float *dither, unsigned dither_offset, unsigned dither_mask, const void *src, void *dst, float scale, float offset, unsigned bits, unsigned left, unsigned right) { const float *src_p = static_cast<const float *>(src); uint16_t *dst_p = static_cast<uint16_t *>(dst); unsigned vec_left = ceil_n(left, 16); unsigned vec_right = floor_n(right, 16); const __m256 scale_ps = _mm256_set1_ps(scale); const __m256 offset_ps = _mm256_set1_ps(offset); const __m256i out_max = _mm256_set1_epi16((uint16_t)((1 << bits) - 1)); #define XITER ordered_dither_f2w_avx2_xiter<LoadF32> #define XARGS dither, dither_offset, dither_mask, src_p, scale_ps, offset_ps, out_max if (left != vec_left) { __m256i x = XITER(vec_left - 16, XARGS); mm256_store_left_epi16(dst_p + vec_left - 16, x, vec_left - left); } for (unsigned j = vec_left; j < vec_right; j += 16) { __m256i x = XITER(j, XARGS); _mm256_store_si256((__m256i *)(dst_p + j), x); } if (right != vec_right) { __m256i x = XITER(vec_right, XARGS); mm256_store_right_epi16(dst_p + vec_right, x, right - vec_right); } #undef XITER #undef XARGS } } // namespace depth } // namespace zimg #endif // ZIMG_X86
32.093385
137
0.701443
dubhater
eafe2510b498e25c1d76448ee34dc2b1e217e409
601
cpp
C++
place_recognition/generate_signatures/src/GIST/src/main.cpp
IRVLab/so_dso_place_recognition
c330ee459bf3140fe2c117f0a3ad3535f8cad2ce
[ "Unlicense" ]
38
2020-07-23T04:33:41.000Z
2022-03-07T03:41:38.000Z
place_recognition/generate_signatures/src/GIST/src/main.cpp
IRVLab/so_dso_place_recognition
c330ee459bf3140fe2c117f0a3ad3535f8cad2ce
[ "Unlicense" ]
null
null
null
place_recognition/generate_signatures/src/GIST/src/main.cpp
IRVLab/so_dso_place_recognition
c330ee459bf3140fe2c117f0a3ad3535f8cad2ce
[ "Unlicense" ]
10
2020-10-19T01:00:43.000Z
2022-02-21T03:57:57.000Z
#include <iomanip> #include <iostream> #include <opencv2/opencv.hpp> #include "gist.h" #include "standalone_image.h" using namespace std; using namespace cv; using namespace cls; const GISTParams DEFAULT_PARAMS{true, 32, 32, 4, 3, {8, 8, 4}}; int main(int argc, char *argv[]) { Mat src = imread(argv[1]); if (src.empty()) { cerr << "No input image!" << endl; exit(1); } vector<float> result; GIST gist_ext(DEFAULT_PARAMS); gist_ext.extract(src, result); for (const auto &val : result) { cout << fixed << setprecision(4) << val << " "; } cout << endl; return 0; }
19.387097
63
0.635607
IRVLab
d80066e417bd53da3def109bc4936bb747115a6c
60
cpp
C++
LoveLiveWallpaper/src/IPointerUp.cpp
Juvwxyz/LoveLiveWallpaper
a0eeac941b5ccd53af538192cb92b7df049839c4
[ "MIT" ]
2
2020-05-09T00:13:06.000Z
2020-05-25T05:49:40.000Z
LoveLiveWallpaper/src/IPointerUp.cpp
Juvwxyz/LoveLiveWallpaper
a0eeac941b5ccd53af538192cb92b7df049839c4
[ "MIT" ]
null
null
null
LoveLiveWallpaper/src/IPointerUp.cpp
Juvwxyz/LoveLiveWallpaper
a0eeac941b5ccd53af538192cb92b7df049839c4
[ "MIT" ]
1
2020-05-25T05:49:44.000Z
2020-05-25T05:49:44.000Z
#include "IPointerUp.h" LLWP::IPointerUp::IPointerUp() { }
10
30
0.7
Juvwxyz
d800e268757cf43faee658356e2ab81a77a362db
7,726
cxx
C++
CORRFW/AliCFPair.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
114
2017-03-03T09:12:23.000Z
2022-03-03T20:29:42.000Z
CORRFW/AliCFPair.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
19,637
2017-01-16T12:34:41.000Z
2022-03-31T22:02:40.000Z
CORRFW/AliCFPair.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
1,021
2016-07-14T22:41:16.000Z
2022-03-31T05:15:51.000Z
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ //////////////////////////////////////////////// // Class to handle pairs of tracks // Useful for resonance analysis // Derives from AliVParticle => // usable in Correction Framework //////////////////////////////////////////////// // author : renaud.vernet@cern.ch //////////////////////////////////////////////// #include "AliCFPair.h" #include "AliESDtrack.h" #include "AliESDv0.h" #include "AliESDEvent.h" #include "TMath.h" #include "AliAODv0.h" ClassImp(AliCFPair) AliCFPair::AliCFPair(AliVParticle* t1, AliVParticle* t2) : AliVParticle(), fIsV0(0), fTrackNeg(t1), fTrackPos(t2), fESDV0(0x0), fAODV0(0x0), fLabel(-1), fV0PDG(0), fMassNeg(0.), fMassPos(0.) { // // 2-track ctor // } AliCFPair::AliCFPair(AliESDv0* v0, AliESDEvent* esd) : AliVParticle(), fIsV0(1), fTrackNeg(esd->GetTrack(v0->GetNindex())), fTrackPos(esd->GetTrack(v0->GetPindex())), fESDV0(v0), fAODV0(0x0), fLabel(-1), fV0PDG(0), fMassNeg(0.), fMassPos(0.) { // // V0 ctor // } AliCFPair::AliCFPair(AliAODv0* v0) : AliVParticle(), fIsV0(1), fTrackNeg((AliVParticle*)v0->GetSecondaryVtx()->GetDaughter(1)), fTrackPos((AliVParticle*)v0->GetSecondaryVtx()->GetDaughter(0)), fESDV0(0x0), fAODV0(v0), fLabel(-1), fV0PDG(0), fMassNeg(0.), fMassPos(0.) { // // V0 ctor // } AliCFPair::AliCFPair(const AliCFPair& c) : AliVParticle(c), fIsV0(c.fIsV0), fTrackNeg(c.fTrackNeg), fTrackPos(c.fTrackPos), fESDV0(c.fESDV0), fAODV0(c.fAODV0), fLabel(c.fLabel), fV0PDG(c.fV0PDG), fMassNeg(c.fMassNeg), fMassPos(c.fMassPos) { // // Copy constructor. // } AliCFPair& AliCFPair::operator=(const AliCFPair& c) { // // assignment operator. // if (this!=&c) { AliVParticle::operator=(c); fIsV0 = c.fIsV0; fTrackNeg = c.fTrackNeg ; fTrackPos = c.fTrackPos ; fESDV0 = c.fESDV0 ; fAODV0 = c.fAODV0 ; fLabel = c.fLabel ; fV0PDG = c.fV0PDG ; fMassNeg = c.fMassNeg ; fMassPos = c.fMassPos; } return *this; } Bool_t AliCFPair::PxPyPz(Double_t p[3]) const { // // sets pair total momentum in vector p // if (fIsV0) { if (fESDV0) fESDV0->GetPxPyPz(p[0],p[1],p[2]); else if (fAODV0) fAODV0->PxPyPz(p); else Error("PxPyPz","Pointer to V0 not found"); } else if (fTrackNeg && fTrackPos) { p[0]=fTrackNeg->Px()+fTrackPos->Px(); p[1]=fTrackNeg->Py()+fTrackPos->Py(); p[2]=fTrackNeg->Pz()+fTrackPos->Pz(); } else Error("PxPyPz","Could not find V0 nor track pointers"); return kTRUE; } Double32_t AliCFPair::P() const { // // returns pair total momentum norm // Double32_t mom[3]; PxPyPz(mom); return TMath::Sqrt(mom[0]*mom[0]+mom[1]*mom[1]+mom[2]*mom[2]); } Double32_t AliCFPair::Px() const { // // returns pair X-projected momentum // Double32_t mom[3]; PxPyPz(mom); return mom[0]; } Double32_t AliCFPair::Py() const { // // returns pair Y-projected momentum // Double32_t mom[3]; PxPyPz(mom); return mom[1]; } Double32_t AliCFPair::Pz() const { // // returns pair Z-projected momentum // Double32_t mom[3]; PxPyPz(mom); return mom[2]; } Double32_t AliCFPair::Pt() const { // // returns pair transverse (XY) momentum // Double32_t mom[3]; PxPyPz(mom); return sqrt(mom[0]*mom[0]+mom[1]*mom[1]); } Double32_t AliCFPair::E() const { // // returns pair total energy according to ESD-calculated mass // Double32_t mom[3]; PxPyPz(mom); Double32_t mass=M() ; return TMath::Sqrt(mass*mass + mom[0]*mom[0]+ mom[1]*mom[1]+ mom[2]*mom[2]); } Bool_t AliCFPair::XvYvZv(Double_t x[3]) const { // // sets pair position to x // since this class is designed for resonances, the assumed pair position // should be the same for both tracks. neg track position is kept here // if (fIsV0) { if (fESDV0) fESDV0->GetXYZ(x[0],x[1],x[2]); else if (fAODV0) fAODV0->XvYvZv(x); else Error("PxPyPz","Pointer to V0 not found"); } else if (fTrackNeg) fTrackNeg->PxPyPz(x); else Error("PxPyPz","Could not find V0 nor track pointers"); return kTRUE; } Double32_t AliCFPair::Xv() const { // // returns pair X-projected position // Double32_t pos[3]; XvYvZv(pos); return pos[0]; } Double32_t AliCFPair::Yv() const { // // returns pair Y-projected position // Double32_t pos[3]; XvYvZv(pos); return pos[1]; } Double32_t AliCFPair::Zv() const { // // returns pair Z-projected position // Double32_t pos[3]; XvYvZv(pos); return pos[2]; } Double32_t AliCFPair::Phi() const { // // returns pair phi angle (in transverse plane) // return TMath::Pi()+TMath::ATan2(-Py(),-Px()); } Double32_t AliCFPair::Theta() const { // // returns pair theta angle (in YZ plane) // return (Pz()==0)?TMath::PiOver2():TMath::ACos(Pz()/P()); } Double32_t AliCFPair::Eta() const { // // returns pair pseudo-rapidity // Double32_t pmom = P(); Double32_t pz = Pz(); if (pmom != TMath::Abs(pz)) return 0.5*TMath::Log((pmom+pz)/(pmom-pz)); else return 999; } Double32_t AliCFPair::Y() const { // // returns pair rapidity // Double32_t e = E(); Double32_t pz = Pz(); if (e == pz || e == -pz) { printf("GetRapidity : ERROR : rapidity for 4-vector with E = Pz -- infinite result"); return 999; } if (e < pz) { printf("GetRapidity : ERROR : rapidity for 4-vector with E = Pz -- infinite result"); return 999; } Double32_t y = 0.5 * log((e + pz) / (e - pz)); return y; } Double32_t AliCFPair::M() const { // // returns pair invariant mass // in case of a V0, returns the current mass hypothesis // otherwise returns ESD-calculated mass // Double32_t minv = 0. ; if (fIsV0) { if (fESDV0) { fESDV0->ChangeMassHypothesis(fV0PDG); minv = (Double32_t)fESDV0->GetEffMass(); } else if (fAODV0) { switch (fV0PDG) { case 310 : minv = fAODV0->MassK0Short() ; break ; case 3122 : minv = fAODV0->MassLambda() ; break ; case -3122: minv = fAODV0->MassAntiLambda() ; break ; default: minv = -1. ; break ; } } else Error("PxPyPz","Pointer to V0 not found"); } else if (fTrackNeg && fTrackPos) { Double32_t p = P() ; Double32_t e =0. ; if (fMassNeg==0. && fMassPos==0.) { e = fTrackNeg->E() + fTrackPos->E() ; } else { e = TMath::Sqrt(TMath::Power(fTrackNeg->P(),2)+TMath::Power(fMassNeg,2)) + TMath::Sqrt(TMath::Power(fTrackPos->P(),2)+TMath::Power(fMassPos,2)) ; } minv = TMath::Sqrt(e*e-p*p); } else Error("M","Could not find V0 nor track pointers"); return minv ; }
25.166124
89
0.582708
maroozm
d8010d8b2e5a912437b2d9292b01bfc1732a2f0f
3,502
hpp
C++
include/RED4ext/Scripting/Natives/Generated/AtmosphereAreaSettings.hpp
flibX0r/RED4ext.SDK
18d075ef7559e35d8b02dc2e00a03ccc7ff4d77b
[ "MIT" ]
42
2020-12-25T08:33:00.000Z
2022-03-22T14:47:07.000Z
include/RED4ext/Scripting/Natives/Generated/AtmosphereAreaSettings.hpp
flibX0r/RED4ext.SDK
18d075ef7559e35d8b02dc2e00a03ccc7ff4d77b
[ "MIT" ]
38
2020-12-28T22:36:06.000Z
2022-02-16T11:25:47.000Z
include/RED4ext/Scripting/Natives/Generated/AtmosphereAreaSettings.hpp
flibX0r/RED4ext.SDK
18d075ef7559e35d8b02dc2e00a03ccc7ff4d77b
[ "MIT" ]
20
2020-12-28T22:17:38.000Z
2022-03-22T17:19:01.000Z
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/NativeTypes.hpp> #include <RED4ext/Scripting/Natives/Generated/HDRColor.hpp> #include <RED4ext/Scripting/Natives/Generated/IAreaSettings.hpp> namespace RED4ext { struct CBitmapTexture; struct CCubeTexture; struct AtmosphereAreaSettings : IAreaSettings { static constexpr const char* NAME = "AtmosphereAreaSettings"; static constexpr const char* ALIAS = NAME; CurveData<HDRColor> skydomeColor; // 48 CurveData<HDRColor> skylightColor; // 80 CurveData<HDRColor> groundReflectance; // B8 CurveData<float> horizonMinZ; // F0 CurveData<float> sunMinZ; // 128 CurveData<float> horizonFalloff; // 160 CurveData<float> turbidity; // 198 CurveData<float> lutTurbidity; // 1D0 CurveData<HDRColor> artisticDarkeningColor; // 208 CurveData<float> artisticDarkeningStartPoint; // 240 CurveData<float> artisticDarkeningEndPoint; // 278 CurveData<float> artisticDarkeningExponent; // 2B0 CurveData<HDRColor> sunColor; // 2E8 CurveData<float> sunFalloff; // 320 CurveData<float> rayTracedSunShadowRange; // 358 CurveData<HDRColor> moonColor; // 390 CurveData<float> moonFalloff; // 3C8 CurveData<float> moonGlowIntensity; // 400 CurveData<float> moonGlowFalloff; // 438 Ref<CBitmapTexture> moonTexture; // 470 CurveData<float> galaxyIntensity; // 488 CurveData<float> starMapIntensity; // 4C0 CurveData<float> starMapBrightScale; // 4F8 CurveData<float> starMapDimScale; // 530 CurveData<float> starMapConstelationsScale; // 568 CurveData<float> starCornerLuminanceFix; // 5A0 Ref<CCubeTexture> starMapTexture; // 5D8 Ref<CBitmapTexture> galaxyTexture; // 5F0 CurveData<HDRColor> probeColorOverrideHorizon; // 608 CurveData<float> probeAlphaOverrideHorizon; // 640 CurveData<HDRColor> probeColorOverrideZenith; // 678 CurveData<float> probeAlphaOverrideZenith; // 6B0 CurveData<float> cloudSunShadowFaloff; // 6E8 CurveData<float> cloudSunScattering; // 720 CurveData<float> cloudMoonScattering; // 758 CurveData<float> cloudCirrusOpacity; // 790 CurveData<float> cloudAmbientIntensity; // 7C8 CurveData<float> cloudCirrusScale; // 800 CurveData<float> cloudCirrusAltitude; // 838 Ref<CBitmapTexture> cloudCirrusTexture; // 870 Ref<CBitmapTexture> volWeatherTexture; // 888 Ref<CBitmapTexture> volNoiseTexture; // 8A0 CurveData<float> volCoverage; // 8B8 float volHorizonCoverage; // 8F0 uint8_t unk8F4[0x8F8 - 0x8F4]; // 8F4 CurveData<float> volDensity; // 8F8 float cloudsBottom; // 930 float cloudsTop; // 934 float rayStartOffset; // 938 float rayStartFalloff; // 93C CurveData<float> lightIntensity; // 940 CurveData<float> reflectionProbeLightIntensity; // 978 CurveData<float> shadowIntensity; // 9B0 CurveData<float> worldShadowIntensity; // 9E8 CurveData<float> ambientIntensity; // A20 float inScatter; // A58 float outScatter; // A5C float inVsOutScatter; // A60 float silverLining; // A64 uint8_t unkA68[0xA70 - 0xA68]; // A68 CurveData<float> ambientOutscatter; // A70 float volCoverageWindInfluence; // AA8 float volNoiseWindInfluence; // AAC float volDetailWindInfluence; // AB0 float volDistantFogOpacity; // AB4 }; RED4EXT_ASSERT_SIZE(AtmosphereAreaSettings, 0xAB8); } // namespace RED4ext
39.348315
65
0.729298
flibX0r
d807cd0ff6bf9012a57b42dc97e65526bd31f6f3
1,053
cpp
C++
232ImplementQueueUsingStacks.cpp
yuyangh/LeetCode
5d81cbd975c0c1f2bbca0cb25cefe361a169e460
[ "MIT" ]
1
2020-10-11T08:10:53.000Z
2020-10-11T08:10:53.000Z
232ImplementQueueUsingStacks.cpp
yuyangh/LeetCode
5d81cbd975c0c1f2bbca0cb25cefe361a169e460
[ "MIT" ]
null
null
null
232ImplementQueueUsingStacks.cpp
yuyangh/LeetCode
5d81cbd975c0c1f2bbca0cb25cefe361a169e460
[ "MIT" ]
null
null
null
#include "LeetCodeLib.h" class MyQueue { public: /** Initialize your data structure here. */ stack<int> reverse, order; MyQueue() { } /** Push element x to the back of queue. */ void push(int x) { restoreReverseElements(); reverse.push(x); } /** Removes the element from in front of queue and returns that element. */ int pop() { int result = peek(); order.pop(); return result; } /** Get the front element. */ int peek() { restoreReverseElements(); while (!reverse.empty()) { order.push(reverse.top()); reverse.pop(); } int result = order.top(); return result; } /** Returns whether the queue is empty. */ bool empty() { return reverse.empty() && order.empty(); } void restoreReverseElements() { while (!order.empty()) { reverse.push(order.top()); order.pop(); } } }; /** * Your MyQueue object will be instantiated and called as such: * MyQueue* obj = new MyQueue(); * obj->push(x); * int param_2 = obj->pop(); * int param_3 = obj->peek(); * bool param_4 = obj->empty(); */
18.803571
76
0.617284
yuyangh
d807d13dac6afc0d3daf1edd4ea8b1ded5b83f7b
790
cpp
C++
17-database-xml/17-13/myxmlstream/main.cpp
Franklin-Qi/qtcreator-example
5d573f961c3255fbf740991996f935092cc62018
[ "MIT" ]
null
null
null
17-database-xml/17-13/myxmlstream/main.cpp
Franklin-Qi/qtcreator-example
5d573f961c3255fbf740991996f935092cc62018
[ "MIT" ]
null
null
null
17-database-xml/17-13/myxmlstream/main.cpp
Franklin-Qi/qtcreator-example
5d573f961c3255fbf740991996f935092cc62018
[ "MIT" ]
null
null
null
#include <QCoreApplication> #include <QFile> #include <QXmlStreamReader> #include <QXmlStreamWriter> #include <QDebug> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QFile file("../myxmlstream/my2.xml"); if (!file.open(QFile::WriteOnly | QFile::Text)) { qDebug() << "Error: cannot open file"; return 1; } QXmlStreamWriter stream(&file); stream.setAutoFormatting(true); stream.writeStartDocument(); stream.writeStartElement("bookmark"); stream.writeAttribute("href", "http://www.qt.io/"); stream.writeTextElement("title", "Qt Home"); stream.writeEndElement(); stream.writeEndDocument(); file.close(); qDebug() << "write finished!"; return a.exec(); }
23.235294
56
0.620253
Franklin-Qi
d809305893b9a98d5d664f8379a5c24bb29c0a46
2,323
cc
C++
src/proto/core/entity-system/interface.cc
kcpikkt/proto
2d7458c2ce2f571303de040f660137dc0a1d33de
[ "MIT" ]
null
null
null
src/proto/core/entity-system/interface.cc
kcpikkt/proto
2d7458c2ce2f571303de040f660137dc0a1d33de
[ "MIT" ]
null
null
null
src/proto/core/entity-system/interface.cc
kcpikkt/proto
2d7458c2ce2f571303de040f660137dc0a1d33de
[ "MIT" ]
null
null
null
#include "proto/core/entity-system/interface.hh" namespace proto { // for doing things, that are usually done compile time, runtime // i.e. type erasure at its best struct _Runtime { template<size_t I> using CompAt = typename CompTList::template at_t<I>; // get template<typename...> struct _get_switch; template<size_t...Is> struct _get_switch<meta::sequence<Is...>> { Entity _ent; size_t _idx; void * _ret = nullptr; template<size_t I> inline void _case() { if(_ret) return; // we compare runtime index with static I, if(I == _idx) if(auto comp = get_comp<CompAt<I>>(_ent)) _ret = (void*)comp; } // go through all the cases _get_switch(Entity ent, size_t idx) : _ent(ent), _idx(idx) { ((_case<Is>()),...); } }; static void * get_comp_at(Entity ent, size_t idx) { if(idx >= CompTList::size) return nullptr; return _get_switch< meta::make_sequence<0, CompTList::size> >(ent, idx)._ret; } // add template<typename...> struct _add_switch; template<size_t...Is> struct _add_switch<meta::sequence<Is...>> { Entity _ent; size_t _idx; void * _ret = nullptr; template<size_t I> inline void _case() { if(_ret) return; // we compare runtime index with static I, if(I == _idx) if(auto comp = add_comp<CompAt<I>>(_ent)) _ret = (void*)comp; } // go through all the cases _add_switch(Entity ent, size_t idx) : _ent(ent), _idx(idx) { ((_case<Is>()),...); } }; static void * add_comp_at(Entity ent, size_t idx) { if(idx >= CompTList::size) return nullptr; return _add_switch< meta::make_sequence<0, CompTList::size> >(ent, idx)._ret; } }; void * get_comp(Entity entity, u64 comp_idx) { return _Runtime::get_comp_at(entity, comp_idx); } void * add_comp(Entity entity, u64 comp_idx) { return _Runtime::add_comp_at(entity, comp_idx); } } //namespace proto
32.71831
89
0.530779
kcpikkt
d80da73ddb700e879f1359d3387ef87b329bd11e
1,275
cc
C++
TrkFitter/TrkDeadMaker.cc
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
TrkFitter/TrkDeadMaker.cc
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
TrkFitter/TrkDeadMaker.cc
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
//-------------------------------------------------------------------------- // File and Version Information: // $Id: TrkDeadMaker.cc 104 2010-01-15 12:13:14Z stroili $ // // Description: // // Environment: // Software developed for the BaBar Detector at the SLAC B-Factory. // // Authors: Steve Schaffner // //------------------------------------------------------------------------ #include "BaBar/BaBar.hh" #include "TrkFitter/TrkDeadMaker.hh" #include "TrkFitter/TrkDeadRep.hh" #include "TrkBase/TrkRecoTrk.hh" #include <assert.h> //------------------------------------------------------------------------ TrkDeadMaker::~TrkDeadMaker() {} //------------------------------------------------------------------------ //------------------------------------------------------------------------ TrkDeadMaker::TrkDeadMaker() {} //------------------------------------------------------------------------ //------------------------------------------------------------------------ void TrkDeadMaker::addHypo(TrkRecoTrk* trk, PdtPid::PidType hypo) { //------------------------------------------------------------------------ assert (trk != 0); TrkDeadRep* newRep = new TrkDeadRep(trk, hypo); // Install via TrkFitMaker fcn addHypoTo(*trk, newRep, hypo); }
32.692308
76
0.370196
brownd1978
d810e3d06ba7e8c537f455c21dbe790b83752c4a
33
hh
C++
build/ARM/arch/registers.hh
magnuram/edelsten5
63de812a22142f07fa48c253636e5c96156d4da9
[ "BSD-3-Clause" ]
null
null
null
build/ARM/arch/registers.hh
magnuram/edelsten5
63de812a22142f07fa48c253636e5c96156d4da9
[ "BSD-3-Clause" ]
null
null
null
build/ARM/arch/registers.hh
magnuram/edelsten5
63de812a22142f07fa48c253636e5c96156d4da9
[ "BSD-3-Clause" ]
null
null
null
#include "arch/arm/registers.hh"
16.5
32
0.757576
magnuram
d811e05fd7042c828b95a833e7567ea334f31190
29,688
cpp
C++
Libraries/RobsJuceModules/rosic/legacy/AggressorOscSection.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
34
2017-04-19T18:26:02.000Z
2022-02-15T17:47:26.000Z
Libraries/RobsJuceModules/rosic/legacy/AggressorOscSection.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
307
2017-05-04T21:45:01.000Z
2022-02-03T00:59:01.000Z
Libraries/RobsJuceModules/rosic/legacy/AggressorOscSection.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
4
2017-09-05T17:04:31.000Z
2021-12-15T21:24:28.000Z
#include "AggressorOscSection.h" //construction/destruction AggressorOscSection::AggressorOscSection() { //init member variables: slideTime = 0.5; //init slieTime to 0.5 seconds sampleRate = 44100; slideSamples = slideTime*sampleRate; slideSampCount = 0; syncMode = 0; modulationMode = 0; currentNote = -1; currentDetune = 0; currentPitch = 64.0; targetPitch = 64.0; freqBend = 1.0; currentFreq = PITCH2FREQ(currentPitch); targetFreq = PITCH2FREQ(targetPitch); osc1IsPlaying = true; osc2IsPlaying = true; osc3IsPlaying = true; vibIsActive = true; pwmIsActive = true; modulationsOff = false; syncIsActive = false; tuneCoarse2 = 0.0; tuneFine2 = 0.0; tuneFactor2 = 1.0; tuneCoarse3 = 0.0; tuneFine3 = 0.0; tuneFactor3 = 1.0; pulseWidth1 = 0.5; pulseWidth2 = 0.5; pulseWidth3 = 0.5; pitchIncPerSamp = 0.0; freqFacPerSamp = 1.0; accent = 1.0; vibDepth = 0.0; pwmDepth = 0.0; phase1 = 0.0; vol1Start = 0.0; vol1StartByVel = 0.0; vol1StartByVelAc = 0.0; pitch1Start = 0.0; pitch1StartByVel = 0.0; pitch1StartByVelAc = 0.0; amBy2Start = 0.0; amBy2StartByVel = 0.0; amBy2StartByVelAc = 0.0; amBy3Start = 0.0; amBy3StartByVel = 0.0; amBy3StartByVelAc = 0.0; fmBy1Start = 0.0; fmBy1StartByVel = 0.0; fmBy1StartByVelAc = 0.0; fmBy2Start = 0.0; fmBy2StartByVel = 0.0; fmBy2StartByVelAc = 0.0; fmBy3Start = 0.0; fmBy3StartByVel = 0.0; fmBy3StartByVelAc = 0.0; phase2 = 0.0; vol2Start = 0.0; vol2StartByVel = 0.0; vol2StartByVelAc = 0.0; pitch2Start = 0.0; pitch2StartByVel = 0.0; pitch2StartByVelAc = 0.0; phase3 = 0.0; vol3Start = 0.0; vol3StartByVel = 0.0; vol3StartByVelAc = 0.0; pitch3Start = 0.0; pitch3StartByVel = 0.0; pitch3StartByVelAc = 0.0; rm12Start = 0.0; rm12StartByVel = 0.0; rm12StartByVelAc = 0.0; rm13Start = 0.0; rm13StartByVel = 0.0; rm13StartByVelAc = 0.0; rm23Start = 0.0; rm23StartByVel = 0.0; rm23StartByVelAc = 0.0; flt1.setLpfCutoff(20000.0); flt1.setHpfCutoff(20.0); flt1.setApfCutoff(20000.0); flt2.setLpfCutoff(20000.0); flt2.setHpfCutoff(20.0); flt2.setApfCutoff(20000.0); flt3.setLpfCutoff(20000.0); flt3.setHpfCutoff(20.0); flt3.setApfCutoff(20000.0); } AggressorOscSection::~AggressorOscSection() {} //------------------------------------------------------------------------------------------------------------ //parameter settings: //general: void AggressorOscSection::setSampleRate(double SampleRate) { if(SampleRate>0) sampleRate = SampleRate; //tell the oscillators the new sample-rate: osc1.setSampleRate(sampleRate); osc2.setSampleRate(sampleRate); osc3.setSampleRate(sampleRate); //tell the lfo's the new sample-rate and let them //re-calculate their increments: vibLfo.setSampleRate(sampleRate); pwmLfo.setSampleRate(sampleRate); vibLfo.calcIncrements(); pwmLfo.calcIncrements(); //tell the filters the new sample-rate: flt1.setSampleRate(sampleRate); flt2.setSampleRate(sampleRate); flt3.setSampleRate(sampleRate); //tell the ramp-envelopes the new sample-rate: ampRamp1.setSampleRate(sampleRate); ampRamp2.setSampleRate(sampleRate); ampRamp3.setSampleRate(sampleRate); freqRamp1.setSampleRate(sampleRate); freqRamp2.setSampleRate(sampleRate); freqRamp3.setSampleRate(sampleRate); rm12Ramp.setSampleRate(sampleRate); rm13Ramp.setSampleRate(sampleRate); rm23Ramp.setSampleRate(sampleRate); detuneRamp.setSampleRate(sampleRate); amBy2Ramp.setSampleRate(sampleRate); amBy3Ramp.setSampleRate(sampleRate); fmBy1Ramp.setSampleRate(sampleRate); fmBy2Ramp.setSampleRate(sampleRate); fmBy3Ramp.setSampleRate(sampleRate); } void AggressorOscSection::setMonoPoly(long MonoPoly) { } void AggressorOscSection::setSlideTime(double SlideTime) { if(SlideTime>=0) slideTime = SlideTime; slideSamples = slideTime*sampleRate; } void AggressorOscSection::setAccent(double Accent) { accent = Accent; vol1StartByVelAc = accent*vol1StartByVel; vol2StartByVelAc = accent*vol2StartByVel; vol3StartByVelAc = accent*vol3StartByVel; pitch1StartByVelAc = accent*pitch1StartByVel; pitch2StartByVelAc = accent*pitch2StartByVel; pitch3StartByVelAc = accent*pitch3StartByVel; amBy2StartByVelAc = accent*amBy2StartByVel; amBy3StartByVelAc = accent*amBy3StartByVel; fmBy1StartByVelAc = accent*fmBy1StartByVel; fmBy2StartByVelAc = accent*fmBy2StartByVel; fmBy3StartByVelAc = accent*fmBy3StartByVel; } void AggressorOscSection::setEnvSlope(double EnvSlope) { ampRamp1.setTauScale(EnvSlope); ampRamp2.setTauScale(EnvSlope); ampRamp3.setTauScale(EnvSlope); freqRamp1.setTauScale(EnvSlope); freqRamp2.setTauScale(EnvSlope); freqRamp3.setTauScale(EnvSlope); rm12Ramp.setTauScale(EnvSlope); rm13Ramp.setTauScale(EnvSlope); rm23Ramp.setTauScale(EnvSlope); detuneRamp.setTauScale(EnvSlope); amBy2Ramp.setTauScale(EnvSlope); amBy3Ramp.setTauScale(EnvSlope); fmBy1Ramp.setTauScale(EnvSlope); fmBy2Ramp.setTauScale(EnvSlope); fmBy3Ramp.setTauScale(EnvSlope); } void AggressorOscSection::setVibDepth(double VibDepth) {vibDepth = 0.01*VibDepth;} void AggressorOscSection::setVibRate(double VibRate) { vibLfo.setFreq(VibRate); vibLfo.calcIncrements(); } void AggressorOscSection::setVibWave(long VibWave) { if(VibWave>0) vibIsActive = true; else vibIsActive = false; vibLfo.setWaveForm(VibWave); } void AggressorOscSection::setPwmDepth(double PwmDepth) {pwmDepth = 0.01*PwmDepth;} void AggressorOscSection::setPwmRate(double PwmRate) { pwmLfo.setFreq(PwmRate); pwmLfo.calcIncrements(); } void AggressorOscSection::setPwmWave(long PwmWave) { if(PwmWave>0) pwmIsActive = true; else pwmIsActive = false; pwmLfo.setWaveForm(PwmWave); } //oscillator 1: void AggressorOscSection::setWaveForm1(long WaveForm1) { if(WaveForm1>0) osc1IsPlaying = true; else osc1IsPlaying = false; osc1.setWaveForm(WaveForm1); } void AggressorOscSection::setStartPhase1(double StartPhase1) { phase1 = StartPhase1; osc1.setStartPhase(StartPhase1); } void AggressorOscSection::setVol1Start(double Vol1Start) { vol1Start = Vol1Start; ampRamp1.setStart(DB2AMP(vol1Start)); } void AggressorOscSection::setVol1StartByVel(double Vol1StartByVel) { vol1StartByVel = Vol1StartByVel; vol1StartByVelAc = accent*vol1StartByVel; } void AggressorOscSection::setVol1Time(double Vol1Time) {ampRamp1.setTime(0.001*Vol1Time);} void AggressorOscSection::setVol1End(double Vol1End) {ampRamp1.setEnd(DB2AMP(Vol1End));} void AggressorOscSection::setPitch1Start(double Pitch1Start) { pitch1Start = Pitch1Start; freqRamp1.setStart(PITCHOFFSET2FREQFACTOR(pitch1Start)); } void AggressorOscSection::setPitch1StartByVel(double Pitch1StartByVel) { pitch1StartByVel = Pitch1StartByVel; pitch1StartByVelAc = accent*pitch1StartByVel; } void AggressorOscSection::setPitch1Time(double Pitch1Time) {freqRamp1.setTime(0.001*Pitch1Time);} void AggressorOscSection::setPitch1End(double Pitch1End) {freqRamp1.setEnd(PITCHOFFSET2FREQFACTOR(Pitch1End));} void AggressorOscSection::setOsc1Lpf(double Osc1Lpf) { flt1.setLpfCutoff(Osc1Lpf); } void AggressorOscSection::setOsc1Hpf(double Osc1Hpf) { flt1.setHpfCutoff(Osc1Hpf); } void AggressorOscSection::setOsc1Apf(double Osc1Apf) { flt1.setApfCutoff(Osc1Apf); } void AggressorOscSection::setPulseWidth1(double PulseWidth1) { if( (PulseWidth1>0.0) && (PulseWidth1<100.0) ) pulseWidth1 = 0.01*PulseWidth1; osc1.setPulseWidth(pulseWidth1); } void AggressorOscSection::setDensity(double Density) { osc1.setNumVoices((long) Density); } void AggressorOscSection::setDetuneStart(double DetuneStart) { detuneRamp.setStart(DetuneStart); } void AggressorOscSection::setDetuneTime(double DetuneTime) { detuneRamp.setTime(0.001*DetuneTime); } void AggressorOscSection::setDetuneEnd(double DetuneEnd) { detuneRamp.setEnd(DetuneEnd); } void AggressorOscSection::setDetuneRatio(double DetuneRatio) { osc1.setDetuneRatio(DetuneRatio); } void AggressorOscSection::setDetunePhaseSpread(double DetunePhaseSpread) { osc1.setDetunePhaseSpread(DetunePhaseSpread); } void AggressorOscSection::setDetuneSpacing(int DetuneSpacing) { osc1.setFreqSpacing(DetuneSpacing); } //modulation: void AggressorOscSection::setAmBy2Start(double AmBy2Start) { amBy2Start = AmBy2Start; amBy2Ramp.setStart(amBy2Start); } void AggressorOscSection::setAmBy2StartByVel(double AmBy2StartByVel) { amBy2StartByVel = AmBy2StartByVel; amBy2StartByVelAc = accent*amBy2StartByVel; } void AggressorOscSection::setAmBy2Time(double AmBy2Time) { amBy2Ramp.setTime(0.001*AmBy2Time); } void AggressorOscSection::setAmBy2End(double AmBy2End) { amBy2Ramp.setEnd(AmBy2End); } void AggressorOscSection::setAmBy3Start(double AmBy3Start) { amBy3Start = AmBy3Start; amBy3Ramp.setStart(amBy3Start); } void AggressorOscSection::setAmBy3StartByVel(double AmBy3StartByVel) { amBy3StartByVel = AmBy3StartByVel; amBy3StartByVelAc = accent*amBy3StartByVel; } void AggressorOscSection::setAmBy3Time(double AmBy3Time) { amBy3Ramp.setTime(0.001*AmBy3Time); } void AggressorOscSection::setAmBy3End(double AmBy3End) { amBy3Ramp.setEnd(AmBy3End); } void AggressorOscSection::setFmBy1Start(double FmBy1Start) { if(FmBy1Start>=0 && FmBy1Start<=100) fmBy1Start = 0.5*FmBy1Start; fmBy1Ramp.setStart(fmBy1Start); } void AggressorOscSection::setFmBy1StartByVel(double FmBy1StartByVel) { if(FmBy1StartByVel>=0 && FmBy1StartByVel<=100) fmBy1StartByVel = 0.01*FmBy1StartByVel; fmBy1StartByVelAc = accent*fmBy1StartByVel; } void AggressorOscSection::setFmBy1Time(double FmBy1Time) { fmBy1Ramp.setTime(0.001*FmBy1Time); } void AggressorOscSection::setFmBy1End(double FmBy1End) { if(FmBy1End>=0 && FmBy1End<=100) fmBy1Ramp.setEnd(0.5*FmBy1End); } void AggressorOscSection::setFmBy2Start(double FmBy2Start) { fmBy2Start = FmBy2Start; fmBy2Ramp.setStart(fmBy2Start); } void AggressorOscSection::setFmBy2StartByVel(double FmBy2StartByVel) { fmBy2StartByVel = FmBy2StartByVel; fmBy2StartByVelAc = accent*fmBy2StartByVel; } void AggressorOscSection::setFmBy2Time(double FmBy2Time) { fmBy2Ramp.setTime(0.001*FmBy2Time); } void AggressorOscSection::setFmBy2End(double FmBy2End) { fmBy2Ramp.setEnd(FmBy2End); //fm12Index = FmBy2End; } void AggressorOscSection::setFmBy3Start(double FmBy3Start) { fmBy3Start = FmBy3Start; fmBy3Ramp.setStart(fmBy3Start); } void AggressorOscSection::setFmBy3StartByVel(double FmBy3StartByVel) { fmBy3StartByVel = FmBy3StartByVel; fmBy3StartByVelAc = accent*fmBy3StartByVel; } void AggressorOscSection::setFmBy3Time(double FmBy3Time) { fmBy3Ramp.setTime(0.001*FmBy3Time); } void AggressorOscSection::setFmBy3End(double FmBy3End) { fmBy3Ramp.setEnd(FmBy3End); } void AggressorOscSection::setModulationMode(long ModulationMode) { if(ModulationMode==0) modulationsOff = true; else modulationsOff = false; modulationMode = ModulationMode; } void AggressorOscSection::setSyncMode(long SyncMode) { if(SyncMode==0) syncIsActive = false; else syncIsActive = true; syncMode = SyncMode; } //oscillator 2: void AggressorOscSection::setWaveForm2(long WaveForm2) { if(WaveForm2>0) osc2IsPlaying = true; else osc2IsPlaying = false; osc2.setWaveForm(WaveForm2); } void AggressorOscSection::setStartPhase2(double StartPhase2) { phase2 = StartPhase2; osc2.setStartPhase(StartPhase2); } void AggressorOscSection::setVol2Start(double Vol2Start) { vol2Start = Vol2Start; ampRamp2.setStart(DB2AMP(vol2Start)); } void AggressorOscSection::setVol2StartByVel(double Vol2StartByVel) { vol2StartByVel = Vol2StartByVel; vol2StartByVelAc = accent*vol2StartByVel; } void AggressorOscSection::setVol2Time(double Vol2Time) {ampRamp2.setTime(0.001*Vol2Time);} void AggressorOscSection::setVol2End(double Vol2End) {ampRamp2.setEnd(DB2AMP(Vol2End));} void AggressorOscSection::setPitch2Start(double Pitch2Start) { pitch2Start = Pitch2Start; freqRamp2.setStart(PITCHOFFSET2FREQFACTOR(pitch2Start)); } void AggressorOscSection::setPitch2StartByVel(double Pitch2StartByVel) { pitch2StartByVel = Pitch2StartByVel; pitch2StartByVelAc = accent*pitch2StartByVel; } void AggressorOscSection::setPitch2Time(double Pitch2Time) {freqRamp2.setTime(0.001*Pitch2Time);} void AggressorOscSection::setPitch2End(double Pitch2End) {freqRamp2.setEnd(PITCHOFFSET2FREQFACTOR(Pitch2End));} void AggressorOscSection::setOsc2Lpf(double Osc2Lpf) { flt2.setLpfCutoff(Osc2Lpf); } void AggressorOscSection::setOsc2Hpf(double Osc2Hpf) { flt2.setHpfCutoff(Osc2Hpf); } void AggressorOscSection::setOsc2Apf(double Osc2Apf) { flt2.setApfCutoff(Osc2Apf); } void AggressorOscSection::setPulseWidth2(double PulseWidth2) { if( (PulseWidth2>0.0) && (PulseWidth2<100.0) ) pulseWidth2 = 0.01*PulseWidth2; osc2.setPulseWidth(pulseWidth2); } void AggressorOscSection::setTuneCoarse2(double TuneCoarse2) { tuneCoarse2 = TuneCoarse2; tuneFactor2 = PITCHOFFSET2FREQFACTOR(tuneCoarse2 + 0.01*tuneFine2); } void AggressorOscSection::setTuneFine2(double TuneFine2) { tuneFine2 = TuneFine2; tuneFactor2 = PITCHOFFSET2FREQFACTOR(tuneCoarse2 + 0.01*tuneFine2); } //oscillator 3: void AggressorOscSection::setWaveForm3(long WaveForm3) { if(WaveForm3>0) osc3IsPlaying = true; else osc3IsPlaying = false; osc3.setWaveForm(WaveForm3); } void AggressorOscSection::setStartPhase3(double StartPhase3) { phase3 = StartPhase3; osc3.setStartPhase(StartPhase3); } void AggressorOscSection::setVol3Start(double Vol3Start) { vol3Start = Vol3Start; ampRamp3.setStart(DB2AMP(vol3Start)); } void AggressorOscSection::setVol3StartByVel(double Vol3StartByVel) { vol3StartByVel = Vol3StartByVel; vol3StartByVelAc = accent*vol3StartByVel; } void AggressorOscSection::setVol3Time(double Vol3Time) {ampRamp3.setTime(0.001*Vol3Time);} void AggressorOscSection::setVol3End(double Vol3End) {ampRamp3.setEnd(DB2AMP(Vol3End));} void AggressorOscSection::setPitch3Start(double Pitch3Start) { pitch3Start = Pitch3Start; freqRamp3.setStart(PITCHOFFSET2FREQFACTOR(pitch3Start)); } void AggressorOscSection::setPitch3StartByVel(double Pitch3StartByVel) { pitch3StartByVel = Pitch3StartByVel; pitch3StartByVelAc = accent*pitch3StartByVel; } void AggressorOscSection::setPitch3Time(double Pitch3Time) {freqRamp3.setTime(0.001*Pitch3Time);} void AggressorOscSection::setPitch3End(double Pitch3End) {freqRamp3.setEnd(PITCHOFFSET2FREQFACTOR(Pitch3End));} void AggressorOscSection::setOsc3Lpf(double Osc3Lpf) { flt3.setLpfCutoff(Osc3Lpf); } void AggressorOscSection::setOsc3Hpf(double Osc3Hpf) { flt3.setHpfCutoff(Osc3Hpf); } void AggressorOscSection::setOsc3Apf(double Osc3Apf) { flt3.setApfCutoff(Osc3Apf); } void AggressorOscSection::setPulseWidth3(double PulseWidth3) { if( (PulseWidth3>0.0) && (PulseWidth3<100.0) ) pulseWidth3 = 0.01*PulseWidth3; osc3.setPulseWidth(pulseWidth3); } void AggressorOscSection::setTuneCoarse3(double TuneCoarse3) { tuneCoarse3 = TuneCoarse3; tuneFactor3 = PITCHOFFSET2FREQFACTOR(tuneCoarse3 + 0.01*tuneFine3); } void AggressorOscSection::setTuneFine3(double TuneFine3) { tuneFine3 = TuneFine3; tuneFactor3 = PITCHOFFSET2FREQFACTOR(tuneCoarse3 + 0.01*tuneFine3); } //ringmodulation: void AggressorOscSection::setRm12Start(double Rm12Start) { rm12Start = Rm12Start; rm12Ramp.setStart(DB2AMP(rm12Start)); } void AggressorOscSection::setRm12StartByVel(double Rm12StartByVel) { rm12StartByVel = Rm12StartByVel; rm12StartByVelAc = accent*rm12StartByVel; } void AggressorOscSection::setRm12Time(double Rm12Time) {rm12Ramp.setTime(0.001*Rm12Time);} void AggressorOscSection::setRm12End(double Rm12End) {rm12Ramp.setEnd(DB2AMP(Rm12End));} void AggressorOscSection::setRm13Start(double Rm13Start) { rm13Start = Rm13Start; rm13Ramp.setStart(DB2AMP(rm13Start)); } void AggressorOscSection::setRm13StartByVel(double Rm13StartByVel) { rm13StartByVel = Rm13StartByVel; rm13StartByVelAc = accent*rm13StartByVel; } void AggressorOscSection::setRm13Time(double Rm13Time) {rm13Ramp.setTime(0.001*Rm13Time);} void AggressorOscSection::setRm13End(double Rm13End) {rm13Ramp.setEnd(DB2AMP(Rm13End));} void AggressorOscSection::setRm23Start(double Rm23Start) { rm23Start = Rm23Start; rm23Ramp.setStart(DB2AMP(rm23Start)); } void AggressorOscSection::setRm23StartByVel(double Rm23StartByVel) { rm23StartByVel = Rm23StartByVel; rm23StartByVelAc = accent*rm23StartByVel; } void AggressorOscSection::setRm23Time(double Rm23Time) {rm23Ramp.setTime(0.001*Rm23Time);} void AggressorOscSection::setRm23End(double Rm23End) {rm23Ramp.setEnd(DB2AMP(Rm23End));} //------------------------------------------------------------------------------------------------------- //event processing: //(re)triggers pitchEnvelope and set oscillator to the //new frequency: void AggressorOscSection::triggerNote(long NoteNumber, long Velocity, long Detune) { static double temp; currentNote = NoteNumber; currentPitch = NoteNumber + 0.01 * (double) Detune; targetPitch = currentPitch; currentFreq = PITCH2FREQ(currentPitch); targetFreq = currentFreq; //calculate the start values of the ramp-envelopes from the unscaled values, and the //velocity dependence (which is in itselt dependent from accent): //calculate start value of osc1's amplitude ramp and set it: temp = DB2AMP(vol1Start + (Velocity-64)*vol1StartByVelAc/63); ampRamp1.setStart(temp); //calculate start value of osc1's amplitude ramp and set it: temp = PITCHOFFSET2FREQFACTOR(pitch1Start + (Velocity-64)*pitch1StartByVelAc/63); freqRamp1.setStart(temp); //the same for osc2 and osc3: temp = DB2AMP(vol2Start + (Velocity-64)*vol2StartByVelAc/63); ampRamp2.setStart(temp); temp = PITCHOFFSET2FREQFACTOR(pitch2Start + (Velocity-64)*pitch2StartByVelAc/63); freqRamp2.setStart(temp); temp = DB2AMP(vol3Start + (Velocity-64)*vol3StartByVelAc/63); ampRamp3.setStart(temp); temp = PITCHOFFSET2FREQFACTOR(pitch3Start + (Velocity-64)*pitch3StartByVelAc/63); freqRamp3.setStart(temp); //the same for the AM- and FM-ramp-envelopes: temp = amBy2Start + (Velocity-64)*amBy2StartByVelAc/63; amBy2Ramp.setStart(temp); temp = amBy3Start + (Velocity-64)*amBy3StartByVelAc/63; amBy3Ramp.setStart(temp); /* velocity->feedback-fm has to be implemented here temp = fmBy1Start + (Velocity-64)*fmBy1StartByVelAc/63; fmBy1Ramp.setStart(temp); */ temp = fmBy2Start + (Velocity-64)*fmBy2StartByVelAc/63; fmBy2Ramp.setStart(temp); temp = fmBy3Start + (Velocity-64)*fmBy3StartByVelAc/63; fmBy3Ramp.setStart(temp); //the same for the ringmod-ramp-envelopes: temp = DB2AMP(rm12Start + (Velocity-64)*rm12StartByVelAc/63); rm12Ramp.setStart(temp); temp = DB2AMP(rm13Start + (Velocity-64)*rm13StartByVelAc/63); rm13Ramp.setStart(temp); temp = DB2AMP(rm23Start + (Velocity-64)*rm23StartByVelAc/63); rm23Ramp.setStart(temp); //trigger the ramp-envelops: ampRamp1.trigger(); ampRamp2.trigger(); ampRamp3.trigger(); freqRamp1.trigger(); freqRamp2.trigger(); freqRamp3.trigger(); rm12Ramp.trigger(); rm13Ramp.trigger(); rm23Ramp.trigger(); detuneRamp.trigger(); amBy2Ramp.trigger(); amBy3Ramp.trigger(); fmBy1Ramp.trigger(); fmBy2Ramp.trigger(); fmBy3Ramp.trigger(); } //slide to the new pitch witchout retriggering envelope and oscillator: void AggressorOscSection::slideToNote(long NoteNumber, long Velocity, long Detune) { currentNote = NoteNumber; targetPitch = NoteNumber + 0.01 * (double) Detune; targetFreq = PITCH2FREQ(targetPitch); double pitchDiff = targetPitch - currentPitch; if(slideSamples<1) //immediate slide { pitchIncPerSamp = 0; freqFacPerSamp = 1; currentFreq = targetFreq; currentPitch = targetPitch; osc1.setFreq(targetFreq); } else //scale frequency sample by sample (is done in getSample) { pitchIncPerSamp = pitchDiff/slideSamples; freqFacPerSamp = PITCHOFFSET2FREQFACTOR(pitchIncPerSamp); } //reset the sampleCounter: slideSampCount = 0; } void AggressorOscSection::noteOff(long NoteNumber) { currentNote = -1; } void AggressorOscSection::setPitchBend(double PitchBend) {freqBend = PITCHOFFSET2FREQFACTOR(PitchBend);} //------------------------------------------------------------------------------------------------------------ //audio processing: /* __forceinline sample AggressorOscSection::getSample() { static sample instFreq1, instFreq2, instFreq3; //frequency at this instant of time (for the 3 oscs) static sample ampFactor1, ampFactor2, ampFactor3; //factor for the amplitudes (comes from envelope and amplitude modulation) static sample vibFactor; static sample instPulseWidth1, instPulseWidth2, instPulseWidth3, pulseWidthOffset; static sample freqDeviation; //for FM in osc1 //the audio signals (at different satges of the signal chain): static sample osc1Out, osc2Out, osc3Out, osc1WithFilter, osc2WithFilter, osc3WithFilter, osc1WithFilterAndEnv, osc2WithFilterAndEnv, osc3WithFilterAndEnv; static sample rm12Out, rm13Out, rm23Out; rm12Out = 0; rm13Out = 0; rm23Out = 0; static sample outputSample; //update the frequency (slide): if(currentFreq!=targetFreq) { currentPitch += pitchIncPerSamp; currentFreq *= freqFacPerSamp; slideSampCount++; } //compensate for roundoff-error in frequency after slide: if(slideSampCount>=slideSamples) { currentFreq = targetFreq; currentPitch = targetPitch; } //calculate freq-factor for vibrato: //if(vibIsActive) vibFactor = PITCHOFFSET2FREQFACTOR(vibLfo.getSample()*vibDepth); //linear vibrato would be more efficient //else vibFactor = 1.0; //calculate an offset for the pulseWidths from the PWM-LFO: if(pwmIsActive) pulseWidthOffset = pwmDepth*pwmLfo.getSample(); else pulseWidthOffset = 0.0; if(osc2IsPlaying) { instFreq2 = currentFreq*freqRamp2.getSample(); //applies by the pitch ramp: instFreq2 *= tuneFactor2; //applies tuning-factor: instFreq2 *= vibFactor; //applies the vibrato instFreq2 *= freqBend; //applies pitchbend instPulseWidth2 = pulseWidth2 + pulseWidthOffset; //applies pwm to the static pulseWidth ampFactor2 = ampRamp2.getSample(); //calculates the output amplitude //set up the oscillator: osc2.freq = instFreq2; osc2.setPulseWidth(instPulseWidth2); //the function-call makes sure that pw is between 0.01 and 0.99 osc2.calcIncrements(); //calculate the oscillators output: //osc2Out = osc2.getSample(); osc2Out = osc2.getSampleAntiAliased(); //apply the static filter: osc2WithFilter = bpf2.getSample(osc2Out); //apply the amp-ramp: osc2WithFilterAndEnv = osc2WithFilter*ampFactor2; } else { osc2Out = 0.0; osc2WithFilter = 0.0; osc2WithFilterAndEnv = 0.0; } if(osc3IsPlaying) { instFreq3 = currentFreq*freqRamp3.getSample(); //applies by the pitch ramp: instFreq3 *= tuneFactor3; //applies tuning-factor: instFreq3 *= vibFactor; //applies the vibrato instFreq3 *= freqBend; //applies pitchbend instPulseWidth3 = pulseWidth3 + pulseWidthOffset; //applies pwm to the static pulseWidth ampFactor3 = ampRamp3.getSample(); //calculates the output amplitude //set up the oscillator: osc3.freq = instFreq3; osc3.setPulseWidth(instPulseWidth3); //the function-call makes sure that pw is between 0.01 and 0.99 osc3.calcIncrements(); //calculate the oscillators output: //osc3Out = osc3.getSample(); osc3Out = osc3.getSampleAntiAliased(); //apply the static filter: osc3WithFilter = bpf3.getSample(osc3Out); //apply the amp-ramp: osc3WithFilterAndEnv = osc3WithFilter*ampFactor3; } else { osc3Out = 0.0; osc3WithFilter = 0.0; osc3WithFilterAndEnv = 0.0; } if(osc1IsPlaying) { instFreq1 = currentFreq*freqRamp1.getSample(); //applies by the pitch ramp instFreq1 *= vibFactor; //applies the vibrato instFreq1 *= freqBend; //applies pitchbend instPulseWidth1 = pulseWidth1 + pulseWidthOffset; //applies pwm to the static pulseWidth ampFactor1 = ampRamp1.getSample(); //calculates the output amplitude //apply the modulations: if(modulationsOff) { //do nothing } else if(modulationMode==1) //the oscillator outputs directly modulate osc1 { //feedback-FM doesn't work yet //calculate frequency deviation of osc1 caused by osc1 (feedback-FM): //freqDeviation = fmBy1Ramp.getSample()*instFreq1; //use the previous output of osc1 (it keeps its value from one call to another because it is //declared as a static variable) to modulate osc's frequency: //instFreq1 += fmBy1Ramp.getSample() * osc1Out * sampleRate * osc1.tableLengthRec; //calculate frequency deviation of osc1 caused by osc2 : freqDeviation = fmBy2Ramp.getSample()*instFreq2; //use also the previous output of osc2 : instFreq1 += freqDeviation * osc2Out; //calculate frequency deviation of osc1 caused by osc3 : freqDeviation = fmBy3Ramp.getSample()*instFreq3; //use also the previous output of osc3 : instFreq1 += freqDeviation * osc3Out; //calculate the freq-deviation caused by feedback-fm: instFreq1 = instFreq1 + fmBy1Ramp.getSample()*instFreq1*osc1Out; //ranges from 0 to 2*instFreq1 //does not work this way -> pitch decreases when incresing amount //osc1.modulateIncrement(fmBy1Ramp.getSample()*osc1Out); //calculate amplitude factor for osc1 from its envelope and the amplitude modulation ramps: ampFactor1 = ampFactor1 * (1 + amBy2Ramp.getSample()*osc2Out); ampFactor1 = ampFactor1 * (1 + amBy3Ramp.getSample()*osc3Out); //calculate the ringmodulations output values: rm12Out = osc1Out*osc2Out*rm12Ramp.getSample(); rm13Out = osc1Out*osc3Out*rm13Ramp.getSample(); rm23Out = osc2Out*osc3Out*rm23Ramp.getSample(); } else if(modulationMode==2) { //calculate frequency deviation of osc1 caused by osc2 : freqDeviation = fmBy2Ramp.getSample()*instFreq2; //use also the previous output of osc2 : instFreq1 += freqDeviation * osc2WithFilter; //calculate frequency deviation of osc1 caused by osc3 : freqDeviation = fmBy3Ramp.getSample()*instFreq3; //use also the previous output of osc3 : instFreq1 += freqDeviation * osc3WithFilter; //calculate the freq-deviation caused by feedback-fm: instFreq1 = instFreq1 + fmBy1Ramp.getSample()*instFreq1*osc1WithFilter; //ranges from 0 to 2*instFreq1 //calculate amplitude factor for osc1 from its envelope and the amplitude modulation ramps: ampFactor1 = ampFactor1 * (1 + amBy2Ramp.getSample()*osc2WithFilter); ampFactor1 = ampFactor1 * (1 + amBy3Ramp.getSample()*osc3WithFilter); //calculate the ringmodulations output values: rm12Out = osc1WithFilter*osc2WithFilter*rm12Ramp.getSample(); rm13Out = osc1WithFilter*osc3WithFilter*rm13Ramp.getSample(); rm23Out = osc2WithFilter*osc3WithFilter*rm23Ramp.getSample(); } else if(modulationMode==3) { //calculate frequency deviation of osc1 caused by osc2 : freqDeviation = fmBy2Ramp.getSample()*instFreq2; //use also the previous output of osc2 : instFreq1 += freqDeviation * osc2WithFilterAndEnv; //calculate frequency deviation of osc1 caused by osc3 : freqDeviation = fmBy3Ramp.getSample()*instFreq3; //use also the previous output of osc3 : instFreq1 += freqDeviation * osc3WithFilterAndEnv; //calculate amplitude factor for osc1 from its envelope and the amplitude modulation ramps: ampFactor1 = ampFactor1 * (1 + amBy2Ramp.getSample()*osc2WithFilterAndEnv); ampFactor1 = ampFactor1 * (1 + amBy3Ramp.getSample()*osc3WithFilterAndEnv); //calculate the ringmodulations output values: rm12Out = osc1WithFilterAndEnv*osc2WithFilterAndEnv*rm12Ramp.getSample(); rm13Out = osc1WithFilterAndEnv*osc3WithFilterAndEnv*rm13Ramp.getSample(); rm23Out = osc2WithFilterAndEnv*osc3WithFilterAndEnv*rm23Ramp.getSample(); } //set up the oscillator: osc1.setDetune(detuneRamp.getSample()); osc1.setPulseWidth(instPulseWidth1); //the function-call makes sure that pw is between 0.01 and 0.99 osc1.setFreq(instFreq1); //optimize here! //osc1.calcIncrements(); //calculate the oscillators output: //osc1Out = osc1.getSample(); osc1Out = osc1.getSampleAntiAliased(); //apply the static filter: osc1WithFilter = bpf1.getSample(osc1Out); //apply the amp-ramp: osc1WithFilterAndEnv = osc1WithFilter*ampFactor1; } else { osc1Out = 0.0; osc1WithFilter = 0.0; osc1WithFilterAndEnv = 0.0; } //sync if sync is active: if(syncIsActive) { if( osc1.wraparoundOccurred && (syncMode==1 || syncMode==3) ) osc2.resetPhase(); if( osc1.wraparoundOccurred && (syncMode==2 || syncMode==3) ) osc3.resetPhase(); } //add the signals: outputSample = osc1WithFilterAndEnv + osc2WithFilterAndEnv + osc3WithFilterAndEnv + rm12Out + rm13Out + rm23Out; return outputSample; } */ //------------------------------------------------------------------------------------------------------------ //others: void AggressorOscSection::resetOscillators() { if( phase1 <= 359.99 ) osc1.resetPhase(); if( phase2 <= 359.99 ) osc2.resetPhase(); if( phase3 <= 359.99 ) osc3.resetPhase(); // lfo's are always re-trigeered: vibLfo.resetPhase(); pwmLfo.resetPhase(); }
27.849906
110
0.737301
RobinSchmidt
d81322e0d678c8f93fe9cd39d6121143c4e8b8ba
2,209
cpp
C++
code/RJObject/ConditionalPriors/BasicCircular.cpp
tripathi/DNestD3SB
400eb9ce73e789cdb3c6f791ef147c575ed3b2ea
[ "MIT" ]
null
null
null
code/RJObject/ConditionalPriors/BasicCircular.cpp
tripathi/DNestD3SB
400eb9ce73e789cdb3c6f791ef147c575ed3b2ea
[ "MIT" ]
null
null
null
code/RJObject/ConditionalPriors/BasicCircular.cpp
tripathi/DNestD3SB
400eb9ce73e789cdb3c6f791ef147c575ed3b2ea
[ "MIT" ]
null
null
null
#include "BasicCircular.h" #include "../../Utils.h" #include <cmath> using namespace DNest4; BasicCircular::BasicCircular(double x_min, double x_max, double y_min, double y_max, double mu_min, double mu_max) :x_min(x_min) ,x_max(x_max) ,y_min(y_min) ,y_max(y_max) ,size(sqrt((x_max - x_min)*(y_max - y_min))) ,mu_min(mu_min) ,mu_max(mu_max) { } void BasicCircular::from_prior(RNG& rng) { xc = x_min + (x_max - x_min)*rng.rand(); yc = y_min + (y_max - y_min)*rng.rand(); width = exp(log(1E-2*size) + log(1E3)*rng.rand()); mu = exp(log(mu_min) + log(mu_max/mu_min)*rng.rand()); } double BasicCircular::perturb_hyperparameters(RNG& rng) { double logH = 0.; int which = rng.rand_int(3); if(which == 0) { double scale = size*pow(10., 1.5 - 6.*rng.rand()); xc += scale*rng.randn(); yc += scale*rng.randn(); xc = DNest4::mod(xc - x_min, x_max - x_min) + x_min; yc = DNest4::mod(yc - y_min, y_max - y_min) + y_min; } else if(which == 1) { width = log(width); width += log(1E3)*rng.randh(); width = DNest4::mod(width - log(1E-2*size), log(1E3)) + log(1E-2*size); width = exp(width); } else if(which == 2) { mu = log(mu); mu += log(mu_max/mu_min)*rng.randh(); mu = DNest4::mod(mu - log(mu_min), log(mu_max/mu_min)) + log(mu_min); mu = exp(mu); } return logH; } double BasicCircular::log_pdf(const std::vector<double>& vec) const { if(vec[2] < 0.) return -1E300; double logp = 0.; double r = sqrt(pow(vec[0] - xc, 2) + pow(vec[1] - yc, 2)); logp += -log(r) - log(width) - r/width; logp += -log(mu) - vec[2]/mu; return logp; } void BasicCircular::from_uniform(std::vector<double>& vec) const { double r = -width*log(1. - vec[0]); double phi = 2.*M_PI*vec[1]; vec[0] = xc + r*cos(phi); vec[1] = yc + r*sin(phi); vec[2] = -mu*log(1. - vec[2]); } void BasicCircular::to_uniform(std::vector<double>& vec) const { double r = sqrt(pow(vec[0] - xc, 2) + pow(vec[1] - yc, 2)); double phi = atan2(vec[1] - yc, vec[0] - xc); if(phi < 0.) phi += 2.*M_PI; vec[0] = 1. - exp(-r/width); vec[1] = phi/(2.*M_PI); vec[2] = 1. - exp(-vec[2]/mu); } void BasicCircular::print(std::ostream& out) const { out<<xc<<' '<<yc<<' '<<width<<' '<<mu<<' '; }
21.656863
73
0.601177
tripathi
d8161240d9a11919311d33cf5afd9081d4138df2
3,710
hpp
C++
modules/core/gallery/include/nt2/gallery/functions/gallery_impl/invhilb.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
34
2017-05-19T18:10:17.000Z
2022-01-04T02:18:13.000Z
modules/core/gallery/include/nt2/gallery/functions/gallery_impl/invhilb.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
modules/core/gallery/include/nt2/gallery/functions/gallery_impl/invhilb.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
7
2017-12-02T12:59:17.000Z
2021-07-31T12:46:14.000Z
//============================================================================== // Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef NT2_GALLERY_FUNCTIONS_GALLERY_IMPL_INVHILB_HPP_INCLUDED #define NT2_GALLERY_FUNCTIONS_GALLERY_IMPL_INVHILB_HPP_INCLUDED #include <nt2/include/functions/rec.hpp> #include <nt2/include/functions/minusone.hpp> #include <nt2/include/functions/sqr.hpp> #include <nt2/include/functions/rif.hpp> #include <nt2/include/functions/cif.hpp> #include <nt2/include/functions/round2even.hpp> namespace nt2{ namespace ext { BOOST_DISPATCH_IMPLEMENT ( invhilb_, tag::cpu_ , (A0)(T) , (scalar_<integer_<A0> >) (target_< scalar_< unspecified_<T> > > ) ) { typedef typename boost::proto:: result_of::make_expr< nt2::tag::invhilb_ , container::domain , T, _2D >::type result_type; BOOST_FORCEINLINE result_type operator()(A0 a0,T const& tgt) const { return boost::proto:: make_expr < nt2::tag::invhilb_ , container::domain >( tgt, _2D(a0,a0) ); } }; BOOST_DISPATCH_IMPLEMENT ( invhilb_, tag::cpu_ , (A0) , (scalar_<integer_<A0> >) ) { typedef typename boost::proto:: result_of::make_expr< nt2::tag::invhilb_ , container::domain , meta::as_<double> , _2D >::type result_type; BOOST_FORCEINLINE result_type operator()(A0 a0) const { return boost::proto:: make_expr < nt2::tag::invhilb_ , container::domain >( meta::as_<double>(), _2D(a0,a0) ); } }; BOOST_DISPATCH_IMPLEMENT ( run_assign_, tag::cpu_ , (A0)(A1)(N) , ((ast_<A0, nt2::container::domain>)) ((node_<A1,nt2::tag::invhilb_,N,nt2::container::domain>)) ) { typedef A0& result_type; typedef typename A0::value_type value_type; result_type operator()(A0& out, const A1& in) const { _2D sz = boost::proto::value(boost::proto::child_c<1>(in)); out.resize(sz); value_type n = sz[0]; value_type p = n; value_type r = nt2::sqr(p); out(1, 1) = r; for(std::size_t j = 2; j <= n; ++j) { r = -((n-j+1)*r*(n+j-1))/nt2::sqr(j-1); out(1,j) = r/j; out(j,1) = out(1, j); } for(std::size_t i = 2; i <= n; ++i) { p = ((n-i+1)*p*(n+i-1))/nt2::sqr(i-1); r = nt2::sqr(p); out(i,i) = r/(2*i-1); for(std::size_t j = i+1; j <= n; ++j) { r = -((n-j+1)*r*(n+j-1))/nt2::sqr(j-1); out(i,j) = r/(i+j-1); out(j,i) = out(i, j); } } return out = nt2::round2even(out); } }; } } #endif
33.423423
87
0.437197
psiha
d81b16346a72dceed10f671c098d126f6f86c10c
221
hpp
C++
include/jln/mp.hpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
9
2020-07-04T16:46:13.000Z
2022-01-09T21:59:31.000Z
include/jln/mp.hpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
null
null
null
include/jln/mp.hpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
1
2021-05-23T13:37:40.000Z
2021-05-23T13:37:40.000Z
#pragma once #include <jln/mp/algorithm.hpp> #include <jln/mp/error.hpp> #include <jln/mp/functional.hpp> #include <jln/mp/list.hpp> #include <jln/mp/number.hpp> #include <jln/mp/utility.hpp> #include <jln/mp/value.hpp>
22.1
32
0.728507
jonathanpoelen
d81bef6500dc6aedb5992dca6635cb3536756727
3,113
cpp
C++
Assets/Plugins/Windows/RefreshRateHelper~/RefreshRateHelper/Source.cpp
Unity-Technologies/FrameSmoothnessTest
20dc8e469ec31fde7fe3a3aefe001ae2c5676a2d
[ "MIT" ]
5
2020-08-25T01:55:20.000Z
2022-02-20T21:44:55.000Z
Assets/Plugins/Windows/RefreshRateHelper~/RefreshRateHelper/Source.cpp
Unity-Technologies/FramerateSmoothnessTest
20dc8e469ec31fde7fe3a3aefe001ae2c5676a2d
[ "MIT" ]
null
null
null
Assets/Plugins/Windows/RefreshRateHelper~/RefreshRateHelper/Source.cpp
Unity-Technologies/FramerateSmoothnessTest
20dc8e469ec31fde7fe3a3aefe001ae2c5676a2d
[ "MIT" ]
null
null
null
#include <utility> #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include <windows.h> #include <d3d11.h> #include <dxgi.h> #include <wrl.h> using Microsoft::WRL::ComPtr; static ComPtr<IDXGIFactory> s_DXGIFactory; static ComPtr<ID3D11Device> s_D3D11Device; static ComPtr<IDXGIOutput> s_CachedOutput; extern "C" __declspec(dllexport) HRESULT GetCurrentRefreshRate(int* outNumerator, int* outDenominator) { auto monitor = MonitorFromWindow(GetActiveWindow(), MONITOR_DEFAULTTONEAREST); if (monitor == nullptr) MonitorFromWindow(GetActiveWindow(), MONITOR_DEFAULTTOPRIMARY); bool matches = true; if (s_CachedOutput != nullptr) { DXGI_OUTPUT_DESC outputDesc; auto hr = s_CachedOutput->GetDesc(&outputDesc); if (FAILED(hr)) return hr; if (outputDesc.Monitor != monitor) s_CachedOutput = nullptr; } if (s_CachedOutput == nullptr) { if (s_D3D11Device == nullptr) { ComPtr<ID3D11Device> d3d11Device; D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0 }; auto hr = D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, 0, featureLevels, ARRAYSIZE(featureLevels), D3D11_SDK_VERSION, &d3d11Device, nullptr, nullptr); if (FAILED(hr)) return hr; ComPtr<IDXGIDevice> dxgiDevice; hr = d3d11Device.As(&dxgiDevice); if (FAILED(hr)) return hr; ComPtr<IDXGIAdapter> dxgiAdapter; hr = dxgiDevice->GetAdapter(&dxgiAdapter); if (FAILED(hr)) return hr; hr = dxgiAdapter->GetParent(__uuidof(s_DXGIFactory), &s_DXGIFactory); if (FAILED(hr)) return hr; s_D3D11Device = std::move(d3d11Device); } HRESULT hr = DXGI_ERROR_NOT_FOUND; ComPtr<IDXGIAdapter> adapter; for (UINT i = 0; s_CachedOutput == nullptr && SUCCEEDED(hr = s_DXGIFactory->EnumAdapters(i, &adapter)); i++) { ComPtr<IDXGIOutput> output; for (UINT j = 0; SUCCEEDED(hr = adapter->EnumOutputs(j, &output)); j++) { DXGI_OUTPUT_DESC outputDesc; hr = output->GetDesc(&outputDesc); if (FAILED(hr)) continue; if (outputDesc.Monitor == monitor) { s_CachedOutput = std::move(output); break; } } } if (s_CachedOutput == nullptr) { if (FAILED(hr)) return hr; return DXGI_ERROR_NOT_FOUND; } } DXGI_MODE_DESC modeToMatch = {}; DXGI_MODE_DESC currentMode; auto hr = s_CachedOutput->FindClosestMatchingMode(&modeToMatch, &currentMode, s_D3D11Device.Get()); if (FAILED(hr)) return hr; *outNumerator = currentMode.RefreshRate.Numerator; *outDenominator = currentMode.RefreshRate.Denominator; return S_OK; }
30.223301
179
0.594925
Unity-Technologies
d81e696d806073560d7545b44687dfc400d1ce63
1,874
cpp
C++
src/ping_pong.cpp
duclos-cavalcanti/OpenMPI-Tutorial
5a1adeac3e0aaf9eae3e478b8479e5ddcdf08055
[ "MIT" ]
null
null
null
src/ping_pong.cpp
duclos-cavalcanti/OpenMPI-Tutorial
5a1adeac3e0aaf9eae3e478b8479e5ddcdf08055
[ "MIT" ]
null
null
null
src/ping_pong.cpp
duclos-cavalcanti/OpenMPI-Tutorial
5a1adeac3e0aaf9eae3e478b8479e5ddcdf08055
[ "MIT" ]
null
null
null
// Author: Wes Kendall // Copyright 2011 www.mpitutorial.com // This code is provided freely with the tutorials on mpitutorial.com. Feel // free to modify it for your own use. Any distribution of the code must // either provide a link to www.mpitutorial.com or keep this header intact. // // Ping pong example with MPI_Send and MPI_Recv. Two processes ping pong a // number back and forth, incrementing it until it reaches a given value. // #include <iostream> #include <mpi.h> int main(int argc, char* argv[]) { const int PING_PONG_LIMIT = 5; // Initialize the MPI environment MPI_Init(&argc, &argv); // Find out rank and size int world_rank, world_size; MPI_Comm_rank(MPI_COMM_WORLD, &world_rank); MPI_Comm_size(MPI_COMM_WORLD, &world_size); // We are assuming exactly 2 processors for this task if (world_size != 2) { std::cerr << "World size must be two for " << argv[0] << std::endl; MPI_Abort(MPI_COMM_WORLD, 1); } int ping_pong_count = 0; int partner_rank = (world_rank + 1) % 2; while (ping_pong_count < PING_PONG_LIMIT) { if (world_rank == ping_pong_count % 2) { // Increment the ping pong count before you send it ping_pong_count++; MPI_Send(&ping_pong_count, 1, MPI_INT, partner_rank, 0, MPI_COMM_WORLD); std::cout << "Processor " << world_rank << " sent ++ping_pong_count " << ping_pong_count << " to " << partner_rank << std::endl; } else { MPI_Recv(&ping_pong_count, 1, MPI_INT, partner_rank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); std::cout << "Processor " << world_rank << " received ping_pong_count " << ping_pong_count << " from " << partner_rank << std::endl; } } // Finalize the MPI environment. No more MPI calls can be made after this MPI_Finalize(); return 0; }
27.970149
78
0.65635
duclos-cavalcanti
d820d5cb1a2fd4de7e367b5ff1c59aee6347e408
3,835
hh
C++
source/include/Algorithm/Calorimetry/HoughTransformAlgorithm.hh
rete/Baboon
e5b2cfe6b9e5b5a41c2c68feda84b8df109eb086
[ "FSFAP" ]
null
null
null
source/include/Algorithm/Calorimetry/HoughTransformAlgorithm.hh
rete/Baboon
e5b2cfe6b9e5b5a41c2c68feda84b8df109eb086
[ "FSFAP" ]
null
null
null
source/include/Algorithm/Calorimetry/HoughTransformAlgorithm.hh
rete/Baboon
e5b2cfe6b9e5b5a41c2c68feda84b8df109eb086
[ "FSFAP" ]
null
null
null
/* * * HoughTransformAlgorithm.hh header template generated by fclass * Creation date : Thu Mar 14 21:55:13 2013 * Copyright (c) CNRS / IPNL * All Right Reserved. * * Use and copying of these libraries and preparation of derivative works * based upon these libraries are permitted. Any copy of these libraries * must include this copyright notice. * * Written by : R. Eté */ #ifndef HOUGHTRANSFORMALGORITHM_HH #define HOUGHTRANSFORMALGORITHM_HH #include <iostream> #include <string> #include <cstdlib> #include <cmath> #include <numeric> #include <map> #include <vector> #include <utility> #include <algorithm> // sdhcal includes #include "Algorithm/AbstractAlgorithm.hh" #include "Objects/Cluster.hh" #include "Managers/ClusteringManager.hh" #include "Managers/TrackManager.hh" #include "Reconstruction/Tag.hh" #include "Utilities/ReturnValues.hh" #include "Reconstruction/Linear3DFit.hh" #include "TH2D.h" #include "TCanvas.h" #include "TGraph.h" namespace baboon { /*! * @brief Class HoughTransformAlgorithm. * Inherit from 'AbstractAlgorithm' base class. */ class HoughTransformAlgorithm : public AbstractAlgorithm { /*! * @brief Hough tag used in HoughTransformAlgorithm to tag candidate clusters */ enum HoughTag { fGood, fBad }; /*! * * @brief Cluster structure for Hough Transform algorithm. Allows to tag the clusters while processing * */ typedef struct { public : Cluster *cluster; std::vector<int> rhox; std::vector<int> rhoy; HoughTag tagx; HoughTag tagy; HoughTag finalTag; } HoughCluster; typedef std::vector<HoughCluster*> HoughClusterCollection; typedef struct { public : CaloHit *caloHit; std::vector<int> rhox; std::vector<int> rhoy; HoughTag tagx; HoughTag tagy; HoughTag finalTag; } HoughHit; typedef std::vector<HoughHit*> HoughHitCollection; /*! * * HoughPoint struct for Hough Transform Algorithm * */ typedef struct { CaloHit* caloHit; double theta; double rho; int pointID; } HoughPoint; typedef std::vector<HoughPoint*> HoughPointCollection; public : /*! * * @brief Default Constructor * */ HoughTransformAlgorithm(); /*! * * @brief Default Destructor * */ virtual ~HoughTransformAlgorithm(); protected : /*! * * @brief Initialize the algorithm, i.e by initializing specific variables * */ virtual Return Init(); /*! * * @brief Execute the algorithm * */ virtual Return Execute(); /*! * * @brief Finalize the algorithm * */ virtual Return End(); /*! * * @brief Allow to check if everything is well set in the algorithm before starting it * */ virtual Return CheckConsistency(); /*! * * @brief Delete the Hough parameter space ( 2D array ) * */ void DeleteHoughSpace(); /*! * * @brief Allocate the Hough parameter space ( 2D array ) * */ void AllocateHoughSpace(); // Algorithm parameters int thetaMax; int rMax; int clusterSizeLimit; int minimumBinning; int deltaPosMax; int trackSegmentMinimumSize; int maximumDistanceBetweenHitsInPlane; int maximumDistanceBetweenHitsForLayers; double maximumDistanceAllowedForHitsInTrack; int minimumNumberOfLayersForTrack; double normalizedChi2Limit; double chi2DifferenceLimit; int trackModel; int minHitOnTrack; double maxHitDistXY; double maxHitDistZ; int binningLevel; int baseBinning; // new hough transform double deltaThetaCluster; double deltaRhoCluster; int houghPointCollectionMinimumSize; int ** houghSpaceX; int ** houghSpaceY; }; } #endif // HOUGHTRANSFORMALGORITHM_HH
17.75463
104
0.669622
rete
d822717cd1dc1d8c6e13574b3a595fe5d256dca6
1,082
cpp
C++
platforms/gfg/0273_split_n_maximum_composite_number.cpp
idfumg/algorithms
06f85c5a1d07a965df44219b5a6bf0d43a129256
[ "MIT" ]
2
2020-09-17T09:04:00.000Z
2020-11-20T19:43:18.000Z
platforms/gfg/0273_split_n_maximum_composite_number.cpp
idfumg/algorithms
06f85c5a1d07a965df44219b5a6bf0d43a129256
[ "MIT" ]
null
null
null
platforms/gfg/0273_split_n_maximum_composite_number.cpp
idfumg/algorithms
06f85c5a1d07a965df44219b5a6bf0d43a129256
[ "MIT" ]
null
null
null
#include "../../template.hpp" bool IsPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 or n % 3 == 0) return false; for (int i = 5; i * i <= n; i += 6) { if (n % i == 0 or n % (i + 2) == 0) { return false; } } return true; } bool IsComposite(int n) { return not IsPrime(n); } int SplitIntoMaxCompositeNumbers(int n) { int i = 4, ans = 0; if (IsPrime(n)) { return 0; } while (n != 0) { if (not IsComposite(i)) { ++i; continue; } int count = n / i; if (n != count * i) { --count; } n -= count * i; ans += count; ++i; } return ans; } int main() { TimeMeasure _; cout << SplitIntoMaxCompositeNumbers(90) << '\n'; // 22 cout << SplitIntoMaxCompositeNumbers(10) << '\n'; // 2 cout << SplitIntoMaxCompositeNumbers(143) << '\n'; // 34 cout << SplitIntoMaxCompositeNumbers(11) << '\n'; // 2 cout << SplitIntoMaxCompositeNumbers(12) << '\n'; // 3 }
23.021277
60
0.470425
idfumg
d829a305b5cf67d1a528e2212a9ee3910ce0443b
1,485
cpp
C++
src/World/World.cpp
cristianglezm/AntFarm
df7551621ad6eda6dae43a2ede56222500be1ae1
[ "Apache-2.0" ]
null
null
null
src/World/World.cpp
cristianglezm/AntFarm
df7551621ad6eda6dae43a2ede56222500be1ae1
[ "Apache-2.0" ]
1
2016-03-13T10:55:21.000Z
2016-03-13T10:55:21.000Z
src/World/World.cpp
cristianglezm/AntFarm
df7551621ad6eda6dae43a2ede56222500be1ae1
[ "Apache-2.0" ]
null
null
null
#include <World/World.hpp> namespace ant{ World::World() : id(0) , eventQueue(std::make_shared<EventQueue>()) , entityManager(std::make_shared<EntityManager>()) , systemManager(std::make_unique<SystemManager>()){} World::World(int id) : id(id) , eventQueue(std::make_shared<EventQueue>()) , entityManager(std::make_shared<EntityManager>()) , systemManager(std::make_unique<SystemManager>()){} World::World(int id,std::shared_ptr<EntityManager> eM,std::unique_ptr<SystemManager> sM,std::shared_ptr<EventQueue> eQ) : id(id) , eventQueue(eQ) , entityManager(eM) , systemManager(std::move(sM)){} void World::setEntityManager(std::shared_ptr<EntityManager> eM){ entityManager = eM; systemManager->setEntityManager(entityManager); } void World::setSystemManager(std::unique_ptr<SystemManager> sM){ systemManager = std::move(sM); systemManager->setEntityManager(entityManager); systemManager->setEventQueue(eventQueue); } void World::setEventQueue(std::shared_ptr<EventQueue> eQ){ eventQueue = eQ; } void World::setGameEventDispatcher(std::shared_ptr<GameEventDispatcher> ged){ gameEventDispatcher = ged; } void World::setId(int id){ this->id = id; } void World::update(const sf::Time& dt){ systemManager->update(dt); } void World::render(sf::RenderWindow& win){ systemManager->render(win); } }
33.75
123
0.660606
cristianglezm
d82de41caf327f07caee8da2b0c2aba1f73b1fd8
2,256
cpp
C++
src/test/unit/services/sample/standalone_gqs_2390_test.cpp
sthagen/stan-dev-stan
38ab6922649f1cf35e66fa812fc28ce693cde345
[ "CC-BY-3.0", "BSD-3-Clause" ]
2,171
2015-01-09T01:41:18.000Z
2022-03-30T12:00:36.000Z
src/test/unit/services/sample/standalone_gqs_2390_test.cpp
sthagen/stan-dev-stan
38ab6922649f1cf35e66fa812fc28ce693cde345
[ "CC-BY-3.0", "BSD-3-Clause" ]
1,885
2015-01-02T13:33:12.000Z
2022-03-31T23:00:39.000Z
src/test/unit/services/sample/standalone_gqs_2390_test.cpp
sthagen/stan-dev-stan
38ab6922649f1cf35e66fa812fc28ce693cde345
[ "CC-BY-3.0", "BSD-3-Clause" ]
393
2015-01-16T22:42:33.000Z
2022-03-29T23:21:16.000Z
#include <stan/services/error_codes.hpp> #include <stan/services/sample/standalone_gqs.hpp> #include <stan/callbacks/stream_writer.hpp> #include <stan/callbacks/stream_logger.hpp> #include <stan/io/empty_var_context.hpp> #include <stan/io/stan_csv_reader.hpp> #include <test/test-models/good/services/bug_2390_gq.hpp> #include <test/unit/services/instrumented_callbacks.hpp> #include <test/unit/util.hpp> #include <Eigen/Dense> #include <gtest/gtest.h> #include <iostream> #include <string> #include <vector> class ServicesStandaloneGQ4 : public ::testing::Test { public: ServicesStandaloneGQ4() : logger(logger_ss, logger_ss, logger_ss, logger_ss, logger_ss) {} void SetUp() { stan::io::empty_var_context context; model = new stan_model(context); } void TearDown() { delete model; } stan::test::unit::instrumented_interrupt interrupt; std::stringstream logger_ss; stan::callbacks::stream_logger logger; stan_model *model; }; TEST_F(ServicesStandaloneGQ4, genDraws_gq_test_vec_len_1) { stan::io::stan_csv multidim_csv; std::stringstream out; std::ifstream csv_stream; csv_stream.open( "src/test/test-models/good/services/bug_2390_fitted_params.csv"); multidim_csv = stan::io::stan_csv_reader::parse(csv_stream, &out); csv_stream.close(); EXPECT_EQ("b[1]", multidim_csv.header[7]); // model bug_2390_model has 1 param, vector[1] b; std::vector<std::string> param_names; std::vector<std::vector<size_t>> param_dimss; stan::services::get_model_parameters(*model, param_names, param_dimss); EXPECT_EQ(param_names.size(), 1); EXPECT_EQ(param_dimss.size(), 1); int total = 1; for (size_t i = 0; i < param_dimss[0].size(); ++i) { total *= param_dimss[0][i]; } EXPECT_EQ(total, 1); std::stringstream sample_ss; stan::callbacks::stream_writer sample_writer(sample_ss, ""); int return_code = stan::services::standalone_generate( *model, multidim_csv.samples.middleCols<1>(7), 12345, interrupt, logger, sample_writer); EXPECT_EQ(return_code, stan::services::error_codes::OK); EXPECT_EQ(count_matches("y_est", sample_ss.str()), 5); EXPECT_EQ(count_matches("\n", sample_ss.str()), 1001); match_csv_columns(multidim_csv.samples, sample_ss.str(), 1000, 0, 6); }
33.671642
78
0.73227
sthagen
d82fb1ca4994fdfb13d600c1456309668abfb87b
103
cpp
C++
src/examples/06_module/01_bank/customer.cpp
acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-Grecia1813
f356c1ed8f6e75b9e9d6164747a5c199bead8c95
[ "MIT" ]
null
null
null
src/examples/06_module/01_bank/customer.cpp
acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-Grecia1813
f356c1ed8f6e75b9e9d6164747a5c199bead8c95
[ "MIT" ]
null
null
null
src/examples/06_module/01_bank/customer.cpp
acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-Grecia1813
f356c1ed8f6e75b9e9d6164747a5c199bead8c95
[ "MIT" ]
null
null
null
//customer.cpp #include "customer.h" Demo::Demo() { cout << "2. Now the constructor is running\n"; }
14.714286
48
0.650485
acc-cosc-1337-fall-2020
d8320c7f5cf41634ca06cd96ca2c66a1a18d8df4
24,939
cpp
C++
pljit/parser/Parser.cpp
cakebytheoceanLuo/pl0-jit-compiler
033c6033a8b1274531e92d43141a8c43b7100a7f
[ "MIT" ]
null
null
null
pljit/parser/Parser.cpp
cakebytheoceanLuo/pl0-jit-compiler
033c6033a8b1274531e92d43141a8c43b7100a7f
[ "MIT" ]
null
null
null
pljit/parser/Parser.cpp
cakebytheoceanLuo/pl0-jit-compiler
033c6033a8b1274531e92d43141a8c43b7100a7f
[ "MIT" ]
null
null
null
//--------------------------------------------------------------------------- #include "parser/Parser.hpp" #include <cassert> #include <vector> #include <memory> //--------------------------------------------------------------------------- namespace pljit { //--------------------------------------------------------------------------- Parser::Parser(const SourceCodeManagement& source_code_management) : lexer(source_code_management) {} //--------------------------------------------------------------------------- SourceCodeReference Parser::BuildChildrenSourceCodeReference(const std::vector<std::unique_ptr<ParseTreeNode>>& children) { const size_t length = [&children] { size_t l = 0; for (const std::unique_ptr<ParseTreeNode>& child: children) { l += child->GetSourceCodeReference().GetLength(); } return l; } (); return SourceCodeReference(children[0]->GetSourceCodeReference().GetLineNumber(), children[0]->GetSourceCodeReference().GetCharOffset(), length, lexer.GetSourceCodeManagement()); } //--------------------------------------------------------------------------- std::unique_ptr<NonTerminalParseTreeNode> Parser::ErrorHandling(std::string_view str, bool in_declaration) { assert(!declaration_error); if (in_declaration) { declaration_error = true; } current_token_ptr->GetSourceCodeReference().PrintContext(str); return nullptr; } //--------------------------------------------------------------------------- std::unique_ptr<NonTerminalParseTreeNode> Parser::ParseFunctionDefinition() { assert(!current_token_ptr && "The ultimate starting point of building the parse tree."); current_token_ptr = std::make_unique<Token>(lexer.ProduceNextToken()); assert(current_token_ptr->GetType() != Token::Type::ERROR); assert(current_token_ptr->GetType() != Token::Type::EOT); // A vector storing parse tree nodes. std::vector<std::unique_ptr<ParseTreeNode>> parse_tree_nodes; if (current_token_ptr->GetType() == Token::Type::PARAM) { // Case for *[ parameter-declarations ]* inside of a *function-definition*, which is optional. std::unique_ptr<ParseTreeNode> parameter_declarations = ParseParameterDeclarations(); if (declaration_error) { return nullptr; } assert(parameter_declarations && " A valid pointer without any declaration error."); parse_tree_nodes.emplace_back(std::move(parameter_declarations)); } if (current_token_ptr->GetType() == Token::Type::VAR) { // Case for *[ variable-declarations ]* inside of a *function-definition*, which is optional. std::unique_ptr<ParseTreeNode> variable_declarations = ParseVariableDeclarations(); if (declaration_error) { return nullptr; } assert(variable_declarations && " A valid pointer without any declaration error."); parse_tree_nodes.emplace_back(std::move(variable_declarations)); } if (current_token_ptr->GetType() == Token::Type::CONST) { // Case for *[ constant-declarations ]* inside of a *function-definition*, which is optional. std::unique_ptr<ParseTreeNode> constant_declarations = ParseConstantDeclarations(); if (declaration_error) { return nullptr; } assert(constant_declarations && " A valid pointer without any declaration error."); parse_tree_nodes.emplace_back(std::move(constant_declarations)); } // Case for *compound-statement* inside of a *function-definition*. std::unique_ptr<ParseTreeNode> compound_statement = ParseCompoundStatement(); if (!compound_statement) { return nullptr; } parse_tree_nodes.emplace_back(std::move(compound_statement)); // Case for *"."* inside of a *function-definition*. if (current_token_ptr->GetType() != Token::Type::DOT) { return ErrorHandling("Expected \".\" DOT", true); } parse_tree_nodes.emplace_back(std::make_unique<GenericTokenParseTreeNode>(current_token_ptr->GetSourceCodeReference())); // "." return std::make_unique<NonTerminalParseTreeNode>(BuildChildrenSourceCodeReference(parse_tree_nodes), ParseTreeNode::Type::FunctionDefinition, std::move(parse_tree_nodes)); } //--------------------------------------------------------------------------- std::unique_ptr<ParseTreeNode> Parser::ParseParameterDeclarations() { assert(current_token_ptr->GetType() == Token::Type::PARAM && " Pre-condition of calling this function: PARAM."); std::vector<std::unique_ptr<ParseTreeNode>> children; children.emplace_back(std::make_unique<GenericTokenParseTreeNode>(current_token_ptr->GetSourceCodeReference())); // "PARAM" // Let lexer produce the next token. current_token_ptr = std::make_unique<Token>(lexer.ProduceNextToken()); // Case for *declarator-list* inside of a *parameter-declarations*. if (current_token_ptr->GetType() != Token::Type::IDENTIFIER) { return ErrorHandling("Expected the first identifier", true); } std::unique_ptr<ParseTreeNode> declarator_list = ParseDeclaratorList(); if (!declarator_list) { return nullptr; } children.emplace_back(std::move(declarator_list)); assert(children.back()->GetType() == ParseTreeNode::Type::DeclaratorList && !(static_cast<NonTerminalParseTreeNode*>(children.back().get())->GetChildren().empty()) && " At least one IDENTIFIER inside of *declarator-list*. "); if (current_token_ptr->GetType() != Token::Type::SEMICOLON) { return ErrorHandling("Expected a \";\" SEMICOLON", true); } children.emplace_back(std::make_unique<GenericTokenParseTreeNode>(current_token_ptr->GetSourceCodeReference())); // SEMICOLON ";" // Let lexer produce the next token. current_token_ptr = std::make_unique<Token>(lexer.ProduceNextToken()); return std::make_unique<NonTerminalParseTreeNode>(BuildChildrenSourceCodeReference(children), ParseTreeNode::Type::ParameterDeclarations, std::move(children)); } //--------------------------------------------------------------------------- std::unique_ptr<ParseTreeNode> Parser::ParseVariableDeclarations() { assert(current_token_ptr->GetType() == Token::Type::VAR && " Pre-condition of calling this function: VAR."); std::vector<std::unique_ptr<ParseTreeNode>> children; children.emplace_back(std::make_unique<GenericTokenParseTreeNode>(current_token_ptr->GetSourceCodeReference())); // "VAR" // Let lexer produce the next token. current_token_ptr = std::make_unique<Token>(lexer.ProduceNextToken()); // Case for *declarator-list* inside of a *variable-declarations*. if (current_token_ptr->GetType() != Token::Type::IDENTIFIER) { return ErrorHandling("Expected the first identifier", true); } std::unique_ptr<ParseTreeNode> declarator_list = ParseDeclaratorList(); if (!declarator_list) { return nullptr; } children.emplace_back(std::move(declarator_list)); assert(children.back()->GetType() == ParseTreeNode::Type::DeclaratorList && !(static_cast<NonTerminalParseTreeNode*>(children.back().get())->GetChildren().empty()) && " At least one IDENTIFIER inside of *declarator-list*. "); if (current_token_ptr->GetType() != Token::Type::SEMICOLON) { return ErrorHandling("Expected a \";\" SEMICOLON"); } children.emplace_back(std::make_unique<GenericTokenParseTreeNode>(current_token_ptr->GetSourceCodeReference())); // SEMICOLON ";" // Let lexer produce the next token. current_token_ptr = std::make_unique<Token>(lexer.ProduceNextToken()); return std::make_unique<NonTerminalParseTreeNode>(BuildChildrenSourceCodeReference(children), ParseTreeNode::Type::VariableDeclarations, std::move(children)); } //--------------------------------------------------------------------------- std::unique_ptr<ParseTreeNode> Parser::ParseConstantDeclarations() { assert(current_token_ptr->GetType() == Token::Type::CONST && " Pre-condition of calling this function: CONST."); std::vector<std::unique_ptr<ParseTreeNode>> children; children.emplace_back(std::make_unique<GenericTokenParseTreeNode>(current_token_ptr->GetSourceCodeReference())); // "CONST" // Let lexer produce the next token. current_token_ptr = std::make_unique<Token>(lexer.ProduceNextToken()); if (current_token_ptr->GetType() != Token::Type::IDENTIFIER) { return ErrorHandling("Expected the first identifier", true); } std::unique_ptr<ParseTreeNode> declarator_list = ParseInitDeclaratorList(); if (!declarator_list) { return nullptr; } children.emplace_back(std::move(declarator_list)); assert(children.back()->GetType() == ParseTreeNode::Type::InitDeclaratorList && !(static_cast<NonTerminalParseTreeNode*>(children.back().get())->GetChildren().empty()) && " At least one IDENTIFIER inside of *declarator-list*. "); if (current_token_ptr->GetType() != Token::Type::SEMICOLON) { return ErrorHandling("Expected a \";\" SEMICOLON"); } children.emplace_back(std::make_unique<GenericTokenParseTreeNode>(current_token_ptr->GetSourceCodeReference())); // SEMICOLON ";" // Let lexer produce the next token. current_token_ptr = std::make_unique<Token>(lexer.ProduceNextToken()); return std::make_unique<NonTerminalParseTreeNode>(BuildChildrenSourceCodeReference(children), ParseTreeNode::Type::ConstantDeclarations, std::move(children)); } //--------------------------------------------------------------------------- std::unique_ptr<ParseTreeNode> Parser::ParseDeclaratorList() { assert(current_token_ptr->GetType() == Token::Type::IDENTIFIER && " Pre-condition of calling this function: IDENTIFIER."); std::vector<std::unique_ptr<ParseTreeNode>> children; children.emplace_back(std::make_unique<IdentifierParseTreeNode>(current_token_ptr->GetSourceCodeReference())); // The repetition part inside of a declarator-list: { "," identifier }. while ( (current_token_ptr = std::make_unique<Token>(lexer.ProduceNextToken())) /* Let the lexer produce the next token. */ && current_token_ptr->GetType() == Token::Type::COMMA) { children.emplace_back(std::make_unique<GenericTokenParseTreeNode>(current_token_ptr->GetSourceCodeReference())); // "COMMA" // Let lexer produce the next token. current_token_ptr = std::make_unique<Token>(lexer.ProduceNextToken()); if (current_token_ptr->GetType() != Token::Type::IDENTIFIER) { return ErrorHandling("Expected identifier", true); } children.emplace_back(std::make_unique<IdentifierParseTreeNode>(current_token_ptr->GetSourceCodeReference())); // IDENTIFIER } assert(current_token_ptr && current_token_ptr->GetType() != Token::Type::COMMA && " Post-condition of calling this function: not COMMA."); return std::make_unique<NonTerminalParseTreeNode>(BuildChildrenSourceCodeReference(children), ParseTreeNode::Type::DeclaratorList, std::move(children)); } //--------------------------------------------------------------------------- std::unique_ptr<ParseTreeNode> Parser::ParseInitDeclaratorList() { assert(current_token_ptr->GetType() == Token::Type::IDENTIFIER && " Pre-condition of calling this function: IDENTIFIER."); std::unique_ptr<ParseTreeNode> init_declarator = ParseInitDeclarator(); // Should advance to next token after this function call. if (!init_declarator) { return nullptr; } std::vector<std::unique_ptr<ParseTreeNode>> children; children.emplace_back(std::move(init_declarator)); // The repetition part inside of a init-declarator-list: { "," init-declarator }. while (current_token_ptr && current_token_ptr->GetType() == Token::Type::COMMA) { children.emplace_back(std::make_unique<GenericTokenParseTreeNode>(current_token_ptr->GetSourceCodeReference())); // "COMMA" // Let lexer produce the next token. current_token_ptr = std::make_unique<Token>(lexer.ProduceNextToken()); if (!current_token_ptr) { return nullptr; } init_declarator = ParseInitDeclarator(); if (!init_declarator) { return nullptr; } children.emplace_back(std::move(init_declarator)); } assert(current_token_ptr && current_token_ptr->GetType() != Token::Type::COMMA && " Post-condition of calling this function: not COMMA."); return std::make_unique<NonTerminalParseTreeNode>(BuildChildrenSourceCodeReference(children), ParseTreeNode::Type::InitDeclaratorList, std::move(children)); } //--------------------------------------------------------------------------- std::unique_ptr<ParseTreeNode> Parser::ParseInitDeclarator() { assert(current_token_ptr->GetType() == Token::Type::IDENTIFIER && " Pre-condition of calling this function: IDENTIFIER."); std::vector<std::unique_ptr<ParseTreeNode>> children; children.emplace_back(std::make_unique<IdentifierParseTreeNode>(current_token_ptr->GetSourceCodeReference())); // IDENTIFIER // Let lexer produce the next token. current_token_ptr = std::make_unique<Token>(lexer.ProduceNextToken()); if (current_token_ptr->GetType() != Token::Type::EQUAL) { return ErrorHandling("Expected \"=\" equal sign", true); } children.emplace_back(std::make_unique<GenericTokenParseTreeNode>(current_token_ptr->GetSourceCodeReference())); // "=" // Let lexer produce the next token. current_token_ptr = std::make_unique<Token>(lexer.ProduceNextToken()); if (current_token_ptr->GetType() != Token::Type::LITERAL) { return ErrorHandling("Expected literal", true); } children.emplace_back(std::make_unique<LiteralParseTreeNode>(current_token_ptr->GetSourceCodeReference(), std::stoll(std::string(current_token_ptr->GetSourceCodeReference().GetSourceCode())))); // Let lexer produce the next token. current_token_ptr = std::make_unique<Token>(lexer.ProduceNextToken()); return std::make_unique<NonTerminalParseTreeNode>(BuildChildrenSourceCodeReference(children), ParseTreeNode::Type::InitDeclarator, std::move(children)); } //--------------------------------------------------------------------------- std::unique_ptr<ParseTreeNode> Parser::ParseCompoundStatement() { if (current_token_ptr->GetType() != Token::Type::BEGIN) { return ErrorHandling("Expected \"BEGIN\""); } std::vector<std::unique_ptr<ParseTreeNode>> children; children.emplace_back(std::make_unique<GenericTokenParseTreeNode>(current_token_ptr->GetSourceCodeReference())); // "BEGIN" // Let lexer produce the next token. current_token_ptr = std::make_unique<Token>(lexer.ProduceNextToken()); std::unique_ptr<ParseTreeNode> statement_list = ParseStatementList(); // Should advance to next token after this function call. if (!statement_list) { return nullptr; } children.emplace_back(std::move(statement_list)); if (current_token_ptr->GetType() != Token::Type::END) { return ErrorHandling("Expected \"END\""); } children.emplace_back(std::make_unique<GenericTokenParseTreeNode>(current_token_ptr->GetSourceCodeReference())); // "END" // Let lexer produce the next token. current_token_ptr = std::make_unique<Token>(lexer.ProduceNextToken()); return std::make_unique<NonTerminalParseTreeNode>(BuildChildrenSourceCodeReference(children), ParseTreeNode::Type::CompoundStatement, std::move(children)); } //--------------------------------------------------------------------------- std::unique_ptr<ParseTreeNode> Parser::ParseStatementList() { std::unique_ptr<ParseTreeNode> statement = ParseStatement(); // Should advance to next token after this function call. if (!statement) { return nullptr; } std::vector<std::unique_ptr<ParseTreeNode>> children; children.emplace_back(std::move(statement)); // The repetition part inside of a statement-list : { ";" statement }. while (current_token_ptr->GetType() == Token::Type::SEMICOLON) { children.emplace_back(std::make_unique<GenericTokenParseTreeNode>(current_token_ptr->GetSourceCodeReference())); // SEMICOLON ";" current_token_ptr = std::make_unique<Token>(lexer.ProduceNextToken()); statement = ParseStatement(); if (!statement) { return nullptr; } children.emplace_back(std::move(statement)); } return std::make_unique<NonTerminalParseTreeNode>(BuildChildrenSourceCodeReference(children), ParseTreeNode::Type::StatementList, std::move(children)); } //--------------------------------------------------------------------------- std::unique_ptr<ParseTreeNode> Parser::ParseStatement() { std::vector<std::unique_ptr<ParseTreeNode>> children; if (current_token_ptr->GetType() == Token::Type::RETURN) { children.emplace_back(std::make_unique<GenericTokenParseTreeNode>(current_token_ptr->GetSourceCodeReference())); // "RETURN" current_token_ptr = std::make_unique<Token>(lexer.ProduceNextToken()); std::unique_ptr<ParseTreeNode> additive_expression = ParseAdditiveExpression(); if (!additive_expression) { return nullptr; } children.emplace_back(std::move(additive_expression)); } else { std::unique_ptr<ParseTreeNode> assignment_expression = ParseAssignmentExpresion(); if (!assignment_expression) { return nullptr; } children.emplace_back(std::move(assignment_expression)); } return std::make_unique<NonTerminalParseTreeNode>(BuildChildrenSourceCodeReference(children), ParseTreeNode::Type::Statement, std::move(children)); } //--------------------------------------------------------------------------- std::unique_ptr<ParseTreeNode> Parser::ParseAssignmentExpresion() { // identifier if (current_token_ptr->GetType() != Token::Type::IDENTIFIER) { return ErrorHandling("Expected identifier"); } std::vector<std::unique_ptr<ParseTreeNode>> children; children.emplace_back(std::make_unique<IdentifierParseTreeNode>(current_token_ptr->GetSourceCodeReference())); // IDENTIFIER current_token_ptr = std::make_unique<Token>(lexer.ProduceNextToken()); // ":= if (current_token_ptr->GetType() != Token::Type::ASSIGNMENT) { return ErrorHandling("Expected assignment"); } children.emplace_back(std::make_unique<GenericTokenParseTreeNode>(current_token_ptr->GetSourceCodeReference())); // ASSIGNMENT current_token_ptr = std::make_unique<Token>(lexer.ProduceNextToken()); // additive-expression std::unique_ptr<ParseTreeNode> additive_expression = ParseAdditiveExpression(); if (!additive_expression) { return nullptr; } children.emplace_back(std::move(additive_expression)); return std::make_unique<NonTerminalParseTreeNode>(BuildChildrenSourceCodeReference(children), ParseTreeNode::Type::AssignmentExpression, std::move(children)); } //--------------------------------------------------------------------------- std::unique_ptr<ParseTreeNode> Parser::ParseAdditiveExpression() { // multiplicative-expression std::unique_ptr<ParseTreeNode> multiplicative_expression = ParseMultiplicativeExpression(); if (!multiplicative_expression) { return nullptr; } std::vector<std::unique_ptr<ParseTreeNode>> children; children.emplace_back(std::move(multiplicative_expression)); // [ ( "+" | "-" ) additive-expression ] if (current_token_ptr->GetType() == Token::Type::PLUS || current_token_ptr->GetType() == Token::Type::MINUS) { if (current_token_ptr->GetType() == Token::Type::PLUS) { children.emplace_back(std::make_unique<OperatorAlternationParseTreeNode>(current_token_ptr->GetSourceCodeReference(), OperatorAlternationParseTreeNode::Plus)); } else { children.emplace_back(std::make_unique<OperatorAlternationParseTreeNode>(current_token_ptr->GetSourceCodeReference(), OperatorAlternationParseTreeNode::Minus)); } current_token_ptr = std::make_unique<Token>(lexer.ProduceNextToken()); std::unique_ptr<ParseTreeNode> additive_expression = ParseAdditiveExpression(); if (!additive_expression) { return nullptr; } children.emplace_back(std::move(additive_expression)); } return std::make_unique<NonTerminalParseTreeNode>(BuildChildrenSourceCodeReference(children), ParseTreeNode::Type::AdditiveExpression, std::move(children)); } //--------------------------------------------------------------------------- std::unique_ptr<ParseTreeNode> Parser::ParseMultiplicativeExpression() { // unary-expression std::unique_ptr<ParseTreeNode> unary_expression = ParseUnaryExpression(); if (!unary_expression) { return nullptr; } std::vector<std::unique_ptr<ParseTreeNode>> children; children.emplace_back(std::move(unary_expression)); // [ ( "*" | "/" ) multiplicative-expression ] if (current_token_ptr->GetType() == Token::Type::MUL || current_token_ptr->GetType() == Token::Type::DIV) { if (current_token_ptr->GetType() == Token::Type::MUL) { children.emplace_back(std::make_unique<OperatorAlternationParseTreeNode>(current_token_ptr->GetSourceCodeReference(), OperatorAlternationParseTreeNode::Multiply)); } else { children.emplace_back(std::make_unique<OperatorAlternationParseTreeNode>(current_token_ptr->GetSourceCodeReference(), OperatorAlternationParseTreeNode::Divide)); } current_token_ptr = std::make_unique<Token>(lexer.ProduceNextToken()); std::unique_ptr<ParseTreeNode> multiplicative_expression = ParseMultiplicativeExpression(); if (!multiplicative_expression) { return nullptr; } children.emplace_back(std::move(multiplicative_expression)); } return std::make_unique<NonTerminalParseTreeNode>(BuildChildrenSourceCodeReference(children), ParseTreeNode::Type::MultiplicativeExpression, std::move(children)); } //--------------------------------------------------------------------------- std::unique_ptr<ParseTreeNode> Parser::ParseUnaryExpression() { std::vector<std::unique_ptr<ParseTreeNode>> children; // [ "+" | "-" ] if (current_token_ptr->GetType() == Token::Type::PLUS) { children.emplace_back(std::make_unique<OperatorAlternationParseTreeNode>(current_token_ptr->GetSourceCodeReference(), OperatorAlternationParseTreeNode::Plus)); current_token_ptr = std::make_unique<Token>(lexer.ProduceNextToken()); } else if (current_token_ptr->GetType() == Token::Type::MINUS) { children.emplace_back(std::make_unique<OperatorAlternationParseTreeNode>(current_token_ptr->GetSourceCodeReference(), OperatorAlternationParseTreeNode::Minus)); current_token_ptr = std::make_unique<Token>(lexer.ProduceNextToken()); } // primary-expression. std::unique_ptr<ParseTreeNode> primary_expression = ParsePrimaryExpression(); if (!primary_expression) { return nullptr; } children.emplace_back(std::move(primary_expression)); return std::make_unique<NonTerminalParseTreeNode>(BuildChildrenSourceCodeReference(children), ParseTreeNode::Type::UnaryExpression, std::move(children)); } //--------------------------------------------------------------------------- std::unique_ptr<ParseTreeNode> Parser::ParsePrimaryExpression() { std::vector<std::unique_ptr<ParseTreeNode>> children; if (current_token_ptr->GetType() == Token::Type::IDENTIFIER) { children.emplace_back(std::make_unique<IdentifierParseTreeNode>(current_token_ptr->GetSourceCodeReference())); } else if (current_token_ptr->GetType() == Token::Type::LITERAL) { children.emplace_back(std::make_unique<LiteralParseTreeNode>(current_token_ptr->GetSourceCodeReference(), std::stoll(std::string(current_token_ptr->GetSourceCodeReference().GetSourceCode())))); } else if (current_token_ptr->GetType() == Token::Type::LEFT_PARENTHESE) { children.emplace_back(std::make_unique<GenericTokenParseTreeNode>(current_token_ptr->GetSourceCodeReference())); // "(" auto left_parenthese = std::move(current_token_ptr); current_token_ptr = std::make_unique<Token>(lexer.ProduceNextToken()); std::unique_ptr<ParseTreeNode> additive_expression = ParseAdditiveExpression(); if (!additive_expression) { return nullptr; } children.emplace_back(std::move(additive_expression)); if (current_token_ptr && current_token_ptr->GetType() != Token::Type::RIGHT_PARENTHESE) { current_token_ptr->GetSourceCodeReference().PrintContext("Expected a ')'"); left_parenthese->GetSourceCodeReference().PrintContext("To match this previous '('"); return nullptr; } children.emplace_back(std::make_unique<GenericTokenParseTreeNode>(current_token_ptr->GetSourceCodeReference())); // ")" } else { return ErrorHandling("Expected an identifier, literal or '('"); } current_token_ptr = std::make_unique<Token>(lexer.ProduceNextToken()); return std::make_unique<NonTerminalParseTreeNode>(BuildChildrenSourceCodeReference(children), ParseTreeNode::Type::PrimaryExpression, std::move(children)); } //--------------------------------------------------------------------------- } // namespace pljit //---------------------------------------------------------------------------
69.662011
233
0.687758
cakebytheoceanLuo
d834f7a7a0796bddd9d752b80cca8a55eb26e282
3,440
cpp
C++
Graph/310. Minimum Height Trees/main.cpp
Minecodecraft/LeetCode-Minecode
185fd6efe88d8ffcad94e581915c41502a0361a0
[ "MIT" ]
1
2021-11-19T19:58:33.000Z
2021-11-19T19:58:33.000Z
Graph/310. Minimum Height Trees/main.cpp
Minecodecraft/LeetCode-Minecode
185fd6efe88d8ffcad94e581915c41502a0361a0
[ "MIT" ]
null
null
null
Graph/310. Minimum Height Trees/main.cpp
Minecodecraft/LeetCode-Minecode
185fd6efe88d8ffcad94e581915c41502a0361a0
[ "MIT" ]
2
2021-11-26T12:47:27.000Z
2022-01-13T16:14:46.000Z
// // main.cpp // 310. Minimum Height Trees // // Created by 边俊林 on 2019/11/13. // Copyright © 2019 边俊林. All rights reserved. // #include <map> #include <set> #include <queue> #include <string> #include <stack> #include <vector> #include <cstdio> #include <numeric> #include <cstdlib> #include <utility> #include <iostream> #include <algorithm> #include <unordered_map> #include <unordered_set> using namespace std; /// Solution: // // Solution 1: Not conciselly /* class Solution { public: vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) { if (n == 1) return {0}; vector<int> degree (n, 0); unordered_map<int, vector<int>> mp; for (auto& e: edges) { degree[e[0]]++; degree[e[1]]++; mp[e[0]].push_back(e[1]); mp[e[1]].push_back(e[0]); } int last = n; queue<int> q; for (int i = 0; i < n; ++i) if (degree[i] == 1) q.push(i); while (q.size() && last > 2) { int p = q.front(); q.pop(); degree[p]--; last--; for (auto it = mp[p].begin(); it != mp[p].end(); ++it) { if (--degree[*it] == 1) q.push(*it); } } map<int, vector<int>> cnt; while (q.size()) { int p = q.front(); q.pop(); int num = countstep(mp, p, n); cnt[num].push_back(p); } return cnt.empty() ? vector<int>() : cnt.begin()->second; } private: const long long SEED = 1e6; int countstep(unordered_map<int, vector<int>>& mp, int idx, int n) { queue<long long> q; vector<bool> vis (n, false); int maxlevel = 0; q.push(idx + 1 * SEED); while (q.size()) { long cp = q.front(); q.pop(); int level = cp / SEED; int p = cp % SEED; if (vis[p]) continue; vis[p] = true; maxlevel = max(maxlevel, level); for (auto it = mp[p].begin(); it != mp[p].end(); ++it) { q.push(*it + (level+1) * SEED); } } return maxlevel; } }; */ // Solution 2: Conciselly code class Solution { public: vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) { // corner case if (n == 1) return {0}; unordered_map<int, unordered_set<int>> mp; for (auto& e: edges) { mp[e[0]].insert(e[1]); mp[e[1]].insert(e[0]); } vector<int> curr; for (int i = 0; i < n; ++i) if (mp[i].size() == 1) curr.push_back(i); while (true) { vector<int> next; for (auto& cur: curr) { for (auto& adj: mp[cur]) { mp[adj].erase(cur); if (mp[adj].size() == 1) next.push_back(adj); } } if (next.empty()) return curr; curr = next; } } }; int main() { Solution sol = Solution(); // int n = 4; // int n = 6; int n = 1; vector<vector<int>> mat = { // {1, 0}, {1, 2}, {1, 3} // [0, 3], [1, 3], [2, 3], [4, 3], [5, 4] }; auto res = sol.findMinHeightTrees(n, mat); for_each(begin(res), end(res), [](int ele) { cout << ele << ", "; }); cout << endl; return 0; }
24.571429
73
0.451163
Minecodecraft
d8352c55a668b2a9e176f2bd98cdb41746e4a0d7
3,938
cxx
C++
test/test_utility.cxx
cmbrandt/stl-algorithms
9eb0bc664e8423fb066c29aa501a72f4e672be1d
[ "MIT" ]
null
null
null
test/test_utility.cxx
cmbrandt/stl-algorithms
9eb0bc664e8423fb066c29aa501a72f4e672be1d
[ "MIT" ]
null
null
null
test/test_utility.cxx
cmbrandt/stl-algorithms
9eb0bc664e8423fb066c29aa501a72f4e672be1d
[ "MIT" ]
null
null
null
#include <array> #include <iostream> #include <utility.hxx> #include <test_helpers.hxx> #include <test_utility.hxx> void test_utility() { int fail = 0; fail = test_swap(fail); fail = test_exchange(fail); fail = test_forward(fail); fail = test_move(fail); fail = test_move_if_noexcept(fail); if (fail == 0) std::cout << "\ntest_utility() passed with zero errors." << std::endl; else std::cout << "\ntest_utility() had " << fail << " errors." << std::endl; } // // Utility component tests int test_swap(int fail) { int x{0}; int y{5}; std::array<int, 5> a{ 0, 1, 2, 3, 4 }; std::array<int, 5> b{ 2, 2, 2, 2, 2 }; std::array<int, 5> soln1{ 2, 2, 2, 2, 2 }; std::array<int, 5> soln2{ 0, 1, 2, 3, 4 }; cmb::swap(x, y); cmb::swap(a, b); bool r3 = compare_numeric_sequences( a.begin(), a.end(), soln1.begin() ); bool r4 = compare_numeric_sequences( b.begin(), b.end(), soln2.begin() ); if (x != 5 or y != 0 or r3 != false or r4 != false) { ++fail; std::cout << "\nERROR! cmb::swap()" << "\nx = " << x << "\nsoln = " << 5 << "\ny = " << y << "\nsoln = " << 0 << std::endl; print_sequence( "a", a.begin(), a.end() ); print_sequence( "soln1", soln1.begin(), soln1.end() ); print_sequence( "b", b.begin(), b.end() ); print_sequence( "soln2", soln2.begin(), soln2.end() ); } return fail; } int test_exchange(int fail) { int x{0}; int y{5}; int z = cmb::exchange(x, y); if (x != 5 or y != 5 or z != 0) { ++fail; std::cout << "\nERROR! cmb::exchange()" << "\nx = " << x << "\nsoln = " << 5 << "\ny = " << y << "\nsoln = " << 5 << "\ny = " << z << "\nsoln = " << 0 << std::endl; } return fail; } // // Helper functions for test_forward // Function with lvalue and rvalue overloads int f(int const& x) { return x; } // denotes lvalue int f(int&& x) { x = 1; return x; } // denotes rvalue // Function template template <class T> int g(T&& x) { int a = f( x ); // always an lvalue int b = f( cmb::forward<T>(x) ); // rvalue if argument is an rvalue return a + b; } int test_forward(int fail) { int a{5}; int r1 = g(a); int r2 = g(5); if (r1 != 10 or r2 != 6) { ++fail; std::cout << "\nERROR! cmb::move()" << "\nr1 = " << r1 << "\ns1 = " << 10 << "\nr2 = " << r2 << "\ns2 = " << 6 << std::endl; } return fail; } int test_move(int fail) { std::string s1 = "abc"; std::string s2 = cmb::move(s1); std::string r1 = ""; std::string r2 = "abc"; if (s1 != r1 or s2 != r2) { ++fail; std::cout << "\nERROR! cmb::move()" << "\nr1 = " << r1 << "\ns1 = " << s1 << "\nr2 = " << r2 << "\ns2 = " << s2 << std::endl; } return fail; } // // Helper structs for test_move_if_noexcept // struct with noexcept move ctor and noexcept copy ctor struct Good { Good() = default; Good(Good&&) noexcept { i = 1; } Good(Good const&) noexcept { i = 2; } int i{0}; }; // struct with move ctor and copy ctor that may throw struct Bad { Bad() = default; Bad(Bad&&) { i = 3; } Bad(Bad const&) { i = 4; } int i{0}; }; int test_move_if_noexcept(int fail) { Good g1; Bad b1; Good g2( cmb::move_if_noexcept(g1) ); Bad b2( cmb::move_if_noexcept(b1) ); int r1 = g2.i; int r2 = b2.i; if (r1 != 1 or r2 != 4) { ++fail; std::cout << "\nERROR! cmb::move_if_noexcept()" << "\nr1 = " << r1 << "\nsoln1 = " << 1 << "\nr2 = " << r2 << "\nsoln2 = " << 4 << std::endl; } return fail; }
20.298969
79
0.466988
cmbrandt
d8396904e5f66985816aaacb88aa88e90458ed18
25,494
cxx
C++
main/desktop/source/deployment/registry/dp_backenddb.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/desktop/source/deployment/registry/dp_backenddb.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/desktop/source/deployment/registry/dp_backenddb.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF 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. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_desktop.hxx" #include "rtl/string.h" #include "rtl/strbuf.hxx" #include "rtl/bootstrap.hxx" #include "cppuhelper/exc_hlp.hxx" #include "osl/file.hxx" #include "com/sun/star/uno/XComponentContext.hpp" #include "com/sun/star/xml/dom/XDocumentBuilder.hpp" #include "com/sun/star/xml/xpath/XXPathAPI.hpp" #include "com/sun/star/io/XActiveDataSource.hpp" #include "com/sun/star/io/XActiveDataControl.hpp" #include "dp_ucb.h" #include "dp_misc.h" #include "ucbhelper/content.hxx" #include "xmlscript/xml_helper.hxx" #include "dp_backenddb.hxx" namespace css = ::com::sun::star; using namespace ::com::sun::star::uno; using ::rtl::OUString; namespace dp_registry { namespace backend { BackendDb::BackendDb( Reference<css::uno::XComponentContext> const & xContext, ::rtl::OUString const & url): m_xContext(xContext) { m_urlDb = dp_misc::expandUnoRcUrl(url); } void BackendDb::save() { const Reference<css::io::XActiveDataSource> xDataSource(m_doc,css::uno::UNO_QUERY_THROW); ::rtl::ByteSequence bytes; xDataSource->setOutputStream(::xmlscript::createOutputStream(&bytes)); const Reference<css::io::XActiveDataControl> xDataControl(m_doc,css::uno::UNO_QUERY_THROW); xDataControl->start(); const Reference<css::io::XInputStream> xData( ::xmlscript::createInputStream(bytes)); ::ucbhelper::Content ucbDb(m_urlDb, 0); ucbDb.writeStream(xData, true /*replace existing*/); } css::uno::Reference<css::xml::dom::XDocument> BackendDb::getDocument() { if (!m_doc.is()) { const Reference<css::xml::dom::XDocumentBuilder> xDocBuilder( m_xContext->getServiceManager()->createInstanceWithContext( OUSTR("com.sun.star.xml.dom.DocumentBuilder"), m_xContext ), css::uno::UNO_QUERY); if (!xDocBuilder.is()) throw css::uno::RuntimeException( OUSTR(" Could not create service com.sun.star.xml.dom.DocumentBuilder"), 0); ::osl::DirectoryItem item; ::osl::File::RC err = ::osl::DirectoryItem::get(m_urlDb, item); if (err == ::osl::File::E_None) { ::ucbhelper::Content descContent( m_urlDb, css::uno::Reference<css::ucb::XCommandEnvironment>()); Reference<css::io::XInputStream> xIn = descContent.openStream(); m_doc = xDocBuilder->parse(xIn); } else if (err == ::osl::File::E_NOENT) { //Create a new document and insert some basic stuff m_doc = xDocBuilder->newDocument(); const Reference<css::xml::dom::XElement> rootNode = m_doc->createElementNS(getDbNSName(), getNSPrefix() + OUSTR(":") + getRootElementName()); m_doc->appendChild(Reference<css::xml::dom::XNode>( rootNode, UNO_QUERY_THROW)); save(); } else throw css::uno::RuntimeException( OUSTR("Extension manager could not access database file:" ) + m_urlDb, 0); if (!m_doc.is()) throw css::uno::RuntimeException( OUSTR("Extension manager could not get root node of data base file: ") + m_urlDb, 0); } return m_doc; } Reference<css::xml::xpath::XXPathAPI> BackendDb::getXPathAPI() { if (!m_xpathApi.is()) { m_xpathApi = Reference< css::xml::xpath::XXPathAPI >( m_xContext->getServiceManager()->createInstanceWithContext( OUSTR("com.sun.star.xml.xpath.XPathAPI"), m_xContext), css::uno::UNO_QUERY); if (!m_xpathApi.is()) throw css::uno::RuntimeException( OUSTR(" Could not create service com.sun.star.xml.xpath.XPathAPI"), 0); m_xpathApi->registerNS( getNSPrefix(), getDbNSName()); } return m_xpathApi; } void BackendDb::removeElement(::rtl::OUString const & sXPathExpression) { try { const Reference<css::xml::dom::XDocument> doc = getDocument(); const Reference<css::xml::dom::XNode> root = doc->getFirstChild(); const Reference<css::xml::xpath::XXPathAPI> xpathApi = getXPathAPI(); //find the extension element that is to be removed const Reference<css::xml::dom::XNode> aNode = xpathApi->selectSingleNode(root, sXPathExpression); if (aNode.is()) { root->removeChild(aNode); save(); } #if OSL_DEBUG_LEVEL > 0 //There must not be any other entry with the same url const Reference<css::xml::dom::XNode> nextNode = xpathApi->selectSingleNode(root, sXPathExpression); OSL_ASSERT(! nextNode.is()); #endif } catch(css::uno::Exception &) { Any exc( ::cppu::getCaughtException() ); throw css::deployment::DeploymentException( OUSTR("Extension Manager: failed to write data entry in backend db: ") + m_urlDb, 0, exc); } } void BackendDb::removeEntry(::rtl::OUString const & url) { const OUString sKeyElement = getKeyElementName(); const OUString sPrefix = getNSPrefix(); ::rtl::OUStringBuffer sExpression(500); sExpression.append(sPrefix); sExpression.appendAscii(":"); sExpression.append(sKeyElement); sExpression.append(OUSTR("[@url = \"")); sExpression.append(url); sExpression.appendAscii("\"]"); removeElement(sExpression.makeStringAndClear()); } void BackendDb::revokeEntry(::rtl::OUString const & url) { try { Reference<css::xml::dom::XElement> entry = Reference<css::xml::dom::XElement>(getKeyElement(url), UNO_QUERY); if (entry.is()) { entry->setAttribute(OUSTR("revoked"), OUSTR("true")); save(); } } catch(css::uno::Exception &) { Any exc( ::cppu::getCaughtException() ); throw css::deployment::DeploymentException( OUSTR("Extension Manager: failed to revoke data entry in backend db: ") + m_urlDb, 0, exc); } } bool BackendDb::activateEntry(::rtl::OUString const & url) { try { bool ret = false; Reference<css::xml::dom::XElement> entry = Reference<css::xml::dom::XElement>(getKeyElement(url), UNO_QUERY); if (entry.is()) { //no attribute "active" means it is active, that is, registered. entry->removeAttribute(OUSTR("revoked")); save(); ret = true; } return ret; } catch(css::uno::Exception &) { Any exc( ::cppu::getCaughtException() ); throw css::deployment::DeploymentException( OUSTR("Extension Manager: failed to revoke data entry in backend db: ") + m_urlDb, 0, exc); } } bool BackendDb::hasActiveEntry(::rtl::OUString const & url) { try { bool ret = false; Reference<css::xml::dom::XElement> entry = Reference<css::xml::dom::XElement>(getKeyElement(url), UNO_QUERY); if (entry.is()) { OUString sActive = entry->getAttribute(OUSTR("revoked")); if (!sActive.equals(OUSTR("true"))) ret = true; } return ret; } catch(css::uno::Exception &) { Any exc( ::cppu::getCaughtException() ); throw css::deployment::DeploymentException( OUSTR("Extension Manager: failed to determine an active entry in backend db: ") + m_urlDb, 0, exc); } } Reference<css::xml::dom::XNode> BackendDb::getKeyElement( ::rtl::OUString const & url) { try { const OUString sPrefix = getNSPrefix(); const OUString sKeyElement = getKeyElementName(); ::rtl::OUStringBuffer sExpression(500); sExpression.append(sPrefix); sExpression.appendAscii(":"); sExpression.append(sKeyElement); sExpression.append(OUSTR("[@url = \"")); sExpression.append(url); sExpression.appendAscii("\"]"); const Reference<css::xml::dom::XDocument> doc = getDocument(); const Reference<css::xml::dom::XNode> root = doc->getFirstChild(); const Reference<css::xml::xpath::XXPathAPI> xpathApi = getXPathAPI(); return xpathApi->selectSingleNode(root, sExpression.makeStringAndClear()); } catch(css::uno::Exception &) { Any exc( ::cppu::getCaughtException() ); throw css::deployment::DeploymentException( OUSTR("Extension Manager: failed to read key element in backend db: ") + m_urlDb, 0, exc); } } //Only writes the data if there is at least one entry void BackendDb::writeVectorOfPair( ::std::vector< ::std::pair< ::rtl::OUString, ::rtl::OUString > > const & vecPairs, OUString const & sVectorTagName, OUString const & sPairTagName, OUString const & sFirstTagName, OUString const & sSecondTagName, css::uno::Reference<css::xml::dom::XNode> const & xParent) { try{ if (vecPairs.size() == 0) return; const OUString sNameSpace = getDbNSName(); OSL_ASSERT(sNameSpace.getLength()); const OUString sPrefix(getNSPrefix() + OUSTR(":")); const Reference<css::xml::dom::XDocument> doc = getDocument(); const Reference<css::xml::dom::XNode> root = doc->getFirstChild(); const Reference<css::xml::dom::XElement> vectorNode( doc->createElementNS(sNameSpace, sPrefix + sVectorTagName)); xParent->appendChild( Reference<css::xml::dom::XNode>( vectorNode, css::uno::UNO_QUERY_THROW)); typedef ::std::vector< ::std::pair< OUString, OUString > >::const_iterator CIT; for (CIT i = vecPairs.begin(); i != vecPairs.end(); i++) { const Reference<css::xml::dom::XElement> pairNode( doc->createElementNS(sNameSpace, sPrefix + sPairTagName)); vectorNode->appendChild( Reference<css::xml::dom::XNode>( pairNode, css::uno::UNO_QUERY_THROW)); const Reference<css::xml::dom::XElement> firstNode( doc->createElementNS(sNameSpace, sPrefix + sFirstTagName)); pairNode->appendChild( Reference<css::xml::dom::XNode>( firstNode, css::uno::UNO_QUERY_THROW)); const Reference<css::xml::dom::XText> firstTextNode( doc->createTextNode( i->first)); firstNode->appendChild( Reference<css::xml::dom::XNode>( firstTextNode, css::uno::UNO_QUERY_THROW)); const Reference<css::xml::dom::XElement> secondNode( doc->createElementNS(sNameSpace, sPrefix + sSecondTagName)); pairNode->appendChild( Reference<css::xml::dom::XNode>( secondNode, css::uno::UNO_QUERY_THROW)); const Reference<css::xml::dom::XText> secondTextNode( doc->createTextNode( i->second)); secondNode->appendChild( Reference<css::xml::dom::XNode>( secondTextNode, css::uno::UNO_QUERY_THROW)); } } catch(css::uno::Exception &) { Any exc( ::cppu::getCaughtException() ); throw css::deployment::DeploymentException( OUSTR("Extension Manager: failed to write data entry in backend db: ") + m_urlDb, 0, exc); } } ::std::vector< ::std::pair< OUString, OUString > > BackendDb::readVectorOfPair( Reference<css::xml::dom::XNode> const & parent, OUString const & sListTagName, OUString const & sPairTagName, OUString const & sFirstTagName, OUString const & sSecondTagName) { try { OSL_ASSERT(parent.is()); const OUString sPrefix(getNSPrefix() + OUSTR(":")); const Reference<css::xml::xpath::XXPathAPI> xpathApi = getXPathAPI(); const OUString sExprPairs( sPrefix + sListTagName + OUSTR("/") + sPrefix + sPairTagName); const Reference<css::xml::dom::XNodeList> listPairs = xpathApi->selectNodeList(parent, sExprPairs); ::std::vector< ::std::pair< OUString, OUString > > retVector; sal_Int32 length = listPairs->getLength(); for (sal_Int32 i = 0; i < length; i++) { const Reference<css::xml::dom::XNode> aPair = listPairs->item(i); const OUString sExprFirst(sPrefix + sFirstTagName + OUSTR("/text()")); const Reference<css::xml::dom::XNode> first = xpathApi->selectSingleNode(aPair, sExprFirst); const OUString sExprSecond(sPrefix + sSecondTagName + OUSTR("/text()")); const Reference<css::xml::dom::XNode> second = xpathApi->selectSingleNode(aPair, sExprSecond); OSL_ASSERT(first.is() && second.is()); retVector.push_back(::std::make_pair( first->getNodeValue(), second->getNodeValue())); } return retVector; } catch(css::uno::Exception &) { Any exc( ::cppu::getCaughtException() ); throw css::deployment::DeploymentException( OUSTR("Extension Manager: failed to read data entry in backend db: ") + m_urlDb, 0, exc); } } //Only writes the data if there is at least one entry void BackendDb::writeSimpleList( ::std::list< ::rtl::OUString> const & list, OUString const & sListTagName, OUString const & sMemberTagName, Reference<css::xml::dom::XNode> const & xParent) { try { if (list.size() == 0) return; const OUString sNameSpace = getDbNSName(); const OUString sPrefix(getNSPrefix() + OUSTR(":")); const Reference<css::xml::dom::XDocument> doc = getDocument(); const Reference<css::xml::dom::XElement> listNode( doc->createElementNS(sNameSpace, sPrefix + sListTagName)); xParent->appendChild( Reference<css::xml::dom::XNode>( listNode, css::uno::UNO_QUERY_THROW)); typedef ::std::list<OUString>::const_iterator ITC_ITEMS; for (ITC_ITEMS i = list.begin(); i != list.end(); i++) { const Reference<css::xml::dom::XNode> memberNode( doc->createElementNS(sNameSpace, sPrefix + sMemberTagName), css::uno::UNO_QUERY_THROW); listNode->appendChild(memberNode); const Reference<css::xml::dom::XNode> textNode( doc->createTextNode( *i), css::uno::UNO_QUERY_THROW); memberNode->appendChild(textNode); } } catch(css::uno::Exception &) { Any exc( ::cppu::getCaughtException() ); throw css::deployment::DeploymentException( OUSTR("Extension Manager: failed to write data entry in backend db: ") + m_urlDb, 0, exc); } } //Writes only the element if is has a value. //The prefix is automatically added to the element name void BackendDb::writeSimpleElement( OUString const & sElementName, OUString const & value, Reference<css::xml::dom::XNode> const & xParent) { try { if (value.getLength() == 0) return; const OUString sPrefix = getNSPrefix(); const Reference<css::xml::dom::XDocument> doc = getDocument(); const OUString sNameSpace = getDbNSName(); const Reference<css::xml::dom::XNode> dataNode( doc->createElementNS(sNameSpace, sPrefix + OUSTR(":") + sElementName), UNO_QUERY_THROW); xParent->appendChild(dataNode); const Reference<css::xml::dom::XNode> dataValue( doc->createTextNode(value), UNO_QUERY_THROW); dataNode->appendChild(dataValue); } catch(css::uno::Exception &) { Any exc( ::cppu::getCaughtException() ); throw css::deployment::DeploymentException( OUSTR("Extension Manager: failed to write data entry(writeSimpleElement) in backend db: ") + m_urlDb, 0, exc); } } /** The key elements have an url attribute and are always children of the root element. */ Reference<css::xml::dom::XNode> BackendDb::writeKeyElement( ::rtl::OUString const & url) { try { const OUString sNameSpace = getDbNSName(); const OUString sPrefix = getNSPrefix(); const OUString sElementName = getKeyElementName(); const Reference<css::xml::dom::XDocument> doc = getDocument(); const Reference<css::xml::dom::XNode> root = doc->getFirstChild(); //Check if there are an entry with the same url. This can be the case if the //the status of an XPackage is ambiguous. In this case a call to activateExtension //(dp_extensionmanager.cxx), will register the package again. See also //Package::processPackage_impl in dp_backend.cxx. //A package can become //invalid after its successful registration, for example if a second extension with //the same service is installed. const OUString sExpression( sPrefix + OUSTR(":") + sElementName + OUSTR("[@url = \"") + url + OUSTR("\"]")); const Reference<css::xml::dom::XNode> existingNode = getXPathAPI()->selectSingleNode(root, sExpression); if (existingNode.is()) { OSL_ASSERT(0); //replace the existing entry. removeEntry(url); } const Reference<css::xml::dom::XElement> keyElement( doc->createElementNS(sNameSpace, sPrefix + OUSTR(":") + sElementName)); keyElement->setAttribute(OUSTR("url"), url); const Reference<css::xml::dom::XNode> keyNode( keyElement, UNO_QUERY_THROW); root->appendChild(keyNode); return keyNode; } catch(css::uno::Exception &) { Any exc( ::cppu::getCaughtException() ); throw css::deployment::DeploymentException( OUSTR("Extension Manager: failed to write key element in backend db: ") + m_urlDb, 0, exc); } } OUString BackendDb::readSimpleElement( OUString const & sElementName, Reference<css::xml::dom::XNode> const & xParent) { try { const OUString sPrefix = getNSPrefix(); const OUString sExpr(sPrefix + OUSTR(":") + sElementName + OUSTR("/text()")); const Reference<css::xml::xpath::XXPathAPI> xpathApi = getXPathAPI(); const Reference<css::xml::dom::XNode> val = xpathApi->selectSingleNode(xParent, sExpr); if (val.is()) return val->getNodeValue(); return OUString(); } catch(css::uno::Exception &) { Any exc( ::cppu::getCaughtException() ); throw css::deployment::DeploymentException( OUSTR("Extension Manager: failed to read data (readSimpleElement) in backend db: ") + m_urlDb, 0, exc); } } ::std::list< OUString> BackendDb::readList( Reference<css::xml::dom::XNode> const & parent, OUString const & sListTagName, OUString const & sMemberTagName) { try { OSL_ASSERT(parent.is()); const OUString sPrefix(getNSPrefix() + OUSTR(":")); const Reference<css::xml::xpath::XXPathAPI> xpathApi = getXPathAPI(); const OUString sExprList( sPrefix + sListTagName + OUSTR("/") + sPrefix + sMemberTagName + OUSTR("/text()")); const Reference<css::xml::dom::XNodeList> list = xpathApi->selectNodeList(parent, sExprList); ::std::list<OUString > retList; sal_Int32 length = list->getLength(); for (sal_Int32 i = 0; i < length; i++) { const Reference<css::xml::dom::XNode> member = list->item(i); retList.push_back(member->getNodeValue()); } return retList; } catch(css::uno::Exception &) { Any exc( ::cppu::getCaughtException() ); throw css::deployment::DeploymentException( OUSTR("Extension Manager: failed to read data entry in backend db: ") + m_urlDb, 0, exc); } } ::std::list<OUString> BackendDb::getOneChildFromAllEntries( OUString const & name) { try { ::std::list<OUString> listRet; Reference<css::xml::dom::XDocument> doc = getDocument(); Reference<css::xml::dom::XNode> root = doc->getFirstChild(); Reference<css::xml::xpath::XXPathAPI> xpathApi = getXPathAPI(); const OUString sPrefix = getNSPrefix(); const OUString sKeyElement = getKeyElementName(); ::rtl::OUStringBuffer buf(512); buf.append(sPrefix); buf.appendAscii(":"); buf.append(sKeyElement); buf.appendAscii("/"); buf.append(sPrefix); buf.appendAscii(":"); buf.append(name); buf.append(OUSTR("/text()")); Reference<css::xml::dom::XNodeList> nodes = xpathApi->selectNodeList(root, buf.makeStringAndClear()); if (nodes.is()) { sal_Int32 length = nodes->getLength(); for (sal_Int32 i = 0; i < length; i++) listRet.push_back(nodes->item(i)->getNodeValue()); } return listRet; } catch (css::deployment::DeploymentException& ) { throw; } catch(css::uno::Exception &) { Any exc( ::cppu::getCaughtException() ); throw css::deployment::DeploymentException( OUSTR("Extension Manager: failed to read data entry in backend db: ") + m_urlDb, 0, exc); } } //================================================================================ RegisteredDb::RegisteredDb( Reference<XComponentContext> const & xContext, ::rtl::OUString const & url):BackendDb(xContext, url) { } void RegisteredDb::addEntry(::rtl::OUString const & url) { try{ if (!activateEntry(url)) { const OUString sNameSpace = getDbNSName(); const OUString sPrefix = getNSPrefix(); const OUString sEntry = getKeyElementName(); Reference<css::xml::dom::XDocument> doc = getDocument(); Reference<css::xml::dom::XNode> root = doc->getFirstChild(); #if OSL_DEBUG_LEVEL > 0 //There must not be yet an entry with the same url OUString sExpression( sPrefix + OUSTR(":") + sEntry + OUSTR("[@url = \"") + url + OUSTR("\"]")); Reference<css::xml::dom::XNode> _extensionNode = getXPathAPI()->selectSingleNode(root, sExpression); OSL_ASSERT(! _extensionNode.is()); #endif Reference<css::xml::dom::XElement> helpElement( doc->createElementNS(sNameSpace, sPrefix + OUSTR(":") + sEntry)); helpElement->setAttribute(OUSTR("url"), url); Reference<css::xml::dom::XNode> helpNode( helpElement, UNO_QUERY_THROW); root->appendChild(helpNode); save(); } } catch(css::uno::Exception &) { Any exc( ::cppu::getCaughtException() ); throw css::deployment::DeploymentException( OUSTR("Extension Manager: failed to write data entry in backend db: ") + m_urlDb, 0, exc); } } bool RegisteredDb::getEntry(::rtl::OUString const & url) { try { const OUString sPrefix = getNSPrefix(); const OUString sEntry = getKeyElementName(); const OUString sExpression( sPrefix + OUSTR(":") + sEntry + OUSTR("[@url = \"") + url + OUSTR("\"]")); Reference<css::xml::dom::XDocument> doc = getDocument(); Reference<css::xml::dom::XNode> root = doc->getFirstChild(); Reference<css::xml::xpath::XXPathAPI> xpathApi = getXPathAPI(); //find the extension element that is to be removed Reference<css::xml::dom::XNode> aNode = xpathApi->selectSingleNode(root, sExpression); if (!aNode.is()) { return false; } return true; } catch(css::uno::Exception &) { Any exc( ::cppu::getCaughtException() ); throw css::deployment::DeploymentException( OUSTR("Extension Manager: failed to read data entry in backend db: ") + m_urlDb, 0, exc); } } } // namespace backend } // namespace dp_registry
35.45758
117
0.593198
Grosskopf
d83a1e36cb59e58725c9d29e38d2b894d0e82387
1,134
cpp
C++
source/core.cpp
henrygouk/nnet
dd33ce43852d2deb33e6495c0c1b1ba2227d2aa5
[ "BSD-3-Clause" ]
1
2018-10-12T01:33:23.000Z
2018-10-12T01:33:23.000Z
source/core.cpp
henrygouk/nnet
dd33ce43852d2deb33e6495c0c1b1ba2227d2aa5
[ "BSD-3-Clause" ]
4
2015-07-21T02:24:13.000Z
2016-07-06T10:06:31.000Z
source/core.cpp
henrygouk/nnet
dd33ce43852d2deb33e6495c0c1b1ba2227d2aa5
[ "BSD-3-Clause" ]
2
2016-07-06T08:56:01.000Z
2018-03-04T02:55:29.000Z
#include <cstring> #include <mm_malloc.h> #include <nnet/types.hpp> nnet_float *nnet_malloc(size_t length) { return (nnet_float *)_mm_malloc(sizeof(nnet_float) * length, 32); } void nnet_free(nnet_float *ptr) { _mm_free(ptr); } void nnet_shuffle_instances(nnet_float *features, nnet_float *labels, size_t length, size_t num_features, size_t num_labels) { nnet_float *temp_features = nnet_malloc(num_features); nnet_float *temp_labels = nnet_malloc(num_labels); for(size_t i = length - 1; i > 0; i--) { size_t j = rand() % i; memcpy(temp_features, features + i * num_features, num_features * sizeof(nnet_float)); memcpy(features + i * num_features, features + j * num_features, num_features * sizeof(nnet_float)); memcpy(features + j * num_features, temp_features, num_features * sizeof(nnet_float)); memcpy(temp_labels, labels + i * num_labels, num_labels * sizeof(nnet_float)); memcpy(labels + i * num_labels, labels + j * num_labels, num_labels * sizeof(nnet_float)); memcpy(labels + j * num_labels, temp_labels, num_labels * sizeof(nnet_float)); } nnet_free(temp_features); nnet_free(temp_labels); }
30.648649
124
0.737213
henrygouk
d83b223c6b3268602c1be98587d5769b27e9b1c1
634
cc
C++
test/lib/nut_Test_Particle.cc
losalamos/NuT
5c6e03c45a380ae24ea9ee8bc2e68c3748ddd4e0
[ "BSD-3-Clause" ]
4
2015-01-01T13:47:53.000Z
2016-03-31T01:56:43.000Z
test/lib/nut_Test_Particle.cc
losalamos/NuT
5c6e03c45a380ae24ea9ee8bc2e68c3748ddd4e0
[ "BSD-3-Clause" ]
1
2019-05-08T16:21:43.000Z
2019-05-14T17:20:19.000Z
test/lib/nut_Test_Particle.cc
lanl/NuT
5c6e03c45a380ae24ea9ee8bc2e68c3748ddd4e0
[ "BSD-3-Clause" ]
4
2017-06-21T20:26:30.000Z
2020-03-19T07:05:00.000Z
// T. M. Kelley (c) 2011 LANS LLC #include "Particle.hh" #include "RNG.hh" #include "gtest/gtest.h" #include "meshes/mesh_common/Vector.h" TEST(nut_Particle, instantiation) { // for a very simple test, we can use a totally bogus RNG typedef uint32_t rng_t; typedef double fp_t; using Vector = nut_mesh::Vector; typedef nut::Particle<fp_t, rng_t, Vector> part_t; fp_t x(1.0); fp_t omega(1.0); fp_t e(1.0); fp_t t(1.0); fp_t wt(1.0); nut::cell_t cell(1); nut::Species s(nut::nu_e); rng_t rng(42); part_t particle({x}, {omega}, e, t, wt, cell, rng, s); EXPECT_TRUE(true); return; } // End of file
18.647059
59
0.652997
losalamos
d83c80cd46a0f68e4e9d5774401f5ddc453b84d9
2,859
cpp
C++
net/socket/SocketAddress.cpp
w20089527/Net
ca40f0d4a5aa94c64abb8ccc7306bc66bdf12584
[ "MIT" ]
1
2019-08-10T20:29:13.000Z
2019-08-10T20:29:13.000Z
net/socket/SocketAddress.cpp
whrool/Net
ca40f0d4a5aa94c64abb8ccc7306bc66bdf12584
[ "MIT" ]
null
null
null
net/socket/SocketAddress.cpp
whrool/Net
ca40f0d4a5aa94c64abb8ccc7306bc66bdf12584
[ "MIT" ]
null
null
null
// The MIT License (MIT) // // Copyright(c) 2015 huan.wang // // 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 <cassert> #include "net/socket/SocketAddress.h" namespace net { struct SocketAddressPrivate { std::string Host; uint16_t Port; sockaddr_in Address; }; SocketAddress::SocketAddress() { } SocketAddress::SocketAddress(const std::string& strHost, uint16_t port) : m_data(std::make_shared<SocketAddressPrivate>()) { sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_addr.S_un.S_addr = strHost.empty() ? htonl(ADDR_ANY) : inet_addr(strHost.c_str()); addr.sin_port = htons(port); m_data->Host = strHost; m_data->Port = port; m_data->Address = addr; } SocketAddress::SocketAddress(const struct sockaddr* addr, int length) : m_data(std::make_shared<SocketAddressPrivate>()) { assert(sizeof(sockaddr_in) == length); memcpy(&m_data->Address, addr, length); m_data->Host = inet_ntoa(m_data->Address.sin_addr); m_data->Port = ntohs(m_data->Address.sin_port); } SocketAddress::SocketAddress(const SocketAddress& address) : m_data(address.m_data) { } SocketAddress::~SocketAddress() { } SocketAddress::operator bool() const { return bool(m_data); } std::string SocketAddress::GetHost() const { if (m_data) return m_data->Host; return ""; } uint16_t SocketAddress::GetPort() const { if (m_data) return m_data->Port; return 0; } const struct sockaddr* SocketAddress::GetAddress() const { if (m_data) return reinterpret_cast<const struct sockaddr*>(&m_data->Address); return nullptr; } int SocketAddress::GetLength() const { if (m_data) return sizeof(m_data->Address); return 0; } } //!net
28.59
130
0.693949
w20089527
d844f0cf73b3ac22ab589bfd4bca3af1cfb12a9e
335
cpp
C++
source/dynamic_static/vulkan/framebuffer-utilities.cpp
dynamic-static/Dynamic_Static.Graphics
b4fcf3c53519d3a63448aa7d9a90e07ec68d69d4
[ "MIT" ]
3
2017-11-20T15:42:41.000Z
2020-05-02T22:05:39.000Z
source/dynamic_static/vulkan/framebuffer-utilities.cpp
DynamicStatic/Dynamic_Static.Graphics
b4fcf3c53519d3a63448aa7d9a90e07ec68d69d4
[ "MIT" ]
null
null
null
source/dynamic_static/vulkan/framebuffer-utilities.cpp
DynamicStatic/Dynamic_Static.Graphics
b4fcf3c53519d3a63448aa7d9a90e07ec68d69d4
[ "MIT" ]
null
null
null
/* ========================================== Copyright (c) 2021 dynamic_static Licensed under the MIT license http://opensource.org/licenses/MIT ========================================== */ #include "dynamic_static/vulkan/framebuffer-utilities.hpp" namespace dst { namespace vk { } // namespace vk } // namespace dst
19.705882
58
0.531343
dynamic-static
d8466183e691dba7d2b2345b07a478a3e7372dcf
12,130
cpp
C++
src/ossim/util/ossimSlopeUtil.cpp
rkanavath/ossim18
d2e8204d11559a6a868755a490f2ec155407fa96
[ "MIT" ]
null
null
null
src/ossim/util/ossimSlopeUtil.cpp
rkanavath/ossim18
d2e8204d11559a6a868755a490f2ec155407fa96
[ "MIT" ]
null
null
null
src/ossim/util/ossimSlopeUtil.cpp
rkanavath/ossim18
d2e8204d11559a6a868755a490f2ec155407fa96
[ "MIT" ]
1
2019-09-25T00:43:35.000Z
2019-09-25T00:43:35.000Z
//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Oscar Kramer // //******************************************************************* // $Id: ossimSlopeUtil.cpp 23664 2015-12-14 14:17:27Z dburken $ #include <ossim/util/ossimSlopeUtil.h> #include <ossim/init/ossimInit.h> #include <ossim/base/ossimConstants.h> #include <ossim/base/ossimApplicationUsage.h> #include <ossim/base/ossimNotify.h> #include <ossim/base/ossimPreferences.h> #include <ossim/base/ossimGrect.h> #include <ossim/base/ossimIrect.h> #include <ossim/elevation/ossimElevManager.h> #include <ossim/projection/ossimEquDistCylProjection.h> #include <ossim/projection/ossimImageViewProjectionTransform.h> #include <ossim/imaging/ossimSlopeFilter.h> #include <ossim/imaging/ossimImageHandlerRegistry.h> #include <ossim/imaging/ossimImageWriterFactoryRegistry.h> #include <ossim/imaging/ossimTiffWriter.h> #include <ossim/imaging/ossimIndexToRgbLutFilter.h> #include <ossim/imaging/ossimScalarRemapper.h> #include <ossim/imaging/ossimImageGeometry.h> #include <ossim/imaging/ossimImageRenderer.h> #include <ossim/imaging/ossimImageMosaic.h> #include <iostream> using namespace std; ossimSlopeUtil::ossimSlopeUtil() : m_aoiRadius(0), m_remapToByte(false) { m_centerGpt.makeNan(); } ossimSlopeUtil::~ossimSlopeUtil() { } void ossimSlopeUtil::usage(ossimArgumentParser& ap) { // Add global usage options. ossimInit::instance()->addOptions(ap); // Add options. addArguments(ap); // Write usage. ap.getApplicationUsage()->write(ossimNotify(ossimNotifyLevel_INFO)); ossimNotify(ossimNotifyLevel_INFO) << "\nUtility for computing the slope at each elevation post and generating " << "a corresponding slope image. The output scalar type is a normalized float with 1.0 = 90 " << "degree angle from the local vertical. Optional 8-bit scalar type is available." << "Examples:\n\n" << " ossim-slope [options] --dem <input-dem> <output-slope-image-file>\n" << " ossim-slope [options] --center <lat> <lon> --roi <meters> <output-slope-image-file>\n" << std::endl; } void ossimSlopeUtil::addArguments(ossimArgumentParser& ap) { // Set the general usage: ossimApplicationUsage* au = ap.getApplicationUsage(); ossimString usageString = ap.getApplicationName(); usageString += " [options] <output-image>"; au->setCommandLineUsage(usageString); // Set the command line options: au->addCommandLineOption( "--center <lat> <lon>", "The center position of the output product. Required if no input DEM is specified."); au->addCommandLineOption( "--dem <filename>", "Specifies the input DEM filename. If none provided, the elevation database is referenced " "as specified in prefs file for the center and ROI specified."); au->addCommandLineOption( "--remap", "The range of slope angle (0.0 to 90.0) is remapped to 0-255 (one byte/pixel)"); au->addCommandLineOption( "--lut <filename>", "Specifies the optional lookup table filename for mapping the single-band output " "image to an RGB. The LUT provided must be in the ossimIndexToRgbLutFilter format " "and should accomodate the output pixel range. This option forces remap to 8-bit, " "0-255 where 255 = 90 deg slope"); au->addCommandLineOption( "--request-api", "Causes applications API to be output as JSON to stdout. Accepts optional filename " "to store JSON output."); au->addCommandLineOption( "--roi <meters>", "radius of interest surrounding the center point. If absent, the product defaults to " "1024 x 1024 pixels, with a radius of 512 * GSD. Alternatively, if a DEM file is " "specified, the product ROI defaults to the full DEM coverage."); } bool ossimSlopeUtil::initialize(ossimArgumentParser& ap) { if ( (ap.argc() == 1) || ap.read("-h") || ap.read("--help") ) { usage(ap); return false; } std::string ts1; ossimArgumentParser::ossimParameter sp1(ts1); std::string ts2; ossimArgumentParser::ossimParameter sp2(ts2); if (ap.read("--center", sp1, sp2)) { m_centerGpt.lat = ossimString(ts1).toDouble(); m_centerGpt.lon = ossimString(ts2).toDouble(); m_centerGpt.hgt = 0.0; } if (ap.read("--dem", sp1)) m_demFile = ts1; if ( ap.read("--remap")) { m_remapToByte = true; } if ( ap.read("--lut", sp1) ) m_lutFile = ts1; if ( ap.read("--request-api", sp1)) { ofstream ofs ( ts1.c_str() ); printApiJson(ofs); ofs.close(); return false; } if ( ap.read("--request-api")) { printApiJson(cout); return false; } if (ap.read("--roi", sp1)) m_aoiRadius = ossimString(ts1).toDouble(); if (m_demFile.empty() && m_centerGpt.hasNans()) { ossimNotify(ossimNotifyLevel_WARN)<<"No DEM file nor center point provided. Cannot " <<"compute slope image."<<endl; usage(ap); return false; } // There should only be the required command line args left: if (ap.argc() != 2) { usage(ap); return false; } m_slopeFile = ap[1]; return initializeChain(); } bool ossimSlopeUtil::initializeChain() { // Establish connection to elevation data. Image handler (or combiner) returned in m_procChain: if (!m_demFile.empty()) { if (!loadDemFile()) return false; } else if (!loadElevDb()) return false; ossimRefPtr<ossimSlopeFilter> slope_filter = new ossimSlopeFilter(m_procChain.get()); slope_filter->setSlopeType(ossimSlopeFilter::NORMALIZED); m_procChain = slope_filter.get(); // If remap to one byte per pixel selected, insert remapper here: if (m_remapToByte || !m_lutFile.empty()) { ossimRefPtr<ossimScalarRemapper> sr = new ossimScalarRemapper; sr->connectMyInputTo(0, m_procChain.get()); m_procChain = sr.get(); sr->setOutputScalarType(OSSIM_UINT8); } // If LUT remap requested, insert here in the chain: if (!m_lutFile.empty()) { if (m_lutFile.isReadable()) { ossimRefPtr<ossimIndexToRgbLutFilter> lut = new ossimIndexToRgbLutFilter; lut->connectMyInputTo(0, m_procChain.get()); m_procChain = lut.get(); lut->setLut(m_lutFile); } else { ossimNotify(ossimNotifyLevel_WARN)<<"The LUT file specified, <"<<m_lutFile<<"> is " "not readbale. The LUT remap will be ignored."<<endl; } } m_procChain->initialize(); return true; } bool ossimSlopeUtil::loadDemFile() { m_procChain = ossimImageHandlerRegistry::instance()->open(m_demFile, true, false); if (!m_procChain.valid()) { ossimNotify(ossimNotifyLevel_FATAL) << "Could not open DEM file at <"<<m_demFile <<">. Aborting..."<<endl; return false; } return true; } bool ossimSlopeUtil::loadElevDb() { // Determine if default GSD needs to be computed. Query for target H so as to autoload cell: ossimElevManager* elevMgr = ossimElevManager::instance(); elevMgr->getHeightAboveEllipsoid(m_centerGpt); double gsd = elevMgr->getMeanSpacingMeters(); if (ossim::isnan(gsd)) { ossimNotify(ossimNotifyLevel_FATAL) << "Could not establish DEM GSD at center point " <<m_centerGpt<<". Verify that the elevation database provides coverage at this " <<"location."<<endl; return false; } // Establish output radius if not provided: ossimIrect viewRect(0, 0, 1023, 1023); if (m_aoiRadius == 0) { // The radius of interest can default given a GSD to achieve a specific output image size. m_aoiRadius = (viewRect.size().x + viewRect.size().y -2) * gsd / 4.0; } // Establish ground-space AOI rectangle: ossimDpt metersPerDeg (m_centerGpt.metersPerDegree()); double dlat = m_aoiRadius/metersPerDeg.y; double dlon = m_aoiRadius/metersPerDeg.x; ossimGrect gndRect (m_centerGpt.lat + dlat, m_centerGpt.lon - dlon, m_centerGpt.lat - dlat, m_centerGpt.lon + dlon); // Query elevation manager for cells providing needed coverage: std::vector<std::string> cells; elevMgr->getCellsForBounds(gndRect, cells); // Open a raster image for each elevation source being considered: ossimConnectableObject::ConnectableObjectList elevChains; std::vector<std::string>::iterator fname_iter = cells.begin(); while (fname_iter != cells.end()) { ossimRefPtr<ossimImageHandler> dem = ossimImageHandlerRegistry::instance()->open(*fname_iter); if (!dem.valid()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimHLZUtil::initElevSources() ERR: Cannot open DEM file at <" <<*fname_iter<<">\n"<< std::endl; return false; } elevChains.push_back(dem.get()); ++fname_iter; } // Establish the output image's projection geometry: ossimRefPtr<ossimEquDistCylProjection> mapProj = new ossimEquDistCylProjection(); mapProj->setOrigin(m_centerGpt); mapProj->setMetersPerPixel(ossimDpt(gsd, gsd)); ossimDpt degPerPixel(mapProj->getDecimalDegreesPerPixel()); mapProj->setElevationLookupFlag(false); mapProj->setUlTiePoints(gndRect.ul()); ossimRefPtr<ossimImageGeometry> productGeom = new ossimImageGeometry(0, mapProj.get()); ossimDpt viewPt; productGeom->worldToLocal(gndRect.ul(), viewPt); viewRect.set_ulx(ossim::round<ossim_int32, double>(viewPt.x)); viewRect.set_uly(ossim::round<ossim_int32, double>(viewPt.y)); productGeom->worldToLocal(gndRect.lr(), viewPt); viewRect.set_lrx(ossim::round<ossim_int32, double>(viewPt.x)); viewRect.set_lry(ossim::round<ossim_int32, double>(viewPt.y)); ossimIpt image_size(viewRect.width(), viewRect.height()); productGeom->setImageSize(image_size); // Now loop to add a renderer to each input cell to insure common output projection: ossimConnectableObject::ConnectableObjectList::iterator cell_iter = elevChains.begin(); while (cell_iter != elevChains.end()) { ossimImageSource* chain = (ossimImageSource*) cell_iter->get(); ossimRefPtr<ossimImageViewProjectionTransform> ivt = new ossimImageViewProjectionTransform( chain->getImageGeometry().get(), productGeom.get()); chain = new ossimImageRenderer(chain, ivt.get()); chain->initialize(); *cell_iter = chain; ++cell_iter; } // Finally create the combiner: m_procChain = new ossimImageMosaic(elevChains); return true; } bool ossimSlopeUtil::execute() { if (!m_procChain.valid()) { if (!initializeChain()) return false; } // Set up the writer: bool all_good = false; ossimRefPtr<ossimTiffWriter> tif_writer = new ossimTiffWriter(); tif_writer->setGeotiffFlag(true); tif_writer->setFilename(m_slopeFile); if (tif_writer.valid()) { tif_writer->connectMyInputTo(0, m_procChain.get()); ossimIrect viewRect; m_procChain->getImageGeometry()->getBoundingRect(viewRect); tif_writer->setAreaOfInterest(viewRect); all_good = tif_writer->execute(); if (all_good) ossimNotify(ossimNotifyLevel_INFO)<<"Output written to <"<<m_slopeFile<<">"<<endl; else { ossimNotify(ossimNotifyLevel_FATAL)<<"Error encountered writing out slope image to <" <<m_slopeFile<<">."<<endl; } } return all_good; } void ossimSlopeUtil::printApiJson(ostream& out) const { ossimFilename json_path (ossimPreferences::instance()->findPreference("ossim_share_directory")); json_path += "/ossim/util/ossimSlopeApi.json"; if (json_path.isReadable()) { char line[256]; ifstream ifs (json_path.chars()); ifs.getline(line, 256); while (ifs.good()) { out << line << endl; ifs.getline(line, 256); } ifs.close(); } }
32.346667
100
0.662737
rkanavath
d849e0dd94deb2ee024e2f9a8dd896a0b0502a2c
968
cpp
C++
text.cpp
hehichens/Mini-PhotoShop
b3d0bd89da7a8cf369ad98a9bc7b4cb0d0145a51
[ "Apache-2.0" ]
3
2021-06-09T03:19:25.000Z
2021-12-27T04:23:28.000Z
text.cpp
hehichens/Mini-PhotoShop
b3d0bd89da7a8cf369ad98a9bc7b4cb0d0145a51
[ "Apache-2.0" ]
null
null
null
text.cpp
hehichens/Mini-PhotoShop
b3d0bd89da7a8cf369ad98a9bc7b4cb0d0145a51
[ "Apache-2.0" ]
null
null
null
#include "graph_scene.h" #include <opencv2/imgproc/imgproc.hpp> #include <QGraphicsSceneMouseEvent> #include <QtCore> #include <opencv2/highgui.hpp> #include <iostream> #include <unistd.h> using std::string; using namespace cv; void GraphScreen::add_text(int mx,int my, int size,QString text_content){ std::cout<<"here add_text "<<size<<endl; QPainter painter(& *ScreenPic); //为这个QImage构造一个QPainter painter.setCompositionMode(QPainter::CompositionMode_SourceIn); QPen pen = painter.pen(); pen.setColor(Qt::white); QFont font = painter.font(); font.setBold(true);//加粗 font.setPixelSize(size);//改变字体大小 painter.setPen(pen); painter.setFont(font); painter.drawText(mx,my,text_content); } void GraphScreen::set_m_text(bool state){ m_text = state; qDebug()<<state; } void GraphScreen::set_text_size(int size){ text_size = size; } void GraphScreen::set_text_content(QString content){ text_content = content; }
25.473684
73
0.719008
hehichens
d84b98c24c424c30b717045c425aeaf4f67144fc
941
cpp
C++
Leetcode/res/Binary Tree Paths/1.cpp
AllanNozomu/CompetitiveProgramming
ac560ab5784d2e2861016434a97e6dcc44e26dc8
[ "MIT" ]
1
2022-03-04T16:06:41.000Z
2022-03-04T16:06:41.000Z
Leetcode/res/Binary Tree Paths/1.cpp
AllanNozomu/CompetitiveProgramming
ac560ab5784d2e2861016434a97e6dcc44e26dc8
[ "MIT" ]
null
null
null
Leetcode/res/Binary Tree Paths/1.cpp
AllanNozomu/CompetitiveProgramming
ac560ab5784d2e2861016434a97e6dcc44e26dc8
[ "MIT" ]
null
null
null
\* Author: allannozomu Runtime: 4 ms Memory: 11.5 MB*\ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void binaryTreecPathsRec(TreeNode* root, vector<string>& paths, string path){ if (root->left == NULL && root->right == NULL){ paths.push_back(path + to_string(root->val)); return; } if (root->left != NULL) binaryTreecPathsRec(root->left, paths, path + to_string(root->val) + "->"); if (root->right != NULL) binaryTreecPathsRec(root->right, paths, path + to_string(root->val) + "->"); } vector<string> binaryTreePaths(TreeNode* root) { vector<string> res; if (!root) return res; binaryTreecPathsRec(root, res, ""); return res; } };
27.676471
88
0.563231
AllanNozomu
d84e5a28b50382247dd241e3f938307d2ea248f5
2,015
cpp
C++
src/parser/expression_defs.cpp
pmenon/noisepage
73d50cdfa2e15b5d45e61b51e34672d10a851e14
[ "MIT" ]
971
2020-09-13T10:24:02.000Z
2022-03-31T07:02:51.000Z
src/parser/expression_defs.cpp
pmenon/noisepage
73d50cdfa2e15b5d45e61b51e34672d10a851e14
[ "MIT" ]
1,019
2018-07-20T23:11:10.000Z
2020-09-10T06:41:42.000Z
src/parser/expression_defs.cpp
pmenon/noisepage
73d50cdfa2e15b5d45e61b51e34672d10a851e14
[ "MIT" ]
318
2018-07-23T16:48:16.000Z
2020-09-07T09:46:31.000Z
#include "parser/expression_defs.h" #include <string> namespace noisepage::parser { std::string ExpressionTypeToShortString(ExpressionType type) { switch (type) { // clang-format off case ExpressionType::OPERATOR_PLUS: return "+"; case ExpressionType::OPERATOR_MINUS: return "-"; case ExpressionType::OPERATOR_MULTIPLY: return "*"; case ExpressionType::OPERATOR_DIVIDE: return "/"; case ExpressionType::COMPARE_EQUAL: return "="; case ExpressionType::COMPARE_NOT_EQUAL: return "!="; case ExpressionType::COMPARE_LESS_THAN: return "<"; case ExpressionType::COMPARE_GREATER_THAN: return ">"; case ExpressionType::COMPARE_LESS_THAN_OR_EQUAL_TO: return "<="; case ExpressionType::COMPARE_GREATER_THAN_OR_EQUAL_TO: return ">="; case ExpressionType::COMPARE_LIKE: return "~~"; case ExpressionType::COMPARE_NOT_LIKE: return "!~~"; case ExpressionType::COMPARE_IN: return "IN"; case ExpressionType::COMPARE_IS_DISTINCT_FROM: return "IS_DISTINCT_FROM"; case ExpressionType::CONJUNCTION_AND: return "AND"; case ExpressionType::CONJUNCTION_OR: return "OR"; case ExpressionType::AGGREGATE_COUNT: return "COUNT"; case ExpressionType::AGGREGATE_SUM: return "SUM"; case ExpressionType::AGGREGATE_MIN: return "MIN"; case ExpressionType::AGGREGATE_MAX: return "MAX"; case ExpressionType::AGGREGATE_AVG: return "AVG"; case ExpressionType::AGGREGATE_TOP_K: return "TOP_K"; case ExpressionType::AGGREGATE_HISTOGRAM: return "HISTOGRAM"; default: return ExpressionTypeToString(type); // clang-format on } } } // namespace noisepage::parser
51.666667
86
0.598015
pmenon
d8509208a3026d9a17a883853aeb591c29e8bda5
12,341
cpp
C++
sourceCode/textures/imgLoaderSaver.cpp
mdecourse/CoppeliaSimLib
934e65b4b6ea5a07d08919ae35c50fd3ae960ef2
[ "RSA-MD" ]
null
null
null
sourceCode/textures/imgLoaderSaver.cpp
mdecourse/CoppeliaSimLib
934e65b4b6ea5a07d08919ae35c50fd3ae960ef2
[ "RSA-MD" ]
null
null
null
sourceCode/textures/imgLoaderSaver.cpp
mdecourse/CoppeliaSimLib
934e65b4b6ea5a07d08919ae35c50fd3ae960ef2
[ "RSA-MD" ]
null
null
null
#include "imgLoaderSaver.h" #ifdef SIM_WITH_QT #include "tGAFormat.h" #include "stb_image.h" #include "ttUtil.h" #include "vVarious.h" #include <QImage> #include <QImageWriter> #include <QColor> #include <QtCore/QBuffer> #endif unsigned char* CImageLoaderSaver::load(const char* filename,int* resX,int* resY,int* colorComponents,int desiredColorComponents,int scaleTo) { // scaleTo is 0 by default (no scaling). ScaleTo should be a power of 2! #ifdef SIM_WITH_QT std::string ext(CTTUtil::getLowerCaseString(VVarious::splitPath_fileExtension(filename).c_str())); unsigned char* data=nullptr; if ((ext.compare("tga")==0)||(ext.compare("gif")==0)) { data=stbi_load(filename,resX,resY,colorComponents,desiredColorComponents); } else { QImage image; if (image.load(filename)) { if (image.hasAlphaChannel()) colorComponents[0]=4; else colorComponents[0]=3; resX[0]=image.width(); resY[0]=image.height(); data=new unsigned char[resX[0]*resY[0]*colorComponents[0]]; for (int j=0;j<resY[0];j++) { for (int i=0;i<resX[0];i++) { QRgb pixel=image.pixel(i,j); if (colorComponents[0]==3) { data[3*(j*resX[0]+i)+0]=(unsigned char)qRed(pixel); data[3*(j*resX[0]+i)+1]=(unsigned char)qGreen(pixel); data[3*(j*resX[0]+i)+2]=(unsigned char)qBlue(pixel); } else { data[4*(j*resX[0]+i)+0]=(unsigned char)qRed(pixel); data[4*(j*resX[0]+i)+1]=(unsigned char)qGreen(pixel); data[4*(j*resX[0]+i)+2]=(unsigned char)qBlue(pixel); data[4*(j*resX[0]+i)+3]=(unsigned char)qAlpha(pixel); } } } } } if ((scaleTo!=0)&&(data!=nullptr)) { unsigned char* img=data; int s[2]; s[0]=resX[0]; s[1]=resY[0]; int ns[2]; ns[0]=resX[0]; ns[1]=resY[0]; for (int i=0;i<2;i++) { // set the side size to a power of 2 and smaller or equal to 'scaleTo': int v=s[i]; v&=(32768-1); unsigned short tmp=32768; while (tmp!=1) { if (v&tmp) { v=tmp; break; } tmp/=2; } if (v!=s[i]) v=v*2; while (v>scaleTo) v/=2; ns[i]=v; } if ((ns[0]!=s[0])||(ns[1]!=s[1])) { data=getScaledImage(img,colorComponents[0],s[0],s[1],ns[0],ns[1]); delete[] img; resX[0]=ns[0]; resY[0]=ns[1]; } } return(data); #else return(nullptr); #endif } unsigned char* CImageLoaderSaver::loadQTgaImageData(const char* fileAndPath,int& resX,int& resY,bool& rgba,unsigned char invisibleColor[3],int bitsPerPixel[1]) { #ifdef SIM_WITH_QT unsigned char* data=CTGAFormat::getQ_ImageData(fileAndPath,resX,resY,rgba,invisibleColor,bitsPerPixel); return(data); #else return(nullptr); #endif } unsigned char* CImageLoaderSaver::getScaledImage(const unsigned char* originalImg,int colorComponents,int originalX,int originalY,int newX,int newY) { #ifdef SIM_WITH_QT QImage::Format f=QImage::Format_RGB888; unsigned char* im=new unsigned char[originalX*originalY*colorComponents]; if (colorComponents==4) { f=QImage::Format_ARGB32; for (int i=0;i<originalX*originalY;i++) { // from rgba to bgra (corrected on 9/9/2914) im[4*i+0]=originalImg[4*i+2]; im[4*i+1]=originalImg[4*i+1]; im[4*i+2]=originalImg[4*i+0]; im[4*i+3]=originalImg[4*i+3]; } } else { for (int i=0;i<originalX*originalY;i++) { im[3*i+0]=originalImg[3*i+0]; im[3*i+1]=originalImg[3*i+1]; im[3*i+2]=originalImg[3*i+2]; } } QImage image(im,originalX,originalY,originalX*colorComponents,f); unsigned char* nim=new unsigned char[newX*newY*colorComponents]; QImage nimage(image.scaled(newX,newY,Qt::IgnoreAspectRatio,Qt::SmoothTransformation)); for (int j=0;j<newY;j++) { for (int i=0;i<newX;i++) { QRgb pixel=nimage.pixel(i,j); if (colorComponents==3) { nim[3*(j*newX+i)+0]=(unsigned char)qRed(pixel); nim[3*(j*newX+i)+1]=(unsigned char)qGreen(pixel); nim[3*(j*newX+i)+2]=(unsigned char)qBlue(pixel); } else { nim[4*(j*newX+i)+0]=(unsigned char)qRed(pixel); nim[4*(j*newX+i)+1]=(unsigned char)qGreen(pixel); nim[4*(j*newX+i)+2]=(unsigned char)qBlue(pixel); nim[4*(j*newX+i)+3]=(unsigned char)qAlpha(pixel); } } } delete[] im; return(nim); #else return(nullptr); #endif } bool CImageLoaderSaver::transformImage(unsigned char* img,int resX,int resY,int options) { int comp=3; if (options&1) comp=4; unsigned char* img2=new unsigned char[resX*resY*comp]; for (int i=0;i<resX*resY*comp;i++) img2[i]=img[i]; for (int x=0;x<resX;x++) { int x2=x; if (options&2) x2=resX-1-x; for (int y=0;y<resY;y++) { int y2=y; if (options&4) y2=resY-1-y; img[comp*(x+y*resX)+0]=img2[comp*(x2+y2*resX)+0]; img[comp*(x+y*resX)+1]=img2[comp*(x2+y2*resX)+1]; img[comp*(x+y*resX)+2]=img2[comp*(x2+y2*resX)+2]; if (comp==4) img[comp*(x+y*resX)+3]=img2[comp*(x2+y2*resX)+3]; } } delete[] img2; return(true); } unsigned char* CImageLoaderSaver::getScaledImage(const unsigned char* originalImg,const int resolIn[2],int resolOut[2],int options) { #ifdef SIM_WITH_QT int compIn=3; int compOut=3; if (options&1) compIn=4; if (options&2) compOut=4; QImage::Format f=QImage::Format_RGB888; unsigned char* im=new unsigned char[resolIn[0]*resolIn[1]*compIn]; if (compIn==4) { f=QImage::Format_ARGB32; for (int i=0;i<resolIn[0]*resolIn[1];i++) { // from rgba to bgra (corrected on 9/9/2914) im[4*i+0]=originalImg[4*i+2]; im[4*i+1]=originalImg[4*i+1]; im[4*i+2]=originalImg[4*i+0]; im[4*i+3]=originalImg[4*i+3]; } } else { for (int i=0;i<resolIn[0]*resolIn[1];i++) { im[3*i+0]=originalImg[3*i+0]; im[3*i+1]=originalImg[3*i+1]; im[3*i+2]=originalImg[3*i+2]; } } QImage image(im,resolIn[0],resolIn[1],resolIn[0]*compIn,f); Qt::AspectRatioMode aspectRatio=Qt::IgnoreAspectRatio; if ((options&12)==4) aspectRatio=Qt::KeepAspectRatio; if ((options&12)==8) aspectRatio=Qt::KeepAspectRatioByExpanding; Qt::TransformationMode transform=Qt::SmoothTransformation; if (options&16) transform=Qt::FastTransformation; QImage nimage(image.scaled(resolOut[0],resolOut[1],aspectRatio,transform)); resolOut[0]=nimage.width(); resolOut[1]=nimage.height(); unsigned char* nim=new unsigned char[resolOut[0]*resolOut[1]*compOut]; for (int j=0;j<resolOut[1];j++) { for (int i=0;i<resolOut[0];i++) { QRgb pixel=nimage.pixel(i,j); if (compOut==3) { nim[3*(j*resolOut[0]+i)+0]=(unsigned char)qRed(pixel); nim[3*(j*resolOut[0]+i)+1]=(unsigned char)qGreen(pixel); nim[3*(j*resolOut[0]+i)+2]=(unsigned char)qBlue(pixel); } else { nim[4*(j*resolOut[0]+i)+0]=(unsigned char)qRed(pixel); nim[4*(j*resolOut[0]+i)+1]=(unsigned char)qGreen(pixel); nim[4*(j*resolOut[0]+i)+2]=(unsigned char)qBlue(pixel); nim[4*(j*resolOut[0]+i)+3]=(unsigned char)qAlpha(pixel); } } } delete[] im; return(nim); #else return(nullptr); #endif } bool CImageLoaderSaver::save(const unsigned char* data,const int resolution[2],int options,const char* filename,int quality,std::string* buffer) { bool retVal=false; #ifdef SIM_WITH_QT unsigned char *buff=nullptr; QImage::Format format=QImage::Format_ARGB32; buff=new unsigned char[4*resolution[0]*resolution[1]]; int bytesPerPixel=4; for (int i=0;i<resolution[0];i++) { for (int j=0;j<resolution[1];j++) { if ((options&1)==0) { // input img provided as rgb if ((options&2)==0) { bytesPerPixel=3; format=QImage::Format_RGB888; buff[3*(resolution[0]*j+i)+0]=data[3*(resolution[0]*(resolution[1]-j-1)+i)+0]; buff[3*(resolution[0]*j+i)+1]=data[3*(resolution[0]*(resolution[1]-j-1)+i)+1]; buff[3*(resolution[0]*j+i)+2]=data[3*(resolution[0]*(resolution[1]-j-1)+i)+2]; } else { bytesPerPixel=1; format=QImage::Format_Grayscale8; buff[resolution[0]*j+i]=data[resolution[0]*(resolution[1]-j-1)+i]; } } else { // input img provided as rgba buff[4*(resolution[0]*j+i)+0]=data[4*(resolution[0]*(resolution[1]-j-1)+i)+2]; buff[4*(resolution[0]*j+i)+1]=data[4*(resolution[0]*(resolution[1]-j-1)+i)+1]; buff[4*(resolution[0]*j+i)+2]=data[4*(resolution[0]*(resolution[1]-j-1)+i)+0]; buff[4*(resolution[0]*j+i)+3]=data[4*(resolution[0]*(resolution[1]-j-1)+i)+3]; } } } { QImage image(buff,resolution[0],resolution[1],resolution[0]*bytesPerPixel,format); if (buffer==nullptr) retVal=image.save(filename,0,quality); else { if (filename[0]=='.') { QByteArray ba; QBuffer qbuffer(&ba); qbuffer.open(QIODevice::WriteOnly); retVal=image.save(&qbuffer,filename+1); if (retVal) buffer->assign(ba.data(),ba.data()+ba.size()); } } } delete[] buff; #endif return(retVal); } unsigned char* CImageLoaderSaver::load(int resolution[2],int options,const char* filename,void* reserved) { unsigned char* retVal=nullptr; #ifdef SIM_WITH_QT QImage image; bool loadRes=false; if (reserved!=nullptr) loadRes=image.loadFromData((const unsigned char*)filename,((int*)reserved)[0]); else loadRes=image.load(filename,0); if (loadRes) { if (options&1) retVal=new unsigned char[image.height()*image.width()*4]; else retVal=new unsigned char[image.height()*image.width()*3]; resolution[0]=image.width(); resolution[1]=image.height(); for (int x=0;x<image.width();++x) { for (int y=0;y<image.height();++y) { QColor col(image.pixel(x,y)); if (options&1) { retVal[4*(resolution[0]*(resolution[1]-y-1)+x)+0]=col.red(); retVal[4*(resolution[0]*(resolution[1]-y-1)+x)+1]=col.green(); retVal[4*(resolution[0]*(resolution[1]-y-1)+x)+2]=col.blue(); retVal[4*(resolution[0]*(resolution[1]-y-1)+x)+3]=col.alpha(); } else { retVal[3*(resolution[0]*(resolution[1]-y-1)+x)+0]=col.red(); retVal[3*(resolution[0]*(resolution[1]-y-1)+x)+1]=col.green(); retVal[3*(resolution[0]*(resolution[1]-y-1)+x)+2]=col.blue(); } } } } #endif return(retVal); }
33.444444
159
0.51333
mdecourse
d851b73d72148dc84f24876dd7036dca78269130
9,947
cpp
C++
ortc/services/cpp/services_DHPublicKey.cpp
ortclib/ortclib-services-cpp
f770d97044b1ffbff04b61fa1488eedc8ddc66e4
[ "BSD-2-Clause" ]
2
2016-10-12T09:16:32.000Z
2016-10-13T03:49:47.000Z
ortc/services/cpp/services_DHPublicKey.cpp
ortclib/ortclib-services-cpp
f770d97044b1ffbff04b61fa1488eedc8ddc66e4
[ "BSD-2-Clause" ]
2
2017-11-24T09:18:45.000Z
2017-11-24T09:20:53.000Z
ortc/services/cpp/services_DHPublicKey.cpp
ortclib/ortclib-services-cpp
f770d97044b1ffbff04b61fa1488eedc8ddc66e4
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (c) 2014, Hookflash Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ #include <ortc/services/internal/services_DHPublicKey.h> #include <ortc/services/internal/services_DHKeyDomain.h> #include <ortc/services/IHelper.h> #include <zsLib/XML.h> #include <zsLib/eventing/IHasher.h> namespace ortc { namespace services { ZS_DECLARE_SUBSYSTEM(ortc_services) } } namespace ortc { namespace services { namespace internal { using CryptoPP::AutoSeededRandomPool; using namespace zsLib::XML; //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark IDHPublicKeyForDHPublicKey #pragma mark //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark DHPublicKey #pragma mark //----------------------------------------------------------------------- DHPublicKey::DHPublicKey(const make_private &) { ZS_LOG_DEBUG(log("created")) } //----------------------------------------------------------------------- DHPublicKey::~DHPublicKey() { if(isNoop()) return; ZS_LOG_DEBUG(log("destroyed")) } //----------------------------------------------------------------------- DHPublicKeyPtr DHPublicKey::convert(IDHPublicKeyPtr publicKey) { return ZS_DYNAMIC_PTR_CAST(DHPublicKey, publicKey); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark DHPublicKey => IDHPublicKey #pragma mark //----------------------------------------------------------------------- ElementPtr DHPublicKey::toDebug(IDHPublicKeyPtr keyDomain) { if (!keyDomain) return ElementPtr(); return convert(keyDomain)->toDebug(); } //----------------------------------------------------------------------- DHPublicKeyPtr DHPublicKey::load( const SecureByteBlock &staticPublicKey, const SecureByteBlock &ephemeralPublicKey ) { DHPublicKeyPtr pThis(make_shared<DHPublicKey>(make_private{})); pThis->mStaticPublicKey.Assign(staticPublicKey); pThis->mEphemeralPublicKey.Assign(ephemeralPublicKey); if (ZS_IS_LOGGING(Trace)) { ZS_LOG_TRACE(pThis->debug("loaded")) } else { ZS_LOG_DEBUG(pThis->log("loaded")) } return pThis; } //----------------------------------------------------------------------- void DHPublicKey::save( SecureByteBlock *outStaticPublicKey, SecureByteBlock *outEphemeralPublicKey ) const { ZS_LOG_TRACE(log("save called")) if (outStaticPublicKey) { (*outStaticPublicKey).Assign(mStaticPublicKey); } if (outEphemeralPublicKey) { (*outEphemeralPublicKey).Assign(mEphemeralPublicKey); } } //----------------------------------------------------------------------- String DHPublicKey::getFingerprint() const { return IHelper::convertToHex(*IHasher::hash(mStaticPublicKey, IHasher::hmacSHA1(mEphemeralPublicKey))); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark DHPublicKey => IDHPublicKeyForDHPrivateKey #pragma mark //----------------------------------------------------------------------- const SecureByteBlock &DHPublicKey::getStaticPublicKey() const { return mStaticPublicKey; } //----------------------------------------------------------------------- const SecureByteBlock &DHPublicKey::getEphemeralPublicKey() const { return mEphemeralPublicKey; } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark DHPublicKey => (internal) #pragma mark //----------------------------------------------------------------------- Log::Params DHPublicKey::log(const char *message) const { ElementPtr objectEl = Element::create("DHPublicKey"); IHelper::debugAppend(objectEl, "id", mID); return Log::Params(message, objectEl); } //----------------------------------------------------------------------- Log::Params DHPublicKey::debug(const char *message) const { return Log::Params(message, toDebug()); } //----------------------------------------------------------------------- ElementPtr DHPublicKey::toDebug() const { ElementPtr resultEl = Element::create("DHPublicKey"); IHelper::debugAppend(resultEl, "id", mID); IHelper::debugAppend(resultEl, "static public key", IHelper::convertToHex(mStaticPublicKey, true)); IHelper::debugAppend(resultEl, "ephemeral public key", IHelper::convertToHex(mEphemeralPublicKey, true)); return resultEl; } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark IDHPublicKeyFactory #pragma mark //----------------------------------------------------------------------- IDHPublicKeyFactory &IDHPublicKeyFactory::singleton() { return DHPublicKeyFactory::singleton(); } //----------------------------------------------------------------------- DHPublicKeyPtr IDHPublicKeyFactory::load( const SecureByteBlock &staticPublicKey, const SecureByteBlock &ephemeralPublicKey ) { if (this) {} return DHPublicKey::load(staticPublicKey, ephemeralPublicKey); } } //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- #pragma mark #pragma mark IDHPublicKey #pragma mark //------------------------------------------------------------------------- ElementPtr IDHPublicKey::toDebug(IDHPublicKeyPtr keyDomain) { return internal::DHPublicKey::toDebug(keyDomain); } //------------------------------------------------------------------------- IDHPublicKeyPtr IDHPublicKey::load( const SecureByteBlock &staticPublicKey, const SecureByteBlock &ephemeralPublicKey ) { return internal::IDHPublicKeyFactory::singleton().load(staticPublicKey, ephemeralPublicKey); } } }
39.472222
113
0.41701
ortclib
d85306e3e2c87156f925039aeee4b27cf7bb7a15
3,509
cc
C++
test/unit/Eval/EvalSubgoalTest.cc
mnowotnik/fovris
82f692743fa6c96fef05041e686d716b03c22f07
[ "BSD-3-Clause" ]
4
2017-01-04T17:22:55.000Z
2018-12-08T02:10:18.000Z
test/unit/Eval/EvalSubgoalTest.cc
Mike-Now/fovris
82f692743fa6c96fef05041e686d716b03c22f07
[ "BSD-3-Clause" ]
null
null
null
test/unit/Eval/EvalSubgoalTest.cc
Mike-Now/fovris
82f692743fa6c96fef05041e686d716b03c22f07
[ "BSD-3-Clause" ]
1
2022-03-24T05:26:13.000Z
2022-03-24T05:26:13.000Z
#include "KB/KBHeadLiteral.h" #include "Eval/EvalSubgoal.h" #include "Eval/TestUtils.h" #include "thirdparty/Catch/include/catch.hpp" #include <string> using namespace fovris; TEST_CASE("Check subgoal evaluation result", "[EvalSubgoal]") { // given unsigned relId = 0xDEADBEEF; KBRelation relation{ relId, {TermType::Integer, TermType::Integer, TermType::Integer}}; KBGroundTerm Id1{10}, Id2{20}, Id3{30}; KBTuple tup{{Id1, Id2, Id1}, TruthValue::True}; KBTuple tup2{{Id1, Id2, Id3}, TruthValue::True}; relation.addTuple(tup); relation.addTuple(tup2); KBVarTerm X{1}, Y{2}, Z{5}; KBRuleLiteral kbr{relId, {X, Y, X}, TruthValue::True}; SECTION("Check EvalSubgoalFirst") { auto evalFirst = CreateEvalSubgoalFirst(kbr, EvalDestination{Y, X}); // then auto result = evalFirst->evaluate({}, relation.getFacts()); REQUIRE(result.size() == 1); REQUIRE(result[0].getTerms().length() == 2); REQUIRE(result[0].getTerms()[0] == Id2); REQUIRE(result[0].getTerms()[1] == Id1); } SECTION("Check EvalSubgoalNext") { KBRuleLiteral tmpKbr{relId, {X, Y, Z}, TruthValue::True}; auto evalNext = CreateEvalSubgoalNext(tmpKbr, kbr, {Y, Z}); // given // then KBTuple tmpTup = {{Id1, Id2, Id3}, TruthValue::True}; auto result = evalNext->evaluate({tmpTup}, relation.getFacts()); REQUIRE(result.size() == 1); REQUIRE(result[0].getTerms().length() == 2); REQUIRE(result[0].getTerms()[0] == Id2); REQUIRE(result[0].getTerms()[1] == Id3); } } TEST_CASE("Check subgoal with function evaluation", "[EvalSubgoal]") { unsigned relId = 0; TermMapper termMapper; KBGroundTerm foo{termMapper.internTerm("foo")}; KBGroundTerm bar{termMapper.internTerm("bar")}; KBGroundTerm baz{termMapper.internTerm("baz")}; KBRelation relation{relId, {TermType::Id, TermType::Id, TermType::Id}}; relation.addFact({foo, bar, baz}, TruthValue::True); relation.addFact({foo, foo, baz}, TruthValue::True); KBVarTerm X{1}, Y{2}, Z{5}; KBRuleLiteral kbr{relId, {X, Y, Z}, TruthValue::True}; // function predicates matche std::vector<KBRuleFunction> functions; functions.emplace_back([](const Array<Term> &terms) -> bool { return terms[0].get<std::string>() == "foo" && terms[1].get<std::string>() == "bar"; }, std::vector<KBTerm>{X, Y}, std::vector<TermType>{TermType::Id, TermType::Id}); KBRuleLiteral tmpKbr{relId, {X, Y, Z}, TruthValue::True}; auto evalNext = CreateEvalSubgoalLast(tmpKbr, kbr, {Y, Z}, functions, termMapper); KBTuple tmpTup = {{foo, bar, baz}, TruthValue::True}; auto result = evalNext->evaluate({tmpTup}, relation.getFacts()); REQUIRE(result.size() == 1); // function predicates don't match functions.emplace_back([](const Array<Term> &terms) -> bool { return terms[0].get<std::string>() == "baz"; }, std::vector<KBTerm>{X, Y}, std::vector<TermType>{TermType::Id, TermType::Id}); evalNext = CreateEvalSubgoalLast(tmpKbr, kbr, {Y, Z}, functions, termMapper); result = evalNext->evaluate({tmpTup}, relation.getFacts()); REQUIRE(result.size() == 0); }
34.401961
78
0.588487
mnowotnik
d855695e7f9b2b5d51d12e6e80b1e1bbd4a7b389
1,362
cpp
C++
SDIZO_Graphs/my_graph.cpp
michaltkacz/SDIZO_Graphs
085a9be87ff96826ca2a6dec1f7206ebabaca341
[ "MIT" ]
null
null
null
SDIZO_Graphs/my_graph.cpp
michaltkacz/SDIZO_Graphs
085a9be87ff96826ca2a6dec1f7206ebabaca341
[ "MIT" ]
null
null
null
SDIZO_Graphs/my_graph.cpp
michaltkacz/SDIZO_Graphs
085a9be87ff96826ca2a6dec1f7206ebabaca341
[ "MIT" ]
null
null
null
#include "my_graph.h" #include "graph_exception.h" #include "my_rand.h" #include <fstream> #include <iomanip> void my_graph::random() { const int v_number = my_rand::random_int(min_vert, max_vert); const int density = my_rand::random_int(min_dens, max_dens); random(v_number, density); } void my_graph::random(int v_number, int density) { if (v_number < min_vert || v_number >= max_vert) { std::string msg = "Liczba wierzcholkow poza zakresem! ("; msg += std::to_string(min_vert); msg += "-"; msg += std::to_string(max_vert-1); msg += ")"; throw graph_exception(msg.c_str()); } if(density < min_dens || density >= max_dens) { std::string msg = "Gestosc poza zakresem! ("; msg += std::to_string(min_dens); msg += "-"; msg += std::to_string(max_dens-1); msg += ")"; throw graph_exception(msg.c_str()); } } void my_graph::load_from_file(const std::string& file_name) { std::ifstream fin(file_name); if (fin.is_open()) { int e = 0; int v = 0; int v_start = 0; int v_end = 0; int w = 0; fin >> e; fin >> v; try { init(v, e); while (!fin.eof()) { fin >> v_start; fin >> v_end; fin >> w; add_edge(v_start, v_end, w); } } catch (graph_exception& exc) { fin.close(); throw exc; } fin.close(); } else { throw graph_exception("Podany plik nie istnieje!"); } }
17.921053
62
0.61674
michaltkacz
d858b4d2863db23ed4f62818c5eaf13a6d571930
2,115
cpp
C++
uppsrc/ide/Debuggers/GdbUtils.cpp
UltimateScript/Forgotten
ac59ad21767af9628994c0eecc91e9e0e5680d95
[ "BSD-3-Clause" ]
null
null
null
uppsrc/ide/Debuggers/GdbUtils.cpp
UltimateScript/Forgotten
ac59ad21767af9628994c0eecc91e9e0e5680d95
[ "BSD-3-Clause" ]
null
null
null
uppsrc/ide/Debuggers/GdbUtils.cpp
UltimateScript/Forgotten
ac59ad21767af9628994c0eecc91e9e0e5680d95
[ "BSD-3-Clause" ]
null
null
null
#include "GdbUtils.h" #include <memory> #include <ide/Core/Logger.h> #include <ide/Common/CommandLineOptions.h> using namespace Upp; One<IGdbUtils> GdbUtilsFactory::Create() { #if defined(PLATFORM_WIN32) return MakeOne<GdbWindowsUtils>(); #elif defined(PLATFORM_POSIX) return MakeOne<GdbPosixUtils>(); #endif } #if defined(PLATFORM_WIN32) #define METHOD_NAME UPP_METHOD_NAME("GdbWindowsUtils") using DeleteHandleFun = std::function<void(HANDLE)>; static void DeleteHandle(HANDLE handle) { if (handle) { CloseHandle(handle); } } String GdbWindowsUtils::BreakRunning(int pid) { std::unique_ptr<void, DeleteHandleFun> handle(OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid), &DeleteHandle); if(!handle) return String().Cat() << "Failed to open process associated with " << pid << " PID."; if(Is64BitIde() && !Is64BitProcess(handle.get())) { auto path = String().Cat() << GetExeFolder() << "\\" << GetExeTitle() << "32.exe"; auto cmd = String().Cat() << path << " " << COMMAND_LINE_GDB_DEBUG_BREAK_PROCESS_OPTION << " " << pid; String out; if(Sys(cmd, out) == COMMAND_LINE_GDB_DEBUG_BREAK_PROCESS_FAILURE_STATUS) { Logd() << METHOD_NAME << cmd; return String().Cat() << "Failed to interrupt process via 32-bit TheIDE. Output from command is \"" << out << "\"."; } return ""; } if (!DebugBreakProcess(handle.get())) return String().Cat() << "Failed to break process associated with " << pid << " PID."; return ""; } bool GdbWindowsUtils::Is64BitIde() const { return sizeof(void*) == 8; } bool GdbWindowsUtils::Is64BitProcess(HANDLE handle) const { BOOL is_wow_64 = FALSE; if(!IsWow64Process(handle, &is_wow_64)) { Loge() << METHOD_NAME << "Failed to check that process is under wow64 emulation layer."; } return !is_wow_64; } #undef METHOD_NAME #elif defined(PLATFORM_POSIX) String GdbPosixUtils::BreakRunning(int pid) { if(kill(pid, SIGINT) == -1) return String().Cat() << "Failed to interrupt process associated with " << pid << " PID."; return ""; } #endif
24.593023
120
0.661466
UltimateScript
d858f20cd9418ed569a886d53eecf7466c64150e
4,141
hpp
C++
include/seqan3/core/simd/simd.hpp
FirstLoveLife/seqan3
ac2e983e0a576515c13ebb2c851c43c1eba1ece1
[ "BSD-3-Clause" ]
null
null
null
include/seqan3/core/simd/simd.hpp
FirstLoveLife/seqan3
ac2e983e0a576515c13ebb2c851c43c1eba1ece1
[ "BSD-3-Clause" ]
null
null
null
include/seqan3/core/simd/simd.hpp
FirstLoveLife/seqan3
ac2e983e0a576515c13ebb2c851c43c1eba1ece1
[ "BSD-3-Clause" ]
null
null
null
// ============================================================================ // SeqAn - The Library for Sequence Analysis // ============================================================================ // // Copyright (c) 2006-2018, Knut Reinert & Freie Universitaet Berlin // Copyright (c) 2016-2018, Knut Reinert & MPI Molekulare Genetik // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Knut Reinert or the FU Berlin nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. // // ============================================================================ /*!\file * \brief Contains seqan3::simd::simd_type * \author Marcel Ehrhardt <marcel.ehrhardt AT fu-berlin.de> */ #pragma once #include <seqan3/core/simd/detail/default_simd_backend.hpp> namespace seqan3 { inline namespace simd { /*!\brief seqan3::simd::simd_type encapsulates simd vector types, which can be manipulated * by simd operations. * \ingroup simd * \tparam scalar_t The underlying type of a simd vector * \tparam length The number of packed values in a simd vector * \tparam simd_backend The simd backend to use, e.g. * seqan3::detail::builtin_simd * * \include test/snippet/core/simd/simd.cpp * \attention * seqan3::simd::simd_type may not support *float* types depending on the selected backend. * * All implementations support *[u]intX_t* types, e.g. *uint8_t*. * * \par Helper types * seqan3::simd::simd_type_t as a shorthand for seqan3::simd::simd_type::type * \sa https://en.wikipedia.org/wiki/SIMD What is SIMD conceptually? * \sa https://en.wikipedia.org/wiki/Streaming_SIMD_Extensions Which SIMD architectures exist? * \sa https://gcc.gnu.org/onlinedocs/gcc/Vector-Extensions.html Underlying technique of *seqan3::detail::builtin_simd types*. * \sa https://github.com/edanor/umesimd Underlying library of *seqan3::detail::ume_simd* types. * \sa https://software.intel.com/sites/landingpage/IntrinsicsGuide Instruction sets and their low-level intrinsics. */ template <typename scalar_t, size_t length = detail::default_simd_length<scalar_t, detail::default_simd_backend>, typename simd_backend = detail::default_simd_backend<scalar_t, length>> struct simd_type : simd_backend { //!\brief The actual simd type. using type = typename simd_backend::type; }; //!\brief Helper type of seqan3::simd::simd_type //!\ingroup simd template <typename scalar_t, size_t length = detail::default_simd_length<scalar_t, detail::default_simd_backend>, typename simd_backend = detail::default_simd_backend<scalar_t, length>> using simd_type_t = typename simd_type<scalar_t, length, simd_backend>::type; } // inline namespace simd } // namespace seqan3
45.505495
126
0.702729
FirstLoveLife
d85f4e78725f54a82f55b1a2fa66d9ee72a4c7f3
3,978
cpp
C++
src/threads.cpp
yanmingsohu/PlayJS
2f9e015d0ec38f9613aa6915c5289a815bb5a52f
[ "Apache-2.0" ]
1
2019-09-03T19:13:54.000Z
2019-09-03T19:13:54.000Z
src/threads.cpp
yanmingsohu/PlayJS
2f9e015d0ec38f9613aa6915c5289a815bb5a52f
[ "Apache-2.0" ]
null
null
null
src/threads.cpp
yanmingsohu/PlayJS
2f9e015d0ec38f9613aa6915c5289a815bb5a52f
[ "Apache-2.0" ]
null
null
null
#include "threads.h" #include "export-js.h" #include "fs.h" #include "util.h" #include "vm.h" #include <map> #include <mutex> using std::map; using std::thread; using std::string; using std::mutex; using std::lock_guard; typedef map<threadId, thread*> ThreadMap; static volatile int nextId = 0x10; static mutex lock_map; static ThreadMap tmap; static void freeThread(threadId* _id) { lock_guard<mutex> guard(lock_map); threadId id = reinterpret_cast<threadId>(_id); tmap.erase((threadId)id); } static string& operator+(string& s, int i) { return s.append(std::to_string(i)); } void loadScript(string& filename, threadId id) { LocalResource<threadId> freeThreadHandle(reinterpret_cast<threadId*>(id), freeThread); println("Start Script '"+ filename +"'", id); std::string code; if (FAILED == readTxtFile(filename, code)) { println("Read '"+ filename +"' error", id); return; } VM vm(id); installJsLibrary(&vm); JsErrorCode r = vm.loadModule(0, filename, code); if (r) { println("Load Module '"+ filename +"' failed code: "+ r, id, LERROR); println(parseJsErrCode(r), id, LERROR); } LocalVal err = vm.checkError(); if (err.notNull()) { println("Exit on failed: "+ errorStack(err), id, LERROR); } unstallJsLIbrary(&vm); println("Script '"+ filename+ "' Exit", id); } threadId loadScriptInNewThread(string& fileName) { lock_guard<mutex> guard(lock_map); threadId id = nextId++; thread* newThread = new thread(loadScript, fileName, id); tmap.insert(ThreadMap::value_type(id, newThread)); return id; } thread* getThread(threadId i) { lock_guard<mutex> guard(lock_map); auto p = tmap.find(i); if (p == tmap.end()) { return 0; } return p->second; } void joinAll() { println(string("Running Thread: ")+ tmap.size()); lock_map.lock(); for (auto it = tmap.begin(); it != tmap.end(); ++it) { // // 当线程运行时可能会启动新的线程, 交叉锁可以防止死锁. // lock_map.unlock(); println(std::string("Wait thread [id:")+ (it->first) +"]"); it->second->join(); lock_map.lock(); } lock_map.unlock(); } static JsValueRef js_run(JsValueRef callee, JsValueRef *args, unsigned short ac, JsNativeFunctionInfo *info, void *d) { if (ac != 2) { pushException("bad arguments, run(scriptFilePath)"); return 0; } LocalVal filenameArg(args[1]); string filename = filenameArg.toString(); threadId id = loadScriptInNewThread(filename); return wrapJs(id); } static JsValueRef js_sleep(JsValueRef callee, JsValueRef *args, unsigned short ac, JsNativeFunctionInfo *info, void *d) { if (ac != 2) { pushException("bad arguments, sleep(ms)"); return 0; } int time = intValue(args[1]); if (time > 0) { std::this_thread::sleep_for( std::chrono::duration<int, std::milli>(time)); } return 0; } static JsValueRef js_running(JsValueRef callee, JsValueRef *args, unsigned short ac, JsNativeFunctionInfo *info, void *d) { if (ac != 2) { pushException("bad arguments, get(threadid)"); return 0; } int id = intValue(args[1]); return wrapJs(0 != getThread(id)); } static JsValueRef js_id(JsValueRef callee, JsValueRef *args, unsigned short ac, JsNativeFunctionInfo *info, void *id) { return wrapJs(reinterpret_cast<threadId>(id)); } void installThread(VM* vm) { LocalVal thread = vm->createObject(); vm->getGlobal().put("thread", thread); void * id = reinterpret_cast<void*>(vm->thread()); DEF_JS_FUNC(vm, id, thread, id, js_id); DEF_JS_FUNC(vm, 0, thread, run, js_run); DEF_JS_FUNC(vm, 0, thread, sleep, js_sleep); DEF_JS_FUNC(vm, 0, thread, wait, js_sleep); DEF_JS_FUNC(vm, 0, thread, running, js_running); }
25.177215
90
0.616642
yanmingsohu
d8711fe5a8b2142a73751d6580651b63e075013b
9,749
cpp
C++
src/wrappers/src/mfx_gst_frame_constructor.cpp
AntonGrishin/gstreamer-plugins
6d86897e02b525da4bf1d3f8b4bb6472cc72eb2b
[ "BSD-3-Clause" ]
20
2016-08-06T02:31:53.000Z
2022-01-24T13:29:41.000Z
src/wrappers/src/mfx_gst_frame_constructor.cpp
AntonGrishin/gstreamer-plugins
6d86897e02b525da4bf1d3f8b4bb6472cc72eb2b
[ "BSD-3-Clause" ]
5
2016-08-01T15:35:36.000Z
2021-07-15T10:33:59.000Z
src/wrappers/src/mfx_gst_frame_constructor.cpp
AntonGrishin/gstreamer-plugins
6d86897e02b525da4bf1d3f8b4bb6472cc72eb2b
[ "BSD-3-Clause" ]
14
2016-08-18T23:42:06.000Z
2021-05-16T22:06:59.000Z
/********************************************************************************** Copyright (C) 2005-2019 Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************************/ #include "mfx_defs.h" #include "mfx_gst_debug.h" #include "mfx_gst_frame_constructor.h" #include "mfx_utils.h" #undef MFX_DEBUG_MODULE_NAME #define MFX_DEBUG_MODULE_NAME "mfx_gst_frame_constructor" /*------------------------------------------------------------------------------*/ IMfxGstFrameConstuctor::IMfxGstFrameConstuctor(): m_bs_state(MfxGstBS_HeaderAwaiting) { MFX_DEBUG_TRACE_FUNC; } /*------------------------------------------------------------------------------*/ IMfxGstFrameConstuctor::~IMfxGstFrameConstuctor(void) { MFX_DEBUG_TRACE_FUNC; if (buffered_bst_.Data) { MSDK_FREE(buffered_bst_.Data); } } /*------------------------------------------------------------------------------*/ mfxStatus IMfxGstFrameConstuctor::Load(std::shared_ptr<mfxGstBitstreamBufferRef> bst_ref, bool header) { MFX_DEBUG_TRACE_FUNC; mfxStatus sts = LoadToNativeFormat(bst_ref, header); if (MFX_ERR_NONE != sts) { Unload(); } MFX_DEBUG_TRACE_I32(sts); return sts; } /*------------------------------------------------------------------------------*/ mfxStatus IMfxGstFrameConstuctor::Unload(void) { MFX_DEBUG_TRACE_FUNC; mfxStatus sts = Sync(); current_bst_.reset(); MFX_DEBUG_TRACE_I32(sts); return sts; } /*------------------------------------------------------------------------------*/ mfxStatus IMfxGstFrameConstuctor::Sync(void) { MFX_DEBUG_TRACE_FUNC; mfxStatus sts = MFX_ERR_NONE; if (buffered_bst_.DataLength && buffered_bst_.DataOffset) { memmove(buffered_bst_.Data, buffered_bst_.Data + buffered_bst_.DataOffset, buffered_bst_.DataLength); } buffered_bst_.DataOffset = 0; mfxBitstream * bst = current_bst_.get() ? current_bst_->bst() : NULL; if (bst && bst->DataLength) { sts = buffered_bst_.Append(bst); } MFX_DEBUG_TRACE_I32(sts); return sts; } /*------------------------------------------------------------------------------*/ mfxStatus IMfxGstFrameConstuctor::Reset(void) { MFX_DEBUG_TRACE_FUNC; mfxStatus sts = MFX_ERR_NONE; buffered_bst_.Reset(); if (m_bs_state >= MfxGstBS_HeaderCollecting) m_bs_state = MfxGstBS_Resetting; MFX_DEBUG_TRACE_I32(sts); return sts; } /*------------------------------------------------------------------------------*/ mfxBitstream * IMfxGstFrameConstuctor::GetMfxBitstream(void) { MFX_DEBUG_TRACE_FUNC; mfxBitstream * bst = nullptr; auto loaded_bst = current_bst_ ? current_bst_->bst() : nullptr; if (buffered_bst_.Data && buffered_bst_.DataLength) { bst = &buffered_bst_; } else if (loaded_bst && loaded_bst->Data && loaded_bst->DataLength) { bst = loaded_bst; } else { bst = &buffered_bst_; } MFX_DEBUG_TRACE_P(&buffered_bst_); MFX_DEBUG_TRACE_P(&loaded_bst); MFX_DEBUG_TRACE_P(bst); return bst; } /*------------------------------------------------------------------------------*/ IMfxGstFrameConstuctor* MfxGstFrameConstuctorFactory::CreateFrameConstuctor(MfxGstFrameConstuctorType type) { IMfxGstFrameConstuctor* fc = nullptr; if (MfxGstFC_NoChange == type) { fc = new MfxGstFrameConstuctor; } else if (MfxGstFC_AVCC == type) { fc = new MfxGstAVCFrameConstuctorAVCC; } return fc; } /*------------------------------------------------------------------------------*/ mfxStatus MfxGstFrameConstuctor::LoadToNativeFormat(std::shared_ptr<mfxGstBitstreamBufferRef> bst_ref, bool /*header*/) { MFX_DEBUG_TRACE_FUNC; mfxStatus sts = MFX_ERR_NONE; auto bst = bst_ref ? bst_ref->bst() : nullptr; if (buffered_bst_.DataLength) { sts = buffered_bst_.Append(bst); current_bst_.reset(); } else { current_bst_ = bst_ref; } MFX_DEBUG_TRACE_I32(sts); return sts; } /*------------------------------------------------------------------------------*/ mfxStatus MfxGstAVCFrameConstuctorAVCC::LoadToNativeFormat(std::shared_ptr<mfxGstBitstreamBufferRef> bst_ref, bool header) { MFX_DEBUG_TRACE_FUNC; mfxStatus sts = MFX_ERR_NONE; if (header) { ConstructHeader(bst_ref); } else { auto * bst = bst_ref ? bst_ref->bst() : nullptr; convert_avcc_to_bytestream(bst); if (buffered_bst_.DataLength) { sts = buffered_bst_.Append(bst); current_bst_.reset(); } else { current_bst_ = bst_ref; } } MFX_DEBUG_TRACE_I32(sts); return sts; } mfxStatus MfxGstAVCFrameConstuctorAVCC::ConstructHeader(std::shared_ptr<mfxGstBitstreamBufferRef> bst_ref) { MFX_DEBUG_TRACE_FUNC; mfxStatus sts = MFX_ERR_NONE; mfxU8 * data = NULL; mfxU32 size = 0; mfxU32 numOfSequenceParameterSets = 0; mfxU32 numOfPictureParameterSets = 0; mfxU32 sequenceParameterSetLength = 0; mfxU32 pictureParameterSetLength = 0; static mfxU8 header[4] = {0x00, 0x00, 0x00, 0x01}; MfxBistreamBuffer bst_header; mfxBitstream * in_bst = bst_ref.get() ? bst_ref->bst() : NULL; if (!in_bst) { sts = MFX_ERR_NULL_PTR; goto _done; } if ((bst_header.Extend(1024) != MFX_ERR_NONE) || (!bst_header.Data)) { sts = MFX_ERR_MEMORY_ALLOC; goto _done; } data = in_bst->Data; size = in_bst->DataLength; /* AVCDecoderConfigurationRecord: * - mfxU8 - configurationVersion = 1 * - mfxU8 - AVCProfileIndication * - mfxU8 - profile_compatibility * - mfxU8 - AVCLevelIndication * - mfxU8 - '111111'b + lengthSizeMinusOne * - mfxU8 - '111'b + numOfSequenceParameterSets * - for (i = 0; i < numOfSequenceParameterSets; ++i) { * - mfxU16 - sequenceParameterSetLength * - mfxU8*sequenceParameterSetLength - SPS * } * - mfxU8 - numOfPictureParameterSets * - for (i = 0; i < numOfPictureParameterSets; ++i) { * - mfxU16 - pictureParameterSetLength * - mfxU8*pictureParameterSetLength - PPS * } */ if (size < 5) { sts = MFX_ERR_NOT_ENOUGH_BUFFER; goto _done; } data += 5; size -= 5; if (size < 1) { sts = MFX_ERR_NOT_ENOUGH_BUFFER; goto _done; } numOfSequenceParameterSets = data[0] & 0x1f; ++data; --size; for (mfxU32 i = 0; i < numOfSequenceParameterSets; ++i) { if (size < 2) { sts = MFX_ERR_NOT_ENOUGH_BUFFER; goto _done; } sequenceParameterSetLength = (data[0] << 8) | data[1]; data += 2; size -= 2; if (size < sequenceParameterSetLength) { sts = MFX_ERR_NOT_ENOUGH_BUFFER; goto _done; } if (bst_header.MaxLength - bst_header.DataOffset + bst_header.DataLength < 4 + sequenceParameterSetLength) { if (MFX_ERR_NONE != bst_header.Extend(4 + sequenceParameterSetLength)) { sts = MFX_ERR_NOT_ENOUGH_BUFFER; goto _done; } } mfxU8 * buf = bst_header.Data + bst_header.DataOffset + bst_header.DataLength; memcpy(buf, header, sizeof(mfxU8)*4); memcpy(&(buf[4]), data, sizeof(mfxU8)*sequenceParameterSetLength); data += sequenceParameterSetLength; size -= sequenceParameterSetLength; bst_header.DataLength += 4 + sequenceParameterSetLength; } if (size < 1) { sts = MFX_ERR_NOT_ENOUGH_BUFFER; goto _done; } numOfPictureParameterSets = data[0]; ++data; --size; for (mfxU32 i = 0; i < numOfPictureParameterSets; ++i) { if (size < 2) { sts = MFX_ERR_NOT_ENOUGH_BUFFER; goto _done; } pictureParameterSetLength = (data[0] << 8) | data[1]; data += 2; size -= 2; if (size < pictureParameterSetLength) { sts = MFX_ERR_NOT_ENOUGH_BUFFER; goto _done; } if (bst_header.MaxLength - bst_header.DataOffset + bst_header.DataLength < 4 + pictureParameterSetLength) { if (MFX_ERR_NONE != bst_header.Extend(4 + pictureParameterSetLength)) { sts = MFX_ERR_NOT_ENOUGH_BUFFER; goto _done; } } mfxU8 * buf = bst_header.Data + bst_header.DataOffset + bst_header.DataLength; memcpy(buf, header, sizeof(mfxU8)*4); memcpy(&(buf[4]), data, sizeof(mfxU8)*pictureParameterSetLength); data += pictureParameterSetLength; size -= pictureParameterSetLength; bst_header.DataLength += 4 + pictureParameterSetLength; } sts = buffered_bst_.Append(bst_header); _done: return sts; }
28.673529
122
0.637296
AntonGrishin
d871c04714b3c998d4d0f8f20d2f85a9bd6f8ce3
206
cpp
C++
Object Oriented Algo Design in C++/practice/height_heap.cpp
aishwaryamallampati/BTech-IIITDM
4cfc25a4e6e066b848361cb92770cad3260c7d48
[ "MIT" ]
null
null
null
Object Oriented Algo Design in C++/practice/height_heap.cpp
aishwaryamallampati/BTech-IIITDM
4cfc25a4e6e066b848361cb92770cad3260c7d48
[ "MIT" ]
null
null
null
Object Oriented Algo Design in C++/practice/height_heap.cpp
aishwaryamallampati/BTech-IIITDM
4cfc25a4e6e066b848361cb92770cad3260c7d48
[ "MIT" ]
null
null
null
int height(int i,int size) { int l,r; if(i>size) return 0; else { l=height(2*i,size); r=height(((2*i)+1),size); if(l>r) { l=l+1; return l; } else { r=r+1; return r; } } }
9.363636
27
0.475728
aishwaryamallampati
d872dad72aa20ff0381e61a47744ec79c79d5686
4,281
hpp
C++
src/nnfusion/core/kernels/cpu/eigen/softmax.hpp
lynex/nnfusion
6332697c71b6614ca6f04c0dac8614636882630d
[ "MIT" ]
639
2020-09-05T10:00:59.000Z
2022-03-30T08:42:39.000Z
src/nnfusion/core/kernels/cpu/eigen/softmax.hpp
QPC-database/nnfusion
99ada47c50f355ca278001f11bc752d1c7abcee2
[ "MIT" ]
252
2020-09-09T05:35:36.000Z
2022-03-29T04:58:41.000Z
src/nnfusion/core/kernels/cpu/eigen/softmax.hpp
QPC-database/nnfusion
99ada47c50f355ca278001f11bc752d1c7abcee2
[ "MIT" ]
104
2020-09-05T10:01:08.000Z
2022-03-23T10:59:13.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #include "../cpu_kernel_emitter.hpp" #include "nnfusion/core/operators/generic_op/generic_op.hpp" namespace nnfusion { namespace kernels { namespace cpu { template <typename ElementType> class SoftmaxEigen : public EigenKernelEmitter { public: SoftmaxEigen(shared_ptr<KernelContext> ctx) : EigenKernelEmitter(ctx) { auto pad = static_pointer_cast<nnfusion::op::Softmax>(ctx->gnode->get_op_ptr()); input_shape = nnfusion::Shape(ctx->inputs[0]->get_shape()); output_shape = nnfusion::Shape(ctx->outputs[0]->get_shape()); axes = pad->get_axes(); output_type = ctx->outputs[0]->get_element_type().c_type_string(); rank = static_cast<uint32_t>(input_shape.size()); std::stringstream tag; tag << rank << "softmax_i" << join(input_shape, "_") << "softmax_o" << join(output_shape, "_") << "_axes" << join(axes, "_"); custom_tag = tag.str(); } LanguageUnit_p emit_function_body() override { LanguageUnit_p _lu(new LanguageUnit(get_function_name())); auto& lu = *_lu; if (m_context->inputs[0]->get_element_type() == element::f32) { nnfusion::Shape rdims(rank); nnfusion::Shape bcast(rank); for (size_t i = 0; i < rank; ++i) { if (axes.count(i)) { rdims[i] = 1; } else { rdims[i] = input_shape[i]; } } for (size_t i = 0; i < rank; ++i) { bcast[i] = input_shape[i] / rdims[i]; } auto code = nnfusion::op::create_code_from_template( R"( Eigen::array<Eigen::Index, @Rank@> in_dims({@in_dims@}); Eigen::array<Eigen::Index, @Rank@> rdims({@rdims@}); Eigen::array<Eigen::Index, @Rank@> bcast({@bcast@}); Eigen::array<Eigen::Index, @AxisCount@> axes({@axes@}); Eigen::TensorMap<Eigen::Tensor<@ElementType@, @Rank@, Eigen::RowMajor>> out( static_cast<@ElementType@ *>(output0), in_dims), in(static_cast<@ElementType@ *>(input0), in_dims); out.device(*(thread_pool->GetDevice())) = (in - in.maximum(axes).eval().reshape(rdims).broadcast(bcast)).exp(); out.device(*(thread_pool->GetDevice())) = out * out.sum(axes).inverse().eval().reshape(rdims).broadcast(bcast); )", {{"Rank", rank}, {"AxisCount", axes.size()}, {"in_dims", join(input_shape)}, {"rdims", join(rdims)}, {"bcast", join(bcast)}, {"axes", join(axes)}, {"ElementType", output_type}}); lu << code; } else { return nullptr; } return _lu; } LanguageUnit_p emit_dependency() override { LanguageUnit_p _lu(new LanguageUnit(get_function_name() + "_dep")); _lu->require(header::thread); _lu->require(header::eigen_tensor); return _lu; } private: shared_ptr<KernelContext> kernel_ctx; nnfusion::Shape input_shape, output_shape; nnfusion::AxisSet axes; uint32_t rank; string output_type; }; } // namespace cpu } // namespace kernels } // namespace nnfusion
38.223214
100
0.443354
lynex
d874fed91ddb84f034e8e97d57a87d232bd6e028
2,108
hpp
C++
Core/DescriptorSet.hpp
Shmaug/vkCAVE
e502aedaf172047557f0454acb170a46b9d350f8
[ "MIT" ]
2
2019-10-01T22:55:47.000Z
2019-10-04T20:25:29.000Z
Core/DescriptorSet.hpp
Shmaug/vkCAVE
e502aedaf172047557f0454acb170a46b9d350f8
[ "MIT" ]
null
null
null
Core/DescriptorSet.hpp
Shmaug/vkCAVE
e502aedaf172047557f0454acb170a46b9d350f8
[ "MIT" ]
null
null
null
#pragma once #include <Util/Util.hpp> class Device; class Texture; class Buffer; class Sampler; class DescriptorSet { public: ENGINE_EXPORT DescriptorSet(const std::string& name, Device* device, VkDescriptorSetLayout layout); ENGINE_EXPORT ~DescriptorSet(); ENGINE_EXPORT void CreateStorageBufferDescriptor(Buffer* buffer, uint32_t index, VkDeviceSize offset, VkDeviceSize range, uint32_t binding); ENGINE_EXPORT void CreateStorageBufferDescriptor(Buffer* buffer, VkDeviceSize offset, VkDeviceSize range, uint32_t binding); ENGINE_EXPORT void CreateStorageTexelBufferDescriptor(Buffer* view, uint32_t binding); ENGINE_EXPORT void CreateUniformBufferDescriptor(Buffer* buffer, VkDeviceSize offset, VkDeviceSize range, uint32_t binding); ENGINE_EXPORT void CreateStorageTextureDescriptor(Texture* texture, uint32_t binding, VkImageLayout layout = VK_IMAGE_LAYOUT_GENERAL); ENGINE_EXPORT void CreateStorageTextureDescriptor(Texture* texture, uint32_t index, uint32_t binding, VkImageLayout layout = VK_IMAGE_LAYOUT_GENERAL); ENGINE_EXPORT void CreateSampledTextureDescriptor(Texture* texture, uint32_t binding, VkImageLayout layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); ENGINE_EXPORT void CreateSampledTextureDescriptor(Texture* texture, uint32_t index, uint32_t binding, VkImageLayout layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); ENGINE_EXPORT void CreateSamplerDescriptor(Sampler* sampler, uint32_t binding); ENGINE_EXPORT void FlushWrites(); inline VkDescriptorSetLayout Layout() const { return mLayout; } inline operator const VkDescriptorSet*() const { return &mDescriptorSet; } inline operator VkDescriptorSet() const { return mDescriptorSet; } private: std::unordered_map<uint64_t, VkWriteDescriptorSet> mCurrent; std::vector<VkWriteDescriptorSet> mPending; std::queue<VkDescriptorBufferInfo*> mBufferInfoPool; std::queue<VkDescriptorImageInfo*> mImageInfoPool; std::vector<VkDescriptorBufferInfo*> mPendingBuffers; std::vector<VkDescriptorImageInfo*> mPendingImages; Device* mDevice; VkDescriptorSet mDescriptorSet; VkDescriptorSetLayout mLayout; };
45.826087
168
0.833491
Shmaug
d875c03131f5d23004d3af46de9f475a03d9e566
2,102
cc
C++
TC-programs/STUFF/sort_excitationsa.cc
sklinkusch/scripts
a717cadb559db823a0d5172545661d5afa2715e7
[ "MIT" ]
null
null
null
TC-programs/STUFF/sort_excitationsa.cc
sklinkusch/scripts
a717cadb559db823a0d5172545661d5afa2715e7
[ "MIT" ]
null
null
null
TC-programs/STUFF/sort_excitationsa.cc
sklinkusch/scripts
a717cadb559db823a0d5172545661d5afa2715e7
[ "MIT" ]
null
null
null
# include <iostream> # include <fstream> # include <string.h> # include <stdio.h> # include <stdlib.h> # include <sstream> # include <math.h> using namespace std; void swap_line(int &froma, int &toa, double &coeffa, int &fromb, int &tob, double &coeffb){ int tempfrom, tempto; double tempcoeff; tempfrom = froma; froma = fromb; fromb = tempfrom; tempto = toa; toa = tob; tob = tempto; tempcoeff = coeffa; coeffa = coeffb; coeffb = tempcoeff; } int main(int argc, char* argv[]){ if(argc != 2){ cerr << "Usage: ./sort_excitations <infile>\n"; exit(0); } ifstream inf; inf.open(argv[1]); int nros; double gsenergy; inf >> gsenergy >> nros; double* excenergies = new double[nros]; for(int i = 0; i < nros; i++) inf >> excenergies[i]; int limit, state; double dndum; double* upcoeff = new double[500]; int* frommo = new int[500]; int* tomo = new int[500]; for(int i = 0; i < nros; i++){ inf >> limit; if(limit > 0){ for(int j = 0; j < limit; j++){ inf >> state >> frommo[j] >> tomo[j] >> upcoeff[j] >> dndum; cout << state << " " << frommo[j] << " " << tomo[j] << " " << upcoeff[j] << " " << dndum << "\n"; } for(int k = 0; k < (limit-2); k++){ if(k%2 == 0){ #pragma omp parallel for for(int j = 0; j < (limit/2); j++){ if(fabs(upcoeff[2*j]) < fabs(upcoeff[2*j+1])){ swap_line(frommo[2*j], tomo[2*j], upcoeff[2*j], frommo[2*j+1], tomo[2*j+1], upcoeff[2*j+1]); } } }else{ #pragma omp parallel for for(int j = 0; j < (nros/2-1); j++){ if(fabs(upcoeff[2*j+1]) < fabs(upcoeff[2*j+2])){ swap_line(frommo[2*j+1], tomo[2*j+1], upcoeff[2*j+1], frommo[2*j+2], tomo[2*j+2], upcoeff[2*j+2]); } } } } } cout << "State: " << i << "\n"; if(limit >= 3){ for(int j = 0; j < 3; j++) cout << frommo[j] << " " << tomo[j] << " " << upcoeff[j] << "\n"; }else if(limit > 0){ for(int j = 0; j < limit; j++) cout << frommo[j] << " " << tomo[j] << " " << upcoeff[j] << "\n"; }else{ cout << "0 0 1.00000\n"; } } }
26.607595
103
0.519029
sklinkusch
d877e2908aa3d9ea6e7a4a3a17d62b6954741c44
1,481
cpp
C++
src/cpp/UTILS/DistilleryExceptionCode.cpp
IBMStreams/OSStreams
c6287bd9ec4323f567d2faf59125baba8604e1db
[ "Apache-2.0" ]
10
2021-02-19T20:19:24.000Z
2021-09-16T05:11:50.000Z
src/cpp/UTILS/DistilleryExceptionCode.cpp
xguerin/openstreams
7000370b81a7f8778db283b2ba9f9ead984b7439
[ "Apache-2.0" ]
7
2021-02-20T01:17:12.000Z
2021-06-08T14:56:34.000Z
src/cpp/UTILS/DistilleryExceptionCode.cpp
IBMStreams/OSStreams
c6287bd9ec4323f567d2faf59125baba8604e1db
[ "Apache-2.0" ]
4
2021-02-19T18:43:10.000Z
2022-02-23T14:18:16.000Z
/* * Copyright 2021 IBM 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. */ #include <UTILS/DistilleryExceptionCode.h> #include <UTILS/SerializationBuffer.h> UTILS_NAMESPACE_USE using namespace std; const string DistilleryExceptionCode::NO_MESSAGE_ID = "NoMessageId"; DistilleryExceptionCode::DistilleryExceptionCode(const string& messageId) : _msgId(messageId){}; DistilleryExceptionCode::DistilleryExceptionCode(const DistilleryExceptionCode& ec) : _msgId(ec._msgId){}; DistilleryExceptionCode::DistilleryExceptionCode(SerializationBuffer& data) : _msgId(data.getSTLString()){}; void DistilleryExceptionCode::serialize(SerializationBuffer& s) const { s.addSTLString(_msgId); } void DistilleryExceptionCode::print(ostream& o) const { o << _msgId; } DistilleryExceptionCode::~DistilleryExceptionCode(void) throw() {} ostream& UTILS_NAMESPACE::operator<<(ostream& o, const DistilleryExceptionCode& i) { i.print(o); return o; }
29.039216
83
0.766374
IBMStreams
d8795b1764abefc1e1b3e6a06455b268e65532f0
522
cpp
C++
CodingInterviews/cpp/56_get_missing_number.cpp
YorkFish/git_study
6e023244daaa22e12b24e632e76a13e5066f2947
[ "MIT" ]
null
null
null
CodingInterviews/cpp/56_get_missing_number.cpp
YorkFish/git_study
6e023244daaa22e12b24e632e76a13e5066f2947
[ "MIT" ]
null
null
null
CodingInterviews/cpp/56_get_missing_number.cpp
YorkFish/git_study
6e023244daaa22e12b24e632e76a13e5066f2947
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; class Solution { public: int getMissingNumber(vector<int>& nums) { int left = 0, right = nums.size(); while (left < right) { int mid = left + (right - left) / 2; if (mid == nums[mid]) left = mid + 1; else right = mid; } return left; } }; int main() { vector<int> nums{0, 1, 2, 4}; Solution s; int ans = s.getMissingNumber(nums); cout << ans << endl; return 0; }
18.642857
49
0.519157
YorkFish
f21d904334a6c51d4a57974b32bc4313dfb92ad1
1,929
hpp
C++
src/pyprx/visualization/three_js_group_py.hpp
aravindsiv/ML4KP
064015a7545e1713cbcad3e79807b5cec0849f54
[ "MIT" ]
3
2021-05-31T11:28:03.000Z
2021-05-31T13:49:30.000Z
src/pyprx/visualization/three_js_group_py.hpp
aravindsiv/ML4KP
064015a7545e1713cbcad3e79807b5cec0849f54
[ "MIT" ]
1
2021-09-03T09:39:32.000Z
2021-12-10T22:17:56.000Z
src/pyprx/visualization/three_js_group_py.hpp
aravindsiv/ML4KP
064015a7545e1713cbcad3e79807b5cec0849f54
[ "MIT" ]
2
2021-09-03T09:17:45.000Z
2021-10-04T15:52:58.000Z
#include <iostream> #include <boost/python.hpp> #include "prx/visualization/three_js_group.hpp" void (prx::three_js_group_t::*update_vis_infos_1_1)(prx::info_geometry_t, const prx::trajectory_t&, std::string, prx::space_t*, std::string color) = &prx::three_js_group_t::add_vis_infos; void (prx::three_js_group_t::*update_vis_infos_2_1)(prx::info_geometry_t, std::vector<prx::vector_t>, std::string, double) = &prx::three_js_group_t::add_vis_infos; // void (prx::three_js_group_t::*update_vis_infos_2_2)(prx::info_geometry_t, std::vector<prx::vector_t>, std::string) = &prx::three_js_group_t::add_vis_infos; // void (prx::three_js_group_t::*update_vis_infos_2_3)(prx::info_geometry_t, std::vector<prx::vector_t>) = &prx::three_js_group_t::add_vis_infos; void pyprx_visualization_three_js_group_py() { enum_<prx::info_geometry_t>("info_geometry") .value("LINE", prx::info_geometry_t::LINE) .value("QUAD", prx::info_geometry_t::QUAD) .value("FULL_LINE", prx::info_geometry_t::FULL_LINE) .value("CIRCLE", prx::info_geometry_t::CIRCLE) .export_values() ; class_<prx::three_js_group_t>("three_js_group", init<std::vector<prx::system_ptr_t>, std::vector<std::shared_ptr<prx::movable_object_t>>>()) .def("output_html", &prx::three_js_group_t::output_html) .def("update_vis_infos", &prx::three_js_group_t::update_vis_infos) .def("add_vis_infos", update_vis_infos_1_1) // .def("add_vis_infos", update_vis_infos_1_2) .def("add_vis_infos", update_vis_infos_2_1) // .def("add_vis_infos", update_vis_infos_2_2) // .def("add_vis_infos", update_vis_infos_2_3) .def("add_detailed_vis_infos", &prx::three_js_group_t::add_detailed_vis_infos) .def("snapshot_state", &prx::three_js_group_t::snapshot_state) ; }
53.583333
191
0.6817
aravindsiv
f21f1628be052c4ba093baefeb32dbf6eae4df4b
13,324
cc
C++
agp-7.1.0-alpha01/tools/base/profiler/native/perfd/profiler_service_test.cc
jomof/CppBuildCacheWorkInProgress
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
[ "Apache-2.0" ]
1
2020-10-04T19:30:22.000Z
2020-10-04T19:30:22.000Z
agp-7.1.0-alpha01/tools/base/profiler/native/perfd/profiler_service_test.cc
jomof/CppBuildCacheWorkInProgress
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
[ "Apache-2.0" ]
null
null
null
agp-7.1.0-alpha01/tools/base/profiler/native/perfd/profiler_service_test.cc
jomof/CppBuildCacheWorkInProgress
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
[ "Apache-2.0" ]
2
2020-10-04T19:30:24.000Z
2020-11-04T05:58:17.000Z
/* * Copyright (C) 2018 The Android Open Source Project * * 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 <gtest/gtest.h> #include <climits> #include <unordered_set> #include <grpc++/grpc++.h> #include "perfd/profiler_service.h" #include "perfd/sessions/sessions_manager.h" #include "proto/profiler.grpc.pb.h" #include "utils/daemon_config.h" #include "utils/fake_clock.h" #include "utils/file_cache.h" #include "utils/fs/memory_file_system.h" #include "utils/log.h" using std::unique_ptr; namespace profiler { class ProfilerServiceTest : public ::testing::Test { public: ProfilerServiceTest() : file_cache_(unique_ptr<FileSystem>(new MemoryFileSystem()), "/"), config_(proto::DaemonConfig::default_instance()), buffer_(&clock_, 10, 5), daemon_(&clock_, &config_, &file_cache_, &buffer_), service_(&daemon_) {} void SetUp() override { grpc::ServerBuilder builder; int port; builder.AddListeningPort("0.0.0.0:0", grpc::InsecureServerCredentials(), &port); builder.RegisterService(&service_); server_ = builder.BuildAndStart(); std::shared_ptr<grpc::ChannelInterface> channel = grpc::CreateChannel(std::string("0.0.0.0:") + std::to_string(port), grpc::InsecureChannelCredentials()); stub_ = proto::ProfilerService::NewStub(channel); // Create a new thread to read events on. events_thread_ = std::thread(&ProfilerServiceTest::GetEvents, this); SessionsManager::Instance()->ClearSessions(); } proto::Session BeginSession(int32_t device_id, int32_t pid) { proto::BeginSessionRequest req; req.set_device_id(device_id); req.set_pid(pid); grpc::ClientContext context; proto::BeginSessionResponse res; stub_->BeginSession(&context, req, &res); return res.session(); } proto::Session EndSession(int32_t device_id, int32_t session_id) { proto::EndSessionRequest req; req.set_device_id(device_id); req.set_session_id(session_id); grpc::ClientContext context; proto::EndSessionResponse res; stub_->EndSession(&context, req, &res); return res.session(); } proto::GetSessionsResponse GetSessions(int64_t start, int64_t end) { proto::GetSessionsRequest request; request.set_start_timestamp(start); request.set_end_timestamp(end); grpc::ClientContext context; proto::GetSessionsResponse sessions; stub_->GetSessions(&context, request, &sessions); return sessions; } void GetEvents() { proto::GetEventsRequest request; events_reader_ = stub_->GetEvents(&events_context_, request); proto::Event event; // Read is a blocking call. while (events_reader_->Read(&event)) { std::unique_lock<std::mutex> lock(events_mutex_); events_.push(event); events_cv_.notify_all(); } } std::unique_ptr<proto::Event> PopEvent() { std::unique_lock<std::mutex> lock(events_mutex_); // Check events list for elements, if no elements found block until // we timeout (returning null) or we have an event. if (events_cv_.wait_for(lock, std::chrono::milliseconds(500), [this] { return !events_.empty(); })) { proto::Event event = events_.front(); events_.pop(); return std::unique_ptr<proto::Event>(new proto::Event(event)); } return nullptr; } bool IsSessionActive(const proto::Session& session) { return session.end_timestamp() == LLONG_MAX; } void TearDown() override { // Stop client and server listeners. daemon_.InterruptWriteEvents(); events_context_.TryCancel(); events_reader_->Finish(); events_thread_.join(); server_->Shutdown(); } FakeClock clock_; FileCache file_cache_; DaemonConfig config_; EventBuffer buffer_; Daemon daemon_; ProfilerServiceImpl service_; std::mutex events_mutex_; std::condition_variable events_cv_; std::queue<proto::Event> events_; std::thread events_thread_; grpc::ClientContext events_context_; std::unique_ptr<::grpc::Server> server_; std::unique_ptr<proto::ProfilerService::Stub> stub_; std::unique_ptr<grpc::ClientReader<proto::Event>> events_reader_; }; TEST_F(ProfilerServiceTest, TestBeginSessionCommand) { // Test legacy api: // Because lagacy APIs use device ID but new APIs don't, we have to call // legacy BeginSession API at least once so profiler service knows about the // device ID. clock_.SetCurrentTime(20); proto::BeginSessionRequest begin_req; begin_req.set_device_id(100); begin_req.set_pid(1002); grpc::ClientContext begin_context; proto::BeginSessionResponse begin_res; stub_->BeginSession(&begin_context, begin_req, &begin_res); grpc::ClientContext sessions_context; proto::GetSessionsRequest sreq; sreq.set_start_timestamp(0); sreq.set_end_timestamp(20); proto::GetSessionsResponse sres; stub_->GetSessions(&sessions_context, sreq, &sres); ASSERT_EQ(3, sres.sessions_size()); // Test id generation to ensure refactoring maintains same id's. EXPECT_EQ(96, sres.sessions(0).session_id()); EXPECT_EQ(100, sres.sessions(0).stream_id()); EXPECT_EQ(1000, sres.sessions(0).pid()); EXPECT_EQ(2, sres.sessions(0).start_timestamp()); EXPECT_EQ(4, sres.sessions(0).end_timestamp()); EXPECT_EQ(108, sres.sessions(1).session_id()); EXPECT_EQ(100, sres.sessions(1).stream_id()); EXPECT_EQ(1001, sres.sessions(1).pid()); EXPECT_EQ(4, sres.sessions(1).start_timestamp()); EXPECT_EQ(20, sres.sessions(1).end_timestamp()); EXPECT_EQ(LLONG_MAX, sres.sessions(2).end_timestamp()); } TEST_F(ProfilerServiceTest, TestBufferFull) { for (int32_t i = 0; i < 5; i++) { clock_.SetCurrentTime(i); BeginSession(1234, 101); proto::GetSessionsResponse sessions = GetSessions(0, i + 1); ASSERT_EQ(i + 1, sessions.sessions_size()); } proto::GetSessionsResponse sessions = GetSessions(0, 6); ASSERT_EQ(5, sessions.sessions_size()); auto first = sessions.sessions(0).session_id(); auto second = sessions.sessions(1).session_id(); // Creating a new session would push the first one out clock_.SetCurrentTime(5); BeginSession(1234, 101); sessions = GetSessions(0, 6); ASSERT_EQ(5, sessions.sessions_size()); ASSERT_NE(first, second); ASSERT_EQ(second, sessions.sessions(0).session_id()); } TEST_F(ProfilerServiceTest, TestBeginSession) { clock_.SetCurrentTime(2); BeginSession(100, 1000); clock_.SetCurrentTime(4); BeginSession(101, 1001); proto::GetSessionsResponse sessions = GetSessions(1, 3); ASSERT_EQ(1, sessions.sessions_size()); sessions = GetSessions(1, 5); ASSERT_EQ(2, sessions.sessions_size()); sessions = GetSessions(3, 5); ASSERT_EQ(2, sessions.sessions_size()); } TEST_F(ProfilerServiceTest, CanBeginAndEndASession) { clock_.SetCurrentTime(1234); proto::Session begin = BeginSession(2222, 1); EXPECT_EQ(begin.start_timestamp(), 1234); EXPECT_EQ(begin.end_timestamp(), LONG_MAX); EXPECT_EQ(begin.stream_id(), 2222); EXPECT_EQ(begin.pid(), 1); EXPECT_TRUE(IsSessionActive(begin)); clock_.Elapse(10); // Session ended_session; proto::Session end = EndSession(2222, begin.session_id()); EXPECT_EQ(begin.session_id(), end.session_id()); // Test ids to ensure they are stable EXPECT_EQ(0x10A, end.session_id()); EXPECT_EQ(end.end_timestamp(), 1234 + 10); EXPECT_FALSE(IsSessionActive(end)); } TEST_F(ProfilerServiceTest, BeginClosesPreviousSession) { clock_.SetCurrentTime(1234); proto::Session session1 = BeginSession(-1, 1); clock_.Elapse(10); EXPECT_TRUE(IsSessionActive(session1)); EXPECT_EQ(1, session1.pid()); proto::Session session2 = BeginSession(-2, 2); clock_.Elapse(10); EXPECT_TRUE(IsSessionActive(session2)); EXPECT_EQ(2, session2.pid()); proto::Session session3 = BeginSession(-3, 3); clock_.Elapse(10); EXPECT_TRUE(IsSessionActive(session3)); EXPECT_EQ(3, session3.pid()); { proto::GetSessionsResponse sessions = GetSessions(LLONG_MIN, LLONG_MAX); EXPECT_EQ(3, sessions.sessions_size()); EXPECT_FALSE(IsSessionActive(sessions.sessions(0))); EXPECT_FALSE(IsSessionActive(sessions.sessions(1))); EXPECT_TRUE(IsSessionActive(sessions.sessions(2))); } // End and already ended session EndSession(-1, session2.session_id()); { proto::GetSessionsResponse sessions = GetSessions(LLONG_MIN, LLONG_MAX); EXPECT_EQ(3, sessions.sessions_size()); EXPECT_FALSE(IsSessionActive(sessions.sessions(0))); EXPECT_FALSE(IsSessionActive(sessions.sessions(1))); EXPECT_TRUE(IsSessionActive(sessions.sessions(2))); } // End the last session EndSession(-1, session3.session_id()); { proto::GetSessionsResponse sessions = GetSessions(LLONG_MIN, LLONG_MAX); EXPECT_EQ(3, sessions.sessions_size()); EXPECT_FALSE(IsSessionActive(sessions.sessions(0))); EXPECT_FALSE(IsSessionActive(sessions.sessions(1))); EXPECT_FALSE(IsSessionActive(sessions.sessions(2))); } } TEST_F(ProfilerServiceTest, GetSessionsByTimeRangeWorks) { clock_.SetCurrentTime(1000); // Session from 1000 to 1500. proto::Session session = BeginSession(-10, 10); clock_.Elapse(500); session = EndSession(-1, session.session_id()); // Session from 2000 to 2500. clock_.Elapse(500); session = BeginSession(-20, 20); clock_.Elapse(500); session = EndSession(-1, session.session_id()); // Session from 3000 to 3500. clock_.Elapse(500); session = BeginSession(-30, 30); clock_.Elapse(500); session = EndSession(-1, session.session_id()); // Session from 4000 to 4500. clock_.Elapse(500); session = BeginSession(-40, 40); clock_.Elapse(500); session = EndSession(-1, session.session_id()); // Session from 5000 to present. clock_.Elapse(500); session = BeginSession(-50, 50); EXPECT_TRUE(IsSessionActive(session)); { // Get all auto sessions = GetSessions(LLONG_MIN, LLONG_MAX); EXPECT_EQ(5, sessions.sessions_size()); EXPECT_EQ(10, sessions.sessions(0).pid()); EXPECT_EQ(20, sessions.sessions(1).pid()); EXPECT_EQ(30, sessions.sessions(2).pid()); EXPECT_EQ(40, sessions.sessions(3).pid()); EXPECT_EQ(50, sessions.sessions(4).pid()); } { // Get all sessions ended after a time range auto sessions = GetSessions(3250, LLONG_MAX); EXPECT_EQ(3, sessions.sessions_size()); EXPECT_EQ(30, sessions.sessions(0).pid()); EXPECT_EQ(40, sessions.sessions(1).pid()); EXPECT_EQ(50, sessions.sessions(2).pid()); } { // Get all sessions started before a time range auto sessions = GetSessions(0, 3250); EXPECT_EQ(3, sessions.sessions_size()); EXPECT_EQ(10, sessions.sessions(0).pid()); EXPECT_EQ(20, sessions.sessions(1).pid()); EXPECT_EQ(30, sessions.sessions(2).pid()); } { // Get sessions between two time ranges auto sessions = GetSessions(2250, 3250); EXPECT_EQ(2, sessions.sessions_size()); EXPECT_EQ(20, sessions.sessions(0).pid()); EXPECT_EQ(30, sessions.sessions(1).pid()); } { // An active session has no end timestamp and, until it ends, is assumed // extend forever. auto sessions = GetSessions(clock_.GetCurrentTime() + 1000, LLONG_MAX); EXPECT_EQ(1, sessions.sessions_size()); EXPECT_EQ(50, sessions.sessions(0).pid()); } } TEST_F(ProfilerServiceTest, BeginingTwiceIsTheSameAsEndingInBetween) { clock_.SetCurrentTime(1000); proto::Session session; EXPECT_EQ(0, GetSessions(LLONG_MIN, LLONG_MAX).sessions_size()); session = BeginSession(-10, 10); clock_.Elapse(10); EXPECT_EQ(1, GetSessions(LLONG_MIN, LLONG_MAX).sessions_size()); session = BeginSession(-10, 10); clock_.Elapse(10); EXPECT_EQ(2, GetSessions(LLONG_MIN, LLONG_MAX).sessions_size()); session = EndSession(-1, session.session_id()); clock_.Elapse(10); session = BeginSession(-10, 10); clock_.Elapse(10); { auto sessions = GetSessions(LLONG_MIN, LLONG_MAX); EXPECT_EQ(3, sessions.sessions_size()); EXPECT_EQ(10, sessions.sessions(0).pid()); EXPECT_FALSE(IsSessionActive(sessions.sessions(0))); EXPECT_EQ(10, sessions.sessions(1).pid()); EXPECT_FALSE(IsSessionActive(sessions.sessions(1))); EXPECT_EQ(10, sessions.sessions(2).pid()); EXPECT_TRUE(IsSessionActive(sessions.sessions(2))); } } TEST_F(ProfilerServiceTest, UniqueSessionIds) { clock_.SetCurrentTime(1234); std::unordered_set<int64_t> session_ids; for (int32_t device_id = 0; device_id < 100; device_id++) { for (int64_t start_time = 0; start_time < 10000; start_time += 100) { clock_.SetCurrentTime(start_time); proto::Session session = BeginSession(device_id, start_time); EXPECT_EQ(session_ids.end(), session_ids.find(session.session_id())); session_ids.insert(session.session_id()); } } } } // namespace profiler
33.31
78
0.707896
jomof
f22135104eb6c134a71fbbb52d41a9b1c7f155c1
20,275
cpp
C++
src/textnet_nextbasket.cpp
pl8787/textnet-release
c85a4162c55b4cfe22eab6f8f0c8b615854f9b8f
[ "Apache-2.0" ]
114
2017-06-14T07:05:31.000Z
2021-06-13T05:30:49.000Z
src/textnet_nextbasket.cpp
pl8787/textnet-release
c85a4162c55b4cfe22eab6f8f0c8b615854f9b8f
[ "Apache-2.0" ]
7
2017-11-17T08:16:55.000Z
2019-10-05T00:09:20.000Z
src/textnet_nextbasket.cpp
pl8787/textnet-release
c85a4162c55b4cfe22eab6f8f0c8b615854f9b8f
[ "Apache-2.0" ]
40
2017-06-15T03:21:10.000Z
2021-10-31T15:03:30.000Z
#define _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_DEPRECATE #include <iostream> #include <fstream> #include <ctime> #include <string> #include <cstring> #include <vector> #include <map> #include <climits> #include "./layer/layer.h" #include "./io/json/json.h" #include "global.h" #include <cassert> #include "./checker/checker.h" using namespace std; using namespace textnet; using namespace textnet::layer; using namespace mshadow; void PrintTensor(const char * name, Tensor<cpu, 1> x) { Shape<1> s = x.shape_; cout << name << " shape " << s[0] << endl; for (unsigned int d1 = 0; d1 < s[0]; ++d1) { cout << x[d1] << " "; } cout << endl; } void PrintTensor(const char * name, Tensor<cpu, 2> x) { Shape<2> s = x.shape_; cout << name << " shape " << s[0] << "x" << s[1] << endl; for (unsigned int d1 = 0; d1 < s[0]; ++d1) { for (unsigned int d2 = 0; d2 < s[1]; ++d2) { cout << x[d1][d2] << " "; } cout << endl; } cout << endl; } void PrintTensor(const char * name, Tensor<cpu, 3> x) { Shape<3> s = x.shape_; cout << name << " shape " << s[0] << "x" << s[1] << "x" << s[2] << endl; for (unsigned int d1 = 0; d1 < s[0]; ++d1) { for (unsigned int d2 = 0; d2 < s[1]; ++d2) { for (unsigned int d3 = 0; d3 < s[2]; ++d3) { cout << x[d1][d2][d3] << " "; } cout << ";"; } cout << endl; } } void PrintTensor(const char * name, Tensor<cpu, 4> x) { Shape<4> s = x.shape_; cout << name << " shape " << s[0] << "x" << s[1] << "x" << s[2] << "x" << s[3] << endl; for (unsigned int d1 = 0; d1 < s[0]; ++d1) { for (unsigned int d2 = 0; d2 < s[1]; ++d2) { for (unsigned int d3 = 0; d3 < s[2]; ++d3) { for (unsigned int d4 = 0; d4 < s[3]; ++d4) { cout << x[d1][d2][d3][d4] << " "; } cout << "|"; } cout << ";"; } cout << endl; } cout << endl; } struct EvalRet { float acc, loss; EvalRet(): acc(0.), loss(0.) {} void clear() { acc = 0.; loss = 0.; } }; void eval(vector<Layer<cpu> *> senti_net, vector<vector<Node<cpu> *> > &bottoms, vector<vector<Node<cpu> *> > &tops, int nBatch, EvalRet &ret) { ret.clear(); for (int i = 0; i < nBatch; ++i) { for (int j = 0; j < senti_net.size(); ++j) { senti_net[j]->SetPhrase(kTest); senti_net[j]->Forward(bottoms[j], tops[j]); } ret.loss += tops[tops.size()-2][0]->data_d1()[0]; ret.acc += tops[tops.size()-1][0]->data_d1()[0] * tops[0][0]->data.size(0); } ret.loss /= float(nBatch); // ret.acc /= float(nBatch); } int main(int argc, char *argv[]) { mshadow::Random<cpu> rnd(37); vector<Layer<cpu>*> senti_net, senti_valid, senti_test, senti_train; if (argc >= 3) { freopen(argv[2], "w", stdout); setvbuf(stdout, NULL, _IOLBF, 0); } bool no_bias = true; float l2 = 0.f; int max_session_len = 300; int context_window = 1; int min_doc_len = 1; int batch_size = 1; int word_rep_dim = 50; int num_hidden = (context_window+1) * word_rep_dim; int num_item = 7973; int num_user = 2265; int num_class = num_item; float base_lr = 0.1; float ADA_GRAD_EPS = 0.1; float decay = 0.00; int nTrain = 168933;// nValid = 7, nTest = 7; int nTrainPred = num_user;// nValid = 7, nTest = 7; int nValid = num_user;// nValid = 7, nTest = 7; int nTest = num_user; // nValid = 7, nTest = 7; int max_iter = (20*nTrain)/(batch_size); int iter_eval = (nTrain/batch_size)/20; // int ADA_GRAD_MAX_ITER = 1000000; int ADA_GRAD_MAX_ITER = (nTrain/batch_size)/3; string train_data_file = "/home/wsx/dl.shengxian/data/pengfei/tafeng_sub.textnet.train.1"; string train_pred_data_file = "/home/wsx/dl.shengxian/data/pengfei/tafeng_sub.textnet.train_pred.1"; string valid_data_file = "/home/wsx/dl.shengxian/data/pengfei/tafeng_sub.textnet.valid.1"; string test_data_file = "/home/wsx/dl.shengxian/data/pengfei/tafeng_sub.textnet.test.1"; string embedding_file = ""; // string embedding_file = "/home/pangliang/matching/data/wikicorp_50_msr.txt"; // int nTrain = 1000;// nValid = 7, nTest = 7; if (argc >= 2) { base_lr = atof(argv[1]); } map<string, SettingV> &g_updater = *(new map<string, SettingV>()); // g_updater["updater_type"] = SettingV(updater::kAdaDelta); g_updater["updater_type"] = SettingV(updater::kAdagrad); g_updater["batch_size"] = SettingV(batch_size); g_updater["l2"] = SettingV(l2); g_updater["max_iter"] = SettingV(ADA_GRAD_MAX_ITER); g_updater["eps"] = SettingV(ADA_GRAD_EPS); g_updater["lr"] = SettingV(base_lr); // g_updater["decay"] = SettingV(decay); // g_updater["momentum"] = SettingV(0.0f); senti_net.push_back(CreateLayer<cpu>(kNextBasketData)); senti_net[senti_net.size()-1]->layer_name = "data"; senti_net.push_back(CreateLayer<cpu>(kEmbedding)); senti_net[senti_net.size()-1]->layer_name = "user_embedding"; senti_net.push_back(CreateLayer<cpu>(kEmbedding)); senti_net[senti_net.size()-1]->layer_name = "item_embedding"; senti_net.push_back(CreateLayer<cpu>(kWholePooling)); senti_net[senti_net.size()-1]->layer_name = "wholepooling"; senti_net.push_back(CreateLayer<cpu>(kConcat)); senti_net[senti_net.size()-1]->layer_name = "concat"; senti_net.push_back(CreateLayer<cpu>(kFullConnect)); senti_net[senti_net.size()-1]->layer_name = "fullconnect"; senti_net.push_back(CreateLayer<cpu>(kRectifiedLinear)); senti_net[senti_net.size()-1]->layer_name = "activation"; senti_net.push_back(CreateLayer<cpu>(kDropout)); senti_net[senti_net.size()-1]->layer_name = "dropout"; senti_net.push_back(CreateLayer<cpu>(kFullConnect)); senti_net[senti_net.size()-1]->layer_name = "fullconnect"; senti_net.push_back(CreateLayer<cpu>(kSoftmax)); senti_net[senti_net.size()-1]->layer_name = "softmax"; senti_net.push_back(CreateLayer<cpu>(kAccuracy)); senti_net[senti_net.size()-1]->layer_name = "accuracy"; senti_train = senti_net; senti_test = senti_net; senti_valid = senti_net; senti_train[0] = CreateLayer<cpu>(kNextBasketData); senti_test[0] = CreateLayer<cpu>(kNextBasketData); senti_valid[0]= CreateLayer<cpu>(kNextBasketData); vector<vector<Node<cpu>*> > bottom_vecs(senti_net.size(), vector<Node<cpu>*>()); vector<vector<Node<cpu>*> > top_vecs(senti_net.size(), vector<Node<cpu>*>()); vector<Node<cpu>*> nodes; for (int i = 0; i < senti_net.size(); ++i) { // last layers are softmax layer and accuracy layers int top_node_num = 0; top_node_num = senti_net[i]->TopNodeNum(); for (int j = 0; j < top_node_num; ++j) { Node<cpu>* node = new Node<cpu>(); stringstream ss; ss << nodes.size(); node->node_name = ss.str(); nodes.push_back(node); top_vecs[i].push_back(node); senti_net[i]->top_nodes.push_back(node->node_name); } } int layerIdx = 0; // data senti_net[0]->top_nodes.push_back(nodes[0]->node_name); // label senti_net[0]->top_nodes.push_back(nodes[1]->node_name); // label set senti_net[0]->top_nodes.push_back(nodes[2]->node_name); // user senti_net[0]->top_nodes.push_back(nodes[3]->node_name); // item senti_valid[0]->top_nodes.push_back(nodes[0]->node_name); // label senti_valid[0]->top_nodes.push_back(nodes[1]->node_name); // label set senti_valid[0]->top_nodes.push_back(nodes[2]->node_name); // user senti_valid[0]->top_nodes.push_back(nodes[3]->node_name); // item ++layerIdx; // user_embedding bottom_vecs[1].push_back(top_vecs[0][2]); senti_net[1]->bottom_nodes.push_back(nodes[2]->node_name); senti_net[1]->top_nodes.push_back(nodes[4]->node_name); ++layerIdx; // item_embedding bottom_vecs[2].push_back(top_vecs[0][3]); senti_net[2]->bottom_nodes.push_back(nodes[3]->node_name); senti_net[2]->top_nodes.push_back(nodes[5]->node_name); ++layerIdx; // whole_pooling bottom_vecs[3].push_back(top_vecs[2][0]); senti_net[3]->bottom_nodes.push_back(nodes[5]->node_name); senti_net[3]->top_nodes.push_back(nodes[6]->node_name); ++layerIdx; // 4 // concat bottom_vecs[layerIdx].push_back(top_vecs[layerIdx-3][0]); bottom_vecs[layerIdx].push_back(top_vecs[layerIdx-1][0]); senti_net[layerIdx]->bottom_nodes.push_back(nodes[4]->node_name); senti_net[layerIdx]->bottom_nodes.push_back(nodes[6]->node_name); senti_net[layerIdx]->top_nodes.push_back(nodes[7]->node_name); ++layerIdx; // fullconnect bottom_vecs[layerIdx].push_back(top_vecs[layerIdx-1][0]); senti_net[layerIdx]->bottom_nodes.push_back(nodes[layerIdx+3-1]->node_name); senti_net[layerIdx]->top_nodes.push_back(nodes[layerIdx+3]->node_name); ++layerIdx; // activation bottom_vecs[layerIdx].push_back(top_vecs[layerIdx-1][0]); senti_net[layerIdx]->bottom_nodes.push_back(nodes[layerIdx+3-1]->node_name); senti_net[layerIdx]->top_nodes.push_back(nodes[layerIdx+3]->node_name); ++layerIdx; // dropout bottom_vecs[layerIdx].push_back(top_vecs[layerIdx-1][0]); senti_net[layerIdx]->bottom_nodes.push_back(nodes[layerIdx+3-1]->node_name); senti_net[layerIdx]->top_nodes.push_back(nodes[layerIdx+3]->node_name); ++layerIdx; // fullconnect bottom_vecs[layerIdx].push_back(top_vecs[layerIdx-1][0]); senti_net[layerIdx]->bottom_nodes.push_back(nodes[layerIdx+3-1]->node_name); senti_net[layerIdx]->top_nodes.push_back(nodes[layerIdx+3]->node_name); ++layerIdx; // softmax bottom_vecs[layerIdx].push_back(top_vecs[layerIdx-1][0]); bottom_vecs[layerIdx].push_back(top_vecs[0][0]); senti_net[layerIdx]->bottom_nodes.push_back(nodes[layerIdx+3-1]->node_name); senti_net[layerIdx]->bottom_nodes.push_back(nodes[0]->node_name); senti_net[layerIdx]->top_nodes.push_back(nodes[layerIdx+3]->node_name); ++layerIdx; // hit_cnt bottom_vecs[layerIdx].push_back(top_vecs[layerIdx-2][0]); bottom_vecs[layerIdx].push_back(top_vecs[0][1]); senti_net[layerIdx]->bottom_nodes.push_back(nodes[layerIdx+3-2]->node_name); senti_net[layerIdx]->bottom_nodes.push_back(nodes[1]->node_name); senti_net[layerIdx]->top_nodes.push_back(nodes[layerIdx+3]->node_name); // Fill Settings vector vector<map<string, SettingV> > setting_vec; // kNextBasketLayer { map<string, SettingV> setting; // orc setting["data_file"] = SettingV(train_data_file); setting["batch_size"] = SettingV(batch_size); setting["max_session_len"] = SettingV(max_session_len); setting["context_window"] = SettingV(context_window); setting_vec.push_back(setting); // test setting["batch_size"] = SettingV(batch_size); setting["data_file"] = SettingV(valid_data_file); senti_valid[0]->PropAll(); senti_valid[0]->SetupLayer(setting, bottom_vecs[0], top_vecs[0], &rnd); senti_valid[0]->Reshape(bottom_vecs[0], top_vecs[0]); setting["batch_size"] = SettingV(batch_size); setting["data_file"] = SettingV(train_pred_data_file); senti_train[0]->PropAll(); senti_train[0]->SetupLayer(setting, bottom_vecs[0], top_vecs[0], &rnd); senti_train[0]->Reshape(bottom_vecs[0], top_vecs[0]); setting["batch_size"] = SettingV(batch_size); setting["data_file"] = SettingV(test_data_file); senti_test[0]->PropAll(); senti_test[0]->SetupLayer(setting, bottom_vecs[0], top_vecs[0], &rnd); senti_test[0]->Reshape(bottom_vecs[0], top_vecs[0]); } // kEmbedding user { map<string, SettingV> setting; // orc setting["embedding_file"] = SettingV(embedding_file); setting["word_count"] = SettingV(num_user); setting["feat_size"] = SettingV(word_rep_dim); setting["pad_value"] = SettingV((float)(NAN)); map<string, SettingV> &w_setting = *(new map<string, SettingV>()); w_setting["init_type"] = SettingV(initializer::kUniform); w_setting["range"] = SettingV(1.f/word_rep_dim); setting["w_filler"] = SettingV(&w_setting); map<string, SettingV> &w_updater = *(new map<string, SettingV>()); w_updater = g_updater; setting["w_updater"] = SettingV(&w_updater); setting_vec.push_back(setting); } // kEmbedding item { map<string, SettingV> setting; // orc setting["embedding_file"] = SettingV(embedding_file); setting["word_count"] = SettingV(num_item); setting["feat_size"] = SettingV(word_rep_dim); setting["pad_value"] = SettingV((float)(NAN)); map<string, SettingV> &w_setting = *(new map<string, SettingV>()); w_setting = *setting_vec[setting_vec.size()-1]["w_filler"].mVal(); setting["w_filler"] = SettingV(&w_setting); map<string, SettingV> &w_updater = *(new map<string, SettingV>()); w_updater = g_updater; setting["w_updater"]= SettingV(&w_updater); setting_vec.push_back(setting); } // kWholeMaxPooling { map<string, SettingV> setting; setting["pool_type"] = "ave"; setting_vec.push_back(setting); } // kConcat { map<string, SettingV> setting; setting["bottom_node_num"] = context_window + 1; setting_vec.push_back(setting); } // kFullConnect { map<string, SettingV> setting; setting["num_hidden"] = SettingV(num_hidden); setting["no_bias"] = SettingV(no_bias); map<string, SettingV> &w_setting = *(new map<string, SettingV>()); w_setting["init_type"] = SettingV(initializer::kUniform); w_setting["range"] = SettingV(1.f/word_rep_dim); map<string, SettingV> &b_setting = *(new map<string, SettingV>()); b_setting["init_type"] = SettingV(initializer::kZero); setting["w_filler"] = SettingV(&w_setting); setting["b_filler"] = SettingV(&b_setting); map<string, SettingV> &w_updater = *(new map<string, SettingV>()); w_updater = g_updater; map<string, SettingV> &b_updater = *(new map<string, SettingV>()); b_updater = g_updater; setting["w_updater"] = SettingV(&w_updater); setting["b_updater"] = SettingV(&b_updater); setting_vec.push_back(setting); } // kActivation { map<string, SettingV> setting; setting_vec.push_back(setting); } // kDropout { map<string, SettingV> setting; setting["rate"] = SettingV(0.5f); setting_vec.push_back(setting); } // kFullConnect { map<string, SettingV> setting; setting["num_hidden"] = SettingV(num_class); setting["no_bias"] = SettingV(no_bias); map<string, SettingV> &w_setting = *(new map<string, SettingV>()); // w_setting["init_type"] = SettingV(initializer::kZero); w_setting["init_type"] = SettingV(initializer::kUniform); w_setting["range"] = SettingV(1.f/word_rep_dim); map<string, SettingV> &b_setting = *(new map<string, SettingV>()); b_setting["init_type"] = SettingV(initializer::kZero); setting["w_filler"] = SettingV(&w_setting); setting["b_filler"] = SettingV(&b_setting); map<string, SettingV> &w_updater = *(new map<string, SettingV>()); w_updater = g_updater; map<string, SettingV> &b_updater = *(new map<string, SettingV>()); b_updater = g_updater; setting["w_updater"] = SettingV(&w_updater); setting["b_updater"] = SettingV(&b_updater); setting_vec.push_back(setting); } // kSoftmax { map<string, SettingV> setting; // map<string, SettingV> &w_setting = *(new map<string, SettingV>()); // // w_setting["init_type"] = SettingV(initializer::kZero); // w_setting["init_type"] = SettingV(initializer::kZero); // map<string, SettingV> &b_setting = *(new map<string, SettingV>()); // b_setting["init_type"] = SettingV(initializer::kZero); // setting["w_filler"] = SettingV(&w_setting); // setting["b_filler"] = SettingV(&b_setting); setting_vec.push_back(setting); } // kAccuracy { map<string, SettingV> setting; setting["topk"] = SettingV(5); setting_vec.push_back(setting); } cout << "Setting Vector Filled." << endl; // Set up Layers for (index_t i = 0; i < senti_net.size(); ++i) { cout << "Begin set up layer " << i << endl; senti_net[i]->PropAll(); cout << "\tPropAll" << endl; senti_net[i]->SetupLayer(setting_vec[i], bottom_vecs[i], top_vecs[i], &rnd); cout << "\tSetup Layer" << endl; senti_net[i]->Reshape(bottom_vecs[i], top_vecs[i]); cout << "\tReshape" << endl; } // Save Initial Model { ofstream _of("./next.basket.model"); Json::StyledWriter writer; Json::Value net_root; net_root["net_name"] = "next_basket"; Json::Value layers_root; for (index_t i = 0; i < senti_net.size(); ++i) { Json::Value layer_root; senti_net[i]->SaveModel(layer_root, false); layers_root.append(layer_root); } net_root["layers"] = layers_root; string json_file = writer.write(net_root); _of << json_file; _of.close(); } // Begin Training float maxValidAcc = 0., testAccByValid = 0.; for (int iter = 0; iter < max_iter; ++iter) { // if (iter % 100 == 0) { cout << "iter:" << iter << endl; } if (iter % iter_eval == 0) { EvalRet train_ret, valid_ret, test_ret; // eval(senti_net, bottom_vecs, top_vecs, (nTrain/batch_size), train_ret); eval(senti_train, bottom_vecs, top_vecs, (nTrainPred/batch_size), train_ret); eval(senti_valid, bottom_vecs, top_vecs, (nValid/batch_size), valid_ret); eval(senti_test, bottom_vecs, top_vecs, (nTest/batch_size), test_ret); fprintf(stdout, "****%d,%f,%f,%f,%f,%f,%f", iter, train_ret.loss, valid_ret.loss, test_ret.loss, train_ret.acc, valid_ret.acc, test_ret.acc); if (valid_ret.acc > maxValidAcc) { maxValidAcc = valid_ret.acc; testAccByValid = test_ret.acc; fprintf(stdout, "*^_^*"); } fprintf(stdout, "\n"); } // cout << "Begin iter " << iter << endl; for (index_t i = 0; i < senti_net.size(); ++i) { senti_net[i]->SetPhrase(kTrain); // cout << "Forward layer " << i << endl; senti_net[i]->Forward(bottom_vecs[i], top_vecs[i]); } #if 0 for (index_t i = 0; i < nodes.size(); ++i) { cout << "# Data " << nodes[i]->node_name << " : "; for (index_t j = 0; j < 5; ++j) { cout << nodes[i]->data[0][0][0][j] << "\t"; } cout << endl; cout << "# Diff " << nodes[i]->node_name << " : "; for (index_t j = 0; j < 5; ++j) { cout << nodes[i]->diff[0][0][0][j] << "\t"; } cout << endl; } #endif for (int i = 0; i < senti_net.size(); ++i) { senti_net[i]->ClearDiff(bottom_vecs[i], top_vecs[i]); } for (int i = senti_net.size()-2; i >= 0; --i) { // cout << "Backprop layer " << i << endl; senti_net[i]->Backprop(bottom_vecs[i], top_vecs[i]); } for (index_t i = 0; i < senti_net.size(); ++i) { for (index_t j = 0; j < senti_net[i]->ParamNodeNum(); ++j) { // cout << "Update param in layer " << i << " params " << j << endl; // cout << "param data" << i << " , " << j << ": " << senti_net[i]->GetParams()[j].data[0][0][0][0] << endl; // cout << "param diff" << i << " , " << j << ": " << senti_net[i]->GetParams()[j].diff[0][0][0][0] << endl; if (senti_net[i]->layer_name == "fullconnect" && j == 1) continue; // bias is shit if (senti_net[i]->layer_name == "lstm" && j == 2) continue; // bias is shit senti_net[i]->GetParams()[j].Update(); // cout << "param data" << i << " , " << j << ": " << senti_net[i]->GetParams()[j].data[0][0][0][0] << endl<<endl; } } // Output informations // cout << "###### Iter " << iter << ": error =\t" << nodes[nodes.size()-2]->data_d1()[0] << endl; } return 0; }
38.472486
123
0.612429
pl8787
f22dfd860b4d10bf32ddef2f1593e46d9b44ea93
3,276
cpp
C++
src/util/node.cpp
markhary/ctci
eb96014b779e2a7eca1229644300bae18caf328d
[ "Unlicense" ]
1
2021-11-17T16:50:54.000Z
2021-11-17T16:50:54.000Z
src/util/node.cpp
markhary/ctci
eb96014b779e2a7eca1229644300bae18caf328d
[ "Unlicense" ]
null
null
null
src/util/node.cpp
markhary/ctci
eb96014b779e2a7eca1229644300bae18caf328d
[ "Unlicense" ]
1
2020-06-15T13:54:04.000Z
2020-06-15T13:54:04.000Z
// Node object // #include <iostream> #include <vector> #include <gtest/gtest.h> #include "args.h" #include "macros.h" #include "util/node.h" using namespace std; using namespace ctci; using namespace ctci::util; TEST(Node, Initialize) { int value = 5; Node<int> node(value); ASSERT_EQ(node.value, value); ASSERT_EQ(node.visitState, UNVISITED); } TEST(Node, Cout) { // Simple test string test = "test"; const NodeTypeEnum nodeType = DIRECTED; Node<string> node(test, nodeType); stringstream testOutput; testOutput << node; string testExpected = "test -> {}"; ASSERT_EQ(testOutput.str(), testExpected); // Complicated test string nodeOne = "a"; string nodeTwo = "b"; string nodeThree = "c"; shared_ptr<Node<string>> node1(new Node<string>(nodeOne, nodeType)); shared_ptr<Node<string>> node2(new Node<string>(nodeTwo, nodeType)); shared_ptr<Node<string>> node3(new Node<string>(nodeThree, nodeType)); vector<pair<string, shared_ptr<Node<string>>>> adjacencyList = {{nodeTwo, node2}, {nodeThree, node3}}; node1->insert(adjacencyList); string expectedOne = "a -> {b c}"; stringstream outputOne; string expectedTwo = "b -> {}"; stringstream outputTwo; string expectedThree = "c -> {}"; stringstream outputThree; outputOne << *node1; outputTwo << *node2; outputThree << *node3; ASSERT_EQ(outputOne.str(), expectedOne); ASSERT_EQ(outputTwo.str(), expectedTwo); ASSERT_EQ(outputThree.str(), expectedThree); // Make sure output was not affected outputOne.str(""); outputTwo.str(""); outputThree.str(""); outputOne << *node1; outputTwo << *node2; outputThree << *node3; ASSERT_EQ(outputOne.str(), expectedOne); ASSERT_EQ(outputTwo.str(), expectedTwo); ASSERT_EQ(outputThree.str(), expectedThree); } TEST(Node, Insert) { string nodeOne = "one"; string nodeTwo = "two"; string nodeThree = "three"; shared_ptr<Node<string>> node1(new Node<string>(nodeOne)); shared_ptr<Node<string>> node2(new Node<string>(nodeTwo)); shared_ptr<Node<string>> node3(new Node<string>(nodeThree)); vector<pair<string, shared_ptr<Node<string>>>> adjacencyList = {{nodeTwo, node2}, {nodeThree, node3}}; node1->insert(adjacencyList); ASSERT_EQ(node1->value, nodeOne); ASSERT_EQ(node2->value, nodeTwo); ASSERT_EQ(node3->value, nodeThree); // Check duplicates are not successful ASSERT_EQ(node1->insert({nodeTwo, node2}), false); auto c2 = node1->connections.find(nodeTwo); if ( c2 == node1->connections.end() ) { ASSERT_EQ(true, false); } else { ASSERT_EQ(c2->first, nodeTwo); } auto c3 = node1->connections.find(nodeThree); if ( c3 == node1->connections.end() ) { ASSERT_EQ(true, false); } else { ASSERT_EQ(c3->first, nodeThree); } } TEST(Node, Templating) { int intValue = 5; Node<int> nodeInt(intValue); ASSERT_EQ(nodeInt.value, intValue); string stringValue = "abc"; Node<string> nodeString(stringValue); ASSERT_EQ(nodeString.value, stringValue); double doubleValue = 3.14; Node<double> nodeDouble(doubleValue); ASSERT_EQ(nodeDouble.value, doubleValue); }
25.395349
106
0.654762
markhary
f23084bf6073bb48b042bc99e01b044d35f4d297
600
cpp
C++
Tau/src/core/Midi/MidiEvent.cpp
cymheart/tau
1881046c7e362451e8d4f5d4b885e9011dade319
[ "MIT" ]
7
2021-10-05T07:07:45.000Z
2022-03-01T07:28:34.000Z
Tau/src/core/Midi/MidiEvent.cpp
cymheart/tau
1881046c7e362451e8d4f5d4b885e9011dade319
[ "MIT" ]
1
2021-09-21T07:25:53.000Z
2021-10-02T02:02:10.000Z
Tau/src/core/Midi/MidiEvent.cpp
cymheart/ventrue
57219117a40077ffdde76c7183ea744c0ac2a08f
[ "MIT" ]
1
2022-02-24T21:24:27.000Z
2022-02-24T21:24:27.000Z
#include"MidiEvent.h" namespace tau { SysexEvent::~SysexEvent() { free(data); } void SysexEvent::CreateData(byte* d, size_t len) { if (len <= 0) return; try { data = (byte*)malloc(len); if (data != nullptr) memcpy(data, d, len); this->size = len; } catch (exception) { } } UnknownEvent::~UnknownEvent() { free(data); } void UnknownEvent::CreateData(byte* d, size_t len) { if (len <= 0) return; try { data = (byte*)malloc(len); if (data != nullptr) memcpy(data, d, len); this->size = len; } catch (exception) { } } }
12
51
0.558333
cymheart
f23107e929ed9d288e7d9d15b2b4f334ffea79a3
3,679
cpp
C++
src/main.cpp
fixstars/cRTOS-loader
d3da5738d2511b497a56d320eafe1f3dc628347b
[ "Apache-2.0" ]
null
null
null
src/main.cpp
fixstars/cRTOS-loader
d3da5738d2511b497a56d320eafe1f3dc628347b
[ "Apache-2.0" ]
null
null
null
src/main.cpp
fixstars/cRTOS-loader
d3da5738d2511b497a56d320eafe1f3dc628347b
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2020 Yang, Chung-Fan @ Fixstars corporation * <chungfan.yang@fixstars.com> * 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. */ #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <cassert> #include <iostream> #include <vector> #include <stdexcept> #include <unistd.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <signal.h> #include "MMAP.hpp" #include "IO.hpp" #include "Proxy.hpp" #include "verbose.hpp" #define __VERBOSE verbose static std::string get_filename(const std::string& s) { char sep = '/'; size_t i = s.rfind(sep, s.length()); if (i != std::string::npos) { return(s.substr(i + 1, s.length() - i)); } return(""); } std::string readenv(std::string in, std::string def) { if (std::getenv(in.c_str()) != NULL) { return std::string(std::getenv(in.c_str())); } else { return def; } return std::string("NULL"); } void print_usage() { std::cout << "Usage: loader <optional env> <elf file> ..." << std::endl; std::cout << "Environment variable APPMEM must be set to corresponding uio device" << std::endl; } int main(int argc, char *argv[], char *envp[]) { bool verbose = (readenv("VERBOSE", "0") == "1"); bool magic = (readenv("MAGIC", "0") == "1"); std::vector<std::string> llargv; std::vector<std::string> llenvv; int i; /* Early declaration for additional arguments or environs */ for (i = 1; i < argc; i++) { auto curr = std::string(argv[i]); if (curr.find('=') != std::string::npos) { // Take a string with '=' as env llenvv.push_back(curr); } else { break; } } /* Nothing left? */ if ( argc - i < 1 ) { print_usage(); exit(1); } /* Construct the argv and envv list */ std::string elf_filename(argv[i++]); llargv.push_back(elf_filename); for ( ; i < argc; i++) { llargv.push_back(std::string(argv[i])); } for (i = 0; envp[i]; i++) { llenvv.push_back(std::string(envp[i])); } /* Create the TCP/IP and Shadow channel * Test the connection and spawn the Proxy */ std::string shadow = readenv("SHADOWPROC", "/dev/shadow-process0"); auto io = IO("172.16.0.2", 42, verbose); VERBOSE("Testing Communication..."); io.ping(); auto pxy = Proxy(io, shadow, verbose); /* Reserve the Lower 1GB of the memory, used by application * to prevent libc and kernel being funky */ if (!mmap((void*)0x0, 0x40000000, PROT_NONE, MAP_SHARED, 0, 0)) { throw std::runtime_error("Unable to reserve the low memory space!"); } /* Reserve the Upper portion of the memory, used by Nuttx kernel * to prevent libc and kernel being funky */ if (!mmap((void*)KERNELMEM_VIRT_START, KERNELMEM_SIZE, PROT_NONE, MAP_SHARED, 0, 0)) { throw std::runtime_error("Unable to reserve the low memory space!"); } pxy.rexec(elf_filename, llargv, llenvv); return 0; }
25.908451
100
0.608046
fixstars
f239b20b515adeda1a89ac106b609cd22e0fef40
2,474
cpp
C++
app/src/main/cpp/Feature_Extraction/RSMelFilterBank.cpp
PetrFlajsingr/SpeechRecognition
23c675c7389b9ad97b18a8ba3739dceb04f42856
[ "Apache-2.0" ]
1
2019-04-18T06:33:09.000Z
2019-04-18T06:33:09.000Z
app/src/main/cpp/Feature_Extraction/RSMelFilterBank.cpp
PetrFlajsingr/SpeechRecognition
23c675c7389b9ad97b18a8ba3739dceb04f42856
[ "Apache-2.0" ]
null
null
null
app/src/main/cpp/Feature_Extraction/RSMelFilterBank.cpp
PetrFlajsingr/SpeechRecognition
23c675c7389b9ad97b18a8ba3739dceb04f42856
[ "Apache-2.0" ]
null
null
null
/* * Class providing interface to renderscript implementation of mel bank filters. * * Created by Petr Flajsingr on 15/12/2017. */ #include <RSMelFilterBank.h> #include <constants.h> SpeechRecognition::Feature_Extraction::RSMelFilterBank::RSMelFilterBank(const char* cacheDir) { this->renderScriptObject = new RS(); this->renderScriptObject->init(cacheDir); this->melRSinstance = new ScriptC_RSmelfilterbank(this->renderScriptObject); this->prepareAllocations(); } void SpeechRecognition::Feature_Extraction::RSMelFilterBank::prepareAllocations() { Element::Builder* elBuilder = new Element::Builder(this->renderScriptObject); elBuilder->add(Element::F32(this->renderScriptObject), "", FFT_FRAME_LENGTH); this->fftFrameAllocation = Allocation::createTyped(this->renderScriptObject, Type::create(this->renderScriptObject, elBuilder->create(), 1, 0, 0)); this->melIterationAllocation = Allocation::createSized(this->renderScriptObject, Element::U32(this->renderScriptObject), MEL_BANK_FRAME_LENGTH); uint32_t iter[MEL_BANK_FRAME_LENGTH]; for(uint32_t i = 0; i < MEL_BANK_FRAME_LENGTH; ++i) iter[i] = i; melIterationAllocation->copy1DFrom(iter); this->melBankAllocation = Allocation::createSized(this->renderScriptObject, Element::F32(this->renderScriptObject), MEL_BANK_FRAME_LENGTH); } float *SpeechRecognition::Feature_Extraction::RSMelFilterBank::calculateMelBank(kiss_fft_cpx *fftData) { fftFrameAllocation->copy1DFrom(fftData); this->melRSinstance->set_fftFrame(fftFrameAllocation); this->melRSinstance->forEach_melBank(melIterationAllocation, melBankAllocation); renderScriptObject->finish(); float* returnMelValues = new float[MEL_BANK_FRAME_LENGTH]; this->melBankAllocation->copy1DTo(returnMelValues); return returnMelValues; } void SpeechRecognition::Feature_Extraction::RSMelFilterBank::normalise(float *data) { for(int i = 0; i < MEL_BANK_FRAME_LENGTH; i++){ meanForNormalisation[i] = (meanForNormalisation[i] * elementCount + data[i]) / (elementCount + 1); data[i] = data[i] - meanForNormalisation[i]; } elementCount++; }
38.65625
134
0.657639
PetrFlajsingr