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 109 | 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 48.5k ⌀ | 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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
de3f0e25654f5c1a369c26c7b6896c2122a2fc29 | 252 | hpp | C++ | src/EventListener.hpp | OMKE/TalesOfAlester | 20ce17cf68ad956fc9d6f7cc3ac73a11c61f1118 | [
"MIT"
] | null | null | null | src/EventListener.hpp | OMKE/TalesOfAlester | 20ce17cf68ad956fc9d6f7cc3ac73a11c61f1118 | [
"MIT"
] | 1 | 2019-06-23T00:09:39.000Z | 2019-06-24T19:15:13.000Z | src/EventListener.hpp | OMKE/TalesOfAlester | 20ce17cf68ad956fc9d6f7cc3ac73a11c61f1118 | [
"MIT"
] | null | null | null | #ifndef EVENT_LISTENER_H
#define EVENT_LISTENER_H
#include "SDL2/SDL.h"
/*
** INTERFACE **
desc:
Interface that listens for events
*/
class EventListener {
public:
virtual void listen(SDL_Event &e) = 0;
};
#endif // EVENT_LISTENER_H | 14.823529 | 46 | 0.690476 | OMKE |
de3ffbb91f35912b778bef0b688156e258045e0f | 13,301 | cpp | C++ | net.ssa/xr_3da/xrGame/MainUI.cpp | ixray-team/xray-vss-archive | b245c8601dcefb505b4b51f58142da6769d4dc92 | [
"Linux-OpenIB"
] | 1 | 2022-03-26T17:00:19.000Z | 2022-03-26T17:00:19.000Z | xr_3da/xrGame/MainUI.cpp | ixray-team/xray-vss-archive | b245c8601dcefb505b4b51f58142da6769d4dc92 | [
"Linux-OpenIB"
] | null | null | null | xr_3da/xrGame/MainUI.cpp | ixray-team/xray-vss-archive | b245c8601dcefb505b4b51f58142da6769d4dc92 | [
"Linux-OpenIB"
] | 1 | 2022-03-26T17:00:21.000Z | 2022-03-26T17:00:21.000Z | #include "stdafx.h"
#include "MainUI.h"
#include "UI/UIDialogWnd.h"
#include "ui/UIMessageBoxEx.h"
#include "UICursor.h"
#include "HUDManager.h"
#include "../xr_IOConsole.h"
#include "../IGame_Level.h"
#include "../CameraManager.h"
#include "xr_Level_controller.h"
#include "ui\UITextureMaster.h"
#include "ui\UIXmlInit.h"
#include <dinput.h>
#include "ui\UIBtnHint.h"
extern CUICursor* GetUICursor(){return UI()->GetUICursor();};
extern CMainUI* UI(){return (CMainUI*)(g_pGamePersistent->m_pMainUI);};
//----------------------------------------------------------------------------------
void S2DVert::rotate_pt(const Fvector2& pivot, float cosA, float sinA)
{
Fvector2 t = pt;
t.sub (pivot);
pt.x = t.x*cosA+t.y*sinA;
pt.y = t.y*cosA-t.x*sinA;
pt.add (pivot);
}
void C2DFrustum::CreateFromRect (const Frect& rect)
{
m_rect.set(float(rect.x1), float(rect.y1), float(rect.x2), float(rect.y2) );
planes.resize (4);
planes[0].build (rect.lt, Fvector2().set(-1, 0));
planes[1].build (rect.lt, Fvector2().set( 0,-1));
planes[2].build (rect.rb, Fvector2().set(+1, 0));
planes[3].build (rect.rb, Fvector2().set( 0,+1));
}
sPoly2D* C2DFrustum::ClipPoly (sPoly2D& S, sPoly2D& D) const
{
bool bFullTest = false;
for (u32 j=0; j<S.size(); j++)
{
if( !m_rect.in(S[j].pt) ) {
bFullTest = true;
break ;
}
}
sPoly2D* src = &D;
sPoly2D* dest = &S;
if(!bFullTest) return dest;
for (u32 i=0; i<planes.size(); i++)
{
// cache plane and swap lists
const Fplane2 &P = planes[i] ;
std::swap (src,dest) ;
dest->clear () ;
// classify all points relative to plane #i
float cls[UI_FRUSTUM_SAFE] ;
for (u32 j=0; j<src->size(); j++) cls[j]=P.classify((*src)[j].pt);
// clip everything to this plane
cls[src->size()] = cls[0] ;
src->push_back((*src)[0]) ;
Fvector2 dir_pt,dir_uv; float denum,t;
for (j=0; j<src->size()-1; j++) {
if ((*src)[j].pt.similar((*src)[j+1].pt,EPS_S)) continue;
if (negative(cls[j])) {
dest->push_back((*src)[j]) ;
if (positive(cls[j+1])) {
// segment intersects plane
dir_pt.sub((*src)[j+1].pt,(*src)[j].pt);
dir_uv.sub((*src)[j+1].uv,(*src)[j].uv);
denum = P.n.dotproduct(dir_pt);
if (denum!=0) {
t = -cls[j]/denum ; //VERIFY(t<=1.f && t>=0);
dest->last().pt.mad ((*src)[j].pt,dir_pt,t);
dest->last().uv.mad ((*src)[j].uv,dir_uv,t);
dest->inc();
}
}
} else {
// J - outside
if (negative(cls[j+1])) {
// J+1 - inside
// segment intersects plane
dir_pt.sub((*src)[j+1].pt,(*src)[j].pt);
dir_uv.sub((*src)[j+1].uv,(*src)[j].uv);
denum = P.n.dotproduct(dir_pt);
if (denum!=0) {
t = -cls[j]/denum ; //VERIFY(t<=1.f && t>=0);
dest->last().pt.mad ((*src)[j].pt,dir_pt,t);
dest->last().uv.mad ((*src)[j].uv,dir_uv,t);
dest->inc();
}
}
}
}
// here we end up with complete polygon in 'dest' which is inside plane #i
if (dest->size()<3) return 0;
}
return dest;
}
//----------------------------------------------------------------------------------
CMainUI::CMainUI ()
{
m_Flags.zero ();
m_startDialog = NULL;
m_pUICursor = xr_new<CUICursor>();
m_pFontManager = xr_new<CFontManager>();
g_pGamePersistent->m_pMainUI= this;
if (Device.bReady) OnDeviceCreate();
ReadTextureInfo ();
CUIXmlInit::InitColorDefs ();
g_btnHint = xr_new<CUIButtonHint>();
m_bPostprocess = false;
m_pMessageBox = NULL;
//m_pMessageInvalidPass = NULL;
//m_pMessageSessionFull = NULL;
}
CMainUI::~CMainUI ()
{
xr_delete (g_btnHint);
xr_delete (m_startDialog);
xr_delete (m_pFontManager);
xr_delete (m_pUICursor);
xr_delete (m_pMessageBox);
//xr_delete (m_pMessageInvalidPass);
//xr_delete (m_pMessageSessionFull);
g_pGamePersistent->m_pMainUI = NULL;
CUITextureMaster::WriteLog ();
}
void CMainUI::ReadTextureInfo(){
if (pSettings->section_exist("texture_desc"))
{
xr_string itemsList;
string256 single_item;
itemsList = pSettings->r_string("texture_desc", "files");
int itemsCount = _GetItemCount(itemsList.c_str());
for (int i = 0; i < itemsCount; i++)
{
_GetItem(itemsList.c_str(), i, single_item);
strcat(single_item,".xml");
CUITextureMaster::ParseShTexInfo(single_item);
}
}
}
void CMainUI::Activate (bool bActivate)
{
if(!!m_Flags.is(flActive) == bActivate) return;
if(bActivate){
m_Flags.set (flActive|flNeedChangeCapture,TRUE);
DLL_Pure* dlg = NEW_INSTANCE (TEXT2CLSID("MAIN_MNU"));
if(!dlg) {
m_Flags.set (flActive|flNeedChangeCapture,FALSE);
return;
}
xr_delete(m_startDialog);
m_startDialog = smart_cast<CUIDialogWnd*>(dlg);
VERIFY(m_startDialog);
m_Flags.set (flRestoreConsole,Console->bVisible);
m_Flags.set (flRestorePause,Device.Pause());
Console->Hide ();
m_Flags.set (flRestoreCursor,GetUICursor()->IsVisible());
if(!m_Flags.is(flRestorePause))
Device.Pause (TRUE);
::Sound->set_volume (1.0f);// pause set to 0
StartStopMenu (m_startDialog,true);
if(g_pGameLevel){
Device.seqFrame.Remove (g_pGameLevel);
Device.seqRender.Remove (g_pGameLevel);
CCameraManager::ResetPP ();
};
Device.seqRender.Add (this, 3); // 1-console 2-cursor
}else{
m_Flags.set (flActive, FALSE);
m_Flags.set (flNeedChangeCapture, TRUE);
Device.seqRender.Remove (this);
bool b = !!Console->bVisible;
if(b){
Console->Hide ();
}
IR_Release ();
if(b){
Console->Show ();
}
CleanInternals ();
if(g_pGameLevel){
Device.seqFrame.Add (g_pGameLevel);
Device.seqRender.Add (g_pGameLevel);
};
if(m_Flags.is(flRestoreConsole))
Console->Show ();
if(!m_Flags.is(flRestorePause))
Device.Pause(FALSE);
if(m_Flags.is(flRestoreCursor))
GetUICursor()->Show();
}
}
bool CMainUI::IsActive ()
{
return !!m_Flags.is(flActive);
}
//IInputReceiver
static int mouse_button_2_key [] = {MOUSE_1,MOUSE_2,MOUSE_3};
void CMainUI::IR_OnMousePress (int btn)
{
if(!IsActive()) return;
IR_OnKeyboardPress(mouse_button_2_key[btn]);
};
void CMainUI::IR_OnMouseRelease (int btn)
{
if(!IsActive()) return;
IR_OnKeyboardRelease(mouse_button_2_key[btn]);
};
void CMainUI::IR_OnMouseHold (int btn)
{
if(!IsActive()) return;
IR_OnKeyboardHold(mouse_button_2_key[btn]);
};
void CMainUI::IR_OnMouseMove (int x, int y)
{
if(!IsActive()) return;
MainInputReceiver()->IR_OnMouseMove(x, y);
};
void CMainUI::IR_OnMouseStop (int x, int y)
{
if(!IsActive()) return;
};
void CMainUI::IR_OnKeyboardPress (int dik)
{
if(!IsActive()) return;
if(key_binding[dik]== kCONSOLE){
Console->Show();
return;
}
if (DIK_F12 == dik){
Render->Screenshot();
return;
}
MainInputReceiver()->IR_OnKeyboardPress( dik);
};
void CMainUI::IR_OnKeyboardRelease (int dik)
{
if(!IsActive()) return;
MainInputReceiver()->IR_OnKeyboardRelease(dik);
};
void CMainUI::IR_OnKeyboardHold (int dik)
{
if(!IsActive()) return;
};
void CMainUI::IR_OnMouseWheel(int direction)
{
if(!IsActive()) return;
MainInputReceiver()->IR_OnMouseWheel(direction);
}
bool CMainUI::OnRenderPPUI_query()
{
return IsActive() && !m_Flags.is(flGameSaveScreenshot);
}
void CMainUI::OnRender ()
{
if(m_Flags.is(flGameSaveScreenshot))
return;
Render->Render ();
}
void CMainUI::OnRenderPPUI_main ()
{
if(!IsActive()) return;
if(m_Flags.is(flGameSaveScreenshot)){
return;
};
m_bPostprocess = true;
m_2DFrustum2.CreateFromRect (Frect().set( 0.0f,
0.0f,
ClientToScreenScaledX(UI_BASE_WIDTH),
ClientToScreenScaledY(UI_BASE_HEIGHT)
));
DoRenderDialogs();
m_pFontManager->Render();
m_bPostprocess = false;
}
void CMainUI::OnRenderPPUI_PP ()
{
if(!IsActive()) return;
m_bPostprocess = true;
xr_vector<CUIWindow*>::iterator it = m_pp_draw_wnds.begin();
for(; it!=m_pp_draw_wnds.end();++it){
(*it)->Draw();
}
m_bPostprocess = false;
}
//pureFrame
void CMainUI::OnFrame (void)
{
m_2DFrustum.CreateFromRect (Frect().set( 0.0f,
0.0f,
ClientToScreenScaledX(UI_BASE_WIDTH),
ClientToScreenScaledY(UI_BASE_HEIGHT)
));
if(!IsActive() && m_startDialog){
xr_delete (m_startDialog);
}
if (m_Flags.is(flNeedChangeCapture)){
m_Flags.set (flNeedChangeCapture,FALSE);
if (m_Flags.is(flActive)) IR_Capture();
else IR_Release();
}
CDialogHolder::OnFrame ();
//screenshot stuff
if(m_Flags.is(flGameSaveScreenshot) && Device.dwFrame > m_screenshotFrame ){
m_Flags.set (flGameSaveScreenshot,FALSE);
::Render->Screenshot (IRender_interface::SM_FOR_GAMESAVE, m_screenshot_name);
if(g_pGameLevel && m_Flags.is(flActive)){
Device.seqFrame.Remove (g_pGameLevel);
Device.seqRender.Remove (g_pGameLevel);
};
if(m_Flags.is(flRestoreConsole))
Console->Show ();
}
}
void CMainUI::OnDeviceCreate()
{
}
void CMainUI::ClientToScreenScaled(Fvector2& dest, float left, float top)
{
dest.set(ClientToScreenScaledX(left), ClientToScreenScaledY(top));
}
float CMainUI::ClientToScreenScaledX(float left)
{
return left * GetScaleX();
}
float CMainUI::ClientToScreenScaledY(float top)
{
return top * GetScaleY();
}
void CMainUI::OutText(CGameFont *pFont, Frect r, float x, float y, LPCSTR fmt, ...)
{
if (r.in(x, y))
{
R_ASSERT(pFont);
va_list lst;
static string512 buf;
::ZeroMemory(buf, 512);
xr_string str;
va_start(lst, fmt);
vsprintf(buf, fmt, lst);
str += buf;
va_end(lst);
// Rescale position in lower resolution
if (x >= 1.0f && y >= 1.0f)
{
x *= GetScaleX();
y *= GetScaleY();
}
pFont->Out(x, y, "%s", str.c_str());
}
}
Frect CMainUI::ScreenRect()
{
static Frect R={0.0f, 0.0f, UI_BASE_WIDTH, UI_BASE_HEIGHT};
return R;
}
void CMainUI::PushScissor(const Frect& r_tgt, bool overlapped)
{
// return;
Frect r_top = ScreenRect();
Frect result = r_tgt;
if (!m_Scissors.empty()&&!overlapped){
r_top = m_Scissors.top();
}
if (!result.intersection(r_top,r_tgt))
result.set (0.0f,0.0f,0.0f,0.0f);
VERIFY(result.x1>=0&&result.y1>=0&&result.x2<=UI_BASE_WIDTH&&result.y2<=UI_BASE_HEIGHT);
m_Scissors.push (result);
result.lt.x = ClientToScreenScaledX(result.lt.x);
result.lt.y = ClientToScreenScaledY(result.lt.y);
result.rb.x = ClientToScreenScaledX(result.rb.x);
result.rb.y = ClientToScreenScaledY(result.rb.y);
Irect r;
r.x1 = iFloor(result.x1);
r.x2 = iFloor(result.x2+0.5f);
r.y1 = iFloor(result.y1);
r.y2 = iFloor(result.y2+0.5f);
VERIFY(r.x1>=0&&r.y1>=0&&(r.x2<=UI_BASE_WIDTH*GetScaleX())&&(r.y2<=UI_BASE_HEIGHT*GetScaleY()));
RCache.set_Scissor (&r);
}
void CMainUI::PopScissor()
{
// return;
VERIFY(!m_Scissors.empty());
m_Scissors.pop ();
if(m_Scissors.empty())
RCache.set_Scissor(NULL);
else{
const Frect& top= m_Scissors.top();
Irect tgt;
tgt.lt.x = iFloor(ClientToScreenScaledX(top.lt.x));
tgt.lt.y = iFloor(ClientToScreenScaledY(top.lt.y));
tgt.rb.x = iFloor(ClientToScreenScaledX(top.rb.x));
tgt.rb.y = iFloor(ClientToScreenScaledY(top.rb.y));
RCache.set_Scissor(&tgt);
}
}
void CMainUI::Screenshot (IRender_interface::ScreenshotMode mode, LPCSTR name)
{
if(mode != IRender_interface::SM_FOR_GAMESAVE){
::Render->Screenshot (mode,name);
}else{
m_Flags.set (flGameSaveScreenshot, TRUE);
strcpy(m_screenshot_name,name);
if(g_pGameLevel && m_Flags.is(flActive)){
Device.seqFrame.Add (g_pGameLevel);
Device.seqRender.Add (g_pGameLevel);
};
m_screenshotFrame = Device.dwFrame+1;
m_Flags.set (flRestoreConsole, Console->bVisible);
Console->Hide ();
}
}
void CMainUI::RegisterPPDraw (CUIWindow* w)
{
UnregisterPPDraw (w);
m_pp_draw_wnds.push_back (w);
}
void CMainUI::UnregisterPPDraw (CUIWindow* w)
{
xr_vector<CUIWindow*>::iterator it = remove( m_pp_draw_wnds.begin(), m_pp_draw_wnds.end(), w);
m_pp_draw_wnds.erase(it, m_pp_draw_wnds.end());
}
void CMainUI::OnInvalidHost(){
if (!m_pMessageBox)
{
m_pMessageBox = xr_new<CUIMessageBoxEx>();
}
m_pMessageBox->Init("message_box_invalid_host");
StartStopMenu(m_pMessageBox, false);
}
void CMainUI::OnInvalidPass(){
if (!m_pMessageBox)
{
m_pMessageBox = xr_new<CUIMessageBoxEx>();
}
m_pMessageBox->Init("message_box_invalid_pass");
StartStopMenu(m_pMessageBox, false);
}
void CMainUI::OnSessionFull(){
if (!m_pMessageBox)
{
m_pMessageBox = xr_new<CUIMessageBoxEx>();
}
m_pMessageBox->Init("message_box_session_full");
StartStopMenu(m_pMessageBox, false);
}
void CMainUI::OnServerReject(){
if (!m_pMessageBox)
{
m_pMessageBox = xr_new<CUIMessageBoxEx>();
}
m_pMessageBox->Init("message_box_server_reject");
StartStopMenu(m_pMessageBox, false);
} | 24.495396 | 98 | 0.62469 | ixray-team |
de4224e4307f30cf5295d56be1e578b5f2e27acc | 879 | cpp | C++ | chap10/Page386_predicate.cpp | sjbarigye/CPP_Primer | d9d31a73a45ca46909bae104804fc9503ab242f2 | [
"Apache-2.0"
] | 50 | 2016-01-08T14:28:53.000Z | 2022-01-21T12:55:00.000Z | chap10/Page386_predicate.cpp | sjbarigye/CPP_Primer | d9d31a73a45ca46909bae104804fc9503ab242f2 | [
"Apache-2.0"
] | 2 | 2017-06-05T16:45:20.000Z | 2021-04-17T13:39:24.000Z | chap10/Page386_predicate.cpp | sjbarigye/CPP_Primer | d9d31a73a45ca46909bae104804fc9503ab242f2 | [
"Apache-2.0"
] | 18 | 2016-08-17T15:23:51.000Z | 2022-03-26T18:08:43.000Z | #include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using std::cout;
using std::endl;
using std::string;
using std::vector;
bool isShorter(const string &s1, const string &s2)
{
return s1.size() < s2.size();
}
void elimDups(vector<string> &words)
{
sort(words.begin(), words.end());
auto end_unique = unique(words.begin(), words.end());
words.erase(end_unique, words.end());
}
int main()
{
vector<string> story = { "the", "quick", "red", "fox", "jump", "over", "the", "slow", "red", "turtle" };
elimDups(story);
for(const auto &s : story)
cout << s << " ";
cout << endl;
// we cannot put isShorter into sort, or the first order will be length rather than alphabet
stable_sort(story.begin(), story.end(), isShorter);
for(const auto &s : story)
cout << s << " ";
cout << endl;
return 0;
}
| 26.636364 | 108 | 0.612059 | sjbarigye |
de44d8873b4bd0425df24b1db6e97e6e2c4c982c | 5,204 | cpp | C++ | main.cpp | maltsevda/FakeD3D9 | 9d14b19cef9a9795847961101aa5378491624af5 | [
"MIT"
] | 12 | 2019-05-14T04:50:06.000Z | 2022-03-22T09:28:54.000Z | main.cpp | maltsevda/FakeD3D9 | 9d14b19cef9a9795847961101aa5378491624af5 | [
"MIT"
] | null | null | null | main.cpp | maltsevda/FakeD3D9 | 9d14b19cef9a9795847961101aa5378491624af5 | [
"MIT"
] | 2 | 2020-07-06T18:45:38.000Z | 2022-02-06T23:40:49.000Z | #define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include "FakeDirect3D9.h"
struct OriginalLibrary
{
HMODULE hDll;
FARPROC D3DPERF_BeginEvent;
FARPROC D3DPERF_EndEvent;
FARPROC D3DPERF_GetStatus;
FARPROC D3DPERF_QueryRepeatFrame;
FARPROC D3DPERF_SetMarker;
FARPROC D3DPERF_SetOptions;
FARPROC D3DPERF_SetRegion;
FARPROC DebugSetLevel;
FARPROC DebugSetMute;
FARPROC Direct3D9EnableMaximizedWindowedModeShim;
FARPROC Direct3DCreate9;
FARPROC Direct3DCreate9Ex;
FARPROC Direct3DShaderValidatorCreate9;
FARPROC PSGPError;
FARPROC PSGPSampleTexture;
} d3d9dll;
extern "C" __declspec(naked) void Fake_D3DPERF_BeginEvent() { _asm { jmp[d3d9dll.D3DPERF_BeginEvent] } }
extern "C" __declspec(naked) void Fake_D3DPERF_EndEvent() { _asm { jmp[d3d9dll.D3DPERF_EndEvent] } }
extern "C" __declspec(naked) void Fake_D3DPERF_GetStatus() { _asm { jmp[d3d9dll.D3DPERF_GetStatus] } }
extern "C" __declspec(naked) void Fake_D3DPERF_QueryRepeatFrame() { _asm { jmp[d3d9dll.D3DPERF_QueryRepeatFrame] } }
extern "C" __declspec(naked) void Fake_D3DPERF_SetMarker() { _asm { jmp[d3d9dll.D3DPERF_SetMarker] } }
extern "C" __declspec(naked) void Fake_D3DPERF_SetOptions() { _asm { jmp[d3d9dll.D3DPERF_SetOptions] } }
extern "C" __declspec(naked) void Fake_D3DPERF_SetRegion() { _asm { jmp[d3d9dll.D3DPERF_SetRegion] } }
extern "C" __declspec(naked) void Fake_DebugSetLevel() { _asm { jmp[d3d9dll.DebugSetLevel] } }
extern "C" __declspec(naked) void Fake_DebugSetMute() { _asm { jmp[d3d9dll.DebugSetMute] } }
extern "C" __declspec(naked) void Fake_Direct3D9EnableMaximizedWindowedModeShim() { _asm { jmp[d3d9dll.Direct3D9EnableMaximizedWindowedModeShim] } }
// extern "C" __declspec(naked) void Fake_Direct3DCreate9() { _asm { jmp[d3d9dll.Direct3DCreate9] } }
extern "C" __declspec(naked) void Fake_Direct3DCreate9Ex() { _asm { jmp[d3d9dll.Direct3DCreate9Ex] } }
extern "C" __declspec(naked) void Fake_Direct3DShaderValidatorCreate9() { _asm { jmp[d3d9dll.Direct3DShaderValidatorCreate9] } }
extern "C" __declspec(naked) void Fake_PSGPError() { _asm { jmp[d3d9dll.PSGPError] } }
extern "C" __declspec(naked) void Fake_PSGPSampleTexture() { _asm { jmp[d3d9dll.PSGPSampleTexture] } }
extern "C" IDirect3D9* WINAPI Fake_Direct3DCreate9(UINT SDKVersion)
{
typedef IDirect3D9* (WINAPI * DIRECT3DCREATEPROC)(UINT SDKVersion);
DIRECT3DCREATEPROC Direct3DCreate9Proc = (DIRECT3DCREATEPROC)d3d9dll.Direct3DCreate9;
IDirect3D9* pRealDirect3D9 = Direct3DCreate9Proc(SDKVersion);
return new FakeDirect3D9(pRealDirect3D9);
}
// error LNK2019: unresolved external symbol _memcpy referenced in function _DllMain@12
void MyCopyMemory(void* pDst, const void* pSrc, size_t uiSize)
{
BYTE* pDstB = (BYTE*)pDst;
const BYTE* pSrcB = (const BYTE*)pSrc;
for (UINT i = 0; i < uiSize; ++i)
pDstB[i] = pSrcB[i];
}
BOOL APIENTRY DllMain(HMODULE hModule, DWORD dwReason, LPVOID lpReserved)
{
switch (dwReason)
{
case DLL_PROCESS_ATTACH:
{
WCHAR path[MAX_PATH];
UINT length = GetSystemDirectoryW(path, MAX_PATH - 10);
MyCopyMemory(path + length, L"\\d3d9.dll", sizeof(WCHAR) * 10);
d3d9dll.hDll = LoadLibraryW(path);
if (!d3d9dll.hDll)
{
MessageBoxW(0, L"Cannot load original d3d9.dll library", L"d3d9.dll proxy", MB_ICONERROR);
ExitProcess(0);
}
d3d9dll.D3DPERF_BeginEvent = GetProcAddress(d3d9dll.hDll, "D3DPERF_BeginEvent");
d3d9dll.D3DPERF_EndEvent = GetProcAddress(d3d9dll.hDll, "D3DPERF_EndEvent");
d3d9dll.D3DPERF_GetStatus = GetProcAddress(d3d9dll.hDll, "D3DPERF_GetStatus");
d3d9dll.D3DPERF_QueryRepeatFrame = GetProcAddress(d3d9dll.hDll, "D3DPERF_QueryRepeatFrame");
d3d9dll.D3DPERF_SetMarker = GetProcAddress(d3d9dll.hDll, "D3DPERF_SetMarker");
d3d9dll.D3DPERF_SetOptions = GetProcAddress(d3d9dll.hDll, "D3DPERF_SetOptions");
d3d9dll.D3DPERF_SetRegion = GetProcAddress(d3d9dll.hDll, "D3DPERF_SetRegion");
d3d9dll.DebugSetLevel = GetProcAddress(d3d9dll.hDll, "DebugSetLevel");
d3d9dll.DebugSetMute = GetProcAddress(d3d9dll.hDll, "DebugSetMute");
d3d9dll.Direct3D9EnableMaximizedWindowedModeShim = GetProcAddress(d3d9dll.hDll, "Direct3D9EnableMaximizedWindowedModeShim");
d3d9dll.Direct3DCreate9 = GetProcAddress(d3d9dll.hDll, "Direct3DCreate9");
d3d9dll.Direct3DCreate9Ex = GetProcAddress(d3d9dll.hDll, "Direct3DCreate9Ex");
d3d9dll.Direct3DShaderValidatorCreate9 = GetProcAddress(d3d9dll.hDll, "Direct3DShaderValidatorCreate9");
d3d9dll.PSGPError = GetProcAddress(d3d9dll.hDll, "PSGPError");
d3d9dll.PSGPSampleTexture = GetProcAddress(d3d9dll.hDll, "PSGPSampleTexture");
break;
}
case DLL_PROCESS_DETACH:
FreeLibrary(d3d9dll.hDll);
break;
}
return TRUE;
}
// error LNK2001: unresolved external symbol "void * __cdecl operator new(unsigned int)" (??2@YAPAXI@Z)
void* __cdecl operator new(unsigned int size)
{
return HeapAlloc(GetProcessHeap(), 0, size);
}
// error LNK2001: unresolved external symbol "void __cdecl operator delete(void *,unsigned int)" (??3@YAXPAXI@Z)
void __cdecl operator delete(void* ptr, unsigned int)
{
HeapFree(GetProcessHeap(), 0, ptr);
}
// error LNK2001: unresolved external symbol __fltused
// it should be a single underscore since the double one is the mangled name
extern "C" int _fltused = 0;
| 46.464286 | 148 | 0.777479 | maltsevda |
de4b9b0c96f9648057d5d578f6104890301b0ab5 | 32,686 | cpp | C++ | src/z_zodiacreader.cpp | SpehleonLP/Zodiac | 19ec600c269afda4ef15dead9ed614320fecb14a | [
"MIT"
] | null | null | null | src/z_zodiacreader.cpp | SpehleonLP/Zodiac | 19ec600c269afda4ef15dead9ed614320fecb14a | [
"MIT"
] | null | null | null | src/z_zodiacreader.cpp | SpehleonLP/Zodiac | 19ec600c269afda4ef15dead9ed614320fecb14a | [
"MIT"
] | null | null | null | #include "z_zodiacreader.h"
#ifdef HAVE_ZODIAC
#include "z_zodiacwriter.h"
#include "z_zodiac.h"
#include "z_zodiaccontext.h"
#include "z_zodiacexception.h"
#include <stdexcept>
#include <cstring>
#include <cassert>
#include <cstring>
#include <stdexcept>
#include "add_on/scriptdictionary/scriptdictionary.h"
namespace Zodiac
{
zCZodiacReader::zCZodiacReader(zCZodiac * parent, zIFileDescriptor * file, std::atomic<int> & progress, std::atomic<int> & total_steps) :
m_parent(parent),
m_file(file),
m_mmap(file),
m_progress(progress),
m_totalSteps(total_steps)
{
m_header = (zCHeader const*)(m_mmap.GetAddress() + (m_mmap.GetLength() - sizeof(zCHeader)));
m_stringTable = (char const *)(m_mmap.GetAddress() + m_header->stringTableOffset);
m_entries = (zCEntry const*)(m_mmap.GetAddress() + m_header->addressTableOffset);
m_modules = (zCModule const*)(m_mmap.GetAddress() + m_header->moduleDataOffset);
m_typeInfo = (zCTypeInfo const*)(m_mmap.GetAddress() + m_header->typeInfoOffset);
m_globals = (zCGlobalInfo const*)(m_mmap.GetAddress() + m_header->globalsOffset);
Verify();
m_loadedObjects.reset(new LoadedInfo[addressTableLength()]);
memset(&m_loadedObjects[0], 0, addressTableLength() * sizeof(LoadedInfo));
m_progress = 0;
m_totalSteps = addressTableLength();
}
zCZodiacReader::~zCZodiacReader()
{
//return;
if(m_loadedObjects != nullptr)
{
auto engine = GetEngine();
for(uint32_t i = 0; i < addressTableLength(); ++i)
{
if(!m_loadedObjects[i].needRelease) continue;
auto typeInfo = engine->GetTypeInfoById(m_loadedObjects[i].asTypeId);
while(m_loadedObjects[i].needRelease-- > 0)
{
engine->ReleaseScriptObject(m_loadedObjects[i].ptr, typeInfo);
}
}
}
}
void zCZodiacReader::Verify() const
{
void * end = (void*)(m_mmap.GetAddress() + m_mmap.GetLength());
zCHeader check;
if(strncmp(check.magic, m_header->magic, sizeof(check.magic)) != 0)
throw Exception("Not a zodiac file.", zE_BadFileType);
if(m_header->saveDataByteOffset + saveDataByteLength() > m_mmap.GetLength())
throw Exception("save data", zE_BufferOverrun);
//-----------------------
// CHECK STRINGS
//----------------------
if(GetStringAddresses() + stringAddressCount() > end)
throw Exception("string entry", zE_BufferOverrun);
if(m_stringTable + stringTableLength() > end)
throw Exception("string table", zE_BufferOverrun);
for(uint32_t i = 0; i < stringAddressCount(); ++i)
{
if(GetStringAddresses()[i] > stringTableLength())
{
throw Exception("string address", zE_BufferOverrun);
}
}
//-----------------------
// CHECK ENTRIES
//----------------------
if(m_entries + addressTableLength() > end)
throw Exception("address table", zE_BufferOverrun);
for(uint32_t i = 0; i < addressTableLength(); ++i)
{
if(m_header->savedObjectOffset > m_entries[i].offset)
{
throw Exception("entry save location", zE_BufferOverrun);
}
uint32_t entry_end = (m_entries[i].offset + m_entries[i].byteLength) - m_header->savedObjectOffset;
if(entry_end > m_header->savedObjectLength)
{
throw Exception("entry save size", zE_BufferOverrun);
}
}
//-----------------------
// CHECK MODULES
//----------------------
if(m_modules + moduleDataLength() > end)
throw Exception("module table", zE_BufferOverrun);
for(uint32_t i = 0; i < moduleDataLength(); ++i)
{
if(m_modules[i].name > stringTableLength())
{
throw Exception("name in module", zE_BufferOverrun);
}
if(m_header->byteCodeOffset > m_modules[i].byteCodeOffset || m_modules[i].byteCodeOffset + m_modules[i].byteCodeLength > m_header->byteCodeOffset + m_header->byteCodeByteLength)
{
throw Exception("byte code in module", zE_BufferOverrun);
}
if(m_modules[i].beginTypeInfo + m_modules[i].typeInfoLength > typeInfoLength())
{
throw Exception("asTypeInfo in module", zE_BufferOverrun);
}
if(m_modules[i].beginGlobalInfo + m_modules[i].globalsLength > globalsLength())
{
throw Exception("global variables in module", zE_BufferOverrun);
}
}
//-----------------------
// CHECK Functions
//----------------------
if(GetFunctions() + functionTableLength() > end)
throw Exception("function table", zE_BufferOverrun);
for(uint32_t i = 0; i < functionTableLength(); ++i)
{
auto & function = GetFunctions()[i];
if(function.delegateAddress > addressTableLength())
{
throw Exception("entry id in function", zE_BufferOverrun);
}
if(function.delegateTypeId > typeInfoLength())
{
throw Exception("delegate id in function", zE_BufferOverrun);
}
if(function.module > stringTableLength())
{
throw Exception("module id in function", zE_BufferOverrun);
}
if(function.objectType > typeTableLength())
{
throw Exception("typeId in function", zE_BufferOverrun);
}
if(function.declaration > stringTableLength())
{
throw Exception("declaration in function", zE_BufferOverrun);
}
}
//-----------------------
// CHECK Globals
//----------------------
if(m_globals + globalsLength() > end)
throw Exception("global variables", zE_BufferOverrun);
for(uint32_t i = 0; i < globalsLength(); ++i)
{
if(m_globals[i].name > stringTableLength())
{
throw Exception("name in global", zE_BufferOverrun);
}
if(m_globals[i].nameSpace > stringTableLength())
{
throw Exception("namespace in global", zE_BufferOverrun);
}
if(m_globals[i].address > addressTableLength())
{
throw Exception("entry id in global", zE_BufferOverrun);
}
}
//-----------------------
// CHECK TypeInfo
//----------------------
if(m_typeInfo + typeInfoLength() > end)
throw Exception("type info", zE_BufferOverrun);
for(uint32_t i = 0; i < typeInfoLength(); ++i)
{
auto & typeInfo = m_typeInfo[i];
if(typeInfo.name > stringTableLength())
{
throw Exception("name in typeInfo", zE_BufferOverrun);
}
if(typeInfo.nameSpace > stringTableLength())
{
throw Exception("namespace in typeInfo", zE_BufferOverrun);
}
if(typeInfo.propertiesBegin + typeInfo.propertiesLength > propertiesLength())
{
throw Exception("properties in typeInfo", zE_BufferOverrun);
}
}
//-----------------------
// CHECK Properties
//----------------------
zCProperty const* pBegin, * pEnd;
GetProperties(-1, pBegin, pEnd);
for(auto p = pBegin; p < pEnd; ++p)
{
if(p->name > stringTableLength())
{
throw Exception("name in property", zE_BufferOverrun);
}
if( p->typeId & asTYPEID_MASK_OBJECT
&& (p->typeId & asTYPEID_MASK_SEQNBR) > typeTableLength())
{
throw Exception("typeId in property", zE_BufferOverrun);
}
}
//-----------------------
// CHECK Templates
//----------------------
if(GetTemplates() + templatesLength() > end)
throw Exception("templates", zE_BufferOverrun);
for(uint32_t i = 0; i < templatesLength(); ++i)
{
auto & _template = GetTemplates()[i];
if(_template.name > stringTableLength())
{
throw Exception("name in template", zE_BufferOverrun);
}
if(_template.nameSpace > stringTableLength())
{
throw Exception("namespace in template", zE_BufferOverrun);
}
if(_template.module > stringTableLength())
{
throw Exception("module in template", zE_BufferOverrun);
}
if(_template.declaration > stringTableLength())
{
throw Exception("declaration in template", zE_BufferOverrun);
}
}
}
void zCZodiacReader::ReadSaveData(zREADER_FUNC_t func, void * userData)
{
if(func)
{
zIFileDescriptor::ReadSubFile sub_file(m_file, m_header->saveDataByteOffset, m_header->saveDataByteLength);
func(this, userData);
}
}
void zCZodiacReader::DocumentGlobalVariables(asIScriptEngine * engine)
{
int typeId;
const char *name, *nameSpace;
uint32_t noModules = engine->GetModuleCount();
for(uint32_t i = 0; i < noModules; ++i)
{
auto mod = engine->GetModuleByIndex(i);
int index = GetModuleIndex(mod->GetName(), i);
if(index < 0) continue;
uint32_t varCount = mod->GetGlobalVarCount();
for(uint32_t j = 0; j < varCount; j++ )
{
mod->GetGlobalVar(j, &name, &nameSpace, &typeId);
zCGlobalInfo const* global = GetGlobalVar(index, name, nameSpace, j);
PopulateTable( mod->GetAddressOfGlobalVar(j), global->address, typeId);
}
}
}
void zCZodiacReader::RestoreGlobalVariables(asIScriptEngine * engine)
{
int typeId;
const char *name, *nameSpace;
uint32_t noModules = engine->GetModuleCount();
for(uint32_t i = 0; i < noModules; ++i)
{
auto mod = engine->GetModuleByIndex(i);
int index = GetModuleIndex(mod->GetName(), i);
if(index < 0) continue;
uint32_t varCount = mod->GetGlobalVarCount();
for(uint32_t j = 0; j < varCount; j++ )
{
mod->GetGlobalVar(j, &name, &nameSpace, &typeId);
zCGlobalInfo const* global = GetGlobalVar(index, name, nameSpace, j);
if(global)
LoadScriptObject(mod->GetAddressOfGlobalVar(j), global->address, typeId);
}
}
}
template<typename T>
static asITypeInfo * GetEnumByIndex(T * t, int i) { return t->GetEnumByIndex(i); }
template<typename T>
static asITypeInfo * GetObjectTypeByIndex(T * t, int i) { return t->GetObjectTypeByIndex(i); }
template<typename T>
static asITypeInfo * GetTypedefByIndex(T * t, int i) { return t->GetTypedefByIndex(i); }
static asITypeInfo * GetFuncdefByIndex(asIScriptEngine * t, int i) { return t->GetFuncdefByIndex(i); }
template<typename T>
inline void zCZodiacReader::SolveTypeInfo(T * op, int i, uint32_t & quickCheck, asITypeInfo* (GetterFunc)(T*, int), uint32_t N)
{
for(uint32_t j = 0; j < N; ++j)
{
auto typeInfo = GetterFunc(op, j);
auto type = GetTypeInfo(i, typeInfo->GetName(), typeInfo->GetNamespace(), &quickCheck);
if(type != nullptr)
{
assert(m_asTypeIdFromStored[type - m_typeInfo] == 0);
m_asTypeIdFromStored[type - m_typeInfo] = typeInfo->GetTypeId();
}
}
}
template<typename T>
inline void zCZodiacReader::SolveTypeInfo(T * op, int i)
{
uint32_t quickCheck{};
SolveTypeInfo(op, i, quickCheck, &GetObjectTypeByIndex<T>, op->GetObjectTypeCount());
SolveTypeInfo(op, i, quickCheck, &GetEnumByIndex<T>, op->GetEnumCount());
}
bool zCZodiacReader::LoadByteCode(asIScriptEngine * engine)
{
bool loadedByteCode;
for(uint32_t i = 0; i < moduleDataLength() - 1; ++i)
{
// bool created = false;
auto moduleName = LoadString(m_modules[i].name);
asIScriptModule * module = engine->GetModule(moduleName, asGM_ONLY_IF_EXISTS);
if(!module && m_modules[i].byteCodeLength != 0)
{
module = engine->GetModule(moduleName, asGM_ALWAYS_CREATE);
zIFileDescriptor::ReadSubFile sub_file(m_file, m_modules[i].byteCodeOffset, m_modules[i].byteCodeLength);
module->LoadByteCode(m_file, nullptr);
loadedByteCode = true;
}
}
//bind imports
if(loadedByteCode)
{
auto noModules = engine->GetModuleCount();
for(uint32_t i = 0; i < noModules; ++i)
{
engine->GetModuleByIndex(i)->BindAllImportedFunctions();
}
}
return loadedByteCode;
}
void zCZodiacReader::ProcessModules(asIScriptEngine * engine, bool loadedByteCode)
{
(void)loadedByteCode;
m_asTypeIdFromStored.resize(typeTableLength());
for(int i = 0; i <= asTYPEID_DOUBLE; ++i)
m_asTypeIdFromStored[i] = i;
//solve typeinfo
for(uint32_t i = 0; i < moduleDataLength() - 1; ++i)
{
asIScriptModule * module = engine->GetModule(LoadString(m_modules[i].name), asGM_ONLY_IF_EXISTS);
if(!module) throw Exception(zE_ModuleDoesNotExist);
SolveTypeInfo(module, i);
}
SolveTypeInfo(engine, moduleDataLength()-1);
uint32_t quickCheck{};
SolveTypeInfo(engine, moduleDataLength()-1, quickCheck, &GetFuncdefByIndex, engine->GetFuncdefCount());
SolveTemplates(engine);
zCProperty const* pBegin{}, * pEnd{};
GetProperties(-1, pBegin, pEnd);
m_properties.resize(pEnd-pBegin);
//create property conversion table
void const* end = m_typeInfo + typeInfoLength();
for(auto ti = m_typeInfo; ti < end; ++ti)
{
if(ti->typeId <= asTYPEID_DOUBLE) continue;
auto typeInfo = engine->GetTypeInfoById(m_asTypeIdFromStored[ti - m_typeInfo]);
if(typeInfo == nullptr) throw Exception(zE_BadTypeId);
int asTypeId{};
auto N = ti->propertiesBegin + ti->propertiesLength;
uint32_t start{};
for(uint32_t i = ti->propertiesBegin; i < N; ++i)
{
if(m_properties[i].propertyId != ~0u)
throw Exception(zE_DuplicatePropertyAddress);
auto prop = asGetProperty(typeInfo,LoadString(pBegin[i].name), &asTypeId, start);
if(prop == -1)
throw Exception(zE_UnableToRestoreProperty);
start = prop+1;
m_properties[i].propertyId = prop;
m_properties[i].readOffset = pBegin[i].offset;
m_properties[i].readType = LoadTypeId(pBegin[i].typeId);
m_properties[i].writeType = asTypeId;
assert(!loadedByteCode || (m_properties[i].readType&zTYPEID_OBJECT) == (m_properties[i].writeType&zTYPEID_OBJECT));
}
}
DocumentGlobalVariables(engine);
}
void zCZodiacReader::SolveTemplates(asIScriptEngine * engine)
{
int index = typeInfoLength();
void const* end = GetTemplates() + templatesLength();
for(auto ti = GetTemplates(); ti < end; ++ti, ++index)
{
asITypeInfo * typeInfo{};
if(!ti->module)
typeInfo = engine->GetTypeInfoByDecl(LoadString(ti->declaration));
else
{
asIScriptModule * module = engine->GetModule(LoadString(ti->module), asGM_ONLY_IF_EXISTS);
if(!module) throw Exception(zE_ModuleDoesNotExist);
typeInfo = module->GetTypeInfoByDecl(LoadString(ti->declaration));
}
if(!typeInfo)
throw Exception(zE_BadTypeId);
m_asTypeIdFromStored[index] = typeInfo->GetTypeId();
}
}
int zCZodiacReader::asGetProperty(asITypeInfo * typeInfo, const char * pName, int * typeId, int from) const
{
const char * name;
int propertyCount = typeInfo->GetPropertyCount();
//most likely to be 1 after the last thing we found so try this.....
for(int j = from; j < propertyCount; ++j)
{
typeInfo->GetProperty(j, &name, typeId);
if(strcmp(pName, name) == 0)
{
return j;
}
}
for(int j = 0; j < from; ++j)
{
typeInfo->GetProperty(j, &name, typeId);
if(strcmp(pName, name) == 0)
{
return j;
}
}
return -1;
}
int zCZodiacReader::GetModuleIndex(const char * name, uint32_t quickCheck) const
{
if(quickCheck < moduleDataLength())
{
if(strcmp(LoadString(m_modules[quickCheck].name), name) == 0)
return quickCheck;
}
for(uint32_t i = 0; i < moduleDataLength(); ++i)
{
if(strcmp(LoadString(m_modules[i].name), name) == 0)
return i;
}
return -1;
}
zCGlobalInfo const* zCZodiacReader::GetGlobalVar(uint32_t module, const char * name, const char * nameSpace, uint32_t quickCheck) const
{
auto globals = (zCGlobalInfo const*)(m_globals + m_modules[module].beginGlobalInfo);
auto global_end = globals + m_modules[module].globalsLength;
if(quickCheck < m_modules[module].globalsLength)
{
if(strcmp(LoadString(globals[quickCheck].name), name) == 0
&& strcmp(LoadString(globals[quickCheck].nameSpace), nameSpace) == 0)
{
return &globals[quickCheck];
}
}
for(auto p = globals; p < global_end; ++p)
{
if(strcmp(LoadString(p->name), name) == 0
&& strcmp(LoadString(p->nameSpace), nameSpace) == 0)
{
return p;
}
}
return nullptr;
}
zCTypeInfo const* zCZodiacReader::GetTypeInfo(uint32_t module, const char * name, const char * nameSpace, uint32_t * quickCheck) const
{
auto typeInfo = (m_typeInfo + m_modules[module].beginTypeInfo);
auto End = typeInfo + m_modules[module].typeInfoLength;
if(nameSpace == nullptr) nameSpace = "";
if(quickCheck && *quickCheck < m_modules[module].typeInfoLength)
{
auto p = &typeInfo[*quickCheck];
auto _name = LoadString(p->name);
auto _nameSpace = LoadString(p->nameSpace);
if(strcmp(_name, name) == 0
&& strcmp(_nameSpace, nameSpace) == 0)
{
*quickCheck += 1;
return p;
}
}
for(auto p = typeInfo; p < End; ++p)
{
auto _name = LoadString(p->name);
auto _nameSpace = LoadString(p->nameSpace);
if(strcmp(_name, name) == 0
&& strcmp(_nameSpace, nameSpace) == 0)
{
if(quickCheck) *quickCheck = (p - typeInfo) + 1;
return p;
}
}
return nullptr;
}
void zCZodiacReader::GetProperties(int typeId, zCProperty const*& begin, zCProperty const*& end) const
{
if((uint32_t)typeId > typeInfoLength())
{
begin = (zCProperty const*)(m_mmap.GetAddress() + m_header->propertiesOffset);
end = begin + m_header->propertiesLength;
}
else
{
auto & typeInfo = m_typeInfo[typeId];
begin = (zCProperty const*)(m_mmap.GetAddress() + m_header->propertiesOffset) + typeInfo.propertiesLength;
end = begin + typeInfo.propertiesLength;
}
}
bool zCZodiacReader::RestoreAppObject(void * dst, int address, int asTypeId)
{
if(!(asTypeId & asTYPEID_APPOBJECT || asTypeId & asTYPEID_TEMPLATE))
return false;
auto typeInfo = GetEngine()->GetTypeInfoById(asTypeId);
if(RestoreFunction((void**)dst, address, typeInfo))
return true;
///registered thing?
auto entry = m_parent->GetTypeEntryFromAsTypeId(asTypeId);
if(!entry)
throw Exception(zE_UnknownEncodingProtocol);
void const* src = m_mmap.GetAddress() + m_entries[address].offset;
//POD
if(!entry->onLoad)
memcpy(dst, src, entry->byteLength);
else if(typeInfo->GetFlags() & asOBJ_VALUE)
{
assert(LoadTypeId(m_entries[address].typeId) == asTypeId);
assert(entry->isValueType);
zIFileDescriptor::ReadSubFile sub_file(m_file, m_entries[address].offset, m_entries[address].byteLength);
(entry->onLoad)(this, dst, m_loadedObjects[address].zTypeId, asTypeId & asTYPEID_OBJHANDLE);
}
else
{
auto stored_id = LoadTypeId(m_entries[address].typeId);
assert((stored_id & asTYPEID_TEMPLATE) == (asTypeId & asTYPEID_TEMPLATE));
assert(((asTypeId&zTYPEID_OBJECT) == stored_id));
assert(!entry->isValueType);
assert(!m_loadedObjects[address].beingLoaded);
m_loadedObjects[address].zTypeId = entry->zTypeId;
m_loadedObjects[address].asTypeId = stored_id;
m_loadedObjects[address].beingLoaded = true;
m_loadedObjects[address].needRelease = 0;
zIFileDescriptor::ReadSubFile sub_file(m_file, m_entries[address].offset, m_entries[address].byteLength);
try
{
if(asTypeId & asTYPEID_OBJHANDLE)
{
(entry->onLoad)(this, &m_loadedObjects[address].ptr, m_loadedObjects[address].zTypeId, asTypeId & asTYPEID_OBJHANDLE);
*((void**)dst) = m_loadedObjects[address].ptr;
}
else
{
(entry->onLoad)(this, &dst, m_loadedObjects[address].zTypeId, asTypeId & asTYPEID_OBJHANDLE);
m_loadedObjects[address].ptr = dst;
}
}
catch(Code & c)
{
throw Exception(c);
}
m_loadedObjects[address].beingLoaded = false;
assert(m_loadedObjects[address].zTypeId == entry->zTypeId);
assert(m_loadedObjects[address].asTypeId = stored_id);
}
return true;
}
void zCZodiacReader::PopulateTable(void * dst, uint32_t address, int typeId)
{
if(!(typeId & asTYPEID_SCRIPTOBJECT) || (typeId & asTYPEID_OBJHANDLE))
{
return;
}
if(address > addressTableLength())
throw Exception(zE_BadObjectAddress);
if(m_loadedObjects[address].ptr)
{
if(m_loadedObjects[address].ptr == dst)
return;
throw Exception(zE_DoubleLoad);
}
m_loadedObjects[address].ptr = dst;
m_loadedObjects[address].zTypeId = zIZodiac::GetTypeId<asIScriptObject>();
m_loadedObjects[address].asTypeId = typeId;
++m_progress;
if(!(typeId & asTYPEID_SCRIPTOBJECT))
return;
void const* src = m_mmap.GetAddress() + m_entries[address].offset;
auto & zTypeInfo = m_typeInfo[m_entries[address].typeId];
asIScriptObject * ref = (asIScriptObject*)dst;
const auto begin = &m_properties[zTypeInfo.propertiesBegin];
const auto end = begin + zTypeInfo.propertiesLength;
//first loop populate lookup table
for(auto p = begin; p < end; ++p)
{
auto typeId = p->writeType;
auto offset = ref->GetAddressOfProperty(p->propertyId);
uint32_t read = *(uint32_t*)((uint8_t*)src + p->readOffset);
assert(p->writeType == ref->GetPropertyTypeId(p->propertyId));
//app objects don't have an owner so it shouldn't cause an infinite loop
if((typeId & asTYPEID_SCRIPTOBJECT) && !(typeId & asTYPEID_OBJHANDLE))
{
PopulateTable(offset, read, p->writeType);
}
}
}
void zCZodiacReader::LoadScriptObject(void * dst, int address, int asTypeId, bool isWeak)
{
//object address 0 is nullptr so negative values aren't considered
if((uint32_t)address >= addressTableLength())
throw Exception(zE_BadObjectAddress);
//if the owner is non-zero restore the owner
if(m_entries[address].owner && asTypeId > asTYPEID_DOUBLE)
{
void * ptr{};
auto ownr = m_entries[address].owner;
auto ownrTypeId = LoadTypeId(m_entries[ownr].typeId);
//load owner if it isn't loaded (check to avoid addreffing it i guess)
if(!m_loadedObjects[ownr].ptr && !m_loadedObjects[ownr].beingLoaded)
{
LoadScriptObject(&ptr, ownr, ownrTypeId | asTYPEID_OBJHANDLE, false);
}
}
auto & loaded = m_loadedObjects[address];
//it is a handle i suppose
if(loaded.ptr && dst != loaded.ptr)
{
assert(dst && *(void**)dst == nullptr);
assert(loaded.asTypeId & (asTYPEID_MASK_OBJECT));
auto engine = GetEngine();
auto from_type = engine->GetTypeInfoById(loaded.asTypeId);
auto to_type = engine->GetTypeInfoById(asTypeId);
if(to_type->GetFuncdefSignature())
{
if(RestoreAppObject(dst, address, asTypeId))
return;
}
assert(to_type != nullptr);
if(asTypeId == loaded.asTypeId && asTypeId & asTYPEID_SCRIPTOBJECT)
{
assert(m_loadedObjects[address].zTypeId == zIZodiac::GetTypeId<asIScriptObject>());
auto obj = (asIScriptObject *)m_loadedObjects[address].ptr;
*(asIScriptObject**)dst = obj;
if(!isWeak) obj->AddRef();
}
else
{
engine->RefCastObject(m_loadedObjects[address].ptr, from_type, to_type, (void**)dst);
m_loadedObjects[address].needRelease += isWeak;
}
if(*(void**)dst == nullptr)
throw Exception(zE_ObjectRestoreTypeMismatch);
return;
}
//it loaded as nullptr
else if(loaded.asTypeId & asTYPEID_OBJHANDLE && (asTypeId & asTYPEID_OBJHANDLE))
{
*(void**)dst = nullptr;
return;
}
void const* src = m_mmap.GetAddress() + m_entries[address].offset;
if(RestoreAppObject(dst, address, asTypeId))
return;
else if(asTypeId <= asTYPEID_DOUBLE && m_entries[address].typeId <= asTYPEID_DOUBLE)
{
RestorePrimitive(dst, asTypeId, src, m_entries[address].typeId);
return;
}
//should always be a script object by this point
assert(asTypeId & asTYPEID_SCRIPTOBJECT);
//---------------------------------------------------------
// Script Object
//---------------------------------------------------------
auto _typeId = LoadTypeId(m_entries[address].typeId);
auto _typeInfo = GetEngine()->GetTypeInfoById(_typeId);
auto typeInfo = _typeId == asTypeId? _typeInfo : GetEngine()->GetTypeInfoById(asTypeId);
if(asTypeId & asTYPEID_OBJHANDLE || *(void**)dst == nullptr)
{
//impossible??
// assert(typeInfo->GetFactoryCount() != 0);
assert(asTypeId & asTYPEID_SCRIPTOBJECT);
if(address == 0)
{
*(void**)dst = nullptr;
return;
}
m_loadedObjects[address].asTypeId = _typeId & ~zTYPEID_OBJHANDLE;
m_loadedObjects[address].zTypeId = zIZodiac::GetTypeId<asIScriptObject>();
m_loadedObjects[address].ptr = GetEngine()->CreateUninitializedScriptObject(_typeInfo);
m_loadedObjects[address].needRelease = 1 + isWeak;
++m_progress;
GetEngine()->RefCastObject(m_loadedObjects[address].ptr, _typeInfo, typeInfo, (void**)dst);
if(*(void**)dst == nullptr)
throw Exception(zE_ObjectRestoreTypeMismatch);
//dereference to set up script object...
dst = *(void**)dst;
}
else if(loaded.ptr)
assert(loaded.ptr == dst);
else
{
//assure table is populated
m_loadedObjects[address].asTypeId = _typeId & ~zTYPEID_OBJHANDLE;
m_loadedObjects[address].zTypeId = zIZodiac::GetTypeId<asIScriptObject>();
m_loadedObjects[address].ptr = dst;
++m_progress;
}
//---------------------------------------------------------
// set up script object
//---------------------------------------------------------
auto & zTypeInfo = m_typeInfo[m_entries[address].typeId];
asIScriptObject * ref = (asIScriptObject*)dst;
const auto begin = &m_properties[zTypeInfo.propertiesBegin];
const auto end = begin + zTypeInfo.propertiesLength;
//first loop populate lookup table
for(auto p = begin; p < end; ++p)
{
#ifndef NDEBUG
auto name = ref->GetPropertyName(p->propertyId);
#endif
auto typeId = p->writeType;
auto offset = ref->GetAddressOfProperty(p->propertyId);
uint32_t read = *(uint32_t*)((uint8_t*)src + p->readOffset);
assert(p->writeType == ref->GetPropertyTypeId(p->propertyId));
//app objects don't have an owner so it shouldn't cause an infinite loop
PopulateTable(offset, read, typeId);
}
//Restore object contents
for(auto p = begin; p < end; ++p)
{
#ifndef NDEBUG
auto name = ref->GetPropertyName(p->propertyId);
#endif
auto offset = ref->GetAddressOfProperty(p->propertyId);
auto typeId = ref->GetPropertyTypeId(p->propertyId);
void * read = ((uint8_t*)src + p->readOffset);
assert(p->writeType == typeId);
if(*(uint32_t*)read == 31)
{
int break_point = 0;
++break_point;
}
//app objects don't have an owner so it shouldn't cause an infinite loop
RestoreScriptObject(offset, read, typeId);
}
}
bool zCZodiacReader::RestoreFunction(void ** dst, uint32_t handle, asITypeInfo * typeInfo)
{
assert(handle != 0);
if(!(typeInfo && typeInfo->GetFuncdefSignature()))
return false;
asIScriptFunction * delegate = LoadFunction(handle);
if(!delegate->IsCompatibleWithTypeId(typeInfo->GetTypeId()))
throw Exception(zE_ObjectRestoreTypeMismatch);
*dst = delegate;
return true;
}
void zCZodiacReader::RestoreScriptObject(void * dst, void const* src, uint asTypeId)
{
if(asTypeId <= asTYPEID_DOUBLE)
{
memcpy(dst, src, GetEngine()->GetSizeOfPrimitiveType(asTypeId));
return;
}
else if((asTypeId & asTYPEID_OBJHANDLE) || (asTypeId & asTYPEID_SCRIPTOBJECT))
{
LoadScriptObject(dst, *(uint32_t*)src, asTypeId);
}
else
{
auto typeInfo = GetEngine()->GetTypeInfoById(asTypeId);
//funcdef, next thing is an address
if(typeInfo && typeInfo->GetFuncdefSignature())
{
RestoreFunction((void**)dst, *(uint32_t*)src, typeInfo);
return;
}
auto entry = m_parent->GetTypeEntryFromAsTypeId(asTypeId);
if(!entry) throw Exception(zE_UnknownEncodingProtocol);
if(!entry->onLoad)
{
memcpy(dst, src, entry->byteLength);
}
else
{
LoadScriptObject(dst, *(uint32_t*)src, asTypeId);
}
}
}
asITypeInfo * zCZodiacReader::LoadTypeInfo(int id, bool RefCount)
{
if(id < 0) return nullptr;
auto typeId = LoadTypeId(id);
auto typeInfo = GetEngine()->GetTypeInfoById(typeId);
if(typeInfo && RefCount)
typeInfo->AddRef();
return typeInfo;
}
int zCZodiacReader::LoadTypeId(int id)
{
if(id <= asTYPEID_DOUBLE) return id;
if((uint32_t)id >= typeTableLength())
throw Exception(zE_BadTypeId);
return m_asTypeIdFromStored[id];
}
asIScriptFunction * zCZodiacReader::LoadFunction(int id)
{
if(id <= 0) return nullptr;
if((uint)id > functionTableLength())
throw Exception(zE_BadObjectAddress);
auto & function = GetFunctions()[id];
auto declaration = LoadString(function.declaration);
if(m_loadedFunctions == nullptr)
{
m_loadedFunctions.reset(new void*[functionTableLength()]);
memset(&m_loadedFunctions[0], 0, sizeof(m_loadedFunctions[0]) * functionTableLength());
}
if(m_loadedFunctions[id] != nullptr)
{
asIScriptFunction * func = reinterpret_cast<asIScriptFunction*>(m_loadedFunctions[id]);
func->AddRef();
return func;
}
asIScriptFunction * func = nullptr;
asITypeInfo * typeInfo = LoadTypeInfo(function.objectType, false);
if(typeInfo)
{
//should it be virtual???
func = typeInfo->GetMethodByDecl(declaration);
}
else if(function.module)
{
auto moduleName = LoadString(function.module);
auto module = GetEngine()->GetModule(moduleName, asGM_ONLY_IF_EXISTS);
if(!module)
throw Exception(zE_ModuleDoesNotExist);
func = module->GetFunctionByDecl(declaration);
}
else
{
func = GetEngine()->GetGlobalFunctionByDecl(declaration);
}
if(func == nullptr)
throw Exception(zE_BadObjectAddress);
//is it a delegate?
if(!function.delegateAddress)
func->AddRef();
else
{
void * delegateObject{};
LoadScriptObject(&delegateObject, function.delegateAddress, LoadTypeId(function.delegateTypeId) | asTYPEID_OBJHANDLE);
asIScriptFunction * delegate = GetEngine()->CreateDelegate(func, delegateObject);
if(!delegate)
throw Exception(zE_BadFunctionInfo);
func = delegate;
}
m_loadedFunctions[id] = func;
++m_progress;
return func;
}
asIScriptContext * zCZodiacReader::LoadContext(int id)
{
if(id <= 0)
return nullptr;
//object address 0 is nullptr so negative values aren't considered
if((uint32_t)id >= addressTableLength())
throw Exception(zE_BadObjectAddress);
if(m_loadedObjects[id].ptr != nullptr)
{
if(m_loadedObjects[id].zTypeId != zIZodiac::GetTypeId<asIScriptContext>())
throw Exception(zE_ObjectRestoreTypeMismatch);
asIScriptContext * context = reinterpret_cast<asIScriptContext*>(m_loadedObjects[id].ptr);
context->AddRef();
return context;
}
asIScriptContext * context{};
zCEntry const* entry = &m_entries[id];
zIFileDescriptor::ReadSubFile sub_file(m_file, entry->offset, entry->byteLength);
int real_type{};
ZodiacLoad(this, &context, real_type);
++m_progress;
m_loadedObjects[id].ptr = context;
m_loadedObjects[id].zTypeId = zIZodiac::GetTypeId<asIScriptContext>();
return context;
}
void * zCZodiacReader::LoadObject(int id, zLOAD_FUNC_t load_func, int & actualType)
{
if(id <= 0)
return nullptr;
//object address 0 is nullptr so negative values aren't considered
if((uint32_t)id >= addressTableLength())
throw Exception(zE_BadObjectAddress);
if(m_loadedObjects[id].ptr == nullptr && m_loadedObjects[id].zTypeId == 0)
{
zCEntry const* entry = &m_entries[id];
zIFileDescriptor::ReadSubFile sub_file(m_file, entry->offset, entry->byteLength);
//ensure stack corruption if something goes wrong, (fail quickly if behavior is undefined)
void * dst{};
load_func(this, &dst, actualType, false);
m_loadedObjects[id].ptr = dst;
m_loadedObjects[id].zTypeId = actualType;
m_loadedObjects[id].asTypeId = -1;
++m_progress;
}
actualType = m_loadedObjects[id].zTypeId;
return m_loadedObjects[id].ptr;
}
void zCZodiacReader::LoadObject(int id, void * dst, zLOAD_FUNC_t load_func, int & actualType, bool isHandle)
{
//object address 0 is nullptr so negative values aren't considered
if(id == 0 || (uint32_t)id >= addressTableLength())
throw Exception(zE_BadObjectAddress);
zCEntry const* entry = &m_entries[id];
zIFileDescriptor::ReadSubFile sub_file(m_file, entry->offset, entry->byteLength);
load_func(this, dst, actualType, isHandle);
}
template<typename T>
static T ReadPrimitive2(void const* address, int asTypeId)
{
assert(asTypeId <= asTYPEID_DOUBLE);
switch(asTypeId)
{
case asTYPEID_VOID: return 0L;
case asTYPEID_BOOL: return *(uint8_t*)address;
case asTYPEID_INT8: return *(asINT8*)address;
case asTYPEID_INT16: return *(asINT16*)address;
case asTYPEID_INT32: return *(int32_t*)address;
case asTYPEID_INT64: return *(asINT64*)address;
case asTYPEID_UINT8: return *(asBYTE*)address;
case asTYPEID_UINT16: return *(asWORD*)address;
case asTYPEID_UINT32: return *(asDWORD*)address;
case asTYPEID_UINT64: return *(asQWORD*)address;
case asTYPEID_FLOAT: return *(float*)address;
case asTYPEID_DOUBLE: return *(double*)address;
default:break;
};
return 0;
}
template<typename T>
static T ReadPrimitive(void const* address, int asTypeId)
{
auto eax = ReadPrimitive2<T>(address, asTypeId);
return eax;
}
//hopefully this gets optimized a lot
void zCZodiacReader::RestorePrimitive(void * dst, int dstTypeId, void const* address, int srcTypeId)
{
assert(dstTypeId <= asTYPEID_DOUBLE);
switch(dstTypeId)
{
case asTYPEID_VOID: break;
case asTYPEID_BOOL: *(bool *)dst = ReadPrimitive<bool> (address, srcTypeId); break;
case asTYPEID_INT8: *(asINT8 *)dst = ReadPrimitive<asINT64>(address, srcTypeId); break;
case asTYPEID_INT16: *(asINT16*)dst = ReadPrimitive<asINT64>(address, srcTypeId); break;
case asTYPEID_INT32: *(int32_t*)dst = ReadPrimitive<asINT64>(address, srcTypeId); break;
case asTYPEID_INT64: *(asINT64*)dst = ReadPrimitive<asINT64>(address, srcTypeId); break;
case asTYPEID_UINT8: *(asBYTE *)dst = ReadPrimitive<asQWORD>(address, srcTypeId); break;
case asTYPEID_UINT16: *(asWORD *)dst = ReadPrimitive<asQWORD>(address, srcTypeId); break;
case asTYPEID_UINT32: *(asDWORD*)dst = ReadPrimitive<asQWORD>(address, srcTypeId); break;
case asTYPEID_UINT64: *(asQWORD*)dst = ReadPrimitive<asQWORD>(address, srcTypeId); break;
case asTYPEID_FLOAT: *(float *)dst = ReadPrimitive<double> (address, srcTypeId); break;
case asTYPEID_DOUBLE: *(double *)dst = ReadPrimitive<double> (address, srcTypeId); break;
};
}
}
#endif
| 27.329431 | 180 | 0.701615 | SpehleonLP |
de4dabbd4fe6fafb74938d19ad038a5db6820ce6 | 788 | cpp | C++ | src/geometry.cpp | josiest/gold | 140d7c92fce8548b8a4cc6d2eda4be5b12e32975 | [
"MIT"
] | null | null | null | src/geometry.cpp | josiest/gold | 140d7c92fce8548b8a4cc6d2eda4be5b12e32975 | [
"MIT"
] | null | null | null | src/geometry.cpp | josiest/gold | 140d7c92fce8548b8a4cc6d2eda4be5b12e32975 | [
"MIT"
] | null | null | null | #include "gold/geometry.hpp"
namespace au {
bool within_closed_bounds(SDL_Point const & p, SDL_Rect const & rect)
{
return p.x >= rect.x and p.x <= rect.x + rect.w
and p.y >= rect.y and p.y <= rect.y + rect.h;
}
double scale_by_height(SDL_Rect const & from, SDL_Rect const & to)
{
// scale width by normalizing the rect height to the max height
return to.h / static_cast<double>(from.h);
}
SDL_Rect clip_width(SDL_Rect const & rect, SDL_Rect const & max)
{
SDL_Rect clipped{rect};
// scale the rect to be clipped into the space of the max bounds
double const scale = scale_by_height(rect, max);
// clip the width if it's too wide
if (clipped.w * scale > max.w) {
clipped.w = static_cast<int>(max.w/scale);
}
return clipped;
}
}
| 27.172414 | 69 | 0.659898 | josiest |
de4eeb154a95d899df52b4bf82c4437fa6b5a8eb | 661 | cpp | C++ | TestProject1/TestProject1.cpp | halterman/318_F19 | fd04d3bf9168485947fae86d5d2d7af1752f61af | [
"MIT"
] | null | null | null | TestProject1/TestProject1.cpp | halterman/318_F19 | fd04d3bf9168485947fae86d5d2d7af1752f61af | [
"MIT"
] | null | null | null | TestProject1/TestProject1.cpp | halterman/318_F19 | fd04d3bf9168485947fae86d5d2d7af1752f61af | [
"MIT"
] | null | null | null | #include <iostream>
class Int {
int value;
public:
Int(int value) {
this->value = value;
}
int get() const {
return value;
}
};
class NotCopyable {
Int value;
public:
NotCopyable() = default;
NotCopyable(int value) : value(value) {}
NotCopyable(const NotCopyable& other) = delete;
NotCopyable& operator=(const NotCopyable& other) = delete;
int get() const {
return value.get();
}
};
void f(NotCopyable nc) {
std::cout << nc.get() << '\n';
}
int main() {
NotCopyable x{ 45 };
std::cout << x.get() << '\n';
//NotCopyable y;
//std::cout << y.get() << '\n';
std::cout << "----------\n";
//f(x);
}
| 16.948718 | 60 | 0.556732 | halterman |
de51e0065e9eb226edf02e5b7532b2daec70f6f2 | 15,881 | cc | C++ | lib/flyMS/FlightCore.cc | msardonini/flyMS | ea1127a3313fb52a8fe789222ba654e05583e06c | [
"MIT"
] | null | null | null | lib/flyMS/FlightCore.cc | msardonini/flyMS | ea1127a3313fb52a8fe789222ba654e05583e06c | [
"MIT"
] | null | null | null | lib/flyMS/FlightCore.cc | msardonini/flyMS | ea1127a3313fb52a8fe789222ba654e05583e06c | [
"MIT"
] | null | null | null | /**
* @file FlightCore.cc
* @brief Main control loop for the flyMS program
*
* @author Mike Sardonini
* @date 10/15/2018
*/
#include "flyMS/FlightCore.h"
#include <sys/stat.h>
#include <algorithm>
#include <iomanip>
#include <sstream>
#include <stdexcept>
#include "spdlog/fmt/ostr.h"
#include "spdlog/sinks/rotating_file_sink.h"
#include "spdlog/sinks/stdout_color_sinks.h"
#include "spdlog/spdlog.h"
namespace flyMS {
void FlightCore::zero_pids() {
roll_outer_PID_.zero_values();
roll_inner_PID_.zero_values();
pitch_outer_PID_.zero_values();
pitch_inner_PID_.zero_values();
yaw_PID_.zero_values();
}
FlightCore::FlightCore(const YAML::Node &config_params)
: imu_module_(Imu::getInstance()),
ulog_(),
setpoint_module_(config_params),
mavlink_interface_(config_params),
position_controller_(config_params),
gps_module_(config_params),
config_params_(config_params) {
flight_mode_ = static_cast<FlightMode>(config_params["flight_mode"].as<uint32_t>());
is_debug_mode_ = config_params["debug_mode"].as<bool>();
log_filepath_ = config_params["log_filepath"].as<std::string>();
YAML::Node controller = config_params["controller"];
max_control_effort_ = controller["max_control_effort"].as<std::array<float, 3>>();
}
int FlightCore::flight_core(StateData &imu_data_body) {
if (mavlink_interface_) {
mavlink_interface_.SendImuMessage(imu_data_body);
}
/************************************************************************
* Check the Mavlink Interface for New Visual Odometry Data
************************************************************************/
Eigen::Vector3f setpoint_orientation;
if (mavlink_interface_) {
VioData vio;
float vio_yaw;
if (mavlink_interface_.GetVioData(&vio)) {
position_controller_.ReceiveVio(vio);
position_controller_.GetSetpoint(setpoint_orientation, vio_yaw);
float log_setpoint[4] = {setpoint_orientation(0), setpoint_orientation(1), vio_yaw, setpoint_orientation(2)};
float quat_setpoint[4] = {vio.quat.w(), vio.quat.x(), vio.quat.y(), vio.quat.z()};
// Log the VIO Data
ULogPosCntrlMsg vio_log_msg(imu_data_body.timestamp_us, vio.position.data(), vio.velocity.data(), quat_setpoint,
log_setpoint);
ulog_.WriteFlightData<ULogPosCntrlMsg>(vio_log_msg, ULogPosCntrlMsg::ID());
flyStereo_streaming_data_ = true;
}
}
/************************************************************************
* Get Setpoint Data *
************************************************************************/
auto setpoint = setpoint_module_.get_setpoint_data();
// If we have commanded a switch in Aux, activate the perception system
if (mavlink_interface_) {
if (setpoint.Aux[0] < 0.1 && setpoint.Aux[1] > 0.9) {
// Transition to start flyStereo
mavlink_interface_.SendStartCommand();
// Assume that the current throttle value will be an average value to keep
// altitude
standing_throttle_ = setpoint.throttle;
initial_yaw_ = imu_data_body.euler[2];
// Make sure our first setpoint is zero
flyStereo_running_ = true;
} else if (setpoint.Aux[0] > 0.9 && setpoint.Aux[1] < 0.1) {
flyStereo_running_ = false;
flyStereo_streaming_data_ = false;
mavlink_interface_.SendShutdownCommand();
// Reset the filters in the Position controller
position_controller_.ResetController();
setpoint_orientation = Eigen::Vector3f::Zero();
position_generator_.ResetCounter();
}
}
// Apply orientation commands from the position controller if running
if (flyStereo_running_ && flyStereo_streaming_data_) {
setpoint.euler_ref[0] = setpoint_orientation(0);
setpoint.euler_ref[1] = setpoint_orientation(1);
setpoint.throttle = setpoint_orientation(2) + standing_throttle_;
// setpoint.euler[2] = vio_yaw - imu_data_body.euler[2] + initial_yaw_;
// Apply the position setpoint
Eigen::Vector3f pos_ref;
position_generator_.GetPosition(&pos_ref);
position_controller_.SetReferencePosition(pos_ref);
}
std::array<float, 3> u_euler; //< The amount of controller effort (-1 to 1) to give in each euler angle [RPY]
/************************************************************************
* Roll Controller *
************************************************************************/
float droll_setpoint;
if (flight_mode_ == FlightMode::STABILIZED) {
droll_setpoint = roll_outer_PID_.update_filter(setpoint.euler_ref[0] - imu_data_body.euler[0]);
} else if (flight_mode_ == FlightMode::ACRO) { // Acro mode
droll_setpoint = setpoint.euler_ref[0];
} else {
throw std::runtime_error("[FlightCore] Error! Invalid flight mode. Shutting down now");
}
imu_data_body.eulerRate[0] = gyro_lpf_roll_.update_filter(imu_data_body.eulerRate[0]);
u_euler[0] = roll_inner_PID_.update_filter(droll_setpoint - imu_data_body.eulerRate[0]);
u_euler[0] = std::clamp(u_euler[0], -max_control_effort_[0], max_control_effort_[0]);
/************************************************************************
* Pitch Controller *
************************************************************************/
float dpitch_setpoint;
if (flight_mode_ == FlightMode::STABILIZED) { // Stabilized Flight Mode
dpitch_setpoint = pitch_outer_PID_.update_filter(setpoint.euler_ref[1] - imu_data_body.euler[1]);
} else if (flight_mode_ == FlightMode::ACRO) { // Acro mode
dpitch_setpoint = setpoint.euler_ref[1];
} else {
throw std::runtime_error("[FlightCore] Error! Invalid flight mode. Shutting down now");
}
imu_data_body.eulerRate[1] = gyro_lpf_pitch_.update_filter(imu_data_body.eulerRate[1]);
u_euler[1] = pitch_inner_PID_.update_filter(dpitch_setpoint - imu_data_body.eulerRate[1]);
u_euler[1] = std::clamp(u_euler[1], -max_control_effort_[1], max_control_effort_[1]);
/************************************************************************
* Yaw Controller *
************************************************************************/
imu_data_body.eulerRate[2] = gyro_lpf_yaw_.update_filter(imu_data_body.eulerRate[2]);
u_euler[2] = yaw_PID_.update_filter(setpoint.euler_ref[2] - imu_data_body.euler[2]);
// Apply a saturation filter
u_euler[2] = std::clamp(u_euler[2], -max_control_effort_[2], max_control_effort_[2]);
/************************************************************************
* Reset the Integrators if Landed *
************************************************************************/
if (setpoint.throttle < setpoint_module_.get_min_throttle() + .01) {
integrator_reset_++;
} else {
integrator_reset_ = 0;
}
// if landed for 2 seconds, reset integrators and Yaw error
if (integrator_reset_ > 2 / LOOP_DELTA_T) {
setpoint.euler_ref[2] = imu_data_body.euler[2];
setpoint_module_.set_yaw_ref(imu_data_body.euler[2]);
zero_pids();
}
/************************************************************************
* Mixing
*
* CCW 1 2 CW Body Frame:
* \ / X
* / \ Y_|
* CW 3 4 CCW Z UP
*
************************************************************************/
// The amount of power (0 - 1) to give to each motor
std::array<float, 4> u;
u[0] = setpoint.throttle + u_euler[0] - u_euler[1] - u_euler[2];
u[1] = setpoint.throttle - u_euler[0] - u_euler[1] + u_euler[2];
u[2] = setpoint.throttle + u_euler[0] + u_euler[1] + u_euler[2];
u[3] = setpoint.throttle - u_euler[0] + u_euler[1] - u_euler[2];
/************************************************************************
* Check Output Ranges, if outside, adjust *
************************************************************************/
static constexpr float smallest_value = 0.f;
float largest_value = 1.f;
for (int i = 0; i < 4; i++) {
if (u[i] > largest_value) {
largest_value = u[i];
}
if (u[i] < smallest_value) u[i] = 0;
}
// if upper saturation would have occurred, reduce all outputs evenly
if (largest_value > 1) {
float offset = largest_value - 1;
for (int i = 0; i < 4; i++) u[i] -= offset;
}
/************************************************************************
* Send Commands to ESCs *
************************************************************************/
if (!is_debug_mode_) {
pru_client_.setSendData(u);
}
/************************************************************************
* Check the kill Switch and Shutdown if set *
************************************************************************/
if (setpoint.kill_switch < 0.5 && !is_debug_mode_) {
spdlog::info("\nKill Switch Hit! Shutting Down\n");
rc_set_state(EXITING);
}
// Print some stuff to the console in debug mode
if (is_debug_mode_) {
console_print(imu_data_body, setpoint);
}
/************************************************************************
* Check for GPS Data and Handle Accordingly *
************************************************************************/
gps_module_.getGpsData(&gps_);
/************************************************************************
* Log Important Flight Data For Analysis *
************************************************************************/
struct ULogFlightMsg flight_msg {
imu_data_body.timestamp_us, imu_data_body, setpoint, u, u_euler
};
ulog_.WriteFlightData<struct ULogFlightMsg>(flight_msg, ULogFlightMsg::ID());
return 0;
}
int FlightCore::console_print(const StateData &imu_data_body, const SetpointData &setpoint) {
// spdlog::info("time {:3.3f} ", control->time);
// spdlog::info("Alt_ref {:3.1f} ",control->alt_ref);
// spdlog::info("U1: {:2.2f}, U2: {:2.2f}, U3: {:2.2f}, U4: {:2.2f} ", u[0],
// u[1], u[2], u[3]); spdlog::info("Aux {:2.1f} ", setpoint.Aux[0]);
// spdlog::info("function: {}",rc_get_dsm_ch_normalized(6));
// spdlog::info("num wraps {} ",control->num_wraps);
// spdlog::info(" Throt {:2.2f}, Roll_ref {:2.2f}, Pitch_ref {:2.2f}, Yaw_ref {:2.2f} KS {:2.2f} ", setpoint.throttle,
// setpoint.euler_ref[0], setpoint.euler_ref[1], setpoint.euler_ref[2], setpoint.kill_switch);
// spdlog::info("Roll {:1.2f}, Pitch {:1.2f}, Yaw {:2.3f}", imu_data_body.euler[0], imu_data_body.euler[1],
// imu_data_body.euler[2]);
spdlog::info("droll {:1.2f}, dpitch {:1.2f}, dyaw {:2.3f}", imu_data_body.eulerRate[0], imu_data_body.eulerRate[1],
imu_data_body.eulerRate[2]);
// spdlog::info(" Mag X {:4.2f}",control->mag[0]);
// spdlog::info(" Mag Y {:4.2f}",control->mag[1]);
// spdlog::info(" Mag Z {:4.2f}",control->mag[2]);
// spdlog::info(" Accel X {:4.2f}",control->accel[0]);
// spdlog::info(" Accel Y {:4.2f}",control->accel[1]);
// spdlog::info(" Accel Z {:4.2f}",control->accel[2]);
// spdlog::info(" Pos N {:2.3f} ", control->ekf_filter.output.ned_pos[0]);
// spdlog::info(" Pos E {:2.3f} ", control->ekf_filter.output.ned_pos[1]);
// spdlog::info(" Pos D {:2.3f} ", control->ekf_filter.output.ned_pos[2]);
// spdlog::info(" DRoll {:1.2f}, DPitch {:1.2f}, DYaw {:2.3f}",
// imu_data_body.eulerRate[0],
// imu_data_body.eulerRate[1], imu_data_body.eulerRate[2]);
// spdlog::info("uroll {:2.3f}, upitch {:2.3f}, uyaw {:2.3f}", u_euler[0],
// u_euler[1],
// u_euler[2]);
// spdlog::info(" GPS pos lat: {:2.2f}", control->GPS_data.pos_lat);
// spdlog::info(" GPS pos lon: {:2.2f}", control->GPS_data.pos_lon);
// spdlog::info(" HDOP: {}", control->GPS_data.HDOP);
// spdlog::info("Baro Alt: {} ",control->baro_alt);
return 0;
}
void FlightCore::init_logging(const std::string &log_location) {
int run_number = 1;
std::stringstream run_str;
run_str << std::internal << std::setfill('0') << std::setw(3) << run_number;
std::string log_dir(log_location + std::string("/run") + run_str.str());
// Find the next run number folder that isn't in use
struct stat st = {0};
while (!stat(log_dir.c_str(), &st)) {
run_str.str(std::string());
run_str << std::internal << std::setfill('0') << std::setw(3) << ++run_number;
log_dir = (log_location + std::string("/run") + run_str.str());
}
// Make a new folder to hold the logged data
mkdir(log_dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
// Initialize spdlog
std::vector<spdlog::sink_ptr> sinks;
// Only use the console sink if we are in debug mode
if (is_debug_mode_) {
sinks.push_back(std::make_shared<spdlog::sinks::stdout_color_sink_mt>());
}
int max_bytes = 1048576 * 20; // Max 20 MB
int max_files = 20;
sinks.push_back(
std::make_shared<spdlog::sinks::rotating_file_sink_mt>(log_dir + "/console_log.txt", max_bytes, max_files));
auto flyMS_log = std::make_shared<spdlog::logger>("flyMS_log", std::begin(sinks), std::end(sinks));
// Register loggers to be global logger
flyMS_log->set_level(spdlog::level::trace);
spdlog::register_logger(flyMS_log);
spdlog::set_default_logger(flyMS_log);
flyMS_log->flush_on(spdlog::level::trace); // TODO REMOVE
// Initialize Ulog
ulog_.init(log_dir);
}
int FlightCore::init() {
// Create a file for logging and initialize our file logger
init_logging(log_filepath_);
std::cout << "hi\n";
if (config_params_["mavlink_interface"]["enable"].as<bool>()) {
mavlink_interface_.Init();
}
// Initialize the remote controller through the setpoint object
setpoint_module_.init();
// Blocks execution until a packet is received
if (!is_debug_mode_) {
setpoint_module_.wait_for_data_packet();
}
// Tell the system that we are running if we are in the predicted UNINITIALIZED state. Else shutdown
if (rc_get_state() == UNINITIALIZED) {
rc_set_state(RUNNING);
} else {
rc_set_state(EXITING);
}
// Generate the PID controllers and low-pass filters
YAML::Node controller = config_params_["controller"];
YAML::Node filters = config_params_["filters"];
double pid_lpf_const = controller["pid_LPF_const_sec"].as<double>();
roll_inner_PID_ = generate_pid(controller["roll_PID_inner"].as<std::array<double, 3>>(), pid_lpf_const, LOOP_DELTA_T);
roll_outer_PID_ = generate_pid(controller["roll_PID_outer"].as<std::array<double, 3>>(), pid_lpf_const, LOOP_DELTA_T);
pitch_outer_PID_ =
generate_pid(controller["pitch_PID_outer"].as<std::array<double, 3>>(), pid_lpf_const, LOOP_DELTA_T);
pitch_inner_PID_ =
generate_pid(controller["pitch_PID_inner"].as<std::array<double, 3>>(), pid_lpf_const, LOOP_DELTA_T);
yaw_PID_ = generate_pid(controller["yaw_PID"].as<std::array<double, 3>>(), pid_lpf_const, LOOP_DELTA_T);
auto lpf_num = filters["imu_lpf_num"].as<std::vector<double>>();
auto lpf_den = filters["imu_lpf_den"].as<std::vector<double>>();
gyro_lpf_roll_ = DigitalFilter(lpf_num, lpf_den);
gyro_lpf_pitch_ = DigitalFilter(lpf_num, lpf_den);
gyro_lpf_yaw_ = DigitalFilter(lpf_num, lpf_den);
// Initialize the client to connect to the PRU handler
pru_client_.startPruClient();
// Start the flight program
std::function<int(StateData &)> f = std::bind(&FlightCore::flight_core, this, std::placeholders::_1);
imu_module_.init(config_params_["imu_params"], f);
return 0;
}
} // namespace flyMS
| 42.349333 | 120 | 0.581575 | msardonini |
de54a78f41108e308a7b40ee164cfc22cebd0e21 | 2,276 | cpp | C++ | cpp_10/parallel_algorithms/spinlock_vs_atomic/test.cpp | eshernan/parallel_course | 37528e0c19e1524f948138bcc7a6ccdc6a3aa0dd | [
"MIT"
] | 3 | 2021-01-18T18:15:51.000Z | 2021-05-21T07:04:31.000Z | spinlock_vs_atomic/test.cpp | andy-thomason/parallel_algorithms | c7ca071dd87dd8044d16d41d61efb1d07b9fbca3 | [
"MIT"
] | null | null | null | spinlock_vs_atomic/test.cpp | andy-thomason/parallel_algorithms | c7ca071dd87dd8044d16d41d61efb1d07b9fbca3 | [
"MIT"
] | 1 | 2021-05-21T07:04:44.000Z | 2021-05-21T07:04:44.000Z |
#include <chrono>
#include <atomic>
#include <future>
#include <array>
#include <mutex>
class nolock {
public:
void lock() {
}
void unlock() {
}
};
class spinlock {
std::atomic_flag flag_{false};
public:
void lock() {
while (flag_.test_and_set(std::memory_order_acquire)) ;
}
void unlock() {
flag_.clear(std::memory_order_release);
}
};
template <class LockType>
class locker {
LockType &lock_;
public:
locker(LockType &lock) : lock_(lock) { lock_.lock(); }
~locker() { lock_.unlock(); }
};
auto now() { return std::chrono::high_resolution_clock::now(); }
// crude growable array
// see http://www.stroustrup.com/lock-free-vector.pdf for an elegant growable array.
template< typename Type, typename SizeType, typename LockType >
class vector {
static const int capacity_ = 0x100000;
Type *values_ = nullptr;
SizeType size_{0};
LockType lock_;
public:
vector() : values_(new Type[capacity_]) {}
~vector() { delete[] values_; }
void push_back(const Type &x) {
locker<LockType> lck(lock_);
int dest = size_++;
if (dest < capacity_) values_[dest] = x;
}
const Type &operator[](int idx) { return values_[idx]; }
int size() const { return size_; };
};
template <class Fn>
void time(Fn fn, const char *text) {
auto start = now();
{
std::array<std::future<void>, 8 > futures;
for ( auto &f: futures ) f = std::async(std::launch::async, fn);
}
int ns = (int)std::chrono::nanoseconds(now() - start).count();
printf("%20s: t=%dns\n", text, ns);
}
int main() {
vector<int, std::atomic<int>, nolock> vec1;
time([&vec1] {
for (int i = 0; i != 0x100000 / 8; ++i) {
vec1.push_back(i);
}
}, "atomic");
printf("atomic version: size=%x\n", vec1.size());
vector<int, int, spinlock> vec2;
time([&vec2] {
for (int i = 0; i != 0x100000 / 8; ++i) {
vec2.push_back(i);
}
}, "spinlock");
printf("spinlock version: size=%x\n", vec2.size());
vector<int, volatile int, nolock> vec3;
time([&vec3] {
for (int i = 0; i != 0x100000 / 8; ++i) {
vec3.push_back(i);
}
}, "single thread");
printf("single thread version: size=%x\n", vec2.size());
}
| 22.76 | 85 | 0.588313 | eshernan |
de58bb811e689c91b09f785c404790bf07b48bdb | 6,424 | cpp | C++ | src/io_worker.cpp | Paycasso/cpp-driver | 9e6efd4842afc226d999baf890a55275e7e94cf8 | [
"Apache-2.0"
] | null | null | null | src/io_worker.cpp | Paycasso/cpp-driver | 9e6efd4842afc226d999baf890a55275e7e94cf8 | [
"Apache-2.0"
] | null | null | null | src/io_worker.cpp | Paycasso/cpp-driver | 9e6efd4842afc226d999baf890a55275e7e94cf8 | [
"Apache-2.0"
] | null | null | null | /*
Copyright (c) 2014 DataStax
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 "io_worker.hpp"
#include "pool.hpp"
namespace cass {
IOWorker::IOWorker(Session* session, Logger* logger, const Config& config)
: session_(session)
, logger_(logger)
, ssl_context_(nullptr)
, is_closing_(false)
, pending_request_count_(0)
, config_(config)
, request_queue_(config.queue_size_io()) {
prepare_.data = this;
}
IOWorker::~IOWorker() {
cleanup();
}
int IOWorker::init() {
int rc = EventThread::init(config_.queue_size_event());
if (rc != 0) return rc;
rc = request_queue_.init(loop(), this, &IOWorker::on_execute);
if (rc != 0) return rc;
rc = uv_prepare_init(loop(), &prepare_);
if (rc != 0) return rc;
rc = uv_prepare_start(&prepare_, on_prepare);
return rc;
}
bool IOWorker::add_pool_async(Host host) {
IOWorkerEvent event;
event.type = IOWorkerEvent::ADD_POOL;
event.host = host;
return send_event_async(event);
}
bool IOWorker::remove_pool_async(Host host) {
IOWorkerEvent event;
event.type = IOWorkerEvent::REMOVE_POOL;
event.host = host;
return send_event_async(event);
}
void IOWorker::close_async() {
is_closing_ = true;
while (!request_queue_.enqueue(nullptr)) {
// Keep trying
}
}
void IOWorker::add_pool(Host host) {
if (!is_closing_ && pools.count(host) == 0) {
Pool* pool = new Pool(host, loop(), ssl_context_, logger_, config_);
pool->set_ready_callback(
std::bind(&IOWorker::on_pool_ready, this, std::placeholders::_1));
pool->set_closed_callback(
std::bind(&IOWorker::on_pool_closed, this, std::placeholders::_1));
pool->set_keyspace_callback(
std::bind(&IOWorker::on_set_keyspace, this, std::placeholders::_1));
pool->connect(session_->keyspace());
pools[host] = pool;
}
}
bool IOWorker::execute(RequestHandler* request_handler) {
if (is_closing_) {
return false;
}
return request_queue_.enqueue(request_handler);
}
void IOWorker::on_set_keyspace(const std::string& keyspace) {
session_->set_keyspace(keyspace);
}
void IOWorker::maybe_close() {
if (is_closing_ && pending_request_count_ <= 0) {
for (auto& entry : pools) {
entry.second->close();
}
maybe_notify_closed();
}
}
void IOWorker::maybe_notify_closed() {
if (pools.empty()) {
session_->notify_closed_async();
close_handles();
}
}
void IOWorker::cleanup() {
auto it = pending_delete_.begin();
while (it != pending_delete_.end()) {
delete *it;
it = pending_delete_.erase(it);
}
}
void IOWorker::close_handles() {
EventThread::close_handles();
request_queue_.close_handles();
uv_prepare_stop(&prepare_);
logger_->debug("IO worker active handles %d", loop()->active_handles);
}
void IOWorker::on_pool_ready(Pool* pool) {
session_->notify_ready_async();
}
void IOWorker::on_pool_closed(Pool* pool) {
Host host = pool->host();
logger_->info("Pool for '%s' closed", host.address.to_string().c_str());
pending_delete_.push_back(pool);
pools.erase(host);
if (is_closing_) {
maybe_notify_closed();
} else {
ReconnectRequest* reconnect_request = new ReconnectRequest(this, host);
Timer::start(loop(), config_.reconnect_wait(), reconnect_request,
IOWorker::on_pool_reconnect);
}
}
void IOWorker::on_retry(RequestHandler* request_handler, RetryType retry_type) {
Host host;
if (retry_type == RETRY_WITH_NEXT_HOST) {
request_handler->next_host();
}
if (!request_handler->get_current_host(&host)) {
request_handler->on_error(CASS_ERROR_LIB_NO_HOSTS_AVAILABLE,
"No hosts available");
delete request_handler;
return;
}
auto it = pools.find(host);
if (it != pools.end()) {
auto pool = it->second;
Connection* connection = pool->borrow_connection(request_handler->keyspace);
if (connection != nullptr) {
if (!pool->execute(connection, request_handler)) {
on_retry(request_handler, RETRY_WITH_NEXT_HOST);
}
} else { // Too busy, or no connections
if (!pool->wait_for_connection(request_handler)) {
on_retry(request_handler, RETRY_WITH_NEXT_HOST);
}
}
} else {
on_retry(request_handler, RETRY_WITH_NEXT_HOST);
}
}
void IOWorker::on_request_finished(RequestHandler* request_handler) {
pending_request_count_--;
maybe_close();
}
void IOWorker::on_event(const IOWorkerEvent& event) {
if (event.type == IOWorkerEvent::ADD_POOL) {
add_pool(event.host);
} else if (event.type == IOWorkerEvent::REMOVE_POOL) {
// TODO(mpenick):
}
}
void IOWorker::on_pool_reconnect(Timer* timer) {
ReconnectRequest* reconnect_request =
static_cast<ReconnectRequest*>(timer->data());
IOWorker* io_worker = reconnect_request->io_worker;
if (!io_worker->is_closing_) {
io_worker->logger_->info(
"Attempting to reconnect to '%s'",
reconnect_request->host.address.to_string().c_str());
io_worker->add_pool(reconnect_request->host);
}
delete reconnect_request;
}
void IOWorker::on_execute(uv_async_t* async, int status) {
IOWorker* io_worker = reinterpret_cast<IOWorker*>(async->data);
RequestHandler* request_handler = nullptr;
while (io_worker->request_queue_.dequeue(request_handler)) {
if (request_handler != nullptr) {
io_worker->pending_request_count_++;
request_handler->set_retry_callback(
std::bind(&IOWorker::on_retry, io_worker, std::placeholders::_1,
std::placeholders::_2));
request_handler->set_finished_callback(std::bind(
&IOWorker::on_request_finished, io_worker, std::placeholders::_1));
request_handler->retry(RETRY_WITH_CURRENT_HOST);
}
}
io_worker->maybe_close();
}
void IOWorker::on_prepare(uv_prepare_t* prepare, int status) {
IOWorker* io_worker = reinterpret_cast<IOWorker*>(prepare->data);
io_worker->cleanup();
}
} // namespace cass
| 28.175439 | 80 | 0.693337 | Paycasso |
de5a2a360613b4f97ca9dc28208b296e0d9d8c88 | 1,721 | cpp | C++ | LeetCode/100/1847.cpp | K-ona/C-_Training | d54970f7923607bdc54fc13677220d1b3daf09e5 | [
"Apache-2.0"
] | 1 | 2021-03-05T14:16:46.000Z | 2021-03-05T14:16:46.000Z | LeetCode/100/1847.cpp | K-ona/CPP-Training | aa312970505f67c270257c8a5816e89c10f2d1ce | [
"Apache-2.0"
] | null | null | null | LeetCode/100/1847.cpp | K-ona/CPP-Training | aa312970505f67c270257c8a5816e89c10f2d1ce | [
"Apache-2.0"
] | null | null | null | // created by Kona @VSCode
#include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <vector>
#define LOCAL_TEST
typedef long long ll;
using std::cin;
using std::cout;
using std::endl;
using std::map;
using std::queue;
using std::set;
using std::string;
using std::vector;
class Solution {
public:
vector<int> closestRoom(vector<vector<int>>& rooms,
vector<vector<int>>& queries) {
std::sort(rooms.begin(), rooms.end(),
[&](vector<int> &first, vector<int> &second) -> bool {
return first[1] > second[1];
});
for (int i = 0; i < queries.size(); ++i) {
queries[i].push_back(i);
}
std::sort(queries.begin(), queries.end(),
[&](vector<int> &first, vector<int> &second) -> bool {
return first[1] > second[1];
});
vector<int> res(queries.size(), 0);
set<int> Sup;
for (int i = 0, l = 0; i < queries.size(); ++i) {
// cout << queries[i][1] << endl;
while (l < rooms.size() && rooms[l][1] >= queries[i][1])
Sup.insert(rooms[l++][0]);
auto pos = Sup.lower_bound(queries[i][0]);
if (Sup.empty())
res[queries[i][2]] = -1;
else if (pos == Sup.begin())
res[queries[i][2]] = *pos;
else if (abs(*pos - queries[i][0]) >= abs(*(--pos) - queries[i][0])) {
res[queries[i][2]] = *pos;
} else {
res[queries[i][2]] = *(++pos);
}
}
return res;
}
};
int main() {
std::ios_base::sync_with_stdio(false);
#ifdef LOCAL_TEST
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
/* code */
return 0;
} | 24.942029 | 76 | 0.531087 | K-ona |
de5baaef664e1b5ea845d6166be70d38c0830770 | 454 | cpp | C++ | Olympiad Programs/Helli Programming Training/Codeforces 189A.cpp | mirtaba/ACMICPC-INOI_Archive | ea06e4e40e984f0807410e4f9b5f7042580da2e3 | [
"MIT"
] | 1 | 2020-12-08T11:21:34.000Z | 2020-12-08T11:21:34.000Z | Olympiad Programs/Helli Programming Training/Codeforces 189A.cpp | mirtaba/ACMICPC-INOI_Archive | ea06e4e40e984f0807410e4f9b5f7042580da2e3 | [
"MIT"
] | null | null | null | Olympiad Programs/Helli Programming Training/Codeforces 189A.cpp | mirtaba/ACMICPC-INOI_Archive | ea06e4e40e984f0807410e4f9b5f7042580da2e3 | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
using namespace std;
const int Maxn=4*1E4+25;
int N,a,b,c;
//bool can[Maxn];
int num[Maxn];
int main()
{
cin >> N >> a >> b >> c;
num[a]=1;
num[b]=1;
num[c]=1;
for (int i=1;i<=N;i++)
if(num[i]!=0)
{
num[i+a]=max(num[i+a],num[i]+1);
num[i+b]=max(num[i+b],num[i]+1);
num[i+c]=max(num[i+c],num[i]+1);
}
cout << num[N] << endl;
}
| 17.461538 | 44 | 0.455947 | mirtaba |
de6081cdb76d6ad83b0f3733e23a463a59c18229 | 9,473 | cpp | C++ | Data Structures Final C++/CIS22C-Final-Group3/CIS22C-Final-Group3/FileIO.cpp | LEmilio14/Projects_in_C_PlusPlus | 3c004b0a7c958163243752a4903329d2e40517d4 | [
"MIT"
] | 2 | 2019-09-21T05:48:53.000Z | 2020-03-30T00:29:42.000Z | Data Structures Final C++/CIS22C-Final-Group3/CIS22C-Final-Group3/FileIO.cpp | LEmilio14/Projects_in_C_PlusPlus | 3c004b0a7c958163243752a4903329d2e40517d4 | [
"MIT"
] | null | null | null | Data Structures Final C++/CIS22C-Final-Group3/CIS22C-Final-Group3/FileIO.cpp | LEmilio14/Projects_in_C_PlusPlus | 3c004b0a7c958163243752a4903329d2e40517d4 | [
"MIT"
] | 1 | 2019-09-21T05:47:20.000Z | 2019-09-21T05:47:20.000Z | #include "FileIO.h"
#include <fstream>
namespace FileIO
{
namespace
{
const std::string DELIM_ITEM = "item";
const std::string DELIM_UID = "UID";
const std::string DELIM_UPC = "UPC";
const std::string DELIM_NAME = "name";
const std::string DELIM_SIZE = "size";
const std::string DELIM_CATEGORY = "category";
const std::string DELIM_WHOLESALE = "wholesale";
const std::string DELIM_RETAIL = "retail";
const std::string DELIM_QUANTITY = "quantity";
/**
* @author Olivier Chan
*
* @brief Returns a substring of the passed string starting at the (skip + 1)th instance of "<delimiter>" and ending after the subsequent instance of "</delimiter>".
* The angle brackets and delimiters are removed from the substring.
* If skip is greater than the number of delimiters in the string, an empty string is returned.
*
* @detail Example: parseString("<txt>Foo</txt> <txt>Bar</txt>", "txt", 0) will return "Foo".
*
* @param str The string to parse. The string should contain "<delimiter>" and "</delimiter>" tags.
*
* @param delimiter The string to act as a delimiter. This function adds angle brackets around the delimiter, so they should not be included in the passed delimiter.
*
* @param skip The number of times to skip an instance of the delimiter.
*
* @return A substring of the passed string starting at the (skip + 1)th instance of "<delimiter>" and ending after the subsequent instance of "</delimiter>".
* The angle brackets and delimiters are removed from the substring.
* If skip is greater than the number of delimiters in the string, an empty string is returned.
*/
std::string parseString(const std::string& str, const std::string& delimiter, const int skip)
{
const std::string delimitBeg = "<" + delimiter + ">";
const std::string delimitEnd = "</" + delimiter + ">";
//Set the starting position to after the (skip)th delimiter
size_t startingPos = 0;
for (int i = 0; i < skip; i++)
{
const size_t delimiterPos = str.find(delimitEnd, startingPos);
if (delimiterPos != std::string::npos)
{
startingPos = str.find(delimitEnd, startingPos) + delimitEnd.length();
}
else
{
//The starting position is after the last delimiter, return an empty string
throw std::invalid_argument("Passed end of string.");
}
}
//From the starting position, find the positions of the first instances of the beginning and ending delimiters
const size_t delimitBegPos = str.find(delimitBeg, startingPos);
const size_t delimitEndPos = str.find(delimitEnd, startingPos);
//Return the substring between the beginning and ending delimiters
return str.substr(delimitBegPos + delimitBeg.length(), delimitEndPos - delimitBegPos - delimitBeg.length());
}
std::string parseString(const std::string& str, const std::string& delimiter)
{
const std::string delimitBeg = "<" + delimiter + ">";
const std::string delimitEnd = "</" + delimiter + ">";
//Find the positions of the first instances of the beginning and ending delimiters
const size_t delimitBegPos = str.find(delimitBeg);
const size_t delimitEndPos = str.find(delimitEnd);
if (delimitBegPos != std::string::npos)
{
return str.substr(delimitBegPos + delimitBeg.length(), delimitEndPos - delimitBegPos - delimitBeg.length());
}
else
{
//The delimiter doesn't exist in the string, return an empty string
return std::string();
}
}
/**
* @author Olivier Chan
*
* @brief Returns the contents of the file located at path as a string. If the file at path doesn't exist, returns an empty string.
*
* @param path The path of the file to convert contents to a string.
*
* @return The contents of the file from path as a string. If the file at path doesn't exist, returns an empty string.
*/
std::string fileToString(const std::string& path)
{
std::ifstream in(path, std::ios::ate);
if (in)
{
std::string str;
//Reserve space in the string to store the entire file, not strictly required
str.reserve(static_cast<size_t>(in.tellg()));
in.seekg(0, std::ios::beg);
//Store the entire file in the string by iterating from beginning to end
str.assign((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
return str;
}
else
{
//If the file doesn't exist or isn't openable, throw an exception
throw std::invalid_argument("ERROR: File doesn't exist or is unopenable.");
}
}
/**
* getNumBooksInString
*
* @brief Returns the number of books in the string based on the book delimiter.
*
* @param str The string to search for books. In almost every case this should be the inventory string.
*
* @return Number of books in the string.
*/
int getNumItemsInString(const std::string& str)
{
int count = 0;
size_t pos = 0;
const std::string delimiter = "<" + DELIM_ITEM + ">";
pos = str.find(delimiter, pos);
while (pos != std::string::npos)
{
count++;
pos = str.find(delimiter, pos + delimiter.length());
}
return count;
}
/**
* @brief Turns an item into a string, formatted into the form used in the inventory file.
*
* @param item The item to turn into a string.
*
* @return The item as a database formatted string.
*/
std::string itemToString(const Item& item)
{
std::string wholesaleString = std::to_string(item.wholesale);
wholesaleString = wholesaleString.substr(0, wholesaleString.find('.') + 3);
std::string retailString = std::to_string(item.retail);
retailString = retailString.substr(0, retailString.find('.') + 3);
std::string itemString =
"<" + DELIM_ITEM + ">" + "\n"
+ "\t" + "<" + DELIM_UID + ">" + std::to_string(item.uid) + "</" + DELIM_UID + ">" + "\n"
+ "\t" + "<" + DELIM_UPC + ">" + item.upc + "</" + DELIM_UPC + ">" + "\n"
+ "\t" + "<" + DELIM_NAME + ">" + item.name + "</" + DELIM_NAME + ">" + "\n"
+ "\t" + "<" + DELIM_SIZE + ">" + item.size + "</" + DELIM_SIZE + ">" + "\n"
+ "\t" + "<" + DELIM_CATEGORY + ">" + std::to_string(item.category) + "</" + DELIM_CATEGORY + ">" + "\n"
+ "\t" + "<" + DELIM_WHOLESALE + ">" + wholesaleString + "</" + DELIM_WHOLESALE + ">" + "\n"
+ "\t" + "<" + DELIM_RETAIL + ">" + retailString + "</" + DELIM_RETAIL + ">" + "\n"
+ "\t" + "<" + DELIM_QUANTITY + ">" + std::to_string(item.quantity) + "</" + DELIM_QUANTITY + ">" "\n"
"</" + DELIM_ITEM + ">" + "\n";
return itemString;
}
}
void loadFileIntoArray(Array<Item>& arr, const std::string& filePath)
{
if (arr.getSize() > 0)
{
throw std::invalid_argument("ERROR: Array is not empty.");
}
const std::string itemsString = fileToString(filePath);
const int numItems = getNumItemsInString(itemsString);
for (int i = 0; i < numItems; i++)
{
const std::string itemString = parseString(itemsString, DELIM_ITEM, i);
int uid;
std::string upc;
std::string name;
std::string size;
int category;
double wholesale;
double retail;
int quantity;
//UID - must be validated
const std::string uidString = parseString(itemString, DELIM_UID);
if (uidString.empty())
{
throw std::runtime_error("ERROR: Database file corrupted - UID missing.");
}
else
{
try
{
uid = std::stoi(uidString);
}
catch (...)
{
throw std::runtime_error("ERROR: Database file corrupted - UID corrupted.");
}
}
//UPC
upc = parseString(itemString, DELIM_UPC);
//Name
name = parseString(itemString, DELIM_NAME);
//Size
size = parseString(itemString, DELIM_SIZE);
//Category
const std::string categoryString = parseString(itemString, DELIM_CATEGORY);
if (categoryString.empty())
{
category = 0;
}
else
{
try
{
category = std::stoi(categoryString);
}
catch (...)
{
throw std::runtime_error("ERROR: Database file corrupted - Category corrupted.");
}
}
//Wholesale
const std::string wholesaleString = parseString(itemString, DELIM_WHOLESALE);
if (wholesaleString.empty())
{
wholesale = 0;
}
else
{
try
{
wholesale = std::stod(wholesaleString);
}
catch (...)
{
throw std::runtime_error("ERROR: Database file corrupted - Wholesale price corrupted.");
}
}
//Retail
const std::string retailString = parseString(itemString, DELIM_RETAIL);
if (retailString.empty())
{
retail = 0;
}
else
{
try
{
retail = std::stod(retailString);
}
catch (...)
{
throw std::runtime_error("ERROR: Database file corrupted - Retail price corrupted.");
}
}
//Quantity
const std::string quantityString = parseString(itemString, DELIM_QUANTITY);
if (quantityString.empty())
{
quantity = 0;
}
else
{
try
{
quantity = std::stoi(quantityString);
}
catch (...)
{
throw std::runtime_error("ERROR: Database file corrupted - Quantity corrupted.");
}
}
arr.append(Item(std::move(uid), std::move(upc), std::move(name), std::move(size), std::move(category), std::move(wholesale), std::move(retail), std::move(quantity)));
}
}
void saveListIntoFile(List<Item>& list, const std::string& filePath)
{
std::string itemsString = std::string();
for (int i = 0; i < list.getCount(); i++)
{
itemsString.append(itemToString(list[i]));
}
std::ofstream os;
os.open(filePath);
os << itemsString;
os.close();
}
} | 30.957516 | 169 | 0.642141 | LEmilio14 |
de644c9121d2c4979dc1e482b0ccf025b86ce39e | 638 | cpp | C++ | done/blist2.cpp | birdhumming/usaco | f011e7bd4b71de22736a61004e501af2b273b246 | [
"OLDAP-2.2.1"
] | null | null | null | done/blist2.cpp | birdhumming/usaco | f011e7bd4b71de22736a61004e501af2b273b246 | [
"OLDAP-2.2.1"
] | null | null | null | done/blist2.cpp | birdhumming/usaco | f011e7bd4b71de22736a61004e501af2b273b246 | [
"OLDAP-2.2.1"
] | null | null | null | #include <algorithm>
#include <fstream>
#include <iostream>
using namespace std;
int N;
int S[101], T[101], B[101]; //start, end, buckets
int main(void) {
ifstream fin ("blist.in");
ofstream fout ("blist.out");
fin>>N;
for (int i=1; i<=N; i++) {
fin>>S[i]>>T[i]>>B[i];
}
int max_buckets=0;
for (int t=1; t<=1000; t++) { //time
int buckets_at_time=0;
for (int i=1; i<=N; i++) {
if (S[i] <= t && t <= T[i]) {
buckets_at_time+=B[i];
}
}
max_buckets=max(max_buckets, buckets_at_time); //finding max
}
fout<<max_buckets;
}
| 22.785714 | 68 | 0.504702 | birdhumming |
de667200b1edc16c4a6733f4a8050b9fb5ec4a99 | 22,013 | cpp | C++ | resultswindow.cpp | DOMjudge/DOMjura | 271e579713995b75be3d6fef289c6c714f26f1b4 | [
"MIT"
] | 9 | 2019-04-23T08:07:08.000Z | 2021-12-04T07:11:35.000Z | resultswindow.cpp | DOMjudge/DOMjura | 271e579713995b75be3d6fef289c6c714f26f1b4 | [
"MIT"
] | 5 | 2019-04-24T05:45:35.000Z | 2021-10-08T06:48:09.000Z | resultswindow.cpp | nickygerritsen/DOMjura | 271e579713995b75be3d6fef289c6c714f26f1b4 | [
"MIT"
] | 6 | 2015-06-26T14:00:23.000Z | 2019-04-22T02:59:31.000Z | #include "resultswindow.h"
#include <QKeyEvent>
#include <QApplication>
#include <QDesktopWidget>
#include <QPropertyAnimation>
#include <QtOpenGL/QtOpenGL>
#include <QTimer>
#include <QSettings>
#include <math.h>
#include "gradientcache.h"
#include "defines.h"
#include "contest.h"
namespace DJ {
namespace View {
ResultsWindow::ResultsWindow(QWidget *parent) : QGraphicsView(parent) {
setFrameShape(QFrame::NoFrame);
this->started = false;
this->offset = 0.0;
this->canDoNextStep = true;
this->resolvDone = false;
this->lastResolvTeam = -1;
this->currentResolvIndex = -1;
this->scene = new QGraphicsScene(this);
this->scene->setSceneRect(QApplication::desktop()->screenGeometry());
this->scene->setBackgroundBrush(Qt::black);
this->setScene(this->scene);
this->setGeometry(QApplication::desktop()->screenGeometry());
this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
this->centerOn(0, 0);
this->setViewportUpdateMode(FullViewportUpdate);
this->setCacheMode(CacheBackground);
this->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform | QPainter::TextAntialiasing);
if (USE_OPENGL) {
this->setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers)));
} else {
this->setViewport(new QWidget);
}
this->headerItem = new HeaderGraphicsItem(QApplication::desktop()->screenGeometry().width());
this->headerItem->setPos(0, 0);
this->legendaItem = new LegendaGraphicsItem();
QRectF legendaRect = this->legendaItem->boundingRect();
this->legendaItem->setPos(QApplication::desktop()->screenGeometry().width() - legendaRect.width() - LEGENDA_RIGHT_OFFSET,
QApplication::desktop()->screenGeometry().height() - legendaRect.height() - LEGENDA_BOTTOM_OFFSET);
this->legendaItem->setZValue(1);
this->winnerItem = new WinnerGraphicsItem;
this->winnerItem->setPos(0, 0);
this->winnerItem->setZValue(2);
this->winnerItem->setOpacity(0);
this->pixmap = new QGraphicsPixmapItem;
this->pixmap->setZValue(1);
this->scene->addItem(this->pixmap);
this->scene->addItem(this->headerItem);
this->scene->addItem(this->legendaItem);
this->scene->addItem(this->winnerItem);
}
void ResultsWindow::setTeams(QList<ResultTeam> teams, bool animated, int lastResolvedTeam, int lastResolvedProblem, int currentTeam) {
if (animated) {
if (this->lastResolvTeam >= 0) {
this->teamItems.at(this->lastResolvTeam)->setHighlighted(false);
}
// Save all data
this->teamsToSet = teams;
this->lastResolvTeam = lastResolvedTeam;
this->lastResolvProblem = lastResolvedProblem;
this->currentResolvIndex = currentTeam;
this->teamItems.at(this->lastResolvTeam)->setHighlighted(true);
int screenHeight = QApplication::desktop()->screenGeometry().height();
int itemToScrollHeight = HEADER_HEIGHT + (this->lastResolvTeam + 1) * TEAMITEM_HEIGHT + RESOLV_BELOW_OFFSET;
int toScroll = qMax(0, itemToScrollHeight - screenHeight);
QPointF toScrollPoint(0, toScroll);
if (this->headerItem->pos().y() == -toScroll) {
// start a timer that waits a second
QTimer *timer = new QTimer;
timer->setSingleShot(true);
connect(timer, SIGNAL(timeout()), this, SLOT(timerDone()));
this->runningTimers.append(timer);
timer->start(TIME_TO_WAIT);
} else {
// First, move to the the row to highlight
QParallelAnimationGroup *scrollToRowAnim = new QParallelAnimationGroup;
scrollToRowAnim->setProperty("DJ_animType", "toRow");
connect(scrollToRowAnim, SIGNAL(finished()), this, SLOT(animationDone()));
QPropertyAnimation *animHeader = new QPropertyAnimation(this->headerItem, "pos");
animHeader->setDuration(TIME_TO_SCROLL);
animHeader->setStartValue(this->headerItem->pos());
animHeader->setEndValue(QPointF(0, 0) - toScrollPoint);
scrollToRowAnim->addAnimation(animHeader);
for (int i = 0; i < this->teamItems.size(); i++) {
QPropertyAnimation *animItem = new QPropertyAnimation(this->teamItems.at(i), "pos");
animItem->setDuration(TIME_TO_SCROLL);
QPointF startPoint;
startPoint.setX(0);
startPoint.setY(HEADER_HEIGHT + i * TEAMITEM_HEIGHT);
QPointF newPoint = startPoint;
newPoint -= toScrollPoint;
animItem->setStartValue(this->teamItems.at(i)->pos());
animItem->setEndValue(newPoint);
scrollToRowAnim->addAnimation(animItem);
}
this->runningAnimations.append(scrollToRowAnim);
scrollToRowAnim->start();
}
} else {
for (int i = 0; i < this->teamItems.size(); i++) {
this->scene->removeItem(this->teamItems.at(i));
delete this->teamItems.at(i);
}
this->teamItems.clear();
if (teams.size() == 0) {
return;
}
this->teams = teams;
int numprobs = teams.at(0).problems.size();
GradientCache::getInstance()->setNumProbs(numprobs);
int probWidth = (NAME_WIDTH - (numprobs - 1) * PROB_MARGIN) / numprobs;
for (int i = 0; i < teams.size(); i++) {
QList<ResultProblem> problems = teams.at(i).problems;
if (problems.size() == 0) {
return;
}
QList<ProblemGraphicsItem *> problemItems;
for (int j = 0; j < numprobs; j++) {
ProblemGraphicsItem *probItem = new ProblemGraphicsItem(0, probWidth);
probItem->setProblemId(problems.at(j).problemId);
probItem->setState(problems.at(j).state);
probItem->setNumTries(problems.at(j).numTries);
probItem->setTime(problems.at(j).time);
problemItems.append(probItem);
}
TeamGraphicsItem *teamItem = new TeamGraphicsItem(problemItems);
teamItem->setRank(teams.at(i).rank);
teamItem->setName(teams.at(i).name);
teamItem->setSolved(teams.at(i).solved);
teamItem->setTime(teams.at(i).time);
if (this->lastResolvTeam >= 0 && i >= this->lastResolvTeam && i < GOLD) {
teamItem->setMedal(GOLD_MEDAL);
} else if (this->lastResolvTeam >= 0 && i >= this->lastResolvTeam && i < SILVER) {
teamItem->setMedal(SILVER_MEDAL);
} else if (this->lastResolvTeam >= 0 && i >= this->lastResolvTeam && i < BRONZE) {
teamItem->setMedal(BRONZE_MEDAL);
} else {
teamItem->setMedal(NO_MEDAL);
}
teamItem->setPos(0, HEADER_HEIGHT + i * TEAMITEM_HEIGHT + this->offset);
teamItem->setEven(i % 2 == 0);
this->teamItems.append(teamItem);
this->scene->addItem(teamItem);
}
}
}
void ResultsWindow::keyPressEvent(QKeyEvent *event) {
switch (event->key()) {
case Qt::Key_Escape:
case Qt::Key_Q:
case Qt::Key_X:
close();
break;
case Qt::Key_Enter:
case Qt::Key_Return:
case Qt::Key_Space:
if (this->canDoNextStep) {
doNextStep();
}
}
}
void ResultsWindow::mousePressEvent(QMouseEvent *event) {
if (event->button() == Qt::LeftButton) {
if (this->canDoNextStep) {
doNextStep();
}
}
}
void ResultsWindow::stopAnimations() {
foreach (QAbstractAnimation *animation, this->runningAnimations) {
animation->stop();
delete animation;
}
this->runningAnimations.clear();
foreach (QTimer *timer, this->runningTimers) {
timer->stop();
delete timer;
}
this->runningTimers.clear();
}
void ResultsWindow::reload() {
if (USE_OPENGL) {
this->setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers)));
} else {
this->setViewport(new QWidget);
}
QString filename = BRANDING_IMAGE;
// Update branding image
if (!filename.isEmpty()) {
QPixmap pixmap(filename);
if (!pixmap.isNull()) {
this->pixmap->setPixmap(pixmap);
} else {
this->pixmap->setPixmap(QPixmap());
}
} else {
this->pixmap->setPixmap(QPixmap());
}
resizeImage();
this->offset = 0.0;
this->started = false;
this->canDoNextStep = true;
this->currentResolvIndex = -1;
this->lastResolvTeam = -1;
this->resolvDone = false;
this->headerItem->setPos(0, 0);
this->winnerItem->setOpacity(0);
this->hideLegendAfterTimeout();
}
void ResultsWindow::setResolvDone() {
this->resolvDone = true;
this->canDoNextStep = true;
}
void ResultsWindow::hideLegendAfterTimeout() {
this->legendaItem->setOpacity(1);
QRectF legendaRect = this->legendaItem->boundingRect();
this->legendaItem->setPos(QApplication::desktop()->screenGeometry().width() - legendaRect.width() - LEGENDA_RIGHT_OFFSET,
QApplication::desktop()->screenGeometry().height() - legendaRect.height() - LEGENDA_BOTTOM_OFFSET);
QTimer *legendaTimer = new QTimer(this);
legendaTimer->setSingleShot(true);
connect(legendaTimer, SIGNAL(timeout()), this, SLOT(hideLegenda()));
this->runningTimers.append(legendaTimer);
legendaTimer->start(LEGEND_WAIT_TIME);
}
void ResultsWindow::doNextStep() {
if (!this->started) {
this->canDoNextStep = false;
QParallelAnimationGroup *scrollToBottomAnim = new QParallelAnimationGroup;
connect(scrollToBottomAnim, SIGNAL(finished()), this, SLOT(animationDone()));
int screenHeight = QApplication::desktop()->screenGeometry().height();
int totalItemsHeight = HEADER_HEIGHT + this->teamItems.size() * TEAMITEM_HEIGHT + SCROLL_BELOW_OFFSET;
int toScroll = qMax(0, totalItemsHeight - screenHeight);
QPointF toScrollPoint(0, toScroll);
if (toScroll == 0) {
delete scrollToBottomAnim;
this->started = true;
doNextStep();
} else {
int timetoScroll = TIME_TO_WAIT + TIME_PER_ITEM * log(this->teamItems.size());
QPropertyAnimation *animHeader = new QPropertyAnimation(this->headerItem, "pos");
animHeader->setDuration(timetoScroll);
animHeader->setEasingCurve(QEasingCurve::OutBack);
animHeader->setStartValue(QPointF(0, 0));
animHeader->setEndValue(QPointF(0, 0) - toScrollPoint);
scrollToBottomAnim->addAnimation(animHeader);
for (int i = 0; i < this->teamItems.size(); i++) {
QPropertyAnimation *animItem = new QPropertyAnimation(this->teamItems.at(i), "pos");
animItem->setDuration(timetoScroll);
animItem->setEasingCurve(QEasingCurve::OutBack);
QPointF startPoint;
startPoint.setX(0);
startPoint.setY(HEADER_HEIGHT + i * TEAMITEM_HEIGHT);
QPointF newPoint = startPoint;
newPoint -= toScrollPoint;
animItem->setStartValue(startPoint);
animItem->setEndValue(newPoint);
scrollToBottomAnim->addAnimation(animItem);
}
scrollToBottomAnim->setProperty("DJ_animType", "scrollToBottom");
this->runningAnimations.append(scrollToBottomAnim);
scrollToBottomAnim->start();
}
} else if (this->resolvDone) {
this->canDoNextStep = false;
if (this->teams.isEmpty()) {
this->winnerItem->setWinner("No teams selected");
} else {
ResultTeam winningTeam = this->teams.at(0);
this->winnerItem->setWinner(winningTeam.name);
}
QPropertyAnimation *winnerAnim = new QPropertyAnimation(this->winnerItem, "opacity");
winnerAnim->setDuration(TIME_FOR_WINNER);
winnerAnim->setStartValue(0);
winnerAnim->setEndValue(1);
winnerAnim->setProperty("DJ_animType", "winner");
this->runningAnimations.append(winnerAnim);
winnerAnim->start();
} else {
this->canDoNextStep = false;
emit newStandingNeeded();
}
}
void ResultsWindow::animationDone() {
this->runningAnimations.removeAll((QAbstractAnimation *)this->sender());
this->sender()->deleteLater();
if (this->sender()->property("DJ_animType") == "scrollToBottom") {
this->started = true;
this->canDoNextStep = true;
} else if (this->sender()->property("DJ_animType") == "toRow") {
// start a timer that waits a second
QTimer *timer = new QTimer;
timer->setSingleShot(true);
connect(timer, SIGNAL(timeout()), this, SLOT(timerDone()));
this->runningTimers.append(timer);
timer->start(TIME_TO_WAIT);
} else if (this->sender()->property("DJ_animType") == "problemResolv") {
TeamGraphicsItem *team = this->teamItems.at(this->lastResolvTeam);
ProblemGraphicsItem *problem = team->getProblemGraphicsItem(this->lastResolvProblem);
problem->setHighlighted(false);
if (problem->isSolved()) {
problem->setState(SOLVED);
// Determine where to move the row to
int moveTo = this->lastResolvTeam;
while (this->teamsToSet.at(moveTo).id != this->teams.at(this->lastResolvTeam).id) {
moveTo--;
}
TeamGraphicsItem *teamThatMoves = this->teamItems.at(this->lastResolvTeam);
ResultTeam resultTeam = this->teamsToSet.at(moveTo);
teamThatMoves->setRank(resultTeam.rank);
teamThatMoves->setTime(resultTeam.time);
teamThatMoves->setSolved(resultTeam.solved);
int tme = TIME_TO_MOVE_INIT + TIME_TO_MOVE * (this->lastResolvTeam - moveTo);
if (tme == TIME_TO_MOVE_INIT) {
QTimer *timer = new QTimer;
timer->setSingleShot(true);
connect(timer, SIGNAL(timeout()), this, SLOT(timerMoveUpDone()));
this->runningTimers.append(timer);
timer->start(TIME_TO_MOVE);
} else {
// Now move the current team to moveTo and move all teams from moveTo until the current team one down
QPointF moveToPoint = this->teamItems.at(moveTo)->pos();
QParallelAnimationGroup *moveAnim = new QParallelAnimationGroup;
QPropertyAnimation *moveUpAnim = new QPropertyAnimation(this->teamItems.at(this->lastResolvTeam), "pos");
connect(moveAnim, SIGNAL(finished()), this, SLOT(animationDone()));
moveUpAnim->setDuration(tme);
moveUpAnim->setStartValue(this->teamItems.at(this->lastResolvTeam)->pos());
moveUpAnim->setEndValue(moveToPoint);
moveAnim->addAnimation(moveUpAnim);
// Update standings
for (int i = moveTo; i < this->teamItems.size(); i++) {
if (i != this->lastResolvTeam) {
TeamGraphicsItem *team = this->teamItems.at(i);
ResultTeam resultTeamToSet;
if (i < this->lastResolvTeam) {
resultTeamToSet = this->teamsToSet.at(i+1);
} else {
resultTeamToSet = this->teamsToSet.at(i);
}
team->setRank(resultTeamToSet.rank);
}
}
for (int i = moveTo; i < this->lastResolvTeam; i++) {
TeamGraphicsItem *team = this->teamItems.at(i);
QPropertyAnimation *moveDownAnim = new QPropertyAnimation(team, "pos");
moveDownAnim->setDuration(tme);
moveDownAnim->setStartValue(team->pos());
moveDownAnim->setEndValue(team->pos() + QPointF(0, TEAMITEM_HEIGHT));
moveAnim->addAnimation(moveDownAnim);
}
this->runningAnimations.append(moveAnim);
moveAnim->setProperty("DJ_animType", "moveTeam");
moveAnim->start();
}
} else { // if the problem is not solved, just go to the next resolv
this->offset = this->headerItem->pos().y();
this->setTeams(this->teamsToSet);
doNextStep();
}
} else if (this->sender()->property("DJ_animType") == "moveTeam") {
QTimer *timer = new QTimer;
timer->setSingleShot(true);
connect(timer, SIGNAL(timeout()), this, SLOT(timerMoveUpDone()));
this->runningTimers.append(timer);
timer->start(TIME_TO_MOVE_INIT);
} else if (this->sender()->property("DJ_animType") == "winner") {
// Do nothing...
}
}
void ResultsWindow::timerDone() {
this->runningTimers.removeAll((QTimer *)this->sender());
this->sender()->deleteLater();
if (this->lastResolvTeam == this->currentResolvIndex) {
// Animate problem highlight
TeamGraphicsItem *team = this->teamItems.at(this->lastResolvTeam);
ProblemGraphicsItem *problem = team->getProblemGraphicsItem(this->lastResolvProblem);
problem->setHighlighted(true);
QPropertyAnimation *animHLC = new QPropertyAnimation(problem, "highlightColor");
animHLC->setDuration(TIME_TO_BLINK);
animHLC->setKeyValueAt(0, QColor(143, 124, 29));
animHLC->setKeyValueAt(0.125, QColor(70, 62, 14));
animHLC->setKeyValueAt(0.25, QColor(143, 124, 29));
animHLC->setKeyValueAt(0.375, QColor(70, 62, 14));
animHLC->setKeyValueAt(0.5, QColor(143, 124, 29));
animHLC->setKeyValueAt(0.625, QColor(70, 62, 14));
animHLC->setKeyValueAt(0.75, QColor(143, 124, 29));
animHLC->setKeyValueAt(0.875, QColor(70, 62, 14));
if (problem->isSolved()) {
animHLC->setKeyValueAt(1, QColor(0, 128, 0));
} else {
animHLC->setKeyValueAt(1, QColor(133, 0, 0));
}
QPropertyAnimation *animFC = new QPropertyAnimation(problem, "finalColor");
animFC->setDuration(TIME_TO_BLINK);
animFC->setKeyValueAt(0, QColor(255, 223, 54));
animFC->setKeyValueAt(0.125, QColor(255, 223, 54));
animFC->setKeyValueAt(0.25, QColor(255, 223, 54));
animFC->setKeyValueAt(0.375, QColor(255, 223, 54));
animFC->setKeyValueAt(0.5, QColor(255, 223, 54));
animFC->setKeyValueAt(0.625, QColor(255, 223, 54));
animFC->setKeyValueAt(0.75, QColor(255, 223, 54));
animFC->setKeyValueAt(0.875, QColor(255, 223, 54));
if (problem->isSolved()) {
animFC->setKeyValueAt(1, QColor(0, 230, 0));
} else {
animFC->setKeyValueAt(1, QColor(240, 0, 0));
}
QParallelAnimationGroup *parAnim = new QParallelAnimationGroup;
parAnim->addAnimation(animHLC);
parAnim->addAnimation(animFC);
parAnim->setProperty("DJ_animType", "problemResolv");
this->runningAnimations.append(parAnim);
connect(parAnim, SIGNAL(finished()), this, SLOT(animationDone()));
parAnim->start();
} else {
this->offset = this->headerItem->pos().y();
this->setTeams(this->teamsToSet);
this->teamItems.at(this->lastResolvTeam)->setHighlighted(true);
if (this->lastResolvTeam >= NEED_TO_CLICK) {
doNextStep();
} else {
this->canDoNextStep = true;
}
}
}
void ResultsWindow::timerMoveUpDone() {
this->runningTimers.removeAll((QTimer *)this->sender());
this->sender()->deleteLater();
this->offset = this->headerItem->pos().y();
this->setTeams(this->teamsToSet);
doNextStep();
}
void ResultsWindow::resizeImage() {
QSize size;
if (!this->pixmap->pixmap().isNull()) {
size = this->pixmap->pixmap().size();
} else {
size = QSize(0, 0);
}
QRect screenSize = QApplication::desktop()->screenGeometry();
QPointF labelPos;
labelPos.setX(screenSize.width() - size.width() - BRANDING_IMAGE_OFFSET_X);
labelPos.setY(screenSize.height() - size.height() - BRANDING_IMAGE_OFFSET_Y);
this->pixmap->setPos(labelPos);
}
void ResultsWindow::hideLegenda() {
this->runningTimers.removeAll((QTimer *)this->sender());
this->sender()->deleteLater();
QPropertyAnimation *legendaAnim = new QPropertyAnimation(this->legendaItem, "opacity");
legendaAnim->setDuration(LEGEND_HIDE_TIME);
legendaAnim->setEasingCurve(QEasingCurve::InOutExpo);
legendaAnim->setStartValue(1);
legendaAnim->setEndValue(0);
this->runningAnimations.append(legendaAnim);
legendaAnim->setProperty("DJ_animType", "legenda");
legendaAnim->start();
}
int ResultsWindow::getCurrentResolvIndex() {
return this->currentResolvIndex;
}
ResultTeam ResultsWindow::getResultTeam(int i) {
return this->teams.at(i);
}
void ResultsWindow::setContest(Model::Contest *contest) {
this->winnerItem->setContestName(contest->getName());
}
} // namespace View
} // namespace DJ
| 41.37782 | 135 | 0.592968 | DOMjudge |
de6c98ed7e226f6109bc8274ffbd2160d5e7e07c | 530 | cpp | C++ | src/skills/vision/vision.cpp | GiulianoWF/RIDGS | 4acde23988e088b4f9a82c27bae67100ed83de5b | [
"MIT"
] | null | null | null | src/skills/vision/vision.cpp | GiulianoWF/RIDGS | 4acde23988e088b4f9a82c27bae67100ed83de5b | [
"MIT"
] | null | null | null | src/skills/vision/vision.cpp | GiulianoWF/RIDGS | 4acde23988e088b4f9a82c27bae67100ed83de5b | [
"MIT"
] | null | null | null | #include <iostream>
#include <opencv2/core.hpp>
#include "RIDGS_com.hpp"
int main(){
auto server_communication = ridgs::ProcessServerCOM("vision");
std::cout << "vision::working" << std::endl;
auto mat = cv::Mat();
std::string read;
server_communication >> read;
std::cout << "vision:Recieved from server (" << read << ")" << std::endl;
std::cout << "vision::Sending to server an number: 2" << std::endl;
server_communication.send(std::string{"1"});
std::cout << "vision::end working" << std::endl;
}
| 24.090909 | 75 | 0.639623 | GiulianoWF |
de6fbc5f6f6105bfb30d1270b51f1d446087c00e | 3,010 | cpp | C++ | libnaucrates/src/operators/CDXLScalarIndexCondList.cpp | khannaekta/gporca | 94e509d0a2456851a2cabf02e933c3523946b87b | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2019-03-05T10:08:56.000Z | 2019-03-05T10:08:56.000Z | libnaucrates/src/operators/CDXLScalarIndexCondList.cpp | khannaekta/gporca | 94e509d0a2456851a2cabf02e933c3523946b87b | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | libnaucrates/src/operators/CDXLScalarIndexCondList.cpp | khannaekta/gporca | 94e509d0a2456851a2cabf02e933c3523946b87b | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | //---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2012 EMC Corp.
//
// @filename:
// CDXLScalarIndexCondList.cpp
//
// @doc:
// Implementation of DXL index condition lists for DXL index scan operator
//---------------------------------------------------------------------------
#include "naucrates/dxl/operators/CDXLScalarIndexCondList.h"
#include "naucrates/dxl/operators/CDXLNode.h"
#include "naucrates/dxl/xml/CXMLSerializer.h"
using namespace gpos;
using namespace gpdxl;
//---------------------------------------------------------------------------
// @function:
// CDXLScalarIndexCondList::CDXLScalarIndexCondList
//
// @doc:
// ctor
//
//---------------------------------------------------------------------------
CDXLScalarIndexCondList::CDXLScalarIndexCondList
(
IMemoryPool *pmp
)
:
CDXLScalar(pmp)
{
}
//---------------------------------------------------------------------------
// @function:
// CDXLScalarIndexCondList::Edxlop
//
// @doc:
// Operator type
//
//---------------------------------------------------------------------------
Edxlopid
CDXLScalarIndexCondList::Edxlop() const
{
return EdxlopScalarIndexCondList;
}
//---------------------------------------------------------------------------
// @function:
// CDXLScalarIndexCondList::PstrOpName
//
// @doc:
// Operator name
//
//---------------------------------------------------------------------------
const CWStringConst *
CDXLScalarIndexCondList::PstrOpName() const
{
return CDXLTokens::PstrToken(EdxltokenScalarIndexCondList);
}
//---------------------------------------------------------------------------
// @function:
// CDXLScalarIndexCondList::SerializeToDXL
//
// @doc:
// Serialize operator in DXL format
//
//---------------------------------------------------------------------------
void
CDXLScalarIndexCondList::SerializeToDXL
(
CXMLSerializer *pxmlser,
const CDXLNode *pdxln
)
const
{
const CWStringConst *pstrElemName = PstrOpName();
pxmlser->OpenElement(CDXLTokens::PstrToken(EdxltokenNamespacePrefix), pstrElemName);
pdxln->SerializeChildrenToDXL(pxmlser);
pxmlser->CloseElement(CDXLTokens::PstrToken(EdxltokenNamespacePrefix), pstrElemName);
}
#ifdef GPOS_DEBUG
//---------------------------------------------------------------------------
// @function:
// CDXLScalarIndexCondList::AssertValid
//
// @doc:
// Checks whether operator node is well-structured
//
//---------------------------------------------------------------------------
void
CDXLScalarIndexCondList::AssertValid
(
const CDXLNode *pdxln,
BOOL fValidateChildren
)
const
{
GPOS_ASSERT(NULL != pdxln);
if (fValidateChildren)
{
const ULONG ulArity = pdxln->UlArity();
for (ULONG ul = 0; ul < ulArity; ul++)
{
CDXLNode *pdxlnChild = (*pdxln)[ul];
GPOS_ASSERT(EdxloptypeScalar == pdxlnChild->Pdxlop()->Edxloperatortype());
pdxlnChild->Pdxlop()->AssertValid(pdxlnChild, fValidateChildren);
}
}
}
#endif // GPOS_DEBUG
// EOF
| 25.083333 | 86 | 0.509635 | khannaekta |
de711760fec74ea2eb2739d540b16704726d40b8 | 8,384 | cpp | C++ | src/game/client/neotokyo/neo_hud_weapon.cpp | L-Leite/neotokyo-re | a45cdcb9027ffe8af72cf1f8e22976375e6b1e0a | [
"Unlicense"
] | 4 | 2017-08-29T15:39:53.000Z | 2019-06-04T07:37:48.000Z | src/game/client/neotokyo/neo_hud_weapon.cpp | Ochii/neotokyo | a45cdcb9027ffe8af72cf1f8e22976375e6b1e0a | [
"Unlicense"
] | null | null | null | src/game/client/neotokyo/neo_hud_weapon.cpp | Ochii/neotokyo | a45cdcb9027ffe8af72cf1f8e22976375e6b1e0a | [
"Unlicense"
] | 1 | 2021-08-10T20:01:00.000Z | 2021-08-10T20:01:00.000Z | #include "cbase.h"
#include "hud.h"
#include "hud_macros.h"
#include "view.h"
#include "iclientmode.h"
#include <KeyValues.h>
#include <vgui/ISystem.h>
#include <vgui/ISurface.h>
#include <vgui/ILocalize.h>
#include "hudelement.h"
#include "neo_hud_numericdisplay.h"
#include "c_neo_player.h"
#include "weapon_neobase.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
//-----------------------------------------------------------------------------
// Purpose: Health panel
//-----------------------------------------------------------------------------
class CNHudWeapon : public CHudElement, public CNHudNumericDisplay
{
DECLARE_CLASS_SIMPLE( CNHudWeapon, CNHudNumericDisplay );
public:
CNHudWeapon( const char *pElementName );
virtual void Init();
virtual void VidInit();
virtual void OnThink();
virtual void Paint();
virtual void DrawNumber( vgui::HFont hFont, int x, int y, int number );
void DrawBullets( vgui::HFont hFont, int x, int y, int iClip, int iDefaultClip );
void DrawWeaponIcon( vgui::HFont hFont );
void DrawWeaponName( vgui::HFont hFont );
void CopyWeaponName( wchar_t* szNewWepName );
private:
CPanelAnimationVarAliasType( float, m_flDigit_XPos, "digit_xpos", "50", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flDigit_YPos, "digit_ypos", "2", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flDigit2_XPos, "digit2_xpos", "0", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flDigit2_YPos, "digit2_ypos", "0", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flBar_XPos, "bar_xpos", "0", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flBar_YPos, "bar_ypos", "0", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flBar_Width, "bar_width", "2", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flBar_Height, "bar_height", "2", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flIcon_XPos, "icon_xpos", "0", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flIcon_YPos, "icon_ypos", "0", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flText_XPos, "text_xpos", "8", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flText_YPos, "text_ypos", "20", "proportional_float" );
CPanelAnimationVar( Color, m_TextColor, "TextColor", "FgColor" );
CPanelAnimationVar( vgui::HFont, m_hTFont, "TextFont", "NHudOCRSmall" );
CPanelAnimationVar( vgui::HFont, m_hNumberFont, "NumberFont", "NHudOCR" );
CPanelAnimationVar( vgui::HFont, m_hNumberGlowFont, "NumberGlowFont", "NHudOCRBlur" );
CPanelAnimationVar( vgui::HFont, m_hBulletFont, "HudBulletsFont", "NHudBullets" );
int m_iWhiteAdditiveTexture;
wchar_t m_szWeaponName[ 16 ];
EHANDLE m_hCurrentWeapon;
int m_iClip1;
int m_iDefaultClip;
int m_iAmmoCount;
wchar_t m_uBulletChar;
wchar_t m_uWeaponChar;
bool m_bUsesClips;
};
DECLARE_HUDELEMENT_DEPTH( CNHudWeapon, 50 );
using namespace vgui;
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CNHudWeapon::CNHudWeapon( const char *pElementName ) : CHudElement( pElementName ), CNHudNumericDisplay( nullptr, "NHudWeapon" )
{
vgui::Panel *pParent = g_pClientMode->GetViewport();
SetParent( pParent );
SetHiddenBits( HIDEHUD_PLAYERDEAD | HIDEHUD_HEALTH | HIDEHUD_WEAPONSELECTION );
m_iWhiteAdditiveTexture = surface()->CreateNewTextureID();
surface()->DrawSetTextureFile( m_iWhiteAdditiveTexture, "vgui/white_additive", true, false );
}
void CNHudWeapon::Init()
{
m_iClip1 = -1;
m_iDefaultClip = -1;
m_iAmmoCount = -1;
m_uBulletChar = L'a';
m_uWeaponChar = L'h';
}
void CNHudWeapon::VidInit()
{
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNHudWeapon::OnThink()
{
C_NEOPlayer* pLocalPlayer = C_NEOPlayer::GetLocalNEOPlayer();
if ( pLocalPlayer )
{
C_WeaponNEOBase* pWeapon = pLocalPlayer->GetActiveNEOWeapon();
if ( pWeapon )
{
SetPaintEnabled( true );
SetPaintBackgroundEnabled( true );
if ( pWeapon == m_hCurrentWeapon )
{
m_iClip1 = pWeapon->Clip1();
m_iAmmoCount = pLocalPlayer->GetAmmoCount( pWeapon->GetPrimaryAmmoType() );
if ( pWeapon->GetUnknown1452() )
m_iAmmoCount /= pWeapon->GetDefaultClip1();
m_uWeaponChar = pWeapon->GetWeaponChar();
}
else
{
m_hCurrentWeapon = pWeapon;
m_iClip1 = pWeapon->Clip1();
m_iDefaultClip = pWeapon->GetDefaultClip1();
m_uBulletChar = pWeapon->GetNEOWpnData().m_szBulletCharacter[0];
m_iAmmoCount = pLocalPlayer->GetAmmoCount( pWeapon->GetPrimaryAmmoType() );
if ( pWeapon->GetUnknown1452() )
m_iAmmoCount /= pWeapon->GetDefaultClip1();
m_bUsesClips = pWeapon->UsesClipsForAmmo1();
}
return;
}
}
SetPaintEnabled( false );
SetPaintBackgroundEnabled( false );
}
void CNHudWeapon::Paint()
{
int wide, tall;
GetSize( wide, tall );
DrawBox( 0, 0, wide + wide / 2, tall, Color( 200, 200, 200, 28 ), 1.0f );
C_NEOPlayer* pLocalPlayer = C_NEOPlayer::GetLocalNEOPlayer();
if ( !pLocalPlayer )
return;
C_WeaponNEOBase* pWeapon = pLocalPlayer->GetActiveNEOWeapon();
if ( !pWeapon )
return;
surface()->DrawSetTextColor( 255, 255, 255, 150 );
if ( pWeapon->HasAmmoClip() )
{
int iDefaultClip = 30;
if ( m_iDefaultClip <= 30 )
iDefaultClip = m_iDefaultClip;
int iClip = m_iClip1;
if ( iClip > 30 )
iClip = 30;
DrawBullets( m_hBulletFont, m_flDigit_XPos, m_flDigit_YPos, iClip, iDefaultClip );
if ( m_bUsesClips )
{
surface()->DrawSetTextColor( 255, 255, 255, 100 );
DrawNumber( m_hNumberFont, m_flDigit2_XPos, m_flDigit2_YPos, m_iAmmoCount );
DrawWeaponIcon( m_hBulletFont );
}
}
wchar_t weaponName[ 16 ];
g_pVGuiLocalize->ConvertANSIToUnicode( pWeapon->GetPrintName(), weaponName, sizeof( weaponName ) );
CopyWeaponName( weaponName );
DrawWeaponName( m_hTFont );
}
void CNHudWeapon::DrawNumber( HFont hFont, int x, int y, int number )
{
wchar_t buffer[ 10 ];
V_snwprintf( buffer, ARRAYSIZE( buffer ), L"%d", number );
int charWidth = surface()->GetCharacterWidth( hFont, 48 );
if ( number < 100 && m_Unknown246 )
x += charWidth;
if ( number < 10 && m_Unknown246 )
x += charWidth;
int textWide, textTall;
surface()->GetTextSize( hFont, buffer, textWide, textTall );
surface()->DrawSetTextPos( x - textWide, y );
surface()->DrawSetTextFont( hFont );
int bufLen = V_wcslen( buffer );
for ( int i = 0; i < bufLen; i++ )
surface()->DrawUnicodeChar( buffer[ i ] );
}
void CNHudWeapon::DrawBullets( HFont hFont, int x, int y, int iClip, int iDefaultClip )
{
wchar_t buffer[ 10 ];
V_snwprintf( buffer, ARRAYSIZE( buffer ), L"%d", iClip );
int bulletWidth = surface()->GetCharacterWidth( hFont, m_uBulletChar );
int textWide, textTall;
surface()->GetTextSize( hFont, buffer, textWide, textTall );
surface()->DrawSetTextPos( x - iDefaultClip * bulletWidth, y );
surface()->DrawSetTextFont( hFont );
if ( m_uBulletChar == L'd' )
surface()->DrawSetTextPos( x - bulletWidth * ( iDefaultClip + 1 ), y );
for ( int i = 0; i < iDefaultClip; i++ )
{
if ( i < iDefaultClip - iClip )
surface()->DrawSetTextColor( 255, 255, 255, 50 );
else
surface()->DrawSetTextColor( 255, 255, 255, 150 );
surface()->DrawUnicodeChar( m_uBulletChar );
}
}
void CNHudWeapon::DrawWeaponIcon( vgui::HFont hFont )
{
surface()->DrawSetTextPos( m_flIcon_XPos, m_flIcon_YPos );
surface()->DrawSetTextFont( hFont );
surface()->DrawSetTextColor( 255, 255, 255, 100 );
surface()->DrawUnicodeChar( m_uWeaponChar );
}
void CNHudWeapon::DrawWeaponName( vgui::HFont hFont )
{
surface()->DrawSetTextFont( hFont );
int textWide, textTall;
surface()->GetTextSize( hFont, m_szWeaponName, textWide, textTall );
surface()->DrawSetTextPos( m_flText_XPos - textWide, m_flText_YPos );
int bufLen = V_wcslen( m_szWeaponName );
for ( int i = 0; i < bufLen; i++ )
surface()->DrawUnicodeChar( m_szWeaponName[ i ] );
}
void CNHudWeapon::CopyWeaponName( wchar_t* szNewWepName )
{
V_wcsncpy( m_szWeaponName, szNewWepName, sizeof( m_szWeaponName ) );
m_uWeaponChar = 0;
}
| 28.420339 | 128 | 0.671517 | L-Leite |
de71c7d92d2d698230ad1886dda2b7837b009675 | 4,392 | cpp | C++ | src/threadpool.cpp | lingFlya/MyWebServer | 6c87995e19c76c873c8385ccb847d76e3dc62bff | [
"MIT"
] | null | null | null | src/threadpool.cpp | lingFlya/MyWebServer | 6c87995e19c76c873c8385ccb847d76e3dc62bff | [
"MIT"
] | 1 | 2020-09-06T07:57:02.000Z | 2020-09-12T14:32:25.000Z | src/threadpool.cpp | lingFlya/MyWebServer | 6c87995e19c76c873c8385ccb847d76e3dc62bff | [
"MIT"
] | null | null | null | /************************************************************************************
*@author RedDragon
*@date 2020/9/5
*@brief 线程池实现
* 就是通过pthread_create()创建固定线程数,省去了来一个任务才创建线程和销毁线程
* 的开销,我这里创建了四个固定线程,通过互斥量mutex和条件变量cond和一个任务队列task_queue添加任务
* 和完成任务.
*
* addTask是生产者
* worker是消费者
*************************************************************************************/
#include "threadpool.h"
#include <cstring>
// 消费者线程
void* threadPool::worker(void* arg)
{
if(arg == nullptr)
return nullptr;
threadPool* pool = (threadPool*)arg;
for(;;)
{
int err = pthread_mutex_lock(pool->mtx);
if(err != 0)
{
printf("errno = %d: %s", err, strerror(err));
break;
}
while (pool->taskCount <= 0)
pthread_cond_wait(pool->cond, pool->mtx);
// 拿到任务
Task tk = pool->taskQueue[pool->begin];
pool->begin += 1;
pool->taskCount -= 1;
err = pthread_mutex_unlock(pool->mtx);
if(err != 0)
{
printf("errno = %d: %s", err, strerror(err));
break;
}
// 执行任务
tk.func(tk.arg);
}
return nullptr;
}
/*
* @brief: 创建count个工作线程
* @return 成功创建的线程数
*/
int threadPool::createThread(int count)
{
int old = threadCount;
for(int i = 0; i < count; ++i)
{
pthread_t newTid;
int ret = pthread_create(&newTid, nullptr, worker, this);
if(ret != 0)
{// 内存等资源不够, 可能创建线程失败
printf("errno=%d: %s\n",ret, strerror(ret));
break;
}
else
{
printf("创建线程成功!\n");
tidVec.push_back(newTid);
threadCount++;
}
}
return threadCount - old;
}
// 构造函数(线程数初始为4)
threadPool::threadPool()
: threadPool(0)
{}
threadPool::threadPool(int count)
{
mtx = new pthread_mutex_t;
cond = new pthread_cond_t;
pthread_mutex_init(mtx, nullptr);
pthread_cond_init(cond, nullptr);
coreThreadCount = count;
threadCount = 0;
taskQueue = new Task[QUEUE_SIZE];
begin = end = taskCount = 0;
shutdown = false;
}
threadPool::~threadPool()
{
// 如果线程还在运行, 就join
// if(!shutdown)
// joinAll(THREADPOOL_GRACEFUL);
pthread_mutex_destroy(mtx);
pthread_cond_destroy(cond);
delete mtx;
delete cond;
delete[] taskQueue;
}
ThreadPoolStatus threadPool::addTask(Task tk)
{
int ret = pthread_mutex_lock(mtx); // 加锁
if(ret != 0)
{
printf("%s\n", strerror(ret));
return ThreadPoolStatus::LOCK_FAILURE;
}
int next = (end + 1)%QUEUE_SIZE;
ThreadPoolStatus err;
do{
if(taskCount == QUEUE_SIZE){
err = ThreadPoolStatus::QUEUE_FULL;
break;
}
if(shutdown){
err = ThreadPoolStatus::SHUTDOWN;
break;
}
// 创建线程
if(threadCount < maxThreadCount)
createThread(1);
// 增加任务
taskQueue[end] = tk;
++taskCount;
end = next;
// 通知工作线程
ret = pthread_cond_signal(cond);
if(ret != 0)
err = ThreadPoolStatus::LOCK_FAILURE;
}while(false);
ret = pthread_mutex_unlock(mtx);// 解锁
if(ret != 0)
{
printf("%s\n", strerror(ret));
return ThreadPoolStatus::LOCK_FAILURE;
}
return err;
}
ThreadPoolStatus threadPool::joinAll()
{
int ret = pthread_mutex_lock(mtx);
if(ret != 0)
return ThreadPoolStatus::LOCK_FAILURE;
ThreadPoolStatus err;
do{
if(shutdown){
err = ThreadPoolStatus::SHUTDOWN;
break;
}
// 唤醒所有线程, 所有线程都会退出
ret = pthread_cond_broadcast(cond);
if(ret != 0)
err = ThreadPoolStatus::LOCK_FAILURE;
ret = pthread_mutex_unlock(mtx);
if(ret != 0)
err = ThreadPoolStatus::LOCK_FAILURE;
for(int i = 0; i < threadCount; ++i)
{
ret = pthread_join(tidVec.back(), nullptr);
if(ret != 0)
err = ThreadPoolStatus::LOCK_FAILURE;
--threadCount;
tidVec.pop_back();
}
shutdown = true;
}while(false);
return err;
} | 24.4 | 87 | 0.502277 | lingFlya |
de7286095e21275895928729783b3c6f179f3ae9 | 2,897 | cpp | C++ | trunk/ProjectFootball/src/singlePlayer/db/bean/CPfPhaseTypes.cpp | dividio/projectfootball | 3c0b94937de2e3cd6e7daf9d3b4942fda974f20c | [
"Zlib"
] | null | null | null | trunk/ProjectFootball/src/singlePlayer/db/bean/CPfPhaseTypes.cpp | dividio/projectfootball | 3c0b94937de2e3cd6e7daf9d3b4942fda974f20c | [
"Zlib"
] | null | null | null | trunk/ProjectFootball/src/singlePlayer/db/bean/CPfPhaseTypes.cpp | dividio/projectfootball | 3c0b94937de2e3cd6e7daf9d3b4942fda974f20c | [
"Zlib"
] | null | null | null | /******************************************************************************
* Copyright (C) 2010 - Ikaro Games www.ikarogames.com *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License *
* as published by the Free Software Foundation; either version 2 *
* of the License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* *
* generated by dia/DAOcodegen.py *
* Version: 1.23 *
******************************************************************************/
#include <iostream>
#include <sstream>
#include <stdlib.h>
#include "CPfPhaseTypes.h"
CPfPhaseTypes::CPfPhaseTypes()
{
m_SPhaseType = "";
m_XPhaseType = "0";
}
CPfPhaseTypes::CPfPhaseTypes(const CPfPhaseTypes &obj)
{
m_SPhaseType = obj.m_SPhaseType;
m_XPhaseType = obj.m_XPhaseType;
}
CPfPhaseTypes::~CPfPhaseTypes()
{
}
const std::string& CPfPhaseTypes::getSPhaseType() const
{
return m_SPhaseType;
}
const std::string& CPfPhaseTypes::getSPhaseType_str() const
{
return m_SPhaseType;
}
int CPfPhaseTypes::getXPhaseType() const
{
if( m_XPhaseType=="" ){
return 0;
}else{
return atoi(m_XPhaseType.c_str());
}
}
const std::string& CPfPhaseTypes::getXPhaseType_str() const
{
return m_XPhaseType;
}
void CPfPhaseTypes::setSPhaseType(const std::string &SPhaseType)
{
m_SPhaseType = SPhaseType;
}
void CPfPhaseTypes::setSPhaseType_str(const std::string &SPhaseType)
{
m_SPhaseType = SPhaseType;
}
void CPfPhaseTypes::setXPhaseType(int XPhaseType)
{
std::ostringstream stream;
stream << XPhaseType;
m_XPhaseType = stream.str();
}
void CPfPhaseTypes::setXPhaseType_str(const std::string &XPhaseType)
{
m_XPhaseType = XPhaseType;
}
| 31.835165 | 79 | 0.509838 | dividio |
de74d7c4918fd6a20d3e7fa062ba1669a51ee5bc | 3,393 | hpp | C++ | include/parserFuncs.hpp | kleidibujari/doit | 5f566992f0dd1118def6ccdfdff47243f82e9ae1 | [
"MIT"
] | null | null | null | include/parserFuncs.hpp | kleidibujari/doit | 5f566992f0dd1118def6ccdfdff47243f82e9ae1 | [
"MIT"
] | null | null | null | include/parserFuncs.hpp | kleidibujari/doit | 5f566992f0dd1118def6ccdfdff47243f82e9ae1 | [
"MIT"
] | null | null | null | #include <string>
#include <fstream>
#include <vector>
#include <iostream>
#define CONFIG "$HOME/.config/do-it/doit.conf"
#include "usage.hpp"
std::string FILELOC;
//writing to file for strings (tasks)
void writeFile(std::string val)
{
std::ofstream ptr(FILELOC, std::ios_base::app);
ptr << val << std::endl;
ptr.close();
}
std::string readFile(int taskNum)
{
std::ifstream ptr(FILELOC);
int currentLine = 1;
std::string temp;
if (ptr.is_open())
{
while (getline(ptr, temp))
{
if (currentLine == taskNum){break;}
currentLine++;
}
} else
{
temp = "err";
}
ptr.close();
return temp;
}
void listTasks()
{
std::cout << "\n=====<tasks>=====\n";
std::string s;
int sTotal = 0;
std::ifstream ptr(FILELOC);
while (getline(ptr, s))
{
sTotal++;
}
for (int i = 1; i < sTotal + 1; i++){
std::cout << i << ") " << readFile(i) << "\n";
}
std::cout << "=====</tasks>=====\n\n";
}
void removeTask(int taskNum)
{
std::string TEMPFILE = FILELOC;
TEMPFILE.erase(TEMPFILE.length(), TEMPFILE.length() - 7);
TEMPFILE += "temp.txt";
// open file in read mode or in mode
std::ifstream is(FILELOC);
// open file in write mode or out mode
std::ofstream ofs;
//ofs.open("../temp.txt", std::ofstream::out);
ofs.open(TEMPFILE.c_str(), std::ofstream::out);
// loop getting single characters
char c;
int line_no = 1;
while (is.get(c))
{
// if a newline character
if (c == '\n')
line_no++;
// file content not to be deleted
if (line_no != taskNum)
ofs << c;
}
// closing output file
ofs.close();
// closing input file
is.close();
// remove the original file
remove(FILELOC.c_str());
// rename the file
//rename("../temp.txt", FILELOC.c_str());
rename(TEMPFILE.c_str(), FILELOC.c_str());
}
void removeEmpty()
{
int lineNum = 1;
std::string temp;
std::fstream ptr(FILELOC);
while(std::getline(ptr, temp))
{
if (!temp.empty())
{
removeTask(lineNum);
}
lineNum++;
}
}
void parseLine(int argc, std::vector<std::string> &args)
{
//reading location of list from config file
std::fstream config(CONFIG);
getline(config, FILELOC);
if (args[0] == "-help")
{
printUsage();
config.close();
}
else if (args[0] == "-a")
{
std::string temp;
for (size_t i = 1; i < (argc - 1); i++)
{
temp = temp + args[i] + " ";
}
writeFile(temp);
config.close();
}
else if (args[0] == "-l")
{
listTasks();
config.close();
}
else if (args[0] == "-r")
{
removeTask(stoi(args[1]));
removeEmpty();
config.close();
}
else
{
std::cout << "\ninvalid command // use -help to see available commands\n\n";
config.close();
}
}
| 21.074534 | 87 | 0.465665 | kleidibujari |
de7b7bed00d7886066295bde50de83dd9e7a33cb | 2,815 | hpp | C++ | pulsar/datastore/GenericBase.hpp | pulsar-chem/BPModule | f8e64e04fdb01947708f098e833600c459c2ff0e | [
"BSD-3-Clause"
] | null | null | null | pulsar/datastore/GenericBase.hpp | pulsar-chem/BPModule | f8e64e04fdb01947708f098e833600c459c2ff0e | [
"BSD-3-Clause"
] | null | null | null | pulsar/datastore/GenericBase.hpp | pulsar-chem/BPModule | f8e64e04fdb01947708f098e833600c459c2ff0e | [
"BSD-3-Clause"
] | null | null | null | /*! \file
*
* \brief Base class for holding generic data
*/
#pragma once
#include "pulsar/util/Serialization_fwd.hpp"
#include <bphash/Hash.hpp>
#include <memory>
namespace pulsar {
namespace detail {
/* Developer note
*
* Why not just have serialize functions and let cereal handle the
* polymorphic serialization?
*
* Answer: It would require registering every type of GenericHolder<T>,
* including any types held in the modules. That's a pain, so I work around
* it a bit by having the derived GenericHolder<T> handle the serialization
*/
/*! \brief An interface to a templated class that can hold anything
*
* This allows for storing any data types in containers.
*
* \threadunsafe
*/
class GenericBase
{
public:
GenericBase(void) noexcept = default;
virtual ~GenericBase() noexcept = default;
GenericBase & operator=(const GenericBase & rhs) = delete;
GenericBase & operator=(const GenericBase && rhs) = delete;
GenericBase(const GenericBase & rhs) = delete;
GenericBase(const GenericBase && rhs) = delete;
///////////////////////////////////
// Virtual functions
///////////////////////////////////
/*! \brief Returns a string representing the type
*
* \return A string representing the type (obtained via typeid().name())
*/
virtual const char * type(void) const noexcept = 0;
/*! \brief Returns a string representing the demangled type of the stored object
*
* For a C++ object, will return the demangled C++ type. For a python
* object, will return its class string.
*
* \return A string representing the type
*/
virtual std::string demangled_type(void) const = 0;
/*! \brief Check if the data stored in this object is serializable
*
* \return True if the stored type is serializable, false otherwise
*/
virtual bool is_serializable(void) const noexcept = 0;
/*! \brief Check if the data stored in this object is hashable
*
* \return True if the stored type is hashable, false otherwise
*/
virtual bool is_hashable(void) const noexcept = 0;
/*! \brief Serialize the data as a byte array
*
* \throw pulsar::PulsarException if the type is not
* serializable
*/
virtual ByteArray to_byte_array(void) const = 0;
/*! \brief Obtain the hash of the data
*
* \throw pulsar::PulsarException if the type is not
* hashable
*/
virtual bphash::HashValue my_hash(void) const = 0;
};
} //closing namespace datastore
} //closing namespace pulsar
| 26.809524 | 88 | 0.601066 | pulsar-chem |
de863c9bcce16e963f2d95a55060694a965760d8 | 730 | hh | C++ | Geant4/include/NDDRunAction.hh | leenderthayen/NDP | ffc16ccff47da53326e9a83f98b675d5db24bc59 | [
"MIT"
] | 1 | 2022-02-08T20:10:10.000Z | 2022-02-08T20:10:10.000Z | Geant4/include/NDDRunAction.hh | leenderthayen/NDP | ffc16ccff47da53326e9a83f98b675d5db24bc59 | [
"MIT"
] | null | null | null | Geant4/include/NDDRunAction.hh | leenderthayen/NDP | ffc16ccff47da53326e9a83f98b675d5db24bc59 | [
"MIT"
] | 2 | 2021-01-11T20:44:30.000Z | 2021-06-02T17:27:43.000Z | //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
#ifndef NDDRunAction_h
#define NDDRunAction_h 1
#include "G4UserRunAction.hh"
#include "G4String.hh"
//class NDDRunMessenger;
class NDDAnalysisManager;
class G4Run;
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
class NDDRunAction : public G4UserRunAction {
public:
NDDRunAction(NDDAnalysisManager*);
virtual ~NDDRunAction();
public:
virtual void BeginOfRunAction(const G4Run*);
virtual void EndOfRunAction(const G4Run*);
private:
//NDDRunMessenger* runMessenger;
NDDAnalysisManager* analysisManager;
};
#endif
| 23.548387 | 80 | 0.69863 | leenderthayen |
de87008313d0f53b1e0ea3dabdd0a6baef8d04f2 | 12,977 | hpp | C++ | wax/hala_noengine_structs.hpp | LIBHALA/hala | ff3950aef18b6cede48b45669be275b174f362a5 | [
"BSD-3-Clause"
] | 1 | 2021-02-25T16:21:42.000Z | 2021-02-25T16:21:42.000Z | wax/hala_noengine_structs.hpp | mkstoyanov/hala | ff3950aef18b6cede48b45669be275b174f362a5 | [
"BSD-3-Clause"
] | 9 | 2020-09-03T23:31:22.000Z | 2020-10-21T23:40:11.000Z | wax/hala_noengine_structs.hpp | mkstoyanov/hala | ff3950aef18b6cede48b45669be275b174f362a5 | [
"BSD-3-Clause"
] | 2 | 2020-03-03T17:39:37.000Z | 2020-11-05T16:01:28.000Z | #ifndef __HALA_NOENGINE_STRUCTS_HPP
#define __HALA_NOENGINE_STRUCTS_HPP
/*
* Code Author: Miroslav Stoyanov
*
* Copyright (C) 2018 Miroslav Stoyanov
*
* This file is part of
* Hardware Accelerated Linear Algebra (HALA)
*
*/
#include "hala_sparse_extensions.hpp"
namespace hala{
/*!
* \internal
* \file hala_noengine_structs.hpp
* \ingroup HALAWAXENGINED
* \brief Wrappers that use engined vectors and bypass carrying the engine to each call.
* \author Miroslav Stoyanov
* \copyright BSD-3-Clause
*
* \endinternal
*/
/*!
* \ingroup HALAWAXEXT
* \addtogroup HALAWAXENGINED Engined vectors
*
* Writing a generalized template while carrying the engine variable to each call
* can get repetitive and tedious. HALA offers an engined-vector overload that
* binds an engine and a vector using either owning or non-owning references so that the binded pair
* can be used in hala calls without the need to explicitly carry the engine object.
*/
/*!
* \internal
* \ingroup HALAWAXENGINED
* \brief If the class \b a is one of the engines, the struct defaults to std::true_type and std::false_type otherwise.
*
* \endinternal
*/
template<class a> struct is_engine{
//! \brief Set to true or false if the engine type is one of the compatible engine types.
#ifdef HALA_ENABLE_GPU
static const bool value = std::is_same<a, cpu_engine>::value || std::is_same<a, gpu_engine>::value || std::is_same<a, mixed_engine>::value;
#else
static const bool value = std::is_same<a, cpu_engine>::value;
#endif
};
/*!
* \internal
* \ingroup HALAWAXENGINED
* \brief Defines the types of the vector and the internal variable of the hala::engined_vector.
*
* Allows for switching between owning and non-owning modes with specialization to this struct.
* The owning mode (when \b vec is not a reference) this will assume both the internal variable
* and the returned variables as the vector itself, i.e., this is an identity template.
* In non-owning mode (when \b vec is a reference) this will use a reference wrapper for
* the internal variable and will strip away the reference for the return types.
* \endinternal
*/
template<class vec, typename = void> struct engined_vector_binding{
//! \brief The type of the internal variable used in the engined_vector class.
using variable = vec;
//! \brief The type of the returned variable used in the engined_vector class.
using type = vec;
};
#ifndef __HALA_DOXYGEN_SKIP
template<class vec> struct engined_vector_binding<vec, std::enable_if_t<std::is_reference<vec>::value>>{
using variable = std::reference_wrapper<std::remove_reference_t<vec>>;
using type = std::remove_reference_t<vec>;
};
#endif
/*!
* \internal
* \ingroup HALAWAXENGINED
* \brief Allows the distinction between a vector and reference-wrapper to a vector, either way returns a reference to the vector.
*
* \endinternal
*/
template<class vec> vec& get_vec(vec &x){ return x; }
/*!
* \internal
* \ingroup HALAWAXENGINED
* \brief Allows the distinction between a vector and reference-wrapper to a vector, either way returns a reference to the vector.
*
* \endinternal
*/
template<class vec> vec& get_vec(std::reference_wrapper<vec> &x){ return x.get(); }
/*!
* \ingroup HALAWAXENGINED
* \brief A struct that binds an engine and a vector so both can be carried in one context.
*
* The purpose of the construct is to create a new entity that carries both a vector and
* an engine in one context. That way long algorithms do not have to constantly repeat
* the engine variable into each call to HALA. Instead the engine will be bounded to
* all input/output vectors and be carried out through the computations.
*
* Do not call the constructor directly, use the factory methods hala::bind_engine_vector
* and hala::new_vector.
*
* \internal
* The owning vs. non-owning mode is determined by the type \b vec, which must be either
* a vector like (owning) or reference to a vector-like (non-owning).
* The factory methods take care of the distinction depending whether calling
* hala::bind_engine_vector or hala::new_vector.
* \endinternal
*
* For example:
* \code
* template<class VectorLikeA, class VectorLikeB, , class VectorLikeX>
* void advanced_solver(VectorLikeA const &A, VectorLikeB const &b, VectorLikeX &x){
* auto t = hala::new_vector(x);
* hala::vcopy(x, t);
* hala::axpy(-1.0, b, x);
* // ...
* // imagine many more HALA calls used to solve Ax = b
* // ...
* }
* \endcode
* The advanced solver works by default on the CPU, but what if we want to perform the solve
* on the GPU. If we use the engine mechanics, we would have to add another variable to
* the template indicating the engine type and then pass the variable to every HALA call:
* \code
* ...
* auto t = hala::new_vector(engine, x);
* hala::vcopy(engine, x, t);
* ...
* \endcode
* If the advanced solver has many lines of code, the above will change a lot of code
* and can easily lead to an error if one of the calls misses the engine.
* In contrast, the hala::engined_vector allows to instantiate the solver with the GPU backend
* and without making any changes to the solver code:
* \code
* template<class cengine, class VectorLikeA, class VectorLikeB, , class VectorLikeX>
* void advanced_solver(cengine const&engine, VectorLikeA const &A, VectorLikeB const &b, VectorLikeX &x){
* auto bindA = hala::bind_engine_vector(engine, A);
* auto bindb = hala::bind_engine_vector(engine, b);
* auto bindx = hala::bind_engine_vector(engine, x);
* advanced_solver(bindA, bindb, bindx);
* }
* \endcode
* The above small piece of code will overload the advanced solver and allow for calls with any engine type
* while making no changes to the solver itself.
*/
template<class cengine, class vec>
struct engined_vector{
//! \brief The type of the vector used in the binding, removes any reference qualifies but leaves const.
using vtype = typename engined_vector_binding<vec>::type;
//! \brief Defines the scalar type of the underlying vector, mostly used for the precision of the stopping criteria.
using value_type = get_standard_type<vtype>;
//! \brief Reference to the engine, it is recommended to use the engine() method in place of direct access.
std::reference_wrapper<cengine const> e;
//! \brief Either owning a vector variable or non-owning reference to a vector variable.
typename engined_vector_binding<vec>::variable v;
//! \brief Initialize the engined_vector with non-owning references to the engine and \b x.
engined_vector(cengine const &engine, vtype &x) : e(engine), v(x){
static_assert(is_engine<cpu_engine>::value, "engined_vector constructed with cengine that is not an engine");
static_assert(std::is_reference<vec>::value, "engined_vector cannot take a reference in non-referenced mode, instantiate with vec& instead");
}
//! \brief Initialize the engined_vector with ownership to an internal vector.
engined_vector(cengine const &engine) : e(engine), v(new_vector(engine, v)){
static_assert(is_engine<cpu_engine>::value, "engined_vector constructed with cengine that is not an engine");
static_assert(!std::is_reference<vec>::value, "engined_vector in non-owning mode must be initialized with the vector (use the other constructor)");
}
/*!
* \brief Returns \b true if the other engined_vector has a compatible engine.
*
* Engines are compatible if
* -# they have the same type, e.g., both cpu_engine
* -# if using hala::gpu_engine or hala::mixed_engine, then the device ids of the engines should also match.
*
* Overloads are provided to handle all possible pairs of engine types.
*/
template<class oengine, class vec2>
bool engine_match(engined_vector<oengine, vec2> const &) const{ return false; }
#ifndef __HALA_DOXYGEN_SKIP
template<class vec2, class ce = cengine>
std::enable_if_t<std::is_same<ce, cpu_engine>::value, bool>
engine_match(engined_vector<cengine, vec2> const &) const{
return true;
}
#ifdef HALA_ENABLE_GPU
template<class vec2, class ce = cengine>
std::enable_if_t<std::is_same<ce, gpu_engine>::value, bool>
engine_match(engined_vector<cengine, vec2> const &other) const{
return (engine().device() == other.engine().device());
}
template<class vec2, class ce = cengine>
std::enable_if_t<std::is_same<ce, mixed_engine>::value, bool>
engine_match(engined_vector<cengine, vec2> const &other) const{
return (engine().gpu().device() == other.engine().gpu().device());
}
#endif
#endif
//! \brief Return a reference to the engine.
cengine const& engine() const{ return e.get(); }
//! \brief Return a const reference to the vector.
vtype const& vector() const{ return get_vec(v); }
//! \brief Return a reference to the vector.
vtype& vector(){ return get_vec(v); }
//! \brief Returns the size of the vector.
size_t size() const{ return get_size(vector()); }
//! \brief Resizes the vector.
void resize(size_t new_size){ set_size(new_size, vector()); }
};
/*!
* \internal
* \ingroup HALAWAXENGINED
* \brief Runs a sanity check whether the classes have the same engine.
*
* Checks the engine type and the GPU device id.
* There is a variadric overload to check multiple vectors.
* \endinternal
*/
template<class ev1, class ev2>
bool check_engines(ev1 const &x, ev2 const &y){ return x.engine_match(y); }
#ifndef __HALA_DOXYGEN_SKIP
template<class ev1, class ev2, class ev3, class... evs>
bool check_engines(ev1 const &x, ev2 const &y, ev3 const &z, evs const&... more){
if (!check_engines(x, y)) return false;
return check_engines(y, z, more...);
}
#endif
/*!
* \ingroup HALAWAXENGINED
* \brief Creates a bind between the engine and the vector.
*
* Factory method to construct a bind between the vector and the engine.
*
* Overloads:
* \code
* auto x1 = bind_engine_vector(engine, x);
* auto y1 = bind_engine_vector(engined_vector, y);
* auto z1 = bind_engine_vector(vector, z);
* \endcode
* Overloads are provided for all engine types (case x1), the engine reference can be taken from an existing
* hala::engined_vector, or the call can be made with a generic vector-like class in which case
* z1 will be just a reference to z for calls that do not use binded engines.
*/
template<class cengine, class vec>
std::enable_if_t<is_engine<cengine>::value, engined_vector<cengine, vec&>> bind_engine_vector(cengine const &e, vec &x){
return engined_vector<cengine, vec&>(e, x);
}
/*!
* \ingroup HALAWAXENGINED
* \brief Returns the engine associated with the vector.
*
* The method is an easy way to obtain the engine from the engined vector,
* and the method is overloaded for general vector-like classes to return an instance of the cpu_engine.
*
* \b Note: do not use this to differentiate between GPU and CPU vectors,
* i.e., this will return hala::cpu_engine even if \b vec is hala::cuda_vector.
* The intended use is within the no-engine context where
* an engined_vector and a CPU vectors are the only acceptable inputs.
*/
template<class cengine, class vec>
auto get_engine(engined_vector<cengine, vec> const &x){ return x.engine(); }
#ifndef __HALA_DOXYGEN_SKIP // tell Doxygen to skip this section (overloads are documented with the main methods)
template<class vec>
auto get_engine(vec const &){ return cpu_engine(); }
template<class cengine, class vec>
auto new_vector(engined_vector<cengine, vec> const &x){
return engined_vector<cengine, get_vdefault<cengine, typename engined_vector<cengine, vec>::vtype>>(x.engine());
}
template<class cengine, class vec>
void set_zero(size_t num_entries, engined_vector<cengine, vec> &x){
set_zero(x.engine(), num_entries, x.vector());
}
template<class cengine, class vec>
void set_size(size_t num_entries, engined_vector<cengine, vec> &x){
set_size(num_entries, x.vector());
}
template<class vec>
auto new_vector(vec const &x){
return new_vector(cpu_engine(), x);
}
template<class cengine, class vec>
std::enable_if_t<is_engine<cengine>::value, engined_vector<cengine, vec const&>> bind_engine_vector(cengine const &e, vec const &x){
return engined_vector<cengine, vec const&>(e, x);
}
template<class cvec, class vec> std::enable_if_t<!is_engine<cvec>::value, vec&> bind_engine_vector(cvec const &, vec &x){ return x; }
template<class cvec, class vec> std::enable_if_t<!is_engine<cvec>::value, vec const&> bind_engine_vector(cvec const &, vec const &x){ return x; }
template<class cengine, class cvec, class vec>
auto bind_engine_vector(engined_vector<cengine, cvec> const &s, vec &x){ return bind_engine_vector(s.engine(), x); }
#endif
}
#include "hala_noengine_overloads.hpp"
#undef __HALA_NOENGINE_OVERLOADS_HPP
#include "hala_noengine_overloads.hpp"
#endif
| 40.301242 | 155 | 0.720968 | LIBHALA |
de87394e6105d98162a80b0871c3279630f002c7 | 1,907 | cpp | C++ | StringToInt.cpp | vibiu/SwordOfOffer | 6daa7d108a4f043353d372e835a1f8923c933dcc | [
"BSD-3-Clause"
] | 1 | 2020-05-14T13:59:11.000Z | 2020-05-14T13:59:11.000Z | StringToInt.cpp | vibiu/SwordOfOffer | 6daa7d108a4f043353d372e835a1f8923c933dcc | [
"BSD-3-Clause"
] | null | null | null | StringToInt.cpp | vibiu/SwordOfOffer | 6daa7d108a4f043353d372e835a1f8923c933dcc | [
"BSD-3-Clause"
] | null | null | null | #include "StringToInt.h"
#include <cstdio>
int g_nStatus = kValid;
long long StrToIntCore(const char *digit, bool minus)
{
long long num = 0;
while (*digit != '\0')
{
if (*digit >= '0' && *digit <= '9')
{
int flag = minus ? -1 : 1;
num = num * 10 + flag * (*digit - '0');
if ((!minus && num > 0x7FFFFFFF) || (minus && num < (signed int)0x80000000))
{
num = 0;
break;
}
digit++;
}
else
{
num = 0;
break;
}
}
if (*digit == '\0')
g_nStatus = kValid;
return num;
}
int StrToInt(const char *str)
{
g_nStatus = kInvalid;
long long num = 0;
if (str != nullptr && *str != '\0')
{
bool minus = false;
if (*str == '+')
str++;
else if (*str == '-')
{
str++;
minus = true;
}
if (*str != '\0')
num = StrToIntCore(str, minus);
}
return (int)num;
}
void StringToIntTest(const char *string)
{
int result = StrToInt(string);
if (result == 0 && g_nStatus == kInvalid)
printf("the input %s is invalid.\n", string);
else
printf("number for %s is: %d.\n", string, result);
}
void StringToIntTest1()
{
StringToIntTest(nullptr);
StringToIntTest("");
StringToIntTest("123");
StringToIntTest("+123");
StringToIntTest("-123");
StringToIntTest("1a33");
StringToIntTest("+0");
StringToIntTest("-0");
//有效的最大正整数, 0x7FFFFFFF
StringToIntTest("+2147483647");
StringToIntTest("-2147483647");
StringToIntTest("+2147483648");
//有效的最小负整数, 0x80000000
StringToIntTest("-2147483648");
StringToIntTest("+2147483649");
StringToIntTest("-2147483649");
StringToIntTest("+");
StringToIntTest("-");
}
| 18.881188 | 88 | 0.497116 | vibiu |
de89cab261393b40c494907099628b1cfd1e4f51 | 7,456 | cpp | C++ | testapp/scenes/physics/shakescene.cpp | ColinGilbert/d-collide | 8adb354d52e7ee49705ca2853d50a6a879f3cd49 | [
"BSD-3-Clause"
] | 6 | 2015-12-08T05:38:03.000Z | 2021-04-09T13:45:59.000Z | testapp/scenes/physics/shakescene.cpp | ColinGilbert/d-collide | 8adb354d52e7ee49705ca2853d50a6a879f3cd49 | [
"BSD-3-Clause"
] | null | null | null | testapp/scenes/physics/shakescene.cpp | ColinGilbert/d-collide | 8adb354d52e7ee49705ca2853d50a6a879f3cd49 | [
"BSD-3-Clause"
] | null | null | null | /*******************************************************************************
* Copyright (C) 2007 by the members of PG 510, University of Dortmund: *
* [email protected] *
*
* Andreas Beckermann, Christian Bode, Marcel Ens, Sebastian Ens, *
* Martin Fassbach, Maximilian Hegele, Daniel Haus, Oliver Horst, *
* Gregor Jochmann, Timo Loist, Marcel Nienhaus and Marc Schulz *
* *
* 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 the PG510 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 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 *
*******************************************************************************/
#include "shakescene.h"
#include "dcollide-config_testapp.h"
#include "myobjectnode.h"
#include "debug.h"
#include "Ogre.h"
#include <world.h>
#include <shapes/shapes.h>
#include <worldcollisions.h>
#include <collisioninfo.h>
#include <proxyfactory.h>
#include <algorithm>
/*!
* Construct a new d-collide based scene object.
*
* The scene itself is not yet created, only the necessary data
* structures. Call \ref initializeScene to actually create a scene.
*
* \param root A pointer to the ogre root object. Ownership is NOT
* taken, the pointer will not be deleted by this class.
*/
ShakeScene::ShakeScene(Ogre::Root* root) : PhysicsSceneBase(root) {
mPhysicsSimStepsize = 0.03;
mLinearDampingFactor = 0.005;
mAngularDampingFactor = 0.005;
}
ShakeScene::~ShakeScene() {
}
dcollide::Vector3 ShakeScene::initialWorldDimension() const {
return dcollide::Vector3(2048.0, 2048.0, 2048.0);
}
/*!
* Setup the actual scene, i.e. add objects to the \ref dcollide::World
* object.
*
* \return TRUE on success, otherwise FALSE.
*/
bool ShakeScene::initializeScene() {
dWorldSetGravity(mOdeWorld, 0,0,-10);
MyObjectNode* baseplate = new MyObjectNode( getCollisionWorld(),
new dcollide::Box(500,500, 20),
dcollide::PROXYTYPE_FIXED);
baseplate->translate(dcollide::Vector3(-250, -250, -20));
addTopLevelObject(baseplate);
/* z
* ^ -10 10 y
* 40 | +-----+ /
* | | |/
* | | |
* 20 | +-----+
* 20 | +---+ +---+
* | | | | |
* 0 | +---+ +---+
* +-----------------> x
* -21 -1,0,1 21
*/
MyObjectNode* underBox1 = new MyObjectNode(
getCollisionWorld(),new dcollide::Box(20,20,20), dcollide::PROXYTYPE_RIGID, true, false);
underBox1->setPosition(-29,0,0);
underBox1->createPhysicsBody(mOdeWorld,4);
addTopLevelObject(underBox1);
MyObjectNode* underBox2 = new MyObjectNode(
getCollisionWorld(),new dcollide::Box(20,20,20), dcollide::PROXYTYPE_RIGID, true, false);
underBox2->setPosition(9,0,0);
underBox2->createPhysicsBody(mOdeWorld,4);
addTopLevelObject(underBox2);
MyObjectNode* TopBox = new MyObjectNode(
getCollisionWorld(),new dcollide::Box(20,20,20), dcollide::PROXYTYPE_RIGID, true, false);
TopBox->setPosition(-10,0,20);
TopBox->createPhysicsBody(mOdeWorld,50);
addTopLevelObject(TopBox);
// create my own wall
/* z
* ^ +---+
* | | |
* | +---+
* | +---+ +---+
* | | | | |
* | +---+ +---+
* | +---+ +---+ +---+
* | | | | | | |
* | +---+ +---+ +---+
+ | +---+ +---+ +---+ +---+
* | | | | | | | | |
* | +---+ +---+ +---+ +---+
* | +---+ +---+ +---+ +---+ +---+
* | | | | | | | | | | |
* | +---+ +---+ +---+ +---+ +---+
* | +---+ +---+ +---+ +---+ +---+ +---+
* | | | | | | | | | | | | |
* | +---+ +---+ +---+ +---+ +---+ +---+
* +---------------------------------------> x
* -63,-43,-42,-22,-21,-1,0,1 21,22 42,43 63
* 2nd level: -31,-11,-10,10,11,31,32,52
*/
int baseBoxes = 10;
int boxWidth = 20;
int boxDistance = 15;
for (int row = 0; row<baseBoxes;row++){
for (int i=0; i<baseBoxes-row; i++){
MyObjectNode* box = new MyObjectNode( getCollisionWorld(),
new dcollide::Box(boxWidth,boxWidth,boxWidth),dcollide::PROXYTYPE_RIGID, true, false);
float nr = (baseBoxes-row)/2.0;
box->setPosition(-(nr*boxWidth+(nr-0.5)*boxDistance) + i*boxWidth+i*boxDistance, 100 , row*boxWidth );
box->createPhysicsBody(mOdeWorld, 2);
addTopLevelObject(box);
}
}
// Gregors Wall
dcollide::real wallDistance = -100;
int baseboxes = 8;
for (int row = 0; row<baseboxes;row++){
for (int i=0; i<baseboxes-row; i++){
MyObjectNode* box = new MyObjectNode( getCollisionWorld(),
new dcollide::Box(10,10, 10),
dcollide::PROXYTYPE_RIGID, true, false);
box->setPosition(-50 + (row * 15)/2 + i * 13, wallDistance , row*10);
box->createPhysicsBody(mOdeWorld, 4);
addTopLevelObject(box);
}
}
return true;
}
void ShakeScene::startNextSceneFrame() {
}
std::string ShakeScene::getSceneDescription() const {
return "One physikbody on top of two other. Why is it shaking?";
}
/*
* vim: et sw=4 ts=4
*/
| 39.659574 | 114 | 0.51301 | ColinGilbert |
de90eead59c3ab1260386bb28a3889c8ea14ee16 | 7,361 | hpp | C++ | include/System/Xml/Schema/AttributeMatchState.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/System/Xml/Schema/AttributeMatchState.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/System/Xml/Schema/AttributeMatchState.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | 1 | 2022-03-30T21:07:35.000Z | 2022-03-30T21:07:35.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.Enum
#include "System/Enum.hpp"
// Completed includes
// Type namespace: System.Xml.Schema
namespace System::Xml::Schema {
// Forward declaring type: AttributeMatchState
struct AttributeMatchState;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(::System::Xml::Schema::AttributeMatchState, "System.Xml.Schema", "AttributeMatchState");
// Type namespace: System.Xml.Schema
namespace System::Xml::Schema {
// Size: 0x4
#pragma pack(push, 1)
// Autogenerated type: System.Xml.Schema.AttributeMatchState
// [TokenAttribute] Offset: FFFFFFFF
struct AttributeMatchState/*, public ::System::Enum*/ {
public:
public:
// public System.Int32 value__
// Size: 0x4
// Offset: 0x0
int value;
// Field size check
static_assert(sizeof(int) == 0x4);
public:
// Creating value type constructor for type: AttributeMatchState
constexpr AttributeMatchState(int value_ = {}) noexcept : value{value_} {}
// Creating interface conversion operator: operator ::System::Enum
operator ::System::Enum() noexcept {
return *reinterpret_cast<::System::Enum*>(this);
}
// Creating conversion operator: operator int
constexpr operator int() const noexcept {
return value;
}
// static field const value: static public System.Xml.Schema.AttributeMatchState AttributeFound
static constexpr const int AttributeFound = 0;
// Get static field: static public System.Xml.Schema.AttributeMatchState AttributeFound
static ::System::Xml::Schema::AttributeMatchState _get_AttributeFound();
// Set static field: static public System.Xml.Schema.AttributeMatchState AttributeFound
static void _set_AttributeFound(::System::Xml::Schema::AttributeMatchState value);
// static field const value: static public System.Xml.Schema.AttributeMatchState AnyIdAttributeFound
static constexpr const int AnyIdAttributeFound = 1;
// Get static field: static public System.Xml.Schema.AttributeMatchState AnyIdAttributeFound
static ::System::Xml::Schema::AttributeMatchState _get_AnyIdAttributeFound();
// Set static field: static public System.Xml.Schema.AttributeMatchState AnyIdAttributeFound
static void _set_AnyIdAttributeFound(::System::Xml::Schema::AttributeMatchState value);
// static field const value: static public System.Xml.Schema.AttributeMatchState UndeclaredElementAndAttribute
static constexpr const int UndeclaredElementAndAttribute = 2;
// Get static field: static public System.Xml.Schema.AttributeMatchState UndeclaredElementAndAttribute
static ::System::Xml::Schema::AttributeMatchState _get_UndeclaredElementAndAttribute();
// Set static field: static public System.Xml.Schema.AttributeMatchState UndeclaredElementAndAttribute
static void _set_UndeclaredElementAndAttribute(::System::Xml::Schema::AttributeMatchState value);
// static field const value: static public System.Xml.Schema.AttributeMatchState UndeclaredAttribute
static constexpr const int UndeclaredAttribute = 3;
// Get static field: static public System.Xml.Schema.AttributeMatchState UndeclaredAttribute
static ::System::Xml::Schema::AttributeMatchState _get_UndeclaredAttribute();
// Set static field: static public System.Xml.Schema.AttributeMatchState UndeclaredAttribute
static void _set_UndeclaredAttribute(::System::Xml::Schema::AttributeMatchState value);
// static field const value: static public System.Xml.Schema.AttributeMatchState AnyAttributeLax
static constexpr const int AnyAttributeLax = 4;
// Get static field: static public System.Xml.Schema.AttributeMatchState AnyAttributeLax
static ::System::Xml::Schema::AttributeMatchState _get_AnyAttributeLax();
// Set static field: static public System.Xml.Schema.AttributeMatchState AnyAttributeLax
static void _set_AnyAttributeLax(::System::Xml::Schema::AttributeMatchState value);
// static field const value: static public System.Xml.Schema.AttributeMatchState AnyAttributeSkip
static constexpr const int AnyAttributeSkip = 5;
// Get static field: static public System.Xml.Schema.AttributeMatchState AnyAttributeSkip
static ::System::Xml::Schema::AttributeMatchState _get_AnyAttributeSkip();
// Set static field: static public System.Xml.Schema.AttributeMatchState AnyAttributeSkip
static void _set_AnyAttributeSkip(::System::Xml::Schema::AttributeMatchState value);
// static field const value: static public System.Xml.Schema.AttributeMatchState ProhibitedAnyAttribute
static constexpr const int ProhibitedAnyAttribute = 6;
// Get static field: static public System.Xml.Schema.AttributeMatchState ProhibitedAnyAttribute
static ::System::Xml::Schema::AttributeMatchState _get_ProhibitedAnyAttribute();
// Set static field: static public System.Xml.Schema.AttributeMatchState ProhibitedAnyAttribute
static void _set_ProhibitedAnyAttribute(::System::Xml::Schema::AttributeMatchState value);
// static field const value: static public System.Xml.Schema.AttributeMatchState ProhibitedAttribute
static constexpr const int ProhibitedAttribute = 7;
// Get static field: static public System.Xml.Schema.AttributeMatchState ProhibitedAttribute
static ::System::Xml::Schema::AttributeMatchState _get_ProhibitedAttribute();
// Set static field: static public System.Xml.Schema.AttributeMatchState ProhibitedAttribute
static void _set_ProhibitedAttribute(::System::Xml::Schema::AttributeMatchState value);
// static field const value: static public System.Xml.Schema.AttributeMatchState AttributeNameMismatch
static constexpr const int AttributeNameMismatch = 8;
// Get static field: static public System.Xml.Schema.AttributeMatchState AttributeNameMismatch
static ::System::Xml::Schema::AttributeMatchState _get_AttributeNameMismatch();
// Set static field: static public System.Xml.Schema.AttributeMatchState AttributeNameMismatch
static void _set_AttributeNameMismatch(::System::Xml::Schema::AttributeMatchState value);
// static field const value: static public System.Xml.Schema.AttributeMatchState ValidateAttributeInvalidCall
static constexpr const int ValidateAttributeInvalidCall = 9;
// Get static field: static public System.Xml.Schema.AttributeMatchState ValidateAttributeInvalidCall
static ::System::Xml::Schema::AttributeMatchState _get_ValidateAttributeInvalidCall();
// Set static field: static public System.Xml.Schema.AttributeMatchState ValidateAttributeInvalidCall
static void _set_ValidateAttributeInvalidCall(::System::Xml::Schema::AttributeMatchState value);
// Get instance field reference: public System.Int32 value__
[[deprecated("Use field access instead!")]] int& dyn_value__();
}; // System.Xml.Schema.AttributeMatchState
#pragma pack(pop)
static check_size<sizeof(AttributeMatchState), 0 + sizeof(int)> __System_Xml_Schema_AttributeMatchStateSizeCheck;
static_assert(sizeof(AttributeMatchState) == 0x4);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
| 65.723214 | 115 | 0.776253 | v0idp |
de944d3eea1531b4035a9ddc0c78c0761e00f7bd | 8,890 | cpp | C++ | QuadGeom.cpp | cleak/VoxelPerf | 02dad67747b113a3cd38cae6a2c307f877cab068 | [
"MIT"
] | 42 | 2017-07-30T17:50:16.000Z | 2022-03-27T09:27:04.000Z | QuadGeom.cpp | cleak/VoxelPerf | 02dad67747b113a3cd38cae6a2c307f877cab068 | [
"MIT"
] | 1 | 2019-03-13T07:09:44.000Z | 2019-03-15T07:02:23.000Z | QuadGeom.cpp | cleak/VoxelPerf | 02dad67747b113a3cd38cae6a2c307f877cab068 | [
"MIT"
] | 3 | 2018-05-10T20:38:29.000Z | 2020-06-21T21:12:39.000Z | #include "QuadGeom.h"
#include <iostream>
#include <cstddef>
#include <vector>
using namespace glm;
using namespace std;
#pragma pack(push, 1)
struct PointQuad {
//vec3 position;
uint8_t x;
uint8_t y;
uint8_t z;
//uint8_t pad0;
//PackedColor color;
uint8_t r;
uint8_t g;
uint8_t b;
uint8_t faceIdx;
};
#pragma pack(pop)
// Stores information about the location and size of each set of layers of a voxel object
struct LayersInfo {
uint16_t layerStartIdx[6];
uint16_t layerSize[6];
};
struct LayeredVertexBuffer {
int nextLayerIdx[6] = {};
vector<PointQuad> layer[6] = {};
};
int FloatToPackedInt(float f) {
if (f == 1.0f) {
return 511;
}
if (f == -1.0f) {
return -512;
}
return 0;
}
PackedVec PackVec(vec3 v) {
PackedVec p;
p.w = 0;
p.x = FloatToPackedInt(v.x);
p.y = FloatToPackedInt(v.y);
p.z = FloatToPackedInt(v.z);
return p;
}
uint8_t RoundColor(float c) {
return (uint8_t)round(c * 0xff);
}
void BufferPointQuadFace(ivec3 voxIdx, ivec3 normal, vec3 color, vector<PointQuad>& vertices, int& nextIdx,
uint8_t faceIdx) {
if (normal.x > 0 || normal.y > 0 || normal.z > 0) {
voxIdx += normal;
}
PointQuad p;
p.r = RoundColor(color.r);
p.g = RoundColor(color.g);
p.b = RoundColor(color.b);
p.x = voxIdx.x;
p.y = voxIdx.y;
p.z = voxIdx.z;
p.faceIdx = faceIdx;
if (nextIdx >= vertices.size()) {
vertices.push_back(p);
} else {
vertices[nextIdx] = p;
}
nextIdx++;
}
// Buffers all faces of a voxel in the given vector
void BufferPointQuadVoxel(VoxelSet& voxels, vec3 offset, ivec3 idx, LayeredVertexBuffer& vertexBuffers) {
if (!voxels.IsSolid(idx)) {
return;
}
vec3 color = voxels.At(idx);
vector<ivec3> normals = {
{ 1, 0, 0 },
{-1, 0, 0 },
{ 0, 1, 0 },
{ 0,-1, 0 },
{ 0, 0, 1 },
{ 0, 0,-1 },
};
PointQuad p;
int enabledFaces = 0;
for (int i = 0; i < normals.size(); ++i) {
if (voxels.IsSolid(idx + normals[i])) {
continue;
}
BufferPointQuadFace(idx, normals[i], color, vertexBuffers.layer[i], vertexBuffers.nextLayerIdx[i], (uint8_t)i);
}
}
// Buffers an entire voxel model in the given vector
void BufferVoxelSetPointQuads(VoxelSet& voxels, vec3 offset, LayeredVertexBuffer& vertexBuffers) {
for (int i = 0; i < 6; ++i) {
vertexBuffers.nextLayerIdx[i] = 0;
}
for (int z = 0; z < voxels.size.z; ++z) {
for (int y = 0; y < voxels.size.y; ++y) {
for (int x = 0; x < voxels.size.x; ++x) {
BufferPointQuadVoxel(voxels, offset, ivec3(x, y, z), vertexBuffers);
}
}
}
}
void MakeGridPointQuads(VoxelSet& model, ivec3 dimensions, vec3 spacing, std::vector<GLuint>& vaos,
std::vector<GLuint>& vbos, std::vector<LayersInfo>& layersInfo, GLuint program) {
size_t modelCount = dimensions.x * dimensions.y * dimensions.z;
vbos.resize(modelCount);
vaos.resize(modelCount);
layersInfo.resize(modelCount);
glGenBuffers(vbos.size(), &vbos[0]);
CheckGLErrors();
glGenVertexArrays(vaos.size(), &vaos[0]);
CheckGLErrors();
int nextVbo = 0;
LayeredVertexBuffer vertexBuffers;
for (int z = 0; z < dimensions.z; ++z) {
for (int y = 0; y < dimensions.y; ++y) {
for (int x = 0; x < dimensions.x; ++x) {
ivec3 idx(x, y, z);
vec3 offset = vec3(idx) * spacing;
offset -= vec3(0, dimensions.y, 0) * spacing / 2.0f;
BufferVoxelSetPointQuads(model, offset, vertexBuffers);
glBindVertexArray(vaos[nextVbo]);
glBindBuffer(GL_ARRAY_BUFFER, vbos[nextVbo]);
int totalQuads = 0;
for (int i = 0; i < 6; ++i) {
totalQuads += vertexBuffers.layer[i].size();
}
glBufferData(GL_ARRAY_BUFFER, sizeof(PointQuad) * totalQuads, nullptr, GL_STATIC_DRAW);
layersInfo[nextVbo].layerStartIdx[0] = 0;
for (int i = 0; i < 6; ++i) {
layersInfo[nextVbo].layerSize[i] = vertexBuffers.layer[i].size();
if (i > 0) {
layersInfo[nextVbo].layerStartIdx[i] = layersInfo[nextVbo].layerStartIdx[i - 1] + layersInfo[nextVbo].layerSize[i];
}
glBufferSubData(GL_ARRAY_BUFFER, layersInfo[nextVbo].layerStartIdx[i] * sizeof(PointQuad),
layersInfo[nextVbo].layerSize[i] * sizeof(PointQuad), &vertexBuffers.layer[i][0]);
}
GLint vPosLoc = glGetAttribLocation(program, "vPos");
glEnableVertexAttribArray(vPosLoc);
glVertexAttribPointer(vPosLoc, 3, GL_BYTE, GL_FALSE,
sizeof(PointQuad),
(void*)offsetof(PointQuad, x));
CheckGLErrors();
GLint vColorPos = glGetAttribLocation(program, "vColor");
glEnableVertexAttribArray(vColorPos);
glVertexAttribPointer(vColorPos, 3, GL_UNSIGNED_BYTE, GL_TRUE,
sizeof(PointQuad),
(void*)offsetof(PointQuad, r));
CheckGLErrors();
GLint vExtent1 = glGetAttribLocation(program, "vFaceIdx");
glEnableVertexAttribArray(vExtent1);
glVertexAttribIPointer(vExtent1, 1, GL_BYTE,
sizeof(PointQuad),
(void*)offsetof(PointQuad, faceIdx));
CheckGLErrors();
nextVbo++;
}
}
}
}
PerfRecord RunQuadGeometryShaderTest(VoxelSet & model, glm::ivec3 gridSize, glm::vec3 voxelSpacing) {
GLuint program;
GLint mvpLoc;
GLint offsetLoc;
vector<GLuint> vaos;
vector<GLuint> vbos;
vector<vec3> offsets;
std::vector<LayersInfo> layersInfo;
vector<ivec3> normals = {
{ 1, 0, 0 },
{ -1, 0, 0 },
{ 0, 1, 0 },
{ 0,-1, 0 },
{ 0, 0, 1 },
{ 0, 0,-1 },
};
PerfRecord record = RunPerf(
[&]() {
// Setup
program = MakeShaderProgram({
{ "Shaders/point_quads.vert", GL_VERTEX_SHADER },
{ "Shaders/point_voxels.frag", GL_FRAGMENT_SHADER },
{ "Shaders/point_quads.geom", GL_GEOMETRY_SHADER },
});
mvpLoc = glGetUniformLocation(program, "mvp");
offsetLoc = glGetUniformLocation(program, "vOffset");
MakeGridPointQuads(model, gridSize, voxelSpacing, vaos, vbos, layersInfo, program);
offsets.resize(vaos.size());
int nextOffsetIdx = 0;
for (int z = 0; z < gridSize.z; ++z) {
for (int y = 0; y < gridSize.y; ++y) {
for (int x = 0; x < gridSize.x; ++x) {
ivec3 idx(x, y, z);
vec3 offset = vec3(idx) * voxelSpacing;
offset -= vec3(0, gridSize.y, 0) * voxelSpacing / 2.0f;
offsets[nextOffsetIdx] = offset;
nextOffsetIdx++;
}
}
}
},
[&]() {
// Draw
mat4 mvp = MakeMvp();
//PrintMatrix(mvp);
glUseProgram(program);
glUniformMatrix4fv(mvpLoc, 1, GL_FALSE, (const GLfloat*)&mvp);
for (int i = 0; i < vaos.size(); ++i) {
vec3 offset = offsets[i];
glUniform3fv(offsetLoc, 1, (const GLfloat*)&offset);
glBindVertexArray(vaos[i]);
for (int j = 0; j < 6; ++j) {
// Kludge to iterate over x twice, y twice, and z twice
int compareIdx = j / 2;
// Visibility threshold along a particular axis
float thresh = offset[compareIdx] + voxelSpacing[compareIdx] / 2.0f;
// Direction of normal (used for deciding how to compare)
float normalDir = normals[j][compareIdx];
thresh += normalDir * voxelSpacing[compareIdx] / 2.0f;
// Cull layers that are entirely backfacing
if (normalDir * thresh > normalDir * CameraPosition()[compareIdx]) {
continue;
}
glDrawArrays(GL_POINTS, layersInfo[i].layerStartIdx[j], layersInfo[i].layerSize[j]);
}
}
},
[&]() {
// Teardown
glDeleteBuffers(vbos.size(), &vbos[0]);
CheckGLErrors();
glDeleteVertexArrays(vaos.size(), &vaos[0]);
CheckGLErrors();
glDeleteProgram(program);
CheckGLErrors();
});
return record;
}
| 28.49359 | 139 | 0.534196 | cleak |
de95e3bdaf5dec6a0c3ab2e703b95a35ed6c046e | 9,055 | hpp | C++ | include/lug/Math/Matrix.hpp | Lugdunum3D/Lugdunum3D | b6d6907d034fdba1ffc278b96598eba1d860f0d4 | [
"MIT"
] | 275 | 2016-10-08T15:33:17.000Z | 2022-03-30T06:11:56.000Z | include/lug/Math/Matrix.hpp | Lugdunum3D/Lugdunum3D | b6d6907d034fdba1ffc278b96598eba1d860f0d4 | [
"MIT"
] | 24 | 2016-09-29T20:51:20.000Z | 2018-05-09T21:41:36.000Z | include/lug/Math/Matrix.hpp | Lugdunum3D/Lugdunum3D | b6d6907d034fdba1ffc278b96598eba1d860f0d4 | [
"MIT"
] | 37 | 2017-02-25T05:03:48.000Z | 2021-05-10T19:06:29.000Z | #pragma once
#include <cstdint>
#include <valarray>
#include <lug/Math/Export.hpp>
#include <lug/Math/ValArray.hpp>
#include <lug/System/Debug.hpp>
namespace lug {
namespace Math {
template <uint8_t Rows, uint8_t Columns, typename T = float>
class Matrix {
public:
// TODO: Use custom valarray with compile time size
using Values = ValArray<Rows * Columns, T>;
public:
constexpr Matrix() = default;
explicit Matrix(T value);
Matrix(const Values& values);
Matrix(std::initializer_list<T> list);
Matrix(const Matrix<Rows, Columns, T>& matrix) = default;
Matrix(Matrix<Rows, Columns, T>&& matrix) = default;
Matrix<Rows, Columns, T>& operator=(const Matrix<Rows, Columns, T>& rhs) = default;
Matrix<Rows, Columns, T>& operator=(Matrix<Rows, Columns, T>&& rhs) = default;
~Matrix() = default;
constexpr uint8_t getRows() const;
constexpr uint8_t getColumns() const;
Values& getValues();
constexpr const Values& getValues() const;
T& operator()(uint8_t row, uint8_t col = 0);
constexpr const T& operator()(uint8_t row, uint8_t col = 0) const;
// Matrix/Scalar operations
Matrix<Rows, Columns, T>& operator+=(T rhs);
Matrix<Rows, Columns, T>& operator-=(T rhs);
Matrix<Rows, Columns, T>& operator*=(T rhs);
Matrix<Rows, Columns, T>& operator/=(T rhs);
// Matrix/Matrix operations
Matrix<Rows, Columns, T>& operator+=(const Matrix<Rows, Columns, T>& rhs);
Matrix<Rows, Columns, T>& operator-=(const Matrix<Rows, Columns, T>& rhs);
#if defined(LUG_COMPILER_MSVC)
template <typename = typename std::enable_if<(Rows == Columns)>::type>
Matrix<Rows, Columns, T>& operator*=(const Matrix<Rows, Columns, T>& rhs);
template <typename = typename std::enable_if<(Rows == Columns)>::type>
Matrix<Rows, Columns, T>& operator/=(const Matrix<Rows, Columns, T>& rhs);
#else
template <bool EnableBool = true>
typename std::enable_if<(Rows == Columns) && EnableBool, Matrix<Rows, Columns, T>>::type& operator*=(const Matrix<Rows, Columns, T>& rhs);
template <bool EnableBool = true>
typename std::enable_if<(Rows == Columns) && EnableBool, Matrix<Rows, Columns, T>>::type& operator/=(const Matrix<Rows, Columns, T>& rhs);
#endif
#if defined(LUG_COMPILER_MSVC)
template <typename = typename std::enable_if<(Rows == 1)>::type>
Matrix<Rows, Columns, T> inverse() const;
template <typename = typename std::enable_if<(Rows == 2)>::type, typename = void>
Matrix<Rows, Columns, T> inverse() const;
template <typename = typename std::enable_if<(Rows == 3)>::type, typename = void, typename = void>
Matrix<Rows, Columns, T> inverse() const;
template <typename = typename std::enable_if<(Rows == 4)>::type, typename = void, typename = void, typename = void>
Matrix<Rows, Columns, T> inverse() const;
#else
template <bool EnableBool = true>
typename std::enable_if<(Rows == 1) && EnableBool, Matrix<Rows, Columns, T>>::type inverse() const;
template <bool EnableBool = true>
typename std::enable_if<(Rows == 2) && EnableBool, Matrix<Rows, Columns, T>>::type inverse() const;
template <bool EnableBool = true>
typename std::enable_if<(Rows == 3) && EnableBool, Matrix<Rows, Columns, T>>::type inverse() const;
template <bool EnableBool = true>
typename std::enable_if<(Rows == 4) && EnableBool, Matrix<Rows, Columns, T>>::type inverse() const;
#endif
Matrix<Columns, Rows, T> transpose() const;
#if defined(LUG_COMPILER_MSVC)
template <typename = typename std::enable_if<(Rows == 1)>::type>
T det() const;
template <typename = typename std::enable_if<(Rows == 2)>::type, typename = void>
T det() const;
template <typename = typename std::enable_if<(Rows == 3)>::type, typename = void, typename = void>
T det() const;
template <typename = typename std::enable_if<(Rows == 4)>::type, typename = void, typename = void, typename = void>
T det() const;
template <typename = typename std::enable_if<(Rows > 4)>::type, typename = void, typename = void, typename = void, typename = void>
T det() const;
#else
template <bool EnableBool = true>
typename std::enable_if<(Rows == 1) && EnableBool, T>::type det() const;
template <bool EnableBool = true>
typename std::enable_if<(Rows == 2) && EnableBool, T>::type det() const;
template <bool EnableBool = true>
typename std::enable_if<(Rows == 3) && EnableBool, T>::type det() const;
template <bool EnableBool = true>
typename std::enable_if<(Rows == 4) && EnableBool, T>::type det() const;
template <bool EnableBool = true>
typename std::enable_if<(Rows > 4) && EnableBool, T>::type det() const;
#endif
#if defined(LUG_COMPILER_MSVC)
template <typename = typename std::enable_if<(Rows == Columns)>::type>
static Matrix<Rows, Columns, T> identity();
#else
template <bool EnableBool = true>
static typename std::enable_if<(Rows == Columns) && EnableBool, Matrix<Rows, Columns, T>>::type identity();
#endif
protected:
Values _values;
};
#define DEFINE_LENGTH_MATRIX(rows, columns) \
template <typename T = float> \
using Mat##rows##x##columns= Matrix<rows, columns, T>; \
\
template class LUG_MATH_API Matrix<rows, columns, float>; \
using Mat##rows##x##columns##f = Mat##rows##x##columns<float>; \
\
template class LUG_MATH_API Matrix<rows, columns, double>; \
using Mat##rows##x##columns##d = Mat##rows##x##columns<double>; \
\
template class LUG_MATH_API Matrix<rows, columns, int32_t>; \
using Mat##rows##x##columns##i = Mat##rows##x##columns<int32_t>; \
\
template class LUG_MATH_API Matrix<rows, columns, uint32_t>; \
using Mat##rows##x##columns##u = Mat##rows##x##columns<uint32_t>;
DEFINE_LENGTH_MATRIX(2, 2)
DEFINE_LENGTH_MATRIX(2, 3)
DEFINE_LENGTH_MATRIX(2, 4)
DEFINE_LENGTH_MATRIX(3, 2)
DEFINE_LENGTH_MATRIX(3, 3)
DEFINE_LENGTH_MATRIX(3, 4)
DEFINE_LENGTH_MATRIX(4, 2)
DEFINE_LENGTH_MATRIX(4, 3)
DEFINE_LENGTH_MATRIX(4, 4)
#undef DEFINE_LENGTH_MATRIX
// Unary operations
template <uint8_t Rows, uint8_t Columns, typename T>
Matrix<Rows, Columns, T> operator-(const Matrix<Rows, Columns, T>& lhs);
// Matrix/Scalar operations
template <uint8_t Rows, uint8_t Columns, typename T>
Matrix<Rows, Columns, T> operator+(const Matrix<Rows, Columns, T>& lhs, T rhs);
template <uint8_t Rows, uint8_t Columns, typename T>
Matrix<Rows, Columns, T> operator-(const Matrix<Rows, Columns, T>& lhs, T rhs);
template <uint8_t Rows, uint8_t Columns, typename T>
Matrix<Rows, Columns, T> operator*(const Matrix<Rows, Columns, T>& lhs, T rhs);
template <uint8_t Rows, uint8_t Columns, typename T>
Matrix<Rows, Columns, T> operator/(const Matrix<Rows, Columns, T>& lhs, T rhs);
template <uint8_t Rows, uint8_t Columns, typename T>
Matrix<Rows, Columns, T> operator+(T lhs, const Matrix<Rows, Columns, T>& rhs);
template <uint8_t Rows, uint8_t Columns, typename T>
Matrix<Rows, Columns, T> operator-(T lhs, const Matrix<Rows, Columns, T>& rhs);
template <uint8_t Rows, uint8_t Columns, typename T>
Matrix<Rows, Columns, T> operator*(T lhs, const Matrix<Rows, Columns, T>& rhs);
template <uint8_t Rows, uint8_t Columns, typename T>
Matrix<Rows, Columns, T> operator/(T lhs, const Matrix<Rows, Columns, T>& rhs);
// Matrix/Matrix operation
template <uint8_t Rows, uint8_t Columns, typename T>
Matrix<Rows, Columns, T> operator+(const Matrix<Rows, Columns, T>& lhs, const Matrix<Rows, Columns, T>& rhs);
template <uint8_t Rows, uint8_t Columns, typename T>
Matrix<Rows, Columns, T> operator-(const Matrix<Rows, Columns, T>& lhs, const Matrix<Rows, Columns, T>& rhs);
template <uint8_t RowsLeft, uint8_t ColumnsLeft, uint8_t RowsRight, uint8_t ColumnsRight, typename T>
Matrix<RowsLeft, ColumnsRight, T> operator*(const Matrix<RowsLeft, ColumnsLeft, T>& lhs, const Matrix<RowsRight, ColumnsRight, T>& rhs);
template <uint8_t RowsLeft, uint8_t ColumnsLeft, uint8_t RowsRight, uint8_t ColumnsRight, typename T>
Matrix<RowsLeft, ColumnsRight, T> operator/(const Matrix<RowsLeft, ColumnsLeft, T>& lhs, const Matrix<RowsRight, ColumnsRight, T>& rhs);
// Comparaison operators
template <uint8_t Rows, uint8_t Columns, typename T>
bool operator==(const Matrix<Rows, Columns, T>& lhs, const Matrix<Rows, Columns, T>& rhs);
template <uint8_t Rows, uint8_t Columns, typename T>
bool operator!=(const Matrix<Rows, Columns, T>& lhs, const Matrix<Rows, Columns, T>& rhs);
template <uint8_t Rows, uint8_t Columns, typename T>
std::ostream& operator<<(std::ostream& os, const Matrix<Rows, Columns, T>& matrix);
#include <lug/Math/Matrix.inl>
} // Math
} // lug
| 38.206751 | 142 | 0.660298 | Lugdunum3D |
de97a2e85933d99eecd9920b7cbf6585da61d37e | 469 | cpp | C++ | problems/acmicpc_1946.cpp | qawbecrdtey/BOJ-sol | e3f410e8f4e3a6ade51b68ce2024529870edac64 | [
"MIT"
] | null | null | null | problems/acmicpc_1946.cpp | qawbecrdtey/BOJ-sol | e3f410e8f4e3a6ade51b68ce2024529870edac64 | [
"MIT"
] | null | null | null | problems/acmicpc_1946.cpp | qawbecrdtey/BOJ-sol | e3f410e8f4e3a6ade51b68ce2024529870edac64 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <utility>
#include <algorithm>
using namespace std;
int main() {
int t;
scanf("%d", &t);
while(t--) {
int n;
scanf("%d", &n);
auto a = new pair<int, int>[n];
for(int i = 0; i < n; i++) {
scanf("%d%d", &a[i].first, &a[i].second);
}
sort(a, a + n);
int x = a[0].second;
int cnt = 1;
for(int i = 1; i < n; i++) {
if(a[i].second < x) {
cnt++;
x = a[i].second;
}
}
printf("%d\n", cnt);
delete[] a;
}
} | 17.37037 | 44 | 0.479744 | qawbecrdtey |
de9c61d6c8b97e1eac63891e58caadc4bb079554 | 6,422 | cpp | C++ | source/os/cmd_interface_win.cpp | inmoition-depthcamera/sdk | 11f4894295475f6adc896815878fbff9f49b4480 | [
"MIT"
] | 2 | 2018-12-03T03:46:08.000Z | 2020-05-24T04:02:39.000Z | source/os/cmd_interface_win.cpp | inmoition-depthcamera/sdk | 11f4894295475f6adc896815878fbff9f49b4480 | [
"MIT"
] | 1 | 2018-09-20T03:02:35.000Z | 2018-09-30T11:10:40.000Z | source/os/cmd_interface_win.cpp | inmoition-depthcamera/sdk | 11f4894295475f6adc896815878fbff9f49b4480 | [
"MIT"
] | null | null | null | #include "cmd_interface_win.h"
#include <cctype>
#include <algorithm>
#include <SetupAPI.h>
#include <Cfgmgr32.h>
#include "tchar.h"
#pragma comment(lib, "SetupAPI.lib")
#pragma comment(lib, "Cfgmgr32.lib")
#include "iostream"
using namespace std;
CmdInterfaceWin::CmdInterfaceWin()
{
mComHandle = INVALID_HANDLE_VALUE;
memset(&mOverlappedSend, 0, sizeof(OVERLAPPED));
memset(&mOverlappedRecv, 0, sizeof(OVERLAPPED));
mOverlappedSend.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
mOverlappedRecv.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
}
CmdInterfaceWin::~CmdInterfaceWin()
{
if (mOverlappedRecv.hEvent != INVALID_HANDLE_VALUE){
CloseHandle(mOverlappedRecv.hEvent);
mOverlappedRecv.hEvent = INVALID_HANDLE_VALUE;
}
if (mOverlappedSend.hEvent != INVALID_HANDLE_VALUE){
CloseHandle(mOverlappedSend.hEvent);
mOverlappedSend.hEvent = INVALID_HANDLE_VALUE;
}
}
bool CmdInterfaceWin::Open(string &port_name)
{
if (IsOpened())
Close();
mPortName = port_name;
mComHandle = ::CreateFile(port_name.c_str(),
GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
if (mComHandle == INVALID_HANDLE_VALUE) {
CloseHandle(mComHandle);
return false;
}
PurgeComm(mComHandle, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR);
if (SetupComm(mComHandle, 102400, 102400) == 0) {
CloseHandle(mComHandle);
return false;
}
DCB dcb;
dcb.DCBlength = sizeof(DCB);
if (GetCommState(mComHandle, &dcb) == 0) {
CloseHandle(mComHandle);
return false;
}
else {
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
dcb.fRtsControl = 0;
dcb.fDtrControl = 1;// use dtr control to notify usb serial port open and close event
if (SetCommState(mComHandle, &dcb) == 0) {
CloseHandle(mComHandle);
return false;
}
}
COMMTIMEOUTS timeouts;
timeouts.ReadIntervalTimeout = 2;
timeouts.ReadTotalTimeoutMultiplier = 0;
timeouts.ReadTotalTimeoutConstant = 5;
timeouts.WriteTotalTimeoutConstant = 50000;
timeouts.WriteTotalTimeoutMultiplier = 1000;
SetCommTimeouts(mComHandle, &timeouts);
mIsCmdOpened = true;
mRxThreadExitFlag = false;
mRxThread = new std::thread(mRxThreadProc, this);
return true;
}
bool CmdInterfaceWin::Close()
{
if (!IsOpened())
return true;
mRxThreadExitFlag = true;
mIsCmdOpened = false;
if (mComHandle != INVALID_HANDLE_VALUE) {
CloseHandle(mComHandle);
mComHandle = INVALID_HANDLE_VALUE;
}
if (mRxThread->joinable())
mRxThread->join();
delete mRxThread;
mRxThread = NULL;
return true;
}
bool CmdInterfaceWin::ReadFromIO(uint8_t * rx_buf, uint32_t rx_buf_len, uint32_t * rx_len)
{
if (IsOpened()) {
uint32_t res;
ResetEvent(mOverlappedRecv.hEvent);
res = ReadFile(mComHandle, rx_buf, rx_buf_len, (LPDWORD)rx_len, &mOverlappedRecv);
if (res == FALSE){
if (GetLastError() == ERROR_IO_PENDING){
if (WaitForSingleObject(mOverlappedRecv.hEvent, INFINITE) == WAIT_OBJECT_0) {
GetOverlappedResult(mComHandle, &mOverlappedRecv, (LPDWORD)rx_len, FALSE);
return true;
}
}
}
}
return false;
}
bool CmdInterfaceWin::WriteToIo(const uint8_t * tx_buf, uint32_t tx_buf_len, uint32_t * tx_len)
{
if (IsOpened()) {
ResetEvent(mOverlappedSend.hEvent);
uint32_t res = WriteFile(mComHandle, tx_buf, tx_buf_len, (LPDWORD)tx_len, &mOverlappedSend);
if (!res){
if (GetLastError() == ERROR_IO_PENDING){
WaitForSingleObject(mOverlappedSend.hEvent, INFINITE);
GetOverlappedResult(mComHandle, &mOverlappedSend, (LPDWORD)tx_len, FALSE);
}
}
}
return true;
}
bool CmdInterfaceWin::GetCmdDevices(std::vector<std::pair<std::string, std::string>>& device_list)
{
const TCHAR * vid_pid1 = _T("VID_0483&PID_5760"), *vid_pid2 = _T("VID_0483&PID_5740");
DWORD dwGuids = 0;
TCHAR prop_buf[1024];
SetupDiClassGuidsFromName(_T("Ports"), NULL, 0, &dwGuids);
if (dwGuids == 0)
return false;
GUID *pGuids = new GUID[dwGuids];
SetupDiClassGuidsFromName(_T("Ports"), pGuids, dwGuids, &dwGuids);
for (DWORD i = 0; i < dwGuids; i++) {
HDEVINFO hDevInfo = SetupDiGetClassDevs(&pGuids[i], NULL, NULL, DIGCF_PRESENT);
if (hDevInfo == INVALID_HANDLE_VALUE)
break;
for (int index = 0; ; index++) {
SP_DEVINFO_DATA devInfo;
std::pair<std::string, std::string> p;
devInfo.cbSize = sizeof(SP_DEVINFO_DATA);
if (!SetupDiEnumDeviceInfo(hDevInfo, index, &devInfo)) { break; }
prop_buf[0] = 0;
CM_Get_Device_ID(devInfo.DevInst, prop_buf, 1024, 0);
if (_tcsstr(prop_buf, vid_pid1) || _tcsstr(prop_buf, vid_pid2)) {
p.second = prop_buf;
HKEY hDeviceKey = SetupDiOpenDevRegKey(hDevInfo, &devInfo, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_QUERY_VALUE);
if (hDeviceKey) {
prop_buf[0] = 0;
DWORD dw_size = sizeof(prop_buf);
DWORD dw_type = 0;
if ((RegQueryValueEx(hDeviceKey, _T("PortName"), NULL, &dw_type, (LPBYTE)prop_buf, &dw_size) == ERROR_SUCCESS) && (dw_type == REG_SZ)) {
p.first = prop_buf;
device_list.push_back(p);
}
}
}
}
SetupDiDestroyDeviceInfoList(hDevInfo);
}
delete[]pGuids;
return true;
}
bool CmdInterfaceWin::GetUvcRelatedCmdPort(string & uvc_port_name, string & cmd_port_name)
{
std::vector<std::pair<std::string, std::string>> device_list;
bool ret = GetCmdDevices(device_list);
char video_id[32];
string uvc_name = uvc_port_name;
for (uint32_t i = 0; i < uvc_name.length(); i++)
uvc_name[i] = tolower(uvc_name[i]);
const char *id_ptr_end, *id_ptr = strstr(uvc_name.c_str(), "vid_");
if (id_ptr == NULL)
return false;
while (*id_ptr && *id_ptr != '#' && *id_ptr != '\\') id_ptr++;
id_ptr++;
if (strlen(id_ptr) < 5)
return false;
id_ptr_end = id_ptr + 4;
while (*id_ptr_end && *id_ptr_end != '&') id_ptr_end++;
for (int i = 0; i < id_ptr_end - id_ptr; i++)
video_id[i] = tolower(id_ptr[i]); // to lower case
video_id[id_ptr_end - id_ptr] = 0;
if (ret && device_list.size() > 0) {
for (auto dev : device_list) {
for (uint32_t i = 0; i < dev.second.length(); i++)
dev.second[i] = tolower(dev.second[i]);
if (strstr(dev.second.c_str(), video_id)) {
cmd_port_name = "\\\\.\\" + dev.first;
return true;
}
}
}
return false;
} | 28.166667 | 142 | 0.677048 | inmoition-depthcamera |
de9f0148e647af62dac35bb1244d9fccfc910b79 | 4,141 | cpp | C++ | src/sink/asynchronous.p.cpp | JakariaBlaine/blackhole | e340329c6e2e3166858d8466656ad12300b686bd | [
"MIT"
] | 193 | 2015-01-05T08:48:05.000Z | 2022-01-31T22:04:01.000Z | src/sink/asynchronous.p.cpp | JakariaBlaine/blackhole | e340329c6e2e3166858d8466656ad12300b686bd | [
"MIT"
] | 135 | 2015-01-13T13:02:49.000Z | 2022-01-12T15:06:48.000Z | src/sink/asynchronous.p.cpp | JakariaBlaine/blackhole | e340329c6e2e3166858d8466656ad12300b686bd | [
"MIT"
] | 40 | 2015-01-21T16:37:30.000Z | 2022-01-25T15:54:04.000Z | #include "asynchronous.hpp"
#include <cmath>
#include <condition_variable>
#include <mutex>
namespace blackhole {
inline namespace v1 {
namespace sink {
namespace {
auto exp2(std::size_t factor) -> std::size_t {
if (factor < 2 || factor > 20) {
throw std::invalid_argument("factor should fit in [2; 20] range");
}
return static_cast<std::size_t>(std::exp2(factor));
}
} // namespace
class drop_overflow_policy_t : public overflow_policy_t {
typedef overflow_policy_t::action_t action_t;
public:
/// Drops on overlow.
virtual auto overflow() -> action_t {
return action_t::drop;
}
/// Does nothing on wakeup.
virtual auto wakeup() -> void {}
};
class wait_overflow_policy_t : public overflow_policy_t {
typedef overflow_policy_t::action_t action_t;
mutable std::mutex mutex;
std::condition_variable cv;
public:
virtual auto overflow() -> action_t {
std::unique_lock<std::mutex> lock(mutex);
// TODO: WTF? Replace with something more convenient and not filling my eyes with blood.
cv.wait_for(lock, std::chrono::milliseconds(1));
return action_t::retry;
}
virtual auto wakeup() -> void {
cv.notify_one();
}
};
auto overflow_policy_factory_t::create(const std::string& name) const ->
std::unique_ptr<overflow_policy_t>
{
if (name == "drop") {
return std::unique_ptr<overflow_policy_t>(new drop_overflow_policy_t);
} else if (name == "wait") {
return std::unique_ptr<overflow_policy_t>(new wait_overflow_policy_t);
}
throw std::invalid_argument("no overflow policy with name \"" + name + "\" found");
}
asynchronous_t::asynchronous_t(std::unique_ptr<sink_t> wrapped, std::size_t factor) :
queue(exp2(factor)),
stopped(false),
wrapped(std::move(wrapped)),
overflow_policy(new wait_overflow_policy_t),
thread(std::bind(&asynchronous_t::run, this))
{}
asynchronous_t::asynchronous_t(std::unique_ptr<sink_t> sink,
std::size_t factor,
std::unique_ptr<overflow_policy_t> overflow_policy) :
queue(exp2(factor)),
stopped(false),
wrapped(std::move(sink)),
overflow_policy(std::move(overflow_policy)),
thread(std::bind(&asynchronous_t::run, this))
{}
asynchronous_t::~asynchronous_t() {
stopped.store(true);
thread.join();
}
auto asynchronous_t::capacity() const -> std::size_t {
return queue.capacity();
}
auto asynchronous_t::emit(const record_t& record, const string_view& message) -> void {
while (true) {
// TODO: Uncomment.
// switch (filter->filter(record, message)) {
// case filter_t::accept:
// case filter_t::neutral:
// break;
// case filter_t::reject:
// return;
// }
const auto enqueued = queue.enqueue_with([&](value_type& value) {
value = {recordbuf_t(record), message.to_string()};
});
if (enqueued) {
// TODO: underflow_policy->wakeup();
return;
} else {
switch (overflow_policy->overflow()) {
case overflow_policy_t::action_t::retry:
continue;
case overflow_policy_t::action_t::drop:
return;
}
}
}
}
auto asynchronous_t::run() -> void {
while (true) {
value_type result;
const auto dequeued = queue.dequeue_with([&](value_type& value) {
result = std::move(value);
});
if (stopped && !dequeued) {
return;
}
if (dequeued) {
try {
wrapped->emit(result.record.into_view(), result.message);
overflow_policy->wakeup();
} catch (...) {
throw;
// TODO: exception_policy->process();
}
} else {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
// TODO: underflow_policy->underflow(); [wait for enqueue, sleep].
}
}
}
} // namespace sink
} // namespace v1
} // namespace blackhole
| 27.243421 | 96 | 0.596474 | JakariaBlaine |
dea237dfea8efa14ff17503ac74369a0fbe400a7 | 1,201 | cpp | C++ | src/reactor.cpp | vladislavmarkov/sketch | 5afed3edd0245942ed2010df1d092fc7d1ed8610 | [
"MIT"
] | null | null | null | src/reactor.cpp | vladislavmarkov/sketch | 5afed3edd0245942ed2010df1d092fc7d1ed8610 | [
"MIT"
] | null | null | null | src/reactor.cpp | vladislavmarkov/sketch | 5afed3edd0245942ed2010df1d092fc7d1ed8610 | [
"MIT"
] | null | null | null | #include <sketch/reactor.hpp>
#include <iostream>
#include <sketch/window.hpp>
namespace sk {
namespace {
void
default_on_draw(gsl::not_null<window_t*>)
{
// do nothing
std::cout << __FUNCTION__ << '\n';
}
void
default_on_quit(gsl::not_null<window_t*> window)
{
// do nothing
std::cout << __FUNCTION__ << '\n';
window->quit();
}
void
default_on_keydown(
gsl::not_null<window_t*>, [[maybe_unused]] std::size_t keycode)
{
// do nothing
std::cout << __FUNCTION__ << '\n';
}
void
default_on_mouse_move(
gsl::not_null<window_t*>,
[[maybe_unused]] const std::tuple<std::size_t, std::size_t>& point)
{
// do nothing
std::cout << __FUNCTION__ << '\n';
}
}
reactor_t::reactor_t()
: _on_draw(default_on_draw),
_on_quit(default_on_quit),
_on_keydown(default_on_keydown),
_on_mouse_move(default_on_mouse_move)
{
}
void
reactor_t::on_draw()
{
_on_draw(_window);
}
void
reactor_t::on_quit()
{
_on_quit(_window);
}
void
reactor_t::on_keydown(std::size_t keycode)
{
_on_keydown(_window, keycode);
}
void
reactor_t::on_mouse_move(const std::tuple<std::size_t, std::size_t>& point)
{
_on_mouse_move(_window, point);
}
}
| 15.802632 | 75 | 0.665279 | vladislavmarkov |
dea84b5648da991e302dc63bcf4d54da31307b40 | 22,928 | hpp | C++ | libraries/belle/Source/Symbols/Chord.hpp | jogawebb/Spaghettis | 78f21ba3065ce316ef0cb84e94aecc9e8787343d | [
"Zlib",
"BSD-2-Clause",
"BSD-3-Clause"
] | 47 | 2017-09-05T02:49:22.000Z | 2022-01-20T08:11:47.000Z | libraries/belle/Source/Symbols/Chord.hpp | jogawebb/Spaghettis | 78f21ba3065ce316ef0cb84e94aecc9e8787343d | [
"Zlib",
"BSD-2-Clause",
"BSD-3-Clause"
] | 106 | 2018-05-16T14:58:52.000Z | 2022-01-12T13:57:24.000Z | libraries/belle/Source/Symbols/Chord.hpp | jogawebb/Spaghettis | 78f21ba3065ce316ef0cb84e94aecc9e8787343d | [
"Zlib",
"BSD-2-Clause",
"BSD-3-Clause"
] | 11 | 2018-05-16T06:44:51.000Z | 2021-11-10T07:04:46.000Z |
/*
Copyright (c) 2007-2013 William Andrew Burnson.
Copyright (c) 2013-2020 Nicolas Danet.
*/
/* < http://opensource.org/licenses/BSD-2-Clause > */
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
/* < https://en.wikipedia.org/wiki/Chord_%28music%29 > */
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
/* No support for bitonal chord and tonal cluster. */
/* < http://musescore.org/en/node/14449 > */
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
/* No support for Maxima, Longa, Breve (and relative rests). */
/* < https://en.wikipedia.org/wiki/Double_whole_note > */
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
namespace belle {
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
namespace Shapes {
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
class Chord {
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
class Note {
public:
Note() : linespace_ (0), isTied_ (false)
{
}
Note (int i, mica::Concept accidental, mica::Concept chromatic, bool tied)
{
linespace_ = i;
accidental_ = accidental;
chromatic_ = chromatic;
isTied_ = tied;
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
#if PRIM_CPP11
public:
Note (const Note&) = default;
Note (Note&&) = default;
Note& operator = (const Note&) = default;
Note& operator = (Note&&) = default;
#endif
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
public:
bool operator < (const Note& o) const
{
mica::Concept diff = mica::index (mica::Accidentals, o.accidental_, accidental_);
return (linespace_ < o.linespace_) || ((linespace_ == o.linespace_) && (diff.getNumerator() < 0));
}
bool operator > (const Note& o) const
{
mica::Concept diff = mica::index (mica::Accidentals, o.accidental_, accidental_);
return (linespace_ > o.linespace_) || ((linespace_ == o.linespace_) && (diff.getNumerator() > 0));
}
bool operator == (const Note& o) const
{
return (linespace_ == o.linespace_) && (accidental_ == o.accidental_);
}
bool operator != (const Note& o) const
{
return !(*this == o);
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
public:
int getLinespace() const
{
return linespace_;
}
mica::Concept getAccidental() const
{
return accidental_;
}
mica::Concept getChromatic() const
{
return chromatic_;
}
bool isTied() const
{
return isTied_;
}
private:
int linespace_;
mica::Concept accidental_;
mica::Concept chromatic_;
bool isTied_;
};
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
public:
Chord() : duration_ (Ratio (1, 4)), isStemUp_ (true)
{
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
#if PRIM_CPP11
public:
Chord (const Chord&) = default;
Chord (Chord&&) = default;
Chord& operator = (const Chord&) = default;
Chord& operator = (Chord&&) = default;
#endif
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
public:
Chord& setDuration (mica::Concept duration)
{
duration_ = duration.toRatio(); return *this;
}
Chord& setBeam (mica::Concept beam)
{
beam_ = beam; return *this;
}
Chord& setDirection (mica::Concept direction)
{
direction_ = direction; return *this;
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
public:
void addNote (mica::Concept linespace, mica::Concept accidental, mica::Concept chromatic, bool tied)
{
notes_.add (Chord::Note (linespace.getNumerator(), accidental, chromatic, tied));
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
/* Due to path filling artifacts flags are engraved later. */
public:
void addToPath (Path& path) const
{
if (!notes_.size()) { path.addShape (Shapes::Rest (duration_)); }
else {
//
prepare (path); /* Note that in functions below only the sorted notes are used. */
path.addPath (engraveLedgerLines());
Path notes (engraveNotes());
path.addPath (engraveDots (notes));
path.addPath (engraveAccidentals (notes));
path.addPath (notes);
//
}
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
public:
mica::Concept getDirection() const
{
return direction_;
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
private:
void prepare (Path& path) const
{
/* In case. */
sorted_.clear();
clustered_.clear();
/* Sort and remove duplicated notes if any. */
Array < Note > temp (notes_);
temp.sort();
sorted_.add (temp.getFirst());
for (int i = 1; i < temp.size(); ++i) { if (temp[i] != temp[i - 1]) { sorted_.add (temp[i]); } }
/* Determine the ties direction. */
temp.clear();
for (int i = 0; i < sorted_.size(); ++i) {
if (sorted_[i].isTied()) { temp.add (sorted_[i]); }
}
if (temp.size()) {
//
path.setProperty (temp.getFirst().getChromatic(), mica::Below);
path.setProperty (temp.getLast().getChromatic(), mica::Above);
for (int i = 1; i < temp.size() - 1; ++i) {
if (temp[i].getLinespace() >= 0) { path.setProperty (temp[i].getChromatic(), mica::Above); }
else {
path.setProperty (temp[i].getChromatic(), mica::Below);
}
}
//
}
/* Determine the stem direction. */
if (direction_ == mica::Undefined) {
Array < int > linespaces;
for (int i = 0; i < sorted_.size(); ++i) { linespaces.add (sorted_[i].getLinespace()); }
direction_ = Utils::getDirection (linespaces);
}
isStemUp_ = (direction_ == mica::Up);
/* Base of the chord always comes first. */
if (isStemUp_ == false) { sorted_.reverse(); }
/* Group notes by clusters (consecutive staff lines and staff spaces). */
Array < Note > cluster;
cluster.add (sorted_.getFirst());
clustered_.add (cluster);
for (int i = 1; i < sorted_.size(); ++i) {
if ((Math::abs ((sorted_[i].getLinespace() - sorted_[i - 1].getLinespace())) < 2)) {
clustered_.getLast().add (sorted_[i]);
} else {
Array < Note > newCluster;
newCluster.add (sorted_[i]);
clustered_.add (newCluster);
}
}
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
private:
Path engraveLedgerLines() const
{
Path path;
int highNote = getHighestLinespace();
int lowNote = getLowestLinespace();
int highCluster = getHighestLinespaceInClusters();
int lowCluster = getLowestLinespaceInClusters();
for (int i = Utils::getTopLine() + 2; i <= highNote; i += 2) {
Affine affine = Affine::translation (Vector (0.0, Utils::getPosition (i)));
if (i < highCluster) { path.addShape (Shapes::LedgerLineTwoColumn (isStemUp_), affine); }
else {
path.addShape (Shapes::LedgerLine(), affine);
}
}
for (int i = Utils::getBottomLine() - 2; i >= lowNote; i -= 2) {
Affine affine = Affine::translation (Vector (0.0, Utils::getPosition (i)));
if (i > lowCluster) { path.addShape (Shapes::LedgerLineTwoColumn (isStemUp_), affine); }
else {
path.addShape (Shapes::LedgerLine(), affine);
}
}
return path;
}
Path engraveNotes() const
{
Path path;
for (int i = 0; i < sorted_.size(); ++i) {
//
Ratio base = Utils::getUndottedValue (duration_);
double y = Utils::getPosition (sorted_[i].getLinespace());
double x = getColumn (i);
Vector v;
Affine origin;
if (x) { v = Vector (x * (House::kNoteHeadWidthPrecise - (House::kNoteStemThickness / 2.0)), y); }
else {
v = Vector (0.0, y);
}
origin = Affine::translation (v);
path.getBox (sorted_[i].getChromatic()) = Box (v); /* Anchors for ties. */
if (i || (duration_ >= Ratio (1, 1))) {
//
if (base <= Ratio (1, 4)) { path.addShape (Shapes::QuarterNote().setHeight (0.0), origin); }
else if (base == Ratio (1, 2)) { path.addShape (Shapes::HalfNote().setHeight (0.0), origin); }
else {
path.addShape (Shapes::WholeNote(), origin);
}
//
} else {
//
double h = getHeight();
if (base == Ratio (1, 2)) { path.addShape (Shapes::HalfNote().setHeight (h), origin); }
else {
if (beam_ == mica::Undefined) { path.addShape (Shapes::QuarterNote().setHeight (h), origin); }
else {
path.addShape (Shapes::QuarterNote().hasBeam (true).setHeight (h), origin);
}
}
//
}
//
}
/* Rearrange anchors to avoid collision with note heads. */
double right = path.getBounds().getRight();
for (int i = 0; i < sorted_.size(); ++i) {
path.getBox (sorted_[i].getChromatic()).setRight (right);
}
return path;
}
Path engraveDots (Path& notes) const
{
Path path;
int count = Utils::countDots (duration_);
if (count) {
//
Path collision;
/* Reserve the place for the flags. */
if (beam_ == mica::Undefined && Utils::countFlags (duration_)) {
Path flag ((Shapes::FlagStemUp())); /* Avoid most vexing parse. */
Affine affine = Affine::translation (flag.getBounds().getWidth());
collision.addRectangle (notes.getBounds() + affine.appliedTo (notes.getBox (mica::Stem)));
} else {
collision.addRectangle (notes.getBounds());
}
double x = collision.getBounds().getRight() + House::kRhythmicDotDistance;
Array < int > y;
Array < int > remains;
int previous = 1234; /* Dummy. */
for (int i = 0; i < sorted_.size(); ++i) {
//
int linespace = sorted_[i].getLinespace();
int current = (linespace % 2) ? linespace : linespace + 1;
if (current != previous) { y.add (current); previous = current; }
else {
remains.add (current);
}
//
}
for (int i = 0; i < remains.size(); ++i) {
//
int j = 0;
bool placed = false;
while (!placed) {
//
int below = remains[i] - (2 * j);
int above = remains[i] + (2 * j);
if (y.contains (below) == false) { y.add (below); placed = true; }
else if (y.contains (above) == false) { y.add (above); placed = true; }
j++;
//
}
//
}
for (int i = 0; i < y.size(); ++i) {
//
for (int j = 0; j < count; ++j) {
//
Vector v (x + (j * House::kRhythmicDotExtra), Utils::getPosition (y[i]));
Affine origin = Affine::translation (v);
path.addShape (Shapes::RhythmicDot(), origin);
collision.addShape (Shapes::RhythmicDot(), origin);
//
}
//
}
/* Rearrange anchors to avoid collision with dots. */
double right = collision.getBounds().getRight();
for (int i = 0; i < sorted_.size(); ++i) {
notes.getBox (sorted_[i].getChromatic()).setRight (right);
}
//
}
return path;
}
Path engraveAccidentals (Path& notes) const
{
Path path;
Array < Path > shape;
Array < int > order;
Array < Vector > place;
shape.resize (sorted_.size());
order.resize (sorted_.size());
place.resize (sorted_.size());
for (int i = 0; i < sorted_.size(); ++i) {
//
mica::Concept accidental (sorted_[i].getAccidental());
if (accidental == mica::DoubleFlat) { shape[i] = Path (Shapes::AccidentalDoubleFlat()); }
else if (accidental == mica::Flat) { shape[i] = Path (Shapes::AccidentalFlat()); }
else if (accidental == mica::Natural) { shape[i] = Path (Shapes::AccidentalNatural()); }
else if (accidental == mica::Sharp) { shape[i] = Path (Shapes::AccidentalSharp()); }
else if (accidental == mica::DoubleSharp) { shape[i] = Path (Shapes::AccidentalDoubleSharp()); }
//
}
for (int i = 0; i < sorted_.size(); ++i) { /* Alterne from up and down to the middle. */
//
if (isStemUp_) {
if (i % 2 == 0) { order[i] = (sorted_.size() - 1) - (i / 2); }
else {
order[i] = (i - 1) / 2;
}
} else {
if (i % 2 == 0) { order[i] = i / 2; }
else {
order[i] = (sorted_.size() - 1) - (i - 1) / 2;
}
}
//
}
Path collision;
collision.addRectangle (notes.getBounds());
for (int i = 0; i < sorted_.size(); ++i) {
//
if (!shape[order[i]].isEmpty()) {
//
double y = Utils::getPosition (sorted_[order[i]].getLinespace());
double d = Optics::nonCollidingByOutlines (collision, shape[order[i]], Point (0.0, y), kPi);
place[order[i]] = Vector (-(d + House::kAccidentalExtra), y);
collision.addPath (shape[order[i]], Affine::translation (place[order[i]]));
//
}
//
}
Vector v (-(House::kAccidentalDistance - House::kAccidentalExtra), 0.0);
for (int i = 0; i < sorted_.size(); ++i) {
//
if (!shape[order[i]].isEmpty()) {
//
path.addPath (shape[order[i]], Affine::translation (place[order[i]] + v));
//
}
//
}
/* Rearrange anchors to avoid collision with accidentals. */
double left = collision.getBounds().getLeft() + v.getX();
for (int i = 0; i < sorted_.size(); ++i) {
notes.getBox (sorted_[i].getChromatic()).setLeft (left);
}
return path;
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
private:
double getHeight() const
{
/* Basic. */
int last = sorted_.getLast().getLinespace();
int first = sorted_.getFirst().getLinespace();
double height = House::kNoteStemHeight + (Math::abs (last - first) * (House::kNoteHeadHeight / 2.0));
/* Extra flags. */
int flags = Utils::countFlags (duration_);
if (flags > 2) { height += (flags - 2) * House::kStaffSpaceWidth; }
/* Ledger lines case. */
bool top = !isStemUp_ && (last > (Utils::getTopLine() + 2));
bool bottom = isStemUp_ && (last < (Utils::getBottomLine() - 2));
if (top || bottom) { height = Math::max (height, Math::abs (Utils::getPosition (first))); }
/* Stem up or stem down. */
return height * (isStemUp_ ? 1.0 : -1.0);
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
private:
int getColumn (int i) const
{
for (int j = 0; j < clustered_.size(); ++j) { /* Stagger heads according to clusters. */
//
int n = clustered_[j].size();
if (i >= n) { i -= n; }
else {
break;
}
//
}
if (i % 2 == 0) { return 0; }
else if (isStemUp_) { return 1; }
else {
return -1;
}
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
private:
int getLowestLinespace() const
{
int n = sorted_.getFirst().getLinespace();
for (int i = 1; i < sorted_.size(); ++i) { n = Math::min (n, sorted_[i].getLinespace()); }
return n;
}
int getLowestLinespaceInClusters() const
{
int n = 0;
bool first = true;
for (int i = 0; i < clustered_.size(); ++i) {
//
if (clustered_[i].size() > 1) {
//
for (int j = 0; j < clustered_[i].size(); ++j) {
if (first) { n = clustered_[i][j].getLinespace(); first = false; }
else {
n = Math::min (n, clustered_[i][j].getLinespace());
}
}
//
}
//
}
return n;
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
private:
int getHighestLinespace() const
{
int n = sorted_.getFirst().getLinespace();
for (int i = 1; i < sorted_.size(); ++i) { n = Math::max (n, sorted_[i].getLinespace()); }
return n;
}
int getHighestLinespaceInClusters() const
{
int n = 0;
bool first = true;
for (int i = 0; i < clustered_.size(); ++i) {
//
if (clustered_[i].size() > 1) {
//
for (int j = 0; j < clustered_[i].size(); ++j) {
if (first) { n = clustered_[i][j].getLinespace(); first = false; }
else {
n = Math::max (n, clustered_[i][j].getLinespace());
}
}
//
}
//
}
return n;
}
private:
Ratio duration_;
mutable mica::Concept direction_;
mica::Concept beam_;
Array < Note > notes_;
private:
mutable bool isStemUp_;
mutable Array < Note > sorted_;
mutable Array < Array < Note > > clustered_;
private:
PRIM_LEAK_DETECTOR (Chord)
};
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
} // namespace Shapes
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
} // namespace belle
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
| 32.942529 | 110 | 0.371293 | jogawebb |
dea89fd398cf96bb569d0f1b2240062e33740405 | 5,710 | cpp | C++ | src/ScriptProcs/Event/Keyboard.cpp | MichaelMCE/LCDMisc | 1d2a913d62fd4d940ad95b5f8463a5f06e683427 | [
"CC-BY-4.0"
] | null | null | null | src/ScriptProcs/Event/Keyboard.cpp | MichaelMCE/LCDMisc | 1d2a913d62fd4d940ad95b5f8463a5f06e683427 | [
"CC-BY-4.0"
] | null | null | null | src/ScriptProcs/Event/Keyboard.cpp | MichaelMCE/LCDMisc | 1d2a913d62fd4d940ad95b5f8463a5f06e683427 | [
"CC-BY-4.0"
] | null | null | null | #include "../../global.h"
#include "Keyboard.h"
#include "../../Unicode.h"
#include "../../vm.h"
#include "../../Config.h"
int GetKey(ScriptValue *args) {
if (args->type == SCRIPT_LIST && args->listVal->numVals) {
if (args->listVal->vals[0].type == SCRIPT_STRING) {
if (args->listVal->vals[0].stringVal->len) {
int junk;
unsigned long c = NextUnicodeChar(args->listVal->vals[0].stringVal->value, &junk);
if (c > 0xFFFF) return 0;
return 0xFF&VkKeyScanW((wchar_t)c);
}
return 0;
}
else {
ScriptValue sv;
CoerceIntNoRelease(args->listVal->vals[0], sv);
return sv.i32;
}
}
return 0;
}
void ScriptGetKeyState(ScriptValue &s, ScriptValue *args) {
int i = GetKey(args);
CreateIntValue(s, GetKeyState(i));
}
void KeyDown(ScriptValue &s, ScriptValue *args) {
int i = GetKey(args);
if (i && i <= 254) {
int extend = 0;
if (args->type == SCRIPT_LIST && args->listVal->numVals >= 2) {
ScriptValue sv;
CoerceIntNoRelease(args->listVal->vals[1], sv);
if (sv.intVal == 1) {
extend = KEYEVENTF_EXTENDEDKEY;
}
}
keybd_event(i, 0, extend, 0);
}
}
void KeyUp(ScriptValue &s, ScriptValue *args) {
int i = GetKey(args);
if (i && i <= 254) {
int extend = KEYEVENTF_KEYUP;
if (args->type == SCRIPT_LIST && args->listVal->numVals >= 2) {
ScriptValue sv;
CoerceIntNoRelease(args->listVal->vals[1], sv);
if (sv.intVal == 1) {
extend = KEYEVENTF_KEYUP|KEYEVENTF_EXTENDEDKEY;
}
}
keybd_event(i, 0, extend, 0);
}
}
HHOOK hook;
struct KeyboardEvents {
unsigned int total;
unsigned char keys[16*256];
};
KeyboardEvents *keyEvents = 0;
LRESULT CALLBACK KeyboardProc(int code, WPARAM wParam, LPARAM lParam) {
if (hook) {
KBDLLHOOKSTRUCT* key = (KBDLLHOOKSTRUCT*) lParam;
int vk = key->vkCode;
if (vk != 120 && vk != 116) {
vk = vk;
}
if (vk >= 0 && vk <= 255) {
if (*((unsigned int*)&keyEvents->keys[vk*16 ]) |
*((unsigned int*)&keyEvents->keys[vk*16 + 4]) |
*((unsigned int*)&keyEvents->keys[vk*16 + 8]) |
*((unsigned int*)&keyEvents->keys[vk*16 + 12])) {
int flags = 0;
int shift;
if (GetKeyState(VK_CONTROL)&0x8000)
flags = KEY_CONTROL;
if ((shift = GetKeyState(VK_SHIFT))&0x8000)
flags |= KEY_SHIFT;
if (GetKeyState(VK_MENU)&0x8000)
flags |= KEY_ALT;
if ((GetKeyState(VK_RWIN) | GetKeyState(VK_LWIN))&0x8000)
flags |= KEY_WIN;
if (keyEvents->keys[vk*16+flags]) {
int down = (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN);
int scancode = key->scanCode;
unsigned char s[256];
wchar_t key[5];
memset(s, 0, 256);
//int test = GetAsyncKeyState(VK_CAPITAL);
//GetKeyboardState(s);
s[VK_SHIFT] = (shift>>8)&0x80;
s[VK_CAPITAL] = (GetKeyState(VK_CAPITAL))>>8;
s[VK_NUMLOCK] = (GetKeyState(VK_TAB)>>8);
s[VK_SCROLL] = (GetKeyState(VK_SCROLL))>>8;
//s[VK_CONTROL] = (char) GetKeyState(VK_CONTROL);
int wParam = (vk &0xFFFF) + (flags<<16) + (down<<24);
//HKL layout = GetKeyboardLayout(0);
s[vk] = 0x80;
char temp = ToUnicode(vk, scancode, s, key, 5, 0);
int lParam = 0;
if (temp) {
lParam = key[0];
if (temp >= 2) {
lParam = (key[1]<<16);
}
}
PostMessage(ghWnd, WMU_EATEN_KEY, wParam, lParam);
PostMessage(ghWnd, WM_KEYDOWN, wParam, lParam);
return 1;
}
}
}
return CallNextHookEx(hook, code, wParam, lParam);
}
return 0;
}
static void UpdateKeyEvents() {
if (!keyEvents) return;
if (!keyEvents->total && hook) {
UnhookWindowsHookEx(hook);
hook = 0;
free(keyEvents);
keyEvents = 0;
}
else if (!hook) {
hook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardProc, ghInst, 0);
if (!hook) errorPrintf(0, "Hook creation failed: %i\n", GetLastError());
}
}
void CleanKeyEvents() {
if (keyEvents) {
UnhookWindowsHookEx(hook);
hook = 0;
free(keyEvents);
keyEvents = 0;
}
}
void RegisterKeyEvent(ScriptValue &s, ScriptValue *args) {
if (args->type != SCRIPT_LIST) return;
ListValue *list = args->listVal;
int len = list->numVals;
if (len < 2) return;
ScriptValue sv;
CoerceIntNoRelease(list->vals[0], sv);
int dCare = (sv.i32>>16)&15;
sv.intVal -= (dCare<<16);
if (sv.intVal < 0 || sv.intVal > 15 || (dCare&sv.i32)) return;
if (!keyEvents) {
keyEvents = (KeyboardEvents*)calloc(1, sizeof(KeyboardEvents));
if (!keyEvents) return;
}
int state = sv.i32;
int count = 0;
for (int j=0; j<16; j++) {
if (!(j&~dCare)) {
int state2 = state+j;
for (int i=1; i < len; i++) {
CoerceIntNoRelease(list->vals[i], sv);
if (sv.intVal < 0 || sv.intVal > 255) continue;
int t = sv.i32*16 + state2;
if (keyEvents->keys[t] == 255) continue;
keyEvents->keys[t]++;
keyEvents->total++;
count ++;
}
}
}
UpdateKeyEvents();
if (count) {
CreateIntValue(s, count);
}
}
void UnregisterKeyEvent(ScriptValue &s, ScriptValue *args) {
if (args->type != SCRIPT_LIST) return;
ListValue *list = args->listVal;
int len = list->numVals;
if (len < 2) return;
ScriptValue sv;
CoerceIntNoRelease(list->vals[0], sv);
int dCare = (sv.i32>>16)&15;
sv.intVal -= (dCare<<16);
if (sv.intVal < 0 || sv.intVal > 15 || (dCare&sv.i32)) return;
if (!keyEvents) return;
int state = sv.i32;
int count = 0;
for (int j=0; j<16; j++) {
if (!(j&~dCare)) {
int state2 = state+j;
for (int i=1; i < len; i++) {
CoerceIntNoRelease(list->vals[i], sv);
if (sv.intVal < 0 || sv.intVal > 255) continue;
int t = sv.i32*16 + state2;
if (!keyEvents->keys[t]) continue;
keyEvents->keys[t]--;
keyEvents->total--;
count ++;
}
}
}
UpdateKeyEvents();
if (count) {
CreateIntValue(s, count);
}
}
| 25.605381 | 86 | 0.605954 | MichaelMCE |
deac547ad73748c5e87d2125b7fc3a022d4576e1 | 2,699 | cpp | C++ | src/T56_memoryManager/T56_memoryManager.cpp | RemiMattheyDoret/SimBit | ed0e64c0abb97c6c889bc0adeec1277cbc6cbe43 | [
"MIT"
] | 11 | 2017-06-06T23:02:48.000Z | 2021-08-17T20:13:05.000Z | src/T56_memoryManager/T56_memoryManager.cpp | RemiMattheyDoret/SimBit | ed0e64c0abb97c6c889bc0adeec1277cbc6cbe43 | [
"MIT"
] | 1 | 2017-06-06T23:08:05.000Z | 2017-06-07T09:28:08.000Z | src/T56_memoryManager/T56_memoryManager.cpp | RemiMattheyDoret/SimBit | ed0e64c0abb97c6c889bc0adeec1277cbc6cbe43 | [
"MIT"
] | null | null | null | void T56_memoryManager::doStuff(Haplotype& haplo)
{
auto& ntrl = haplo.T5ntrl_Alleles;
auto& sel = haplo.T5sel_Alleles;
/////////////////
// Record info //
/////////////////
if (shouldRecordInfo)
{
if (SSP->Gmap.T5ntrl_nbLoci && ntrl.size() > maxNtrlSizeLastGeneration)
maxNtrlSizeLastGeneration = ntrl.size();
if (SSP->Gmap.T5sel_nbLoci && sel.size() > maxSelSizeLastGeneration)
maxSelSizeLastGeneration = sel.size();
}
////////////
// Shrink //
////////////
if (shouldShrink)
{
if (SSP->Gmap.T5ntrl_nbLoci)
{
if (ntrl.capacity() > 1.1 * (double)ntrl.size()) // if there is some non-negligible loss
{
auto oldCapacity = ntrl.capacity();
ntrl.shrink_to_fit();
if (oldCapacity > maxNtrlSizeLastGeneration && ntrl.size() < maxNtrlSizeLastGeneration && ntrl.size() > (double)maxNtrlSizeLastGeneration / 1.5)
{
ntrl.reserve(maxNtrlSizeLastGeneration);
} else
{
ntrl.reserve(1.1 * (double)ntrl.size());
}
}
}
if (SSP->Gmap.T5sel_nbLoci)
{
if (sel.capacity() > 1.1 * (double)sel.size()) // if there is some non-negligible loss
{
auto oldCapacity = sel.capacity();
sel.shrink_to_fit();
if (oldCapacity > maxNtrlSizeLastGeneration && sel.size() < maxSelSizeLastGeneration && sel.size() > (double)maxSelSizeLastGeneration / 1.5)
{
sel.reserve(maxSelSizeLastGeneration);
} else
{
sel.reserve(1.1 * (double)sel.size());
}
}
}
}
}
void T56_memoryManager::setGenerationInfo()
{
if (attempt_shrinking_every_N_generation != -1)
{
// If info was recorded last generation
if (shouldRecordInfo)
shouldShrink = true;
else
shouldShrink = false;
// Check if it is time to record information
if (GP->CurrentGeneration % attempt_shrinking_every_N_generation == 0)
shouldRecordInfo = true;
else
shouldRecordInfo = false;
}
}
template<typename INT>
void T56_memoryManager::set_attempt_shrinking_every_N_generation(INT i)
{
if (i != -1 && i < 2)
{
std::cout << "For option --shrinkT56EveryNGeneration, received a value that is lower than two and differentt from -1 (-1 means no shrinking)\n";
abort();
}
attempt_shrinking_every_N_generation = i;
}
| 31.022989 | 160 | 0.537607 | RemiMattheyDoret |
deb6cfa20098fe6465e4cf57c429b2ae34bba38f | 891 | cpp | C++ | Source/ModularGameplayActors/Private/ModularAIController.cpp | TheEmidee/UEModularGameplayActors | 9f87c2e4a418f90a2735c823ccb94e43a7721aaf | [
"MIT"
] | 1 | 2022-02-16T10:44:28.000Z | 2022-02-16T10:44:28.000Z | Source/ModularGameplayActors/Private/ModularAIController.cpp | TheEmidee/UEModularGameplayActors | 9f87c2e4a418f90a2735c823ccb94e43a7721aaf | [
"MIT"
] | null | null | null | Source/ModularGameplayActors/Private/ModularAIController.cpp | TheEmidee/UEModularGameplayActors | 9f87c2e4a418f90a2735c823ccb94e43a7721aaf | [
"MIT"
] | null | null | null | #include "ModularAIController.h"
#include <Components/GameFrameworkComponentManager.h>
void AModularAIController::PreInitializeComponents()
{
Super::PreInitializeComponents();
if ( auto * gi = GetGameInstance() )
{
if ( auto * system = gi->GetSubsystem< UGameFrameworkComponentManager >() )
{
system->AddReceiver( this );
}
}
}
void AModularAIController::BeginPlay()
{
UGameFrameworkComponentManager::SendGameFrameworkComponentExtensionEvent( this, UGameFrameworkComponentManager::NAME_GameActorReady );
Super::BeginPlay();
}
void AModularAIController::EndPlay( const EEndPlayReason::Type EndPlayReason )
{
if ( auto * system = GetGameInstance()->GetSubsystem< UGameFrameworkComponentManager >() )
{
system->RemoveReceiver( this );
}
Super::EndPlay( EndPlayReason );
} | 27 | 139 | 0.67789 | TheEmidee |
6312197b3a45d40f0d3df1d3f1156ab513b3d9ce | 1,307 | hpp | C++ | include/oxu/beatmap/components/slider.hpp | oda404/oxu | 5df4755f796be976bed767cd889a2e71ed867f9b | [
"MIT"
] | null | null | null | include/oxu/beatmap/components/slider.hpp | oda404/oxu | 5df4755f796be976bed767cd889a2e71ed867f9b | [
"MIT"
] | null | null | null | include/oxu/beatmap/components/slider.hpp | oda404/oxu | 5df4755f796be976bed767cd889a2e71ed867f9b | [
"MIT"
] | null | null | null | #pragma once
#include<cstdint>
#include<vector>
#include<oxu/beatmap/sections/difficulty.hpp>
#include<oxu/beatmap/components/hitCircle.hpp>
#include<oxu/framework/utils/vector2.hpp>
namespace oxu
{
enum class SliderCurveType
{
LINEAR = 0,
BEZIER = 1,
CIRCLE = 2
};
struct SliderInfo
{
SliderCurveType curve_type;
std::vector<framework::Vector2<float>> curve_points;
std::uint16_t slides;
double length;
/* edge sounds && edge sets */
};
class Slider : public HitCircle
{
private:
std::vector<framework::Vector2<float>> m_curve_points;
SliderCurveType m_curve_type;
std::uint16_t m_slides;
double m_length;
public:
Slider(
const ObjectInfo &obj_info,
const SliderInfo &slider_info,
const Difficulty &difficulty
);
void update(const double &delta, const Difficulty &difficulty) override;
void render(const Skin &skin) override;
void setErrorMargin(const long double &err, const Difficulty &difficulty) override;
bool shouldAddToPool(const std::uint32_t &mapTimeMs, const std::uint16_t &approach_rate_ms) const override;
bool shouldRemoveFromPool() const override;
};
}
| 26.14 | 115 | 0.644989 | oda404 |
63160e547d733a2c8efac6c5f63f11d195f041f2 | 1,511 | hpp | C++ | include/managers/state_manager.hpp | zedrex/algosketch | ff0f759f9e7e0e4ff040cf6c84334aceac47adae | [
"MIT"
] | 16 | 2021-03-27T06:20:42.000Z | 2022-03-31T16:30:37.000Z | include/managers/state_manager.hpp | zedrex/Algo-Plus-Plus | ff0f759f9e7e0e4ff040cf6c84334aceac47adae | [
"MIT"
] | 1 | 2021-07-13T07:57:41.000Z | 2021-07-13T07:57:41.000Z | include/managers/state_manager.hpp | zedrex/Algo-Plus-Plus | ff0f759f9e7e0e4ff040cf6c84334aceac47adae | [
"MIT"
] | 3 | 2021-04-03T02:58:56.000Z | 2021-06-04T18:23:49.000Z | #pragma once
#include <iostream>
#include <managers/window_manager.hpp>
#include <managers/event_manager.hpp>
#include <managers/resource_manager.hpp>
class State;
enum class Action
{
ChangeToMainMenu,
ChangeToNewSketchMenu,
ChangeToLoadSketchMenu,
ChangeToHelpMenu,
ChangeToCreditsMenu,
QuitApplication,
Array,
Graph,
Grid,
String,
Create,
Reset,
Run,
Pause,
Back,
BubbleSort,
SelectionSort,
InsertionSort,
ShellSort,
GnomeSort,
GraphDepthFirstSearch,
GraphBreadthFirstSearch,
GraphDijkstra,
GridDepthFirstSearch,
GridBreadthFirstSearchPathfinding,
GridFloodFill,
GridAStarPathfinder
};
class StateManager
{
public:
StateManager();
StateManager(WindowManager *applicationWindowManager, EventManager *applicationEventManager, ResourceManager *applicationResourceManager);
~StateManager();
void setWindowManager(WindowManager *applicationWindowManager);
void setEventManager(EventManager *applicationEventManager);
void setResourceManager(ResourceManager *applicationResourceManager);
void start();
State *getCurrentState();
WindowManager *getApplicationWindow();
EventManager *getEventManager();
void perform(Action action);
void changeState(State *newState);
void update();
void render();
private:
WindowManager *windowManager;
EventManager *eventManager;
ResourceManager *resourceManager;
State *currentState;
};
| 19.881579 | 142 | 0.731304 | zedrex |
63204c5730e690db4ecfa8622777acef7b5707d1 | 4,138 | cpp | C++ | src/util/Screenshotter.cpp | dat14jpe/mulen | 33beeb8a38e5556ddd44efba909e18aab9a3d401 | [
"MIT"
] | 5 | 2020-01-15T12:49:45.000Z | 2021-11-24T05:15:59.000Z | src/util/Screenshotter.cpp | dat14jpe/mulen | 33beeb8a38e5556ddd44efba909e18aab9a3d401 | [
"MIT"
] | null | null | null | src/util/Screenshotter.cpp | dat14jpe/mulen | 33beeb8a38e5556ddd44efba909e18aab9a3d401 | [
"MIT"
] | null | null | null | #include "Screenshotter.hpp"
#include "GLObject.hpp"
#include "lodepng.h"
#include <iostream>
namespace Util {
Screenshotter::Screenshotter()
: thread{ &Screenshotter::Thread, this }
{
}
Screenshotter::~Screenshotter()
{
{
std::lock_guard<std::mutex> lk(m);
done = true;
}
cv.notify_one();
thread.join();
}
void Screenshotter::Thread()
{
while (true)
{
std::unique_ptr<Job> job;
{
std::unique_lock<std::mutex> lk(m);
cv.wait(lk, [&] { return done || jobs.size(); });
if (done) break;
job = std::move(jobs.front());
jobs.pop();
}
Save(*job);
}
}
void Screenshotter::TakeScreenshot(const std::string& filename, glm::uvec2 size, KeyValuePairs&& keyValuePairs)
{
// - to do: reuse job objects (there's little need for dynamic allocation all the time)
std::unique_ptr<Job> job(new Job{});
job->keyValuePairs = keyValuePairs;
job->size = size;
auto& image = job->image;
auto& channels = job->channels = 3u;
image.resize(size.x * size.y * channels);
// Retrieve from OpenGL buffer.
//glBindFramebuffer(GL_FRAMEBUFFER, 0u);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glReadPixels(0, 0, size.x, size.y, channels == 4u ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, image.data());
{
std::lock_guard<std::mutex> lk(m);
jobs.push(std::move(job));
auto& job = jobs.back();
job->filename = filename;
}
cv.notify_one();
}
void Screenshotter::Save(Job& job)
{
auto& image = job.image;
auto& size = job.size;
auto& channels = job.channels;
// Reverse vertically.
for (auto y = 0u; y < size.y / 2u; ++y)
{
for (auto x = 0u; x < size.x; ++x)
{
for (auto c = 0u; c < channels; ++c)
{
auto i0 = (y * size.x + x) * channels + c;
auto i1 = ((size.y - 1u - y) * size.x + x) * channels + c;
auto temp = image[i0];
image[i0] = image[i1];
image[i1] = temp;
}
}
}
// Encode and save PNG.
// - to do: possibly do this in another thread instead
std::vector<unsigned char> png;
lodepng::State state;
if (false) // - to do: make this configurable
{
// Aim for best compression.
state.encoder.filter_palette_zero = 0; //We try several filter types, including zero, allow trying them all on palette images too.
state.encoder.add_id = false; //Don't add LodePNG version chunk to save more bytes
state.encoder.text_compression = 1; //Not needed because we don't add text chunks, but this demonstrates another optimization setting
state.encoder.zlibsettings.nicematch = 258; //Set this to the max possible, otherwise it can hurt compression
state.encoder.zlibsettings.lazymatching = 1; //Definitely use lazy matching for better compression
state.encoder.zlibsettings.windowsize = 32768; //Use maximum possible window size for best compression
}
// Set up colour types.
state.info_png.color.colortype = LCT_RGB;
state.info_png.color.bitdepth = 8;
state.info_raw.colortype = LCT_RGB;
state.info_raw.bitdepth = 8;
state.encoder.auto_convert = 0;
// Add custom data (key/value strings).
for (auto entry : job.keyValuePairs)
{
lodepng_add_text(&state.info_png, entry.first.c_str(), entry.second.c_str());
}
unsigned error = lodepng::encode(png, image, size.x, size.y, state);
if (!error) lodepng::save_file(png, job.filename.c_str());
if (error) std::cout << "PNG encoder error " << error << ": " << lodepng_error_text(error) << std::endl;
}
}
| 34.483333 | 145 | 0.545191 | dat14jpe |
63230a259fe05b0d4ae620550ca29fcd2de20843 | 313 | cpp | C++ | src/mainApp.cpp | ChayanonPitak/Uics | 0d78f57adcb779aebced8088057555be7def78dc | [
"MIT"
] | 1 | 2021-03-14T07:25:40.000Z | 2021-03-14T07:25:40.000Z | src/mainApp.cpp | ChayanonPitak/Uics | 0d78f57adcb779aebced8088057555be7def78dc | [
"MIT"
] | 13 | 2021-02-21T14:53:19.000Z | 2021-03-18T15:52:51.000Z | src/mainApp.cpp | ChayanonPitak/Uics | 0d78f57adcb779aebced8088057555be7def78dc | [
"MIT"
] | 1 | 2021-07-03T04:36:04.000Z | 2021-07-03T04:36:04.000Z | #include "mainApp.h"
#include "mainFrame.h"
#include <wx/wxprec.h>
wxIMPLEMENT_APP(mainApp);
bool mainApp::OnInit()
{
wxInitAllImageHandlers();
mainFrame* _mainFrame = new mainFrame();
_mainFrame->SetIcons(wxIconBundle("..\\resources\\icon.png", wxBITMAP_TYPE_PNG));
_mainFrame->Show(true);
return true;
} | 20.866667 | 82 | 0.738019 | ChayanonPitak |
63230eb064852458e2ae1afa5b139f4557eedace | 898 | cpp | C++ | src/main.cpp | jklee95/PBDEnergyProjection | 8608e2428d1e84fe129c28b1410940d6c66f85bb | [
"MIT"
] | 1 | 2022-01-25T07:26:24.000Z | 2022-01-25T07:26:24.000Z | src/main.cpp | jklee95/PBDEnergyProjection | 8608e2428d1e84fe129c28b1410940d6c66f85bb | [
"MIT"
] | null | null | null | src/main.cpp | jklee95/PBDEnergyProjection | 8608e2428d1e84fe129c28b1410940d6c66f85bb | [
"MIT"
] | null | null | null | #pragma once
// Console window is displayed in debug mode.
#ifdef _DEBUG
#pragma comment(linker, "/entry:WinMainCRTStartup /subsystem:console")
#endif
#include "SimulationManager.h" // This includes Win32App.h
using namespace DXViewer::xmint3;
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance, PSTR cmdLine, int showCmd)
{
int x = 8;
int y = 16;
float dt = 0.01f;
SimulationManager* sim = new SimulationManager(x, y, dt);
DX12App* dxapp = new DX12App();
dxapp->setCameraProperties(
PROJ::ORTHOGRAPHIC,
static_cast<float>(max_element(sim->iGetObjectCount())) * 0.015f,
2.0f, 0.0f, 0.0f);
dxapp->setBackgroundColor(DirectX::Colors::Black);
Win32App winApp(500, 500);
winApp.setWinName(L"PBD Energy Projection");
winApp.setWinOffset(400, 200);
winApp.initialize(hInstance, dxapp, sim);
return winApp.run();
} | 28.0625 | 90 | 0.694878 | jklee95 |
632435e2806fcbfa4fc92254289c0fee4a01762b | 5,269 | hpp | C++ | include/base_pxfoundations/foundation/PsSortInternals.hpp | DeanoC/base_pxfoundations | 8150e24a606b184781bf1552e09f17c03e67e501 | [
"BSD-3-Clause"
] | null | null | null | include/base_pxfoundations/foundation/PsSortInternals.hpp | DeanoC/base_pxfoundations | 8150e24a606b184781bf1552e09f17c03e67e501 | [
"BSD-3-Clause"
] | null | null | null | include/base_pxfoundations/foundation/PsSortInternals.hpp | DeanoC/base_pxfoundations | 8150e24a606b184781bf1552e09f17c03e67e501 | [
"BSD-3-Clause"
] | null | null | null | //
// 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 NVIDIA 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 THE COPYRIGHT HOLDERS ``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.
//
// Copyright (c) 2008-2019 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PSFOUNDATION_PSSORTINTERNALS_H
#define PSFOUNDATION_PSSORTINTERNALS_H
/** \addtogroup foundation
@{
*/
#include "foundation/PxAssert.h"
#include "foundation/PxIntrinsics.h"
#include "PsBasicTemplates.h"
#include "PsUserAllocated.h"
namespace physx {
namespace shdfnd {
namespace internal {
template<class T, class Predicate>
PX_INLINE void median3(T *elements, int32_t first, int32_t last, Predicate &compare) {
/*
This creates sentinels because we know there is an element at the start minimum(or equal)
than the pivot and an element at the end greater(or equal) than the pivot. Plus the
median of 3 reduces the chance of degenerate behavour.
*/
int32_t mid = (first + last) / 2;
if (compare(elements[mid], elements[first]))
swap(elements[first], elements[mid]);
if (compare(elements[last], elements[first]))
swap(elements[first], elements[last]);
if (compare(elements[last], elements[mid]))
swap(elements[mid], elements[last]);
// keep the pivot at last-1
swap(elements[mid], elements[last - 1]);
}
template<class T, class Predicate>
PX_INLINE int32_t
partition(T
* elements,
int32_t first, int32_t
last,
Predicate &compare
) {
median3(elements, first, last, compare
);
/*
WARNING: using the line:
T partValue = elements[last-1];
and changing the scan loops to:
while(comparator.greater(partValue, elements[++i]));
while(comparator.greater(elements[--j], partValue);
triggers a compiler optimizer bug on xenon where it stores a double to the stack for partValue
then loads it as a single...:-(
*/
int32_t i = first; // we know first is less than pivot(but i gets pre incremented)
int32_t j = last - 1; // pivot is in last-1 (but j gets pre decremented)
for(;;) {
while(
compare(elements[++i], elements[last - 1]
));
while(
compare(elements[last - 1], elements[--j]
));
if(i >= j)
break;
PX_ASSERT(i
<=
last &&j
>= first);
swap(elements[i], elements[j]
);
}
// put the pivot in place
PX_ASSERT(i
<=
last &&first
<= (last - 1));
swap(elements[i], elements[last - 1]
);
return
i;
}
template<class T, class Predicate>
PX_INLINE void smallSort(T *elements, int32_t first, int32_t last, Predicate &compare) {
// selection sort - could reduce to fsel on 360 with floats.
for (int32_t i = first; i < last; i++) {
int32_t m = i;
for (int32_t j = i + 1; j <= last; j++)
if (compare(elements[j], elements[m]))
m = j;
if (m != i)
swap(elements[m], elements[i]);
}
}
template<class Allocator>
class Stack {
Allocator mAllocator;
uint32_t mSize, mCapacity;
int32_t *mMemory;
bool mRealloc;
public:
Stack(int32_t *memory, uint32_t capacity, const Allocator &inAllocator)
: mAllocator(inAllocator), mSize(0), mCapacity(capacity), mMemory(memory), mRealloc(false) {
}
~Stack() {
if (mRealloc)
mAllocator.deallocate(mMemory);
}
void grow() {
mCapacity *= 2;
int32_t *newMem =
reinterpret_cast<int32_t *>(mAllocator.allocate(sizeof(int32_t) * mCapacity, __FILE__, __LINE__));
intrinsics::memCopy(newMem, mMemory, mSize * sizeof(int32_t));
if (mRealloc)
mAllocator.deallocate(mMemory);
mRealloc = true;
mMemory = newMem;
}
PX_INLINE void push(int32_t start, int32_t end) {
if (mSize >= mCapacity - 1)
grow();
mMemory[mSize++] = start;
mMemory[mSize++] = end;
}
PX_INLINE void pop(int32_t &start, int32_t &end) {
PX_ASSERT(!empty());
end = mMemory[--mSize];
start = mMemory[--mSize];
}
PX_INLINE bool empty() {
return mSize == 0;
}
};
} // namespace internal
} // namespace shdfnd
} // namespace physx
#endif // #ifndef PSFOUNDATION_PSSORTINTERNALS_H
| 27.442708 | 102 | 0.719681 | DeanoC |
632dce8665923163268a3209671695bfc84a2064 | 448 | cc | C++ | Semaphore.cc | mjhough/shopify-scraper | eeddd252881bd0d53eae0ab67c98d5f871f10dff | [
"MIT"
] | 2 | 2020-02-22T09:28:31.000Z | 2020-08-27T12:26:35.000Z | Semaphore.cc | mjhough/shopify-scraper | eeddd252881bd0d53eae0ab67c98d5f871f10dff | [
"MIT"
] | null | null | null | Semaphore.cc | mjhough/shopify-scraper | eeddd252881bd0d53eae0ab67c98d5f871f10dff | [
"MIT"
] | 1 | 2022-01-25T07:15:23.000Z | 2022-01-25T07:15:23.000Z | #include "Semaphore.h"
Semaphore::Semaphore(int count) {
this->count = count;
}
void Semaphore::post() {
std::unique_lock<std::mutex> lock(mtx);
count++;
cv.notify_one();
}
void Semaphore::wait() {
std::unique_lock<std::mutex> lock(mtx);
while(count == 0) {
cv.wait(lock);
}
count--;
}
bool Semaphore::try_wait() {
std::unique_lock<std::mutex> lock(mtx);
if (count) {
count--;
return true;
}
return false;
}
| 15.448276 | 41 | 0.613839 | mjhough |
63306eab4231ddadc694dd8465a9771f2e866cdf | 2,928 | cpp | C++ | Button.cpp | alejandrocoria/MinerDisplay | e333c0d352965edf0d98024db254384e1f553314 | [
"MIT"
] | null | null | null | Button.cpp | alejandrocoria/MinerDisplay | e333c0d352965edf0d98024db254384e1f553314 | [
"MIT"
] | null | null | null | Button.cpp | alejandrocoria/MinerDisplay | e333c0d352965edf0d98024db254384e1f553314 | [
"MIT"
] | null | null | null | #include "Button.h"
#include <SFML/Graphics/RenderTarget.hpp>
#include <cmath>
Button::Button(const sf::Font* font):
font(font) {
text.setCharacterSize(16);
text.setFont(*font);
}
void Button::processEvents(const sf::Event& event) {
switch (event.type) {
case sf::Event::MouseButtonPressed:
if (rectangle.getGlobalBounds().contains(event.mouseButton.x, event.mouseButton.y)) {
setSate(State::Pressed);
} else {
setSate(State::Normal);
}
break;
case sf::Event::MouseButtonReleased:
if (rectangle.getGlobalBounds().contains(event.mouseButton.x, event.mouseButton.y)) {
if (state == State::Pressed) {
setSate(State::Hovered);
if (callback) {
callback();
}
}
} else {
setSate(State::Normal);
}
break;
case sf::Event::MouseMoved:
if (rectangle.getGlobalBounds().contains(event.mouseMove.x, event.mouseMove.y)) {
if (state == State::Normal) {
setSate(State::Hovered);
}
} else {
if (state == State::Hovered) {
setSate(State::Normal);
}
}
break;
default:
break;
}
}
void Button::setText(const sf::String& text) {
this->text.setString(text);
dirty = true;
}
void Button::setColors(sf::Color normal, sf::Color hovered, sf::Color pressed, sf::Color text) {
this->normal = normal;
this->hovered = hovered;
this->pressed = pressed;
this->text.setFillColor(text);
updateRectangleColor();
}
void Button::setSize(sf::Vector2f size) {
this->size = size;
dirty = true;
}
void Button::setPosition(sf::Vector2f position) {
this->position = position;
dirty = true;
}
void Button::setCallback(std::function<void()> fn) {
callback = std::move(fn);
}
void Button::draw(sf::RenderTarget& target, sf::RenderStates states) const {
if (dirty) {
dirty = false;
sf::Vector2f center = position + size / 2.f;
rectangle.setPosition(position);
rectangle.setSize(size);
text.setPosition({std::round(center.x - text.getGlobalBounds().width / 2.f), std::round(center.y - 10.f)});
}
target.draw(rectangle, states);
target.draw(text, states);
}
void Button::setSate(State newState) {
if (newState == state) {
return;
}
state = newState;
updateRectangleColor();
}
void Button::updateRectangleColor() {
if (state == State::Normal) {
rectangle.setFillColor(normal);
} else if (state == State::Hovered) {
rectangle.setFillColor(hovered);
} else if (state == State::Pressed) {
rectangle.setFillColor(pressed);
}
}
| 26.378378 | 115 | 0.557036 | alejandrocoria |
6333522daaeb66929f021a8c92aa2286f05b56a5 | 744 | cpp | C++ | July LeetCode Challenge/Day_22.cpp | mishrraG/100DaysOfCode | 3358af290d4f05889917808d68b95f37bd76e698 | [
"MIT"
] | 13 | 2020-08-10T14:06:37.000Z | 2020-09-24T14:21:33.000Z | July LeetCode Challenge/Day_22.cpp | mishrraG/DaysOfCP | 3358af290d4f05889917808d68b95f37bd76e698 | [
"MIT"
] | null | null | null | July LeetCode Challenge/Day_22.cpp | mishrraG/DaysOfCP | 3358af290d4f05889917808d68b95f37bd76e698 | [
"MIT"
] | 1 | 2020-05-31T21:09:14.000Z | 2020-05-31T21:09:14.000Z | class Solution {
public:
vector<vector<int> > zigzagLevelOrder(TreeNode* root) {
if (root == NULL) {
return vector<vector<int> > ();
}
vector<vector<int> > result;
queue<TreeNode*> nodesQueue;
nodesQueue.push(root);
bool leftToRight = true;
while ( !nodesQueue.empty()) {
int size = nodesQueue.size();
vector<int> row(size);
for (int i = 0; i < size; i++) {
TreeNode* node = nodesQueue.front();
nodesQueue.pop();
int index = (leftToRight) ? i : (size - 1 - i);
row[index] = node->val;
if (node->left) {
nodesQueue.push(node->left);
}
if (node->right) {
nodesQueue.push(node->right);
}
}
leftToRight = !leftToRight;
result.push_back(row);
}
return result;
}
}; | 22.545455 | 56 | 0.596774 | mishrraG |
63353bcc292e4c3ab006782fb536e8cb6f3b157f | 196,967 | cpp | C++ | source/D2Common/src/Items/Items.cpp | raumuongluoc/D2MOO | 169de1bd24151cda4c654ef0f8027896a14552ec | [
"MIT"
] | 1 | 2022-03-20T12:12:15.000Z | 2022-03-20T12:12:15.000Z | source/D2Common/src/Items/Items.cpp | raumuongluoc/D2MOO | 169de1bd24151cda4c654ef0f8027896a14552ec | [
"MIT"
] | null | null | null | source/D2Common/src/Items/Items.cpp | raumuongluoc/D2MOO | 169de1bd24151cda4c654ef0f8027896a14552ec | [
"MIT"
] | 1 | 2022-03-20T12:12:18.000Z | 2022-03-20T12:12:18.000Z | #include "D2Items.h"
#include <Units/Item.h>
#include "D2BitManip.h"
#include "D2Composit.h"
#include "D2DataTbls.h"
#include "D2Inventory.h"
#include "D2ItemMods.h"
#include "D2QuestRecord.h"
#include "D2Seed.h"
#include "D2States.h"
#include "D2StatList.h"
#include "Units/Units.h"
#include <D2CMP.h>
#include <DataTbls/MonsterIds.h>
//D2Common.0x6FD98380 (#10687)
void __stdcall ITEMS_AllocItemData(void* pMemPool, D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItem->pItemData = (D2ItemDataStrc*)FOG_AllocServerMemory(pMemPool, sizeof(D2ItemDataStrc), __FILE__, __LINE__, 0);
if (!pItem->pItemData)
{
//FOG_10024_PacketAssertion("Out of Memory in ITEMSDataInit()", __FILE__, __LINE__);
exit(-1);
}
memset(pItem->pItemData, 0x00, sizeof(D2ItemDataStrc));
pItem->pItemData->dwOwnerGUID = -1;
}
}
//D2Common.0x6FD983F0 (#10688)
void __stdcall ITEMS_FreeItemData(void* pMemPool, D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
INVENTORY_RemoveItem(pItem);
if (pItem->pItemData)
{
FOG_FreeServerMemory(pMemPool, pItem->pItemData, __FILE__, __LINE__, 0);
}
}
}
//D2Common.0x6FD98430 (#10689)
uint8_t __stdcall ITEMS_GetBodyLocation(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->nBodyLoc;
}
return BODYLOC_NONE;
}
//D2Common.0x6FD98450 (#10690)
void __stdcall ITEMS_SetBodyLocation(D2UnitStrc* pItem, uint8_t nBodyLoc)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
if (pItem->pItemData)
{
pItem->pItemData->nBodyLoc = nBodyLoc;
}
}
}
//D2Common.0x6FD98470 (#10691)
D2SeedStrc* __stdcall ITEMS_GetItemSeed(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return &pItem->pItemData->pSeed;
}
return NULL;
}
//D2Common.0x6FD98490 (#10692)
void __stdcall ITEMS_InitItemSeed(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
SEED_InitSeed(&pItem->pItemData->pSeed);
}
}
//D2Common.0x6FD984B0 (#10693)
int __stdcall ITEMS_GetItemStartSeed(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->dwInitSeed;
}
return 0;
}
//D2Common.0x6FD984D0 (#10694)
void __stdcall ITEMS_SetItemStartSeed(D2UnitStrc* pItem, int nSeed)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
D2_ASSERT(pItem->pItemData);
pItem->pItemData->dwInitSeed = nSeed;
}
//D2Common.0x6FD98550 (#10695)
int __stdcall ITEMS_GetItemQuality(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->dwQualityNo;
}
return ITEMQUAL_NORMAL;
}
//D2Common.0x6FD98580 (#10696)
void __stdcall ITEMS_SetItemQuality(D2UnitStrc* pItem, int nQuality)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
pItem->pItemData->dwQualityNo = nQuality;
}
}
//D2Common.0x6FD985A0 (#10699)
uint16_t __stdcall ITEMS_GetPrefixId(D2UnitStrc* pItem, int nPrefixNo)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->wMagicPrefix[nPrefixNo];
}
return 0;
}
//D2Common.0x6FD985D0 (#10700)
void __stdcall ITEMS_AssignPrefix(D2UnitStrc* pItem, uint16_t nPrefix, int nPrefixNo)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
pItem->pItemData->wMagicPrefix[nPrefixNo] = nPrefix;
}
}
//D2Common.0x6FD98600 (#10697)
uint16_t __stdcall ITEMS_GetAutoAffix(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->wAutoAffix;
}
return 0;
}
//D2Common.0x6FD98630 (#10698)
void __stdcall ITEMS_SetAutoAffix(D2UnitStrc* pItem, uint16_t nAffix)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
pItem->pItemData->wAutoAffix = nAffix;
}
}
//D2Common.0x6FD98650 (#10701)
uint16_t __stdcall ITEMS_GetSuffixId(D2UnitStrc* pItem, int nSuffixNo)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->wMagicSuffix[nSuffixNo];
}
return 0;
}
//D2Common.0x6FD98680 (#10702)
void __stdcall ITEMS_AssignSuffix(D2UnitStrc* pItem, uint16_t nSuffix, int nSuffixNo)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
pItem->pItemData->wMagicSuffix[nSuffixNo] = nSuffix;
}
}
//D2Common.0x6FD986B0 (#10703)
uint16_t __stdcall ITEMS_GetRarePrefixId(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->wRarePrefix;
}
return 0;
}
//D2Common.0x6FD986E0 (#10704)
void __stdcall ITEMS_AssignRarePrefix(D2UnitStrc* pItem, uint16_t nPrefix)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
pItem->pItemData->wRarePrefix = nPrefix;
}
}
//D2Common.0x6FD98700 (#10705)
uint16_t __stdcall ITEMS_GetRareSuffixId(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->wRareSuffix;
}
return 0;
}
//D2Common.0x6FD98730 (#10706)
void __stdcall ITEMS_AssignRareSuffix(D2UnitStrc* pItem, uint16_t nSuffix)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
pItem->pItemData->wRareSuffix = nSuffix;
}
}
//D2Common.0x6FD98750 (#10707)
BOOL __stdcall ITEMS_CheckItemFlag(D2UnitStrc* pItem, uint32_t dwFlag, int nLine, char* szFile)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->dwItemFlags & dwFlag;
}
return 0;
}
//D2Common.0x6FD98780 (#10708)
void __stdcall ITEMS_SetItemFlag(D2UnitStrc* pItem, uint32_t dwFlag, BOOL bSet)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
if (bSet)
{
pItem->pItemData->dwItemFlags |= dwFlag;
}
else
{
pItem->pItemData->dwItemFlags &= ~dwFlag;
}
}
}
//D2Common.0x6FD987C0 (#10709)
uint32_t __stdcall ITEMS_GetItemFlags(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->dwItemFlags;
}
return 0;
}
//D2Common.0x6FD987E0 (#10710)
BOOL __stdcall ITEMS_CheckItemCMDFlag(D2UnitStrc* pItem, int nFlag)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->dwCommandFlags & nFlag;
}
return 0;
}
//D2Common.0x6FD98810 (#10711)
void __stdcall ITEMS_SetItemCMDFlag(D2UnitStrc* pItem, int nFlag, BOOL bSet)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
if (bSet)
{
pItem->pItemData->dwCommandFlags |= nFlag;
}
else
{
pItem->pItemData->dwCommandFlags &= ~nFlag;
}
}
}
//D2Common.0x6FD98850 (#10712)
uint32_t __stdcall ITEMS_GetItemCMDFlags(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->dwCommandFlags;
}
return 0;
}
//D2Common.0x6FD98870 (#10717)
int __stdcall ITEMS_GetItemLevel(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
if (pItem->pItemData->dwItemLevel < 1)
{
pItem->pItemData->dwItemLevel = 1;
}
return pItem->pItemData->dwItemLevel;
}
return 1;
}
//D2Common.0x6FD988B0 (#10718)
void __stdcall ITEMS_SetItemLevel(D2UnitStrc* pItem, int nItemLevel)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
if (nItemLevel < 1)
{
nItemLevel = 1;
}
pItem->pItemData->dwItemLevel = nItemLevel;
}
}
//D2Common.0x6FD988E0 (#10719)
uint8_t __stdcall ITEMS_GetInvPage(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->nInvPage;
}
return -1;
}
//D2Common.0x6FD98900 (#10720)
void __stdcall ITEMS_SetInvPage(D2UnitStrc* pItem, uint8_t nPage)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
pItem->pItemData->nInvPage = nPage;
}
}
//D2Common.0x6FD98920 (#10721)
uint8_t __stdcall ITEMS_GetCellOverlap(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->nCellOverlap;
}
return -1;
}
//D2Common.0x6FD98940 (#10722)
void __stdcall ITEMS_SetCellOverlap(D2UnitStrc* pItem, int nCellOverlap)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
pItem->pItemData->nCellOverlap = nCellOverlap;
}
}
//D2Common.0x6FD98960 (#10853)
uint8_t __stdcall ITEMS_GetItemCell(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->nItemCell;
}
return -1;
}
//D2Common.0x6FD98980 (#10854)
void __stdcall ITEMS_SetItemCell(D2UnitStrc* pItem, int nItemCell)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
pItem->pItemData->nItemCell = nItemCell;
}
}
//D2Common.0x6FD989A0 (#10723)
char* __stdcall ITEMS_GetEarName(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->szPlayerName;
}
return NULL;
}
//D2Common.0x6FD989C0 (#10724)
void __stdcall ITEMS_SetEarName(D2UnitStrc* pItem, char* szName)
{
int nCounter = 0;
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
do
{
pItem->pItemData->szPlayerName[nCounter] = szName[nCounter];
++nCounter;
}
while (szName[nCounter -1]);
}
}
//D2Common.0x6FD989F0 (#10725)
uint8_t __stdcall ITEMS_GetEarLevel(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->nEarLvl;
}
return 1;
}
//D2Common.0x6FD98A10 (#10726)
void __stdcall ITEMS_SetEarLevel(D2UnitStrc* pItem, uint8_t nLevel)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
pItem->pItemData->nEarLvl = nLevel;
}
}
//D2Common.0x6FD98A30 (#10727)
uint8_t __stdcall ITEMS_GetVarGfxIndex(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->nInvGfxIdx;
}
return 0;
}
//D2Common.0x6FD98A50 (#10728)
void __stdcall ITEMS_SetVarGfxIndex(D2UnitStrc* pItem, uint8_t nIndex)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
pItem->pItemData->nInvGfxIdx = nIndex;
}
}
//D2Common.0x6FD98A70 (#10777)
BOOL __stdcall ITEMS_IsRepairable(D2UnitStrc* pItem)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
int nItemType = 0;
int nCounter = 0;
int nStats = 0;
D2StatStrc pStat[64] = {};
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData && pItem->pItemData->dwItemFlags & IFLAG_IDENTIFIED && !(pItem->pItemData->dwItemFlags & IFLAG_ETHEREAL))
{
nStats = D2Common_11270(pItem, STAT_ITEM_CHARGED_SKILL, pStat, ARRAY_SIZE(pStat));
if (nStats > 0)
{
while ((uint8_t)pStat[nCounter].nValue >= (pStat[nCounter].nValue >> 8))
{
++nCounter;
if (nCounter >= nStats)
{
break;
}
}
if (nCounter < nStats)
{
return TRUE;
}
}
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] < 0)
{
return FALSE;
}
if (pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord && pItemTypesTxtRecord->nRepair)
{
nItemType = ITEMS_GetItemTypeFromItemId(pItem->dwClassId);
if (nItemType < 0)
{
if (!pItemsTxtRecord->nNoDurability && pItemsTxtRecord->nDurability && STATLIST_GetMaxDurabilityFromUnit(pItem) && STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_INDESCTRUCTIBLE, 0) <= 0)
{
return TRUE;
}
return FALSE;
}
if (nItemType < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[nItemType];
if (pItemTypesTxtRecord && pItemTypesTxtRecord->nRepair)
{
if (ITEMS_CheckItemTypeIfThrowable(ITEMS_GetItemType(pItem)) && ITEMS_CheckIfStackable(pItem) && !ITEMS_CheckItemFlag(pItem, IFLAG_ETHEREAL, __LINE__, __FILE__))
{
return TRUE;
}
}
}
if (!pItemsTxtRecord->nNoDurability && pItemsTxtRecord->nDurability && STATLIST_GetMaxDurabilityFromUnit(pItem) && STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_INDESCTRUCTIBLE, 0) <= 0)
{
return TRUE;
}
}
}
}
return FALSE;
}
//D2Common.0x6FD98C60 (#10780)
uint32_t __stdcall ITEMS_GetAmmoTypeFromItemType(int nItemType)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
if (nItemType >= 0 && nItemType < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[nItemType];
if (pItemTypesTxtRecord)
{
return pItemTypesTxtRecord->wShoots;
}
}
return 0;
}
//D2Common.0x6FD98CA0 (#10781)
uint32_t __stdcall ITEMS_GetAmmoType(D2UnitStrc* pItem)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return ITEMS_GetAmmoTypeFromItemType(pItemsTxtRecord->wType[0]);
}
return 0;
}
//D2Common.0x6FD98D20 (#10782)
uint32_t __stdcall ITEMS_GetQuiverTypeFromItemType(int nItemType)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
if (nItemType >= 0 && nItemType < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[nItemType];
if (pItemTypesTxtRecord)
{
return pItemTypesTxtRecord->wQuiver;
}
}
return 0;
}
//D2Common.0x6FD98D60 (#10783)
uint32_t __stdcall ITEMS_GetQuiverType(D2UnitStrc* pItem)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return ITEMS_GetQuiverTypeFromItemType(pItemsTxtRecord->wType[0]);
}
return 0;
}
//D2Common.0x6FD98DE0 (#10784)
uint32_t __stdcall ITEMS_GetAutoStackFromItemType(int nItemType)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
if (nItemType >= 0 && nItemType < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[nItemType];
{
return pItemTypesTxtRecord->nAutoStack;
}
}
return 0;
}
//D2Common.0x6FD98E20 (#10785)
uint32_t __stdcall ITEMS_GetAutoStack(D2UnitStrc* pItem)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return ITEMS_GetAutoStackFromItemType(pItemsTxtRecord->wType[0]);
}
return 0;
}
//D2Common.0x6FD98EA0 (#10786)
uint32_t __stdcall ITEMS_GetReload(D2UnitStrc* pItem)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord)
{
return pItemTypesTxtRecord->nReload;
}
}
}
return 0;
}
//D2Common.0x6FD98F20 (#10787)
uint32_t __stdcall ITEMS_GetReEquip(D2UnitStrc* pItem)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord)
{
return pItemTypesTxtRecord->nReEquip;
}
}
}
return 0;
}
//D2Common.0x6FD98FA0 (#10788)
uint8_t __stdcall ITEMS_GetStorePage(D2UnitStrc* pItem)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord)
{
return pItemTypesTxtRecord->nStorePage;
}
}
}
return -1;
}
//D2Common.0x6FD99020 (#10789)
uint8_t __stdcall ITEMS_GetVarInvGfxCount(D2UnitStrc* pItem)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord)
{
return pItemTypesTxtRecord->nVarInvGfx;
}
}
}
return 0;
}
//D2Common.0x6FD990A0 (#10790)
char* __stdcall ITEMS_GetVarInvGfxString(D2UnitStrc* pItem, int nId)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord)
{
if (nId < 0)
{
nId = 0;
}
if (nId >= pItemTypesTxtRecord->nVarInvGfx - 1)
{
nId = pItemTypesTxtRecord->nVarInvGfx - 1;
}
return pItemTypesTxtRecord->szInvGfx[nId];
}
}
}
return &sgptDataTables->szDefaultString;
}
//D2Common.0x6FD99140 (#10792)
BOOL __stdcall ITEMS_CanBeRare(D2UnitStrc* pItem)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord)
{
return pItemTypesTxtRecord->nRare;
}
}
}
return 0;
}
//D2Common.0x6FD991C0 (#10791)
BOOL __stdcall ITEMS_CanBeMagic(D2UnitStrc* pItem)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord)
{
return pItemTypesTxtRecord->nMagic;
}
}
}
return 0;
}
//D2Common.0x6FD99240 (#10793)
BOOL __stdcall ITEMS_CanBeNormal(D2UnitStrc* pItem)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord)
{
return pItemTypesTxtRecord->nNormal;
}
}
}
return 0;
}
//D2Common.0x6FD992C0 (#10744)
uint32_t __stdcall ITEMS_GetWeaponClassCode(D2UnitStrc* pItem)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (pItemsTxtRecord)
{
return pItemsTxtRecord->dwWeapClass;
}
}
return 0;
}
//D2Common.0x6FD992F0 (#10745)
uint32_t __stdcall ITEMS_Get2HandWeaponClassCode(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->dwWeapClass2Hand;
}
//D2Common.0x6FD99370 (#10746)
uint32_t __stdcall ITEMS_GetBaseCode(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->dwCode;
}
//D2Common.0x6FD993F0 (#10747)
uint32_t __stdcall ITEMS_GetAltGfx(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->dwAlternateGfx)
{
return pItemsTxtRecord->dwAlternateGfx;
}
else
{
return pItemsTxtRecord->dwCode;
}
}
//D2Common.0x6FD99480 (#10748)
uint8_t __stdcall ITEMS_GetComponent(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->nComponent;
}
//D2Common.0x6FD99500 (#10749)
void __stdcall ITEMS_GetDimensions(D2UnitStrc* pItem, uint8_t* pWidth, uint8_t* pHeight, char* szFile, int nLine)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (pItemsTxtRecord)
{
*pWidth = pItemsTxtRecord->nInvWidth;
*pHeight = pItemsTxtRecord->nInvHeight;
}
}
}
//D2Common.0x6FD99540 (#10750)
void __stdcall ITEMS_GetAllowedBodyLocations(D2UnitStrc* pItem, uint8_t* pBodyLoc1, uint8_t* pBodyLoc2)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord)
{
*pBodyLoc1 = pItemTypesTxtRecord->nBodyLoc1;
*pBodyLoc2 = pItemTypesTxtRecord->nBodyLoc2;
return;
}
}
}
*pBodyLoc1 = 0;
*pBodyLoc2 = 0;
}
//D2Common.0x6FD995D0 (#10751)
uint32_t __stdcall ITEMS_GetItemType(D2UnitStrc* pItem)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
D2_ASSERT(pItem);
if (pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->wType[0];
}
return 0;
}
//D2Common.0x6FD99640 (#10752)
uint32_t __stdcall ITEMS_GetItemTypeFromItemId(uint32_t dwItemId)
{
D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(dwItemId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->wType[0];
}
//D2Common.0x6FD99680 (#10753)
uint8_t __stdcall ITEMS_GetItemQlvl(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->nLevel;
}
//D2Common.0x6FD99700 (#10754)
int __stdcall ITEMS_CheckIfFlagIsSet(int nFlags, int nFlag)
{
return nFlags & nFlag;
}
//D2Common.0x6FD99710 (#10755)
void __stdcall ITEMS_SetOrRemoveFlag(int* pFlags, int nFlag, BOOL bSet)
{
if (bSet)
{
*pFlags |= nFlag;
}
else
{
*pFlags &= ~nFlag;
}
}
static int ITEMS_GetBonusStatFromSockets(D2UnitStrc* pItem, D2C_ItemStats stat)
{
int nStatBonusFromSockets = 0;
if (pItem->dwUnitType == UNIT_ITEM)
{
if (ITEMS_CheckIfSocketableByItemId(pItem->dwClassId))
{
for (D2UnitStrc* i = INVENTORY_GetFirstItem(pItem->pInventory); i != NULL; i = INVENTORY_GetNextItem(i))
{
i = INVENTORY_UnitIsItem(i);
if (pItem->dwAnimMode == IMODE_EQUIP)
{
nStatBonusFromSockets += STATLIST_GetUnitStatUnsigned(i, stat, 0);
}
}
}
}
return nStatBonusFromSockets;
}
static bool ITEMS_CheckStatRequirement(D2UnitStrc* pItem, D2UnitStrc* pUnit, D2C_ItemStats stat, BOOL bEquipping, int nStatWithPctBonus)
{
BOOL bStatReqMet = FALSE;
const int nUnitStat = STATLIST_GetUnitStatUnsigned(pUnit, stat, 0);
if (nUnitStat > 0 && nUnitStat >= nStatWithPctBonus)
{
bStatReqMet = TRUE;
// Note: Owner was not checked in the original game for STAT_DEXTERITY
if (bEquipping && STATLIST_GetOwner(pItem, 0))
{
const int nStatBonusFromSockets = ITEMS_GetBonusStatFromSockets(pItem, stat);
if ((nUnitStat - nStatBonusFromSockets) <= 0 || (nUnitStat - nStatBonusFromSockets) < nStatWithPctBonus)
{
bStatReqMet = FALSE;
}
}
}
return bStatReqMet;
}
//D2Common.0x6FD99740 (#10756)
BOOL __stdcall ITEMS_CheckRequirements(D2UnitStrc* pItem, D2UnitStrc* pUnit, BOOL bEquipping, BOOL* bStrength, BOOL* bDexterity, BOOL* bLevel)
{
if (bStrength)
{
*bStrength = FALSE;
}
if (bDexterity)
{
*bDexterity = FALSE;
}
if (bLevel)
{
*bLevel = FALSE;
}
if (pItem == NULL || pItem->dwUnitType != UNIT_ITEM)
{
return FALSE;
}
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (!pItemsTxtRecord)
{
return FALSE;
}
BOOL bIdentified = FALSE;
const D2ItemDataStrc* pItemData = pItem->pItemData;
if (pItemData)
{
bIdentified = pItemData->dwItemFlags & IFLAG_IDENTIFIED;
}
else
{
bIdentified = FALSE;
}
const int nBaseReqStr = pItemsTxtRecord->wReqStr;
const int nBaseReqDex = pItemsTxtRecord->wReqDex;
int nReqStrBonus = 0;
int nReqDexBonus = 0;
if (int nReqPctBonus = STATLIST_GetUnitStatSigned(pItem, STAT_ITEM_REQ_PERCENT, 0))
{
// It seems the original game has some additional logic to handle overflow here
nReqStrBonus = nBaseReqStr * int64_t(nReqPctBonus) / 100;
nReqDexBonus = nBaseReqDex * int64_t(nReqPctBonus) / 100;
}
if (pItemData && pItemData->dwItemFlags & IFLAG_ETHEREAL)
{
nReqStrBonus -= 10;
nReqDexBonus -= 10;
}
const BOOL bStrReqMet = ITEMS_CheckStatRequirement(pItem, pUnit, STAT_STRENGTH, bEquipping, nBaseReqStr + nReqStrBonus);
const BOOL bDexReqMet = ITEMS_CheckStatRequirement(pItem, pUnit, STAT_DEXTERITY, bEquipping, nBaseReqDex + nReqDexBonus);
BOOL bLevelReqMet = FALSE;
const int nLevelReq = ITEMS_GetLevelRequirement(pItem, pUnit);
bLevelReqMet = nLevelReq == -1 || STATLIST_GetUnitStatUnsigned(pUnit, STAT_LEVEL, 0) >= nLevelReq;
if (bStrength)
{
*bStrength = bStrReqMet;
}
if (bDexterity)
{
*bDexterity = bDexReqMet;
}
if (bLevel)
{
*bLevel = bLevelReqMet;
}
if (bStrReqMet && bDexReqMet && bLevelReqMet && bIdentified)
{
if (pItemsTxtRecord->wType[0] == ITEMTYPE_BOOK && STATLIST_GetUnitStatUnsigned(pItem, STAT_QUANTITY, 0) <= 0)
{
return FALSE;
}
const int nItemType = ITEMS_GetItemTypeFromItemId(pItem->dwClassId);
const D2ItemTypesTxt* pItemTypesTxtRecord = DATATBLS_GetItemTypesTxtRecord(nItemType);
if (!pItemTypesTxtRecord || pItemTypesTxtRecord->nClass >= NUMBER_OF_PLAYERCLASSES)
{
return TRUE;
}
const int nClassReq = pItemTypesTxtRecord->nClass;
if (!pUnit)
{
return FALSE;
}
if (pUnit->dwUnitType == UNIT_MONSTER && nClassReq == PCLASS_BARBARIAN)
{
const int nMonsterId = pUnit->dwClassId;
if (nMonsterId >= MONSTER_ACT5HIRE1 && nMonsterId <= MONSTER_ACT5HIRE2)
{
return TRUE;
}
}
if (pUnit->dwUnitType == UNIT_PLAYER && nClassReq == pUnit->dwClassId)
{
return TRUE;
}
}
return FALSE;
}
//D2Common.0x6FD99BC0 (#10741)
BOOL __stdcall ITEMS_GetQuestFromItemId(int nItemId)
{
D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(nItemId);
if (ITEMS_CheckItemTypeIdByItemId(nItemId, ITEMTYPE_ANY_ARMOR) || ITEMS_CheckItemTypeIdByItemId(nItemId, ITEMTYPE_WEAPON))
{
if (pItemsTxtRecord->dwUberCode == pItemsTxtRecord->dwCode || pItemsTxtRecord->dwUltraCode == pItemsTxtRecord->dwCode)
{
if (pItemsTxtRecord->wType[0] != ITEMTYPE_MISSILE_POTION)
{
return !pItemsTxtRecord->nQuest;
}
}
}
return 0;
}
//D2Common.0x6FD99C60 (#10742)
BOOL __stdcall ITEMS_GetQuest(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
return ITEMS_GetQuestFromItemId(pItem->dwClassId);
}
//D2Common.0x6FD99D40 (#10743)
uint32_t __stdcall ITEMS_GetNormalCode(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (pItemsTxtRecord->dwNormCode)
{
return pItemsTxtRecord->dwNormCode;
}
else
{
return pItemsTxtRecord->dwCode;
}
}
//D2Common.0x6FD99DB0
int __fastcall ITEMS_GetRequiredLevel(D2UnitStrc* pItem, D2UnitStrc* pPlayer)
{
D2UniqueItemsTxt* pUniqueItemsTxtRecord = NULL;
D2MagicAffixTxt* pAutoAffixTxtRecord = NULL;
D2MagicAffixTxt* pPrefixTxtRecord = NULL;
D2MagicAffixTxt* pSuffixTxtRecord = NULL;
D2SetItemsTxt* pSetItemsTxtRecord = NULL;
D2SkillsTxt* pSkillsTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
int nRequiredLevelForSocketables = 0;
int nRequiredLevelForSkill = 0;
int nLevelRequirement = 0;
int nRequiredLevel = 0;
int nCraftBonus = 0;
D2StatStrc pStat[64] = {};
if (!pItem || pItem->dwUnitType != UNIT_ITEM || !pItem->pItemData)
{
return 0;
}
nRequiredLevel = 0;
switch (pItem->pItemData->dwQualityNo)
{
case ITEMQUAL_MAGIC:
pPrefixTxtRecord = DATATBLS_GetMagicAffixTxtRecord(pItem->pItemData->wMagicPrefix[0]);
pSuffixTxtRecord = DATATBLS_GetMagicAffixTxtRecord(pItem->pItemData->wMagicSuffix[0]);
pAutoAffixTxtRecord = DATATBLS_GetMagicAffixTxtRecord(pItem->pItemData->wAutoAffix);
if (pPrefixTxtRecord)
{
nLevelRequirement = pPrefixTxtRecord->nClass != -1 && pPlayer && pPrefixTxtRecord->nClass == pPlayer->dwClassId ? pPrefixTxtRecord->nClassLevelReq : pPrefixTxtRecord->nLevelReq;
if (nLevelRequirement >= 0)
{
nRequiredLevel = nLevelRequirement;
}
}
if (pSuffixTxtRecord)
{
nLevelRequirement = pSuffixTxtRecord->nClass != -1 && pPlayer && pSuffixTxtRecord->nClass == pPlayer->dwClassId ? pSuffixTxtRecord->nClassLevelReq : pSuffixTxtRecord->nLevelReq;
if (nRequiredLevel <= nLevelRequirement)
{
nRequiredLevel = nLevelRequirement;
}
}
if (pAutoAffixTxtRecord)
{
nLevelRequirement = pAutoAffixTxtRecord->nClass != -1 && pPlayer && pAutoAffixTxtRecord->nClass == pPlayer->dwClassId ? pAutoAffixTxtRecord->nClassLevelReq : pAutoAffixTxtRecord->nLevelReq;
if (nRequiredLevel <= nLevelRequirement)
{
nRequiredLevel = nLevelRequirement;
}
}
break;
case ITEMQUAL_RARE:
for(int i = 0; i < 3; ++i)
{
pPrefixTxtRecord = DATATBLS_GetMagicAffixTxtRecord(pItem->pItemData->wMagicPrefix[i]);
pSuffixTxtRecord = DATATBLS_GetMagicAffixTxtRecord(pItem->pItemData->wMagicSuffix[i]);
if (pPrefixTxtRecord)
{
nLevelRequirement = pPrefixTxtRecord->nClass != -1 && pPlayer && pPrefixTxtRecord->nClass == pPlayer->dwClassId ? pPrefixTxtRecord->nClassLevelReq : pPrefixTxtRecord->nLevelReq;
if (nRequiredLevel <= nLevelRequirement)
{
nRequiredLevel = nLevelRequirement;
}
}
if (pSuffixTxtRecord)
{
nLevelRequirement = pSuffixTxtRecord->nClass != -1 && pPlayer && pSuffixTxtRecord->nClass == pPlayer->dwClassId ? pSuffixTxtRecord->nClassLevelReq : pSuffixTxtRecord->nLevelReq;
if (nRequiredLevel <= nLevelRequirement)
{
nRequiredLevel = nLevelRequirement;
}
}
}
pAutoAffixTxtRecord = DATATBLS_GetMagicAffixTxtRecord(pItem->pItemData->wAutoAffix);
if (pAutoAffixTxtRecord)
{
nLevelRequirement = pAutoAffixTxtRecord->nClass != -1 && pPlayer && pAutoAffixTxtRecord->nClass == pPlayer->dwClassId ? pAutoAffixTxtRecord->nClassLevelReq : pAutoAffixTxtRecord->nLevelReq;
if (nRequiredLevel <= nLevelRequirement)
{
nRequiredLevel = nLevelRequirement;
}
}
break;
case ITEMQUAL_CRAFT:
nCraftBonus = 10;
for (int i = 0; i < 3; ++i)
{
pPrefixTxtRecord = DATATBLS_GetMagicAffixTxtRecord(pItem->pItemData->wMagicPrefix[i]);
pSuffixTxtRecord = DATATBLS_GetMagicAffixTxtRecord(pItem->pItemData->wMagicSuffix[i]);
if (pPrefixTxtRecord)
{
nCraftBonus += 3;
nLevelRequirement = pPrefixTxtRecord->nClass != -1 && pPlayer && pPrefixTxtRecord->nClass == pPlayer->dwClassId ? pPrefixTxtRecord->nClassLevelReq : pPrefixTxtRecord->nLevelReq;
if (nRequiredLevel <= nLevelRequirement)
{
nRequiredLevel = nLevelRequirement;
}
}
if (pSuffixTxtRecord)
{
nCraftBonus += 3;
nLevelRequirement = pSuffixTxtRecord->nClass != -1 && pPlayer && pSuffixTxtRecord->nClass == pPlayer->dwClassId ? pSuffixTxtRecord->nClassLevelReq : pSuffixTxtRecord->nLevelReq;
if (nRequiredLevel <= nLevelRequirement)
{
nRequiredLevel = nLevelRequirement;
}
}
}
nRequiredLevel += nCraftBonus;
if (nRequiredLevel >= DATATBLS_GetMaxLevel(0))
{
nRequiredLevel = DATATBLS_GetMaxLevel(0) - 1;
}
break;
case ITEMQUAL_UNIQUE:
if (pItem->pItemData->dwFileIndex >= 0 && pItem->pItemData->dwFileIndex < sgptDataTables->nUniqueItemsTxtRecordCount)
{
pUniqueItemsTxtRecord = &sgptDataTables->pUniqueItemsTxt[pItem->pItemData->dwFileIndex];
if (pUniqueItemsTxtRecord)
{
if (pPlayer)
{
if ((ITEMS_CheckUnitFlagEx(pPlayer, UNITFLAGEX_ISEXPANSION) || ITEMS_GetItemFormat(pItem) >= 1) && (int)pUniqueItemsTxtRecord->wLvlReq >= 0)
{
nRequiredLevel = pUniqueItemsTxtRecord->wLvlReq;
}
}
else
{
if ((int)pUniqueItemsTxtRecord->wLvlReq >= 0)
{
nRequiredLevel = pUniqueItemsTxtRecord->wLvlReq;
}
}
}
}
break;
case ITEMQUAL_SET:
pSetItemsTxtRecord = ITEMS_GetSetItemsTxtRecord(ITEMS_GetFileIndex(pItem));
if (pSetItemsTxtRecord && pSetItemsTxtRecord->wLvlReq >= 0)
{
nRequiredLevel = pSetItemsTxtRecord->wLvlReq;
}
break;
default:
break;
}
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (pItemsTxtRecord)
{
if (pItemsTxtRecord->nLevelReq > nRequiredLevel)
{
nRequiredLevel = pItemsTxtRecord->nLevelReq;
}
}
if (pItem->pInventory)
{
for (D2UnitStrc* i = INVENTORY_GetFirstItem(pItem->pInventory); i; i = INVENTORY_GetNextItem(i))
{
if (!INVENTORY_UnitIsItem(i))
{
break;
}
nRequiredLevelForSocketables = ITEMS_GetRequiredLevel(i, pPlayer);
if (nRequiredLevel <= nRequiredLevelForSocketables)
{
nRequiredLevel = nRequiredLevelForSocketables;
}
}
}
for (int i = 0; i < D2Common_11270(pItem, STAT_ITEM_SINGLESKILL, pStat, ARRAY_SIZE(pStat)); ++i)
{
pSkillsTxtRecord = DATATBLS_GetSkillsTxtRecord(pStat[i].nLayer);
if (pSkillsTxtRecord)
{
if (pSkillsTxtRecord->wReqLevel > nRequiredLevel)
{
nRequiredLevel = pSkillsTxtRecord->wReqLevel;
}
}
}
for (int i = 0; i < D2Common_11270(pItem, STAT_ITEM_NONCLASSSKILL, pStat, ARRAY_SIZE(pStat)); ++i)
{
pSkillsTxtRecord = DATATBLS_GetSkillsTxtRecord(pStat[i].nLayer);
if (pSkillsTxtRecord)
{
if (!pPlayer || pPlayer->dwUnitType || pSkillsTxtRecord->nCharClass < 0 || pSkillsTxtRecord->nCharClass >= 7 || (pPlayer->dwClassId & 0xFF) != pSkillsTxtRecord->nCharClass)
{
nRequiredLevelForSkill = pSkillsTxtRecord->wReqLevel + 6;
}
else
{
nRequiredLevelForSkill = pSkillsTxtRecord->wReqLevel;
}
if (nRequiredLevelForSkill > nRequiredLevel)
{
nRequiredLevel = nRequiredLevelForSkill;
}
}
}
nRequiredLevel += STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_LEVELREQ, 0);
if (nRequiredLevel <= 0)
{
nRequiredLevel = 0;
}
return nRequiredLevel;
}
//D2Common.0x6FD9A3F0 (#10757)
int __stdcall ITEMS_GetLevelRequirement(D2UnitStrc* pItem, D2UnitStrc* pUnit)
{
return ITEMS_GetRequiredLevel(pItem, pUnit);
}
//D2Common.0x6FD9A400 (#10758)
BOOL __stdcall ITEMS_CheckBodyLocation(D2UnitStrc* pItem, uint8_t nBodyLoc)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
uint8_t nBodyLoc1 = 0;
uint8_t nBodyLoc2 = 0;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord)
{
nBodyLoc1 = pItemTypesTxtRecord->nBodyLoc1;
nBodyLoc2 = pItemTypesTxtRecord->nBodyLoc2;
}
}
if (nBodyLoc1 == nBodyLoc || nBodyLoc2 == nBodyLoc
|| (nBodyLoc == BODYLOC_SWRARM || nBodyLoc == BODYLOC_SWLARM) && (nBodyLoc1 == BODYLOC_RARM || nBodyLoc2 == BODYLOC_RARM || nBodyLoc1 == BODYLOC_LARM || nBodyLoc2 == BODYLOC_LARM))
{
return TRUE;
}
}
else
{
FOG_WriteToLogFile(" ----- JONM NOTE: Would have crashed, see code at ITEMSCheckBodyLocation. From FILE: %s LINE: %d", __FILE__, __LINE__);
}
return FALSE;
}
//D2Common.0x6FD9A4F0 (#10762)
int __stdcall ITEMS_CheckItemTypeIfThrowable(int nItemType)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
if (nItemType >= 0 && nItemType < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[nItemType];
if (pItemTypesTxtRecord)
{
return pItemTypesTxtRecord->nThrowable;
}
}
return 0;
}
//D2Common.0x6FD9A530 (#10759)
int __stdcall ITEMS_CheckIfThrowable(D2UnitStrc* pItem)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return ITEMS_CheckItemTypeIfThrowable(pItemsTxtRecord->wType[0]);
}
return 0;
}
//D2Common.0x6FD9A5B0 (#10760)
int __stdcall ITEMS_GetMissileType(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
return DATATBLS_GetItemsTxtRecord(pItem->dwClassId)->wMissileType;
}
return -1;
}
//D2Common.0x6FD9A5E0 (#10761)
uint8_t __stdcall ITEMS_GetMeleeRange(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
return DATATBLS_GetItemsTxtRecord(pItem->dwClassId)->nRangeAdder;
}
return 0;
}
//D2Common.0x6FD9A610 (#10763)
BOOL __stdcall ITEMS_CheckWeaponClassByItemId(int nItemId, int nWeapClass)
{
D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(nItemId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->dwWeapClass == nWeapClass;
}
//D2Common.0x6FD9A660 (#10764)
BOOL __stdcall ITEMS_CheckWeaponClass(D2UnitStrc* pItem, int nWeapClass)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
return ITEMS_CheckWeaponClassByItemId(pItem->dwClassId, nWeapClass);
}
return 0;
}
//D2Common.0x6FD9A6C0 (#10766)
uint32_t __stdcall ITEMS_CheckWeaponIfTwoHandedByItemId(int nItemId)
{
D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(nItemId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->n2Handed;
}
//D2Common.0x6FD9A700 (#10765)
uint32_t __stdcall ITEMS_CheckWeaponIfTwoHanded(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
return ITEMS_CheckWeaponIfTwoHandedByItemId(pItem->dwClassId);
}
return 0;
}
//D2Common.0x6FD9A750 (#10767)
uint32_t __stdcall ITEMS_CheckIfStackable(D2UnitStrc* pItem)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->nStackable;
}
return 0;
}
//D2Common.0x6FD9A7A0 (#10768)
uint32_t __stdcall ITEMS_CheckIfBeltable(D2UnitStrc* pItem)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord)
{
return pItemTypesTxtRecord->nBeltable;
}
}
}
return 0;
}
//D2Common.0x6FD9A820 (#10769)
BOOL __stdcall ITEMS_ComparePotionTypes(D2UnitStrc* pItem1, D2UnitStrc* pItem2)
{
static const int szHealthPotCodes[] =
{
' 1ph', ' 2ph', ' 3ph', ' 4ph', ' 5ph'
};
static const int szManaPotCodes[] =
{
' 1pm', ' 2pm', ' 3pm', ' 4pm', ' 5pm'
};
static const int szRejuvPotCodes[] =
{
' lvr', ' svr'
};
D2ItemsTxt* pItemsTxtRecord1 = NULL;
D2ItemsTxt* pItemsTxtRecord2 = NULL;
int nCounter = 0;
bool bPot1 = false;
bool bPot2 = false;
if (pItem1 && pItem2)
{
if (pItem1->dwClassId == pItem2->dwClassId)
{
return TRUE;
}
pItemsTxtRecord1 = DATATBLS_GetItemsTxtRecord(pItem1->dwClassId);
pItemsTxtRecord2 = DATATBLS_GetItemsTxtRecord(pItem2->dwClassId);
bPot1 = false;
bPot2 = false;
nCounter = 0;
do
{
if (!bPot1 && pItemsTxtRecord1->dwCode == szHealthPotCodes[nCounter])
{
bPot1 = true;
}
if (!bPot2 && pItemsTxtRecord2->dwCode == szHealthPotCodes[nCounter])
{
bPot2 = true;
}
if (bPot1 && bPot2)
{
return TRUE;
}
++nCounter;
}
while (nCounter < ARRAY_SIZE(szHealthPotCodes));
bPot1 = false;
bPot2 = false;
nCounter = 0;
do
{
if (!bPot1 && pItemsTxtRecord1->dwCode == szManaPotCodes[nCounter])
{
bPot1 = true;
}
if (!bPot2 && pItemsTxtRecord2->dwCode == szManaPotCodes[nCounter])
{
bPot2 = true;
}
if (bPot1 && bPot2)
{
return TRUE;
}
++nCounter;
}
while (nCounter < ARRAY_SIZE(szManaPotCodes));
bPot1 = false;
bPot2 = false;
nCounter = 0;
do
{
if (!bPot1 && pItemsTxtRecord1->dwCode == szRejuvPotCodes[nCounter])
{
bPot1 = true;
}
if (!bPot2 && pItemsTxtRecord2->dwCode == szRejuvPotCodes[nCounter])
{
bPot2 = true;
}
if (bPot1 && bPot2)
{
return TRUE;
}
++nCounter;
}
while (nCounter < ARRAY_SIZE(szRejuvPotCodes));
}
return FALSE;
}
//D2Common.0x6FD9A960 (#10770)
BOOL __stdcall ITEMS_CheckIfAutoBeltable(D2InventoryStrc* pInventory, D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->nAutoBelt || INVENTORY_HasSimilarPotionInBelt(pInventory, pItem) != -1;
}
//D2Common.0x6FD9AA00 (#10771)
BOOL __stdcall ITEMS_CheckIfUseable(D2UnitStrc* pItem)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->nUseable;
}
else
{
FOG_WriteToLogFile(" ----- JONM NOTE: Would have crashed, see code at ITEMSIsUseable. From FILE: %s LINE: %d", __FILE__, __LINE__);
return 0;
}
}
//D2Common.0x6FD9AA70 (#10772)
int __stdcall ITEMS_GetUniqueColumnFromItemsTxt(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->nUnique;
}
//D2Common.0x6FD9AB00 (#10773)
BOOL __stdcall ITEMS_IsQuestItem(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->nQuest;
}
//D2Common.0x6FD9AB90
int __fastcall ITEMS_CalculateAdditionalCostsForChargedSkills(D2UnitStrc* pUnit, int nBaseCost)
{
D2SkillsTxt* pSkillsTxtRecord = NULL;
int nCounter = 0;
int nSkillId = 0;
int nValue = 0;
int nStats = 0;
int nCost = 0;
int nBase = 0;
int nAdd = 0;
int nMax = 0;
D2StatStrc pStat[64] = {};
nStats = D2Common_11270(pUnit, STAT_ITEM_CHARGED_SKILL, pStat, ARRAY_SIZE(pStat));
if (nStats > 0)
{
do
{
nSkillId = pStat[nCounter].nLayer >> sgptDataTables->nStuff;
nMax = pStat[nCounter].nValue >> 8;
nValue = pStat[nCounter].nValue & 0xFF;
if (nValue < nMax)
{
pSkillsTxtRecord = DATATBLS_GetSkillsTxtRecord(nSkillId);
if (pSkillsTxtRecord)
{
nBase = nBaseCost * ((pStat[nCounter].nLayer & sgptDataTables->nShiftedStuff) + 2 * pSkillsTxtRecord->wReqLevel / 6 + 2);
if (nBase > 65535 && pSkillsTxtRecord->nCostMult)
{
nAdd = pSkillsTxtRecord->nCostMult * nBase / 1024;
}
else
{
nAdd = nBase * pSkillsTxtRecord->nCostMult / 1024;
}
nCost += (pSkillsTxtRecord->nCostAdd + nAdd) * (nMax - nValue) / nMax;
}
}
++nCounter;
}
while (nCounter < nStats);
return nCost;
}
return 0;
}
//D2Common.0x6FD9ACE0
void __fastcall ITEMS_CalculateAdditionalCostsForBonusStats(D2UnitStrc* pItem, int* pSellCost, int* pBuyCost, int* pRepCost, unsigned int nDivisor)
{
D2ItemStatCostTxt* pItemStatCostTxtRecord = NULL;
D2SkillsTxt* pSkillsTxtRecord = NULL;
unsigned int nSell = 0;
unsigned int nBuy = 0;
unsigned int nRep = 0;
int nBonusValue = 0;
int nSkillId = 0;
int nCounter = 0;
int nStatId = 0;
int nStats = 0;
int nValue = 0;
int dw1 = 0;
int dw2 = 0;
int dw3 = 0;
D2StatStrc pStat[511] = {};
nStats = STATLIST_GetFullStatsDataFromUnit(pItem, pStat, ARRAY_SIZE(pStat));
while (nCounter < nStats)
{
nStatId = pStat[nCounter].nStat;
nBonusValue = STATLIST_GetUnitStatBonus(pItem, nStatId, pStat[nCounter].nLayer);
if (nBonusValue)
{
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(nStatId);
if (pItemStatCostTxtRecord)
{
if (pItemStatCostTxtRecord->nValShift)
{
nBonusValue >>= pItemStatCostTxtRecord->nValShift;
}
switch (pItemStatCostTxtRecord->nEncode)
{
case 1:
pSkillsTxtRecord = DATATBLS_GetSkillsTxtRecord(pStat[nCounter].nLayer);
if (pSkillsTxtRecord)
{
if (nBonusValue * *pSellCost > 65535 && pSkillsTxtRecord->nCostMult)
{
nSell += pSkillsTxtRecord->nCostAdd + pSkillsTxtRecord->nCostMult * nBonusValue * *pSellCost / 1024;
nBuy += pSkillsTxtRecord->nCostAdd + pSkillsTxtRecord->nCostMult * nBonusValue * *pBuyCost / 4096;
nRep += pSkillsTxtRecord->nCostAdd + pSkillsTxtRecord->nCostMult * nBonusValue * *pRepCost / 1024;
}
else
{
nSell += pSkillsTxtRecord->nCostAdd + nBonusValue * *pSellCost * pSkillsTxtRecord->nCostMult / 1024;
nBuy += pSkillsTxtRecord->nCostAdd + nBonusValue * pSkillsTxtRecord->nCostMult * *pBuyCost / 4096;
nRep += pSkillsTxtRecord->nCostAdd + nBonusValue * pSkillsTxtRecord->nCostMult * *pRepCost / 1024;
}
}
break;
case 2:
case 3:
nSkillId = pStat[nCounter].nLayer >> sgptDataTables->nStuff;
nValue = pStat[nCounter].nLayer & sgptDataTables->nShiftedStuff;
pSkillsTxtRecord = DATATBLS_GetSkillsTxtRecord(nSkillId);
if (nValue * *pSellCost > 65535 && pSkillsTxtRecord->nCostMult)
{
nSell += pSkillsTxtRecord->nCostAdd + pSkillsTxtRecord->nCostMult * nValue * *pSellCost / 1024;
nBuy += pSkillsTxtRecord->nCostAdd + pSkillsTxtRecord->nCostMult * nValue * *pBuyCost / 4096;
nRep += pSkillsTxtRecord->nCostAdd + pSkillsTxtRecord->nCostMult * nValue * *pRepCost / 1024;
}
else
{
nSell += pSkillsTxtRecord->nCostAdd + nValue * *pSellCost * pSkillsTxtRecord->nCostMult / 1024;
nBuy += pSkillsTxtRecord->nCostAdd + nValue * pSkillsTxtRecord->nCostMult * *pBuyCost / 4096;
nRep += pSkillsTxtRecord->nCostAdd + nValue * pSkillsTxtRecord->nCostMult * *pRepCost / 1024;
}
break;
case 4:
D2COMMON_10843_GetByTimeAdjustment(nBonusValue, 0, 0, &dw1, &dw2, &dw3);
nValue = (dw2 + dw3) / 2;
if (nValue * *pSellCost > 65535 && pItemStatCostTxtRecord->dwMultiply)
{
nSell += pItemStatCostTxtRecord->dwAdd + pItemStatCostTxtRecord->dwMultiply * nValue * *pSellCost / 1024;
nBuy += pItemStatCostTxtRecord->dwAdd + pItemStatCostTxtRecord->dwMultiply * nValue * *pBuyCost / 1024;
nRep += pItemStatCostTxtRecord->dwAdd + pItemStatCostTxtRecord->dwMultiply * nValue * *pRepCost / 1024;
}
else
{
nSell += pItemStatCostTxtRecord->dwAdd + nValue * *pSellCost * pItemStatCostTxtRecord->dwMultiply / 1024;
nBuy += pItemStatCostTxtRecord->dwAdd + nValue * pItemStatCostTxtRecord->dwMultiply * *pBuyCost / 1024;
nRep += pItemStatCostTxtRecord->dwAdd + nValue * pItemStatCostTxtRecord->dwMultiply * *pRepCost / 1024;
}
break;
default:
if (nBonusValue * *pSellCost > 65535 && pItemStatCostTxtRecord->dwMultiply)
{
nSell += pItemStatCostTxtRecord->dwAdd + pItemStatCostTxtRecord->dwMultiply * nBonusValue * *pSellCost / 1024;
nBuy += pItemStatCostTxtRecord->dwAdd + pItemStatCostTxtRecord->dwMultiply * nBonusValue * *pBuyCost / 1024;
nRep += pItemStatCostTxtRecord->dwAdd + pItemStatCostTxtRecord->dwMultiply * nBonusValue * *pRepCost / 1024;
}
else
{
nSell += pItemStatCostTxtRecord->dwAdd + nBonusValue * *pSellCost * pItemStatCostTxtRecord->dwMultiply / 1024;
nBuy += pItemStatCostTxtRecord->dwAdd + nBonusValue * pItemStatCostTxtRecord->dwMultiply * *pBuyCost / 1024;
nRep += pItemStatCostTxtRecord->dwAdd + nBonusValue * pItemStatCostTxtRecord->dwMultiply * *pRepCost / 1024;
}
break;
}
}
}
++nCounter;
}
*pSellCost += nSell / nDivisor;
*pBuyCost += nBuy / nDivisor;
*pRepCost += nRep / nDivisor;
}
//TODO: Check Calculations for unnamed variables, contains some small (rounding?) errors
//D2Common.0x6FD9B1C0
int __fastcall ITEMS_CalculateTransactionCost(D2UnitStrc* pPlayer, D2UnitStrc* pItem, int nDifficulty, D2BitBufferStrc* pQuestFlags, int nVendorId, int nTransactionType)
{
D2UniqueItemsTxt* pUniqueItemsTxtRecord = NULL;
D2MagicAffixTxt* pMagicAffixTxtRecord = NULL;
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2SetItemsTxt* pSetItemsTxtRecord = NULL;
D2MonStatsTxt* pMonStatsTxtRecord = NULL;
D2ItemsTxt* pUltraItemsTxtRecord = NULL;
D2ItemsTxt* pUberItemsTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
D2BooksTxt* pBooksTxtRecord = NULL;
D2ItemDataStrc* pItemData = NULL;
D2NpcTxt* pNpcTxtRecord = NULL;
D2UnitStrc* pSocketable = NULL;
int nSocketableCost = 0;
int nReducePricePct = 0;
int nStackQuantity = 0;
int nArmorClass = 0;
int nDurability = 0;
int nFileIndex = 0;
int nUltraCost = 0;
int nUberCost = 0;
int nItemType = 0;
int nQuantity = 0;
int nMaxStack = 0;
int nSellCost = 0;
int nBuyCost = 0;
int nRepCost = 0;
int nDivisor = 0;
int nMaxDura = 0;
int nQuality = 0;
int nItemId = 0;
int nLevel = 0;
int nStack = 0;
int nCost = 0;
int nBase = 0;
int nSell = 0;
int nBuy = 0;
int nRep = 0;
int v30 = 0, v27 = 0, v22 = 0, v23 = 0; //TODO: Rename
if (!pPlayer || !pItem || pItem->dwUnitType != UNIT_ITEM || !pItem->pItemData)
{
return 0x7FFFFFFF;
}
pItemData = pItem->pItemData;
nLevel = STATLIST_GetUnitStatUnsigned(pPlayer, STAT_LEVEL, 0);
if (nTransactionType == 3 && !ITEMS_IsRepairable(pItem))
{
return 0;
}
if (pItemData->dwItemFlags & IFLAG_STARTITEM)
{
return 1;
}
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
nQuantity = STATLIST_GetUnitStatUnsigned(pItem, STAT_QUANTITY, 0);
if (nQuantity <= 0)
{
nQuantity = 1;
}
nReducePricePct = STATLIST_GetUnitStatUnsigned(pPlayer, STAT_ITEM_REDUCEDPRICES, 0);
if (nReducePricePct >= 99)
{
nReducePricePct = 99;
}
if (nTransactionType != 2)
{
nSellCost = 0;
nBuyCost = 0;
nRepCost = 0;
nDivisor = 1;
if (pItemData->dwItemFlags & IFLAG_ISEAR)
{
nSellCost = pItemsTxtRecord->dwCost * pItemData->nEarLvl;
nBuyCost = nSellCost;
}
else
{
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_BODY_PART))
{
nFileIndex = pItemData->dwFileIndex;
pMonStatsTxtRecord = DATATBLS_GetMonStatsTxtRecord(nFileIndex);
if (pMonStatsTxtRecord)
{
nSellCost = 8 * pMonStatsTxtRecord->nLevel[nDifficulty];
}
nSellCost += pItemsTxtRecord->dwCost;
nBuyCost = nSellCost;
}
else
{
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_BOOK))
{
pBooksTxtRecord = DATATBLS_GetBooksTxtRecord(pItemData->wMagicSuffix[0]);
D2_ASSERT(pBooksTxtRecord);
nSellCost = pItemsTxtRecord->dwCost + nQuantity * pBooksTxtRecord->dwCostPerCharge;
nBuyCost = nSellCost;
}
else
{
pItemTypesTxtRecord = DATATBLS_GetItemTypesTxtRecord(ITEMS_GetItemTypeFromItemId(pItem->dwClassId));
if (pItemTypesTxtRecord && pItemTypesTxtRecord->wQuiver)
{
nSellCost = nQuantity * pItemsTxtRecord->dwCost / 1024;
nBuyCost = nSellCost;
nStackQuantity = STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_EXTRA_STACK, 0) + pItemsTxtRecord->dwMaxStack;
if (nStackQuantity >= 511)
{
nStackQuantity = 511;
}
nRepCost = nStackQuantity * pItemsTxtRecord->dwCost / 1024;
}
else
{
if (!pItemsTxtRecord->nStackable)
{
nSellCost = pItemsTxtRecord->dwCost;
nBuyCost = nSellCost;
nRepCost = nSellCost;
}
else
{
nSellCost = pItemsTxtRecord->dwCost;
nBuyCost = nSellCost;
nRepCost = nSellCost;
nDivisor = STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_EXTRA_STACK, 0) + pItemsTxtRecord->dwMaxStack;
if (nDivisor < 511)
{
if (nDivisor <= 1)
{
nDivisor = 1;
}
}
else
{
nDivisor = 511;
}
}
}
}
}
}
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_ANY_ARMOR))
{
nArmorClass = STATLIST_GetUnitBaseStat(pItem, STAT_ARMORCLASS, 0);
if (pItemsTxtRecord->dwMaxAc - pItemsTxtRecord->dwMinAc != -1)
{
if (pItemsTxtRecord->dwMaxAc)
{
nSellCost = nArmorClass * pItemsTxtRecord->dwCost / pItemsTxtRecord->dwMaxAc;
nBuyCost = nArmorClass * pItemsTxtRecord->dwCost / pItemsTxtRecord->dwMaxAc;
nRepCost = nArmorClass * pItemsTxtRecord->dwCost / pItemsTxtRecord->dwMaxAc;
}
}
}
nQuality = pItemData->dwQualityNo;
if (nQuality < ITEMQUAL_MAGIC || nQuality > ITEMQUAL_TEMPERED)
{
ITEMS_CalculateAdditionalCostsForItemSkill(pItem, &nSellCost, &nBuyCost, &nRepCost, nDivisor);
}
if (pItemData->dwItemFlags & IFLAG_IDENTIFIED)
{
pMagicAffixTxtRecord = DATATBLS_GetMagicAffixTxtRecord(pItemData->wAutoAffix);
if (pMagicAffixTxtRecord)
{
if (nSellCost > 65535 && pMagicAffixTxtRecord->dwMultiply)
{
nSell = pMagicAffixTxtRecord->dwAdd + pMagicAffixTxtRecord->dwMultiply * nSellCost / 1024;
nBuy = pMagicAffixTxtRecord->dwAdd + pMagicAffixTxtRecord->dwMultiply * nBuyCost / 1024;
nRep = pMagicAffixTxtRecord->dwAdd + pMagicAffixTxtRecord->dwMultiply * nRepCost / 1024;
}
else
{
nSell = pMagicAffixTxtRecord->dwAdd + nSellCost * pMagicAffixTxtRecord->dwMultiply / 1024;
nBuy = pMagicAffixTxtRecord->dwAdd + nBuyCost * pMagicAffixTxtRecord->dwMultiply / 1024;
nRep = pMagicAffixTxtRecord->dwAdd + nRepCost * pMagicAffixTxtRecord->dwMultiply / 1024;
}
}
switch (nQuality)
{
case ITEMQUAL_RARE:
case ITEMQUAL_CRAFT:
for (int i = 0; i < 3; ++i)
{
pMagicAffixTxtRecord = DATATBLS_GetMagicAffixTxtRecord(pItemData->wMagicPrefix[i]);
if (pMagicAffixTxtRecord)
{
if (nSellCost > 65535 && pMagicAffixTxtRecord->dwMultiply)
{
nSell += pMagicAffixTxtRecord->dwAdd + pMagicAffixTxtRecord->dwMultiply * nSellCost / 1024;
nBuy += pMagicAffixTxtRecord->dwAdd + pMagicAffixTxtRecord->dwMultiply * nBuyCost / 1024;
nRep += pMagicAffixTxtRecord->dwAdd + pMagicAffixTxtRecord->dwMultiply * nRepCost / 1024;
}
else
{
nSell += pMagicAffixTxtRecord->dwAdd + nSellCost * pMagicAffixTxtRecord->dwMultiply / 1024;
nBuy += pMagicAffixTxtRecord->dwAdd + nBuyCost * pMagicAffixTxtRecord->dwMultiply / 1024;
nRep += pMagicAffixTxtRecord->dwAdd + nRepCost * pMagicAffixTxtRecord->dwMultiply / 1024;
}
}
pMagicAffixTxtRecord = DATATBLS_GetMagicAffixTxtRecord(pItemData->wMagicSuffix[i]);
if (pMagicAffixTxtRecord)
{
if (nSellCost > 65535 && pMagicAffixTxtRecord->dwMultiply)
{
nSell += pMagicAffixTxtRecord->dwAdd + pMagicAffixTxtRecord->dwMultiply * nSellCost / 1024;
nBuy += pMagicAffixTxtRecord->dwAdd + pMagicAffixTxtRecord->dwMultiply * nBuyCost / 1024;
nRep += pMagicAffixTxtRecord->dwAdd + pMagicAffixTxtRecord->dwMultiply * nRepCost / 1024;
}
else
{
nSell += pMagicAffixTxtRecord->dwAdd + nSellCost * pMagicAffixTxtRecord->dwMultiply / 1024;
nBuy += pMagicAffixTxtRecord->dwAdd + nBuyCost * pMagicAffixTxtRecord->dwMultiply / 1024;
nRep += pMagicAffixTxtRecord->dwAdd + nRepCost * pMagicAffixTxtRecord->dwMultiply / 1024;
}
}
}
ITEMS_CalculateAdditionalCostsForBonusStats(pItem, &nSellCost, &nBuyCost, &nRepCost, nDivisor);
break;
case ITEMQUAL_UNIQUE:
if (pItemData->dwFileIndex >= 0 && pItemData->dwFileIndex < sgptDataTables->nUniqueItemsTxtRecordCount)
{
pUniqueItemsTxtRecord = &sgptDataTables->pUniqueItemsTxt[pItemData->dwFileIndex];
if (pUniqueItemsTxtRecord)
{
if (nSellCost > 65535 && pUniqueItemsTxtRecord->dwCostMult)
{
nSell += pUniqueItemsTxtRecord->dwCostAdd + pUniqueItemsTxtRecord->dwCostMult * nSellCost / 1024;
nBuy += pUniqueItemsTxtRecord->dwCostAdd + pUniqueItemsTxtRecord->dwCostMult * nBuyCost / 1024;
nRep += pUniqueItemsTxtRecord->dwCostAdd + pUniqueItemsTxtRecord->dwCostMult * nRepCost / 1024;
}
else
{
nSell += pUniqueItemsTxtRecord->dwCostAdd + nSellCost * pUniqueItemsTxtRecord->dwCostMult / 1024;
nBuy += pUniqueItemsTxtRecord->dwCostAdd + nBuyCost * pUniqueItemsTxtRecord->dwCostMult / 1024;
nRep += pUniqueItemsTxtRecord->dwCostAdd + nRepCost * pUniqueItemsTxtRecord->dwCostMult / 1024;
break;
}
}
}
//TODO: Not sure if it was intended to have no break here
case ITEMQUAL_MAGIC:
pMagicAffixTxtRecord = DATATBLS_GetMagicAffixTxtRecord(pItemData->wMagicPrefix[0]);
if (pMagicAffixTxtRecord)
{
if (nSellCost > 65535 && pMagicAffixTxtRecord->dwMultiply)
{
nSell += pMagicAffixTxtRecord->dwAdd + pMagicAffixTxtRecord->dwMultiply * nSellCost / 1024;
nBuy += pMagicAffixTxtRecord->dwAdd + pMagicAffixTxtRecord->dwMultiply * nBuyCost / 1024;
nRep += pMagicAffixTxtRecord->dwAdd + pMagicAffixTxtRecord->dwMultiply * nRepCost / 1024;
}
else
{
nSell += pMagicAffixTxtRecord->dwAdd + nSellCost * pMagicAffixTxtRecord->dwMultiply / 1024;
nBuy += pMagicAffixTxtRecord->dwAdd + nBuyCost * pMagicAffixTxtRecord->dwMultiply / 1024;
nRep += pMagicAffixTxtRecord->dwAdd + nRepCost * pMagicAffixTxtRecord->dwMultiply / 1024;
}
}
pMagicAffixTxtRecord = DATATBLS_GetMagicAffixTxtRecord(pItemData->wMagicSuffix[0]);
if (pMagicAffixTxtRecord)
{
if (nSellCost > 65535 && pMagicAffixTxtRecord->dwMultiply)
{
nSell += pMagicAffixTxtRecord->dwAdd + pMagicAffixTxtRecord->dwMultiply * nSellCost / 1024;
nBuy += pMagicAffixTxtRecord->dwAdd + pMagicAffixTxtRecord->dwMultiply * nBuyCost / 1024;
nRep += pMagicAffixTxtRecord->dwAdd + pMagicAffixTxtRecord->dwMultiply * nRepCost / 1024;
}
else
{
nSell += pMagicAffixTxtRecord->dwAdd + nSellCost * pMagicAffixTxtRecord->dwMultiply / 1024;
nBuy += pMagicAffixTxtRecord->dwAdd + nBuyCost * pMagicAffixTxtRecord->dwMultiply / 1024;
nRep += pMagicAffixTxtRecord->dwAdd + nRepCost * pMagicAffixTxtRecord->dwMultiply / 1024;
}
}
ITEMS_CalculateAdditionalCostsForBonusStats(pItem, &nSellCost, &nBuyCost, &nRepCost, nDivisor);
break;
case ITEMQUAL_SUPERIOR:
case ITEMQUAL_TEMPERED:
ITEMS_CalculateAdditionalCostsForBonusStats(pItem, &nSellCost, &nBuyCost, &nRepCost, nDivisor);
break;
case ITEMQUAL_SET:
if (pItemData->dwFileIndex >= 0 && pItemData->dwFileIndex < sgptDataTables->nSetItemsTxtRecordCount)
{
pSetItemsTxtRecord = &sgptDataTables->pSetItemsTxt[pItemData->dwFileIndex];
if (pSetItemsTxtRecord)
{
if (nSellCost > 65535 && pSetItemsTxtRecord->dwCostMult)
{
nSell += pSetItemsTxtRecord->dwCostAdd + pSetItemsTxtRecord->dwCostMult * nSellCost / 1024;
nBuy += pSetItemsTxtRecord->dwCostAdd + pSetItemsTxtRecord->dwCostMult * nBuyCost / 1024;
nRep += pSetItemsTxtRecord->dwCostAdd + pSetItemsTxtRecord->dwCostMult * nRepCost / 1024;
}
else
{
nSell += pSetItemsTxtRecord->dwCostAdd + nSellCost * pSetItemsTxtRecord->dwCostMult / 1024;
nBuy += pSetItemsTxtRecord->dwCostAdd + nBuyCost * pSetItemsTxtRecord->dwCostMult / 1024;
nRep += pSetItemsTxtRecord->dwCostAdd + nRepCost * pSetItemsTxtRecord->dwCostMult / 1024;
}
}
}
break;
case ITEMQUAL_INFERIOR:
nSell = nSellCost / -2;
nBuy = nBuyCost / -2;
nRep = nRepCost / -2;
break;
default:
break;
}
nSellCost += nSell / nDivisor;
nBuyCost += nBuy / nDivisor;
nRepCost += nRep / nDivisor;
if (nQuality >= ITEMQUAL_MAGIC && nQuality <= ITEMQUAL_TEMPERED)
{
ITEMS_CalculateAdditionalCostsForItemSkill(pItem, &nSellCost, &nBuyCost, &nRepCost, nDivisor);
}
}
if (pItem->pInventory)
{
pSocketable = INVENTORY_GetFirstItem(pItem->pInventory);
while (pSocketable)
{
if (INVENTORY_UnitIsItem(pSocketable))
{
nSocketableCost = DATATBLS_GetItemsTxtRecord(pSocketable->dwClassId)->dwCost / 2;
nSellCost += nSocketableCost;
nBuyCost += nSocketableCost;
nRepCost += nSocketableCost;
}
pSocketable = INVENTORY_GetNextItem(pSocketable);
}
}
if (pItemData->dwItemFlags & IFLAG_ETHEREAL)
{
nBuyCost /= 4;
}
nItemType = ITEMS_GetItemTypeFromItemId(pItem->dwClassId);
if (nItemType >= 0 && nItemType < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[nItemType];
if (pItemTypesTxtRecord && pItemTypesTxtRecord->nClass < 7)
{
nBuyCost /= 4;
}
}
if (nTransactionType == 1)
{
if (pItemData->dwItemFlags & IFLAG_ETHEREAL && !pItemsTxtRecord->nNoDurability && pItemsTxtRecord->nDurability && STATLIST_GetMaxDurabilityFromUnit(pItem) && STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_INDESCTRUCTIBLE, 0) <= 0)
{
if (STATLIST_GetUnitStatUnsigned(pItem, STAT_DURABILITY, 0) <= 0)
{
nBuyCost = 0;
}
}
}
else if (nTransactionType == 3)
{
pItemTypesTxtRecord = DATATBLS_GetItemTypesTxtRecord(pItemsTxtRecord->wType[0]);
if (!pItemTypesTxtRecord || !pItemTypesTxtRecord->wQuiver || !pItemTypesTxtRecord->nThrowable)
{
if (!pItemsTxtRecord->nNoDurability && pItemsTxtRecord->nDurability && STATLIST_GetMaxDurabilityFromUnit(pItem) && STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_INDESCTRUCTIBLE, 0) <= 0)
{
nDurability = STATLIST_GetUnitStatUnsigned(pItem, STAT_DURABILITY, 0);
nMaxDura = STATLIST_GetMaxDurabilityFromUnit(pItem);
if (nMaxDura && nDurability < nMaxDura)
{
if (STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_REPLENISH_DURABILITY, 0))
{
if (nDurability < nMaxDura - 1)
{
nRepCost *= (nMaxDura - 1) / nMaxDura;
}
else
{
nRepCost = 0;
}
}
else
{
nRepCost *= (nMaxDura - nDurability) / nMaxDura;
}
}
else
{
nRepCost = 0;
}
}
}
}
pNpcTxtRecord = DATATBLS_GetNpcTxtRecord(nVendorId);
D2_ASSERT(pNpcTxtRecord);
if (nSellCost <= 65535 || !pNpcTxtRecord->dwSellMult)
{
nSellCost = nSellCost * pNpcTxtRecord->dwSellMult / 1024;
}
else
{
nSellCost = pNpcTxtRecord->dwSellMult * nSellCost / 1024;
}
if (nBuyCost <= 65535 || !pNpcTxtRecord->dwSellMult)//TODO: Probably Copy-Paste Error by Blizzard, should be dwBuyMult
{
nBuyCost = nBuyCost * pNpcTxtRecord->dwBuyMult / 1024;
}
else
{
nBuyCost = nBuyCost / 1024 * pNpcTxtRecord->dwBuyMult;
}
if (nRepCost <= 65535 || !pNpcTxtRecord->dwRepMult)
{
nRepCost = nRepCost * pNpcTxtRecord->dwRepMult / 1024;
}
else
{
nRepCost = pNpcTxtRecord->dwRepMult * nRepCost / 1024;
}
for (int i = 0; i < 3; ++i)
{
if (pNpcTxtRecord->dwQuestFlag[i] && (QUESTRECORD_GetQuestState(pQuestFlags, pNpcTxtRecord->dwQuestFlag[i], QFLAG_REWARDGRANTED) == 1
|| QUESTRECORD_GetQuestState(pQuestFlags, pNpcTxtRecord->dwQuestFlag[i], QFLAG_REWARDPENDING) == 1))
{
if (nSellCost > 65535 && pNpcTxtRecord->dwQuestSellMult[i])
{
nSellCost = pNpcTxtRecord->dwQuestSellMult[i] * nSellCost / 1024;
}
else
{
nSellCost = nSellCost * pNpcTxtRecord->dwQuestSellMult[i] / 1024;
}
if (nBuyCost > 65535 && pNpcTxtRecord->dwQuestBuyMult[i])
{
nBuyCost = pNpcTxtRecord->dwQuestBuyMult[i] * nBuyCost / 1024;
}
else
{
nBuyCost = nBuyCost * pNpcTxtRecord->dwQuestBuyMult[i] / 1024;
}
if (nRepCost > 65535 && pNpcTxtRecord->dwQuestRepMult[i])
{
nRepCost = pNpcTxtRecord->dwQuestRepMult[i] * nRepCost / 1024;
}
else
{
nRepCost = nRepCost * pNpcTxtRecord->dwQuestRepMult[i] / 1024;
}
}
}
if (!ITEMS_CheckItemTypeId(pItem, ITEMTYPE_BOOK))
{
pItemTypesTxtRecord = DATATBLS_GetItemTypesTxtRecord(pItemsTxtRecord->wType[0]);
if (!pItemTypesTxtRecord || !pItemTypesTxtRecord->wQuiver)
{
nSellCost *= nQuantity;
if (pItemsTxtRecord->nStackable && ITEMS_IsRepairable(pItem))
{
nMaxStack = STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_EXTRA_STACK, 0) + pItemsTxtRecord->dwMaxStack;
if (nMaxStack >= 511)
{
nMaxStack = 511;
}
if (nQuantity < nMaxStack && !STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_REPLENISH_QUANTITY, 0))
{
nRepCost *= (nMaxStack - nQuantity);
}
else
{
nRepCost = 0;
}
nBuyCost *= (nMaxStack - nRepCost);
}
else
{
nBuyCost *= nQuantity;
}
}
}
nCost = nBuyCost;
if (nTransactionType == 3)
{
if (!(pItemData->dwItemFlags & IFLAG_ETHEREAL))
{
nRepCost += ITEMS_CalculateAdditionalCostsForChargedSkills(pItem, 10000);
}
}
if (nCost > pNpcTxtRecord->nMaxBuy[nDifficulty])
{
nCost = pNpcTxtRecord->nMaxBuy[nDifficulty];
}
if (nTransactionType != 1)
{
if (nTransactionType == 3)
{
nCost = nRepCost - DATATBLS_CalculatePercentage(nRepCost, nReducePricePct, 100);
}
else
{
nCost = nSellCost - DATATBLS_CalculatePercentage(nSellCost, nReducePricePct, 100);
}
}
if (nCost < 1)
{
nCost = 1;
}
return nCost;
}
else
{
if (pItemData->wItemFormat >= 1)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(DATATBLS_GetItemIdFromItemCode(pItemsTxtRecord->dwNormCode ? pItemsTxtRecord->dwNormCode : pItemsTxtRecord->dwCode));
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->dwCode == ' nir' || pItemsTxtRecord->dwCode == ' uma')
{
nCost = pItemsTxtRecord->dwGambleCost;
}
else
{
nStack = pItemsTxtRecord->dwMinStack + pItemsTxtRecord->dwMaxStack;
v27 = ((signed int)nStack - HIDWORD(nStack)) >> 1;
if (v27 < 1)
{
v27 = 1;
}
if (pItemsTxtRecord->dwUberCode && pItemsTxtRecord->dwUberCode != ' 0')
{
pUberItemsTxtRecord = DATATBLS_GetItemRecordFromItemCode(pItemsTxtRecord->dwUberCode, &nItemId);
if (pUberItemsTxtRecord)
{
v30 = 100 * (nLevel - pUberItemsTxtRecord->nLevel);
v23 = (((signed int)v30 - HIDWORD(v30)) >> 1) + 1;
if (v23 < 0)
{
v23 = 0;
}
nUberCost = pUberItemsTxtRecord->dwCost;
}
}
if (pItemsTxtRecord->dwUltraCode && pItemsTxtRecord->dwUltraCode != ' 0')
{
pUltraItemsTxtRecord = DATATBLS_GetItemRecordFromItemCode(pItemsTxtRecord->dwUltraCode, &nItemId);
if (pUltraItemsTxtRecord)
{
v30 = 100 * (nLevel - pUltraItemsTxtRecord->nLevel);
v22 = (((BYTE4(v30) & 3) + (signed int)v30) >> 2) + 1;
if (v22 < 0)
{
v22 = 0;
}
nUltraCost = pUltraItemsTxtRecord->dwCost;
}
}
nBase = v23 * nUberCost + v22 * nUltraCost + (v27 * pItemsTxtRecord->dwCost) * (10000 - v22 - v23);
if (nLevel < 5)
{
nLevel = 5;
}
nCost = ((2 * nLevel + 1) / 3 + 20) * (nBase / 10000 + (250 * (nLevel + ((pItemsTxtRecord->nLevel - 45) > 0 ? (pItemsTxtRecord->nLevel - 45) : 0) - (int)pItemsTxtRecord->nLevel / 2)) / 3) / 15;
}
if (nReducePricePct)
{
return nCost - DATATBLS_CalculatePercentage(nCost, nReducePricePct, 100);
}
else
{
return nCost;
}
}
else
{
return DATATBLS_GetItemsTxtRecord(DATATBLS_GetItemIdFromItemCode(pItemsTxtRecord->dwNormCode ? pItemsTxtRecord->dwNormCode : pItemsTxtRecord->dwCode))->dwGambleCost;
}
}
}
//D2Common.0x6FD9CB50
void __fastcall ITEMS_CalculateAdditionalCostsForItemSkill(D2UnitStrc* pItem, int* pSellCost, int* pBuyCost, int* pRepCost, unsigned int nDivisor)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2SkillsTxt* pSkillsTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
unsigned int nSell = 0;
unsigned int nBuy = 0;
unsigned int nRep = 0;
int nStats = 0;
D2StatStrc pStat[64] = {};
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord && pItemTypesTxtRecord->nStaffMods != 7)
{
nStats = D2Common_11270(pItem, STAT_ITEM_SINGLESKILL, pStat, ARRAY_SIZE(pStat));
for (int nStatId = 0; nStatId < nStats; ++nStatId)
{
pSkillsTxtRecord = DATATBLS_GetSkillsTxtRecord(pStat[nStatId].nLayer);
if (pSkillsTxtRecord)
{
if (*pSellCost > 65535 && pSkillsTxtRecord->nCostMult)
{
nSell += (2 * pStat[nStatId].nValue - 1) * (pSkillsTxtRecord->nCostAdd + *pSellCost * pSkillsTxtRecord->nCostMult / 1024);
nBuy += (2 * pStat[nStatId].nValue - 1) * (pSkillsTxtRecord->nCostAdd + *pBuyCost * pSkillsTxtRecord->nCostMult / 4096);
nRep += (2 * pStat[nStatId].nValue - 1) * (pSkillsTxtRecord->nCostAdd + *pRepCost * pSkillsTxtRecord->nCostMult / 1024);
}
else
{
nSell += (2 * pStat[nStatId].nValue - 1) * (pSkillsTxtRecord->nCostAdd + pSkillsTxtRecord->nCostMult * *pSellCost / 1024);
nBuy += (2 * pStat[nStatId].nValue - 1) * (pSkillsTxtRecord->nCostAdd + pSkillsTxtRecord->nCostMult * *pBuyCost / 4096);
nRep += (2 * pStat[nStatId].nValue - 1) * (pSkillsTxtRecord->nCostAdd + pSkillsTxtRecord->nCostMult * *pRepCost / 1024);
}
}
}
*pSellCost += nSell / nDivisor;
*pBuyCost += nBuy / nDivisor;
*pRepCost += nRep / nDivisor;
}
}
}
}
//D2Common.0x6FD9CDC0
int __fastcall ITEMS_CheckUnitFlagEx(D2UnitStrc* pUnit, int nFlag)
{
if (pUnit)
{
return (nFlag & pUnit->dwFlagEx) != 0;
}
return 0;
}
//D2Common.0x6FD9CDE0 (#10775)
int __stdcall ITEMS_GetTransactionCost(D2UnitStrc* pPlayer, D2UnitStrc* pItem, int nDifficulty, D2BitBufferStrc* pQuestFlags, int nVendorId, int nTransactionType)
{
return ITEMS_CalculateTransactionCost(pPlayer, pItem, nDifficulty, pQuestFlags, nVendorId, nTransactionType);
}
//D2Common.0x6FD9CE10 (#10794)
int __stdcall ITEMS_GetMaxStack(int nItemId)
{
D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(nItemId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->dwMaxStack;
}
//D2Common.0x6FD9CE50 (#10795)
int __stdcall ITEMS_GetTotalMaxStack(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
int nMaxStack = STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_EXTRA_STACK, 0) + pItemsTxtRecord->dwMaxStack;
if (nMaxStack >= 511)
{
nMaxStack = 511;
}
return nMaxStack;
}
//D2Common.0x6FD9CEF0 (#10798)
int __stdcall ITEMS_GetSpawnStackFromItemId(int nItemId)
{
D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(nItemId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->dwSpawnStack;
}
//D2Common.0x6FD9CF30 (#10799)
int __stdcall ITEMS_GetSpawnStack(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
return ITEMS_GetSpawnStackFromItemId(pItem->dwClassId);
}
//D2Common.0x6FD9CFB0 (#10796)
int __stdcall ITEMS_GetMinStackFromItemId(int nItemId)
{
D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(nItemId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->dwMinStack;
}
//D2Common.0x6FD9CFF0 (#10797)
int __stdcall ITEMS_GetMinStack(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
return ITEMS_GetMinStackFromItemId(pItem->dwClassId);
}
//D2Common.0x6FD9D070 (#10800) - Unused
int __stdcall ITEMS_CheckBitField1Flag8(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->dwBitField1 & 8;
}
//D2Common.0x6FD9D0F0 (#10804)
int __stdcall ITEMS_GetSpellIcon(D2UnitStrc* pItem)
{
D2BooksTxt* pBooksTxtRecord = NULL;
uint16_t wBookId = 0;
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_SCROLL) || ITEMS_CheckItemTypeId(pItem, ITEMTYPE_BOOK))
{
if (pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
wBookId = pItem->pItemData->wMagicSuffix[0];
}
else
{
wBookId = 0;
}
pBooksTxtRecord = DATATBLS_GetBooksTxtRecord(wBookId);
if (pBooksTxtRecord)
{
return pBooksTxtRecord->nSpellIcon;
}
else
{
return -1;
}
}
else
{
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->nSpellIcon;
}
}
//D2Common.0x6FD9D1E0 (#10805)
uint8_t __stdcall ITEMS_GetDurWarnCount(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->nDurWarning;
}
//D2Common.0x6FD9D260 (#10806)
uint8_t __stdcall ITEMS_GetQtyWarnCount(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->nQuantityWarning;
}
//D2Common.0x6FD9D2E0 (#10807)
short __stdcall ITEMS_GetStrengthBonus(D2UnitStrc* pItem)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (pItemsTxtRecord && pItemsTxtRecord->nStrBonus != 1)
{
return pItemsTxtRecord->nStrBonus;
}
}
return 100;
}
//D2Common.0x6FD9D310 (#10808)
short __stdcall ITEMS_GetDexBonus(D2UnitStrc* pItem)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (pItemsTxtRecord && pItemsTxtRecord->nDexBonus != 1)
{
return pItemsTxtRecord->nDexBonus;
}
}
return 100;
}
//D2Common.0x6FD9D340 (#10809)
int __stdcall ITEMS_CheckIfSocketableByItemId(int nItemId)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(nItemId);
if (pItemsTxtRecord)
{
return pItemsTxtRecord->nHasInv;
}
return 0;
}
//D2Common.0x6FD9D360 (#10810)
int __stdcall ITEMS_CheckIfSocketable(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
return ITEMS_CheckIfSocketableByItemId(pItem->dwClassId);
}
return 0;
}
//D2Common.0x6FD9D390 (#10811)
BOOL __stdcall ITEMS_HasDurability(D2UnitStrc* pItem)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (pItemsTxtRecord && !pItemsTxtRecord->nNoDurability && pItemsTxtRecord->nDurability && STATLIST_GetMaxDurabilityFromUnit(pItem))
{
return STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_INDESCTRUCTIBLE, 0) <= 0;
}
}
return FALSE;
}
//D2Common.0x6FD9D3F0 (#10813)
int __stdcall ITEMS_GetStaffMods(D2UnitStrc* pItem)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord)
{
return pItemTypesTxtRecord->nStaffMods;
}
}
}
return 7;
}
//D2Common.0x6FD9D470 (#10814)
uint8_t __stdcall ITEMS_GetAllowedGemSocketsFromItemId(int nItemId)
{
D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(nItemId);
if (pItemsTxtRecord)
{
return pItemsTxtRecord->nGemSockets;
}
return 0;
}
//D2Common.0x6FD9D490 (#10815)
uint8_t __stdcall ITEMS_GetMaxSockets(D2UnitStrc* pItem)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
uint8_t nMaxSockets = 0;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord)
{
if (pItem->pItemData)
{
if (pItem->pItemData->dwItemLevel < 1)
{
pItem->pItemData->dwItemLevel = 1;
}
if (pItem->pItemData->dwItemLevel > 25)
{
if (pItem->pItemData->dwItemLevel > 40)
{
nMaxSockets = pItemTypesTxtRecord->nMaxSock40;
}
else
{
nMaxSockets = pItemTypesTxtRecord->nMaxSock25;
}
}
else
{
nMaxSockets = pItemTypesTxtRecord->nMaxSock1;
}
}
else
{
nMaxSockets = pItemTypesTxtRecord->nMaxSock1;
}
if (pItemsTxtRecord->nGemSockets < nMaxSockets)
{
return pItemsTxtRecord->nGemSockets;
}
else
{
return nMaxSockets;
}
}
}
}
return 0;
}
//D2Common.0x6FD9D580 (#10816)
int __stdcall ITEMS_GetSockets(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
return STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_NUMSOCKETS, 0);
}
//D2Common.0x6FD9D5E0 (#10817)
void __stdcall ITEMS_AddSockets(D2UnitStrc* pItem, int nSockets)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
uint32_t nQuality = 0;
int nCurrentSockets = 0;
int nMaxSockets = 0;
int nItemLevel = 0;
int nItemType = 0;
int nMaxSocks = 0;
uint8_t nGemSockets = 0;
uint8_t nHeight = 0;
uint8_t nWidth = 0;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
nMaxSockets = 6;
nWidth = 0;
nHeight = 0;
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (pItemsTxtRecord)
{
nWidth = pItemsTxtRecord->nInvWidth;
nHeight = pItemsTxtRecord->nInvHeight;
}
if (nWidth * nHeight <= 6)
{
nMaxSockets = nWidth * nHeight;
}
if (nWidth * nHeight)
{
if (pItem->pItemData)
{
nQuality = pItem->pItemData->dwQualityNo;
}
else
{
nQuality = ITEMQUAL_NORMAL;
}
switch (nQuality)
{
case ITEMQUAL_SET:
case ITEMQUAL_UNIQUE:
nCurrentSockets = STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_NUMSOCKETS, 0);
if (nCurrentSockets <= 0)
{
if (nMaxSockets >= 1)
{
nMaxSockets = 1;
}
}
else
{
nSockets = nCurrentSockets;
}
break;
case ITEMQUAL_RARE:
if (nMaxSockets >= 2)
{
nMaxSockets = 2;
}
break;
case ITEMQUAL_MAGIC:
if (nMaxSockets >= 4)
{
nMaxSockets = 4;
}
break;
case ITEMQUAL_CRAFT:
case ITEMQUAL_TEMPERED:
if (nMaxSockets >= 3)
{
nMaxSockets = 3;
}
break;
default:
break;
}
nItemType = ITEMS_GetItemTypeFromItemId(pItem->dwClassId);
if (nItemType >= 0 && nItemType < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[nItemType];
if (pItemTypesTxtRecord)
{
if (pItemsTxtRecord)
{
nGemSockets = pItemsTxtRecord->nGemSockets;
}
else
{
nGemSockets = 0;
}
nItemLevel = ITEMS_GetItemLevel(pItem);
if (nItemLevel > 25)
{
if (nItemLevel > 40)
{
nMaxSocks = pItemTypesTxtRecord->nMaxSock40;
}
else
{
nMaxSocks = pItemTypesTxtRecord->nMaxSock25;
}
}
else
{
nMaxSocks = pItemTypesTxtRecord->nMaxSock1;
}
if (nGemSockets >= nMaxSocks)
{
nGemSockets = nMaxSocks;
}
}
}
if (nMaxSockets >= nGemSockets)
{
nMaxSockets = nGemSockets;
}
if (nSockets <= 1)
{
nSockets = 1;
}
if (nSockets >= nMaxSockets)
{
nSockets = nMaxSockets;
}
if (nSockets > 0)
{
if (pItem->pItemData)
{
pItem->pItemData->dwItemFlags |= IFLAG_SOCKETED;
}
STATLIST_SetUnitStat(pItem, STAT_ITEM_NUMSOCKETS, nSockets, 0);
}
}
}
}
//D2Common.0x6FD9D7C0 (#10818)
void __stdcall ITEMS_SetSockets(D2UnitStrc* pItem, int nSockets)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
int nMaxSockets = 0;
int nMaxSocks = 0;
int nItemLevel = 0;
int nItemType = 0;
uint8_t nAllowedSockets = 0;
uint8_t nWidth = 0;
uint8_t nHeight = 0;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
nMaxSockets = 6;
nWidth = 0;
nHeight = 0;
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (pItemsTxtRecord)
{
nWidth = pItemsTxtRecord->nInvWidth;
nHeight = pItemsTxtRecord->nInvHeight;
}
if (nWidth * nHeight > 6)
{
if (nWidth * nHeight <= 6)
{
nMaxSockets = nWidth * nHeight;
}
nItemType = ITEMS_GetItemTypeFromItemId(pItem->dwClassId);
if (nItemType >= 0 && nItemType < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[nItemType];
if (pItemTypesTxtRecord)
{
nAllowedSockets = ITEMS_GetAllowedGemSocketsFromItemId(pItem->dwClassId);
nItemLevel = ITEMS_GetItemLevel(pItem);
if (nItemLevel > 25)
{
if (nItemLevel > 40)
{
nMaxSocks = pItemTypesTxtRecord->nMaxSock40;
}
else
{
nMaxSocks = pItemTypesTxtRecord->nMaxSock25;
}
}
else
{
nMaxSocks = pItemTypesTxtRecord->nMaxSock1;
}
if (nAllowedSockets >= nMaxSocks)
{
nAllowedSockets = nMaxSocks;
}
}
}
if (nMaxSockets >= nAllowedSockets)
{
nMaxSockets = nAllowedSockets;
}
if (nSockets <= 1)
{
nSockets = 1;
}
if (nSockets >= nMaxSockets)
{
nSockets = nMaxSockets;
}
if (pItem->pItemData)
{
pItem->pItemData->dwItemFlags |= IFLAG_SOCKETED;
}
STATLIST_SetUnitStat(pItem, STAT_ITEM_NUMSOCKETS, nSockets, 0);
}
}
}
//D2Common.0x6FD9D900 (#10819)
int __stdcall ITEMS_GetGemApplyTypeFromItemId(int nItemId)
{
D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(nItemId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->nGemApplyType;
}
//D2Common.0x6FD9D940 (#10820)
int __stdcall ITEMS_GetGemApplyType(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
return ITEMS_GetGemApplyTypeFromItemId(pItem->dwClassId);
}
//D2Common.0x6FD9D9D0 (#10821)
BOOL __stdcall ITEMS_IsSocketFiller(D2UnitStrc* pItem)
{
return ITEMS_CheckItemTypeId(pItem, ITEMTYPE_SOCKET_FILLER);
}
//D2Common.0x6FD9D9E0 (#10822)
const D2RunesTxt* __stdcall ITEMS_GetRunesTxtRecordFromItem(const D2UnitStrc* pItem)
{
if (!pItem)
{
return nullptr;
}
const bool isItemOfSpecialQuality = (pItem->dwUnitType == UNIT_ITEM && pItem->pItemData && pItem->pItemData->dwQualityNo >= ITEMQUAL_MAGIC && pItem->pItemData->dwQualityNo <= ITEMQUAL_TEMPERED);
// Note: The game specifically checks all the things above, which means we will enter the condition if dwUnitType == UNIT_ITEM
// While this is not really correct, this is what the game does, and it works because it expects the unit to be an item.
// and is using another function that checked if an item was special, which happened to check that the unit was indeed an item
if (isItemOfSpecialQuality)
{
return nullptr;
}
if (!DATATBLS_GetItemsTxtRecord(pItem->dwClassId)->nQuest && pItem->pInventory)
{
int nSocketableIds[6] = {};
int nSocketedItems = 0;
for (D2UnitStrc* pInventoryItem = INVENTORY_GetFirstItem(pItem->pInventory); pInventoryItem && INVENTORY_UnitIsItem(pInventoryItem); pInventoryItem = INVENTORY_GetNextItem(pInventoryItem))
{
nSocketableIds[nSocketedItems] = pInventoryItem->dwClassId;
++nSocketedItems;
}
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
const int nSockets = STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_NUMSOCKETS, 0);
if (nSockets != nSocketedItems)
{
return nullptr;
}
for (int i = 0; i < sgptDataTables->pRuneDataTables.nRunesTxtRecordCount; ++i)
{
const D2RunesTxt* pRunesTxtRecord = &sgptDataTables->pRuneDataTables.pRunesTxt[i];
if (pRunesTxtRecord->nComplete)
{
int nRuneCounter = 0;
bool bMatch = true;
while (nRuneCounter < 6 && pRunesTxtRecord->nRune[nRuneCounter] > 0)
{
if (nSocketedItems < nRuneCounter || nSocketableIds[nRuneCounter] != pRunesTxtRecord->nRune[nRuneCounter])
{
bMatch = false;
break;
}
++nRuneCounter;
}
if (bMatch)
{
// All runes are a match, now check if the item types correspond
bool isItemTypeExcluded = false;
for (int nETypeCounter = 0; nETypeCounter < 3 && pRunesTxtRecord->wEType[nETypeCounter]; ++nETypeCounter)
{
if (ITEMS_CheckItemTypeId(pItem, pRunesTxtRecord->wEType[nETypeCounter]))
{
isItemTypeExcluded = true;
break;
}
}
// Not an excluded type, check valid types
if (!isItemTypeExcluded)
{
for (int nITypeCounter = 0; nITypeCounter < 6 && pRunesTxtRecord->wIType[nITypeCounter]; ++nITypeCounter)
{
if (ITEMS_CheckItemTypeId(pItem, pRunesTxtRecord->wIType[nITypeCounter]))
{
return pRunesTxtRecord;
}
}
}
}
}
}
}
return nullptr;
}
static BOOL ITEMS_CheckTypeEquivalenceFromLUT(uint32_t* pEquivalenceLUT, uint32_t nItemType)
{
return pEquivalenceLUT[nItemType / 32] & gdwBitMasks[nItemType % 32];
}
static uint32_t* ITEMS_TypeEquivalenceLUT(int nItemTypeLUT)
{
return &sgptDataTables->pItemTypesEquivalenceLUTs[nItemTypeLUT * sgptDataTables->nItemTypesIndex];
}
//D2Common.0x6FD9DBA0 (#10729)
BOOL __stdcall ITEMS_CheckItemTypeIdByItemId(int nItemId, int nItemType)
{
if (nItemType >= 0 && nItemType < sgptDataTables->nItemTypesTxtRecordCount)
{
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(nItemId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
if (ITEMS_CheckTypeEquivalenceFromLUT(ITEMS_TypeEquivalenceLUT(pItemsTxtRecord->wType[0]), nItemType))
{
return TRUE;
}
if (pItemsTxtRecord->wType[1] > 0 && pItemsTxtRecord->wType[1] < sgptDataTables->nItemTypesTxtRecordCount)
{
return ITEMS_CheckTypeEquivalenceFromLUT(ITEMS_TypeEquivalenceLUT(pItemsTxtRecord->wType[1]), nItemType);
}
}
}
return FALSE;
}
//D2Common.0x6FD9DC80 (#10730)
BOOL __stdcall ITEMS_CheckType(int nItemType1, int nItemType2)
{
if (nItemType1 >= 0 && nItemType1 < sgptDataTables->nItemTypesTxtRecordCount && nItemType2 >= 0 && nItemType2 < sgptDataTables->nItemTypesTxtRecordCount)
{
return ITEMS_CheckTypeEquivalenceFromLUT(ITEMS_TypeEquivalenceLUT(nItemType1), nItemType2);
}
return FALSE;
}
//D2Common.0x6FD9DCE0 (#10731)
BOOL __stdcall ITEMS_CheckItemTypeId(const D2UnitStrc* pItem, int nItemType)
{
if (pItem)
{
return ITEMS_CheckItemTypeIdByItemId(pItem->dwClassId, nItemType);
}
return FALSE;
}
//D2Common.0x6FD9DDD0 (#10803)
//TODO: Find a better name
int __stdcall ITEMS_CheckBitField1Flag1(int nItemId)
{
D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(nItemId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->dwBitField1 & 1;
}
//D2Common.0x6FD9DE10 (#10802)
int __stdcall ITEMS_IsMetalItem(int nItemId)
{
D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(nItemId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->dwBitField1 & 2;
}
//D2Common.0x6FD9DE50 (#10801) - Unused
int __stdcall ITEMS_CheckBitField1Flag4(int nItemId)
{
D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(nItemId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->dwBitField1 & 4;
}
//D2Common.0x6FD9DE90 (#10774)
BOOL __stdcall ITEMS_IsNotQuestItemByItemId(int nItemId)
{
D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(nItemId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->nQuest < 1 && pItemsTxtRecord->wType[0] != ITEMTYPE_QUEST;
}
//D2Common.0x6FD9DEE0 (#10732)
int __stdcall ITEMS_GetFileIndex(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
D2_ASSERT(pItem->pItemData);
return pItem->pItemData->dwFileIndex;
}
//D2Common.0x6FD9DF60 (#10733)
void __stdcall ITEMS_SetFileIndex(D2UnitStrc* pItem, uint32_t dwFileIndex)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
D2_ASSERT(pItem->pItemData);
pItem->pItemData->dwFileIndex = dwFileIndex;
}
//D2Common.0x6FD9DFE0 (#11244)
void __stdcall ITEMS_GetRealmData(D2UnitStrc* pItem, int* pRealmData0, int* pRealmData1)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
*pRealmData0 = pItem->pItemData->dwRealmData[0];
*pRealmData1 = pItem->pItemData->dwRealmData[1];
}
else
{
*pRealmData0 = 0;
*pRealmData1 = 0;
}
}
//D2Common.0x6FD9E070 (#11245)
void __stdcall ITEMS_SetRealmData(D2UnitStrc* pItem, int a2, int a3)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
pItem->pItemData->dwRealmData[0] = a2;
pItem->pItemData->dwRealmData[1] = a3;
}
}
//D2Common.0x6FD9E0A0 (#10734)
void __stdcall ITEMS_SetOwnerId(D2UnitStrc* pItem, int nOwnerGUID)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
D2_ASSERT(pItem->pItemData);
pItem->pItemData->dwOwnerGUID = nOwnerGUID;
}
//D2Common.0x6FD9E120 (#10735)
int __stdcall ITEMS_GetOwnerId(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
D2_ASSERT(pItem->pItemData);
return pItem->pItemData->dwOwnerGUID;
}
//D2Common.0x6FD9E1A0 (#10736)
BOOL __stdcall ITEMS_IsBodyItem(D2UnitStrc* pItem)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord)
{
if (pItemTypesTxtRecord->nBodyLoc1 || pItemTypesTxtRecord->nBodyLoc2)
{
return pItemTypesTxtRecord->nBody;
}
}
}
}
return FALSE;
}
//D2Common.0x6FD9E2A0 (#10738)
BOOL __stdcall ITEMS_IsClassValidByItemId(int nItemId)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(nItemId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord)
{
return pItemTypesTxtRecord->nClass < 7;
}
}
return FALSE;
}
//D2Common.0x6FD9E310 (#10737)
BOOL __stdcall ITEMS_IsClassValid(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
return ITEMS_IsClassValidByItemId(pItem->dwClassId);
}
return FALSE;
}
//D2Common.0x6FD9E390 (#10739)
int __stdcall ITEMS_GetClassOfClassSpecificItem(D2UnitStrc* pItem)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord && pItemTypesTxtRecord->nClass < 7)
{
return pItemTypesTxtRecord->nClass;
}
}
}
return 7;
}
//D2Common.0x6FD9E410 (#10823)
uint16_t __stdcall ITEMS_GetWeaponClassId(D2UnitStrc* pItem)
{
static const D2CompositStrc stru_6FDE3C08[8] =
{
{ ' wob', WEAPONCLASS_BOW },
{ ' sh1', WEAPONCLASS_1HS },
{ ' th1', WEAPONCLASS_1HT },
{ ' fts', WEAPONCLASS_STF },
{ ' sh2', WEAPONCLASS_2HS },
{ ' th2', WEAPONCLASS_2HT },
{ ' wbx', WEAPONCLASS_XBW },
{ ' 1th', WEAPONCLASS_HT1 },
};
D2ItemsTxt* pItemsTxtRecord = NULL;
int nCounter = 0;
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem ? pItem->dwClassId : -1);
D2_ASSERT(pItemsTxtRecord);
while (pItemsTxtRecord->dwWeapClass != stru_6FDE3C08[nCounter].nWeaponClassCode)
{
++nCounter;
if (nCounter >= ARRAY_SIZE(stru_6FDE3C08))
{
return WEAPONCLASS_HTH;
}
}
return (uint16_t)stru_6FDE3C08[nCounter].nWeaponClassId;
}
//D2Common.0x6FD9E480 (#10824)
uint32_t __stdcall ITEMS_GetTransmogrifyFromItemId(int nItemId)
{
D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(nItemId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->nTransmogrify != 0;
}
//D2Common.0x6FD9E4C0 (#10825)
uint32_t __stdcall ITEMS_GetTransmogrify(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
return ITEMS_GetTransmogrifyFromItemId(pItem->dwClassId);
}
//D2Common.0x6FD9E550 (#10826)
int __stdcall ITEMS_IsMagSetRarUniCrfOrTmp(D2UnitStrc* pItem)
{
return pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData && pItem->pItemData->dwQualityNo >= ITEMQUAL_MAGIC && pItem->pItemData->dwQualityNo <= ITEMQUAL_TEMPERED;
}
//D2Common.0x6FD9E580 (#10740)
BOOL __stdcall ITEMS_IsNotQuestItem(D2UnitStrc* pItem)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
int nItemId = 0;
if (pItem)
{
if (pItem->dwUnitType == UNIT_ITEM && pItem->pItemData && pItem->pItemData->dwItemFlags & IFLAG_NOSELL)
{
return FALSE;
}
nItemId = pItem->dwClassId;
}
else
{
nItemId = -1;
}
return ITEMS_IsNotQuestItemByItemId(nItemId);
}
//D2Common.0x6FD9E5F0 (#10827)
uint8_t __stdcall ITEMS_GetHitClassFromItem(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->nHitClass;
}
//D2Common.0x6FD9E670 (#10828)
int __stdcall ITEMS_Is1Or2Handed(D2UnitStrc* pPlayer, D2UnitStrc* pItem)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
D2_ASSERT(pItem);
D2_ASSERT(pPlayer);
if (pPlayer->dwUnitType || pPlayer->dwClassId != PCLASS_BARBARIAN)
{
return FALSE;
}
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (!pItemsTxtRecord->n1or2Handed)
{
return FALSE;
}
return TRUE;
}
//D2Common.0x6FD9E710 (#10829)
uint8_t* __stdcall ITEMS_GetColor(D2UnitStrc* pPlayer, D2UnitStrc* pItem, uint8_t* pColor, int nTransType)
{
D2UniqueItemsTxt* pUniqueItemsTxtRecord = NULL;
D2MagicAffixTxt* pMagicAffixTxtRecord = NULL;
D2MagicAffixTxt* pAutoAffixTxtRecord = NULL;
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2SetItemsTxt* pSetItemsTxtRecord = NULL;
D2ItemsTxt* pGemItemsTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
D2StatesTxt* pStatesTxtRecord = NULL;
D2GemsTxt* pGemsTxtRecord = NULL;
D2UnitStrc* pInventoryItem = NULL;
int nItemQuality = 0;
int nGemSockets = 0;
int nMaxSockets = 0;
int nItemLevel = 0;
int nItemType = 0;
int nCounter = 0;
uint16_t nAutoAffix = 0;
if (!pItem)
{
return NULL;
}
if (pPlayer)
{
for (int i = 0; i < sgptDataTables->nColourStates; ++i)
{
if (STATES_CheckState(pPlayer, sgptDataTables->pColourStates[i]) && sgptDataTables->pColourStates[i] >= 0 && sgptDataTables->pColourStates[i] < sgptDataTables->nStatesTxtRecordCount)
{
pStatesTxtRecord = &sgptDataTables->pStatesTxt[sgptDataTables->pColourStates[i]];
if (pStatesTxtRecord && pStatesTxtRecord->nItemTrans < 21 && ITEMS_CheckItemTypeId(pItem, pStatesTxtRecord->wItemType))
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (pItemsTxtRecord)
{
return D2CMP_MixPalette(pItemsTxtRecord->nTransform, pStatesTxtRecord->nItemTrans);
}
}
}
}
}
if (pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
nItemQuality = pItem->pItemData->dwQualityNo;
}
else
{
nItemQuality = ITEMQUAL_NORMAL;
}
switch (nItemQuality)
{
case ITEMQUAL_MAGIC:
case ITEMQUAL_RARE:
nCounter = 0;
do
{
pMagicAffixTxtRecord = DATATBLS_GetMagicAffixTxtRecord(pItem->dwUnitType == UNIT_ITEM && pItem->pItemData ? pItem->pItemData->wMagicSuffix[nCounter] : 0);
if (pMagicAffixTxtRecord && pMagicAffixTxtRecord->nTransformColor != -1)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (pItemsTxtRecord->nTransform <= 0 || pItemsTxtRecord->nTransform >= 9 || pMagicAffixTxtRecord->nTransformColor >= 21)
{
*pColor = 0;
}
else
{
*pColor = (pMagicAffixTxtRecord->nTransformColor & 31) + 32 * pItemsTxtRecord->nTransform;
}
if (nTransType)
{
return D2CMP_MixPalette(pItemsTxtRecord->nInvTrans, pMagicAffixTxtRecord->nTransformColor);
}
else
{
return D2CMP_MixPalette(pItemsTxtRecord->nTransform, pMagicAffixTxtRecord->nTransformColor);
}
}
++nCounter;
}
while (nCounter < 3);
nCounter = 0;
do
{
pMagicAffixTxtRecord = DATATBLS_GetMagicAffixTxtRecord(pItem->dwUnitType == UNIT_ITEM && pItem->pItemData ? pItem->pItemData->wMagicPrefix[nCounter] : 0);
if (pMagicAffixTxtRecord && pMagicAffixTxtRecord->nTransformColor != -1)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (pItemsTxtRecord->nTransform <= 0 || pItemsTxtRecord->nTransform >= 9 || pMagicAffixTxtRecord->nTransformColor >= 21)
{
*pColor = 0;
}
else
{
*pColor = (pMagicAffixTxtRecord->nTransformColor & 31) + 32 * pItemsTxtRecord->nTransform;
}
if (nTransType)
{
return D2CMP_MixPalette(pItemsTxtRecord->nInvTrans, pMagicAffixTxtRecord->nTransformColor);
}
else
{
return D2CMP_MixPalette(pItemsTxtRecord->nTransform, pMagicAffixTxtRecord->nTransformColor);
}
}
++nCounter;
}
while (nCounter < 3);
break;
case ITEMQUAL_UNIQUE:
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (!pItemsTxtRecord)
{
return NULL;
}
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
D2_ASSERT(pItem->pItemData);
if (pItem->pItemData->dwFileIndex >= 0 && pItem->pItemData->dwFileIndex < sgptDataTables->nUniqueItemsTxtRecordCount)
{
pUniqueItemsTxtRecord = &sgptDataTables->pUniqueItemsTxt[pItem->pItemData->dwFileIndex];
if (pUniqueItemsTxtRecord)
{
if (nTransType)
{
if (pUniqueItemsTxtRecord->nInvTransform >= 0)
{
if (pItemsTxtRecord->nTransform <= 0 || pItemsTxtRecord->nTransform >= 9 || pUniqueItemsTxtRecord->nChrTransform < 0 || pUniqueItemsTxtRecord->nChrTransform >= 21)
{
*pColor = 0;
}
else
{
*pColor = (pUniqueItemsTxtRecord->nChrTransform & 31) + 32 * pItemsTxtRecord->nTransform;
}
return D2CMP_MixPalette(pItemsTxtRecord->nInvTrans, pUniqueItemsTxtRecord->nInvTransform);
}
}
else
{
if (pUniqueItemsTxtRecord->nChrTransform >= 0)
{
if (pItemsTxtRecord->nTransform <= 0 || pItemsTxtRecord->nTransform >= 9 || pUniqueItemsTxtRecord->nChrTransform < 0 || pUniqueItemsTxtRecord->nChrTransform >= 21)
{
*pColor = 0;
}
else
{
*pColor = (pUniqueItemsTxtRecord->nChrTransform & 31) + 32 * pItemsTxtRecord->nTransform;
}
return D2CMP_MixPalette(pItemsTxtRecord->nTransform, pUniqueItemsTxtRecord->nChrTransform);
}
}
}
}
return NULL;
case ITEMQUAL_SET:
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (!pItemsTxtRecord)
{
return NULL;
}
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
D2_ASSERT(pItem->pItemData);
if (pItem->pItemData->dwFileIndex >= 0 && pItem->pItemData->dwFileIndex < sgptDataTables->nSetItemsTxtRecordCount)
{
pSetItemsTxtRecord = &sgptDataTables->pSetItemsTxt[pItem->pItemData->dwFileIndex];
if (pSetItemsTxtRecord)
{
if (nTransType)
{
if (pSetItemsTxtRecord->nInvTransform >= 0)
{
if (pItemsTxtRecord->nTransform <= 0 || pItemsTxtRecord->nTransform >= 9 || pSetItemsTxtRecord->nChrTransform < 0 || pSetItemsTxtRecord->nChrTransform >= 21)
{
*pColor = 0;
}
else
{
*pColor = (pSetItemsTxtRecord->nChrTransform & 31) + 32 * pItemsTxtRecord->nTransform;
}
return D2CMP_MixPalette(pItemsTxtRecord->nInvTrans, pSetItemsTxtRecord->nInvTransform);
}
}
else
{
if (pSetItemsTxtRecord->nChrTransform >= 0)
{
if (pItemsTxtRecord->nTransform <= 0 || pItemsTxtRecord->nTransform >= 9 || pSetItemsTxtRecord->nChrTransform < 0 || pSetItemsTxtRecord->nChrTransform >= 21)
{
*pColor = 0;
}
else
{
*pColor = (pSetItemsTxtRecord->nChrTransform & 31) + 32 * pItemsTxtRecord->nTransform;
}
return D2CMP_MixPalette(pItemsTxtRecord->nTransform, pSetItemsTxtRecord->nChrTransform);
}
}
}
}
return NULL;
default:
if (pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (pItemsTxtRecord && pItemsTxtRecord->nHasInv)
{
nItemType = ITEMS_GetItemTypeFromItemId(pItem->dwClassId);
if (nItemType >= 0 && nItemType < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[nItemType];
if (pItemTypesTxtRecord)
{
nGemSockets = ITEMS_GetAllowedGemSocketsFromItemId(pItem->dwClassId);
nItemLevel = ITEMS_GetItemLevel(pItem);
if (nItemLevel > 25)
{
if (nItemLevel > 40)
{
nMaxSockets = pItemTypesTxtRecord->nMaxSock40;
}
else
{
nMaxSockets = pItemTypesTxtRecord->nMaxSock25;
}
}
else
{
nMaxSockets = pItemTypesTxtRecord->nMaxSock1;
}
if (nGemSockets >= nMaxSockets)
{
nGemSockets = nMaxSockets;
}
if (nGemSockets && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData && pItem->pItemData->dwItemFlags & IFLAG_SOCKETED)
{
pInventoryItem = INVENTORY_GetFirstItem(pItem->pInventory);
if (pInventoryItem && INVENTORY_UnitIsItem(pInventoryItem) && ITEMS_CheckItemTypeId(pInventoryItem, ITEMTYPE_GEM))
{
pGemItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pInventoryItem->dwClassId);
D2_ASSERT(pGemItemsTxtRecord);
pGemsTxtRecord = DATATBLS_GetGemsTxtRecord(pGemItemsTxtRecord->dwGemOffset);
if (pItemsTxtRecord->nTransform <= 0 || pItemsTxtRecord->nTransform >= 9 || pGemsTxtRecord->nTransForm >= 21)
{
*pColor = 0;
}
else
{
*pColor = (pGemsTxtRecord->nTransForm & 31) + 32 * pItemsTxtRecord->nTransform;
}
if (nTransType)
{
return D2CMP_MixPalette(pItemsTxtRecord->nInvTrans, pGemsTxtRecord->nTransForm);
}
else
{
return D2CMP_MixPalette(pItemsTxtRecord->nTransform, pGemsTxtRecord->nTransForm);
}
}
}
}
}
}
}
break;
}
if (pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
nAutoAffix = pItem->pItemData->wAutoAffix;
}
pAutoAffixTxtRecord = DATATBLS_GetMagicAffixTxtRecord(nAutoAffix);
if (pAutoAffixTxtRecord && pAutoAffixTxtRecord->nTransformColor != -1)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (pItemsTxtRecord->nTransform <= 0 || pItemsTxtRecord->nTransform >= 9 || pAutoAffixTxtRecord->nTransformColor >= 21)
{
*pColor = 0;
}
else
{
*pColor = (pAutoAffixTxtRecord->nTransformColor & 31) + 32 * pItemsTxtRecord->nTransform;
}
if (nTransType)
{
return D2CMP_MixPalette(pItemsTxtRecord->nInvTrans, pAutoAffixTxtRecord->nTransformColor);
}
else
{
return D2CMP_MixPalette(pItemsTxtRecord->nTransform, pAutoAffixTxtRecord->nTransformColor);
}
}
return NULL;
}
//D2Common.0x6FD9EE70
D2SetItemsTxt* __fastcall ITEMS_GetSetItemsTxtRecord(int nRecordId)
{
if (nRecordId >= 0 && nRecordId < sgptDataTables->nSetItemsTxtRecordCount)
{
return &sgptDataTables->pSetItemsTxt[nRecordId];
}
return NULL;
}
//D2Common.0x6FD9EEA0 (#10830)
BOOL __stdcall ITEMS_IsImbueable(D2UnitStrc* pItem)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
D2UnitStrc* pInventoryItem = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (pItemsTxtRecord && pItemsTxtRecord->wType[0] != ITEMTYPE_GOLD)
{
if (!pItem->pItemData || !(pItem->pItemData->dwItemFlags & IFLAG_NOSELL))
{
if (pItemsTxtRecord->dwBitField1 & 1)
{
pItemTypesTxtRecord = DATATBLS_GetItemTypesTxtRecord(ITEMS_GetItemTypeFromItemId(pItem->dwClassId));
if (pItem->dwFlagEx & UNITFLAGEX_ISEXPANSION || !pItemTypesTxtRecord || !pItemTypesTxtRecord->nThrowable)
{
if (!pItemsTxtRecord->nQuest || pItemsTxtRecord->dwCode == ' gel')
{
pInventoryItem = INVENTORY_GetFirstItem(pItem->pInventory);
if (pInventoryItem)
{
while (!INVENTORY_UnitIsItem(pInventoryItem))
{
pInventoryItem = INVENTORY_GetNextItem(pInventoryItem);
if (!pInventoryItem)
{
if ((!pItem->pItemData || !(pItem->pItemData->dwItemFlags & IFLAG_SOCKETED)) && (!pItem->pItemData || (pItem->pItemData->dwQualityNo >= 4 && pItem->pItemData->dwQualityNo <= 9)))
{
return TRUE;
}
break;
}
}
}
else
{
if ((!pItem->pItemData || !(pItem->pItemData->dwItemFlags & IFLAG_SOCKETED)) && (!pItem->pItemData || (pItem->pItemData->dwQualityNo >= 4 && pItem->pItemData->dwQualityNo <= 9)))
{
return TRUE;
}
}
}
}
}
}
}
}
return FALSE;
}
//D2Common.0x6FD9F080 (#10832)
BOOL __stdcall ITEMS_IsPersonalizable(D2UnitStrc* pItem)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
D2_ASSERT(pItem);
if (pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] == ITEMTYPE_GOLD || pItemsTxtRecord->wType[0] == ITEMTYPE_BOW_QUIVER
|| pItemsTxtRecord->wType[0] == ITEMTYPE_CROSSBOW_QUIVER || pItemsTxtRecord->wType[0] == ITEMTYPE_PLAYER_BODY_PART)
{
return FALSE;
}
if (pItem->pItemData && (pItem->pItemData->dwItemFlags & IFLAG_NOSELL || pItem->pItemData->dwItemFlags & IFLAG_BROKEN))
{
return FALSE;
}
if (!pItem->pItemData || !(pItem->pItemData->dwItemFlags & IFLAG_PERSONALIZED))
{
if (!pItemsTxtRecord->nCompactSave)
{
return pItemsTxtRecord->nNameable != 0;
}
}
}
return FALSE;
}
//D2Common.0x6FD9F260 (#10831)
BOOL __stdcall ITEMS_IsSocketable(D2UnitStrc* pItem)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
D2UnitStrc* pSocket = NULL;
uint8_t nAllowedSockets = 0;
int nMaxSockets = 0;
int nItemLevel = 0;
int nItemType = 0;
D2_ASSERT(pItem);
if (pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] == ITEMTYPE_GOLD)
{
return FALSE;
}
if (pItem->pItemData && pItem->pItemData->dwItemFlags & IFLAG_NOSELL)
{
return FALSE;
}
}
if (DATATBLS_GetItemsTxtRecord(pItem->dwClassId)->nQuest)
{
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->dwCode != ' gel')
{
return FALSE;
}
}
if (pItem->dwUnitType == UNIT_ITEM && pItem->pItemData && pItem->pItemData->dwItemFlags & IFLAG_BROKEN)
{
return FALSE;
}
pSocket = INVENTORY_GetFirstItem(pItem->pInventory);
if (pSocket)
{
while (!INVENTORY_UnitIsItem(pSocket))
{
pSocket = INVENTORY_GetNextItem(pSocket);
if (!pSocket)
{
break;
}
}
if (pSocket)
{
return FALSE;
}
}
if (pItem->dwUnitType != UNIT_ITEM || pItem->pItemData && pItem->pItemData->dwItemFlags & IFLAG_SOCKETED)
{
return FALSE;
}
nItemType = ITEMS_GetItemTypeFromItemId(pItem->dwClassId);
if (nItemType < 0 || nItemType >= sgptDataTables->nItemTypesTxtRecordCount)
{
return FALSE;
}
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[nItemType];
if (!pItemTypesTxtRecord)
{
return FALSE;
}
nAllowedSockets = ITEMS_GetAllowedGemSocketsFromItemId(pItem->dwClassId);
nItemLevel = ITEMS_GetItemLevel(pItem);
if (nItemLevel > 25)
{
if (nItemLevel > 40)
{
nMaxSockets = pItemTypesTxtRecord->nMaxSock40;
}
else
{
nMaxSockets = pItemTypesTxtRecord->nMaxSock25;
}
}
else
{
nMaxSockets = pItemTypesTxtRecord->nMaxSock1;
}
if (nAllowedSockets >= nMaxSockets)
{
nAllowedSockets = nMaxSockets;
}
if (!nAllowedSockets)
{
return 0;
}
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
return STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_NUMSOCKETS, 0) == 0;
}
//D2Common.0x6FD9F490 (#10877)
int __stdcall ITEMS_GetAllRepairCosts(D2GameStrc* pGame, D2UnitStrc* pUnit, int nNpcId, int nDifficulty, D2BitBufferStrc* pQuestFlags, void(__fastcall* pfCallback)(D2GameStrc*, D2UnitStrc*, D2UnitStrc*))
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
D2UnitStrc* pItem = NULL;
BOOL bCanBeRepaired = FALSE;
int nMaxDurability = 0;
int nRepairCosts = 0;
int nItemType = 0;
int nMaxStack = 0;
int nCounter = 0;
int nBodyLoc = 0;
int nStats = 0;
D2StatStrc pStat[64] = {};
if (!pUnit || !pUnit->pInventory)
{
return 0;
}
while (nBodyLoc < 13)
{
pItem = INVENTORY_GetItemFromBodyLoc(pUnit->pInventory, nBodyLoc);
if (pItem)
{
bCanBeRepaired = FALSE;
if (ITEMS_IsRepairable(pItem) && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (pItemsTxtRecord && !pItemsTxtRecord->nNoDurability && pItemsTxtRecord->nDurability && STATLIST_GetMaxDurabilityFromUnit(pItem) && STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_INDESCTRUCTIBLE, 0) <= 0)
{
nMaxDurability = STATLIST_GetMaxDurabilityFromUnit(pItem);
if (nMaxDurability && STATLIST_GetUnitStatUnsigned(pItem, STAT_DURABILITY, 0) != nMaxDurability)
{
bCanBeRepaired = TRUE;
}
}
}
if (pItem->dwUnitType == UNIT_ITEM)
{
nItemType = ITEMS_GetItemTypeFromItemId(pItem->dwClassId);
}
else
{
nItemType = 0;
}
if (nItemType >= 0 && nItemType < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[nItemType];
if (pItemTypesTxtRecord && pItemTypesTxtRecord->nRepair && pItem->dwUnitType == UNIT_ITEM && ITEMS_CheckItemTypeIfThrowable(ITEMS_GetItemType(pItem)))
{
if (ITEMS_CheckIfStackable(pItem) && !ITEMS_CheckItemFlag(pItem, IFLAG_ETHEREAL, __LINE__, __FILE__))
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
nMaxStack = STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_EXTRA_STACK, 0) + pItemsTxtRecord->dwMaxStack;
if (nMaxStack >= 511)
{
nMaxStack = 511;
}
if (STATLIST_GetUnitStatUnsigned(pItem, STAT_QUANTITY, 0) < nMaxStack)
{
bCanBeRepaired = TRUE;
}
}
}
}
nStats = D2Common_11270(pItem, STAT_ITEM_CHARGED_SKILL, pStat, ARRAY_SIZE(pStat));
if (nStats <= 0)
{
if (bCanBeRepaired)
{
nRepairCosts += ITEMS_CalculateTransactionCost(pUnit, pItem, nDifficulty, pQuestFlags, nNpcId, 3);
if (pfCallback)
{
pfCallback(pGame, pItem, pUnit);
}
}
}
else
{
nCounter = 0;
while ((uint8_t)pStat[nCounter].nValue >= pStat[nCounter].nValue >> 8)
{
++nCounter;
if (nCounter >= nStats)
{
if (bCanBeRepaired)
{
nRepairCosts += ITEMS_CalculateTransactionCost(pUnit, pItem, nDifficulty, pQuestFlags, nNpcId, 3);
if (pfCallback)
{
pfCallback(pGame, pItem, pUnit);
}
}
break;
}
}
}
}
++nBodyLoc;
}
return nRepairCosts;
}
//D2Common.0x6FD9F720 (#10833)
BOOL __stdcall ITEMS_AreStackablesEqual(D2UnitStrc* pItem1, D2UnitStrc* pItem2)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
if (!pItem1 || pItem1->dwUnitType != UNIT_ITEM || !pItem1->pItemData || !pItem2 || pItem2->dwUnitType != UNIT_ITEM || !pItem2->pItemData)
{
return FALSE;
}
if (pItem1->dwClassId != pItem2->dwClassId || pItem1->pItemData->dwQualityNo != pItem2->pItemData->dwQualityNo || pItem1->pItemData->dwFileIndex != pItem2->pItemData->dwFileIndex)
{
return FALSE;
}
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem1->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (!pItemsTxtRecord->nStackable)
{
return FALSE;
}
if((ITEMS_CheckItemFlag(pItem1, IFLAG_ETHEREAL, __LINE__, __FILE__) != ITEMS_CheckItemFlag(pItem2, IFLAG_ETHEREAL, __LINE__, __FILE__))
|| !pItem1->pItemData->dwQualityNo || pItem1->pItemData->dwQualityNo > 3 && pItem1->pItemData->dwQualityNo <= 9
|| !pItem2->pItemData->dwQualityNo || pItem2->pItemData->dwQualityNo > 3 && pItem2->pItemData->dwQualityNo <= 9
|| STATLIST_GetUnitStatUnsigned(pItem1, STAT_MINDAMAGE, 0) != STATLIST_GetUnitStatUnsigned(pItem2, STAT_MINDAMAGE, 0)
|| STATLIST_GetUnitStatUnsigned(pItem1, STAT_MAXDAMAGE, 0) != STATLIST_GetUnitStatUnsigned(pItem2, STAT_MAXDAMAGE, 0)
|| STATLIST_GetUnitStatUnsigned(pItem1, STAT_SECONDARY_MINDAMAGE, 0) != STATLIST_GetUnitStatUnsigned(pItem2, STAT_SECONDARY_MINDAMAGE, 0)
|| STATLIST_GetUnitStatUnsigned(pItem1, STAT_SECONDARY_MAXDAMAGE, 0) != STATLIST_GetUnitStatUnsigned(pItem2, STAT_SECONDARY_MAXDAMAGE, 0)
|| STATLIST_GetUnitStatUnsigned(pItem1, STAT_ITEM_THROW_MINDAMAGE, 0) != STATLIST_GetUnitStatUnsigned(pItem2, STAT_ITEM_THROW_MINDAMAGE, 0)
|| STATLIST_GetUnitStatUnsigned(pItem1, STAT_ITEM_THROW_MAXDAMAGE, 0) != STATLIST_GetUnitStatUnsigned(pItem2, STAT_ITEM_THROW_MAXDAMAGE, 0))
{
return FALSE;
}
if (STATLIST_GetUnitStatUnsigned(pItem1, STAT_ITEM_NUMSOCKETS, 0) || STATLIST_GetUnitStatUnsigned(pItem2, STAT_ITEM_NUMSOCKETS, 0))
{
return FALSE;
}
else
{
return TRUE;
}
}
//D2Common.0x6FD9FA70 (#10834)
BOOL __stdcall ITEMS_CanItemBeUsedForThrowSkill(D2UnitStrc* pItem)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
int nStack = 0;
if (pItem)
{
if (STATLIST_GetUnitStatUnsigned(pItem, STAT_QUANTITY, 0) > 0)
{
return TRUE;
}
if (STATLIST_GetUnitStatSigned(pItem, STAT_ITEM_THROWABLE, 0))
{
STATLIST_SetUnitStat(pItem, STAT_QUANTITY, 0, 0);
return TRUE;
}
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
nStack = STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_EXTRA_STACK, 0) + pItemsTxtRecord->dwMaxStack;
if (nStack < 511 && nStack <= 0)
{
return TRUE;
}
}
return FALSE;
}
//D2Common.0x6FD9FB40 (#11079)
int __stdcall D2COMMON_11079_Return0(int a1, int a2)
{
REMOVE_LATER_WriteToLogFile("D2COMMON_11079_Return0: Useless");
return 0;
}
//D2Common.0x6FD9FB50 (#10836)
uint32_t __stdcall ITEMS_GetSetItemsMask(D2UnitStrc* pPlayer, D2UnitStrc* pSetItem, BOOL bSkipItem)
{
D2SetItemsTxt* pSetItemsTxtRecord = NULL;
D2ItemDataStrc* pItemData = NULL;
uint32_t nSetItemMask = 0;
int nFileIndex = 0;
if (!pPlayer || !pSetItem || pSetItem->dwUnitType != UNIT_ITEM || !pSetItem->pItemData || pSetItem->pItemData->dwQualityNo != ITEMQUAL_SET || !pPlayer->pInventory)
{
return 0;
}
nFileIndex = pSetItem->pItemData->dwFileIndex;
if (nFileIndex >= 0 && nFileIndex < sgptDataTables->nSetItemsTxtRecordCount)
{
pSetItemsTxtRecord = &sgptDataTables->pSetItemsTxt[nFileIndex];
if (pSetItemsTxtRecord && pSetItemsTxtRecord->nSetId >= 0 && pSetItemsTxtRecord->nSetId < sgptDataTables->nSetsTxtRecordCount && &sgptDataTables->pSetsTxt[pSetItemsTxtRecord->nSetId])
{
for (D2UnitStrc* i = INVENTORY_GetFirstItem(pPlayer->pInventory); i; i = INVENTORY_GetNextItem(i))
{
if (INVENTORY_GetItemNodePage(i) == 3)
{
if (INVENTORY_UnitIsItem(i) && (bSkipItem || i != pSetItem))
{
pItemData = i->pItemData;
if (pItemData && pItemData->dwQualityNo == ITEMQUAL_SET && !(pItemData->dwItemFlags & IFLAG_NOEQUIP) && !(pItemData->dwItemFlags & IFLAG_BROKEN))
{
nFileIndex = pItemData->dwFileIndex;
if (nFileIndex >= 0 && nFileIndex < sgptDataTables->nSetItemsTxtRecordCount)
{
pSetItemsTxtRecord = &sgptDataTables->pSetItemsTxt[nFileIndex];
if (pSetItemsTxtRecord && pSetItemsTxtRecord->nSetId == pSetItemsTxtRecord->nSetId)
{
nSetItemMask |= 1 << LOBYTE(pSetItemsTxtRecord->nSetItems);
}
}
}
}
}
}
return nSetItemMask;
}
}
return 0;
}
//D2Common.0x6FD9FD80 (#10838)
D2SetItemsTxt* __stdcall ITEMS_GetSetItemsTxtRecordFromItem(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData && pItem->pItemData->dwQualityNo == ITEMQUAL_SET)
{
if (pItem->pItemData->dwFileIndex >= 0 && pItem->pItemData->dwFileIndex < sgptDataTables->nSetItemsTxtRecordCount)
{
return &sgptDataTables->pSetItemsTxt[pItem->pItemData->dwFileIndex];
}
}
return NULL;
}
//D2Common.0x6FD9FE20 (#10839)
BOOL __stdcall ITEMS_CanBeEquipped(D2UnitStrc* pItem)
{
if (pItem)
{
if (pItem->dwUnitType != UNIT_ITEM || !pItem->pItemData)
{
return TRUE;
}
return (!(pItem->pItemData->dwItemFlags & IFLAG_BROKEN) && !(pItem->pItemData->dwItemFlags & IFLAG_NOEQUIP));
}
return FALSE;
}
//D2Common.0x6FD9FE70 (#10840)
BOOL __stdcall ITEMS_IsCharmUsable(D2UnitStrc* pItem, D2UnitStrc* pPlayer)
{
if (!pItem || pItem->dwUnitType == UNIT_ITEM && (pItem->pItemData && (pItem->pItemData->dwItemFlags & IFLAG_BROKEN || pItem->pItemData->dwItemFlags & IFLAG_NOEQUIP)))
{
return FALSE;
}
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_CHARM))
{
if (pItem->dwUnitType == UNIT_ITEM && pItem->pItemData->nInvPage == INVPAGE_INVENTORY)
{
return ITEMS_CheckRequirements(pItem, pPlayer, FALSE, NULL, NULL, NULL) != 0;
}
}
return FALSE;
}
//D2Common.0x6FD9FF00 (#10776)
int __stdcall ITEMS_GetNoOfUnidItems(D2UnitStrc* pUnit)
{
D2UnitStrc* pItem = NULL;
int nUnidItems = 0;
int nNodePage = 0;
pItem = INVENTORY_GetFirstItem(pUnit->pInventory);
if (pItem)
{
nUnidItems = 0;
while (INVENTORY_UnitIsItem(pItem))
{
if (!pItem->pItemData || !(pItem->pItemData->dwItemFlags & IFLAG_IDENTIFIED))
{
nNodePage = INVENTORY_GetItemNodePage(pItem);
if (nNodePage != 1)
{
if (nNodePage == 3)
{
++nUnidItems;
}
}
else
{
if (pItem->pItemData && (pItem->pItemData->nInvPage == INVPAGE_CUBE || pItem->pItemData->nInvPage == INVPAGE_INVENTORY))
{
++nUnidItems;
}
}
}
pItem = INVENTORY_GetNextItem(pItem);
if (!pItem)
{
return nUnidItems;
}
}
}
return 0;
}
//D2Common.0x6FD9FF90 (#10841)
int __stdcall ITEMS_GetBonusLifeBasedOnClass(D2UnitStrc* pPlayer, int nValue)
{
if (!pPlayer || pPlayer->dwUnitType != UNIT_PLAYER)
{
return 2 * nValue;
}
else
{
switch (pPlayer->dwClassId)
{
case PCLASS_AMAZON:
case PCLASS_PALADIN:
case PCLASS_ASSASSIN:
return nValue + (nValue >> 1);
case PCLASS_BARBARIAN:
return 2 * nValue;
default:
return nValue;
}
}
}
//D2Common.0x6FD9FFE0 (#10842)
int __stdcall ITEMS_GetBonusManaBasedOnClass(D2UnitStrc* pPlayer, int nValue)
{
if (pPlayer && pPlayer->dwUnitType == UNIT_PLAYER)
{
switch (pPlayer->dwClassId)
{
case PCLASS_SORCERESS:
case PCLASS_NECROMANCER:
case PCLASS_DRUID:
return 2 * nValue;
case PCLASS_AMAZON:
case PCLASS_PALADIN:
case PCLASS_ASSASSIN:
return nValue + (nValue >> 1);
default:
return nValue;
}
}
return nValue;
}
//D2Common.0x6FDA0030 (#10875)
uint16_t __stdcall ITEMS_GetItemFormat(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
D2_ASSERT(pItem->pItemData);
return pItem->pItemData->wItemFormat;
}
//D2Common.0x6FDA00B0 (#10876)
void __stdcall ITEMS_SetItemFormat(D2UnitStrc* pItem, uint16_t nItemFormat)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
D2_ASSERT(pItem->pItemData);
pItem->pItemData->wItemFormat = nItemFormat;
}
//D2Common.0x6FDA0130 (#10878)
int __stdcall ITEMS_GetWeaponAttackSpeed(D2UnitStrc* pUnit, D2UnitStrc* pWeapon)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
int nWeaponClass = 0;
int v11 = 0;
int v13 = 0;
char szPath[8] = {};
int nLength = 0;
D2_ASSERT(pWeapon && pWeapon->dwUnitType == UNIT_ITEM);
D2_ASSERT(ITEMS_CheckItemTypeId(pWeapon, ITEMTYPE_WEAPON));
D2_ASSERT(pUnit);
if (pWeapon->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pWeapon->dwClassId);
if (pItemsTxtRecord)
{
nWeaponClass = pItemsTxtRecord->dwWeapClass;
}
}
D2Common_10884_COMPOSIT_unk(pUnit, pUnit->dwClassId, PLRMODE_ATTACK1, pUnit->dwUnitType, pUnit->pInventory, szPath, &nWeaponClass, 0, 0);
if (D2Common_10641(szPath, &nLength, &v11, &v13))
{
D2_ASSERT(nLength);
return (nLength << 8) / (v11 * (STATLIST_GetUnitStatUnsigned(pWeapon, STAT_ATTACKRATE, 0) + STATLIST_GetUnitStatSigned(pWeapon, STAT_ITEM_FASTERATTACKRATE, 0) + 100) / 100);
}
return 45;
}
//D2Common.0x6FDA02B0 (#10879)
int __stdcall ITEMS_HasUsedCharges(D2UnitStrc* pItem, BOOL* pHasChargedSkills)
{
D2StatStrc pStat[64] = {};
int nCounter = 0;
int nStats = 0;
if (pHasChargedSkills)
{
*pHasChargedSkills = TRUE;
}
nStats = D2Common_11270(pItem, STAT_ITEM_CHARGED_SKILL, pStat, ARRAY_SIZE(pStat));
if (nStats <= 0)
{
return FALSE;
}
else
{
if (pHasChargedSkills)
{
nCounter = 0;
if (nStats > 0)
{
while ((uint8_t)pStat[nCounter].nValue >= (pStat[nCounter].nValue >> 8))
{
++nCounter;
if (nCounter >= nStats)
{
return TRUE;
}
}
*pHasChargedSkills = FALSE;
}
}
return TRUE;
}
}
//D2Common.0x6FDA0340 (#10880)
BOOL __stdcall ITEMS_IsEthereal(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->dwItemFlags & IFLAG_ETHEREAL;
}
return 0;
}
//D2Common.0x6FDA0370 (#10883)
BOOL __stdcall ITEMS_GetCompactItemDataFromBitstream(uint8_t* pBitstream, size_t nSize, BOOL bCheckForHeader, D2ItemSaveStrc* pItemSave)
{
D2BitBufferStrc pBuffer = {};
int dwCode = 0;
BITMANIP_Initialize(&pBuffer, pBitstream, nSize);
if (bCheckForHeader && BITMANIP_ReadSigned(&pBuffer, 16) != 'MJ')
{
return FALSE;
}
else
{
pItemSave->dwFlags = BITMANIP_Read(&pBuffer, 32);
BITMANIP_Read(&pBuffer, 10);
pItemSave->nAnimMode = (uint8_t)BITMANIP_Read(&pBuffer, 3);
if (pItemSave->nAnimMode == IMODE_ONGROUND || pItemSave->nAnimMode == IMODE_DROPPING)
{
pItemSave->nX = (uint16_t)BITMANIP_Read(&pBuffer, 16);
pItemSave->nY = (uint16_t)BITMANIP_Read(&pBuffer, 16);
}
else
{
pItemSave->nBodyloc = (uint8_t)BITMANIP_Read(&pBuffer, 4);
pItemSave->nX = (uint16_t)BITMANIP_Read(&pBuffer, 4);
pItemSave->nY = (uint16_t)BITMANIP_Read(&pBuffer, 4);
pItemSave->nStorePage = (uint8_t)BITMANIP_Read(&pBuffer, 3) - 1;
}
if (pItemSave->dwFlags & IFLAG_ISEAR)
{
dwCode = ' rae';
}
else
{
dwCode = BITMANIP_Read(&pBuffer, 32);
}
pItemSave->nClassId = DATATBLS_GetItemIdFromItemCode(dwCode);
if (!(pItemSave->dwFlags & (IFLAG_LOWQUALITY | IFLAG_COMPACTSAVE)))
{
pItemSave->nItemFileIndex = BITMANIP_Read(&pBuffer, 3);
}
else
{
pItemSave->nItemFileIndex = 0;
}
return TRUE;
}
}
//D2Common.0x6FDA0490 (#10882)
size_t __stdcall ITEMS_DecodeItemFromBitstream(D2UnitStrc* pItem, uint8_t* pBitstream, size_t nSize, BOOL bCheckForHeader, int* pSocketedItemCount, uint32_t dwVersion, BOOL* pFail)
{
D2BitBufferStrc pBuffer = {};
uint32_t dwFlags = 0;
BOOL bGamble = FALSE;
BITMANIP_Initialize(&pBuffer, pBitstream, nSize);
if (bCheckForHeader && BITMANIP_ReadSigned(&pBuffer, 16) != 'MJ')
{
*pFail = TRUE;
return 0;
}
*pFail = FALSE;
dwFlags = BITMANIP_Read(&pBuffer, 32);
if (dwFlags & IFLAG_LOWQUALITY)
{
bGamble = TRUE;
dwFlags &= ~IFLAG_LOWQUALITY;
}
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
pItem->pItemData->dwItemFlags = dwFlags;
pItem->pItemData->dwItemFlags &= ~IFLAG_INIT;
pItem->pItemData->dwItemLevel = 1;
for (int i = 0; i < 3; ++i)
{
pItem->pItemData->wMagicPrefix[i] = 0;
pItem->pItemData->wMagicSuffix[i] = 0;
}
pItem->pItemData->wRarePrefix = 0;
pItem->pItemData->wRareSuffix = 0;
}
if (dwFlags & IFLAG_COMPACTSAVE)
{
if (pSocketedItemCount)
{
*pSocketedItemCount = 0;
}
if (ITEMS_DecodeItemBitstreamCompact(pItem, &pBuffer, bCheckForHeader, dwVersion) <= 0)
{
*pFail = TRUE;
}
}
else
{
if (ITEMS_DecodeItemBitstreamComplete(pItem, &pBuffer, bCheckForHeader, bGamble, pSocketedItemCount, dwVersion) <= 0)
{
*pFail = TRUE;
}
}
return BITMANIP_GetSize(&pBuffer);
}
//D2Common.0x6FDA0620
int __fastcall ITEMS_DecodeItemBitstreamCompact(D2UnitStrc* pItem, D2BitBufferStrc* pBuffer, BOOL bCheckForHeader, uint32_t dwVersion)
{
D2ItemStatCostTxt* pItemStatCostTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
D2ItemDataStrc* pItemData = NULL;
D2StatListStrc* pStatList = NULL;
int nBits = 0;
int nItemId = 0;
int nValue = 0;
uint32_t dwCode = 0;
char szChar = 0;
uint8_t nAnimMode = 0;
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
pItemData = pItem->pItemData;
D2_ASSERT(pItemData);
pItemData->wItemFormat = (uint16_t)BITMANIP_Read(pBuffer, 10);
nAnimMode = (uint8_t)BITMANIP_Read(pBuffer, 3);
if (nAnimMode == IMODE_ONGROUND || nAnimMode == IMODE_DROPPING)
{
UNITS_SetXForStaticUnit(pItem, BITMANIP_Read(pBuffer, 16));
UNITS_SetYForStaticUnit(pItem, BITMANIP_Read(pBuffer, 16));
}
else
{
pItemData->nBodyLoc = (uint8_t)BITMANIP_Read(pBuffer, 4);
UNITS_SetXForStaticUnit(pItem, BITMANIP_Read(pBuffer, 4));
UNITS_SetYForStaticUnit(pItem, BITMANIP_Read(pBuffer, 4));
pItemData->nInvPage = (uint8_t)BITMANIP_Read(pBuffer, 3) - 1;
}
UNITS_ChangeAnimMode(pItem, nAnimMode);
if (pItemData->dwItemFlags & IFLAG_ISEAR)
{
pItemData->dwFileIndex = BITMANIP_Read(pBuffer, 3);
pItemData->nEarLvl = (uint8_t)BITMANIP_Read(pBuffer, 7);
int i = 0;
do
{
szChar = (char)BITMANIP_Read(pBuffer, 7);
pItemData->szPlayerName[i] = szChar;
++i;
}
while (szChar);
}
else
{
dwCode = BITMANIP_Read(pBuffer, 32);
pItem->dwClassId = DATATBLS_GetItemIdFromItemCode(dwCode);
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_GOLD))
{
if (BITMANIP_Read(pBuffer, 1))
{
nBits = 32;
}
else
{
nBits = 12;
}
STATLIST_SetUnitStat(pItem, STAT_GOLD, BITMANIP_Read(pBuffer, nBits), 0);
}
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_SCROLL))
{
if (dwCode == ' cst')
{
pItemData->wMagicSuffix[0] = 0;
}
else if (dwCode == ' csi')
{
pItemData->wMagicSuffix[0] = 1;
}
}
}
if (dwVersion > 92)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
pItemsTxtRecord = DATATBLS_GetItemRecordFromItemCode(pItemsTxtRecord->dwCode, &nItemId);
if (!pItemsTxtRecord)
{
return -1;
}
if (pItemsTxtRecord->nQuest && pItemsTxtRecord->nQuestDiffCheck)
{
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_QUESTITEMDIFFICULTY);
nValue = (BITMANIP_Read(pBuffer, pItemStatCostTxtRecord->nSaveBits) - pItemStatCostTxtRecord->dwSaveAdd) << pItemStatCostTxtRecord->nValShift;
pStatList = STATLIST_GetStatListFromUnitStateOrFlag(pItem, STATE_NONE, 0x40);
if (!pStatList)
{
pStatList = STATLIST_AllocStatList(pItem->pMemoryPool, 0x40, 0, UNIT_ITEM, pItem->dwUnitId);
D2COMMON_10475_PostStatToStatList(pItem, pStatList, 1);
}
if (pStatList)
{
STATLIST_SetStat(pStatList, STAT_QUESTITEMDIFFICULTY, nValue, 0);
}
}
}
if (bCheckForHeader && dwVersion > 86 && BITMANIP_Read(pBuffer, 1))
{
pItemData->dwRealmData[0] = BITMANIP_Read(pBuffer, 32);
pItemData->dwRealmData[1] = BITMANIP_Read(pBuffer, 32);
if (dwVersion > 93)
{
BITMANIP_Read(pBuffer, 32);
}
}
pItem->dwInitSeed = 0;
SEED_InitLowSeed(&pItem->pSeed, 0);
pItemData->dwItemLevel = 1;
pItemData->dwQualityNo = ITEMQUAL_NORMAL;
return 1;
}
//D2Common.0x6FDA0A20
int __fastcall ITEMS_DecodeItemBitstreamComplete(D2UnitStrc* pItem, D2BitBufferStrc* pBuffer, BOOL bCheckForHeader, BOOL bGamble, int* pSocketedItems, uint32_t dwVersion)
{
static const int gnItemSetStates[] =
{
STATE_ITEMSET1, STATE_ITEMSET2, STATE_ITEMSET3, STATE_ITEMSET4, STATE_ITEMSET5
};
D2ItemStatCostTxt* pItemStatCostTxtRecord = NULL;
D2MagicAffixDataTbl* pMagicAffixDataTbl = NULL;
D2SetItemsTxt* pSetItemsTxtRecord = NULL;
D2SkillsTxt* pSkillsTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
D2SetsTxt* pSetsTxtRecord = NULL;
D2ItemDataStrc* pItemData = NULL;
D2StatListStrc* pStatList = NULL;
char* szName = NULL;
int nMagicPrefixOffset = 0;
int nAutoMagicOffset = 0;
int nSocketedItems = 0;
int nSetItemMask = 0;
int nSetRecordId = 0;
int nLastStatId = 0;
int nMaxSockets = 0;
int nStatLists = 0;
int nAnimMode = 0;
int nClassId = 0;
int nSkillId = 0;
int nStatId = 0;
int nState = 0;
int nValue = 0;
int nBits = 0;
int nFlag = 0;
int nMax = 0;
int v237, v238, v240, v241, v242, v243, v244, v245, v246, v247, v248, v249, v250, v251, v252; //TODO: Change names
uint32_t dwCode = 0;
char szChar = 0;
BOOL bRuneword = FALSE;
BOOL bError = FALSE;
BOOL b109 = FALSE;
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
pItemData = pItem->pItemData;
D2_ASSERT(pItemData);
pItemData->wItemFormat = (uint16_t)BITMANIP_Read(pBuffer, 10);
nAnimMode = BITMANIP_Read(pBuffer, 3);
if (nAnimMode == IMODE_ONGROUND || nAnimMode == IMODE_DROPPING)
{
UNITS_SetXForStaticUnit(pItem, BITMANIP_Read(pBuffer, 16));
UNITS_SetYForStaticUnit(pItem, BITMANIP_Read(pBuffer, 16));
}
else
{
pItemData->nBodyLoc = (uint8_t)BITMANIP_Read(pBuffer, 4);
UNITS_SetXForStaticUnit(pItem, BITMANIP_Read(pBuffer, 4));
UNITS_SetYForStaticUnit(pItem, BITMANIP_Read(pBuffer, 4));
pItemData->nInvPage = (uint8_t)(BITMANIP_Read(pBuffer, 3) - 1);
}
UNITS_ChangeAnimMode(pItem, nAnimMode);
dwCode = BITMANIP_Read(pBuffer, 32);
nClassId = DATATBLS_GetItemIdFromItemCode(dwCode);
if (nClassId >= 0)
{
pItem->dwClassId = nClassId;
}
if (bGamble)
{
pItemData->dwItemLevel = 1;
pItemData->dwQualityNo = ITEMQUAL_INFERIOR;
return 1;
}
nSocketedItems = BITMANIP_Read(pBuffer, 3);
if (pSocketedItems)
{
*pSocketedItems = nSocketedItems;
}
if (bCheckForHeader)
{
pItem->dwInitSeed = BITMANIP_Read(pBuffer, 32);
SEED_InitLowSeed(&pItem->pSeed, pItem->dwInitSeed);
}
pItemData->dwItemLevel = BITMANIP_Read(pBuffer, 7);
if (pItemData->dwItemLevel < 1)
{
pItemData->dwItemLevel = 1;
}
pItemData->dwQualityNo = BITMANIP_Read(pBuffer, 4);
if (BITMANIP_Read(pBuffer, 1))
{
pItemData->nInvGfxIdx = (uint8_t)BITMANIP_Read(pBuffer, 3);
}
pMagicAffixDataTbl = DATATBLS_GetMagicAffixDataTables();
nMagicPrefixOffset = pMagicAffixDataTbl->pMagicPrefix - pMagicAffixDataTbl->pMagicAffixTxt;
nAutoMagicOffset = pMagicAffixDataTbl->pAutoMagic - pMagicAffixDataTbl->pMagicAffixTxt;
switch (dwVersion)
{
case 72:
case 73:
case 80:
case 81:
case 82:
nMagicPrefixOffset -= 661;
nAutoMagicOffset -= 1262;
break;
case 83:
case 84:
nMagicPrefixOffset -= 674;
nAutoMagicOffset -= 1265;
break;
case 85:
case 86:
case 87:
nMagicPrefixOffset -= 675;
nAutoMagicOffset -= 1266;
break;
case 88:
nMagicPrefixOffset -= 729;
nAutoMagicOffset -= 1440;
break;
default:
break;
}
if (BITMANIP_Read(pBuffer, 1))
{
pItemData->wAutoAffix = (uint16_t)BITMANIP_Read(pBuffer, 11);
if (dwVersion > 88)
{
if (dwVersion <= 89)
{
++pItemData->wAutoAffix;
}
if (pItemData->wAutoAffix)
{
pItemData->wAutoAffix += nAutoMagicOffset;
}
}
else
{
pItemData->wAutoAffix = 0;
}
}
else
{
pItemData->wAutoAffix = 0;
}
switch (pItemData->dwQualityNo)
{
case ITEMQUAL_INFERIOR:
case ITEMQUAL_SUPERIOR:
{
pItemData->dwFileIndex = BITMANIP_Read(pBuffer, 3);
break;
}
case ITEMQUAL_NORMAL:
{
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_CHARM))
{
if (bCheckForHeader || pItemData->dwItemFlags & IFLAG_IDENTIFIED)
{
if (BITMANIP_Read(pBuffer, 1))
{
pItemData->wMagicPrefix[0] = (uint16_t)BITMANIP_Read(pBuffer, 11);
if (pItemData->wMagicPrefix[0])
{
pItemData->wMagicPrefix[0] += nMagicPrefixOffset;
}
}
else
{
pItemData->wMagicSuffix[0] = (uint16_t)BITMANIP_Read(pBuffer, 11);
}
}
}
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_BODY_PART) && !ITEMS_CheckItemTypeId(pItem, ITEMTYPE_PLAYER_BODY_PART))
{
pItemData->dwFileIndex = BITMANIP_Read(pBuffer, 10);
}
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_SCROLL) || ITEMS_CheckItemTypeId(pItem, ITEMTYPE_BOOK))
{
pItemData->wMagicSuffix[0] = (uint16_t)BITMANIP_Read(pBuffer, 5);
}
break;
}
case ITEMQUAL_RARE:
case ITEMQUAL_CRAFT:
{
if (bCheckForHeader || pItemData->dwItemFlags & IFLAG_IDENTIFIED)
{
pItemData->wRarePrefix = (uint16_t)BITMANIP_Read(pBuffer, 8);
pItemData->wRareSuffix = (uint16_t)BITMANIP_Read(pBuffer, 8);
}
for (int i = 0; i < 3; ++i)
{
if (BITMANIP_Read(pBuffer, 1))
{
pItemData->wMagicPrefix[i] = (uint16_t)BITMANIP_Read(pBuffer, 11);
if (dwVersion <= 89)
{
++pItemData->wMagicPrefix[i];
}
if (pItemData->wMagicPrefix[i])
{
pItemData->wMagicPrefix[i] += nMagicPrefixOffset;
}
}
else
{
pItemData->wMagicPrefix[i] = 0;
}
if (BITMANIP_Read(pBuffer, 1))
{
pItemData->wMagicSuffix[i] = (uint16_t)BITMANIP_Read(pBuffer, 11);
if (dwVersion <= 89)
{
++pItemData->wMagicSuffix[i];
}
}
else
{
pItemData->wMagicSuffix[i] = 0;
}
}
break;
}
case ITEMQUAL_TEMPERED:
{
if (bCheckForHeader || pItemData->dwItemFlags & IFLAG_IDENTIFIED)
{
pItemData->wRarePrefix = (uint16_t)BITMANIP_Read(pBuffer, 8);
pItemData->wRareSuffix = (uint16_t)BITMANIP_Read(pBuffer, 8);
}
break;
}
case ITEMQUAL_MAGIC:
{
if (bCheckForHeader || pItemData->dwItemFlags & IFLAG_IDENTIFIED)
{
pItemData->wMagicPrefix[0] = (uint16_t)BITMANIP_Read(pBuffer, 11);
if (pItemData->wMagicPrefix[0])
{
pItemData->wMagicPrefix[0] += nMagicPrefixOffset;
}
pItemData->wMagicSuffix[0] = (uint16_t)BITMANIP_Read(pBuffer, 11);
}
break;
}
case ITEMQUAL_UNIQUE:
{
if (bCheckForHeader || pItemData->dwItemFlags & IFLAG_IDENTIFIED)
{
pItemData->dwFileIndex = BITMANIP_Read(pBuffer, 12);
if (pItemData->dwFileIndex < 0 || pItemData->dwFileIndex >= sgptDataTables->nUniqueItemsTxtRecordCount)
{
pItemData->dwFileIndex = -1;
}
}
break;
}
case ITEMQUAL_SET:
{
if (bCheckForHeader || pItemData->dwItemFlags & IFLAG_IDENTIFIED)
{
bError = TRUE;
nSetRecordId = BITMANIP_Read(pBuffer, 12);
if (dwVersion > 92)
{
if (nSetRecordId >= 0 && nSetRecordId < sgptDataTables->nSetItemsTxtRecordCount)
{
pSetItemsTxtRecord = &sgptDataTables->pSetItemsTxt[nSetRecordId];
if (pSetItemsTxtRecord)
{
pItemData->dwFileIndex = pSetItemsTxtRecord->wSetItemId;
bError = FALSE;
}
}
}
else
{
if (nSetRecordId >= 0 && nSetRecordId < sgptDataTables->nSetsTxtRecordCount)
{
pSetsTxtRecord = &sgptDataTables->pSetsTxt[nSetRecordId];
if (pSetsTxtRecord)
{
for (int i = 0; i < pSetsTxtRecord->nSetItems; ++i)
{
if (pSetsTxtRecord->pSetItem[i]->szItemCode == dwCode)
{
pItemData->dwFileIndex = pSetsTxtRecord->pSetItem[i]->wSetItemId;
bError = FALSE;
break;
}
}
}
}
}
}
break;
}
default:
{
bError = TRUE;
break;
}
}
if (pItemData->dwItemFlags & IFLAG_RUNEWORD)
{
bRuneword = TRUE;
pItemData->wMagicPrefix[0] = (uint16_t)BITMANIP_Read(pBuffer, 16);
}
if (pItemData->dwItemFlags & IFLAG_ISEAR)
{
pItemData->dwFileIndex = BITMANIP_Read(pBuffer, 3);
pItemData->nEarLvl = (uint8_t)BITMANIP_Read(pBuffer, 7);
szName = pItemData->szPlayerName;
do
{
szChar = (char)BITMANIP_Read(pBuffer, 7);
*szName++ = szChar;
}
while (szChar);
}
else if (pItemData->dwItemFlags & IFLAG_PERSONALIZED)
{
szName = pItemData->szPlayerName;
do
{
szChar = (char)BITMANIP_Read(pBuffer, 7);
*szName++ = szChar;
}
while (szChar);
}
if (bCheckForHeader && dwVersion > 86 && BITMANIP_Read(pBuffer, 1))
{
pItemData->dwRealmData[0] = BITMANIP_Read(pBuffer, 32);
pItemData->dwRealmData[1] = BITMANIP_Read(pBuffer, 32);
if (dwVersion > 93)
{
BITMANIP_Read(pBuffer, 32);
}
}
if (dwVersion < 93)
{
b109 = TRUE;
}
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_ANY_ARMOR))
{
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_ARMORCLASS);
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits)) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetUnitStat(pItem, STAT_ARMORCLASS, nValue, 0);
STATLIST_SetUnitStat(pItem, STAT_TOBLOCK, pItemsTxtRecord->nBlock, 0);
STATLIST_SetUnitStat(pItem, STAT_VELOCITYPERCENT, -pItemsTxtRecord->dwSpeed, 0);
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_MAXDURABILITY);
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits)) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetUnitStat(pItem, STAT_MAXDURABILITY, nValue, 0);
if (nValue)
{
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_DURABILITY);
nBits = (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits);
if (dwVersion <= 95)
{
nBits = 8;
}
nValue = BITMANIP_Read(pBuffer, nBits) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetUnitStat(pItem, STAT_DURABILITY, nValue, 0);
}
}
else if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_WEAPON))
{
STATLIST_SetUnitStat(pItem, STAT_ATTACKRATE, -pItemsTxtRecord->dwSpeed, 0);
if (pItemData->dwQualityNo == ITEMQUAL_INFERIOR)
{
if (pItemsTxtRecord->nMaxDam)
{
nValue = 3 * pItemsTxtRecord->nMaxDam / 4;
if (nValue < 2)
{
nValue = 2;
}
STATLIST_SetUnitStat(pItem, STAT_MAXDAMAGE, nValue, 0);
}
if (pItemsTxtRecord->nMinDam)
{
nValue = 3 * pItemsTxtRecord->nMinDam / 4;
if (nValue < 1)
{
nValue = 1;
}
STATLIST_SetUnitStat(pItem, STAT_MINDAMAGE, nValue, 0);
}
if (pItemsTxtRecord->n2HandMaxDam)
{
nValue = 3 * pItemsTxtRecord->n2HandMaxDam / 4;
if (nValue < 2)
{
nValue = 2;
}
STATLIST_SetUnitStat(pItem, STAT_SECONDARY_MAXDAMAGE, nValue, 0);
}
if (pItemsTxtRecord->n2HandMinDam)
{
nValue = 3 * pItemsTxtRecord->n2HandMinDam / 4;
if (nValue < 1)
{
nValue = 1;
}
STATLIST_SetUnitStat(pItem, STAT_SECONDARY_MINDAMAGE, nValue, 0);
}
if (pItemsTxtRecord->nMaxMisDam)
{
nValue = 3 * pItemsTxtRecord->nMinMisDam / 4;
if (nValue < 1)
{
nValue = 1;
}
STATLIST_SetUnitStat(pItem, STAT_ITEM_THROW_MINDAMAGE, nValue, 0);
nValue = 3 * pItemsTxtRecord->nMaxMisDam / 4;
if (nValue < 2)
{
nValue = 2;
}
STATLIST_SetUnitStat(pItem, STAT_ITEM_THROW_MAXDAMAGE, nValue, 0);
}
}
else
{
STATLIST_SetUnitStat(pItem, STAT_MAXDAMAGE, pItemsTxtRecord->nMaxDam, 0);
STATLIST_SetUnitStat(pItem, STAT_MINDAMAGE, pItemsTxtRecord->nMinDam, 0);
STATLIST_SetUnitStat(pItem, STAT_SECONDARY_MAXDAMAGE, pItemsTxtRecord->n2HandMaxDam, 0);
STATLIST_SetUnitStat(pItem, STAT_SECONDARY_MINDAMAGE, pItemsTxtRecord->n2HandMinDam, 0);
if (pItemsTxtRecord->nMaxMisDam)
{
STATLIST_SetUnitStat(pItem, STAT_ITEM_THROW_MINDAMAGE, pItemsTxtRecord->nMinMisDam, 0);
STATLIST_SetUnitStat(pItem, STAT_ITEM_THROW_MAXDAMAGE, pItemsTxtRecord->nMaxMisDam, 0);
}
}
if (pItemData->dwItemFlags & IFLAG_ETHEREAL)
{
STATLIST_SetUnitStat(pItem, STAT_MINDAMAGE, 3 * STATLIST_GetUnitBaseStat(pItem, STAT_MINDAMAGE, 0) / 2, 0);
STATLIST_SetUnitStat(pItem, STAT_MAXDAMAGE, 3 * STATLIST_GetUnitBaseStat(pItem, STAT_MAXDAMAGE, 0) / 2, 0);
STATLIST_SetUnitStat(pItem, STAT_SECONDARY_MINDAMAGE, 3 * STATLIST_GetUnitBaseStat(pItem, STAT_SECONDARY_MINDAMAGE, 0) / 2, 0);
STATLIST_SetUnitStat(pItem, STAT_SECONDARY_MAXDAMAGE, 3 * STATLIST_GetUnitBaseStat(pItem, STAT_SECONDARY_MAXDAMAGE, 0) / 2, 0);
STATLIST_SetUnitStat(pItem, STAT_ITEM_THROW_MINDAMAGE, 3 * STATLIST_GetUnitBaseStat(pItem, STAT_ITEM_THROW_MINDAMAGE, 0) / 2, 0);
STATLIST_SetUnitStat(pItem, STAT_ITEM_THROW_MAXDAMAGE, 3 * STATLIST_GetUnitBaseStat(pItem, STAT_ITEM_THROW_MAXDAMAGE, 0) / 2, 0);
}
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_MAXDURABILITY);
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits)) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetUnitStat(pItem, STAT_MAXDURABILITY, nValue, 0);
if (nValue)
{
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_DURABILITY);
nBits = (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits);
if (dwVersion <= 95)
{
nBits = 8;
}
nValue = BITMANIP_Read(pBuffer, nBits) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetUnitStat(pItem, STAT_DURABILITY, nValue, 0);
}
}
else if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_GOLD))
{
if (BITMANIP_Read(pBuffer, 1))
{
nBits = 32;
}
else
{
nBits = 12;
}
STATLIST_SetUnitStat(pItem, STAT_GOLD, BITMANIP_Read(pBuffer, nBits), 0);
}
if (pItemsTxtRecord->nStackable)
{
if (dwVersion > 80)
{
nBits = 9;
}
else
{
nBits = 8;
}
STATLIST_SetUnitStat(pItem, STAT_QUANTITY, BITMANIP_Read(pBuffer, nBits), 0);
}
if (pItemData->dwItemFlags & IFLAG_SOCKETED)
{
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_ITEM_NUMSOCKETS);
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits));
nMaxSockets = pItemsTxtRecord->nInvWidth * pItemsTxtRecord->nInvHeight;
if (nMaxSockets > 0)
{
if (nMaxSockets > 6)
{
nMaxSockets = 6;
}
if (nMaxSockets > ITEMS_GetMaxSockets(pItem))
{
nMaxSockets = ITEMS_GetMaxSockets(pItem);
}
if (nValue < 1)
{
nValue = 1;
}
if (nValue > nMaxSockets)
{
nValue = nMaxSockets;
}
ITEMS_SetItemFlag(pItem, IFLAG_SOCKETED, TRUE);
STATLIST_SetUnitStat(pItem, STAT_ITEM_NUMSOCKETS, nValue, 0);
}
}
if (!bCheckForHeader && !(pItemData->dwItemFlags & IFLAG_IDENTIFIED))
{
return 2 * (bError == 0) - 1;
}
if (dwVersion > 84 && pItemData->dwQualityNo == ITEMQUAL_SET)
{
nStatLists = 5;
nSetItemMask = BITMANIP_Read(pBuffer, 5);
}
else
{
nStatLists = 0;
nSetItemMask = 0;
}
if (bRuneword)
{
++nStatLists;
}
for (int nStatListCounter = -1; nStatListCounter < nStatLists; ++nStatListCounter)
{
if (nStatListCounter < 0)
{
nState = 0;
nFlag = 0x40;
}
else if (bRuneword && nStatListCounter == nStatLists - 1)
{
nState = STATE_RUNEWORD;
nFlag = 0x40;
}
else if (nSetItemMask & (1 << nStatListCounter))
{
nState = gnItemSetStates[nStatListCounter];
nFlag = 0x2040;
}
else
{
continue;
}
pStatList = STATLIST_GetStatListFromUnitStateOrFlag(pItem, nState, nFlag);
if (!pStatList)
{
pStatList = STATLIST_AllocStatList(pItem->pMemoryPool, nFlag, 0, UNIT_ITEM, pItem->dwUnitId);
D2COMMON_10475_PostStatToStatList(pItem, pStatList, 1);
STATLIST_SetState(pStatList, nState);
}
nLastStatId = -1;
while (1)
{
nStatId = BITMANIP_Read(pBuffer, 9);
if (nStatId == 511)
{
break;
}
if (!nStatId && !nLastStatId)
{
bError = TRUE;
break;
}
nLastStatId = nStatId;
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(nStatId);
if (!pItemStatCostTxtRecord)
{
break;
}
switch (nStatId)
{
case STAT_STRENGTH:
case STAT_DEXTERITY:
{
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits)) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, nStatId, nValue, 0);
break;
}
case STAT_VITALITY:
{
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits)) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_VITALITY, nValue, 0);
if (dwVersion <= 85)
{
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_MAXHP);
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits)) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_MAXHP, nValue << 8, 0);
}
break;
}
case STAT_ENERGY:
{
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits)) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_ENERGY, nValue, 0);
if (dwVersion <= 85)
{
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_MAXMANA);
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits)) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_MAXMANA, nValue, 0); //TODO: nValue << 8?
}
break;
}
case STAT_ITEM_MAXDAMAGE_PERCENT:
{
ITEMS_SetDefenseOrDamage(pItem, STAT_ITEM_MAXDAMAGE_PERCENT);
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits)) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_ITEM_MAXDAMAGE_PERCENT, nValue, 0);
ITEMS_SetDefenseOrDamage(pItem, STAT_ITEM_MINDAMAGE_PERCENT);
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_ITEM_MINDAMAGE_PERCENT);
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits)) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_ITEM_MINDAMAGE_PERCENT, nValue, 0);
break;
}
case STAT_FIREMINDAM:
{
nBits = (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits);
if (dwVersion <= 81)
{
nBits = 6;
}
nValue = BITMANIP_Read(pBuffer, nBits) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_FIREMINDAM, nValue, 0);
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_FIREMAXDAM);
nBits = (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits);
if (dwVersion <= 81)
{
nBits = 7;
}
nValue = BITMANIP_Read(pBuffer, nBits) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_FIREMAXDAM, nValue, 0);
break;
}
case STAT_LIGHTMINDAM:
{
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits)) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_LIGHTMINDAM, nValue, 0);
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_LIGHTMAXDAM);
nBits = (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits);
if (dwVersion <= 81)
{
nBits = 7;
}
nValue = BITMANIP_Read(pBuffer, nBits) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_LIGHTMAXDAM, nValue, 0);
break;
}
case STAT_MAGICMINDAM:
{
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits)) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_MAGICMINDAM, nValue, 0);
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_MAGICMAXDAM);
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits)) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_MAGICMAXDAM, nValue, 0);
break;
}
case STAT_COLDMINDAM:
{
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits)) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_COLDMINDAM, nValue, 0);
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_COLDMAXDAM);
nBits = (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits);
if (dwVersion <= 81)
{
nBits = 7;
}
nValue = BITMANIP_Read(pBuffer, nBits) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_COLDMAXDAM, nValue, 0);
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_COLDLENGTH);
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits)) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_COLDLENGTH, nValue, 0);
break;
}
case STAT_POISONMINDAM:
{
nBits = (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits);
if (dwVersion <= 81)
{
nBits = 7;
}
nValue = BITMANIP_Read(pBuffer, nBits) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_POISONMINDAM, nValue, 0);
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_POISONMAXDAM);
nBits = (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits);
if (dwVersion <= 81)
{
nBits = 8;
}
nValue = BITMANIP_Read(pBuffer, nBits) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_POISONMAXDAM, nValue, 0);
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_POISONLENGTH);
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits)) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_POISONLENGTH, nValue, 0);
STATLIST_SetStatIfListIsValid(pStatList, STAT_POISON_COUNT, 1, 0);
break;
}
case STAT_ITEM_FREEZE:
{
if (dwVersion > 89)
{
ITEMS_ReadStatFromItemBitstream(pBuffer, pStatList, pItemStatCostTxtRecord, STAT_ITEM_FREEZE, dwVersion, b109);
}
else
{
BITMANIP_Read(pBuffer, 16);
STATLIST_SetStatIfListIsValid(pStatList, STAT_ITEM_FREEZE, 1, 0);
}
break;
}
case STAT_ITEM_ADDCLASSSKILLS:
{
if (dwVersion > 92)
{
ITEMS_ReadStatFromItemBitstream(pBuffer, pStatList, pItemStatCostTxtRecord, STAT_ITEM_ADDCLASSSKILLS, dwVersion, b109);
}
else
{
STATLIST_SetStat(pStatList, STAT_ITEM_ADDCLASSSKILLS, BITMANIP_Read(pBuffer, 3), 0);
}
break;
}
case STAT_UNSENTPARAM1:
{
if (dwVersion > 92)
{
ITEMS_ReadStatFromItemBitstream(pBuffer, pStatList, pItemStatCostTxtRecord, STAT_UNSENTPARAM1, dwVersion, b109);
}
else
{
STATLIST_SetStat(pStatList, STAT_ITEM_ADDCLASSSKILLS, BITMANIP_Read(pBuffer, 3), 3);
}
break;
}
case STAT_ITEM_ADDEXPERIENCE:
{
if (dwVersion > 92)
{
ITEMS_ReadStatFromItemBitstream(pBuffer, pStatList, pItemStatCostTxtRecord, STAT_ITEM_ADDEXPERIENCE, dwVersion, b109);
}
else
{
STATLIST_SetStat(pStatList, STAT_ITEM_ADDCLASSSKILLS, BITMANIP_Read(pBuffer, 3), 2);
}
break;
}
case STAT_ITEM_HEALAFTERKILL:
{
if (dwVersion > 92)
{
ITEMS_ReadStatFromItemBitstream(pBuffer, pStatList, pItemStatCostTxtRecord, STAT_ITEM_HEALAFTERKILL, dwVersion, b109);
}
else
{
STATLIST_SetStat(pStatList, STAT_ITEM_ADDCLASSSKILLS, BITMANIP_Read(pBuffer, 3), 1);
}
break;
}
case STAT_ITEM_REDUCEDPRICES:
{
if (dwVersion > 92)
{
ITEMS_ReadStatFromItemBitstream(pBuffer, pStatList, pItemStatCostTxtRecord, STAT_ITEM_REDUCEDPRICES, dwVersion, b109);
}
else
{
STATLIST_SetStat(pStatList, STAT_ITEM_ADDCLASSSKILLS, BITMANIP_Read(pBuffer, 3), 4);
}
break;
}
case STAT_ATTACK_VS_MONTYPE:
{
if (dwVersion > 92)
{
ITEMS_ReadStatFromItemBitstream(pBuffer, pStatList, pItemStatCostTxtRecord, STAT_ATTACK_VS_MONTYPE, dwVersion, b109);
}
else
{
STATLIST_SetStat(pStatList, STAT_ITEM_ADDCLASSSKILLS, BITMANIP_Read(pBuffer, 3), 5);
}
break;
}
case STAT_DAMAGE_VS_MONTYPE:
{
if (dwVersion > 92)
{
ITEMS_ReadStatFromItemBitstream(pBuffer, pStatList, pItemStatCostTxtRecord, STAT_DAMAGE_VS_MONTYPE, dwVersion, b109);
}
else
{
STATLIST_SetStat(pStatList, STAT_ITEM_ADDCLASSSKILLS, BITMANIP_Read(pBuffer, 3), 6);
}
break;
}
case STAT_ITEM_ADDSKILL_TAB:
case STAT_UNUSED189:
case STAT_UNUSED190:
case STAT_UNUSED191:
case STAT_UNUSED192:
case STAT_UNUSED193:
{
if (dwVersion > 92)
{
ITEMS_ReadStatFromItemBitstream(pBuffer, pStatList, pItemStatCostTxtRecord, nStatId, dwVersion, b109);
}
else
{
D2Common_10848(BITMANIP_Read(pBuffer, 10), &v238, &v237, &nValue);
if (nValue > 7)
{
nValue = 7;
}
STATLIST_SetStat(pStatList, STAT_ITEM_ADDSKILL_TAB, nValue, v237 + 8 * v238);
}
break;
}
case STAT_ITEM_ELEMSKILL:
{
if (dwVersion > 92)
{
ITEMS_ReadStatFromItemBitstream(pBuffer, pStatList, pItemStatCostTxtRecord, STAT_ITEM_ELEMSKILL, dwVersion, b109);
}
else
{
STATLIST_SetStat(pStatList, STAT_ITEM_ELEMSKILL, BITMANIP_Read(pBuffer, 4), 1);
}
break;
}
case STAT_ITEM_SINGLESKILL:
case STAT_ITEM_RESTINPEACE:
case STAT_CURSE_RESISTANCE:
case STAT_FADE:
case STAT_ARMOR_OVERRIDE_PERCENT:
case STAT_UNUSED183:
case STAT_UNUSED184:
case STAT_UNUSED185:
case STAT_UNUSED186:
case STAT_UNUSED187:
{
if (dwVersion > 92)
{
ITEMS_ReadStatFromItemBitstream(pBuffer, pStatList, pItemStatCostTxtRecord, nStatId, dwVersion, b109);
}
else
{
D2Common_10844_ITEMMODS_First(BITMANIP_Read(pBuffer, 14), &nSkillId, &nValue);
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_ITEM_SINGLESKILL);
if (pItemStatCostTxtRecord)
{
nMax = (1 << pItemStatCostTxtRecord->nSaveBits) - 1;
}
else
{
nMax = 7;
}
if (nValue > 0 && nValue <= nMax)
{
pSkillsTxtRecord = DATATBLS_GetSkillsTxtRecord(nSkillId);
if (pSkillsTxtRecord && DATATBLS_GetSkillDescTxtRecord(pSkillsTxtRecord->wSkillDesc))
{
STATLIST_SetStat(pStatList, STAT_ITEM_SINGLESKILL, nValue, nSkillId);
}
}
}
break;
}
case STAT_ITEM_SKILLONATTACK:
case STAT_ITEM_SKILLONKILL:
case STAT_ITEM_SKILLONDEATH:
{
if (dwVersion > 92)
{
ITEMS_ReadStatFromItemBitstream(pBuffer, pStatList, pItemStatCostTxtRecord, nStatId, dwVersion, b109);
}
else
{
D2Common_10845(BITMANIP_Read(pBuffer, 21), &v241, &v240, &v242);
STATLIST_SetStat(pStatList, STAT_ITEM_SKILLONATTACK, v242, ((uint16_t)v241 << 6) + (v240 & 0x3F));
}
break;
}
case STAT_ITEM_SKILLONHIT:
case STAT_ITEM_SKILLONLEVELUP:
case STAT_UNUSED200:
{
if (dwVersion > 92)
{
ITEMS_ReadStatFromItemBitstream(pBuffer, pStatList, pItemStatCostTxtRecord, nStatId, dwVersion, b109);
}
else
{
D2Common_10845(BITMANIP_Read(pBuffer, 21), &v244, &v243, &v245);
STATLIST_SetStat(pStatList, STAT_ITEM_SKILLONHIT, v245, ((uint16_t)v244 << 6) + (v243 & 0x3F));
}
break;
}
case STAT_ITEM_SKILLONGETHIT:
case STAT_UNUSED202:
case STAT_UNUSED203:
{
if (dwVersion > 92)
{
ITEMS_ReadStatFromItemBitstream(pBuffer, pStatList, pItemStatCostTxtRecord, nStatId, dwVersion, b109);
}
else
{
D2Common_10845(BITMANIP_Read(pBuffer, 21), &v247, &v246, &v248);
STATLIST_SetStat(pStatList, STAT_ITEM_SKILLONGETHIT, v248, ((uint16_t)v247 << 6) + (v246 & 0x3F));
}
break;
}
case STAT_ITEM_CHARGED_SKILL:
case STAT_UNUSED204:
case STAT_UNUSED205:
case STAT_UNUSED206:
case STAT_UNUSED207:
case STAT_UNUSED208:
case STAT_UNUSED209:
case STAT_UNUSED210:
case STAT_UNUSED211:
case STAT_UNUSED212:
{
if (dwVersion > 92)
{
ITEMS_ReadStatFromItemBitstream(pBuffer, pStatList, pItemStatCostTxtRecord, nStatId, dwVersion, b109);
}
else
{
if (dwVersion > 73)
{
nBits = 30;
}
else
{
nBits = 29;
}
D2Common_10846(BITMANIP_Read(pBuffer, nBits), &v249, &v250, &v251, &v252);
STATLIST_SetStat(pStatList, STAT_ITEM_CHARGED_SKILL, (v252 << 8) + (uint8_t)v251, (v250 & LOWORD(sgptDataTables->nShiftedStuff)) + ((uint16_t)v249 << sgptDataTables->nStuff));
}
break;
}
default:
{
ITEMS_ReadStatFromItemBitstream(pBuffer, pStatList, pItemStatCostTxtRecord, nStatId, dwVersion, b109);
break;
}
}
}
if (dwVersion <= 92)
{
nValue = STATLIST_GetStatValue(pStatList, STAT_ITEM_ADDCLASSSKILLS, 0);
if (nValue > 0)
{
if (nValue == STATLIST_GetStatValue(pStatList, STAT_ITEM_ADDCLASSSKILLS, 1) && nValue == STATLIST_GetStatValue(pStatList, STAT_ITEM_ADDCLASSSKILLS, 2)
&& nValue == STATLIST_GetStatValue(pStatList, STAT_ITEM_ADDCLASSSKILLS, 3) && nValue == STATLIST_GetStatValue(pStatList, STAT_ITEM_ADDCLASSSKILLS, 4))
{
for (int i = 0; i < 7; ++i)
{
STATLIST_SetStatIfListIsValid(pStatList, STAT_ITEM_ADDCLASSSKILLS, 0, i);
}
STATLIST_SetStatIfListIsValid(pStatList, STAT_ITEM_ALLSKILLS, nValue, 0);
}
}
}
}
return 2 * (bError == FALSE) - 1;
}
//D2Common.0x6FDA2690
void __fastcall ITEMS_SetDefenseOrDamage(D2UnitStrc* pItem, int nStat)
{
int nMaxAc = 0;
int nItemId = 0;
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
pItemsTxtRecord = DATATBLS_GetItemRecordFromItemCode(pItemsTxtRecord->dwCode, &nItemId);
if (pItemsTxtRecord)
{
switch (nStat)
{
case STAT_ITEM_ARMOR_PERCENT:
case STAT_ARMORCLASS:
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_ANY_ARMOR) && pItemsTxtRecord->dwMaxAc)
{
nMaxAc = STATLIST_GetUnitBaseStat(pItem, STAT_ARMORCLASS, 0) + 1;
if (nMaxAc <= pItemsTxtRecord->dwMaxAc)
{
nMaxAc = pItemsTxtRecord->dwMaxAc + 1;
}
STATLIST_SetUnitStat(pItem, STAT_ARMORCLASS, nMaxAc, 0);
}
break;
case STAT_ITEM_MAXDAMAGE_PERCENT:
case STAT_MAXDAMAGE:
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_WEAPON))
{
if (pItemsTxtRecord->nMaxDam && STATLIST_GetUnitBaseStat(pItem, STAT_MAXDAMAGE, 0) < pItemsTxtRecord->nMaxDam)
{
STATLIST_SetUnitStat(pItem, STAT_MAXDAMAGE, pItemsTxtRecord->nMaxDam, 0);
}
if (pItemsTxtRecord->n2HandMaxDam && STATLIST_GetUnitBaseStat(pItem, STAT_SECONDARY_MAXDAMAGE, 0) < pItemsTxtRecord->n2HandMaxDam)
{
STATLIST_SetUnitStat(pItem, STAT_SECONDARY_MAXDAMAGE, pItemsTxtRecord->n2HandMaxDam, 0);
}
if (ITEMS_CheckIfThrowable(pItem) && pItemsTxtRecord->nMaxMisDam && STATLIST_GetUnitBaseStat(pItem, STAT_ITEM_THROW_MAXDAMAGE, 0) < pItemsTxtRecord->nMaxMisDam)
{
STATLIST_SetUnitStat(pItem, STAT_ITEM_THROW_MAXDAMAGE, pItemsTxtRecord->nMaxMisDam, 0);
}
}
break;
case STAT_ITEM_MINDAMAGE_PERCENT:
case STAT_MINDAMAGE:
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_WEAPON))
{
if (pItemsTxtRecord->nMinDam && STATLIST_GetUnitBaseStat(pItem, STAT_MINDAMAGE, 0) < pItemsTxtRecord->nMinDam)
{
STATLIST_SetUnitStat(pItem, STAT_MINDAMAGE, pItemsTxtRecord->nMinDam, 0);
}
if (pItemsTxtRecord->n2HandMinDam && STATLIST_GetUnitBaseStat(pItem, STAT_SECONDARY_MINDAMAGE, 0) < pItemsTxtRecord->n2HandMinDam)
{
STATLIST_SetUnitStat(pItem, STAT_SECONDARY_MINDAMAGE, pItemsTxtRecord->n2HandMinDam, 0);
}
if (ITEMS_CheckIfThrowable(pItem) && pItemsTxtRecord->nMinMisDam && STATLIST_GetUnitBaseStat(pItem, STAT_ITEM_THROW_MINDAMAGE, 0) < pItemsTxtRecord->nMinMisDam)
{
STATLIST_SetUnitStat(pItem, STAT_ITEM_THROW_MINDAMAGE, pItemsTxtRecord->nMinMisDam, 0);
}
}
break;
default:
return;
}
}
}
//D2Common.0x6FDA29D0
void __fastcall ITEMS_ReadStatFromItemBitstream(D2BitBufferStrc* pBuffer, D2StatListStrc* pStatList, D2ItemStatCostTxt* pItemStatCostTxtRecord, int nStatId, uint32_t dwVersion, int n109)
{
int nSaveAdd = n109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd;
int nParamBits = n109 ? pItemStatCostTxtRecord->dw09SaveParamBits : pItemStatCostTxtRecord->dwSaveParamBits;
int nSaveBits = n109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits;
int nParam = 0;
int nValue = 0;
switch (nStatId)
{
case STAT_SECONDARY_MINDAMAGE:
if (dwVersion <= 89)
{
nSaveBits = 5;
}
break;
case STAT_SECONDARY_MAXDAMAGE:
if (dwVersion <= 89)
{
nSaveBits = 6;
}
break;
case STAT_HPREGEN:
if (dwVersion <= 89)
{
nSaveBits = 5;
nSaveAdd = 10;
}
break;
case STAT_ITEM_GOLDBONUS:
if (dwVersion <= 89)
{
nSaveBits = 8;
nSaveAdd = 20;
}
break;
case STAT_ITEM_MAGICBONUS:
if (dwVersion <= 0x59)
{
nSaveBits = 7;
nSaveAdd = 20;
}
break;
case STAT_ITEM_FASTERATTACKRATE:
case STAT_ITEM_FASTERMOVEVELOCITY:
case STAT_ITEM_FASTERGETHITRATE:
case STAT_ITEM_FASTERBLOCKRATE:
case STAT_ITEM_FASTERCASTRATE:
if (dwVersion <= 87)
{
nSaveBits = 6;
}
break;
case STAT_ITEM_LEVELREQ:
case STAT_ITEM_LEVELREQPCT:
if (dwVersion < 93)
{
nStatId = 93;
}
break;
case STAT_LASTBLOCKFRAME:
case STAT_ITEM_NONCLASSSKILL:
if (dwVersion < 93)
{
nStatId = 96;
}
break;
case STAT_STATE:
case STAT_MONSTER_PLAYERCOUNT:
if (dwVersion < 93)
{
nStatId = 99;
}
break;
case STAT_SKILL_POISON_OVERRIDE_LENGTH:
case STAT_SKILL_BYPASS_UNDEAD:
if (dwVersion < 93)
{
nStatId = 102;
}
break;
case STAT_SKILL_BYPASS_DEMONS:
case STAT_SKILL_BYPASS_BEASTS:
if (dwVersion < 93)
{
nStatId = 105;
}
break;
default:
break;
}
if (nParamBits > 0)
{
nParam = BITMANIP_Read(pBuffer, nParamBits);
}
nValue = BITMANIP_Read(pBuffer, nSaveBits);
if (pStatList)
{
STATLIST_SetStat(pStatList, nStatId, (nValue - nSaveAdd) << pItemStatCostTxtRecord->nValShift, nParam);
}
}
//D2Common.0x6FDA2BA0 (#10881)
size_t __stdcall ITEMS_SerializeItemToBitstream(D2UnitStrc* pItem, uint8_t* pBitstream, size_t nSize, BOOL bServer, BOOL bSaveItemInv, BOOL bGamble)
{
D2BitBufferStrc pBuffer = {};
BITMANIP_Initialize(&pBuffer, pBitstream, nSize);
ITEMS_SerializeItem(pItem, &pBuffer, bServer, bSaveItemInv, bGamble);
if (pBuffer.bFull)
{
return 0;
}
else
{
return BITMANIP_GetSize(&pBuffer);
}
}
//Inlined in D2Common.0x6FDA2C00
void __fastcall ITEMS_SerializeItemCompact(D2UnitStrc* pItem, D2BitBufferStrc* pBuffer, D2ItemsTxt* pItemsTxtRecord, BOOL bServer)
{
D2ItemStatCostTxt* pItemStatCostTxtRecord = NULL;
char* szName = NULL;
int nItemFormat = 0;
int nValue = 0;
int nGold = 0;
int nX = 0;
int nY = 0;
uint8_t nBodyLoc = 0;
int v39; // [sp+24h] [bp-8h]@63
int v40; // [sp+28h] [bp-4h]@63
nItemFormat = ITEMS_GetItemFormat(pItem);
if (nItemFormat > 0)
{
if (nItemFormat >= 1023)
{
nItemFormat = 1023;
}
}
else
{
nItemFormat = 0;
}
BITMANIP_Write(pBuffer, nItemFormat, 10);
ITEMS_WriteBitsToBitstream(pBuffer, pItem->dwAnimMode, 3);
if (pItem->dwAnimMode == IMODE_ONGROUND || pItem->dwAnimMode == IMODE_DROPPING)
{
ITEMS_WriteBitsToBitstream(pBuffer, UNITS_GetXPosition(pItem), 16);
ITEMS_WriteBitsToBitstream(pBuffer, UNITS_GetYPosition(pItem), 16);
}
else
{
ITEMS_WriteBitsToBitstream(pBuffer, ITEMS_GetBodyLocation(pItem), 4);
nX = UNITS_GetXPosition(pItem);
if (nX > 0)
{
if (nX >= 15)
{
nX = 15;
}
}
else
{
nX = 0;
}
ITEMS_WriteBitsToBitstream(pBuffer, nX, 4);
nY = UNITS_GetYPosition(pItem);
if (nY > 0)
{
if (nY >= 15)
{
nY = 15;
}
}
else
{
nY = 0;
}
ITEMS_WriteBitsToBitstream(pBuffer, nY, 4);
ITEMS_WriteBitsToBitstream(pBuffer, (ITEMS_GetInvPage(pItem) + 1), 3);
}
if (ITEMS_GetItemFlags(pItem) & IFLAG_ISEAR)
{
ITEMS_WriteBitsToBitstream(pBuffer, ITEMS_GetFileIndex(pItem), 3);
ITEMS_WriteBitsToBitstream(pBuffer, ITEMS_GetEarLevel(pItem), 7);
szName = ITEMS_GetEarName(pItem);
do
{
ITEMS_WriteBitsToBitstream(pBuffer, *szName, 7);
}
while (*szName++);
}
else
{
ITEMS_WriteBitsToBitstream(pBuffer, ITEMS_GetBaseCode(pItem), 32);
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_GOLD))
{
nGold = STATLIST_GetUnitStatUnsigned(pItem, STAT_GOLD, 0);
ITEMS_WriteBitsToBitstream(pBuffer, (nGold >= 4096), 1);
ITEMS_WriteBitsToBitstream(pBuffer, nGold, (((nGold < 4096) - 1) & 20) + 12);
}
}
if (pItemsTxtRecord->nQuest && pItemsTxtRecord->nQuestDiffCheck)
{
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_QUESTITEMDIFFICULTY);
D2_ASSERT(pItemStatCostTxtRecord);
nValue = STATLIST_GetUnitStatUnsigned(pItem, STAT_QUESTITEMDIFFICULTY, 0);
ITEMS_WriteBitsToBitstream(pBuffer, pItemStatCostTxtRecord->dwSaveAdd + (nValue >> pItemStatCostTxtRecord->nValShift), pItemStatCostTxtRecord->nSaveBits);
}
if (bServer)
{
v40 = 0;
v39 = 0;
ITEMS_GetRealmData(pItem, &v40, &v39);
if (v39)
{
ITEMS_WriteBitsToBitstream(pBuffer, 1, 1);
ITEMS_WriteBitsToBitstream(pBuffer, v40, 32);
ITEMS_WriteBitsToBitstream(pBuffer, v39, 32);
ITEMS_WriteBitsToBitstream(pBuffer, 0, 32);
}
else
{
ITEMS_WriteBitsToBitstream(pBuffer, 0, 1);
}
}
}
//D2Common.0x6FDA2C00
size_t __fastcall ITEMS_SerializeItem(D2UnitStrc* pItem, D2BitBufferStrc* pBuffer, BOOL bServer, BOOL bSaveItemInv, BOOL bGamble)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
D2ItemDataStrc* pItemData = NULL;
uint32_t nItemFlags = 0;
if (!pItem || pItem->dwUnitType != UNIT_ITEM)
{
return 0;
}
pItemData = pItem->pItemData;
if (pItemData)
{
nItemFlags = pItemData->dwItemFlags;
}
else
{
nItemFlags = 0;
}
nItemFlags = nItemFlags & ~IFLAG_INIT | IFLAG_JUSTSAVED;
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (!pItemsTxtRecord)
{
return 0;
}
if (pItemsTxtRecord->nCompactSave)
{
nItemFlags |= IFLAG_COMPACTSAVE;
}
if (bGamble)
{
nItemFlags = nItemFlags & ~IFLAG_ETHEREAL | IFLAG_LOWQUALITY;
}
if (bServer)
{
BITMANIP_Write(pBuffer, 'MJ', 16);
}
else
{
if (!(nItemFlags & IFLAG_IDENTIFIED))
{
nItemFlags &= ~IFLAG_SOCKETED;
}
}
BITMANIP_Write(pBuffer, nItemFlags, 32);
if (nItemFlags & IFLAG_COMPACTSAVE)
{
ITEMS_SerializeItemCompact(pItem, pBuffer, pItemsTxtRecord, bServer);
}
else
{
ITEMS_SerializeItemComplete(pItem, pBuffer, bServer, bGamble);
}
if (!bGamble && bSaveItemInv && pItem->pInventory)
{
for (D2UnitStrc* i = INVENTORY_GetFirstItem(pItem->pInventory); i; i = INVENTORY_GetNextItem(i))
{
BITMANIP_GoToNextByte(pBuffer);
ITEMS_SerializeItem(INVENTORY_UnitIsItem(i), pBuffer, bServer, bSaveItemInv, 0);
}
}
return BITMANIP_GetSize(pBuffer);
}
//D2Common.0x6FDA2FD0
void __fastcall ITEMS_WriteBitsToBitstream(D2BitBufferStrc* pBuffer, int nData, int nBits)
{
if (nBits != 32)
{
nData &= (nData <= 0) - 1;
if (nData >= (1 << nBits) - 1)
{
nData = (1 << nBits) - 1;
}
}
return BITMANIP_Write(pBuffer, nData, nBits);
}
//D2Common.0x6FDA3010
void __fastcall ITEMS_SerializeItemComplete(D2UnitStrc* pItem, D2BitBufferStrc* pBuffer, BOOL bServer, BOOL bGamble)
{
static const int gnItemSetStates_6FDD15A8[] =
{
STATE_ITEMSET1, STATE_ITEMSET2, STATE_ITEMSET3, STATE_ITEMSET4, STATE_ITEMSET5
};
D2ItemStatCostTxt* pItemStatCostTxtRecord = NULL;
D2ItemStatCostTxt* pLocalRecord = NULL;
D2MagicAffixDataTbl* pMagicAffixInfo = NULL;
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
D2StatListStrc* pStatListEx = NULL;
D2UnitStrc* pInventoryItem = NULL;
D2ItemDataStrc* pItemData = NULL;
char* szPlayerName = NULL;
int nMagicPrefixOffset = 0;
int nAutoMagicOffset = 0;
int nCurrentCharacter = 0;
int nStatListCounter = 0;
int nSocketedItems = 0;
int nMaxDurability = 0;
int nItemFormat = 0;
int nItemLevel = 0;
int nItemType = 0;
int nQuality = 0;
int nInvGfx = 0;
int nVarInvGfx = 0;
int nAnimMode = 0;
int nBodyLoc = 0;
int nStatCounter = 0;
int nSetItemMask = 0;
int nMagicPrefix = 0;
int nMagicSuffix = 0;
int nRarePrefix = 0;
int nRareSuffix = 0;
int nRunewordId = 0;
int nScrollType = 0;
int nAutoAffix = 0;
int nStatLists = 0;
int nFileIndex = 0;
int nEarLevel = 0;
int nCounter = 0;
int nStatId = 0;
int nStats = 0;
int nValue = 0;
int nGold = 0;
uint8_t nStorePage = 0;
BOOL bIsRuneword = FALSE;
BOOL bContinue = FALSE;
BOOL bInvalid = FALSE;
D2CoordStrc pCoords = {};
int nStatValues[511] = {};
D2StatStrc pStat[511] = {};
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
pItemData = pItem->pItemData;
D2_ASSERT(pItemData);
nItemFormat = pItemData->wItemFormat;
if (nItemFormat > 0)
{
if (nItemFormat >= 1023)
{
nItemFormat = 1023;
}
}
else
{
nItemFormat = 0;
}
BITMANIP_Write(pBuffer, nItemFormat, 10);
nAnimMode = pItem->dwAnimMode;
if (nAnimMode > 0)
{
if (nAnimMode >= 7)
{
nAnimMode = 7;
}
}
else
{
nAnimMode = 0;
}
BITMANIP_Write(pBuffer, nAnimMode, 3);
if (nAnimMode == IMODE_ONGROUND || nAnimMode == IMODE_DROPPING)
{
UNITS_GetCoords(pItem, &pCoords);
if (pCoords.nX > 0)
{
if (pCoords.nX >= 65535)
{
pCoords.nX = 65535;
}
}
else
{
pCoords.nX = 0;
}
BITMANIP_Write(pBuffer, pCoords.nX, 16);
if (pCoords.nY > 0)
{
if (pCoords.nY >= 65535)
{
pCoords.nY = 65535;
}
}
else
{
pCoords.nY = 0;
}
BITMANIP_Write(pBuffer, pCoords.nY, 16);
}
else
{
nBodyLoc = pItemData->nBodyLoc;
if (nBodyLoc > 0)
{
if (nBodyLoc >= 15)
{
nBodyLoc = 15;
}
}
else
{
nBodyLoc = 0;
}
BITMANIP_Write(pBuffer, nBodyLoc, 4);
UNITS_GetCoords(pItem, &pCoords);
if (pCoords.nX > 0)
{
if (pCoords.nX >= 15)
{
pCoords.nX = 15;
}
}
else
{
pCoords.nX = 0;
}
BITMANIP_Write(pBuffer, pCoords.nX, 4);
if (pCoords.nY > 0)
{
if (pCoords.nY >= 15)
{
pCoords.nY = 15;
}
}
else
{
pCoords.nY = 0;
}
BITMANIP_Write(pBuffer, pCoords.nY, 4);
nStorePage = pItemData->nInvPage + 1;
if (nStorePage > 0)
{
if (nStorePage >= 7)
{
nStorePage = 7;
}
}
else
{
nStorePage = 0;
}
BITMANIP_Write(pBuffer, nStorePage, 3);
}
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (bGamble)
{
if (pItemsTxtRecord->dwNormCode)
{
BITMANIP_Write(pBuffer, pItemsTxtRecord->dwNormCode, 32);
}
else
{
BITMANIP_Write(pBuffer, pItemsTxtRecord->dwCode, 32);
}
return;
}
BITMANIP_Write(pBuffer, pItemsTxtRecord->dwCode, 32);
nSocketedItems = 0;
if (ITEMS_CheckIfSocketable(pItem) && pItem->pInventory)
{
pInventoryItem = INVENTORY_GetFirstItem(pItem->pInventory);
if (pInventoryItem)
{
do
{
++nSocketedItems;
pInventoryItem = INVENTORY_GetNextItem(pInventoryItem);
}
while (pInventoryItem);
if (nSocketedItems > 0)
{
if (nSocketedItems >= 7)
{
nSocketedItems = 7;
}
}
else
{
nSocketedItems = 0;
}
}
}
BITMANIP_Write(pBuffer, nSocketedItems, 3);
if (bServer)
{
BITMANIP_Write(pBuffer, pItem->dwInitSeed, 32);
}
if ((int)pItemData->dwItemLevel < 1)
{
pItemData->dwItemLevel = 1;
}
nItemLevel = pItemData->dwItemLevel;
if (nItemLevel > 0)
{
if (nItemLevel >= 127)
{
nItemLevel = 127;
}
}
else
{
nItemLevel = 0;
}
BITMANIP_Write(pBuffer, nItemLevel, 7);
nQuality = pItemData->dwQualityNo;
if (nQuality > 0)
{
if (nQuality >= 15)
{
nQuality = 15;
}
}
else
{
nQuality = 0;
}
BITMANIP_Write(pBuffer, nQuality, 4);
nItemType = ITEMS_GetItemType(pItem);
pItemTypesTxtRecord = DATATBLS_GetItemTypesTxtRecord(nItemType);
if (pItemTypesTxtRecord)
{
nVarInvGfx = pItemTypesTxtRecord->nVarInvGfx;
}
else
{
nVarInvGfx = 0;
}
BITMANIP_Write(pBuffer, nVarInvGfx ? 1 : 0, 1);
if (pItemTypesTxtRecord && pItemTypesTxtRecord->nVarInvGfx)
{
nInvGfx = pItemData->nInvGfxIdx;
if (nInvGfx > 0)
{
if (nInvGfx >= 7)
{
nInvGfx = 7;
}
}
else
{
nInvGfx = 0;
}
BITMANIP_Write(pBuffer, nInvGfx, 3);
}
pMagicAffixInfo = DATATBLS_GetMagicAffixDataTables();
nMagicPrefixOffset = ((int)pMagicAffixInfo->pMagicPrefix - (int)pMagicAffixInfo->pMagicAffixTxt) / sizeof(D2MagicAffixTxt);
nAutoMagicOffset = ((int)pMagicAffixInfo->pAutoMagic - (int)pMagicAffixInfo->pMagicAffixTxt) / sizeof(D2MagicAffixTxt);
nAutoAffix = pItemData->wAutoAffix;
if (nAutoAffix > nAutoMagicOffset)
{
nAutoAffix -= nAutoMagicOffset;
}
BITMANIP_Write(pBuffer, nAutoAffix ? 1 : 0, 1);
if (nAutoAffix)
{
if (nAutoAffix > 0)
{
if (nAutoAffix >= 2047)
{
nAutoAffix = 2047;
}
}
else
{
nAutoAffix = 0;
}
BITMANIP_Write(pBuffer, nAutoAffix, 11);
}
switch (pItemData->dwQualityNo)
{
case ITEMQUAL_INFERIOR:
case ITEMQUAL_SUPERIOR:
{
nFileIndex = pItemData->dwFileIndex;
if (nFileIndex > 0)
{
if (nFileIndex >= 7)
{
nFileIndex = 7;
}
}
else
{
nFileIndex = 0;
}
BITMANIP_Write(pBuffer, nFileIndex, 3);
break;
}
case ITEMQUAL_RARE:
case ITEMQUAL_CRAFT:
{
if (bServer || pItemData->dwItemFlags & IFLAG_IDENTIFIED)
{
nRarePrefix = pItemData->wRarePrefix;
if (nRarePrefix > 0)
{
if (nRarePrefix >= 255)
{
nRarePrefix = 255;
}
}
else
{
nRarePrefix = 0;
}
BITMANIP_Write(pBuffer, nRarePrefix, 8);
nRareSuffix = pItemData->wRareSuffix;
if (nRareSuffix > 0)
{
if (nRareSuffix >= 255)
{
nRareSuffix = 255;
}
}
else
{
nRareSuffix = 0;
}
BITMANIP_Write(pBuffer, nRareSuffix, 8);
}
nCounter = 0;
do
{
nMagicPrefix = pItemData->wMagicPrefix[nCounter];
if (nMagicPrefix > nMagicPrefixOffset)
{
nMagicPrefix -= nMagicPrefixOffset;
}
if (nMagicPrefix)
{
BITMANIP_Write(pBuffer, 1, 1);
if (nMagicPrefix > 0)
{
if (nMagicPrefix >= 2047)
{
nMagicPrefix = 2047;
}
}
else
{
nMagicPrefix = 0;
}
BITMANIP_Write(pBuffer, nMagicPrefix, 11);
}
else
{
BITMANIP_Write(pBuffer, 0, 1);
}
if (pItemData->wMagicSuffix[nCounter] != 0)
{
BITMANIP_Write(pBuffer, 1, 1);
nMagicSuffix = pItemData->wMagicSuffix[nCounter];
if (nMagicSuffix > 0)
{
if (nMagicSuffix >= 2047)
{
nMagicSuffix = 2047;
}
}
else
{
nMagicSuffix = 0;
}
BITMANIP_Write(pBuffer, nMagicSuffix, 11);
}
else
{
BITMANIP_Write(pBuffer, 0, 1);
}
++nCounter;
}
while (nCounter < 3);
break;
}
case ITEMQUAL_TEMPERED:
{
if (bServer || pItemData->dwItemFlags & IFLAG_IDENTIFIED)
{
nRarePrefix = pItemData->wRarePrefix;
if (nRarePrefix > 0)
{
if (nRarePrefix >= 255)
{
nRarePrefix = 255;
}
}
else
{
nRarePrefix = 0;
}
BITMANIP_Write(pBuffer, nRarePrefix, 8);
nRareSuffix = pItemData->wRareSuffix;
if (nRareSuffix > 0)
{
if (nRareSuffix >= 255)
{
nRareSuffix = 255;
}
}
else
{
nRareSuffix = 0;
}
BITMANIP_Write(pBuffer, nRareSuffix, 8);
}
break;
}
case ITEMQUAL_MAGIC:
{
if (bServer || pItemData->dwItemFlags & IFLAG_IDENTIFIED)
{
nMagicPrefix = pItemData->wMagicPrefix[0];
if (nMagicPrefix > nMagicPrefixOffset)
{
nMagicPrefix -= nMagicPrefixOffset;
}
if (nMagicPrefix > 0)
{
if (nMagicPrefix >= 2047)
{
nMagicPrefix = 2047;
}
}
else
{
nMagicPrefix = 0;
}
BITMANIP_Write(pBuffer, nMagicPrefix, 11);
nMagicSuffix = pItemData->wMagicSuffix[0];
if (nMagicSuffix > 0)
{
if (nMagicSuffix >= 2047)
{
nMagicSuffix = 2047;
}
}
else
{
nMagicSuffix = 0;
}
BITMANIP_Write(pBuffer, nMagicSuffix, 11);
}
break;
}
case ITEMQUAL_SET:
case ITEMQUAL_UNIQUE:
{
if (bServer || pItemData->dwItemFlags & IFLAG_IDENTIFIED)
{
nFileIndex = pItemData->dwFileIndex;
if (nFileIndex < 0)
{
nFileIndex = 4095;
}
if (nFileIndex >= 4095)
{
nFileIndex = 4095;
}
BITMANIP_Write(pBuffer, nFileIndex, 12);
}
break;
}
default:
{
if (pItemData->dwQualityNo != ITEMQUAL_NORMAL)
{
pItemData->dwQualityNo = ITEMQUAL_NORMAL;
bInvalid = TRUE;
}
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_CHARM) && (bServer || pItemData->dwItemFlags & IFLAG_IDENTIFIED))
{
nMagicPrefix = pItemData->wMagicPrefix[0];
if (nMagicPrefix > nMagicPrefixOffset)
{
nMagicPrefix -= nMagicPrefixOffset;
}
BITMANIP_Write(pBuffer, nMagicPrefix ? 1 : 0, 1);
if (nMagicPrefix)
{
if (nMagicPrefix > 0)
{
if (nMagicPrefix >= 2047)
{
nMagicPrefix = 2047;
}
BITMANIP_Write(pBuffer, nMagicPrefix, 11);
}
else
{
BITMANIP_Write(pBuffer, 0, 11);
}
}
else
{
nMagicSuffix = pItemData->wMagicSuffix[0];
if (nMagicSuffix > 0)
{
if (nMagicSuffix >= 2047)
{
nMagicSuffix = 2047;
}
BITMANIP_Write(pBuffer, nMagicSuffix, 11);
}
else
{
BITMANIP_Write(pBuffer, 0, 11);
}
}
}
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_BODY_PART) && !ITEMS_CheckItemTypeId(pItem, ITEMTYPE_PLAYER_BODY_PART))
{
nFileIndex = pItemData->dwFileIndex;
if (nFileIndex > 0)
{
if (nFileIndex >= 1023)
{
nFileIndex = 1023;
}
}
else
{
nFileIndex = 0;
}
BITMANIP_Write(pBuffer, nFileIndex, 10);
}
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_SCROLL) || ITEMS_CheckItemTypeId(pItem, ITEMTYPE_BOOK))
{
nScrollType = pItemData->wMagicSuffix[0];
if (nScrollType > 0)
{
if (nScrollType >= 31)
{
nScrollType = 31;
}
}
else
{
nScrollType = 0;
}
BITMANIP_Write(pBuffer, nScrollType, 5);
}
break;
}
}
if (pItemData->dwItemFlags & IFLAG_RUNEWORD)
{
if (const D2RunesTxt* pRunesTxtRecord = ITEMS_GetRunesTxtRecordFromItem(pItem))
{
nRunewordId = pRunesTxtRecord->wStringId;
}
else
{
nRunewordId = -1;
}
if (nRunewordId > 0)
{
if (nRunewordId >= 65535)
{
nRunewordId = 65535;
}
}
else
{
nRunewordId = 0;
}
BITMANIP_Write(pBuffer, nRunewordId, 16);
}
if (pItemData->dwItemFlags & IFLAG_ISEAR)
{
nFileIndex = pItemData->dwFileIndex;
if (nFileIndex > 0)
{
if (nFileIndex >= 7)
{
nFileIndex = 7;
}
}
else
{
nFileIndex = 0;
}
BITMANIP_Write(pBuffer, nFileIndex, 3);
nEarLevel = pItemData->nEarLvl;
if (nEarLevel > 0)
{
if (nEarLevel >= 127)
{
nEarLevel = 127;
}
}
else
{
nEarLevel = 0;
}
BITMANIP_Write(pBuffer, nEarLevel, 7);
szPlayerName = pItemData->szPlayerName;
do
{
nCurrentCharacter = *szPlayerName;
if (nCurrentCharacter > 0)
{
if (nCurrentCharacter >= 127)
{
nCurrentCharacter = 127;
}
}
else
{
nCurrentCharacter = 0;
}
BITMANIP_Write(pBuffer, nCurrentCharacter, 7);
bContinue = *szPlayerName++;
}
while (bContinue);
}
else if (pItemData->dwItemFlags & IFLAG_PERSONALIZED)
{
szPlayerName = pItemData->szPlayerName;
do
{
nCurrentCharacter = *szPlayerName;
if (nCurrentCharacter > 0)
{
if (nCurrentCharacter >= 127)
{
nCurrentCharacter = 127;
}
}
else
{
nCurrentCharacter = 0;
}
BITMANIP_Write(pBuffer, nCurrentCharacter, 7);
bContinue = *szPlayerName++;
}
while (bContinue);
}
if (bServer)
{
if (pItemData->dwRealmData[1])
{
BITMANIP_Write(pBuffer, 1, 1);
BITMANIP_Write(pBuffer, pItemData->dwRealmData[0], 32);
ITEMS_WriteBitsToBitstream(pBuffer, pItemData->dwRealmData[1], 32);
ITEMS_WriteBitsToBitstream(pBuffer, 0, 32);
}
else
{
ITEMS_WriteBitsToBitstream(pBuffer, 0, 1);
}
}
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_ANY_ARMOR))
{
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_ARMORCLASS);
ITEMS_WriteBitsToBitstream(pBuffer, STATLIST_GetUnitBaseStat(pItem, STAT_ARMORCLASS, 0) + pItemStatCostTxtRecord->dwSaveAdd, pItemStatCostTxtRecord->nSaveBits);
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_MAXDURABILITY);
nMaxDurability = STATLIST_GetUnitBaseStat(pItem, STAT_MAXDURABILITY, 0);
ITEMS_WriteBitsToBitstream(pBuffer, nMaxDurability + pItemStatCostTxtRecord->dwSaveAdd, pItemStatCostTxtRecord->nSaveBits);
if (nMaxDurability)
{
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_DURABILITY);
ITEMS_WriteBitsToBitstream(pBuffer, STATLIST_GetUnitStatUnsigned(pItem, STAT_DURABILITY, 0) + pItemStatCostTxtRecord->dwSaveAdd, pItemStatCostTxtRecord->nSaveBits);
}
}
else if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_WEAPON))
{
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_MAXDURABILITY);
nMaxDurability = STATLIST_GetUnitBaseStat(pItem, STAT_MAXDURABILITY, 0);
ITEMS_WriteBitsToBitstream(pBuffer, nMaxDurability + pItemStatCostTxtRecord->dwSaveAdd, pItemStatCostTxtRecord->nSaveBits);
if (nMaxDurability)
{
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_DURABILITY);
ITEMS_WriteBitsToBitstream(pBuffer, STATLIST_GetUnitStatUnsigned(pItem, STAT_DURABILITY, 0) + pItemStatCostTxtRecord->dwSaveAdd, pItemStatCostTxtRecord->nSaveBits);
}
}
else if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_GOLD))
{
nGold = STATLIST_GetUnitStatUnsigned(pItem, STAT_GOLD, 0);
ITEMS_WriteBitsToBitstream(pBuffer, nGold >= 4096, 1);
ITEMS_WriteBitsToBitstream(pBuffer, nGold, nGold >= 4096 ? 32 : 12);
}
if (ITEMS_CheckIfStackable(pItem))
{
ITEMS_WriteBitsToBitstream(pBuffer, STATLIST_GetUnitStatUnsigned(pItem, STAT_QUANTITY, 0), 9);
}
if (pItemData->dwItemFlags & IFLAG_SOCKETED)
{
ITEMS_WriteBitsToBitstream(pBuffer, STATLIST_GetUnitBaseStat(pItem, STAT_ITEM_NUMSOCKETS, 0), ITEMS_GetItemStatCostTxtRecord(STAT_ITEM_NUMSOCKETS)->nSaveBits);
}
if (bServer || pItemData->dwItemFlags & IFLAG_IDENTIFIED)
{
nStatLists = 0;
if (ITEMS_GetItemQuality(pItem) == ITEMQUAL_SET)
{
nSetItemMask = 0;
nCounter = 0;
do
{
if (STATLIST_GetStatListFromUnitStateAndFlag(pItem, gnItemSetStates_6FDD15A8[nCounter], 0x2040) || STATLIST_GetStatListFromUnitStateAndFlag(pItem, gnItemSetStates_6FDD15A8[nCounter], 0x40))
{
nStatLists = nCounter + 1;
nSetItemMask += 1 << nCounter;
}
++nCounter;
}
while (nCounter < 5);
ITEMS_WriteBitsToBitstream(pBuffer, nSetItemMask, 5);
}
bIsRuneword = 0;
if (ITEMS_CheckItemFlag(pItem, IFLAG_RUNEWORD, __LINE__, __FILE__))
{
++nStatLists;
bIsRuneword = TRUE;
}
nStatListCounter = -1;
pStatListEx = STATLIST_GetStatListFromUnitStateAndFlag(pItem, 0, 0x40);
while (1)
{
if (pStatListEx && !bInvalid)
{
memset(nStatValues, 0, sizeof(nStatValues));
nStats = STATLIST_GetBaseStatsData((D2StatListExStrc*)pStatListEx, pStat, ARRAY_SIZE(pStat));
nStatCounter = 0;
while (nStatCounter < nStats)
{
nStatId = pStat[nStatCounter].nStat;
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(nStatId);
nValue = pStat[nStatCounter].nValue >> pItemStatCostTxtRecord->nValShift;
if (pItemStatCostTxtRecord->nSaveBits && nValue && nValue != nStatValues[nStatId])
{
ITEMS_WriteBitsToBitstream(pBuffer, nStatId, 9);
if (nStatId <= STAT_MAGICMINDAM)
{
if (nStatId == STAT_MAGICMINDAM)
{
ITEMS_WriteBitsToBitstream(pBuffer, nValue + pItemStatCostTxtRecord->dwSaveAdd, pItemStatCostTxtRecord->nSaveBits);
pLocalRecord = ITEMS_GetItemStatCostTxtRecord(STAT_MAGICMAXDAM);
nStatValues[STAT_MAGICMAXDAM] = STATLIST_GetStatValue(pStatListEx, STAT_MAGICMAXDAM, 0);
ITEMS_WriteBitsToBitstream(pBuffer, nStatValues[STAT_MAGICMAXDAM] + pLocalRecord->dwSaveAdd, pLocalRecord->nSaveBits);
}
else if (nStatId == STAT_ITEM_MAXDAMAGE_PERCENT)
{
ITEMS_WriteBitsToBitstream(pBuffer, nValue + pItemStatCostTxtRecord->dwSaveAdd, pItemStatCostTxtRecord->nSaveBits);
pLocalRecord = ITEMS_GetItemStatCostTxtRecord(STAT_ITEM_MINDAMAGE_PERCENT);
nStatValues[STAT_ITEM_MINDAMAGE_PERCENT] = STATLIST_GetStatValue(pStatListEx, STAT_ITEM_MINDAMAGE_PERCENT, 0);
ITEMS_WriteBitsToBitstream(pBuffer, nStatValues[STAT_ITEM_MINDAMAGE_PERCENT] + pLocalRecord->dwSaveAdd, pLocalRecord->nSaveBits);
}
else if (nStatId == STAT_FIREMINDAM)
{
ITEMS_WriteBitsToBitstream(pBuffer, nValue + pItemStatCostTxtRecord->dwSaveAdd, pItemStatCostTxtRecord->nSaveBits);
pLocalRecord = ITEMS_GetItemStatCostTxtRecord(STAT_FIREMAXDAM);
nStatValues[STAT_FIREMAXDAM] = STATLIST_GetStatValue(pStatListEx, STAT_FIREMAXDAM, 0);
ITEMS_WriteBitsToBitstream(pBuffer, nStatValues[STAT_FIREMAXDAM] + pLocalRecord->dwSaveAdd, pLocalRecord->nSaveBits);
}
else if (nStatId == STAT_LIGHTMINDAM)
{
ITEMS_WriteBitsToBitstream(pBuffer, nValue + pItemStatCostTxtRecord->dwSaveAdd, pItemStatCostTxtRecord->nSaveBits);
pLocalRecord = ITEMS_GetItemStatCostTxtRecord(STAT_LIGHTMAXDAM);
nStatValues[STAT_LIGHTMAXDAM] = STATLIST_GetStatValue(pStatListEx, STAT_LIGHTMAXDAM, 0);
ITEMS_WriteBitsToBitstream(pBuffer, nStatValues[STAT_LIGHTMAXDAM] + pLocalRecord->dwSaveAdd, pLocalRecord->nSaveBits);
}
else
{
if ((int)pItemStatCostTxtRecord->dwSaveParamBits > 0)
{
ITEMS_WriteBitsToBitstream(pBuffer, pStat[nStatCounter].nLayer, pItemStatCostTxtRecord->dwSaveParamBits);
}
if (pItemStatCostTxtRecord->nSaveBits)
{
ITEMS_WriteBitsToBitstream(pBuffer, nValue + pItemStatCostTxtRecord->dwSaveAdd, pItemStatCostTxtRecord->nSaveBits);
}
}
}
else if (nStatId == STAT_COLDMINDAM)
{
ITEMS_WriteBitsToBitstream(pBuffer, nValue + pItemStatCostTxtRecord->dwSaveAdd, pItemStatCostTxtRecord->nSaveBits);
pLocalRecord = ITEMS_GetItemStatCostTxtRecord(STAT_COLDMAXDAM);
nStatValues[STAT_COLDMAXDAM] = STATLIST_GetStatValue(pStatListEx, STAT_COLDMAXDAM, 0);
ITEMS_WriteBitsToBitstream(pBuffer, nStatValues[STAT_COLDMAXDAM] + pLocalRecord->dwSaveAdd, pLocalRecord->nSaveBits);
pLocalRecord = ITEMS_GetItemStatCostTxtRecord(STAT_COLDLENGTH);
nStatValues[STAT_COLDLENGTH] = STATLIST_GetStatValue(pStatListEx, STAT_COLDLENGTH, 0);
ITEMS_WriteBitsToBitstream(pBuffer, nStatValues[STAT_COLDLENGTH] + pLocalRecord->dwSaveAdd, pLocalRecord->nSaveBits);
}
else if (nStatId == STAT_POISONMINDAM)
{
ITEMS_WriteBitsToBitstream(pBuffer, nValue + pItemStatCostTxtRecord->dwSaveAdd, pItemStatCostTxtRecord->nSaveBits);
pLocalRecord = ITEMS_GetItemStatCostTxtRecord(STAT_POISONMAXDAM);
nStatValues[STAT_POISONMAXDAM] = STATLIST_GetStatValue(pStatListEx, STAT_POISONMAXDAM, 0);
ITEMS_WriteBitsToBitstream(pBuffer, nStatValues[STAT_POISONMAXDAM] + pLocalRecord->dwSaveAdd, pLocalRecord->nSaveBits);
pLocalRecord = ITEMS_GetItemStatCostTxtRecord(STAT_POISONLENGTH);
nStatValues[STAT_POISONLENGTH] = STATLIST_GetStatValue(pStatListEx, STAT_POISONLENGTH, 0);
ITEMS_WriteBitsToBitstream(pBuffer, nStatValues[STAT_POISONLENGTH] + pLocalRecord->dwSaveAdd, pLocalRecord->nSaveBits);
}
else if (nStatId != STAT_POISON_COUNT)
{
if ((int)pItemStatCostTxtRecord->dwSaveParamBits > 0)
{
ITEMS_WriteBitsToBitstream(pBuffer, pStat[nStatCounter].nLayer, pItemStatCostTxtRecord->dwSaveParamBits);
}
if (pItemStatCostTxtRecord->nSaveBits)
{
ITEMS_WriteBitsToBitstream(pBuffer, nValue + pItemStatCostTxtRecord->dwSaveAdd, pItemStatCostTxtRecord->nSaveBits);
}
}
}
++nStatCounter;
}
}
if (nStatListCounter < 0 || pStatListEx || bIsRuneword)
{
ITEMS_WriteBitsToBitstream(pBuffer, 511, 9);
}
++nStatListCounter;
if (nStatListCounter >= nStatLists)
{
return;
}
if (bIsRuneword && nStatListCounter == nStatLists - 1)
{
pStatListEx = STATLIST_GetStatListFromUnitStateOrFlag(pItem, STATE_RUNEWORD, 0x40);
}
else
{
pStatListEx = STATLIST_GetStatListFromUnitStateAndFlag(pItem, gnItemSetStates_6FDD15A8[nStatListCounter], 0x2040);
if (!pStatListEx)
{
pStatListEx = STATLIST_GetStatListFromUnitStateAndFlag(pItem, gnItemSetStates_6FDD15A8[nStatListCounter], 0x40);
}
}
}
}
}
//D2Common.0x6FDA42B0
D2ItemStatCostTxt* __fastcall ITEMS_GetItemStatCostTxtRecord(int nStatId)
{
if (nStatId >= 0 && nStatId < sgptDataTables->nItemStatCostTxtRecordCount)
{
return &sgptDataTables->pItemStatCostTxt[nStatId];
}
return NULL;
}
//D2Common.0x6FDA42E0 (#10837)
int __stdcall ITEMS_GetNoOfSetItemsFromItem(D2UnitStrc* pItem)
{
D2SetItemsTxt* pSetItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData && pItem->pItemData->dwQualityNo == ITEMQUAL_SET)
{
if (pItem->pItemData->dwFileIndex >= 0 && pItem->pItemData->dwFileIndex < sgptDataTables->nSetItemsTxtRecordCount)
{
pSetItemsTxtRecord = &sgptDataTables->pSetItemsTxt[pItem->pItemData->dwFileIndex];
if (pSetItemsTxtRecord)
{
return pSetItemsTxtRecord->nSetItems;
}
}
}
return -1;
}
//D2Common.0x6FDD15C8
int gnItemSetStates[] =
{
STATE_ITEMSET1, STATE_ITEMSET2, STATE_ITEMSET3, STATE_ITEMSET4, STATE_ITEMSET5, STATE_ITEMSET6
};
//D2Common.0x6FDD15E0
int gnSetMaskToBonusMappingTable[] =
{
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6
};
//D2Common.0x6FDA4380
//TODO: Find a name
BOOL __fastcall sub_6FDA4380(D2UnitStrc* pItem, unsigned int nSetItemMask)
{
D2SetItemsTxt* pSetItemsTxt = NULL;
int nSetItems = 0;
int nBonuses = 0;
int nIndex = 0;
BOOL bSet = FALSE;
if (!pItem || pItem->dwUnitType != UNIT_ITEM || ITEMS_GetItemQuality(pItem) != ITEMQUAL_SET)
{
return FALSE;
}
pSetItemsTxt = ITEMS_GetSetItemsTxtRecordFromItem(pItem);
if (!pSetItemsTxt || !pSetItemsTxt->nAddFunc)
{
return FALSE;
}
if (pSetItemsTxt->nAddFunc == 1)
{
nSetItems = ITEMS_GetNoOfSetItemsFromItem(pItem);
for (int i = 0; i < 6; ++i)
{
nIndex = i;
if (i != nSetItems)
{
if (i > nSetItems)
{
--nIndex;
}
if ((1 << i) & nSetItemMask)
{
bSet = FALSE;
}
else
{
bSet = TRUE;
}
D2Common_10574(pItem, gnItemSetStates[nIndex], bSet);
}
}
}
else if (pSetItemsTxt->nAddFunc == 2)
{
nBonuses = nSetItemMask < ARRAY_SIZE(gnSetMaskToBonusMappingTable) ? gnSetMaskToBonusMappingTable[nSetItemMask] : 0;
for (int i = 0; i < nBonuses - 1; ++i)
{
D2Common_10574(pItem, gnItemSetStates[i], FALSE);
}
if (nBonuses - 1 >= 5)
{
return TRUE;
}
for(int i = nBonuses - 1; i < 6; ++i)
{
D2Common_10574(pItem, gnItemSetStates[i], TRUE);
}
}
return TRUE;
}
//D2Common.0x6FDA4490
//TODO: Find a name
BOOL __fastcall sub_6FDA4490(D2UnitStrc* pUnit, D2UnitStrc* pItem, int a3)
{
D2SetItemsTxt* pSetItemsTxtRecord = NULL;
D2StatListStrc* pStatList = NULL;
int nFileIndex = 0;
int nIndex = 0;
int nValue = 0;
if (a3 <= 1 && pUnit && pItem && pItem->dwUnitType == UNIT_ITEM && ITEMS_GetItemQuality(pItem) == ITEMQUAL_SET && (pUnit->dwUnitType != UNIT_ITEM || !ITEMS_IsMagSetRarUniCrfOrTmp(pUnit)))
{
nFileIndex = ITEMS_GetFileIndex(pItem);
if (nFileIndex >= 0 && nFileIndex < sgptDataTables->nSetItemsTxtRecordCount)
{
pSetItemsTxtRecord = &sgptDataTables->pSetItemsTxt[nFileIndex];
if (pSetItemsTxtRecord && pSetItemsTxtRecord->nSetId >= 0 && pSetItemsTxtRecord->nSetId < sgptDataTables->nSetsTxtRecordCount)
{
nValue = pSetItemsTxtRecord->nSetId;
nIndex = -1;
for (int i = 0; i < 6; ++i)
{
pStatList = STATLIST_GetStatListFromUnitAndState(pUnit, gnItemSetStates[i]);
if (pStatList)
{
if (nValue == STATLIST_GetStatValue(pStatList, STAT_VALUE, 0))
{
if (a3 == 0)
{
STATLIST_RemoveAllStats(pStatList);
STATLIST_AddStat(pStatList, STAT_VALUE, nValue, 0);
ITEMMODS_UpdateFullSetBoni(pUnit, pItem, gnItemSetStates[i]);
}
else if (a3 == 1)
{
D2Common_10474(pUnit, pStatList);
STATLIST_FreeStatList(pStatList);
}
return TRUE;
}
}
else if (nIndex < 0)
{
nIndex = i;
}
}
if (a3 == 1 || nIndex < 0)
{
return FALSE;
}
pStatList = STATLIST_AllocStatList(pUnit->pMemoryPool, 0, 0, pItem->dwUnitType, pItem->dwUnitId);
D2COMMON_10475_PostStatToStatList(pUnit, pStatList, 1);
STATLIST_SetState(pStatList, gnItemSetStates[nIndex]);
if (a3 == 0)
{
STATLIST_AddStat(pStatList, STAT_VALUE, nValue, 0);
ITEMMODS_UpdateFullSetBoni(pUnit, pItem, gnItemSetStates[nIndex]);
}
//else if (a3 == 1)
//{
// D2Common_10474(pUnit, pStatList);
// STATLIST_FreeStatList(pStatList);
//}
return TRUE;
}
}
}
return FALSE;
}
//D2Common.0x6FDA4640 (#10866)
BOOL __stdcall ITEMS_UpdateSets(D2UnitStrc* pUnit, D2UnitStrc* pItem, int a3, int a4)
{
unsigned int nSetItemMask = 0;
if (pUnit && pItem && pItem->dwUnitType == UNIT_ITEM && pUnit->pInventory)
{
if (INVENTORY_IsItemInInventory(pUnit->pInventory, pItem) && INVENTORY_GetItemNodePage(pItem) == 3)
{
nSetItemMask = ITEMS_GetSetItemsMask(pUnit, pItem, TRUE);
}
if (a4 || !a3)
{
sub_6FDA4380(pItem, nSetItemMask);
}
sub_6FDA4490(pUnit, pItem, a3);
return TRUE;
}
return FALSE;
}
| 25.696934 | 232 | 0.702981 | raumuongluoc |
6335d7f36b845fd556117015a46314f05aeccb04 | 440 | cc | C++ | lib/lf/base/lf_assert.cc | Pascal-So/lehrfempp | e2716e914169eec7ee59e822ea3ab303143eacd1 | [
"MIT"
] | null | null | null | lib/lf/base/lf_assert.cc | Pascal-So/lehrfempp | e2716e914169eec7ee59e822ea3ab303143eacd1 | [
"MIT"
] | null | null | null | lib/lf/base/lf_assert.cc | Pascal-So/lehrfempp | e2716e914169eec7ee59e822ea3ab303143eacd1 | [
"MIT"
] | null | null | null | /** @file lf_assert.cc */
#include "lf_assert.h"
#include <iostream>
namespace lf::base {
// Output for assertions
void AssertionFailed(const std::string& expr, const std::string& file, int line,
const std::string& msg) {
std::cerr << "***** Internal Program Error - assertion (" << expr
<< ") failed:\n"
<< file << '(' << line << "): " << msg << std::endl;
}
} // end namespace lf::base
| 25.882353 | 80 | 0.552273 | Pascal-So |
63365c091173ab941fac5cf8a42e8a1fb9a587e9 | 11,052 | hxx | C++ | tests/testing_factor_node_unsym.hxx | tasseff/SyLVER | 35cb652ece05447ddf12e530e97428078446eaf4 | [
"BSD-3-Clause"
] | 9 | 2019-07-02T12:46:22.000Z | 2021-07-08T11:54:46.000Z | tests/testing_factor_node_unsym.hxx | tasseff/SyLVER | 35cb652ece05447ddf12e530e97428078446eaf4 | [
"BSD-3-Clause"
] | 2 | 2020-03-23T22:55:52.000Z | 2020-03-24T11:15:16.000Z | tests/testing_factor_node_unsym.hxx | tasseff/SyLVER | 35cb652ece05447ddf12e530e97428078446eaf4 | [
"BSD-3-Clause"
] | 5 | 2019-06-10T11:11:14.000Z | 2020-03-22T02:38:12.000Z | #pragma once
// SpLDLT
#include "SymbolicFront.hxx"
#include "NumericFront.hxx"
#include "factor_unsym.hxx"
#include "kernels/lu_nopiv.hxx"
#include "sylver_ciface.hxx"
// SSIDS
#include "ssids/cpu/cpu_iface.hxx"
namespace sylver {
namespace splu {
namespace tests {
/// @param T working precision
/// @param FactorAllocator memory allocator for factors
/// @param m number of rows/columns in the front
/// @param k number of columns to eliminate
template<typename T, typename FactorAllocator>
int factor_node_unsym_test(
struct spral::ssids::cpu::cpu_factor_options& options, int m, int k,
int ncpu, int ngpu, bool diagdom, bool check) {
bool failed = false;
int blksz = options.cpu_block_size;
printf("[factor_node_unsym_test] m = %d\n", m);
printf("[factor_node_unsym_test] k = %d\n", k);
printf("[factor_node_unsym_test] blksz = %d\n", blksz);
printf("[factor_node_unsym_test] u = %e\n", options.u);
// We don't allow these cases
ASSERT_TRUE(k > 0);
ASSERT_TRUE(m > 0);
ASSERT_TRUE(ncpu > 0);
ASSERT_TRUE(ngpu >= 0);
ASSERT_TRUE(m >= k);
////////////////////////////////////////
// Init test problem
// Generate test matrix
int lda = spral::ssids::cpu::align_lda<T>(m);
printf("[factor_node_unsym_test] lda = %d\n", lda);
T* a = nullptr;
T* b = nullptr;
////////////////////////////////////////
// Setup front
// Setup pool allocator
typedef spldlt::BuddyAllocator<T,std::allocator<T>> PoolAllocator;
// typedef spral::ssids::cpu::BuddyAllocator<T, std::allocator<T>> PoolAllocator;
PoolAllocator pool_alloc(m*m);
// Setup symbolic front
spldlt::SymbolicFront sfront;
sfront.nrow = m;
sfront.ncol = k;
spldlt::NumericFront<T, PoolAllocator> front(sfront, pool_alloc, blksz);
front.ndelay_in = 0; // No incoming delayed columns
front.ndelay_out = 0;
// Allocate factors
FactorAllocator factor_alloc;
size_t lenL = lda*k; // Size of L
// Allocate L factor (size m x k). Contains U factors in the upper triangular part
front.lcol = factor_alloc.allocate(lenL);
// Allocate U factor (size k x (m-k))
int ldu = spral::ssids::cpu::align_lda<T>(k);
size_t lenU = ldu*(m-k); // Size of U
front.ucol = factor_alloc.allocate(lenU);
// Generate factors
if (check) {
a = new T[lda*m];
// if (diagdom) gen_unsym_diagdom(m, a, lda);
if (diagdom) gen_unsym_diagdomblock(m, a, lda, blksz);
else gen_mat(m, m, a, lda);
print_mat_unsym(" %6.2f", m, a, lda);
b = new T[m];
gen_unsym_rhs(m, a, lda, b);
// Copy A in L
memcpy(front.lcol, a, lda*k*sizeof(T));
// Copy A in U
if (m > k) {
for (int j = 0; j < m-k; ++j)
memcpy(&front.ucol[j*ldu], &a[j*lda], k*sizeof(T));
}
}
else {
ASSERT_TRUE(m == k); // FIXME: does not work for non square fronts
if (diagdom) gen_unsym_diagdom(m, front.lcol, lda);
else gen_mat(m, m, front.lcol, lda);
}
// Alloc blocks in the factors
front.alloc_blocks_unsym();
// Allocate contribution blocks
front.alloc_contrib_blocks_unsym();
if (options.pivot_method == spral::ssids::cpu::PivotMethod::app_block) {
// Allocate backups of blocks
front.alloc_backup_blocks_unsym();
// Setup colulm data
front.alloc_cdata(); // TODO only if piv strategy is APTP
}
// Setup permutation vector
// Row permutation
front.perm = new int[m];
for(int i=0; i<m; i++) front.perm[i] = i;
// Column permutation
front.cperm = new int[m];
for(int i=0; i<m; i++) front.cperm[i] = i;
////////////////////////////////////////
// Launch runtime system
#if defined(SPLDLT_USE_STARPU)
struct starpu_conf conf;
starpu_conf_init(&conf);
conf.ncpus = ncpu;
conf.sched_policy_name = "lws";
int ret;
ret = starpu_init(&conf);
STARPU_CHECK_RETURN_VALUE(ret, "starpu_init");
#endif
////////////////////////////////////////
// Create workspaces
int nworkers = 1;
#if defined(SPLDLT_USE_STARPU)
nworkers = starpu_worker_get_count();
// #else
// nworkers = omp_get_num_threads();
#endif
std::vector<spral::ssids::cpu::ThreadStats> worker_stats(nworkers);
std::vector<spral::ssids::cpu::Workspace> workspaces;
const int PAGE_SIZE = 8*1024*1024; // 8 MB
workspaces.reserve(nworkers);
for(int i = 0; i < nworkers; ++i)
workspaces.emplace_back(PAGE_SIZE);
printf("[factor_node_indef_test] nworkers = %d\n", nworkers);
////////////////////////////////////////
// Register data in runtime system
#if defined(SPLDLT_USE_STARPU)
// TODO
#endif
////////////////////////////////////////
// Perform factorization
printf("[factor_node_unsym_test] Factor..\n");
auto start = std::chrono::high_resolution_clock::now();
switch (options.pivot_method) {
case spral::ssids::cpu::PivotMethod::app_aggressive:
// Front factorization using restricted pivoting
factor_front_unsym_rp(front, workspaces);
break;
case spral::ssids::cpu::PivotMethod::app_block:
// Front factorization using restricted pivoting
factor_front_unsym_app(options, front, workspaces);
// Print permutation matrix
printf("cperm = \n");
for (int i=0; i<m; ++i)
printf(" %d ", front.cperm[i]);
printf("\n");
print_mat_unsym(" %6.2f", k, front.lcol, lda, front.perm);
printf("[factor_node_unsym_test] Eliminated pivots = %d\n", front.nelim);
printf("[factor_node_unsym_test] Permute failed\n");
permute_failed_unsym(front);
// Print permutation matrix
printf("cperm = \n");
for (int i=0; i<m; ++i)
printf(" %d ", front.cperm[i]);
printf("\n");
print_mat_unsym(" %6.2f", k, front.lcol, lda, front.perm);
break;
default:
printf("[factor_node_unsym_test] Pivot method not implemented\n");
}
// Wait for completion
#if defined(SPLDLT_USE_STARPU)
starpu_task_wait_for_all();
#endif
auto end = std::chrono::high_resolution_clock::now();
long ttotal =
std::chrono::duration_cast<std::chrono::nanoseconds>
(end-start).count();
////////////////////////////////////////
// Shutdown runtime system
#if defined(SPLDLT_USE_STARPU)
starpu_shutdown();
#endif
////////////////////////////////////////
// Check solution results
if (check) {
int nelim = front.nelim;
int *rperm = front.perm;
int *cperm = front.cperm;
// // Print permutation matrix
// printf("rperm = \n");
// for (int i=0; i<m; ++i)
// printf(" %d ", rperm[i]);
// printf("\n");
// // Print permutation matrix
// printf("cperm = \n");
// for (int i=0; i<m; ++i)
// printf(" %d ", cperm[i]);
// printf("\n");
// Alloc lu array for storing factors
T *lu = factor_alloc.allocate(lda*m);
// Initialize array with zeros
for (int j=0; j<m; ++j)
for (int i=0; i<m; ++i)
lu[i+j*lda] = 0.0;
// Copy factors from lcol into lu array
// Copy only factors (colmuns 1 to k)
memcpy(lu, front.lcol, lda*k*sizeof(T)); // Copy lcol to lu
// print_mat_unsym(" %6.2f", k, lu, lda, rperm);
if (m > k) {
// TODO Copy part from ucol into lu
// TODO Copy cb into lu
}
if (nelim < m) {
printf("[factor_node_unsym_test] Finish off\n");
// Finish off uneliminated entries
lu_pp_factor(
m-nelim, m-nelim, &rperm[nelim], &lu[nelim+nelim*lda], lda,
nelim, &lu[nelim], lda);
print_mat_unsym(" %6.2f", m, lu, lda, rperm);
}
int nrhs = 1;
int ldsoln = m;
T *soln = new T[nrhs*ldsoln];
// Setup permuted rhs
T *pb = new T[m];
for (int i=0; i<m; ++i)
for (int r=0; r<nrhs; ++r)
pb[r*ldsoln+i] = b[r*ldsoln+rperm[i]];
// Copy rhs into solution vector
for(int r=0; r<nrhs; ++r)
memcpy(&soln[r*ldsoln], pb, m*sizeof(T));
// Perform solve
// Fwd substitutuion
lu_nopiv_fwd(m, k, lu, lda, nrhs, soln, ldsoln);
// Bwd substitutuion
lu_nopiv_bwd(m, k, lu, lda, nrhs, soln, ldsoln);
// Permute x
T *psoln = new T[m];
for (int i=0; i<m; ++i)
for (int r=0; r<nrhs; ++r)
psoln[r*ldsoln+i] = soln[r*ldsoln+cperm[i]];
// Calculate bwd error
double bwderr = unsym_backward_error(
m, k, a, lda, b, nrhs, psoln, ldsoln);
printf("bwderr = %le\n", bwderr);
}
////////////////////////////////////////
// Print results
printf("factor time (s) = %e\n", 1e-9*ttotal);
////////////////////////////////////////
// Cleanup memory
if (options.pivot_method == spral::ssids::cpu::PivotMethod::app_block) {
// Allocate backups of blocks
front.release_backup_blocks_unsym();
// Free column data
front.free_cdata();
}
// Cleanup data structures
front.free_contrib_blocks_unsym();
front.free_blocks_unsym();
// Cleanup factors
factor_alloc.deallocate(front.lcol, lenL);
factor_alloc.deallocate(front.ucol, lenU);
if (check) {
delete[] a;
delete[] b;
}
return failed ? -1 : 0;
}
}}} // End of namespace spylver::splu::tests
| 32.795252 | 92 | 0.491857 | tasseff |
6336af14cb080015d674299c2b778c6597206349 | 692 | cpp | C++ | Arrays & Strings/BreakWords.cpp | tanmayagarwal06/CompetitiveProgramming | ce1df2dbe829a0babfb18e65beee8604eb80915c | [
"MIT"
] | null | null | null | Arrays & Strings/BreakWords.cpp | tanmayagarwal06/CompetitiveProgramming | ce1df2dbe829a0babfb18e65beee8604eb80915c | [
"MIT"
] | null | null | null | Arrays & Strings/BreakWords.cpp | tanmayagarwal06/CompetitiveProgramming | ce1df2dbe829a0babfb18e65beee8604eb80915c | [
"MIT"
] | 3 | 2020-10-06T02:57:41.000Z | 2020-10-20T06:54:04.000Z | #include<iostream>
#include<string.h>
using namespace std;
void breakWords(char* S)
{
int j = 0;
int count = 0;
int i = 0;
int n = strlen(S);
while(i<=n){
n = strlen(S);
j = i;
while(S[i] != ' ' || S[i] != '\0'){
i++;
}
count = i-j;
if(count%2 == 0){
int space = j + (count)/2;
for(int z = n; z>=space; z--){
S[z+1] = S[z];
}
S[space] = ' ';
i++;
}
i++;
}
}
int main()
{
char str[100000];
cin.getline(str,100000);
breakWords(str);
cout<<str;
}
| 16.878049 | 44 | 0.348266 | tanmayagarwal06 |
6336bff2c15bf517640b3ca2e8bf426c31964250 | 425 | cpp | C++ | 0001.TwoSum/main.cpp | SumanSudhir/LeetCode | cab5205747b8c1a9d5c27f0e821cf6e6d9ac10d6 | [
"MIT"
] | 1 | 2020-01-13T11:10:35.000Z | 2020-01-13T11:10:35.000Z | 0001.TwoSum/main.cpp | SumanSudhir/LeetCode | cab5205747b8c1a9d5c27f0e821cf6e6d9ac10d6 | [
"MIT"
] | 4 | 2020-01-01T09:47:39.000Z | 2020-04-08T08:34:29.000Z | 0001.TwoSum/main.cpp | SumanSudhir/LeetCode | cab5205747b8c1a9d5c27f0e821cf6e6d9ac10d6 | [
"MIT"
] | null | null | null | class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> out;
for(int i=0;i<nums.size()-1;i++){
for(int j = i+1;j<nums.size();j++){
if((nums[i] + nums[j]) == target){
out.push_back(i);
out.push_back(j);
break;
}
}
}
return out;
}
};
| 20.238095 | 55 | 0.385882 | SumanSudhir |
633812fca97251f92e2181fe6fb38e5394c4015c | 453 | cpp | C++ | android/EuhatExpert/app/src/main/cpp/macHdd.cpp | euhat/EuhatExpert | 3932238a0bd72a8f12b4ae6ced1ade6482228fe0 | [
"BSD-2-Clause"
] | null | null | null | android/EuhatExpert/app/src/main/cpp/macHdd.cpp | euhat/EuhatExpert | 3932238a0bd72a8f12b4ae6ced1ade6482228fe0 | [
"BSD-2-Clause"
] | null | null | null | android/EuhatExpert/app/src/main/cpp/macHdd.cpp | euhat/EuhatExpert | 3932238a0bd72a8f12b4ae6ced1ade6482228fe0 | [
"BSD-2-Clause"
] | null | null | null | #include "macHdd.h"
#include <common/OpCommon.h>
#include <common/WhCommon.h>
#define INI_SECTION_LOCAL "local"
int isMacHddChanged(DbOpIni &ini, const char *mac)
{
string macsOld = ini.readStr(INI_SECTION_LOCAL, "mac");
if (macsOld.empty())
{
ini.write(INI_SECTION_LOCAL, "mac", mac);
return 0;
}
if (macsOld != mac)
{
ini.write(INI_SECTION_LOCAL, "mac", mac);
return 1;
}
return 0;
} | 19.695652 | 59 | 0.613687 | euhat |
633b0d506075e1dfce4c71be4bf01f93c08ec35f | 7,411 | cpp | C++ | src/BldRecons/SPB2BP/ConvertGrid.cpp | liuxinren/UrbanReconstruction | 079d9b0c9089aa9cdb15d31d76155e50a5e72f00 | [
"MIT"
] | 94 | 2017-07-20T05:32:07.000Z | 2022-03-02T03:38:54.000Z | src/BldRecons/SPB2BP/ConvertGrid.cpp | GucciPrada/UrbanReconstruction | 8b058349fd860ea9029623a92d705dd93a4e4878 | [
"MIT"
] | 3 | 2017-09-12T00:07:05.000Z | 2020-03-08T21:12:36.000Z | src/BldRecons/SPB2BP/ConvertGrid.cpp | GucciPrada/UrbanReconstruction | 8b058349fd860ea9029623a92d705dd93a4e4878 | [
"MIT"
] | 38 | 2017-07-25T06:00:52.000Z | 2022-03-19T10:01:06.000Z | #include "StdAfx.h"
#include "ConvertGrid.h"
#include "ParamManager.h"
#include "Miscs\TimeMeter.h"
CConvertGrid::CConvertGrid(void)
{
}
CConvertGrid::~CConvertGrid(void)
{
}
void CConvertGrid::Convert()
{
CParamManager * manager = CParamManager::GetParamManager();
CTimeMeter timer;
timer.Start();
fprintf_s( stderr, "==================== Pass 1, count last cell ====================\n" );
InitCount();
fprintf_s( stderr, "Processing progress ... " );
InitPrintProgress();
int index;
while ( ( index = ReadNextChunk() ) != -1 ) {
PrintProgress( );
CConvertChunk * chunk = m_vecPointer[ index ];
CountChunk( chunk );
delete m_vecPointer[ index ];
m_vecPointer[ index ] = NULL;
}
fprintf_s( stderr, " ... done!\n" );
FinCount();
fprintf_s( stderr, "Total processing time is " );
timer.End();
timer.Print();
fprintf_s( stderr, ".\n\n" );
timer.Start();
fprintf_s( stderr, "==================== Pass 2, output ====================\n" );
InitWrite();
fprintf_s( stderr, "Processing progress ... " );
InitPrintProgress();
while ( ( index = ReadNextChunk() ) != -1 ) {
PrintProgress( );
CConvertChunk * chunk = m_vecPointer[ index ];
WriteChunk( chunk );
delete m_vecPointer[ index ];
m_vecPointer[ index ] = NULL;
}
fprintf_s( stderr, " ... done!\n" );
FinWrite();
fprintf_s( stderr, "Total processing time is " );
timer.End();
timer.Print();
fprintf_s( stderr, ".\n" );
}
int CConvertGrid::ReadNextChunk()
{
// return the index of the finalized chunk
// return -1 indicating a EOF has been read
bool bNoneChunkEnd = true;
int index;
while ( bNoneChunkEnd ) {
if ( m_cReader.ReadNextElement() ) { // read chunk information
SPBCell * cell = m_cReader.GetCell();
switch ( cell->type ) {
case 0: // begin chunk
m_vecPointer[ cell->chunk_index ] = new CConvertChunk( cell->chunk_index, cell->point_number, this );
break;
case 1: // end chunk
bNoneChunkEnd = false;
index = cell->chunk_index;
break;
case -1: // EOF
bNoneChunkEnd = false;
index = -1;
break;
}
} else {
SPBPoint * point = m_cReader.GetPoint();
CVector3D v( point->pos[0], point->pos[1], point->pos[2] );
CConvertChunk * chunk = m_vecPointer[ Index( v ) ];
chunk->PushPoint( point );
IncReadNumber();
}
}
return index;
}
//////////////////////////////////////////////////////////////////////////
// main functions
//////////////////////////////////////////////////////////////////////////
void CConvertGrid::InitCount()
{
CParamManager * manager = CParamManager::GetParamManager();
m_cReader.OpenFile( manager->m_pInputFile );
m_cReader.RegisterGrid( this );
m_cReader.ReadHeader();
m_vecPointer.clear();
m_vecPointer.resize( m_nSideNumber * m_nSideNumber, NULL );
m_hashWriterInfo.clear();
m_hashFinalizedPatch.clear();
}
void CConvertGrid::CountChunk( CConvertChunk * chunk )
{
CParamManager * manager = CParamManager::GetParamManager();
double min_z = MinGroundZ( chunk );
for ( int i = 0; i < ( int )( chunk->m_vecPatchPointData.size() ); i++ ) {
PatchPointData & point = chunk->m_vecPatchPointData[ i ];
if ( CheckPoint( point ) ) {
stdext::hash_map< PatchIndex, PatchWriterInfo >::iterator it = m_hashWriterInfo.find( point.patch.base );
if ( it == m_hashWriterInfo.end() ) {
PatchWriterInfo info;
info.begin_cell = chunk->m_iIndex;
info.final_cell = chunk->m_iIndex;
info.ground_z = min_z;
info.number = 1;
m_hashWriterInfo.insert( std::pair< PatchIndex, PatchWriterInfo >( point.patch.base, info ) );
} else {
it->second.final_cell = chunk->m_iIndex;
if ( it->second.ground_z > min_z )
it->second.ground_z = min_z;
it->second.number++;
}
}
}
}
void CConvertGrid::FinCount()
{
m_cReader.CloseFile();
for ( stdext::hash_map< PatchIndex, PatchWriterInfo >::iterator it = m_hashWriterInfo.begin(); it != m_hashWriterInfo.end(); it++ ) {
stdext::hash_map< int, std::vector< PatchIndex > >::iterator itt = m_hashFinalizedPatch.find( it->second.final_cell );
if ( itt == m_hashFinalizedPatch.end() ) {
std::vector< PatchIndex > temp;
temp.push_back( it->first );
m_hashFinalizedPatch.insert( std::pair< int, std::vector< PatchIndex > >( it->second.final_cell, temp ) );
} else {
itt->second.push_back( it->first );
}
}
fprintf_s( stderr, "Total %d roof patch are going to be written.\n", ( int )m_hashWriterInfo.size() );
}
void CConvertGrid::InitWrite()
{
CParamManager * manager = CParamManager::GetParamManager();
m_cReader.OpenFile( manager->m_pInputFile );
m_cReader.RegisterGrid( this );
m_cReader.ReadHeader();
m_vecPointer.clear();
m_vecPointer.resize( m_nSideNumber * m_nSideNumber, NULL );
m_hashWriter.clear();
}
void CConvertGrid::WriteChunk( CConvertChunk * chunk )
{
CParamManager * manager = CParamManager::GetParamManager();
for ( int i = 0; i < ( int )( chunk->m_vecPatchPointData.size() ); i++ ) {
PatchPointData & point = chunk->m_vecPatchPointData[ i ];
if ( CheckPoint( point ) ) {
stdext::hash_map< PatchIndex, CBPWriter >::iterator it = m_hashWriter.find( point.patch.base );
if ( it == m_hashWriter.end() ) {
stdext::hash_map< PatchIndex, PatchWriterInfo >::iterator itinfo = m_hashWriterInfo.find( point.patch.base );
if ( itinfo->second.ground_z == 1e300 ) {
itinfo->second.ground_z = m_cBoundingBox.m_vMin[ 2 ];
}
char filename[ 1024 ];
sprintf_s( filename, 1024, "%sPatch_%016I64x.bp", manager->m_pOutputDir, point.patch.base );
CBPWriter writer;
writer.OpenFile( filename );
writer.WriteHeader( point.patch.base, itinfo->second.number, itinfo->second.ground_z, m_dbGridLength );
writer.WritePoint( point.v.pVec, point.n.pVec, point.flatness, -1 );
m_hashWriter.insert( std::pair< PatchIndex, CBPWriter >( point.patch.base, writer ) );
} else {
it->second.WritePoint( point.v.pVec, point.n.pVec, point.flatness, -1 );
}
}
}
stdext::hash_map< int, std::vector< PatchIndex > >::iterator itt = m_hashFinalizedPatch.find( chunk->m_iIndex );
if ( itt != m_hashFinalizedPatch.end() ) {
std::vector< PatchIndex > & temp = itt->second;
for ( int k = 0; k < ( int )temp.size(); k++ ) {
stdext::hash_map< PatchIndex, CBPWriter >::iterator it = m_hashWriter.find( temp[ k ] );
it->second.CloseFile();
}
}
}
void CConvertGrid::FinWrite()
{
m_cReader.CloseFile();
}
//////////////////////////////////////////////////////////////////////////
// auxiliary functions
//////////////////////////////////////////////////////////////////////////
bool CConvertGrid::CheckPoint( PatchPointData & point )
{
CParamManager * manager = CParamManager::GetParamManager();
if ( manager->m_bClip == false ||
( ( point.v[0] >= manager->m_dbClip[0][0] )
&& ( point.v[0] <= manager->m_dbClip[0][1] )
&& ( point.v[1] >= manager->m_dbClip[1][0] )
&& ( point.v[1] <= manager->m_dbClip[1][1] ) ) )
{
if ( point.type == PT_Building ) {
return true;
}
}
return false;
}
double CConvertGrid::MinGroundZ( CConvertChunk * chunk )
{
double min_z = 1e300;
for ( int i = 0; i < ( int )( chunk->m_vecPatchPointData.size() ); i++ ) {
PatchPointData & point = chunk->m_vecPatchPointData[ i ];
if ( point.type == PT_Ground && point.v[ 2 ] < min_z ) {
min_z = point.v[ 2 ];
}
}
return min_z;
}
| 23.378549 | 134 | 0.622048 | liuxinren |
6342a63a5a2c6a869687ad8acb3085a1f4174e46 | 9,579 | cpp | C++ | tests/unittest/test_hetercallbacklist_basic.cpp | digital-stage/eventpp | a0978f91f9d74a5943ed668b3fe15d64b0675b5c | [
"Apache-2.0"
] | 685 | 2018-05-13T03:59:19.000Z | 2022-03-31T22:43:43.000Z | tests/unittest/test_hetercallbacklist_basic.cpp | digital-stage/eventpp | a0978f91f9d74a5943ed668b3fe15d64b0675b5c | [
"Apache-2.0"
] | 32 | 2018-06-01T03:15:13.000Z | 2022-01-18T09:23:06.000Z | tests/unittest/test_hetercallbacklist_basic.cpp | digital-stage/eventpp | a0978f91f9d74a5943ed668b3fe15d64b0675b5c | [
"Apache-2.0"
] | 128 | 2018-05-13T06:41:58.000Z | 2022-03-30T16:58:10.000Z | // eventpp library
// Copyright (C) 2018 Wang Qi (wqking)
// Github: https://github.com/wqking/eventpp
// 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 "test.h"
#include "eventpp/hetercallbacklist.h"
#include <vector>
TEST_CASE("HeterCallbackList, empty")
{
using CL = eventpp::HeterCallbackList<eventpp::HeterTuple<void (), void (int)> >;
SECTION("empty") {
CL callbackList;
REQUIRE(callbackList.empty());
}
SECTION("append") {
CL callbackList;
callbackList.append([](){});
REQUIRE(! callbackList.empty());
}
SECTION("prepend") {
CL callbackList;
callbackList.prepend([](int){});
REQUIRE(! callbackList.empty());
}
SECTION("remove") {
CL callbackList;
auto handle = callbackList.append([](){});
REQUIRE(! callbackList.empty());
callbackList.remove(handle);
REQUIRE(callbackList.empty());
}
}
TEST_CASE("HeterCallbackList, append")
{
using CL = eventpp::HeterCallbackList<eventpp::HeterTuple<void (), void (int)> >;
CL callbackList;
std::vector<int> orderList(5);
int order;
callbackList.append([&orderList, &order]() {
orderList[order++] = 1;
});
callbackList.append([&orderList, &order]() {
orderList[order++] = 2;
});
callbackList.append([&orderList, &order](int) {
orderList[order++] = 3;
});
callbackList.append([&orderList, &order](int) {
orderList[order++] = 4;
});
callbackList.append([&orderList, &order](int) {
orderList[order++] = 5;
});
REQUIRE(orderList == std::vector<int>{ 0, 0, 0, 0, 0 });
order = 0;
callbackList(3);
REQUIRE(orderList == std::vector<int>{ 3, 4, 5, 0, 0 });
callbackList();
REQUIRE(orderList == std::vector<int>{ 3, 4, 5, 1, 2 });
}
TEST_CASE("HeterCallbackList, prepend")
{
using CL = eventpp::HeterCallbackList<eventpp::HeterTuple<void (), void (int)> >;
CL callbackList;
std::vector<int> orderList(5);
int order;
callbackList.prepend([&orderList, &order]() {
orderList[order++] = 1;
});
callbackList.prepend([&orderList, &order]() {
orderList[order++] = 2;
});
callbackList.prepend([&orderList, &order](int) {
orderList[order++] = 3;
});
callbackList.prepend([&orderList, &order](int) {
orderList[order++] = 4;
});
callbackList.prepend([&orderList, &order](int) {
orderList[order++] = 5;
});
REQUIRE(orderList == std::vector<int>{ 0, 0, 0, 0, 0 });
order = 0;
callbackList(3);
REQUIRE(orderList == std::vector<int>{ 5, 4, 3, 0, 0 });
callbackList();
REQUIRE(orderList == std::vector<int>{ 5, 4, 3, 2, 1 });
}
TEST_CASE("HeterCallbackList, insert")
{
using CL = eventpp::HeterCallbackList<eventpp::HeterTuple<void (), void (int)> >;
CL callbackList;
std::vector<int> orderList(5);
int order;
auto h1 = callbackList.append([&orderList, &order]() {
orderList[order++] = 1;
});
callbackList.insert([&orderList, &order]() {
orderList[order++] = 2;
}, h1);
auto h2 = callbackList.append([&orderList, &order](int) {
orderList[order++] = 3;
});
callbackList.insert([&orderList, &order](int) {
orderList[order++] = 4;
}, h2);
// Increase h2.index to trigger the check `if(before.index != PrototypeInfo::index)` in HeterCallbackList::insert
// This works as if the callback is appended rather than inserted.
++h2.index;
callbackList.insert([&orderList, &order](int) {
orderList[order++] = 5;
}, h2);
REQUIRE(orderList == std::vector<int>{ 0, 0, 0, 0, 0 });
order = 0;
callbackList(3);
REQUIRE(orderList == std::vector<int>{ 4, 3, 5, 0, 0 });
callbackList();
REQUIRE(orderList == std::vector<int>{ 4, 3, 5, 2, 1 });
}
TEST_CASE("HeterCallbackList, remove")
{
using CL = eventpp::HeterCallbackList<eventpp::HeterTuple<void (), void (int)> >;
CL callbackList;
std::vector<int> dataList(5);
auto h1 = callbackList.append([&dataList]() {
++dataList[0];
});
auto h2 = callbackList.append([&dataList]() {
++dataList[1];
});
auto h3 = callbackList.append([&dataList](int) {
++dataList[2];
});
auto h4 = callbackList.append([&dataList](int) {
++dataList[3];
});
auto h5 = callbackList.append([&dataList](int) {
++dataList[4];
});
REQUIRE(dataList == std::vector<int>{ 0, 0, 0, 0, 0 });
// Remove non-exist handle
REQUIRE(! callbackList.remove(decltype(h1)()));
callbackList(3);
REQUIRE(dataList == std::vector<int>{ 0, 0, 1, 1, 1 });
callbackList();
REQUIRE(dataList == std::vector<int>{ 1, 1, 1, 1, 1 });
REQUIRE(callbackList.remove(h2));
callbackList(3);
callbackList();
REQUIRE(dataList == std::vector<int>{ 2, 1, 2, 2, 2 });
// double remove, no effect
REQUIRE(! callbackList.remove(h2));
callbackList(3);
callbackList();
REQUIRE(dataList == std::vector<int>{ 3, 1, 3, 3, 3 });
REQUIRE(callbackList.remove(h3));
callbackList(3);
callbackList();
REQUIRE(dataList == std::vector<int>{ 4, 1, 3, 4, 4 });
REQUIRE(callbackList.remove(h5));
callbackList(3);
callbackList();
REQUIRE(dataList == std::vector<int>{ 5, 1, 3, 5, 4 });
REQUIRE(callbackList.remove(h1));
callbackList(3);
callbackList();
REQUIRE(dataList == std::vector<int>{ 5, 1, 3, 6, 4 });
REQUIRE(callbackList.remove(h4));
callbackList(3);
callbackList();
REQUIRE(dataList == std::vector<int>{ 5, 1, 3, 6, 4 });
}
TEST_CASE("HeterCallbackList, forEach")
{
using CL = eventpp::HeterCallbackList<eventpp::HeterTuple<int (), int(int)> >;
CL callbackList;
callbackList.append([]() { return 1; });
callbackList.append([]() { return 2; });
callbackList.append([]() { return 3; });
callbackList.append([](int n) { return n + 5 + 0; });
callbackList.append([](int n) { return n + 5 + 1; });
callbackList.append([](int n) { return n + 5 + 2; });
int i = 1;
callbackList.forEach<int ()>([&i](auto callback) {
REQUIRE(callback() == i);
++i;
});
i = 0;
callbackList.forEach<int (int)>([&i](const std::function<int (int)> & callback) {
REQUIRE(callback(3) == 8 + i);
++i;
});
}
TEST_CASE("HeterCallbackList, forEachIf")
{
using CL = eventpp::HeterCallbackList<eventpp::HeterTuple<void (), void(int)> >;
CL callbackList;
std::vector<int> dataListNoArg(3);
std::vector<int> dataListWithArg(3);
callbackList.append([&dataListNoArg]() {
dataListNoArg[0] += 1;
});
callbackList.append([&dataListNoArg]() {
dataListNoArg[1] += 2;
});
callbackList.append([&dataListNoArg]() {
dataListNoArg[2] += 3;
});
callbackList.append([&dataListWithArg](int n) {
dataListWithArg[0] += n;
});
callbackList.append([&dataListWithArg](int n) {
dataListWithArg[1] += n * 2;
});
callbackList.append([&dataListWithArg](int n) {
dataListWithArg[2] += n * 3;
});
REQUIRE(dataListNoArg == std::vector<int>{ 0, 0, 0 });
REQUIRE(dataListWithArg == std::vector<int>{ 0, 0, 0 });
int i = 0;
bool result = callbackList.forEachIf<void ()>([&i](const std::function<void ()> & callback) -> bool {
callback();
++i;
return i != 2;
});
REQUIRE(! result);
REQUIRE(dataListNoArg == std::vector<int>{ 1, 2, 0 });
REQUIRE(dataListWithArg == std::vector<int>{ 0, 0, 0 });
i = 0;
result = callbackList.forEachIf<void (int)>([&i](const std::function<void (int)> & callback) -> bool {
callback(3);
++i;
return i != 1;
});
REQUIRE(! result);
REQUIRE(dataListNoArg == std::vector<int>{ 1, 2, 0 });
REQUIRE(dataListWithArg == std::vector<int>{ 3, 0, 0 });
}
TEST_CASE("HeterCallbackList, invoke")
{
using CL = eventpp::HeterCallbackList<eventpp::HeterTuple<void (), void(int)> >;
CL callbackList;
std::vector<int> dataListNoArg(3);
std::vector<int> dataListWithArg(3);
callbackList.append([&dataListNoArg]() {
dataListNoArg[0] += 1;
});
callbackList.append([&dataListNoArg]() {
dataListNoArg[1] += 2;
});
callbackList.append([&dataListNoArg]() {
dataListNoArg[2] += 3;
});
callbackList.append([&dataListWithArg](int n) {
dataListWithArg[0] += n;
});
callbackList.append([&dataListWithArg](int n) {
dataListWithArg[1] += n * 2;
});
callbackList.append([&dataListWithArg](int n) {
dataListWithArg[2] += n * 3;
});
REQUIRE(dataListNoArg == std::vector<int>{ 0, 0, 0 });
REQUIRE(dataListWithArg == std::vector<int>{ 0, 0, 0 });
callbackList();
REQUIRE(dataListNoArg == std::vector<int>{ 1, 2, 3 });
REQUIRE(dataListWithArg == std::vector<int>{ 0, 0, 0 });
callbackList();
REQUIRE(dataListNoArg == std::vector<int>{ 2, 4, 6 });
REQUIRE(dataListWithArg == std::vector<int>{ 0, 0, 0 });
callbackList(1);
REQUIRE(dataListNoArg == std::vector<int>{ 2, 4, 6 });
REQUIRE(dataListWithArg == std::vector<int>{ 1, 2, 3 });
callbackList(2);
REQUIRE(dataListNoArg == std::vector<int>{ 2, 4, 6 });
REQUIRE(dataListWithArg == std::vector<int>{ 3, 6, 9 });
}
TEST_CASE("HeterCallbackList, prototype convert")
{
struct MyClass
{
MyClass(int) {}
};
using CL = eventpp::HeterCallbackList<eventpp::HeterTuple<void (int)> >;
CL callbackList;
std::vector<int> dataList(2);
callbackList.append([&dataList](int) {
++dataList[0];
});
callbackList.append([&dataList](const MyClass &) {
++dataList[1];
});
REQUIRE(dataList == std::vector<int>{ 0, 0 });
callbackList((int)5);
REQUIRE(dataList == std::vector<int>{ 1, 1 });
callbackList((char)5);
REQUIRE(dataList == std::vector<int>{ 2, 2 });
}
| 25.408488 | 114 | 0.649024 | digital-stage |
6345730d11666a9992159533a2677a96ed7e8752 | 347 | cpp | C++ | TrainingWithBook/JumpingBinarySearch.cpp | andzh1/Competitive-programming | babb9494e03fe0feb2130e50887996d0ffc92c4e | [
"MIT"
] | null | null | null | TrainingWithBook/JumpingBinarySearch.cpp | andzh1/Competitive-programming | babb9494e03fe0feb2130e50887996d0ffc92c4e | [
"MIT"
] | null | null | null | TrainingWithBook/JumpingBinarySearch.cpp | andzh1/Competitive-programming | babb9494e03fe0feb2130e50887996d0ffc92c4e | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define loop(a,b) for(int i = a; i < b; i++)
int main(){
int n = 5, wanted = 5;
int array[] = {1,2,3,4,5};
int k = 0;
for(int b = n/2; b >= 1; b /= 2){
while(k + b < n && array[k+b] <= wanted) k += b;
}
if(array[k] == wanted){
//we got wanted value
}
}
| 20.411765 | 56 | 0.458213 | andzh1 |
63489ad56bf0b0d5a22c5bbb6c18274404087dd7 | 2,306 | cpp | C++ | STM32F1/libraries/MakeArduino_Examples/examples/MakeArduino_F103Rx_UsbCardReader/app_usb_mass.cpp | iamdev/MakeArduino_STM32 | 3dba2f132082d63cdbb318ba0fcc1df6d382227a | [
"Unlicense"
] | null | null | null | STM32F1/libraries/MakeArduino_Examples/examples/MakeArduino_F103Rx_UsbCardReader/app_usb_mass.cpp | iamdev/MakeArduino_STM32 | 3dba2f132082d63cdbb318ba0fcc1df6d382227a | [
"Unlicense"
] | null | null | null | STM32F1/libraries/MakeArduino_Examples/examples/MakeArduino_F103Rx_UsbCardReader/app_usb_mass.cpp | iamdev/MakeArduino_STM32 | 3dba2f132082d63cdbb318ba0fcc1df6d382227a | [
"Unlicense"
] | null | null | null | #include "app_usb_mass.h"
#include "app_sdfat.h"
#define DEBUG_READ_WRITE 0
bool sd_write_buffer(uint32_t memoryOffset, const uint8_t *writebuff, uint16_t transferLength)
{
digitalWrite(LED_BUILTIN,LOW);
#if SERIAL_DEBUG >0 && DEBUG_SD_INFO > 0 && DEBUG_READ_WRITE > 0
Serial.print("Write [0x");
Serial.print(memoryOffset,HEX);
Serial.print(":");
Serial.print(transferLength,DEC);
Serial.print("]...");
#endif
bool ret = sd.card()->writeBlocks(memoryOffset/512, writebuff, transferLength/512);
#if SERIAL_DEBUG >0 && DEBUG_SD_INFO > 0 && DEBUG_READ_WRITE > 0
if(ret)
Serial.println("Pass");
else
Serial.println("Fail");
#endif
digitalWrite(LED_BUILTIN,HIGH);
return ret;
}
bool sd_read_buffer(uint32_t memoryOffset, uint8_t *readbuff, uint16_t transferLength) {
digitalWrite(LED_BUILTIN,LOW);
int c = 0;
#if SERIAL_DEBUG >0 && DEBUG_SD_INFO > 0 && DEBUG_READ_WRITE > 0
Serial.print("Read [0x");
Serial.print(memoryOffset,HEX);
Serial.print(":");
Serial.print(transferLength,DEC);
Serial.print("]...");
#endif
bool ret= sd.card()->readBlocks(memoryOffset/512, readbuff, transferLength/512);
#if SERIAL_DEBUG >0 && DEBUG_SD_INFO > 0 && DEBUG_READ_WRITE > 0
if(ret)
Serial.println("Pass");
else
Serial.println("Fail");
c = 0;
CompositeSerial.print("Read [0x");
CompositeSerial.print(memoryOffset,HEX);
CompositeSerial.print(":");
CompositeSerial.print(transferLength,DEC);
CompositeSerial.println("]");
while(c<transferLength){
for(int i=0;i<32;i++){
uint8_t v = readbuff[c++];
if(v<0x10)CompositeSerial.print("0");
CompositeSerial.print(v,HEX);
CompositeSerial.print(" ");
}
CompositeSerial.println();
}
#endif
digitalWrite(LED_BUILTIN,HIGH);
return ret;
}
void init_reader() {
Serial.println(F("Initialize USB Mass Storage"));
cardSize = sd.card()->cardSize();
USBComposite.setProductId(PRODUCT_ID);
MassStorage.setDrive(0, cardSize*512, sd_read_buffer, sd_write_buffer);
MassStorage.registerComponent();
CompositeSerial.registerComponent();
USBComposite.begin();
digitalWrite(USB_DESC_PIN,HIGH);
usb_mass_enabled=true;
}
void usb_mass_loop(){
if (!usb_mass_enabled) {
init_reader();
}
else {
MassStorage.loop();
}
}
| 26.813953 | 95 | 0.691674 | iamdev |
634c5a28e779a93d5770eaecfa8fbc46d2f4cad5 | 3,852 | cpp | C++ | src/skylines_engine/queries/algorithms/single_thread_sorting.cpp | gggprojects/skylines | 1b0d204f1fbb8e24af026723ba9887988798c974 | [
"MIT"
] | null | null | null | src/skylines_engine/queries/algorithms/single_thread_sorting.cpp | gggprojects/skylines | 1b0d204f1fbb8e24af026723ba9887988798c974 | [
"MIT"
] | null | null | null | src/skylines_engine/queries/algorithms/single_thread_sorting.cpp | gggprojects/skylines | 1b0d204f1fbb8e24af026723ba9887988798c974 | [
"MIT"
] | 1 | 2018-08-31T15:53:36.000Z | 2018-08-31T15:53:36.000Z | #include <iostream>
#include "queries/algorithms/single_thread_sorting.hpp"
#include "common/time.hpp"
namespace sl { namespace queries { namespace algorithms {
data::Statistics SingleThreadSorting::Run(NonConstData<data::WeightedPoint> *output, DistanceType distance_type) {
if (!Init(output)) return data::Statistics();
return Compute(output, distance_type);
}
template<class Comparator, class Sorter>
data::Statistics SingleThreadSorting::ComputeSkylines(
Comparator comparator_function,
Sorter sorter_function,
std::vector<data::WeightedPoint> *skylines) {
data::Statistics stats_results;
const sl::queries::data::Point *input_q = input_q_.GetPoints().data();
const int q_size = static_cast<int>(input_q_.GetPoints().size());
NonConstData<data::WeightedPoint> sorted_input;
//copy P
sorted_input = input_p_;
//sorting depending on function
std::sort(sorted_input.Points().begin(), sorted_input.Points().end(), sorter_function);
//the first element is skyline
skylines->emplace_back(sorted_input.GetPoints()[0]);
std::vector<data::WeightedPoint>::const_iterator first_element = sorted_input.GetPoints().cbegin();
std::vector<data::WeightedPoint>::const_iterator last_element = sorted_input.GetPoints().cend();
std::vector<data::WeightedPoint>::const_iterator skyline_candidate;
for (skyline_candidate = first_element + 1;
skyline_candidate != last_element;
++skyline_candidate) {
std::vector<data::WeightedPoint>::const_iterator skyline_element = skylines->cbegin();
bool is_skyline = true;
while (is_skyline && skyline_element != skylines->cend()) {
if (IsDominated(*skyline_candidate, *skyline_element, input_q, q_size, &stats_results.num_comparisions_, comparator_function)) {
is_skyline = false;
}
skyline_element++;
}
if (is_skyline) {
skylines->emplace_back(*skyline_candidate);
}
}
return stats_results;
}
template<class Comparator, class Sorter>
data::Statistics SingleThreadSorting::_Compute(Comparator comparator_function, Sorter sorter_function, NonConstData<data::WeightedPoint> *output) {
std::vector<data::WeightedPoint> skylines;
data::Statistics stats_results = ComputeSkylines(comparator_function, sorter_function, &skylines);
ComputeTopK(skylines, output);
stats_results.output_size_ = output->GetPoints().size();
return stats_results;
}
data::Statistics SingleThreadSorting::Compute(NonConstData<data::WeightedPoint> *output, DistanceType distance_type) {
//std::cout << "Computing STS\n";
const data::Point &first_q = input_q_.GetPoints()[0];
switch (distance_type) {
case sl::queries::algorithms::DistanceType::Nearest:
return _Compute(
[](const float a, const float b) -> bool { return a <= b; },
[&first_q](const data::WeightedPoint &a, const data::WeightedPoint &b) -> bool { return a.SquaredDistance(first_q) < b.SquaredDistance(first_q); },
output);
break;
case sl::queries::algorithms::DistanceType::Furthest:
return _Compute(
[](const float a, const float b) -> bool { return a >= b; },
[&first_q](const data::WeightedPoint &a, const data::WeightedPoint &b) -> bool { return a.SquaredDistance(first_q) > b.SquaredDistance(first_q); },
output);
break;
default:
break;
}
return data::Statistics();
}
}}}
| 43.280899 | 167 | 0.631101 | gggprojects |
634ff123129d4b1a5fc42ca350d23c31bf9127b1 | 7,922 | cpp | C++ | cocos2d-x-2.2/extensions/CocoStudio/ActionTimeline/CCActionTimeline.cpp | centrallydecentralized/ufo | 29e8f9ce4ce92635ed22f8a051c917cfe6e0313d | [
"BSD-3-Clause"
] | 58 | 2015-01-05T04:40:48.000Z | 2021-12-17T06:01:28.000Z | cocos2d-x-2.2/extensions/CocoStudio/ActionTimeline/CCActionTimeline.cpp | centrallydecentralized/ufo | 29e8f9ce4ce92635ed22f8a051c917cfe6e0313d | [
"BSD-3-Clause"
] | 4 | 2021-04-29T06:20:51.000Z | 2021-04-29T15:20:13.000Z | cocos2d-x-2.2/extensions/CocoStudio/ActionTimeline/CCActionTimeline.cpp | centrallydecentralized/ufo | 29e8f9ce4ce92635ed22f8a051c917cfe6e0313d | [
"BSD-3-Clause"
] | 46 | 2015-01-03T06:20:54.000Z | 2020-04-18T13:32:52.000Z | /****************************************************************************
Copyright (c) 2013 cocos2d-x.org
http://www.cocos2d-x.org
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 "CCActionTimeline.h"
#include "CCNodeReader.h"
using namespace cocos2d;
NS_TIMELINE_BEGIN
ActionTimeline* ActionTimeline::create()
{
ActionTimeline* object = new ActionTimeline();
if (object && object->init())
{
object->autorelease();
return object;
}
CC_SAFE_DELETE(object);
return NULL;
}
ActionTimeline::ActionTimeline()
: _timelineList(NULL)
, _duration(0)
, _time(0)
, _timeSpeed(1)
, _frameInternal(1/60.0f)
, _playing(false)
, _currentFrame(0)
, _startFrame(0)
, _endFrame(0)
, _frameEventCallFunc(NULL)
, _frameEventTarget(NULL)
, _scriptObjectDict(NULL)
{
}
ActionTimeline::~ActionTimeline()
{
std::map<int, cocos2d::CCArray*>::const_iterator i = _timelineMap.begin();
for (; i != _timelineMap.end(); i++)
{
CCArray* timelines = i->second;
CC_SAFE_DELETE(timelines);
}
CC_SAFE_DELETE(_timelineList);
CC_SAFE_RELEASE_NULL(_scriptObjectDict);
}
bool ActionTimeline::init()
{
_timelineList = new cocos2d::CCArray();
_timelineList->init();
return true;
}
void ActionTimeline::gotoFrameAndPlay(int startIndex)
{
gotoFrameAndPlay(startIndex, true);
}
void ActionTimeline::gotoFrameAndPlay(int startIndex, bool loop)
{
gotoFrameAndPlay(startIndex, _duration, loop);
}
void ActionTimeline::gotoFrameAndPlay(int startIndex, int endIndex, bool loop)
{
gotoFrameAndPlay(startIndex, endIndex, startIndex, loop);
}
void ActionTimeline::gotoFrameAndPlay(int startIndex, int endIndex, int currentFrameIndex, bool loop)
{
_startFrame = startIndex;
_endFrame = endIndex;
_currentFrame = currentFrameIndex;
_loop = loop;
_time = _currentFrame*_frameInternal;
resume();
gotoFrame(_currentFrame);
}
void ActionTimeline::gotoFrameAndPause(int startIndex)
{
_startFrame = _currentFrame = startIndex;
_time = _currentFrame * _frameInternal;
pause();
gotoFrame(_currentFrame);
}
void ActionTimeline::pause()
{
_playing = false;
}
void ActionTimeline::resume()
{
_playing = true;
}
bool ActionTimeline::isPlaying() const
{
return _playing;
}
void ActionTimeline::setCurrentFrame(int frameIndex)
{
if (frameIndex >= _startFrame && frameIndex >= _endFrame)
{
_currentFrame = frameIndex;
_time = _currentFrame*_frameInternal;
}
else
{
CCLOG("frame index is not between start frame and end frame");
}
}
ActionTimeline* ActionTimeline::clone() const
{
ActionTimeline* newAction = ActionTimeline::create();
newAction->setDuration(_duration);
newAction->setTimeSpeed(_timeSpeed);
std::map<int, cocos2d::CCArray*>::const_iterator i = _timelineMap.begin();
for (; i != _timelineMap.end(); i++)
{
CCObject* object = NULL;
CCARRAY_FOREACH(i->second, object)
{
Timeline* timeline = static_cast<Timeline*>(object);
Timeline* newTimeline = timeline->clone();
newAction->addTimeline(newTimeline);
}
}
return newAction;
}
void ActionTimeline::step(float delta)
{
if (!_playing || _timelineMap.size() == 0 || _duration == 0)
{
return;
}
_time += delta * _timeSpeed;
_currentFrame = (int)(_time / _frameInternal);
stepToFrame(_currentFrame);
if(_time > _endFrame * _frameInternal)
{
_playing = _loop;
if(!_playing)
_time = _endFrame * _frameInternal;
else
_time = _startFrame * _frameInternal;
}
}
void ActionTimeline::foreachNodeDescendant(CCNode* parent)
{
TimelineActionData* data = dynamic_cast<TimelineActionData*>(parent->getUserObject());
CCObject* object = NULL;
if(data)
{
int actionTag = data->getActionTag();
if(_timelineMap.find(actionTag) != _timelineMap.end())
{
CCArray* timelines = this->_timelineMap[actionTag];
CCARRAY_FOREACH (timelines, object)
{
Timeline* timeline = static_cast<Timeline*>(object);
timeline->setNode(parent);
}
}
}
CCArray* children = parent->getChildren();
CCARRAY_FOREACH (children, object)
{
CCNode* child = static_cast<CCNode*>(object);
foreachNodeDescendant(child);
}
}
void ActionTimeline::startWithTarget(CCNode *target)
{
CCAction::startWithTarget(target);
foreachNodeDescendant(target);
}
void ActionTimeline::addTimeline(Timeline* timeline)
{
int tag = timeline->getActionTag();
if (_timelineMap.find(tag) == _timelineMap.end())
{
CCArray* timelines = new CCArray();
timelines->init();
_timelineMap[tag] = timelines;
}
if (!_timelineMap[tag]->containsObject(timeline))
{
_timelineList->addObject(timeline);
_timelineMap[tag]->addObject(timeline);
timeline->setActionTimeline(this);
}
}
void ActionTimeline::removeTimeline(Timeline* timeline)
{
int tag = timeline->getActionTag();
if (_timelineMap.find(tag) != _timelineMap.end())
{
if(_timelineMap[tag]->containsObject(timeline))
{
_timelineMap[tag]->removeObject(timeline);
_timelineList->removeObject(timeline);
timeline->setActionTimeline(NULL);
}
}
}
void ActionTimeline::setFrameEventCallFunc (CCObject *target, SEL_TimelineFrameEventCallFunc callFunc)
{
_frameEventTarget = target;
_frameEventCallFunc = callFunc;
}
void ActionTimeline::clearFrameEventCallFunc()
{
_frameEventTarget = NULL;
_frameEventCallFunc = NULL;
}
void ActionTimeline::emitFrameEvent(Frame* frame)
{
if (_frameEventTarget != NULL && _frameEventCallFunc != NULL)
{
(_frameEventTarget->*_frameEventCallFunc)(frame);
}
}
void ActionTimeline::gotoFrame(int frameIndex)
{
int size = _timelineList->count();
Timeline** timelines = (Timeline**)_timelineList->data->arr;
for(int i = 0; i<size; i++)
{
timelines[i]->gotoFrame(frameIndex);
}
}
void ActionTimeline::stepToFrame(int frameIndex)
{
int size = _timelineList->count();
Timeline** timelines = (Timeline**)_timelineList->data->arr;
for(int i = 0; i<size; i++)
{
timelines[i]->stepToFrame(frameIndex);
}
}
void ActionTimeline::setScriptObjectDict(cocos2d::CCDictionary *scriptObjectDict)
{
CC_SAFE_RETAIN(scriptObjectDict);
CC_SAFE_RELEASE(_scriptObjectDict);
_scriptObjectDict = scriptObjectDict;
}
cocos2d::CCDictionary* ActionTimeline::getScriptObjectDict() const
{
return _scriptObjectDict;
}
NS_TIMELINE_END
| 25.554839 | 103 | 0.662964 | centrallydecentralized |
635a2d20960c28bd98e165dbecc1334fa1439da0 | 3,102 | cpp | C++ | server/src/server.cpp | fruityloops1/smo-duktape | b840048b9f682eb5d46c3d48c3fa870a7509e55c | [
"MIT"
] | 2 | 2021-12-03T17:41:19.000Z | 2022-02-26T05:57:11.000Z | server/src/server.cpp | fruityloops1/smo-duktape | b840048b9f682eb5d46c3d48c3fa870a7509e55c | [
"MIT"
] | null | null | null | server/src/server.cpp | fruityloops1/smo-duktape | b840048b9f682eb5d46c3d48c3fa870a7509e55c | [
"MIT"
] | null | null | null | #include <ratio>
#include <server.h>
#include <packet.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <thread>
#include <iostream>
#include <fstream>
#define MAX_PACKET_SIZE 0x400
#define IN_PACKET(TYPE) case smo::InPacketType::TYPE: {\
InPacket##TYPE p;\
p.parse(data + 1, length - 1);\
p.on(*this, *parent);\
break;}
namespace smo
{
void smo::Client::connect()
{
struct in_addr ip;
ip.s_addr = uid;
std::cout << "Client connected from " << inet_ntoa(ip) << std::endl;
}
void smo::Client::handlePacket(Server* parent, u8* data, s32 length)
{
if (length < 1) return;
switch ((InPacketType) data[0])
{
case smo::InPacketType::DummyInit:
{
break;
}
case smo::InPacketType::Init:
{
connect();
break;
}
IN_PACKET(Log)
default: break;
}
}
void smo::Client::sendPacket(Server* parent, smo::OutPacket& packet, smo::OutPacketType type)
{
u32 len = packet.calcLen();
u8* packetData = new u8[len + 1];
packet.construct(packetData + 1);
packetData[0] = (u8) type;
sendto(parent->getSocket(), packetData, len + 1, 0, (struct sockaddr*) &client, sizeof(client));
delete[] packetData;
}
bool smo::Server::disconnect(u64 uid)
{
if (clients.find(uid) != clients.end())
{
clients.erase(uid);
return true;
} else return false;
}
u8 smo::Server::start(u16 port)
{
struct sockaddr_in addr, cli;
socketfd = socket(AF_INET, SOCK_DGRAM, 0);
if (socketfd == -1) return 1;
setsockopt(socketfd, SOL_SOCKET, SO_REUSEADDR, nullptr, sizeof(int));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(port);
int rval = bind(socketfd, (struct sockaddr*) &addr, sizeof(addr));
if (rval != 0) return 2;
listen(socketfd, 2);
u8 buf[12288];
s32 size = 0;
std::thread loop(&smo::Server::loopThread, this);
loop.detach();
while (true)
{
s32 length = sizeof(cli);
struct sockaddr_in client;
socklen_t addrSize;
if ((size = recvfrom(socketfd, buf, sizeof(buf), 0, (struct sockaddr *) &client, &addrSize)) < 0) continue;
u64 uid = client.sin_addr.s_addr + client.sin_port;
Client& c = clients[uid];
c.uid = uid;
c.addr = client.sin_addr.s_addr;
c.client = client;
c.handlePacket(this, buf, size);
}
return 0;
}
void smo::Server::loopThread()
{
using namespace std::chrono_literals;
while (true)
{
std::this_thread::sleep_for(10000ms);
}
}
s32 smo::Server::getSocket() {return socketfd;}
} | 25.016129 | 119 | 0.527724 | fruityloops1 |
635f1c293fa074f158292cee2f3ec52e8ba7c145 | 1,707 | cpp | C++ | src/Compiler/Parser/ParseHelper.cpp | feral-lang/feral | 1ce8eb72eec7c8a5ac19d3767e907b86387e29e0 | [
"MIT"
] | 131 | 2020-03-19T15:22:37.000Z | 2021-12-19T02:37:01.000Z | src/Compiler/Parser/ParseHelper.cpp | Electrux/feral | 1ce8eb72eec7c8a5ac19d3767e907b86387e29e0 | [
"BSD-3-Clause"
] | 14 | 2020-04-06T05:50:15.000Z | 2021-06-26T06:19:04.000Z | src/Compiler/Parser/ParseHelper.cpp | Electrux/feral | 1ce8eb72eec7c8a5ac19d3767e907b86387e29e0 | [
"BSD-3-Clause"
] | 20 | 2020-04-06T07:28:30.000Z | 2021-09-05T14:46:25.000Z | /*
MIT License
Copyright (c) 2020 Feral Language repositories
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.
*/
#include "Compiler/Parser/ParseHelper.hpp"
#include <cstdarg>
phelper_t::phelper_t(lex::toks_t &toks, const size_t begin)
: m_toks(toks), m_invalid(0, TOK_INVALID, ""),
m_eof(toks.size() > 0 ? toks.back().pos : 0, TOK_EOF, ""), m_idx(begin)
{}
const lex::tok_t *phelper_t::peak(const int offset) const
{
if(offset < 0 && m_idx < (-offset)) return &m_eof;
if(m_idx + offset >= m_toks.size()) return &m_eof;
return &m_toks[m_idx + offset];
}
TokType phelper_t::peakt(const int offset) const
{
if(offset < 0 && m_idx < (-offset)) return m_eof.type;
if(m_idx + offset >= m_toks.size()) return m_eof.type;
return m_toks[m_idx + offset].type;
}
const lex::tok_t *phelper_t::next()
{
++m_idx;
if(m_idx >= m_toks.size()) return &m_eof;
return &m_toks[m_idx];
}
TokType phelper_t::nextt()
{
++m_idx;
if(m_idx >= m_toks.size()) return m_eof.type;
return m_toks[m_idx].type;
}
const lex::tok_t *phelper_t::prev()
{
if(m_idx == 0) return &m_invalid;
--m_idx;
return &m_toks[m_idx];
}
TokType phelper_t::prevt()
{
if(m_idx == 0) return m_invalid.type;
--m_idx;
return m_toks[m_idx].type;
}
const lex::tok_t *phelper_t::at(const size_t &idx) const
{
if(idx >= m_toks.size()) return &m_invalid;
return &m_toks[idx];
} | 24.73913 | 78 | 0.70123 | feral-lang |
6360c83106eccf789b6fa68dbb1a18def5e4ced4 | 6,030 | hpp | C++ | Spark/Buffer.hpp | MickAlmighty/SparkRenderer | 0e30e342c7cf4003da54e9ce191fead647a868eb | [
"MIT"
] | 1 | 2022-02-15T19:50:01.000Z | 2022-02-15T19:50:01.000Z | Spark/Buffer.hpp | MickAlmighty/SparkRenderer | 0e30e342c7cf4003da54e9ce191fead647a868eb | [
"MIT"
] | null | null | null | Spark/Buffer.hpp | MickAlmighty/SparkRenderer | 0e30e342c7cf4003da54e9ce191fead647a868eb | [
"MIT"
] | null | null | null | #pragma once
#include <algorithm>
#include <optional>
#include <set>
#include <vector>
#include <glad/glad.h>
template<GLenum BUFFER_TYPE>
class Buffer
{
public:
GLuint ID{0};
GLint binding{-1};
GLsizei size{0};
Buffer(std::size_t sizeInBytes = 0, GLenum usage = GL_DYNAMIC_DRAW);
Buffer(const Buffer& buffer) = delete;
Buffer(Buffer&& buffer) = delete;
Buffer& operator=(const Buffer& buffer) = delete;
Buffer& operator=(Buffer&& buffer) = delete;
~Buffer();
void bind() const;
static void unbind();
template<typename T>
void updateData(const std::vector<T>& buffer);
template<typename T>
void updateSubData(size_t offsetFromBeginning, const std::vector<T>& buffer);
template<typename T, size_t Size>
void updateData(const std::array<T, Size>& buffer);
template<typename T, size_t Size>
void updateSubData(size_t offsetFromBeginning, const std::array<T, Size>& buffer);
void resizeBuffer(size_t sizeInBytes);
// this method sets value 0 for all bytes in the buffer
void clearData();
private:
void genBuffer(size_t sizeInBytes = 0);
void cleanup();
void getBinding();
void freeBinding();
static inline std::set<uint32_t> bindings{};
const GLenum bufferUsage;
};
template<GLenum BUFFER_TYPE>
Buffer<BUFFER_TYPE>::Buffer(std::size_t sizeInBytes, GLenum usage) : bufferUsage(usage)
{
genBuffer(sizeInBytes);
}
template<GLenum BUFFER_TYPE>
Buffer<BUFFER_TYPE>::~Buffer()
{
if(ID != 0)
{
cleanup();
}
}
template<GLenum BUFFER_TYPE>
void Buffer<BUFFER_TYPE>::bind() const
{
glBindBuffer(BUFFER_TYPE, ID);
}
template<GLenum BUFFER_TYPE>
void Buffer<BUFFER_TYPE>::unbind()
{
glBindBuffer(BUFFER_TYPE, 0);
}
template<GLenum BUFFER_TYPE>
template<typename T>
void Buffer<BUFFER_TYPE>::updateData(const std::vector<T>& buffer)
{
const size_t vectorSize = buffer.size() * sizeof(T);
if(vectorSize < size || vectorSize > size)
{
// SPARK_WARN("Trying to update SSBO with a vector with too large size! SSBO size: {}, vector size: {}. Buffer will be resized and update
// will be processed!", size, vectorSize);
size = static_cast<GLsizei>(vectorSize);
glNamedBufferData(ID, vectorSize, buffer.data(), bufferUsage);
}
else
{
glNamedBufferSubData(ID, 0, vectorSize, buffer.data());
}
}
template<GLenum BUFFER_TYPE>
template<typename T>
void Buffer<BUFFER_TYPE>::updateSubData(size_t offsetFromBeginning, const std::vector<T>& buffer)
{
const size_t vectorSize = buffer.size() * sizeof(T);
const GLintptr offset = static_cast<GLintptr>(offsetFromBeginning);
if(offset > size)
{
return;
}
if(offset + vectorSize > size)
{
return;
}
glNamedBufferSubData(ID, offset, vectorSize, buffer.data());
}
template<GLenum BUFFER_TYPE>
template<typename T, size_t Size>
void Buffer<BUFFER_TYPE>::updateData(const std::array<T, Size>& buffer)
{
const size_t vectorSize = Size * sizeof(T);
if(vectorSize < size || vectorSize > size)
{
// SPARK_WARN("Trying to update SSBO with a vector with too large size! SSBO size: {}, vector size: {}. Buffer will be resized and update
// will be processed!", size, vectorSize);
size = static_cast<GLsizei>(vectorSize);
glNamedBufferData(ID, vectorSize, buffer.data(), bufferUsage);
}
else
{
glNamedBufferSubData(ID, 0, vectorSize, buffer.data());
}
}
template<GLenum BUFFER_TYPE>
template<typename T, size_t Size>
void Buffer<BUFFER_TYPE>::updateSubData(size_t offsetFromBeginning, const std::array<T, Size>& buffer)
{
const size_t vectorSize = Size * sizeof(T);
const GLintptr offset = static_cast<GLintptr>(offsetFromBeginning);
if(offset > size)
{
return;
}
if(offset + vectorSize > size)
{
return;
}
glNamedBufferSubData(ID, offset, vectorSize, buffer.data());
}
template<GLenum BUFFER_TYPE>
void Buffer<BUFFER_TYPE>::resizeBuffer(size_t sizeInBytes)
{
glNamedBufferData(ID, sizeInBytes, nullptr, bufferUsage);
size = static_cast<GLsizei>(sizeInBytes);
}
template<GLenum BUFFER_TYPE>
void Buffer<BUFFER_TYPE>::clearData()
{
glClearNamedBufferData(ID, GL_R32F, GL_RED, GL_FLOAT, nullptr);
}
template<GLenum BUFFER_TYPE>
void Buffer<BUFFER_TYPE>::genBuffer(size_t sizeInBytes)
{
if(ID != 0)
{
cleanup();
}
size = static_cast<GLsizei>(sizeInBytes);
glGenBuffers(1, &ID);
glBindBuffer(BUFFER_TYPE, ID);
glBufferData(BUFFER_TYPE, size, nullptr, bufferUsage);
glBindBuffer(BUFFER_TYPE, 0);
getBinding();
}
template<GLenum BUFFER_TYPE>
void Buffer<BUFFER_TYPE>::cleanup()
{
glDeleteBuffers(1, &ID);
ID = 0;
freeBinding();
}
template<GLenum BUFFER_TYPE>
void Buffer<BUFFER_TYPE>::getBinding()
{
constexpr auto findFreeBindingBetweenAdjacentBindings = [](const uint32_t& binding1, const uint32_t& binding2) {
constexpr auto allowedDistanceBetweenBindings = 1;
return (binding2 - binding1) > allowedDistanceBetweenBindings;
};
const auto it = std::adjacent_find(bindings.begin(), bindings.end(), findFreeBindingBetweenAdjacentBindings);
if(it != bindings.end())
{
binding = *it + 1;
bindings.insert(binding);
}
else
{
if(bindings.empty())
{
binding = 0;
bindings.insert(binding);
}
else
{
binding = *std::prev(bindings.end()) + 1;
bindings.insert(binding);
}
}
}
template<GLenum BUFFER_TYPE>
void Buffer<BUFFER_TYPE>::freeBinding()
{
const auto it = bindings.find(binding);
if(it != bindings.end())
{
bindings.erase(it);
binding = -1;
}
}
using SSBO = Buffer<GL_SHADER_STORAGE_BUFFER>;
using UniformBuffer = Buffer<GL_UNIFORM_BUFFER>;
using ElementArrayBuffer = Buffer<GL_ELEMENT_ARRAY_BUFFER>;
using VertexBuffer = Buffer<GL_ARRAY_BUFFER>; | 25.550847 | 145 | 0.670813 | MickAlmighty |
63671d1240dc16daf9cf31de2d059475a5d5d032 | 16,303 | cxx | C++ | Examples/ANTSIntegrateVectorField.cxx | KevinScholtes/ANTsX | 5462269c0c32e5d65560bae4014c5a05cb02588d | [
"BSD-3-Clause"
] | null | null | null | Examples/ANTSIntegrateVectorField.cxx | KevinScholtes/ANTsX | 5462269c0c32e5d65560bae4014c5a05cb02588d | [
"BSD-3-Clause"
] | null | null | null | Examples/ANTSIntegrateVectorField.cxx | KevinScholtes/ANTsX | 5462269c0c32e5d65560bae4014c5a05cb02588d | [
"BSD-3-Clause"
] | 1 | 2019-10-06T07:31:58.000Z | 2019-10-06T07:31:58.000Z |
#include "antsUtilities.h"
#include "antsAllocImage.h"
#include <algorithm>
#include "itkVectorIndexSelectionCastImageFilter.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "vnl/algo/vnl_determinant.h"
#include "itkWarpImageFilter.h"
#include "itkImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "vnl/algo/vnl_determinant.h"
#include "itkDiscreteGaussianImageFilter.h"
#include "itkVectorLinearInterpolateImageFunction.h"
#include "itkGradientRecursiveGaussianImageFilter.h"
#include "itkVectorCurvatureAnisotropicDiffusionImageFilter.h"
#include "itkLaplacianRecursiveGaussianImageFilter.h"
#include "itkGradientRecursiveGaussianImageFilter.h"
#include "ReadWriteData.h"
namespace ants
{
template <typename TField, typename TImage>
typename TImage::Pointer
GetVectorComponent(typename TField::Pointer field, unsigned int index)
{
// Initialize the Moving to the displacement field
typedef TImage ImageType;
typename ImageType::Pointer sfield = AllocImage<ImageType>(field);
typedef itk::ImageRegionIteratorWithIndex<TField> Iterator;
Iterator vfIter( field, field->GetLargestPossibleRegion() );
for( vfIter.GoToBegin(); !vfIter.IsAtEnd(); ++vfIter )
{
typename TField::PixelType v1 = vfIter.Get();
sfield->SetPixel(vfIter.GetIndex(), v1[index]);
}
return sfield;
}
template <typename TImage>
typename TImage::Pointer
SmoothImage(typename TImage::Pointer image, float sig)
{
// find min value
typedef itk::ImageRegionIteratorWithIndex<TImage> Iterator;
Iterator vfIter(image, image->GetLargestPossibleRegion() );
for( vfIter.GoToBegin(); !vfIter.IsAtEnd(); ++vfIter )
{
typename TImage::PixelType v1 = vfIter.Get();
if( std::isnan(v1) )
{
vfIter.Set(0);
}
}
typedef itk::DiscreteGaussianImageFilter<TImage, TImage> dgf;
typename dgf::Pointer filter = dgf::New();
filter->SetVariance(sig);
filter->SetUseImageSpacingOn();
filter->SetMaximumError(.01f);
filter->SetInput(image);
filter->Update();
typename TImage::Pointer out = filter->GetOutput();
return out;
}
template <typename TImage>
void
SmoothDeformation(typename TImage::Pointer vectorimage, float sig)
{
typedef itk::Vector<float, 3> VectorType;
typedef itk::Image<float, 3> ImageType;
typename ImageType::Pointer subimgx = GetVectorComponent<TImage, ImageType>(vectorimage, 0);
subimgx = SmoothImage<ImageType>(subimgx, sig);
typename ImageType::Pointer subimgy = GetVectorComponent<TImage, ImageType>(vectorimage, 1);
subimgy = SmoothImage<ImageType>(subimgy, sig);
typename ImageType::Pointer subimgz = GetVectorComponent<TImage, ImageType>(vectorimage, 2);
subimgz = SmoothImage<ImageType>(subimgz, sig);
typedef itk::ImageRegionIteratorWithIndex<TImage> IteratorType;
IteratorType Iterator( vectorimage, vectorimage->GetLargestPossibleRegion().GetSize() );
Iterator.GoToBegin();
while( !Iterator.IsAtEnd() )
{
VectorType vec;
vec[0] = subimgx->GetPixel(Iterator.GetIndex() );
vec[1] = subimgy->GetPixel(Iterator.GetIndex() );
vec[2] = subimgz->GetPixel(Iterator.GetIndex() );
Iterator.Set(vec);
++Iterator;
}
return;
}
template <typename TImage, typename TField, typename TInterp, typename TInterp2>
float IntegrateLength( typename TImage::Pointer gmsurf, typename TImage::Pointer /* thickimage */,
typename TImage::IndexType velind, typename TField::Pointer lapgrad, float itime,
float starttime, const float deltaTime, typename TInterp::Pointer vinterp,
typename TImage::SpacingType spacing, float vecsign, float timesign, float gradsign )
{
typedef typename TField::PixelType VectorType;
typedef typename TField::PointType DPointType;
typedef itk::VectorLinearInterpolateImageFunction<TField, float> DefaultInterpolatorType;
VectorType zero;
zero.Fill(0);
VectorType disp;
disp.Fill(0);
unsigned int ct = 0;
DPointType pointIn1;
DPointType pointIn2;
typename DefaultInterpolatorType::ContinuousIndexType vcontind;
DPointType pointIn3;
enum { ImageDimension = TImage::ImageDimension };
typedef typename TImage::IndexType IndexType;
unsigned int m_NumberOfTimePoints = 2;
for( unsigned int jj = 0; jj < ImageDimension; jj++ )
{
pointIn1[jj] = velind[jj] * lapgrad->GetSpacing()[jj];
}
itime = starttime;
bool timedone = false;
float totalmag = 0;
while( !timedone )
{
float scale = 1; // *m_DT[timeind]/m_DS[timeind];
// std::cout << " scale " << scale << std::endl;
double itimetn1 = itime - timesign * deltaTime * scale;
double itimetn1h = itime - timesign * deltaTime * 0.5 * scale;
if( itimetn1h < 0 )
{
itimetn1h = 0;
}
if( itimetn1h > m_NumberOfTimePoints - 1 )
{
itimetn1h = m_NumberOfTimePoints - 1;
}
if( itimetn1 < 0 )
{
itimetn1 = 0;
}
if( itimetn1 > m_NumberOfTimePoints - 1 )
{
itimetn1 = m_NumberOfTimePoints - 1;
}
// first get current position of particle
for( unsigned int jj = 0; jj < ImageDimension; jj++ )
{
pointIn1[jj] = velind[jj] * lapgrad->GetSpacing()[jj];
}
// std::cout << " ind " << index << std::endl;
// now index the time varying field at that position.
typename DefaultInterpolatorType::OutputType f1; f1.Fill(0);
typename DefaultInterpolatorType::OutputType f2; f2.Fill(0);
typename DefaultInterpolatorType::OutputType f3; f3.Fill(0);
typename DefaultInterpolatorType::OutputType f4; f4.Fill(0);
typename DefaultInterpolatorType::ContinuousIndexType Y1;
typename DefaultInterpolatorType::ContinuousIndexType Y2;
typename DefaultInterpolatorType::ContinuousIndexType Y3;
typename DefaultInterpolatorType::ContinuousIndexType Y4;
for( unsigned int jj = 0; jj < ImageDimension; jj++ )
{
pointIn2[jj] = disp[jj] + pointIn1[jj];
vcontind[jj] = pointIn2[jj] / lapgrad->GetSpacing()[jj];
Y1[jj] = vcontind[jj];
Y2[jj] = vcontind[jj];
Y3[jj] = vcontind[jj];
Y4[jj] = vcontind[jj];
}
// Y1[ImageDimension]=itimetn1;
// Y2[ImageDimension]=itimetn1h;
// Y3[ImageDimension]=itimetn1h;
// Y4[ImageDimension]=itime;
f1 = vinterp->EvaluateAtContinuousIndex( Y1 );
for( unsigned int jj = 0; jj < ImageDimension; jj++ )
{
Y2[jj] += f1[jj] * deltaTime * 0.5;
}
bool isinside = true;
for( unsigned int jj = 0; jj < ImageDimension; jj++ )
{
if( Y2[jj] < 1 || Y2[jj] > lapgrad->GetLargestPossibleRegion().GetSize()[jj] - 2 )
{
isinside = false;
}
}
if( isinside )
{
f2 = vinterp->EvaluateAtContinuousIndex( Y2 );
}
for( unsigned int jj = 0; jj < ImageDimension; jj++ )
{
Y3[jj] += f2[jj] * deltaTime * 0.5;
}
isinside = true;
for( unsigned int jj = 0; jj < ImageDimension; jj++ )
{
if( Y3[jj] < 1 || Y3[jj] > lapgrad->GetLargestPossibleRegion().GetSize()[jj] - 2 )
{
isinside = false;
}
}
if( isinside )
{
f3 = vinterp->EvaluateAtContinuousIndex( Y3 );
}
for( unsigned int jj = 0; jj < ImageDimension; jj++ )
{
Y4[jj] += f3[jj] * deltaTime;
}
isinside = true;
for( unsigned int jj = 0; jj < ImageDimension; jj++ )
{
if( Y4[jj] < 1 || Y4[jj] > lapgrad->GetLargestPossibleRegion().GetSize()[jj] - 2 )
{
isinside = false;
}
}
if( isinside )
{
f4 = vinterp->EvaluateAtContinuousIndex( Y4 );
}
for( unsigned int jj = 0; jj < ImageDimension; jj++ )
{
pointIn3[jj] = pointIn2[jj] + gradsign * vecsign * deltaTime / 6.0
* ( f1[jj] + 2.0 * f2[jj] + 2.0 * f3[jj] + f4[jj] );
}
VectorType out;
float mag = 0, dmag = 0, voxmag = 0;
for( unsigned int jj = 0; jj < ImageDimension; jj++ )
{
out[jj] = pointIn3[jj] - pointIn1[jj];
mag += (pointIn3[jj] - pointIn2[jj]) * (pointIn3[jj] - pointIn2[jj]);
voxmag += (pointIn3[jj] - pointIn2[jj]) / spacing[jj] * (pointIn3[jj] - pointIn2[jj]) / spacing[jj];
dmag += (pointIn3[jj] - pointIn1[jj]) * (pointIn3[jj] - pointIn1[jj]);
disp[jj] = out[jj];
}
voxmag = sqrt(voxmag);
dmag = sqrt(dmag);
totalmag += sqrt(mag);
ct++;
// if (!propagate) //thislength=dmag;//
// thislength += totalmag;
itime = itime + deltaTime * timesign;
IndexType myind;
for( unsigned int qq = 0; qq < ImageDimension; qq++ )
{
myind[qq] = (unsigned long)(pointIn3[qq] / spacing[qq] + 0.5);
}
if( gmsurf->GetPixel(myind) < 1 )
{
timedone = true;
}
if( ct > 1000 )
{
std::cout << " stopping b/c exceed 1000 points " << voxmag << std::endl; timedone = true;
}
if( voxmag < 0.1 )
{
timedone = true;
}
}
return totalmag;
}
template <unsigned int ImageDimension>
int IntegrateVectorField(int argc, char *argv[])
{
typedef float PixelType;
typedef itk::Vector<float, ImageDimension> VectorType;
typedef itk::Image<VectorType, ImageDimension> DisplacementFieldType;
typedef itk::Image<PixelType, ImageDimension> ImageType;
typedef typename ImageType::SpacingType SpacingType;
constexpr float deltaTime = 0.001;
float gradstep = 1. / deltaTime; // atof(argv[3])*(-1.0);
std::string vectorfn = std::string(argv[1]);
std::string roifn = std::string(argv[2]);
int argct = 3;
argct++;
std::string lenoutname = std::string("");
if( argc > argct )
{
lenoutname = std::string(argv[argct]);
}
argct++;
if( argc > argct )
{
gradstep *= atof(argv[argct]);
}
argct++;
typename ImageType::Pointer ROIimage;
ReadImage<ImageType>(ROIimage, roifn.c_str() );
typename ImageType::Pointer thickimage;
ReadImage<ImageType>(thickimage, roifn.c_str() );
thickimage->FillBuffer(0);
typename DisplacementFieldType::Pointer VECimage;
ReadImage<DisplacementFieldType>(VECimage, vectorfn.c_str() );
SpacingType spacing = ROIimage->GetSpacing();
typedef itk::ImageRegionIteratorWithIndex<ImageType> IteratorType;
IteratorType Iterator( ROIimage, ROIimage->GetLargestPossibleRegion().GetSize() );
double timezero = 0; // 1
double timeone = 1; // (s[ImageDimension]-1-timezero);
float starttime = timezero; // timezero;
float finishtime = timeone; // s[ImageDimension]-1;//timeone;
typename DisplacementFieldType::IndexType velind;
float timesign = 1.0;
if( starttime > finishtime )
{
timesign = -1.0;
}
typedef DisplacementFieldType TimeVaryingVelocityFieldType;
typedef typename DisplacementFieldType::PointType DPointType;
typedef itk::VectorLinearInterpolateImageFunction<TimeVaryingVelocityFieldType, float> DefaultInterpolatorType;
typename DefaultInterpolatorType::Pointer vinterp = DefaultInterpolatorType::New();
typedef itk::LinearInterpolateImageFunction<ImageType, float> ScalarInterpolatorType;
VectorType zero;
zero.Fill(0);
typedef itk::ImageRegionIteratorWithIndex<DisplacementFieldType> VIteratorType;
VIteratorType VIterator( VECimage, VECimage->GetLargestPossibleRegion().GetSize() );
VIterator.GoToBegin();
while( !VIterator.IsAtEnd() )
{
VectorType vec = VIterator.Get();
float mag = 0;
for( unsigned int qq = 0; qq < ImageDimension; qq++ )
{
mag += vec[qq] * vec[qq];
}
mag = sqrt(mag);
if( mag > 0 )
{
vec = vec / mag;
}
VIterator.Set(vec * gradstep);
++VIterator;
}
Iterator.GoToBegin();
while( !Iterator.IsAtEnd() )
{
velind = Iterator.GetIndex();
float itime = starttime;
VectorType disp;
disp.Fill(0.0);
if( ROIimage->GetPixel(velind) == 2 )
{
vinterp->SetInputImage(VECimage);
float gradsign = -1.0;
double vecsign = -1.0;
float len1 = IntegrateLength<ImageType, DisplacementFieldType, DefaultInterpolatorType, ScalarInterpolatorType>
(ROIimage, thickimage, velind, VECimage, itime, starttime, deltaTime, vinterp,
spacing, vecsign, gradsign,
timesign);
gradsign = 1.0; vecsign = 1;
const float len2 = IntegrateLength<ImageType, DisplacementFieldType, DefaultInterpolatorType, ScalarInterpolatorType>
(ROIimage, thickimage, velind, VECimage, itime, starttime, deltaTime, vinterp,
spacing, vecsign, gradsign,
timesign );
float totalength = len1 + len2;
thickimage->SetPixel(velind, totalength);
if( (totalength) > 0 )
{
std::cout << " len1 " << len1 << " len2 " << len2 << " ind " << velind << std::endl;
}
}
++Iterator;
}
WriteImage<ImageType>(thickimage, lenoutname.c_str() );
return EXIT_SUCCESS;
}
// entry point for the library; parameter 'args' is equivalent to 'argv' in (argc,argv) of commandline parameters to
// 'main()'
int ANTSIntegrateVectorField( std::vector<std::string> args, std::ostream* /*out_stream = nullptr*/ )
{
// put the arguments coming in as 'args' into standard (argc,argv) format;
// 'args' doesn't have the command name as first, argument, so add it manually;
// 'args' may have adjacent arguments concatenated into one argument,
// which the parser should handle
args.insert( args.begin(), "ANTSIntegrateVectorField" );
int argc = args.size();
char* * argv = new char *[args.size() + 1];
for( unsigned int i = 0; i < args.size(); ++i )
{
// allocate space for the string plus a null character
argv[i] = new char[args[i].length() + 1];
std::strncpy( argv[i], args[i].c_str(), args[i].length() );
// place the null character in the end
argv[i][args[i].length()] = '\0';
}
argv[argc] = nullptr;
// class to automatically cleanup argv upon destruction
class Cleanup_argv
{
public:
Cleanup_argv( char* * argv_, int argc_plus_one_ ) : argv( argv_ ), argc_plus_one( argc_plus_one_ )
{
}
~Cleanup_argv()
{
for( unsigned int i = 0; i < argc_plus_one; ++i )
{
delete[] argv[i];
}
delete[] argv;
}
private:
char* * argv;
unsigned int argc_plus_one;
};
Cleanup_argv cleanup_argv( argv, argc + 1 );
// antscout->set_stream( out_stream );
if( argc < 4 )
{
std::cout << "Usage: " << argv[0]
<< " VecImageIN.nii.gz ROIMaskIN.nii.gz FibersOUT.vtk LengthImageOUT.nii.gz " << std::endl;
std::cout
<<
" The vector field should have vectors as voxels , the ROI is an integer image, fibers out will be vtk text files .... "
<< std::endl;
std::cout << " ROI-Mask controls where the integration is performed and the start point region ... " << std::endl;
std::cout << " e.g. the brain will have value 1 , the ROI has value 2 , then all starting seed points "
<< std::endl;
std::cout
<< " for the integration will start in the region labeled 2 and be constrained to the region labeled 1. "
<< std::endl;
if( argc >= 2 &&
( std::string( argv[1] ) == std::string("--help") || std::string( argv[1] ) == std::string("-h") ) )
{
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
std::string ifn = std::string(argv[1]);
itk::ImageIOBase::Pointer imageIO =
itk::ImageIOFactory::CreateImageIO(ifn.c_str(), itk::ImageIOFactory::ReadMode);
imageIO->SetFileName(ifn.c_str() );
imageIO->ReadImageInformation();
unsigned int dim = imageIO->GetNumberOfDimensions();
switch( dim )
{
case 2:
{
IntegrateVectorField<2>(argc, argv);
}
break;
case 3:
{
IntegrateVectorField<3>(argc, argv);
}
break;
case 4:
{
IntegrateVectorField<4>(argc, argv);
}
break;
default:
std::cerr << "Unsupported dimension" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
} // namespace ants
| 33.203666 | 126 | 0.635098 | KevinScholtes |
636af685bcd7ad025e660a410b114e639536321f | 5,672 | cpp | C++ | source/mclib/mlr/mlrinfinitelightwithfalloff.cpp | mechasource/mechcommander2 | b2c7cecf001cec1f535aa8d29c31bdc30d9aa983 | [
"BSD-2-Clause"
] | 38 | 2015-04-10T13:31:03.000Z | 2021-09-03T22:34:05.000Z | source/mclib/mlr/mlrinfinitelightwithfalloff.cpp | mechasource/mechcommander2 | b2c7cecf001cec1f535aa8d29c31bdc30d9aa983 | [
"BSD-2-Clause"
] | 1 | 2020-07-09T09:48:44.000Z | 2020-07-12T12:41:43.000Z | source/mclib/mlr/mlrinfinitelightwithfalloff.cpp | mechasource/mechcommander2 | b2c7cecf001cec1f535aa8d29c31bdc30d9aa983 | [
"BSD-2-Clause"
] | 12 | 2015-06-29T08:06:57.000Z | 2021-10-13T13:11:41.000Z | //===========================================================================//
// Copyright (C) Microsoft Corporation. All rights reserved. //
//===========================================================================//
#include "stdinc.h"
#include "mlr/mlrinfinitelightwithfalloff.h"
namespace MidLevelRenderer {
//#############################################################################
//############### MLRInfiniteLightWithFalloff ###########################
//#############################################################################
MLRInfiniteLightWithFalloff::ClassData* MLRInfiniteLightWithFalloff::DefaultData = nullptr;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
void
MLRInfiniteLightWithFalloff::InitializeClass()
{
_ASSERT(!DefaultData);
// _ASSERT(gos_GetCurrentHeap() == StaticHeap);
DefaultData = new ClassData(MLRInfiniteLightWithFalloffClassID,
"MidLevelRenderer::MLRInfiniteLightWithFalloff", MLRLight::DefaultData);
Register_Object(DefaultData);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
void
MLRInfiniteLightWithFalloff::TerminateClass()
{
Unregister_Object(DefaultData);
delete DefaultData;
DefaultData = nullptr;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
MLRInfiniteLightWithFalloff::MLRInfiniteLightWithFalloff(ClassData* class_data) :
MLRLight(class_data)
{
// _ASSERT(gos_GetCurrentHeap() == Heap);
lightMask = MLRState::FaceLightingMode | MLRState::VertexLightingMode;
innerRadius = 0.0f;
outerRadius = 0.0f;
oneOverDistance = 100.0f;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
MLRInfiniteLightWithFalloff::MLRInfiniteLightWithFalloff(
ClassData* class_data, std::iostream stream, uint32_t version) :
MLRLight(class_data, stream, version)
{
Check_Object(stream);
// _ASSERT(gos_GetCurrentHeap() == Heap);
lightMask = MLRState::FaceLightingMode | MLRState::VertexLightingMode;
float inner, outer;
*stream >> inner >> outer;
SetFalloffDistance(inner, outer);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
MLRInfiniteLightWithFalloff::MLRInfiniteLightWithFalloff(ClassData* class_data, Stuff::Page* page) :
MLRLight(class_data, page)
{
Check_Object(page);
// _ASSERT(gos_GetCurrentHeap() == Heap);
lightMask = MLRState::FaceLightingMode | MLRState::VertexLightingMode;
float inner = 0.0f;
page->GetEntry("InnerRadius", &inner);
float outer = 100.0;
page->GetEntry("OuterRadius", &outer);
SetFalloffDistance(inner, outer);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
MLRInfiniteLightWithFalloff::~MLRInfiniteLightWithFalloff() {}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
void
MLRInfiniteLightWithFalloff::Save(std::iostream stream)
{
// Check_Object(this);
Check_Object(stream);
MLRLight::Save(stream);
*stream << innerRadius << outerRadius;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
void
MLRInfiniteLightWithFalloff::Write(Stuff::Page* page)
{
// Check_Object(this);
Check_Object(page);
MLRLight::Write(page);
page->SetEntry("InnerRadius", innerRadius);
page->SetEntry("OuterRadius", outerRadius);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
void
MLRInfiniteLightWithFalloff::TestInstance()
{
_ASSERT(IsDerivedFrom(DefaultData));
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
void
MLRInfiniteLightWithFalloff::SetFalloffDistance(float ir, float or)
{
// Check_Object(this);
innerRadius = ir;
outerRadius = or ;
oneOverDistance = 1.0f / (outerRadius - innerRadius);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
bool
MLRInfiniteLightWithFalloff::GetFalloffDistance(float& ir, float& or)
{
// Check_Object(this);
ir = innerRadius;
or = outerRadius;
return true;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
void
MLRInfiniteLightWithFalloff::LightVertex(const MLRVertexData& vertexData)
{
UnitVector3D light_z;
GetInShapeDirection(light_z);
//
//-------------------------------------------------------------------
// Now we reduce the light level falling on the vertex based upon the
// cosine of the angle between light and normal
//-------------------------------------------------------------------
//
float cosine = -(light_z * (*vertexData.normal)) * intensity;
RGBcolour light_color(color);
Point3D vertex_to_light;
_ASSERT(GetFalloffDistance(vertex_to_light.x, vertex_to_light.y));
GetInShapePosition(vertex_to_light);
vertex_to_light -= *vertexData.point;
//
//--------------------------------------------------------------
// If the distance to the vertex is zero, the light will not
// contribute to the vertex coloration. Otherwise, decrease the
// light level as appropriate to the distance
//--------------------------------------------------------------
//
float length = vertex_to_light.GetApproximateLength();
float falloff = 1.0f;
#if COLOR_AS_DWORD
TO_DO;
#else
if (GetFalloff(length, falloff))
{
light_color.red *= falloff;
light_color.green *= falloff;
light_color.blue *= falloff;
}
else
{
return;
}
if (cosine > SMALL)
{
light_color.red *= cosine;
light_color.green *= cosine;
light_color.blue *= cosine;
vertexData.color->red += light_color.red;
vertexData.color->green += light_color.green;
vertexData.color->blue += light_color.blue;
}
#endif
}
} // namespace MidLevelRenderer
| 29.696335 | 100 | 0.540197 | mechasource |
636b5aff0ad61ecc4287300b959542bb1bde3573 | 982 | cpp | C++ | uva/524.cpp | larc/competitive_programming | deccd7152a14adf217c58546d1cf8ac6b45f1c52 | [
"MIT"
] | 1 | 2019-05-23T19:05:39.000Z | 2019-05-23T19:05:39.000Z | uva/524.cpp | larc/oremor | deccd7152a14adf217c58546d1cf8ac6b45f1c52 | [
"MIT"
] | null | null | null | uva/524.cpp | larc/oremor | deccd7152a14adf217c58546d1cf8ac6b45f1c52 | [
"MIT"
] | null | null | null | // 524 - Prime Ring Problem
#include <cstdio>
#include <cstring>
#define N 16
#define M 32
int ring[N];
bool not_prime[M];
bool selected[N];
void init_prime()
{
memset(not_prime, 0, sizeof(not_prime));
for(int i = 2; i < M; ++i)
if(!not_prime[i])
for(int j = i * i; j < M; j += i)
not_prime[j] = 1;
}
void prime_ring(const int & n, const int & p)
{
if(n == p && !not_prime[ring[p - 1] + ring[0]])
{
printf("%d", ring[0]);
for(int i = 1; i < p; ++i)
printf(" %d", ring[i]);
putchar('\n');
return;
}
for(int i = 2 + !(p & 1); i <= n; i += 2)
if(!selected[i] && !not_prime[i + ring[p - 1]])
{
selected[i] = 1;
ring[p] = i;
prime_ring(n, p + 1);
selected[i] = 0;
}
}
int main()
{
init_prime();
int n, n_cases = 1;
ring[0] = 1;
scanf("%d", &n);
while(1)
{
printf("Case %d:\n", n_cases++);
memset(selected, 0, sizeof(selected));
prime_ring(n, 1);
if(scanf("%d", &n) == EOF) break;
putchar('\n');
}
return 0;
}
| 14.441176 | 49 | 0.525458 | larc |
636cd41bc1e72bf99ab64fb7a368b8d51bc9edd8 | 1,863 | cpp | C++ | Tuniac1/NFN_Exporter/NumberedFileExporter.cpp | Harteex/Tuniac | dac98a68c1b801b7fc82874aad16cc8adcabb606 | [
"BSD-3-Clause"
] | 3 | 2022-01-05T08:47:51.000Z | 2022-01-06T12:42:18.000Z | Tuniac1/NFN_Exporter/NumberedFileExporter.cpp | Harteex/Tuniac | dac98a68c1b801b7fc82874aad16cc8adcabb606 | [
"BSD-3-Clause"
] | null | null | null | Tuniac1/NFN_Exporter/NumberedFileExporter.cpp | Harteex/Tuniac | dac98a68c1b801b7fc82874aad16cc8adcabb606 | [
"BSD-3-Clause"
] | 1 | 2022-01-06T16:12:58.000Z | 2022-01-06T16:12:58.000Z | #include "StdAfx.h"
#include "NumberedFileExporter.h"
CNumberedFileExporter::CNumberedFileExporter(void)
{
}
CNumberedFileExporter::~CNumberedFileExporter(void)
{
}
LPTSTR CNumberedFileExporter::GetName(void)
{
return TEXT("Numbered File Exporter");
}
void CNumberedFileExporter::Destory(void)
{
delete this;
}
unsigned long CNumberedFileExporter::GetNumExtensions(void)
{
return 1;
}
LPTSTR CNumberedFileExporter::SupportedExtension(unsigned long ulExtentionNum)
{
return TEXT("NFN");
}
bool CNumberedFileExporter::CanHandle(LPTSTR szSource)
{
TCHAR * pLastDigits = szSource + (wcsnlen_s(szSource, MAX_PATH)-3);
if(StrStrI(pLastDigits, TEXT("NFN")))
return true;
return false;
}
bool CNumberedFileExporter::BeginExport(LPTSTR szSource, unsigned long ulNumItems)
{
if (IDNO == MessageBox(NULL, TEXT("Warning: NFN_Exporter plugin creates a copy of the selected files. Eg it duplicates the files! \n\nDo you want to continue?"), TEXT("NFN_Exporter"), MB_YESNO | MB_ICONWARNING))
return false;
StringCchCopy(m_szExportFolder, MAX_PATH, szSource);
if(GetFileAttributes(m_szExportFolder) == INVALID_FILE_ATTRIBUTES)
{
// folder doesn't exist, create it.
CreateDirectory(m_szExportFolder, NULL);
}
m_ulCurrentFileIndex = 1;
return true;
}
bool CNumberedFileExporter::ExportEntry(LibraryEntry & libraryEntry)
{
TCHAR m_szTempFile[MAX_PATH];
StringCchCopy(m_szTempFile, MAX_PATH, m_szExportFolder);
PathAddBackslash(m_szTempFile);
TCHAR tempBit[32];
StringCchPrintf(tempBit, 32, TEXT("%04u - "), m_ulCurrentFileIndex);
StringCchCat(m_szTempFile, MAX_PATH, tempBit);
StringCchCat(m_szTempFile, MAX_PATH, PathFindFileName(libraryEntry.szURL));
CopyFile(libraryEntry.szURL, m_szTempFile, TRUE);
m_ulCurrentFileIndex++;
return true;
}
bool CNumberedFileExporter::EndExport(void)
{
return false;
}
| 20.7 | 212 | 0.765432 | Harteex |
636d8faf922ac3c55de0aaf64a883266b3778283 | 4,184 | cpp | C++ | coast/wdbase/ServerLFThreadPoolsManager.cpp | zer0infinity/CuteForCoast | 37d933c5fe2e0ce9a801f51b2aa27c7a18098511 | [
"BSD-3-Clause"
] | null | null | null | coast/wdbase/ServerLFThreadPoolsManager.cpp | zer0infinity/CuteForCoast | 37d933c5fe2e0ce9a801f51b2aa27c7a18098511 | [
"BSD-3-Clause"
] | null | null | null | coast/wdbase/ServerLFThreadPoolsManager.cpp | zer0infinity/CuteForCoast | 37d933c5fe2e0ce9a801f51b2aa27c7a18098511 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
* All rights reserved.
*
* This library/application is free software; you can redistribute and/or modify it under the terms of
* the license that is included with this library/application in the file license.txt.
*/
#include "ServerLFThreadPoolsManager.h"
#include "Server.h"
#include "LFListenerPool.h"
#include "WPMStatHandler.h"
#include "RequestProcessor.h"
RegisterServerPoolsManagerInterface(ServerLFThreadPoolsManager);
ServerLFThreadPoolsManager::ServerLFThreadPoolsManager(const char *ServerThreadPoolsManagerName)
: ServerPoolsManagerInterface(ServerThreadPoolsManagerName)
, fLFPool(0)
, fThreadPoolSz(25)
{
StartTrace(ServerLFThreadPoolsManager.Ctor);
}
ServerLFThreadPoolsManager::~ServerLFThreadPoolsManager()
{
StartTrace(ServerLFThreadPoolsManager.Dtor);
RequestTermination();
Terminate();
delete fLFPool;
fLFPool = 0;
}
int ServerLFThreadPoolsManager::Init(Server *server)
{
StartTrace(ServerLFThreadPoolsManager.Init);
// return 0 in case of success
return ( SetupLFPool(server) ? 0 : 1 );
}
bool ServerLFThreadPoolsManager::SetupLFPool(Server *server)
{
StartTrace(ServerLFThreadPoolsManager.SetupLFPool);
Context ctx;
ctx.SetServer(server);
ctx.Push("ServerLFThreadPoolsManager", this);
fThreadPoolSz = ctx.Lookup("ThreadPoolSize", fThreadPoolSz);
ROAnything listenerPoolConfig;
if (!ctx.Lookup("ListenerPool", listenerPoolConfig)) {
const char *msg = "ListenerPool configuration not found";
SYSERROR(msg);
Trace(msg);
return false;
}
TraceAny(listenerPoolConfig, "ListenerPool config:");
RequestReactor *rr = new RequestReactor(server->MakeProcessor(), new WPMStatHandler(fThreadPoolSz));
server->AddStatGatherer2Observe(rr);
fLFPool = new LFListenerPool(rr);
bool usePoolStorage = (ctx.Lookup("UsePoolStorage", 0L) != 0L);
return fLFPool->Init(fThreadPoolSz, listenerPoolConfig, usePoolStorage);
}
RequestProcessor* ServerLFThreadPoolsManager::DoGetRequestProcessor() {
if ( fLFPool && fLFPool->GetReactor() ) {
RequestReactor* pReactor = dynamic_cast<RequestReactor*>(fLFPool->GetReactor());
if ( pReactor ) {
return pReactor->GetRequestProcessor();
}
}
return 0;
}
int ServerLFThreadPoolsManager::ReInit(Server *server)
{
StartTrace(ServerLFThreadPoolsManager.ReInit);
return 0;
}
int ServerLFThreadPoolsManager::Run(Server *server)
{
StartTrace(ServerLFThreadPoolsManager.Run);
Assert(fLFPool);
Context ctx;
ctx.SetServer(server);
ctx.Push("ServerLFThreadPoolsManager", this);
bool usePoolStorage = (ctx.Lookup("UsePoolStorage", 0L) != 0L);
u_long poolStorageSize = (u_long)ctx.Lookup("PoolStorageSize", 1000L);
u_long numOfPoolBucketSizes = (u_long)ctx.Lookup("NumOfPoolBucketSizes", 20L);
int retVal = fLFPool->Start(usePoolStorage, poolStorageSize, numOfPoolBucketSizes);
if ( retVal != 0 ) {
SYSERROR("server (" << fName << ") start accept loops failed");
return retVal;
}
SetReady(true);
// wait on Join forever
retVal = fLFPool->Join(0);
SetReady(false);
return retVal;
}
bool ServerLFThreadPoolsManager::BlockRequests(Server *server)
{
StartTrace(ServerLFThreadPoolsManager.BlockRequests);
fLFPool->BlockRequests();
String m(" done\n");
SystemLog::WriteToStderr(m);
Trace("done");
m = "Waiting for requests to terminate \n";
SystemLog::WriteToStderr(m);
Trace(m);
Context ctx;
ctx.SetServer(server);
ctx.Push("ServerLFThreadPoolsManager", this);
return fLFPool->AwaitEmpty(ctx.Lookup("AwaitResetEmpty", 120L));
}
void ServerLFThreadPoolsManager::UnblockRequests()
{
StartTrace(ServerLFThreadPoolsManager.UnblockRequests);
fLFPool->UnblockRequests();
}
int ServerLFThreadPoolsManager::RequestTermination()
{
StartTrace(ServerLFThreadPoolsManager.RequestTermination);
if ( fLFPool ) {
fLFPool->RequestTermination();
}
return 0;
}
void ServerLFThreadPoolsManager::Terminate()
{
StartTrace(ServerLFThreadPoolsManager.Terminate);
if ( fLFPool ) {
fLFPool->RequestTermination();
fLFPool->Join(20);
}
Trace("setting ready to false");
SetReady(false);
}
long ServerLFThreadPoolsManager::GetThreadPoolSize()
{
return fThreadPoolSz;
}
| 27.346405 | 102 | 0.769598 | zer0infinity |
636ee9507dff33daf93aa51f732e5acb3874fcbe | 1,040 | hpp | C++ | include/ce2/asset/prefab.hpp | chokomancarr/chokoengine2 | 2825f2b95d24689f4731b096c8be39cc9a0f759a | [
"Apache-2.0"
] | null | null | null | include/ce2/asset/prefab.hpp | chokomancarr/chokoengine2 | 2825f2b95d24689f4731b096c8be39cc9a0f759a | [
"Apache-2.0"
] | null | null | null | include/ce2/asset/prefab.hpp | chokomancarr/chokoengine2 | 2825f2b95d24689f4731b096c8be39cc9a0f759a | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "chokoengine.hpp"
CE_BEGIN_NAMESPACE
/* Prefab class
* A holder of scene objects
* Saves a configuration of objects
* that can be instantiated into the scene
*/
class _Prefab : public _Asset { CE_OBJECT_COMMON
public:
class _ObjBase;
class _ObjTreeBase;
typedef std::function<Prefab(const std::string&)> _Sig2Prb;
typedef std::function<Asset(AssetType, const std::string&)> _Sig2Ass;
private:
std::unique_ptr<_ObjBase> _data;
std::unique_ptr<_ObjTreeBase> _tree;
public:
_Prefab(const SceneObject&, bool link);
_Prefab(const JsonObject&, _Sig2Prb);
~_Prefab(); //explicit destructor where _ObjBase is defined
JsonObject ToJson() const;
SceneObject Instantiate(_Sig2Ass);
std::unique_ptr<_ObjBase>& GetPrefabObj(size_t id);
_ObjTreeBase& GetTreeObj(size_t id);
std::unique_ptr<_ObjTreeBase>& GetTree();
void Apply(const SceneObject&, bool tree = false, size_t id = -1);
void Revert(const SceneObject&, size_t id = -1);
void _UpdateObjs(const SceneObject&);
};
CE_END_NAMESPACE | 22.12766 | 70 | 0.748077 | chokomancarr |
6378afe632187919bb9e47b4fb4b5b5915cd3ae1 | 3,130 | cpp | C++ | src/Shay/AABB.cpp | MajorArkwolf/stonks | 5671f7811f19af33450e5fd07ab61c700f71ee69 | [
"0BSD"
] | null | null | null | src/Shay/AABB.cpp | MajorArkwolf/stonks | 5671f7811f19af33450e5fd07ab61c700f71ee69 | [
"0BSD"
] | null | null | null | src/Shay/AABB.cpp | MajorArkwolf/stonks | 5671f7811f19af33450e5fd07ab61c700f71ee69 | [
"0BSD"
] | null | null | null | #include "AABB.hpp"
using Shay::AABB;
/**
* @brief Sets the max X value for the bounding box
* @param tempX The maxmimum x-coordinate
*/
void AABB::SetMaxX(GLfloat tempX) {
if (this->currentAABB >= m_BBox.size()) {
m_BBox.push_back({});
}
m_BBox[this->currentAABB].max.x = tempX;
}
/**
* @brief Sets the min X value for the bounding box
* @param tempX The minimum x-coordinate
*/
void AABB::SetMinX(GLfloat tempX) {
if (this->currentAABB >= m_BBox.size()) {
m_BBox.push_back({});
}
m_BBox[this->currentAABB].min.x = tempX;
}
/**
* @brief Sets the max Y value for the bounding box
* @param tempY The maxmimum y-coordinate
*/
void AABB::SetMaxY(GLfloat tempY) {
if (this->currentAABB >= m_BBox.size()) {
m_BBox.push_back({});
}
m_BBox[this->currentAABB].max.y = tempY;
}
/**
* @brief Sets the min Y value for the bounding box
* @param tempY The minimum y-coordinate
*/
void AABB::SetMinY(GLfloat tempY) {
if (this->currentAABB >= m_BBox.size()) {
m_BBox.push_back({});
}
m_BBox[this->currentAABB].min.y = tempY;
}
/**
* @brief Sets the max Z value for the bounding box
* @param tempZ The maxmimum z-coordinate
*/
void AABB::SetMaxZ(GLfloat tempZ) {
if (this->currentAABB >= m_BBox.size()) {
m_BBox.push_back({});
}
m_BBox[this->currentAABB].max.z = tempZ;
}
/**
* @brief Sets the min Z value for the bounding box
* @param tempZ The minimum z-coordinate
*/
void AABB::SetMinZ(GLfloat tempZ) {
if (this->currentAABB >= m_BBox.size()) {
m_BBox.push_back({});
}
m_BBox[this->currentAABB].min.z = tempZ;
}
/**
* @brief Sets the index for the bounding box
* @param index The index number to set the bounding box to
*/
auto AABB::SetAABBIndex(size_t index) -> void {
this->currentAABB = index;
}
/**
* @brief Finishes the AABB, what does this do
*/
auto AABB::FinishAABB() -> void {
this->currentAABB++;
}
/**
* @brief Returns the Max X coordinate of the bounding box
* @return The max X coordinate
*/
GLfloat AABB::GetMaxX() {
return m_BBox[this->currentAABB].max.x;
}
/**
* @brief Returns the min X value for the bounding box
* @return The min X coordinate
*/
GLfloat AABB::GetMinX() {
return m_BBox[this->currentAABB].min.x;
}
/**
* @brief Returns the max Y value for the bounding box
* @return The max Y coordinate
*/
GLfloat AABB::GetMaxY() {
return m_BBox[this->currentAABB].max.y;
}
/**
* @brief Returns the min Y value for the bounding box
* @return The min Y coordinate
*/
GLfloat AABB::GetMinY() {
return m_BBox[this->currentAABB].min.y;
}
/**
* @brief Returns the max Z value for the bounding box
* @return The max Z coordinate
*/
GLfloat AABB::GetMaxZ() {
return m_BBox[this->currentAABB].max.z;
}
/**
* @brief Returns the min Z value for the bounding box
* @return The min Z coordinate
*/
GLfloat AABB::GetMinZ() {
return m_BBox[this->currentAABB].min.z;
}
/**
* @brief Returns the number of bounding boxes
* @return The bounding box index number
*/
size_t AABB::GetNoBoundingBoxes() {
return m_BBox.size();
}
| 22.198582 | 59 | 0.650479 | MajorArkwolf |
6388478c98205199031129eabe5f02ca67748796 | 1,207 | hpp | C++ | include/Library/Physics/Time.hpp | cowlicks/library-physics | dd314011132430fcf074a9a1633b24471745cf92 | [
"Apache-2.0"
] | null | null | null | include/Library/Physics/Time.hpp | cowlicks/library-physics | dd314011132430fcf074a9a1633b24471745cf92 | [
"Apache-2.0"
] | null | null | null | include/Library/Physics/Time.hpp | cowlicks/library-physics | dd314011132430fcf074a9a1633b24471745cf92 | [
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @project Library ▸ Physics
/// @file Library/Physics/Time.hpp
/// @author Lucas Brémond <[email protected]>
/// @license Apache License 2.0
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef __Library_Physics_Time__
#define __Library_Physics_Time__
#include <Library/Physics/Time/Instant.hpp>
#include <Library/Physics/Time/Duration.hpp>
#include <Library/Physics/Time/Interval.hpp>
#include <Library/Physics/Time/DateTime.hpp>
#include <Library/Physics/Time/Date.hpp>
#include <Library/Physics/Time/Time.hpp>
#include <Library/Physics/Time/Scale.hpp>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
| 46.423077 | 160 | 0.339685 | cowlicks |
638a1b59b9be595225712a7150cd96d9698d2e34 | 2,498 | cpp | C++ | tests/cpp-tests/Classes/VRTest/VRTest.cpp | DelinWorks/adxe | 0f1ba3a086d744bb52e157e649fa986ae3c7ab05 | [
"MIT"
] | null | null | null | tests/cpp-tests/Classes/VRTest/VRTest.cpp | DelinWorks/adxe | 0f1ba3a086d744bb52e157e649fa986ae3c7ab05 | [
"MIT"
] | 4 | 2020-10-22T05:45:37.000Z | 2020-10-23T12:11:44.000Z | tests/cpp-tests/Classes/VRTest/VRTest.cpp | DelinWorks/adxe | 0f1ba3a086d744bb52e157e649fa986ae3c7ab05 | [
"MIT"
] | 1 | 2020-10-22T03:17:28.000Z | 2020-10-22T03:17:28.000Z | /****************************************************************************
Copyright (c) 2012 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
https://adxeproject.github.io/
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 "VRTest.h"
USING_NS_CC;
VRTests::VRTests()
{
ADD_TEST_CASE(VRTest1);
};
//------------------------------------------------------------------
//
// VRTest1
//
//------------------------------------------------------------------
VRTest1::VRTest1()
{
auto size = Director::getInstance()->getVisibleSize();
auto image = Sprite::create("Images/background.png");
image->setPosition(size / 2);
addChild(image);
auto button = MenuItemFont::create("Enable / Disable VR", [](Ref* ref) {
auto glview = Director::getInstance()->getOpenGLView();
auto vrimpl = glview->getVR();
if (vrimpl)
{
glview->setVR(nullptr);
}
else
{
auto genericvr = new VRGenericRenderer;
glview->setVR(genericvr);
}
});
button->setFontSizeObj(16);
auto menu = Menu::create(button, nullptr);
addChild(menu);
menu->setPosition(size / 6);
}
std::string VRTest1::title() const
{
return "Testing Generic VR";
}
std::string VRTest1::subtitle() const
{
return "Enable / Disable it with the button";
}
| 31.620253 | 78 | 0.617294 | DelinWorks |
638c611b543c3ee35594ac1b41efdf74566d2021 | 2,473 | cc | C++ | egserver.cc | jdb19937/tewel | e2dc25c0998b2bf2763cd68ff66691e0c9f86928 | [
"MIT"
] | null | null | null | egserver.cc | jdb19937/tewel | e2dc25c0998b2bf2763cd68ff66691e0c9f86928 | [
"MIT"
] | null | null | null | egserver.cc | jdb19937/tewel | e2dc25c0998b2bf2763cd68ff66691e0c9f86928 | [
"MIT"
] | null | null | null | #define __MAKEMORE_EGSERVER_CC__ 1
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <sys/fcntl.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/signal.h>
#include <sys/mman.h>
#include <netinet/in.h>
#include <string.h>
#include <string>
#include <vector>
#include <list>
#include "egserver.hh"
#include "youtil.hh"
#include "chain.hh"
#include "colonel.hh"
namespace makemore {
using namespace std;
EGServer::EGServer(const std::vector<std::string> &_ctx, int _pw, int _ph, int _cuda, int _kbs, double _reload, bool _pngout) : Server() {
pw = _pw;
ph = _ph;
ctx = _ctx;
chn = NULL;
cuda = _cuda;
kbs = _kbs;
reload = _reload;
pngout = _pngout;
last_reload = 0.0;
}
void EGServer::prepare() {
setkdev(cuda >= 0 ? cuda : kndevs() > 1 ? 1 : 0);
setkbs(kbs);
chn = new Chain;
for (auto ctxfn : ctx)
chn->push(ctxfn, O_RDONLY);
chn->prepare(pw, ph);
last_reload = now();
Server::prepare();
}
void EGServer::extend() {
if (reload > 0 && last_reload + reload < now()) {
info("reloading chain");
chn->load();
last_reload = now();
}
}
bool EGServer::handle(Client *client) {
int inpn = chn->head->iw * chn->head->ih * chn->head->ic;
assert(inpn > 0);
while (client->can_read(256 + inpn * sizeof(double))) {
uint8_t *hdr = client->inpbuf;
int32_t stop;
memcpy(&stop, hdr, 4);
if (stop > 0 || stop < -4)
return false;
Paracortex *tail = chn->ctxv[chn->ctxv.size() + stop - 1];
int outn = tail->ow * tail->oh * tail->oc;
assert(outn > 0);
double *buf = new double[outn];
uint8_t *rgb = new uint8_t[outn];
double *dat = (double *)(client->inpbuf + 256);
enk(dat, inpn, chn->kinp());
assert(client->read(NULL, 256 + inpn * sizeof(double)));
info(fmt("synthing inpn=%d outn=%d", inpn, outn));
chn->synth(stop);
info("done with synth");
dek(tail->kout(), outn, buf);
if (pngout) {
for (int i = 0; i < outn; ++i)
rgb[i] = (uint8_t)clamp(buf[i] * 256.0, 0, 255);
assert(tail->oc == 3);
uint8_t *png;
unsigned long pngn;
rgbpng(rgb, tail->ow, tail->oh, &png, &pngn);
delete[] buf;
delete[] rgb;
if (!client->write(png, pngn))
return false;
} else {
if (!client->write((uint8_t *)buf, outn * sizeof(double)))
return false;
}
}
return true;
}
}
| 20.608333 | 138 | 0.59078 | jdb19937 |
b0d7ef07b20683853f6b0946d548c3d0a3ec98b4 | 6,910 | cc | C++ | stig/indy/disk/util/stig_dm.cc | ctidder/stigdb | d9ef3eb117d46542745ca98c55df13ec71447091 | [
"Apache-2.0"
] | 5 | 2018-04-24T12:36:50.000Z | 2020-03-25T00:37:17.000Z | stig/indy/disk/util/stig_dm.cc | ctidder/stigdb | d9ef3eb117d46542745ca98c55df13ec71447091 | [
"Apache-2.0"
] | null | null | null | stig/indy/disk/util/stig_dm.cc | ctidder/stigdb | d9ef3eb117d46542745ca98c55df13ec71447091 | [
"Apache-2.0"
] | 2 | 2018-04-24T12:39:24.000Z | 2020-03-25T00:45:08.000Z | /* <stig/indy/disk/util/stig_dm.cc>
The 'main' of the Stig disk manager.
Copyright 2010-2014 Tagged
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 <iostream>
#include <base/booster.h>
#include <base/cmd.h>
#include <base/log.h>
#include <stig/indy/disk/util/disk_util.h>
using namespace std;
using namespace chrono;
using namespace Base;
using namespace Stig::Indy::Fiber;
using namespace Stig::Indy::Disk;
using namespace Stig::Indy::Disk::Util;
/* Command-line arguments. */
class TCmd final
: public Base::TLog::TCmd {
public:
/* Construct with defaults. */
TCmd()
: ZeroSuperBlock(false),
List(false),
CreateVolume(false),
InstanceName(""),
VolumeKind("Stripe"),
DeviceSpeed(""),
NumDevicesInVolume(0UL),
ReplicationFactor(1UL),
StripeSizeKB(64),
ReadTest(false) {}
/* Construct from argc/argv. */
TCmd(int argc, char *argv[])
: TCmd() {
Parse(argc, argv, TMeta());
}
/* If true, clear the superblock of the provided devices */
bool ZeroSuperBlock;
/* If true, then list all the devices. */
bool List;
/* If true, then create a new volume. */
bool CreateVolume;
std::string InstanceName;
std::string VolumeKind;
std::string DeviceSpeed;
size_t NumDevicesInVolume;
size_t ReplicationFactor;
size_t StripeSizeKB;
/* If true, perform a read test on the specified instance volume */
bool ReadTest;
/* The device set. */
std::set<std::string> DeviceSet;
private:
/* Our meta-type. */
class TMeta final
: public Base::TLog::TCmd::TMeta {
public:
/* Registers our fields. */
TMeta()
: Base::TLog::TCmd::TMeta("Stig disk utility") {
Param(
&TCmd::ZeroSuperBlock, "zero-super-block", Optional, "zero-super-block\0",
"Zero out the super block of the provded devices."
);
Param(
&TCmd::ReadTest, "read-test", Optional, "read-test\0",
"Perform a read test on the specified instance volume. (Not Implemented)"
);
Param(
&TCmd::List, "list", Optional, "list\0l\0",
"List all the devices on this system."
);
Param(
&TCmd::CreateVolume, "create-volume", Optional, "create-volume\0cb\0",
"Create a new volume."
);
Param(
&TCmd::InstanceName, "instance-name", Optional, "instance-name\0iname\0",
"The instance name used for the newly created volume."
);
Param(
&TCmd::VolumeKind, "strategy", Optional, "strategy\0strat\0",
"(stripe | chain). The strategy used when creating a new volume."
);
Param(
&TCmd::DeviceSpeed, "device-speed", Optional, "device-speed\0speed\0",
"(fast | slow). The speed of the devices used in creating a new volume."
);
Param(
&TCmd::NumDevicesInVolume, "num-devices", Optional, "num-devices\0nd\0",
"The number of device names expected when creating a new volume."
);
Param(
&TCmd::ReplicationFactor, "replication-factor", Optional, "replication-factor\0rf\0",
"The replication factor used when creating a new volume."
);
Param(
&TCmd::StripeSizeKB, "stripe-size", Optional, "stripe-size\0",
"The stripe size (in KB) used when creating a new striped volume."
);
Param(
&TCmd::DeviceSet, "dev", Optional, /*"dev\0",*/
"The list of devices on which to act."
);
}
}; // TCmd::TMeta
}; // TCmd
int main(int argc, char *argv[]) {
::TCmd cmd(argc, argv);
Base::TLog log(cmd);
Base::TScheduler scheduler(Base::TScheduler::TPolicy(1, 64, milliseconds(10)));
if(cmd.ZeroSuperBlock) {
const auto &device_set = cmd.DeviceSet;
for (const auto &device : device_set) {
string device_path = "/dev/" + device;
TDeviceUtil::ZeroSuperBlock(device_path.c_str());
}
return EXIT_SUCCESS;
} else if (cmd.ReadTest) {
throw std::logic_error("Read test is not implemented");
}
Util::TCacheCb cache_cb = [](TCacheInstr /*cache_instr*/, const TOffset /*logical_start_offset*/, void */*buf*/, size_t /*count*/) {};
TDiskController controller;
TDiskUtil disk_util(&scheduler, &controller, Base::TOpt<std::string>(), cache_cb, true);
if (cmd.List) {
stringstream ss;
//disk_util.List(ss);
cout << ss.str();
cout << "Device\t\tStigFS\tVolumeId\tVolume Device #\t# Devices in Volume\tLogical Extent Start\tLogical Extent Size\tVolume Kind\tInstance Name" << endl;
TDeviceUtil::ForEachDevice([](const char *path) {
TDeviceUtil::TStigDevice device_info;
string path_to_device = "/dev/";
path_to_device += path;
bool ret = TDeviceUtil::ProbeDevice(path_to_device.c_str(), device_info);
cout << "/dev/" << path << "\t";
if (ret) {
cout << "YES\t[" << string(device_info.VolumeId.InstanceName) << ", " << device_info.VolumeId.Id << "]"
<< "\t" << device_info.VolumeDeviceNumber
<< "\t" << device_info.NumDevicesInVolume
<< "\t" << device_info.LogicalExtentStart
<< "\t" << device_info.LogicalExtentSize
<< "\t";
switch (device_info.VolumeStrategy) {
case 1UL: {
cout << "Stripe";
break;
}
case 2UL: {
cout << "Chain";
break;
}
}
}
cout << endl;
return true;
});
return EXIT_SUCCESS;
} else if (cmd.CreateVolume) {
TVolume::TDesc::TKind strategy;
TVolume::TDesc::TStorageSpeed speed;
if (strncmp(cmd.VolumeKind.c_str(), "stripe", 5) == 0) {
strategy = TVolume::TDesc::Striped;
} else if (strncmp(cmd.VolumeKind.c_str(), "chain", 4) == 0) {
strategy = TVolume::TDesc::Chained;
} else {
throw std::runtime_error("strategy must be (stripe | chain)");
}
if (strncmp(cmd.DeviceSpeed.c_str(), "fast", 4) == 0) {
speed = TVolume::TDesc::TStorageSpeed::Fast;
} else if (strncmp(cmd.DeviceSpeed.c_str(), "slow", 4) == 0) {
speed = TVolume::TDesc::TStorageSpeed::Slow;
} else {
throw std::runtime_error("device speed must be (fast | slow)");
}
disk_util.CreateVolume(cmd.InstanceName, cmd.NumDevicesInVolume, cmd.DeviceSet, strategy, cmd.ReplicationFactor, cmd.StripeSizeKB, speed);
}
}
| 33.221154 | 158 | 0.618958 | ctidder |
b0e0e9c86e1475f700fae7a1fb276e7bf76f751f | 19,105 | cpp | C++ | kittycat/catcontainer.cpp | siilky/catomania | cb3a05cbef523d16b8929b390e190e0cd5924ee9 | [
"MIT"
] | 1 | 2021-02-05T23:20:07.000Z | 2021-02-05T23:20:07.000Z | kittycat/catcontainer.cpp | siilky/catomania | cb3a05cbef523d16b8929b390e190e0cd5924ee9 | [
"MIT"
] | null | null | null | kittycat/catcontainer.cpp | siilky/catomania | cb3a05cbef523d16b8929b390e190e0cd5924ee9 | [
"MIT"
] | null | null | null |
#include "stdafx.h"
#include <QMimeData>
#include <QVector>
#include "catcontainer.h"
CatContainer::CatContainer(const JsonValue & config, CatGroup *parent)
: TreeItem(parent)
, config_(config)
, cat_(new CatCtl(config))
, catView_(new CatView(cat_))
{
std::wstring tag;
config.get(L"Tag", tag);
tag_ = QString::fromStdWString(tag);
}
CatContainer::CatContainer(const CatContainer &r, CatGroup *parent)
: TreeItem(parent)
, config_(r.config_)
, tag_(r.tag_)
, cat_(r.cat_)
, catView_(r.catView_)
{
}
CatContainer::operator JsonValue &()
{
config_.set(L"Tag", tag_.toStdWString());
return config_;
}
int CatContainer::columnCount() const
{
return 1;
}
int CatContainer::row() const
{
if (parent_ != NULL)
{
CatGroup *cg = static_cast<CatGroup*>(parent_);
for (int i = 0; i < cg->cats_.count(); i++)
{
if (*cg->cats_[i] == *this)
{
return i;
}
}
}
return -1;
}
QVariant CatContainer::data(int column, int role) const
{
if (column != 0)
{
return QVariant();
}
switch (role)
{
case Qt::DecorationRole:
{
if ( ! catView_)
{
return QVariant();
}
CatView::CatState state = catView_->state();
switch (state)
{
case CatView::Offline: return QIcon(":/catView/door_16.png");
case CatView::Online: return QIcon(":/catView/door_open_16.png");
case CatView::Locked: return QIcon(":/catView/lock_16.png");
case CatView::MarketOpened: return QIcon(":/catView/cat.png");
case CatView::Dead: return QIcon(":/catView/pirate_flag_16.png");
case CatView::Waiting: return QIcon(":/catView/time.png");
}
break;
}
case Qt::DisplayRole:
case Qt::EditRole:
{
if ( ! tag_.isEmpty())
{
return tag_;
}
QString acc = catView_->currentAccount();
return acc.isEmpty() ? "[...]" : acc;
}
}
return QVariant();
}
bool CatContainer::setData(int column, const QVariant &value)
{
if (column == 0)
{
tag_ = value.toString();
return true;
}
return false;
}
CatGroup::CatGroup()
: TreeItem(NULL)
{
}
CatGroup::CatGroup(const CatGroup & r)
: TreeItem(NULL)
, tag_(r.tag_)
{
foreach(CatContainer *c, r.cats_)
{
cats_.push_back(new CatContainer(*c, this));
}
}
CatGroup::CatGroup(const JsonValue & config)
: TreeItem(NULL)
{
std::wstring tag;
config.get(L"Tag", tag);
tag_ = QString::fromStdWString(tag);
class CatConverter
{
public:
CatConverter(CatGroup * group)
: group_(group)
{}
CatContainer * convertIn(const JsonValue & v) const
{
return new CatContainer(v, group_);
}
private:
CatGroup * group_;
};
std::vector<CatContainer *> cats;
config.get(L"Cats", cats, CatConverter(this));
cats_ = QVector<CatContainer *>::fromStdVector(cats).toList();
}
CatGroup::~CatGroup()
{
qDeleteAll(cats_);
}
CatGroup::operator JsonValue()
{
JsonValue config;
config.set(L"Tag", tag_.toStdWString());
config.set(L"Cats", cats_.toVector().toStdVector(), json::TransparentPtrConversion<CatContainer>());
return config;
}
int CatGroup::rowCount() const
{
return cats_.count();
}
TreeItem * CatGroup::child(int number)
{
if (number < 0 || number >= cats_.count())
{
return NULL;
}
return cats_[number];
}
int CatGroup::columnCount() const
{
return 1;
}
QVariant CatGroup::data(int column, int role) const
{
if (column != 0)
{
return QVariant();
}
switch(role)
{
case Qt::DecorationRole:
return QIcon(":/multiView/reseller_programm.png");
case Qt::DisplayRole:
case Qt::EditRole:
return tag_.isEmpty() ? "..." : tag_;
}
return QVariant();
}
bool CatGroup::setData(int column, const QVariant &value)
{
if (column == 0)
{
tag_ = value.toString();
return true;
}
return false;
}
bool CatGroup::insertChildren(int position, int count)
{
if (position < 0 || position > cats_.size())
{
return false;
}
for (int row = 0; row < count; ++row)
{
cats_.insert(position, new CatContainer(JsonValue(), this));
}
return true;
}
bool CatGroup::removeChildren(int position, int count)
{
if (position < 0 || position > cats_.size())
{
return false;
}
while (position < cats_.count() && count > 0)
{
CatContainer *cat = cats_.takeAt(position);
delete cat;
count--;
}
return true;
}
//
CatTreeModel::~CatTreeModel()
{
qDeleteAll(groups_);
}
void CatTreeModel::setCats(const QList<CatGroup*> & cats)
{
beginResetModel();
// qDeleteAll(groups_);
// groups_.clear();
groups_ = cats;
endResetModel();
/*
if ( ! cats.isEmpty())
{
beginInsertRows(QModelIndex(), 0, cats.count());
endInsertRows();
}
*/
}
void CatTreeModel::loadItem(const QString & filename, int row, const QModelIndex & parent)
{
JsonValue jscfg;
if (jscfg.loadFrom(filename.toStdWString())
&& jscfg.isObject())
{
beginInsertRows(parent, row, row);
TreeItem *parentItem = getItem(parent);
if (parentItem != NULL)
{
CatGroup *cg = dynamic_cast<CatGroup*>(parentItem);
if (cg != NULL)
{
if (jscfg.contains(L"Client"))
{
// old-style configuration
cg->cats_.insert(row, new CatContainer(jscfg.get(L"Client"), cg));
}
else
{
cg->cats_.insert(row, new CatContainer(jscfg, cg));
}
}
}
else
{
// no parent, top-level
// TBD groups_.insert(position, new CatGroup());
}
endInsertRows();
}
}
bool CatTreeModel::canBeSaved(const QModelIndex & item)
{
TreeItem * i = getItem(item);
if (i != NULL)
{
CatContainer *cc = dynamic_cast<CatContainer *>(i);
return cc != NULL;
}
return false;
}
void CatTreeModel::saveItem(const QString & filename, const QModelIndex & item)
{
TreeItem * i = getItem(item);
if (i != NULL)
{
CatContainer *cc = dynamic_cast<CatContainer *>(i);
if (cc != NULL)
{
cc->operator JsonValue &().saveTo(filename.toStdWString());
}
}
}
//
QModelIndex CatTreeModel::index(int row, int column, const QModelIndex &parent /*= QModelIndex()*/) const
{
if (parent.isValid() && parent.column() != 0)
{
return QModelIndex();
}
TreeItem *parentItem = getItem(parent);
if (parentItem != NULL)
{
TreeItem *childItem = parentItem->child(row);
if (childItem != NULL)
{
return createIndex(row, column, childItem);
}
}
else
{
// no parent, top-level
if (row < groups_.count())
{
return createIndex(row, column, groups_[row]);
}
}
return QModelIndex();
}
QModelIndex CatTreeModel::parent(const QModelIndex &index) const
{
if (!index.isValid())
{
return QModelIndex();
}
TreeItem *item = getItem(index);
if (item != NULL)
{
TreeItem *parentItem = item->parent();
if (parentItem != NULL)
{
// parent of not top-level item
int pos = groups_.indexOf(static_cast<CatGroup*>(parentItem));
return createIndex(pos, 0, parentItem);
}
}
return QModelIndex();
}
int CatTreeModel::rowCount(const QModelIndex &parent /*= QModelIndex()*/) const
{
TreeItem *parentItem = getItem(parent);
if (parentItem != NULL)
{
return parentItem->rowCount();
}
else
{
// top-level
return groups_.count();
}
}
int CatTreeModel::columnCount(const QModelIndex &parent /*= QModelIndex()*/) const
{
TreeItem *parentItem = getItem(parent);
if (parentItem != NULL)
{
if (parentItem->rowCount() > 0)
{
return parentItem->child(0)->columnCount();
}
}
else
{
// top-level
if (groups_.count() > 0)
{
return groups_[0]->columnCount();
}
}
return 0;
}
QVariant CatTreeModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
{
return QVariant();
}
switch(role)
{
case Qt::DecorationRole:
case Qt::DisplayRole:
case Qt::EditRole:
{
TreeItem *item = getItem(index);
if (item != 0)
{
return item->data(index.column(), role);
}
break;
}
case CatItemRole:
{
TreeItem *item = getItem(index);
if (item != 0)
{
return QVariant::fromValue((void*)item);
}
break;
}
}
return QVariant();
}
QVariant CatTreeModel::headerData(int /*section*/, Qt::Orientation /*orientation*/, int /*role*/ /*= Qt::DisplayRole*/) const
{
return QVariant();
}
bool CatTreeModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (role != Qt::EditRole)
{
return false;
}
TreeItem *item = getItem(index);
bool result = item->setData(index.column(), value);
if (result)
{
emit dataChanged(index, index);
}
return result;
}
Qt::ItemFlags CatTreeModel::flags(const QModelIndex &index) const
{
return Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsDragEnabled
| ((index.isValid() && index.parent().isValid()) ? 0 : Qt::ItemIsDropEnabled)
| /*((index.isValid() && index.parent().isValid()) ? */Qt::ItemIsSelectable/* : 0)*/;
}
Qt::DropActions CatTreeModel::supportedDropActions() const
{
return Qt::MoveAction | Qt::CopyAction;
}
bool CatTreeModel::insertRows(int position, int rows, const QModelIndex &parent /*= QModelIndex()*/)
{
beginInsertRows(parent, position, position + rows - 1);
bool success = false;
TreeItem *parentItem = getItem(parent);
if (parentItem != NULL)
{
success = parentItem->insertChildren(position, rows);
}
else
{
// no parent, top-level
groups_.insert(position, new CatGroup());
}
endInsertRows();
return success;
}
bool CatTreeModel::removeRows(int position, int rows, const QModelIndex &parent /*= QModelIndex()*/)
{
if (position < 0)
{
return false;
}
beginRemoveRows(parent, position, position + rows - 1);
bool success = true;
TreeItem *parentItem = getItem(parent);
if (parentItem != NULL)
{
success = parentItem->removeChildren(position, rows);
}
else
{
// no parent, top-level
while (position < groups_.count() && rows > 0)
{
CatGroup *cg = groups_.takeAt(position);
delete cg;
rows--;
}
}
endRemoveRows();
return success;
}
TreeItem *CatTreeModel::getItem(const QModelIndex & index) const
{
if (index.isValid())
{
TreeItem *item = static_cast<TreeItem*>(index.internalPointer());
return item;
}
else
{
// top-level items
return NULL;
}
}
QStringList CatTreeModel::mimeTypes() const
{
return QStringList()
<< "application/x-catmodeldatalist"
<< "text/uri-list";
}
QMimeData * CatTreeModel::mimeData(const QModelIndexList & indexes) const
{
if (indexes.count() <= 0)
{
return NULL;
}
QByteArray encoded;
QDataStream stream(&encoded, QIODevice::WriteOnly);
for (QModelIndexList::ConstIterator it = indexes.begin(); it != indexes.end(); ++it)
{
TreeItem *item = static_cast<TreeItem*>(it->internalPointer());
TreeItem *parent= static_cast<TreeItem*>(it->parent().internalPointer());
if (parent == NULL)
{
// group level
CatGroup *cg = static_cast<CatGroup*>(item);
stream << false << groups_.indexOf(cg);
}
else
{
// cat level
CatContainer *cc = static_cast<CatContainer*>(item);
CatGroup *cg = static_cast<CatGroup*>(parent);
stream << true << groups_.indexOf(cg) << cc->row();
}
}
QString format = mimeTypes().at(0);
QMimeData *data = new QMimeData();
data->setData(format, encoded);
return data;
}
bool CatTreeModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex & parent)
{
QStringList types = mimeTypes();
if (!data
|| types.isEmpty()
|| (data->hasFormat(types.at(0)) && action != Qt::MoveAction)
|| (data->hasFormat(types.at(1)) && action != Qt::CopyAction))
{
return false;
}
if (column == -1)
column = 0;
// move to
// - empty space: parent=-1 row=-1
// - on group: parent=group row=-1
// - below group: parent=-1 row=nextGroup
// - above group: parent=-1 row=group
// - on cat: parent=cat row=-1
// - between cats: parent=group row=cat
if (data->hasFormat(types.at(0)))
{
QByteArray encoded = data->data(types.at(0));
QDataStream stream(&encoded, QIODevice::ReadOnly);
bool isCat;
int fromGroup;
stream >> isCat >> fromGroup;
if (isCat)
{
// moving cat to other group or within group
int fromRow;
stream >> fromRow;
QModelIndex fromIdx = index(fromRow, 0, index(fromGroup, 0, QModelIndex()));
QModelIndex toGroupIdx = parent;
int toRow = 0;
if (parent.parent().isValid()) // directly to cat
{
toRow = parent.row();
toGroupIdx = parent.parent();
if (toRow > fromRow && toGroupIdx.row() >= fromGroup)
{
toRow++;
}
}
else if (parent.isValid() && row >= 0) // between cats; row < 0 : directly to groups
{
toRow = row;
}
else if (parent.isValid() && row < 0) // directly on group
{
TreeItem *item = (TreeItem *)parent.internalPointer();
toRow = item->rowCount();
}
else if (row < 0) // && ! parent.isValid() // to empty space
{
if ( ! groups_.isEmpty())
{
toGroupIdx = index(groups_.count() - 1, 0, QModelIndex());
toRow = groups_[toGroupIdx.row()]->rowCount();
}
}
else // row >= 0 && !parent.isValid() // group level between groups
{
if ( ! groups_.isEmpty())
{
toGroupIdx = index(row > 0 ? row - 1 : row, 0, QModelIndex());
toRow = groups_[toGroupIdx.row()]->rowCount();
}
}
beginInsertRows(toGroupIdx, toRow, toRow);
groups_[toGroupIdx.row()]->put(toRow, new CatContainer(*groups_[fromGroup]->cats_[fromRow], groups_[toGroupIdx.row()]));
endInsertRows();
}
else
{
// moving/reordering groups
int toRow;
if (parent.parent().isValid()) // directly to cat
{
toRow = parent.parent().row();
}
else if (parent.isValid()) // row >= 0 : between cats; row < 0 : directly on group
{
toRow = parent.row();
}
else if (row < 0) // && ! parent.isValid() // to empty space
{
toRow = groups_.count();
}
else // row >= 0 && !parent.isValid() // group level between groups
{
toRow = row;
}
// 'down' direction should increment index by 1
if (toRow > fromGroup
&& !(row >= 0 && !parent.isValid()))
{
toRow++;
}
beginInsertRows(QModelIndex(), toRow, toRow);
groups_.insert(toRow, new CatGroup(*groups_[fromGroup]));
endInsertRows();
}
}
else if (data->hasFormat(types.at(1)))
{
// QByteArray encoded = data->data(types.at(1));
// QString filename = QString::fromWCharArray((wchar_t*)encoded.data(), encoded.count() / sizeof(wchar_t));
QModelIndex toGroupIdx = parent;
int toRow = 0;
if (parent.parent().isValid()) // directly to cat
{
toRow = parent.row();
toGroupIdx = parent.parent();
}
else if (parent.isValid() && row >= 0) // between cats; row < 0 : directly to groups
{
toRow = row;
}
else if (parent.isValid() && row < 0) // directly on group
{
TreeItem *item = (TreeItem *)parent.internalPointer();
toRow = item->rowCount();
}
else if (row < 0) // && ! parent.isValid() // to empty space
{
if ( ! groups_.isEmpty())
{
toGroupIdx = index(groups_.count() - 1, 0, QModelIndex());
toRow = groups_[toGroupIdx.row()]->rowCount();
}
}
else // row >= 0 && !parent.isValid() // group level between groups
{
if ( ! groups_.isEmpty())
{
toGroupIdx = index(row > 0 ? row - 1 : row, 0, QModelIndex());
toRow = groups_[toGroupIdx.row()]->rowCount();
}
}
QList<QUrl> urlList = data->urls();
for (int i = 0; i < urlList.size(); ++i)
{
loadItem(urlList[i].toLocalFile(), toRow++, toGroupIdx);
}
}
return true;
}
void CatTreeModel::itemUpdate(CatView * w)
{
// TBD should be a tree-like
for (int i = 0; i < groups_.count(); i++)
{
// QModelIndex index = groups_[i]->indexOf(w);
QModelIndex index;
const QList<CatContainer*> & cats_ = groups_.at(i)->cats_;
for (int c = 0; c < cats_.count(); c++)
{
if (cats_[c]->catView() == w)
{
index = createIndex(c, 0, cats_[c]);
break;
}
}
if (index.isValid())
{
emit dataChanged(index, index);
break;
}
}
}
| 24.462228 | 132 | 0.521853 | siilky |
b0e43d3b2a34cd1f30259295f2b66697ee18e1cf | 3,737 | cc | C++ | main.cc | tamerfrombk/gbdsm | 098798c934de124a7a3b7a37dd67e5de83644b7e | [
"MIT"
] | null | null | null | main.cc | tamerfrombk/gbdsm | 098798c934de124a7a3b7a37dd67e5de83644b7e | [
"MIT"
] | null | null | null | main.cc | tamerfrombk/gbdsm | 098798c934de124a7a3b7a37dd67e5de83644b7e | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <limits>
#include "ops.h"
#include "common.h"
#include "dasm.h"
static void print_help()
{
std::printf("gbdsm %s -- The GameBoy ROM disassembler.\n", GBDSM_VERSION);
std::putchar('\n');
std::puts("Usage: gbdsm '/path/to/rom.gb' [-h] [-b address] [-e address] [--linear | --recursive]");
std::putchar('\n');
std::puts("Optional arguments:");
std::puts("-h show this help message and exit.");
std::puts("-b address set the starting address for the disassembler in decimal. Defaults to 0x0.");
std::puts("-e address set the end address for the disassembler in decimal. Defaults to the end of ROM.");
std::puts("--linear use the linear sweep algorithm for disassembly. This algorithm is the default.");
std::puts("--recursive use the recursive search algorithm for disassembly.");
}
static size_t fsize(std::FILE *file)
{
size_t curr = std::ftell(file);
std::fseek(file, 0, SEEK_END);
size_t size = std::ftell(file);
std::fseek(file, curr, SEEK_SET);
return size;
}
static gbdsm::Rom read_rom(const char* path)
{
std::FILE *file = std::fopen(path, "rb");
if (!file) {
return gbdsm::Rom{};
}
size_t fileSize = fsize(file);
gbdsm::Rom rom(fileSize, 0);
size_t bytesRead = std::fread(rom.data(), sizeof(uint8_t), fileSize, file);
if (bytesRead != fileSize) {
std::fclose(file);
return gbdsm::Rom{};
}
std::fclose(file);
return rom;
}
struct Args {
std::string rom_path;
size_t begin, end;
gbdsm::DisassemblerAlgo algo;
bool print_help;
};
static Args parse_args(int argc, char **argv)
{
Args args;
if (argc < 2) {
return args;
}
if (std::strcmp("-h", argv[1]) == 0) {
args.print_help = true;
return args;
}
args.rom_path = argv[1];
args.begin = 0;
args.end = std::numeric_limits<size_t>::max();
args.print_help = false;
args.algo = gbdsm::DisassemblerAlgo::LINEAR_SWEEP;
for (int i = 2; i < argc;) {
if (std::strcmp(argv[i], "-b") == 0) {
args.begin = std::stoull(argv[i + 1]);
i += 2;
}
else if (std::strcmp(argv[i], "-e") == 0) {
args.end = std::stoull(argv[i + 1]);
i += 2;
}
else if (std::strcmp(argv[i], "-h") == 0) {
args.print_help = true;
++i;
}
else if (std::strcmp(argv[i], "--linear") == 0) {
args.algo = gbdsm::DisassemblerAlgo::LINEAR_SWEEP;
++i;
}
else if (std::strcmp(argv[i], "--recursive") == 0) {
args.algo = gbdsm::DisassemblerAlgo::RECURSIVE_SEARCH;
++i;
}
else {
gbdsm::error("Unrecognized argument %s.\n", argv[i]);
std::exit(1);
}
}
return args;
}
int main(int argc, char **argv)
{
Args args = parse_args(argc, argv);
if (args.print_help) {
print_help();
return 0;
}
if (args.rom_path.empty()) {
gbdsm::error("The GameBoy ROM file was not supplied.\n");
return 1;
}
if (args.end < args.begin) {
gbdsm::error("The end (%zu) cannot be less than the beginning (%zu).\n",
args.end, args.begin);
return 1;
}
auto rom = read_rom(args.rom_path.c_str());
if (rom.empty()) {
gbdsm::error("Could not read %s.\n", args.rom_path.c_str());
return 1;
}
if (args.end > rom.size()) {
args.end = rom.size();
}
auto dasm = gbdsm::create_dasm(rom, args.algo);
dasm->disassemble(args.begin, args.end);
}
| 24.585526 | 112 | 0.552047 | tamerfrombk |
b0e67c98e7e73e9500e520a0d9084a414f5cbcc7 | 2,621 | hh | C++ | src/systems/AudioSystem.hh | rovedit/Fort-Candle | 445fb94852df56c279c71b95c820500e7fb33cf7 | [
"MIT"
] | null | null | null | src/systems/AudioSystem.hh | rovedit/Fort-Candle | 445fb94852df56c279c71b95c820500e7fb33cf7 | [
"MIT"
] | null | null | null | src/systems/AudioSystem.hh | rovedit/Fort-Candle | 445fb94852df56c279c71b95c820500e7fb33cf7 | [
"MIT"
] | null | null | null | #pragma once
#include <algorithm>
#include <glow/fwd.hh>
#include "glow/common/log.hh"
#include "ecs/Engine.hh"
#include "ecs/System.hh"
#include "AL/al.h"
#include "AL/alc.h"
#include "typed-geometry/tg.hh"
#include "utility/Sound.hh"
namespace gamedev
{
class AudioSystem : public System
{
public:
void Init(std::shared_ptr<EngineECS>& ecs);
void AddEntity(InstanceHandle& handle, Signature entitySignature);
void RemoveEntity(InstanceHandle& handle, Signature entitySignature);
void RemoveEntity(InstanceHandle& handle);
void RemoveAllEntities();
void Update(float dt);
void UpdateListener(tg::pos3 position, tg::vec3 forward, tg::vec3 velocity = {0, 0, 0});
void SetMasterVolume(float value);
void SetVolume(int type, float value);
void PlayLocalSound(InstanceHandle handle,
std::string name,
SoundType type = effect,
float volume = 1.0f,
bool looping = false,
float minRadius = 1.f,
float maxRadius = 50.f,
SoundPriority priority = low);
void PlayLocalSound(tg::pos3 position,
std::string name,
SoundType type = effect,
float volume = 1.0f,
bool looping = false,
float minRadius = 1.f,
float maxRadius = 50.f,
SoundPriority priority = low);
void PlayGlobalSound(std::string name, SoundType type = effect, float volume = 1.0f, bool looping = false, SoundPriority priority = low);
void LoadSounds();
void destroy();
private:
void UpdateSoundState(InstanceHandle handle, float dt);
void CullEmitters(InstanceHandle handle);
void CleanupLocalEmitters();
void AttachSource(InstanceHandle handle, OALSource* s);
void DetachSource(InstanceHandle handle);
void DetachSources(vector<InstanceHandle>::iterator from, vector<InstanceHandle>::iterator to);
void AttachSources(vector<InstanceHandle>::iterator from, vector<InstanceHandle>::iterator to);
OALSource* GetSource();
bool CompareNodesByPriority(InstanceHandle handle1, InstanceHandle handle2);
std::shared_ptr<EngineECS> mECS;
unsigned int channels;
float masterVolume;
std::vector<float> volumes;
std::vector<OALSource*> sources;
tg::pos3 mListenerPosition;
vector<InstanceHandle> emitters;
vector<InstanceHandle> mLocalEmitters;
ALCcontext* context;
ALCdevice* device;
};
}
| 28.802198 | 141 | 0.636398 | rovedit |
b0e76565499e49fd0da413f8b1c38cf0f93e2bca | 2,558 | cpp | C++ | Frame/OpenGL/Test/StaticMeshTest.cpp | anirul/Frame | 6bf93cc032cc53eb9f9c94965f4b7e795812fa13 | [
"MIT"
] | null | null | null | Frame/OpenGL/Test/StaticMeshTest.cpp | anirul/Frame | 6bf93cc032cc53eb9f9c94965f4b7e795812fa13 | [
"MIT"
] | 1 | 2021-02-24T08:59:22.000Z | 2021-02-24T08:59:22.000Z | Frame/OpenGL/Test/StaticMeshTest.cpp | anirul/Frame | 6bf93cc032cc53eb9f9c94965f4b7e795812fa13 | [
"MIT"
] | null | null | null | #include "StaticMeshTest.h"
#include <GL/glew.h>
#include "Frame/BufferInterface.h"
#include "Frame/File/FileSystem.h"
#include "Frame/OpenGL/File/LoadStaticMesh.h"
#include "Frame/Level.h"
namespace test {
TEST_F(StaticMeshTest, CreateCubeMeshTest)
{
EXPECT_EQ(GLEW_OK, glewInit());
ASSERT_TRUE(window_);
auto level = std::make_unique<frame::Level>();
auto maybe_mesh_vec = frame::opengl::file::LoadStaticMeshesFromFile(
level.get(),
frame::file::FindFile("Asset/Model/Cube.obj"),
"cube");
ASSERT_TRUE(maybe_mesh_vec);
auto mesh_vec = maybe_mesh_vec.value();
auto node_id = mesh_vec.at(0);
auto node = level->GetSceneNodeFromId(node_id);
ASSERT_TRUE(node);
auto static_mesh_id = node->GetLocalMesh();
EXPECT_NE(0, static_mesh_id);
frame::StaticMeshInterface* static_mesh =
level->GetStaticMeshFromId(static_mesh_id);
EXPECT_EQ(1, mesh_vec.size());
EXPECT_TRUE(static_mesh);
EXPECT_EQ(0, static_mesh->GetMaterialId());
EXPECT_NE(0, static_mesh->GetPointBufferId());
EXPECT_NE(0, static_mesh->GetNormalBufferId());
EXPECT_NE(0, static_mesh->GetTextureBufferId());
EXPECT_NE(0, static_mesh->GetIndexBufferId());
auto id = static_mesh->GetIndexBufferId();
auto index_buffer = level->GetBufferFromId(id);
EXPECT_LE(18, index_buffer->GetSize());
EXPECT_GE(144, index_buffer->GetSize());
EXPECT_TRUE(static_mesh);
}
TEST_F(StaticMeshTest, CreateTorusMeshTest)
{
EXPECT_EQ(GLEW_OK, glewInit());
EXPECT_TRUE(window_);
auto level = std::make_unique<frame::Level>();
auto maybe_mesh_vec = frame::opengl::file::LoadStaticMeshesFromFile(
level.get(),
frame::file::FindFile("Asset/Model/Torus.obj"),
"torus");
ASSERT_TRUE(maybe_mesh_vec);
auto mesh_vec = maybe_mesh_vec.value();
EXPECT_EQ(1, mesh_vec.size());
auto node_id = mesh_vec.at(0);
auto node = level->GetSceneNodeFromId(node_id);
auto static_mesh_id = node->GetLocalMesh();
EXPECT_NE(0, static_mesh_id);
frame::StaticMeshInterface* static_mesh =
level->GetStaticMeshFromId(static_mesh_id);
ASSERT_TRUE(static_mesh);
EXPECT_EQ(0, static_mesh->GetMaterialId());
EXPECT_NE(0, static_mesh->GetPointBufferId());
EXPECT_NE(0, static_mesh->GetNormalBufferId());
EXPECT_NE(0, static_mesh->GetTextureBufferId());
EXPECT_NE(0, static_mesh->GetIndexBufferId());
auto id = static_mesh->GetIndexBufferId();
auto index_buffer = level->GetBufferFromId(id);
EXPECT_LE(3456, index_buffer->GetSize());
EXPECT_GE(13824, index_buffer->GetSize());
EXPECT_TRUE(static_mesh);
}
} // End namespace test.
| 33.657895 | 70 | 0.738468 | anirul |
b0f0c9e511948015e676815f65d9fe47a9908ab2 | 1,514 | hpp | C++ | src/binary/bin_wrappers.hpp | kbentum/LPLANN | c526113e583058c3b9f4ea5ef5ccc7d5a9d658d3 | [
"MIT"
] | null | null | null | src/binary/bin_wrappers.hpp | kbentum/LPLANN | c526113e583058c3b9f4ea5ef5ccc7d5a9d658d3 | [
"MIT"
] | null | null | null | src/binary/bin_wrappers.hpp | kbentum/LPLANN | c526113e583058c3b9f4ea5ef5ccc7d5a9d658d3 | [
"MIT"
] | null | null | null | #ifndef BINWRAPPERS_HPP
#define BINWRAPPERS_HPP
#include <vector>
#include <memory>
#include <math.h>
#include "src/construction/layer.hpp"
#include "src/binary/conv.hpp"
#include "src/binary/fc.hpp"
#include "src/ops/print.hpp"
//In general, we always assume a function has binary input and output, not reg
template <typename T1>
void conv2d_wrapper(Layer<T1> & in_layer, Layer<binary16> & out_layer, int slice){
float2bin_conv(in_layer, out_layer, slice);
}
template <typename T1>
void conv2d_wrapper(Layer<T1> & in_layer, Layer<binary16> & out_layer){
float2bin_conv(in_layer, out_layer);
}
void conv2d_wrapper(Layer<binary16> & in_layer, Layer<binary16> & out_layer){
bin2reg_conv_prep(in_layer, out_layer);
reg2bin_conv(in_layer, out_layer);
}
void fc_wrapper(Layer<binary16> & in_layer, Layer<binary16> & out_layer){
binary16 * arr = out_layer.output->arr;
binary16 * in = in_layer.output->arr;
bin2reg_fc_prep(in_layer);
reg2int_fc(in_layer, out_layer);
int2bin_fc_prep(out_layer);
}
void fc_output_wrapper(Layer<binary16> & in_layer, Layer<binary16> & out_layer){
bin2reg_fc_prep(in_layer);
reg2int_fc(in_layer, out_layer);
}
void bin2float_wrapper(Layer<binary16> & in_layer, Layer<float> & out_layer){
int size = 1;
for (int i=0; i < in_layer.output->dims.size(); i++){
size *= in_layer.output->dims[i];
}
for (int i = 0; i < size; i++){
out_layer.output->arr[i] = in_layer.output->arr[i] * -2 + 1.0;
}
}
#endif
| 27.527273 | 82 | 0.703435 | kbentum |
b0f1752b1ca9f4c019ec0e0f115d547f9ff1574b | 3,172 | cpp | C++ | Tridor/src/Log/AppLog.cpp | AzadKshitij/Triger | 969dbead69f5ebc40d8ef6bc9ec9d763c4510ecb | [
"MIT"
] | 2 | 2020-10-25T15:51:46.000Z | 2020-11-10T15:06:22.000Z | Tridor/src/Log/AppLog.cpp | AzadKshitij/Triger | 969dbead69f5ebc40d8ef6bc9ec9d763c4510ecb | [
"MIT"
] | 3 | 2020-11-11T16:54:49.000Z | 2020-11-29T14:35:31.000Z | Tridor/src/Log/AppLog.cpp | AzadKshitij/Triger | 969dbead69f5ebc40d8ef6bc9ec9d763c4510ecb | [
"MIT"
] | null | null | null | #include "AppLog.h"
namespace Triger
{
void AppLog::Clear()
{
m_Buf.clear();
m_LineOffsets.clear();
m_LineOffsets.push_back(0);
}
void AppLog::OnImGuiRender()
{
/*if (!ImGui::Begin(title, p_open))
{
ImGui::End();
return;
}*/
// Options menu
if (ImGui::BeginPopup("Options"))
{
ImGui::Checkbox("Auto-scroll", &m_AutoScroll);
ImGui::EndPopup();
}
// Main window
if (ImGui::Button("Options"))
ImGui::OpenPopup("Options");
ImGui::SameLine();
bool clear = ImGui::Button("Clear");
ImGui::SameLine();
bool copy = ImGui::Button("Copy");
ImGui::SameLine();
m_Filter.Draw("Filter", -100.0f);
ImGui::Separator();
ImGui::BeginChild("scrolling", ImVec2(0, 0), false, ImGuiWindowFlags_HorizontalScrollbar);
if (clear)
Clear();
if (copy)
ImGui::LogToClipboard();
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));
const char* buf = m_Buf.begin();
const char* buf_end = m_Buf.end();
if (m_Filter.IsActive())
{
for (int line_no = 0; line_no < m_LineOffsets.Size; line_no++)
{
const char* line_start = buf + m_LineOffsets[line_no];
const char* line_end = (line_no + 1 < m_LineOffsets.Size) ? (buf + m_LineOffsets[line_no + 1] - 1) : buf_end;
if (m_Filter.PassFilter(line_start, line_end))
ImGui::TextUnformatted(line_start, line_end);
}
}
else
{
ImGuiListClipper clipper;
clipper.Begin(m_LineOffsets.Size);
while (clipper.Step())
{
for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)
{
const char* line_start = buf + m_LineOffsets[line_no];
const char* line_end = (line_no + 1 < m_LineOffsets.Size) ? (buf + m_LineOffsets[line_no + 1] - 1) : buf_end;
ImGui::TextUnformatted(line_start, line_end);
}
}
clipper.End();
}
ImGui::PopStyleVar();
if (m_AutoScroll && ImGui::GetScrollY() >= ImGui::GetScrollMaxY())
ImGui::SetScrollHereY(1.0f);
ImGui::EndChild();
ImGui::End();
}
void AppLog::ShowExampleAppLog( )
{
static AppLog log;
// For the demo: add a debug button _BEFORE_ the normal log window contents
// We take advantage of a rarely used feature: multiple calls to Begin()/End() are appending to the _same_ window.
// Most of the contents of the window will be added by the log.Draw() call.
ImGui::SetNextWindowSize(ImVec2(500, 400), ImGuiCond_FirstUseEver);
ImGui::Begin("Logs");
if (ImGui::SmallButton("[Debug] Add 5 entries"))
{
static int counter = 0;
const char* categories[3] = { "info", "warn", "error" };
const char* words[] = { "Bumfuzzled", "Cattywampus", "Snickersnee", "Abibliophobia", "Absquatulate", "Nincompoop", "Pauciloquent" };
for (int n = 0; n < 5; n++)
{
const char* category = categories[counter % IM_ARRAYSIZE(categories)];
const char* word = words[counter % IM_ARRAYSIZE(words)];
log.AddLog("[%05d] [%s] Hello, current time is %.1f, here's a word: '%s'\n",
ImGui::GetFrameCount(), category, ImGui::GetTime(), word);
counter++;
}
}
// Actually call in the regular Log helper (which will Begin() into the same window as we just did)
log.OnImGuiRender( );
ImGui::End();
}
}
| 28.321429 | 135 | 0.6529 | AzadKshitij |
b0f8934becf2b16425721328c498fc05bb52bbd1 | 49 | hpp | C++ | libraries/protocol/include/offer/protocol/protocol.hpp | nharan/offer | 9d26f480a7d3009969b2b06c0cd2e83772f52c25 | [
"MIT"
] | null | null | null | libraries/protocol/include/offer/protocol/protocol.hpp | nharan/offer | 9d26f480a7d3009969b2b06c0cd2e83772f52c25 | [
"MIT"
] | null | null | null | libraries/protocol/include/offer/protocol/protocol.hpp | nharan/offer | 9d26f480a7d3009969b2b06c0cd2e83772f52c25 | [
"MIT"
] | null | null | null | #pragma once
#include <offer/protocol/block.hpp>
| 16.333333 | 35 | 0.77551 | nharan |
b0f943d10c768e22f9de9aeeef3c86f9b543356e | 822 | cpp | C++ | 8.二叉树的下一个结点/8.二叉树的下一个结点.cpp | shenweichen/coding_interviews | 990cc54a62b8fa277b743289e8d6f6e96a95225d | [
"MIT"
] | 483 | 2020-01-05T12:58:59.000Z | 2022-03-19T05:44:00.000Z | 8.二叉树的下一个结点/8.二叉树的下一个结点.py | moshilangzi/coding_interviews | 990cc54a62b8fa277b743289e8d6f6e96a95225d | [
"MIT"
] | 1 | 2020-01-20T08:47:15.000Z | 2020-01-27T13:24:15.000Z | 8.二叉树的下一个结点/8.二叉树的下一个结点.py | moshilangzi/coding_interviews | 990cc54a62b8fa277b743289e8d6f6e96a95225d | [
"MIT"
] | 122 | 2020-01-05T14:10:04.000Z | 2022-03-19T05:24:42.000Z | /*
struct TreeLinkNode {
int val;
struct TreeLinkNode *left;
struct TreeLinkNode *right;
struct TreeLinkNode *next;
TreeLinkNode(int x) :val(x), left(NULL), right(NULL), next(NULL) {
}
};
*/
class Solution {
public:
TreeLinkNode* GetNext(TreeLinkNode* pNode)
{
if (pNode->right != nullptr){
TreeLinkNode *p = pNode->right;
while(p->left != nullptr){
p = p->left;
}
return p;
}
while(pNode->next!=nullptr){
if(isLeftChild(pNode))
return pNode->next;
pNode = pNode->next;
}
return nullptr;
}
bool isLeftChild(TreeLinkNode* p){
if(p->next!=nullptr && p->next->left == p)
return true;
else
return false;
}
}; | 22.833333 | 70 | 0.512165 | shenweichen |
b0fd1a632a37aa3bfb58fd3a6d009f1f672a7c9a | 994 | cpp | C++ | src/hello_imgui/widgets/logger.cpp | jhoffmann2/hello_imgui | 7430223491de1ee12b4e3c30cc430d026ae10d62 | [
"MIT"
] | 245 | 2020-06-21T10:06:45.000Z | 2022-03-24T04:43:23.000Z | src/hello_imgui/widgets/logger.cpp | jhoffmann2/hello_imgui | 7430223491de1ee12b4e3c30cc430d026ae10d62 | [
"MIT"
] | 19 | 2020-06-22T22:06:25.000Z | 2021-09-05T12:28:44.000Z | src/hello_imgui/widgets/logger.cpp | jhoffmann2/hello_imgui | 7430223491de1ee12b4e3c30cc430d026ae10d62 | [
"MIT"
] | 36 | 2020-06-20T04:42:54.000Z | 2022-03-29T10:55:20.000Z | #include "hello_imgui/widgets/logger.h"
namespace HelloImGui
{
namespace Widgets
{
Logger::Logger(std::string label_, DockSpaceName dockSpaceName_)
: DockableWindow(label_, dockSpaceName_, {})
, log_(logBuffer_, maxBufferSize)
{
this->GuiFonction = [this]() {
log_.draw();
};
}
void Logger::debug(char const* const format, ...)
{
va_list args;
va_start(args, format);
log_.debug(format, args);
va_end(args);
}
void Logger::info(char const* const format, ...)
{
va_list args;
va_start(args, format);
log_.info(format, args);
va_end(args);
}
void Logger::warning(char const* const format, ...)
{
va_list args;
va_start(args, format);
log_.warning(format, args);
va_end(args);
}
void Logger::error(char const* const format, ...)
{
va_list args;
va_start(args, format);
log_.error(format, args);
va_end(args);
}
void Logger::clear()
{
log_.clear();
}
} // namespace Widgets
} // namespace HelloImGui
| 19.115385 | 64 | 0.645875 | jhoffmann2 |
b0fe257dc68660f61f07cf6370abb386d9d89965 | 577 | cpp | C++ | src/client/src/InkEditorModel.cpp | don-reba/peoples-note | c22d6963846af833c55f4294dd0474e83344475d | [
"BSD-2-Clause"
] | null | null | null | src/client/src/InkEditorModel.cpp | don-reba/peoples-note | c22d6963846af833c55f4294dd0474e83344475d | [
"BSD-2-Clause"
] | null | null | null | src/client/src/InkEditorModel.cpp | don-reba/peoples-note | c22d6963846af833c55f4294dd0474e83344475d | [
"BSD-2-Clause"
] | null | null | null | #include "stdafx.h"
#include "InkEditorModel.h"
#include "IRegistryKey.h"
InkEditorModel::InkEditorModel
( IRegistryKey & registryKey
)
: registryKey (registryKey)
{
}
void InkEditorModel::GetPen
( std::wstring & width
, std::wstring & color
)
{
width = registryKey.GetString(L"pen width", L"1px");
color = registryKey.GetString(L"pen color", L"black");
}
void InkEditorModel::SetPen
( const wchar_t * width
, const wchar_t * color
)
{
registryKey.SetString(L"pen width", width);
registryKey.SetString(L"pen color", color);
}
| 19.233333 | 56 | 0.670711 | don-reba |
7c000c1959c00a89b9a7a760e596ebe108aac7f0 | 2,416 | cpp | C++ | CubeEngine/Application/CubeGame/Gun/FPGun.cpp | tangziwen/Cube-Engine | c79b878dcc7e2e382f4463ca63519627d6220afd | [
"MIT"
] | 360 | 2015-01-26T08:15:01.000Z | 2021-07-11T16:30:58.000Z | CubeEngine/Application/CubeGame/Gun/FPGun.cpp | tangziwen/Cube-Engine | c79b878dcc7e2e382f4463ca63519627d6220afd | [
"MIT"
] | 6 | 2015-03-09T09:15:07.000Z | 2020-07-06T01:34:00.000Z | CubeEngine/Application/CubeGame/Gun/FPGun.cpp | tangziwen/CubeMiniGame | 90bffa66d4beba5fddc39fc642a8fb36703cf32d | [
"MIT"
] | 41 | 2015-03-10T03:17:46.000Z | 2021-07-13T06:26:26.000Z | #include "FPGun.h"
#include "CubeGame/BulletMgr.h"
#include "CubeGame/GameUISystem.h"
#include "Lighting/PointLight.h"
#include "Scene/SceneMgr.h"
#include "AudioSystem/AudioSystem.h"
namespace tzw
{
FPGun::FPGun(FPGunData * gunData):
m_data(gunData)
{
m_model = Model::create(m_data->m_filePath);
m_model->setPos(0.12,0.6, -0.22);
m_model->setRotateE(m_data->m_rotateE);
m_model->setScale(vec3(m_data->m_scale, m_data->m_scale, m_data->m_scale));
m_model->setIsAccpectOcTtree(false);
auto pointLight = new PointLight();
pointLight->setRadius(5);
pointLight->setLightColor(vec3(5, 2.5, 0));
pointLight->setPos(vec3(-33.408, 0, 0));
pointLight->setIsVisible(false);
m_pointLight = pointLight;
g_GetCurrScene()->addNode(pointLight);
m_fireSound = AudioSystem::shared()->createSound("Sound/m4a1.wav");
}
void FPGun::setIsADS(bool isADS, bool isNeedTransient)
{
if(isADS && !m_data->m_isAllowADS)//not allowed aim down sight
return;
m_isAds = isADS;
if(m_isAds)
{
GameUISystem::shared()->setIsNeedShowCrossHair(false);
}
else
{
GameUISystem::shared()->setIsNeedShowCrossHair(true);
}
}
void FPGun::toggleADS(bool isNeedTransient)
{
setIsADS(!m_isAds, isNeedTransient);
}
void FPGun::tick(bool isMoving, float dt)
{
if(m_pointLight->getIsVisible())
{
m_flashTime += dt;
if(m_flashTime > 0.035)
{
m_pointLight->setIsVisible(false);
m_flashTime = 0.0;
}
}
float offset = 0.002;
if(m_isAds)
{
offset = 0.0005;
}
float freq = 1.2;
if (isMoving)
{
if(m_isAds)
{
offset = 0.0008;
}
else
{
offset = 0.006;
}
freq = 8;
}
m_shakeTime += freq * dt;
if(m_isAds)
{
m_model->setPos(vec3(m_data->m_adsPos.x, m_data->m_adsPos.y + sinf(m_shakeTime) * offset, m_data->m_adsPos.z));
}
else
{
m_model->setPos(vec3(m_data->m_hipPos.x, m_data->m_hipPos.y + sinf(m_shakeTime) * offset, m_data->m_hipPos.z));
}
}
void FPGun::shoot()
{
auto cam = g_GetCurrScene()->defaultCamera();
auto mdata = cam->getTransform().data();
vec3 gunPointPos = m_model->getTransform().transformVec3(vec3(-33.408,0, 0));
auto bullet = BulletMgr::shared()->fire(nullptr,cam->getWorldPos() ,gunPointPos, cam->getForward(), 15, BulletType::HitScanTracer);
m_pointLight->setIsVisible(true);
m_pointLight->setPos(cam->getWorldPos() + cam->getForward() * 0.15);
m_flashTime = 0.0;
auto event = m_fireSound->playWithOutCare();
event.setVolume(1.2f);
}
}
| 23.009524 | 132 | 0.695364 | tangziwen |
7c0049b4a77f51a230bd957d365651322e605be4 | 132 | cpp | C++ | src/main.cpp | borninla/R-Shell | 72b35fdb5ef7cba23791c65045a8b2bf0272321b | [
"MIT"
] | null | null | null | src/main.cpp | borninla/R-Shell | 72b35fdb5ef7cba23791c65045a8b2bf0272321b | [
"MIT"
] | null | null | null | src/main.cpp | borninla/R-Shell | 72b35fdb5ef7cba23791c65045a8b2bf0272321b | [
"MIT"
] | null | null | null | #include <iostream>
#include "../header/manager.h"
using namespace std;
int main()
{
Manager m;
m.run();
return 0;
}
| 10.153846 | 30 | 0.598485 | borninla |
7c0649e1ccdc5efa9bae15d7d181ec1eef88d889 | 1,630 | cpp | C++ | src/MapEditor/UnitEditor/UnitDlg.cpp | vitek-karas/WarPlusPlus | 3abb26ff30dc0e93de906ab6141b89c2fa301ae4 | [
"MIT"
] | 4 | 2019-06-17T13:44:49.000Z | 2021-01-19T10:39:48.000Z | src/MapEditor/UnitEditor/UnitDlg.cpp | vitek-karas/WarPlusPlus | 3abb26ff30dc0e93de906ab6141b89c2fa301ae4 | [
"MIT"
] | null | null | null | src/MapEditor/UnitEditor/UnitDlg.cpp | vitek-karas/WarPlusPlus | 3abb26ff30dc0e93de906ab6141b89c2fa301ae4 | [
"MIT"
] | 4 | 2019-06-17T16:03:20.000Z | 2020-02-15T09:14:30.000Z | // UnitDlg.cpp : implementation file
//
#include "stdafx.h"
#include "..\MapEditor.h"
#include "UnitDlg.h"
#include "..\DataObjects\EMap.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CUnitDlg
IMPLEMENT_DYNAMIC(CUnitDlg, CPropertySheet)
CUnitDlg::CUnitDlg(UINT nIDCaption, CWnd* pParentWnd, UINT iSelectPage)
:CPropertySheet(nIDCaption, pParentWnd, iSelectPage)
{
}
CUnitDlg::CUnitDlg(LPCTSTR pszCaption, CWnd* pParentWnd, UINT iSelectPage)
:CPropertySheet(pszCaption, pParentWnd, iSelectPage)
{
}
CUnitDlg::~CUnitDlg()
{
}
BEGIN_MESSAGE_MAP(CUnitDlg, CPropertySheet)
//{{AFX_MSG_MAP(CUnitDlg)
// NOTE - the ClassWizard will add and remove mapping macros here.
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CUnitDlg message handlers
void CUnitDlg::Create(CEUnitType *pUnitType, CEMap *pMap)
{
ASSERT_VALID(pUnitType);
ASSERT_VALID(pMap);
m_pUnitType = pUnitType;
m_pMap = pMap;
// we have to load all appearances into the memory
// so do it
m_pUnitType->LoadGraphics();
m_MainPage.Create(m_pUnitType);
AddPage(&m_MainPage);
m_ModesPage.Create(m_pUnitType);
AddPage(&m_ModesPage);
m_AppearancePage.Create(m_pUnitType);
AddPage(&m_AppearancePage);
m_LandTypesPage.Create(m_pUnitType, m_pMap);
AddPage(&m_LandTypesPage);
m_SkillsPage.Create(m_pUnitType);
AddPage(&m_SkillsPage);
}
void CUnitDlg::Delete()
{
// clear the unit appearances
m_pUnitType->ReleaseGraphics();
}
| 22.027027 | 77 | 0.678528 | vitek-karas |
7c09ee479bcf6a832ed5af7a14a248b03e62786c | 3,749 | cpp | C++ | MCMF_Template.cpp | vicennial/Competitive-Coding-Library | 48e338ca5f572d44d8f4224cdb373bb0cab5b856 | [
"MIT"
] | 1 | 2019-02-20T06:44:04.000Z | 2019-02-20T06:44:04.000Z | MCMF_Template.cpp | vicennial/Competitive-Coding-Library | 48e338ca5f572d44d8f4224cdb373bb0cab5b856 | [
"MIT"
] | null | null | null | MCMF_Template.cpp | vicennial/Competitive-Coding-Library | 48e338ca5f572d44d8f4224cdb373bb0cab5b856 | [
"MIT"
] | null | null | null | //Gvs Akhil (Vicennial)
#include<bits/stdc++.h>
#define int long long
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define mt make_tuple
#define ld(a) while(a--)
#define tci(v,i) for(auto i=v.begin();i!=v.end();i++)
#define tcf(v,i) for(auto i : v)
#define all(v) v.begin(),v.end()
#define rep(i,start,lim) for(long long (i)=(start);i<(lim);i++)
#define sync ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define osit ostream_iterator
#define INF 0x3f3f3f3f
#define LLINF 1000111000111000111LL
#define PI 3.14159265358979323
#define endl '\n'
#define trace1(x) cerr<<#x<<": "<<x<<endl
#define trace2(x, y) cerr<<#x<<": "<<x<<" | "<<#y<<": "<<y<<endl
#define trace3(x, y, z) cerr<<#x<<":" <<x<<" | "<<#y<<": "<<y<<" | "<<#z<<": "<<z<<endl
#define trace4(a, b, c, d) cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<endl
#define trace5(a, b, c, d, e) cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<< ": "<<e<<endl
#define trace6(a, b, c, d, e, f) cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<< ": "<<e<<" | "<<#f<<": "<<f<<endl
const int N=1000006;
using namespace std;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef long long ll;
typedef vector<long long> vll;
typedef vector<vll> vvll;
typedef long double ld;
typedef pair<int,int> ii;
typedef vector<ii> vii;
typedef vector<vii> vvii;
typedef tuple<int,int,int> iii;
typedef set<int> si;
typedef complex<double> pnt;
typedef vector<pnt> vpnt;
typedef priority_queue<ii,vii,greater<ii> > spq;
const ll MOD=1000000007LL;
template<typename T> T gcd(T a,T b){if(a==0) return b; return gcd(b%a,a);}
template<typename T> T power(T x,T y,ll m=MOD){T ans=1;while(y>0){if(y&1LL) ans=(ans*x)%m;y>>=1LL;x=(x*x)%m;}return ans%m;}
const int mxN = 40;
const int inf = 2e9;
struct Edgee {
int to, cost, cap, flow, backEdge;
};
struct MCMF {
int s, t, n;
vector<Edgee> g[mxN];
MCMF(int _s, int _t, int _n) { // source,sink, total nodes
s = _s, t = _t, n = _n;
}
void addEdge(int u, int v, int cost, int cap) { // src,dest,cost,capacity
Edgee e1 = { v, cost, cap, 0, g[v].size() };
Edgee e2 = { u, -cost, 0, 0, g[u].size() };
g[u].push_back(e1); g[v].push_back(e2);
}
pair<int, int> minCostMaxFlow() {
int flow = 0, cost = 0;
vector<int> state(n), from(n), from_edge(n), d(n);
deque<int> q;
while (true) {
for (int i = 0; i < n; i++)
state[i] = 2, d[i] = inf, from[i] = -1;
state[s] = 1; q.clear(); q.push_back(s); d[s] = 0;
while (!q.empty()) {
int v = q.front(); q.pop_front(); state[v] = 0;
for (int i = 0; i < (int) g[v].size(); i++) {
Edgee e = g[v][i];
if (e.flow >= e.cap || d[e.to] <= d[v] + e.cost)
continue;
int to = e.to; d[to] = d[v] + e.cost;
from[to] = v; from_edge[to] = i;
if (state[to] == 1) continue;
if (!state[to] || (!q.empty() && d[q.front()] > d[to]))
q.push_front(to);
else q.push_back(to);
state[to] = 1;
}
}
if (d[t] == inf) break;
int it = t, addflow = inf;
while (it != s) {
addflow = min(addflow,
g[from[it]][from_edge[it]].cap
- g[from[it]][from_edge[it]].flow);
it = from[it];
}
it = t;
while (it != s) {
g[from[it]][from_edge[it]].flow += addflow;
g[it][g[from[it]][from_edge[it]].backEdge].flow -= addflow;
cost += g[from[it]][from_edge[it]].cost * addflow;
it = from[it];
}
flow += addflow;
}
return {cost,flow};
}
};
main(){
} | 35.704762 | 157 | 0.516671 | vicennial |
7c0ae2ece9247caf1221df2fc8b40c45c9ea0978 | 449 | hpp | C++ | bridge_graph.hpp | ibaned/omega_h_v1 | 9ab9efca33d66e4411f87206a7bd1534cec116e4 | [
"MIT"
] | null | null | null | bridge_graph.hpp | ibaned/omega_h_v1 | 9ab9efca33d66e4411f87206a7bd1534cec116e4 | [
"MIT"
] | null | null | null | bridge_graph.hpp | ibaned/omega_h_v1 | 9ab9efca33d66e4411f87206a7bd1534cec116e4 | [
"MIT"
] | null | null | null | #ifndef BRIDGE_GRAPH_HPP
#define BRIDGE_GRAPH_HPP
namespace omega_h {
void bridge_graph(
unsigned nverts,
unsigned const* adj_offsets,
unsigned const* adj,
unsigned* nedges_out,
unsigned** verts_of_edges_out);
void bridge_dual_graph(
unsigned elem_dim,
unsigned nelems,
unsigned const* elems_of_elems,
unsigned* nsides_out,
unsigned** elems_of_sides_out,
unsigned** elem_side_of_sides_out);
}
#endif
| 18.708333 | 39 | 0.737194 | ibaned |
7c125a1bf1323b388cbb4a8620cbecbaa69084dd | 6,035 | cpp | C++ | src/midiutils/midiread.cpp | alexames/midiutils | 12ac041c3f2f472473755c46f5f6306e02c2b564 | [
"Unlicense"
] | null | null | null | src/midiutils/midiread.cpp | alexames/midiutils | 12ac041c3f2f472473755c46f5f6306e02c2b564 | [
"Unlicense"
] | null | null | null | src/midiutils/midiread.cpp | alexames/midiutils | 12ac041c3f2f472473755c46f5f6306e02c2b564 | [
"Unlicense"
] | null | null | null | #include "midiutils.hpp"
#include <fstream>
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////////////////////
namespace midi
{
static unsigned int readUInt32be(istream& in)
{
char data[4];
in.read(data, 4);
return (static_cast<unsigned char>(data[0]) << 24)
| (static_cast<unsigned char>(data[1]) << 16)
| (static_cast<unsigned char>(data[2]) << 8)
| static_cast<unsigned char>(data[3]);
}
static unsigned short readUInt16be(istream& in)
{
char data[2];
in.read(static_cast<char*>(data), 2);
return (static_cast<unsigned char>(data[0]) << 8)
| static_cast<unsigned char>(data[1]);
}
////////////////////////////////////////////////////////////////////////////////
static bool isTrackEnd(const Event& event)
{
return event.command == Event::Meta
&& event.meta.command == Event::MetaEvent::EndOfTrack;
}
static void readEventTime(unsigned int& out, istream& in, unsigned int& byteCount)
{
out = 0;
unsigned char byte;
do
{
byte = in.get();
out <<= 7;
out += byte & 0x7f;
if (--byteCount == 0)
{
throw exception();
}
} while (byte & 0x80);
}
static void readNoteEndEvent(Event::NoteEndEvent& event, istream& in, unsigned int& byteCount)
{
event.noteNumber = in.get();
event.velocity = in.get();
byteCount -= 2;
}
static void readNoteBeginEvent(Event::NoteBeginEvent& event, istream& in, unsigned int& byteCount)
{
event.noteNumber = in.get();
event.velocity = in.get();
byteCount -= 2;
}
static void readVelocityChangeEvent(Event::VelocityChangeEvent& event, istream& in, unsigned int& byteCount)
{
event.noteNumber = in.get();
event.velocity = in.get();
byteCount -= 2;
}
static void readControllerChangeEvent(Event::ControllerChangeEvent& event, istream& in, unsigned int& byteCount)
{
event.controllerNumber = in.get();
event.velocity = in.get();
byteCount -= 2;
}
static void readProgramChangeEvent(Event::ProgramChangeEvent& event, istream& in, unsigned int& byteCount)
{
event.newProgramNumber = in.get();
byteCount -= 1;
}
static void readChannelPressureChangeEvent(Event::ChannelPressureChangeEvent& event, istream& in, unsigned int& byteCount)
{
event.channelNumber = in.get();
byteCount -= 1;
}
static void readPitchWheelChangeEvent(Event::PitchWheelChangeEvent& event, istream& in, unsigned int& byteCount)
{
event.bottom = in.get();
event.top = in.get();
byteCount -= 2;
}
static void readMetaEvent(Event::MetaEvent& event, istream& in, unsigned int& byteCount)
{
event.command = static_cast<Event::MetaEvent::MetaCommand>(in.get());
unsigned int length = event.length = in.get();
byteCount -= 2 + event.length;
event.data = (char*)malloc(event.length);
for (unsigned int i = 0; i < length; i++)
event.data[i] = in.get();
}
unsigned char readEventCommand(istream& in, unsigned char& previousCommandByte, unsigned int& byteCount)
{
unsigned char commandByte = in.peek();
if (commandByte & 0x80)
{
--byteCount;
return in.get();
}
else
{
return previousCommandByte;
}
}
static bool readEvent(Event& event, istream& in, unsigned int& byteCount, unsigned char& previousCommandByte, bool strict)
{
readEventTime(event.timeDelta, in, byteCount);
unsigned char commandByte = readEventCommand(in, previousCommandByte, byteCount);
previousCommandByte = commandByte;
event.command = static_cast<Event::Command>(commandByte & 0xF0);
event.channel = commandByte & 0x0F;
switch(event.command)
{
case Event::NoteEnd:
readNoteEndEvent(event.noteEnd, in, byteCount);
break;
case Event::NoteBegin:
readNoteBeginEvent(event.noteBegin, in, byteCount);
break;
case Event::VelocityChange:
readVelocityChangeEvent(event.velocityChange, in, byteCount);
break;
case Event::ControllerChange:
readControllerChangeEvent(event.controllerChange, in, byteCount);
break;
case Event::ProgramChange:
readProgramChangeEvent(event.programChange, in, byteCount);
break;
case Event::ChannelPressureChange:
readChannelPressureChangeEvent(event.channelPressureChange, in, byteCount);
break;
case Event::PitchWheelChange:
readPitchWheelChangeEvent(event.pitchWheelChange, in, byteCount);
break;
case Event::Meta:
readMetaEvent(event.meta, in, byteCount);
if (isTrackEnd(event))
{
if (strict && (byteCount != 0))
{
throw exception("Invalid track length");
}
else
{
return false;
}
}
break;
default:
throw exception("Invalid midi event");
}
return true;
}
static void readTrack(Track& track, istream& in, bool strict)
{
if (readUInt32be(in) != 'MTrk')
{
throw exception("Invalid midi track header");
}
unsigned int byteCount = readUInt32be(in);
unsigned char previousCommand = 0;
if (byteCount || !strict)
{
do
{
track.events.push_back(Event());
} while (readEvent(track.events.back(), in, byteCount, previousCommand, strict));
}
}
void readFile(MidiFile& midi, istream& in, bool strict)
{
if (readUInt32be(in) != 'MThd' || readUInt32be(in) != 0x0006)
{
throw exception("Invalid midi header");
}
midi.format = static_cast<Format>(readUInt16be(in));
midi.tracks.resize(readUInt16be(in));
midi.ticks = readUInt16be(in);
for (Track& track : midi.tracks)
{
readTrack(track, in, strict);
}
}
} // namespace midi | 28.738095 | 123 | 0.60116 | alexames |
7c1612776c03d383b17ff57dfd67c9bffced3cb6 | 516 | cpp | C++ | compendium/test_bundles/ManagedServiceAndFactoryBundle/src/ManagedServiceFactoryServiceImpl.cpp | fmilano/CppMicroServices | b7e79edb558a63e45f6788e4a8b4e787cf956689 | [
"Apache-2.0"
] | 588 | 2015-10-07T15:55:08.000Z | 2022-03-29T00:35:44.000Z | compendium/test_bundles/ManagedServiceAndFactoryBundle/src/ManagedServiceFactoryServiceImpl.cpp | fmilano/CppMicroServices | b7e79edb558a63e45f6788e4a8b4e787cf956689 | [
"Apache-2.0"
] | 459 | 2015-10-05T23:29:59.000Z | 2022-03-29T14:13:37.000Z | compendium/test_bundles/ManagedServiceAndFactoryBundle/src/ManagedServiceFactoryServiceImpl.cpp | fmilano/CppMicroServices | b7e79edb558a63e45f6788e4a8b4e787cf956689 | [
"Apache-2.0"
] | 218 | 2015-11-04T08:19:48.000Z | 2022-03-24T02:17:08.000Z | #include "ManagedServiceFactoryServiceImpl.hpp"
namespace cppmicroservices {
namespace service {
namespace cm {
namespace test {
TestManagedServiceFactoryServiceImpl::TestManagedServiceFactoryServiceImpl(
int initialValue)
: value{ initialValue }
{}
TestManagedServiceFactoryServiceImpl::~TestManagedServiceFactoryServiceImpl() =
default;
int TestManagedServiceFactoryServiceImpl::getValue()
{
return value;
}
} // namespace test
} // namespace cm
} // namespace service
} // namespace cppmicroservices
| 20.64 | 79 | 0.800388 | fmilano |
7c1dc825ae6fba53a1fb46f42f03168f1c4d15c6 | 13,663 | cpp | C++ | src/executors/sort.cpp | ShubhamAgrawal-13/Relational_Database | 5d315633742df18eda6952d286cf86501d93ed58 | [
"MIT"
] | null | null | null | src/executors/sort.cpp | ShubhamAgrawal-13/Relational_Database | 5d315633742df18eda6952d286cf86501d93ed58 | [
"MIT"
] | null | null | null | src/executors/sort.cpp | ShubhamAgrawal-13/Relational_Database | 5d315633742df18eda6952d286cf86501d93ed58 | [
"MIT"
] | null | null | null | #include"global.h"
const int SORT_MAX = 1e5+5;
int temp[SORT_MAX];
// bool isDigit(char ch) {
// if (ch >= '0' && ch <= '9')
// return true;
// return false;
// }
/**
* @brief File contains method to process SORT commands.
*
* syntax:
* R <- SORT relation_name BY column_name IN sorting_order
*
* sorting_order = ASC | DESC
*/
bool syntacticParseSORT(){
logger.log("syntacticParseSORT");
if(tokenizedQuery.size()== 10){
if(tokenizedQuery[4] != "BY" || tokenizedQuery[6] != "IN" || tokenizedQuery[8] != "BUFFER"){
cout<<"SYNTAX ERROR"<<endl;
return false;
}
parsedQuery.queryType = SORT;
parsedQuery.sortResultRelationName = tokenizedQuery[0];
parsedQuery.sortColumnName = tokenizedQuery[5];
parsedQuery.sortRelationName = tokenizedQuery[3];
string sortingStrateg = tokenizedQuery[7];
parsedQuery.sortBuffer = tokenizedQuery[9];
string str = tokenizedQuery[9];
for (int i = 0; i < str.length(); i++) {
if (!(str[i] >= '0' && str[i] <= '9')) {
cout<<"SYNTAX ERROR : Buffer should be an Integer"<<endl;
return false;
}
}
if(sortingStrateg == "ASC")
parsedQuery.sortingStrategy = ASC;
else if(sortingStrateg == "DESC")
parsedQuery.sortingStrategy = DESC;
else{
cout<<"SYNTAX ERROR : sorting strategy should be only ASC or DESC"<<endl;
return false;
}
return true;
}
else if(tokenizedQuery.size()== 8){
if(tokenizedQuery[4] != "BY" || tokenizedQuery[6] != "IN"){
cout<<"SYNTAX ERROR"<<endl;
return false;
}
parsedQuery.queryType = SORT;
parsedQuery.sortResultRelationName = tokenizedQuery[0];
parsedQuery.sortColumnName = tokenizedQuery[5];
parsedQuery.sortRelationName = tokenizedQuery[3];
string sortingStrateg = tokenizedQuery[7];
if(sortingStrateg == "ASC")
parsedQuery.sortingStrategy = ASC;
else if(sortingStrateg == "DESC")
parsedQuery.sortingStrategy = DESC;
else{
cout<<"SYNTAX ERROR"<<endl;
return false;
}
return true;
}
cout<<"SYNTAX ERROR"<<endl;
return false;
}
bool semanticParseSORT(){
logger.log("semanticParseSORT");
if(tableCatalogue.isTable(parsedQuery.sortResultRelationName)){
cout<<"SEMANTIC ERROR: Resultant relation already exists"<<endl;
return false;
}
if(!tableCatalogue.isTable(parsedQuery.sortRelationName)){
cout<<"SEMANTIC ERROR: Relation doesn't exist " << parsedQuery.sortRelationName <<endl;
return false;
}
if(!tableCatalogue.isColumnFromTable(parsedQuery.sortColumnName, parsedQuery.sortRelationName)){
cout<<"SEMANTIC ERROR: Column doesn't exist in relation"<<endl;
return false;
}
return true;
}
/**
* @brief Merging Function
*
* @param a { array which is to be sorted}
* @param[in] l { lower index }
* @param[in] m { mid index }
* @param[in] r { higher index }
*/
void merging(vector<int> &a, int l, int m, int r){
memset(temp, 0, sizeof(temp));
int i=l;
int j=m+1;
int k=l;
while(i<=m && j<=r){
if(a[i]>a[j])
temp[k++]=a[j++];
else
temp[k++]=a[i++];
}
while(i<=m)
temp[k++]=a[i++];
while(j<=r)
temp[k++]=a[j++];
for(int i=l;i<=r;i++)
a[i]=temp[i];
}
/**
* @brief General Merge Sort Algorithm
*
* @param a { array which is to be sorted}
* @param[in] l { lower index }
* @param[in] r { higher index }
*/
void mSort(vector<int> &a, int l, int r) {
if(l>=r)
return;
int m = l + (r - l)/2;
//left half
mSort(a, l, m);
//right half
mSort(a, m + 1, r);
//merging step
merging(a, l, m, r);
}
/**
* @brief Node for heap which is used to merge files.
*/
struct HeapNode{
int element;
string row;
int filePointer;
};
/**
* @brief Comparator for Min Heap
*/
struct comp_min{
bool operator()(const HeapNode &a, const HeapNode &b) const{
return a.element > b.element;
}
};
/**
* @brief Comparator for Max Heap
*/
struct comp_max{
bool operator()(const HeapNode &a, const HeapNode &b) const{
return a.element < b.element;
}
};
/**
* @brief Merge Files input files to a output file
*
* As k is Buffers available.
* So, k-1 buffers for input files
* and 1 buffer for output.
*
* @param[in] input_filenames The input filenames
* @param[in] output_filename The output filename
* @param[in] columnIndex The column index
* @param[in] flag The flag (ASC / DESC)
*/
void mergeFiles(vector<string> input_filenames, string output_filename, int columnIndex, int flag){
int k = input_filenames.size();
ifstream inputPointers[k];
ofstream outputPointer;
for(int i=0; i<k; i++){
inputPointers[i].open(input_filenames[i]);
}
outputPointer.open(output_filename);
if(flag==0){ //min
priority_queue<HeapNode, vector<HeapNode>, comp_min> min_heap;
for(int i=0; i<k; i++){
string line, word;
getline(inputPointers[i], line);
stringstream s(line);
vector<int> temp;
while(getline(s, word, ' ')){
temp.push_back(stoi(word));
}
min_heap.push({ temp[columnIndex], line, i});
}
while(!min_heap.empty()){
HeapNode node = min_heap.top();
min_heap.pop();
outputPointer << node.row <<"\n";
string line, word;
if(getline(inputPointers[node.filePointer], line)){
stringstream s(line);
vector<int> temp;
while(getline(s, word, ' ')){
temp.push_back(stoi(word));
}
min_heap.push({ temp[columnIndex], line, node.filePointer});
}
}
}
else{ //max
priority_queue<HeapNode, vector<HeapNode>, comp_max> max_heap;
for(int i=0; i<k; i++){
string line, word;
getline(inputPointers[i], line);
stringstream s(line);
vector<int> temp;
while(getline(s, word, ' ')){
temp.push_back(stoi(word));
}
max_heap.push({ temp[columnIndex], line, i});
}
while(!max_heap.empty()){
HeapNode node = max_heap.top();
max_heap.pop();
outputPointer << node.row <<"\n";
string line, word;
if(getline(inputPointers[node.filePointer], line)){
stringstream s(line);
vector<int> temp;
while(getline(s, word, ' ')){
temp.push_back(stoi(word));
}
max_heap.push({ temp[columnIndex], line, node.filePointer});
}
}
}
// Closing all file pointers
for(int i=0; i<k; i++){
inputPointers[i].close();
}
outputPointer.close();
}
/**
* @brief Phase 2 of merge sort i.e., merging
*
* @param[in] tableName The table name
* @param[in] blockCount The block count
* @param[in] columnIndex The column index
* @param[in] flag The flag (ASC / DESC)
* @param[in] k Buffer Size
*
* @return { return file output filename }
*/
string phase2(string tableName, int blockCount, int columnIndex, int flag, int k){
//buffers = k ( k-1 inputs and 1 output)
vector<string> files;
for(int i=0; i<blockCount; i++){
string pageName = "../data/temp/" + tableName + "_temp_Page" + to_string(i);
files.push_back(pageName);
}
int pass=1;
while(files.size()>1){
vector<string> files_output;
// int passes = ceil(blockCount/1.0*k);
int out=0; // number of output files
for(int i=0; i<files.size();){
int pp=0;
vector<string> inputs;
while(pp<k-1 && i<files.size()){
inputs.push_back(files[i]);
pp++;
i++;
}
string output_filename = "../data/temp/" + tableName + "_temp_Page_" + to_string(pass) + "_" + to_string(out);
mergeFiles(inputs, output_filename, columnIndex, flag);
files_output.push_back(output_filename);
out++;
}
//delete all files in files vector
for(string file : files){
if (remove(file.c_str())){
logger.log("SORT :: deleting temporary files : ERROR");
cout << "SORT :: deleting temporary files : ERROR";
}
else{
logger.log("SORT :: deleting temporary files : SUCCESS");
}
}
files.clear();
for(string s : files_output){
files.push_back(s);
}
files_output.clear();
pass++;
}
return files[0];
}
/**
* @brief Sort by Decreasing order
*
* @param[in] a { parameter_description }
* @param[in] b { parameter_description }
*
* @return { description_of_the_return_value }
*/
bool sortByDesc(const pair<int,int> &a, const pair<int,int> &b){
return a.first>b.first;
}
/**
* @brief Sorting one block
*
* @param[in] pageName The page name
* @param[in] columnIndex The column index
* @param[in] columnIndex The flag ASC or DESC
*/
void sortPage(string pageName, int columnIndex, int flag){
string line, word;
ifstream fin(pageName, ios::in);
vector<string> rows;
vector<pair<int, int>> res; // columnIndex, original index
int i=0;
while(getline(fin, line)){
stringstream s(line);
vector<int> temp;
while(getline(s, word, ' ')){
temp.push_back(stoi(word));
}
//cout<<temp[columnIndex]<<endl;
res.push_back({temp[columnIndex], i});
i++;
rows.push_back(line);
//cout<<line<<endl;
}
fin.close();
//cout<<"Read Successfullly\n";
if(flag==0)
sort(res.begin(), res.end());
else
sort(res.begin(), res.end(), sortByDesc);
ofstream fout(pageName, ios::trunc);
for (int r = 0; r < res.size(); r++){
auto p = res[r].second;
//cout<< rows[p] <<"\n";
fout << rows[p] <<"\n";
}
fout.close();
//cout<<"Written Successfullly\n";
}
/**
* @brief Doing phase 1 of 2 phase merge sort.
* Sorting individual pages.
*
* @param[in] tableName The table name
* @param[in] blockCount The block count
* @param[in] columnIndex The column index
* @param[in] columnIndex The flag ASC or DESC
*/
void phase1(string tableName, int blockCount, int columnIndex, int flag){
for(int i=0; i<blockCount; i++){
//string pageName = "../data/temp/" + tableName + "_Page" + to_string(i);
// cout<<pageName << endl;
string pageName1 = "../data/temp/" + tableName + "_Page" + to_string(i);
string pageName2 = "../data/temp/" + tableName + "_temp_Page" + to_string(i);
string cmd = "cp " + pageName1 + " " + pageName2;
system(cmd.c_str());
sortPage(pageName2, columnIndex, flag);
// cout<<"Sorted : "<<pageName<<endl;
}
}
// AA <- SORT S BY a IN ASC
// AA <- SORT S BY a IN DESC
void executeSORT(){
logger.log("executeSORT");
Table* table = tableCatalogue.getTable(parsedQuery.sortRelationName);
int k=5; //Initially Default buffers available
if(parsedQuery.sortBuffer != ""){
k = stoi(parsedQuery.sortBuffer);
}
// cout<< parsedQuery.sortRelationName <<endl;
// cout<< parsedQuery.sortResultRelationName <<endl;
// cout<< parsedQuery.sortColumnName <<endl;
// cout<< parsedQuery.sortingStrategy <<endl;
cout<<"Block Count : " << table->blockCount<<endl;
int columnIndex=0;
vector<string> cols = table->columns;
for(int i=0; i<cols.size(); i++){
//cout<< i <<" : "<<cols[i]<<endl;
if(cols[i] == parsedQuery.sortColumnName){
columnIndex = i;
break;
}
}
cout<< "Column Index : " << columnIndex << endl;
phase1(parsedQuery.sortRelationName, (int)table->blockCount, columnIndex, parsedQuery.sortingStrategy);
string output_filename = phase2(parsedQuery.sortRelationName, (int)table->blockCount, columnIndex, parsedQuery.sortingStrategy, k);
//blockify the large file
Table *resultantTable = new Table(parsedQuery.sortResultRelationName, table->columns);
string line, word;
ifstream fin(output_filename, ios::in);
while(getline(fin, line)){
stringstream s(line);
vector<int> row;
while(getline(s, word, ' ')){
row.push_back(stoi(word));
}
resultantTable->writeRow<int>(row);
}
fin.close();
resultantTable->blockify();
tableCatalogue.insertTable(resultantTable);
//delete temporary output file
if (remove(output_filename.c_str())){
logger.log("SORT :: deleting temporary files : ERROR");
cout << "SORT :: deleting temporary files : ERROR";
}
else{
logger.log("SORT :: deleting temporary files : SUCCESS");
}
cout<<"Sorting Completed\n";
return;
}
//added function | 27.826884 | 135 | 0.554344 | ShubhamAgrawal-13 |
7c268a74c47b7d848e1f5195fdab2ea183d3b7ae | 2,364 | cpp | C++ | FileFormats/Key/Key_Friendly.cpp | xloss/NWNFileFormats | 0b3fd4fba416bcdb79f4d898a40a4107234ceea0 | [
"WTFPL"
] | 9 | 2018-03-02T17:03:43.000Z | 2021-09-02T13:26:04.000Z | FileFormats/Key/Key_Friendly.cpp | xloss/NWNFileFormats | 0b3fd4fba416bcdb79f4d898a40a4107234ceea0 | [
"WTFPL"
] | 8 | 2018-03-04T09:20:46.000Z | 2020-12-06T04:28:33.000Z | FileFormats/Key/Key_Friendly.cpp | xloss/NWNFileFormats | 0b3fd4fba416bcdb79f4d898a40a4107234ceea0 | [
"WTFPL"
] | 8 | 2018-03-04T09:18:49.000Z | 2020-12-01T01:15:41.000Z | #include "FileFormats/Key/Key_Friendly.hpp"
#include "Utility/Assert.hpp"
#include <algorithm>
#include <cstring>
namespace FileFormats::Key::Friendly {
Key::Key(Raw::Key const& rawKey)
{
// Get the referenced BIFs.
for (Raw::KeyFile const& rawFile : rawKey.m_Files)
{
KeyBifReference reference;
reference.m_Drives = rawFile.m_Drives;
reference.m_FileSize = rawFile.m_FileSize;
std::uint32_t offSetStartIntoFilenameTable = rawKey.m_Header.m_OffsetToFileTable + (rawKey.m_Header.m_BIFCount * sizeof(Raw::KeyFile)); // End of file table
std::uint32_t offSetIntoFilenameTable = rawFile.m_FilenameOffset - offSetStartIntoFilenameTable;
ASSERT(offSetStartIntoFilenameTable + offSetIntoFilenameTable + rawFile.m_FilenameSize <= rawKey.m_Header.m_OffsetToKeyTable);
char const* ptr = rawKey.m_Filenames.data() + offSetIntoFilenameTable;
reference.m_Path = std::string(ptr, strnlen(ptr, rawFile.m_FilenameSize));
// Replace all back slash with forward slashes. This avoids any nasty platform-related issues.
std::replace(std::begin(reference.m_Path), std::end(reference.m_Path), '\\', '/');
m_ReferencedBifs.emplace_back(std::move(reference));
}
// Get the references resources.
for (Raw::KeyEntry const& rawEntry : rawKey.m_Entries)
{
std::string resref = std::string(rawEntry.m_ResRef, rawEntry.m_ResRef + strnlen(rawEntry.m_ResRef, 16));
// NWN is case insensitive and cases are mixed like crazy in the official modules.
// We just do the conversion to lower here to simplify things.
std::transform(std::begin(resref), std::end(resref), std::begin(resref), ::tolower);
KeyBifReferencedResource entry;
entry.m_ResRef = std::move(resref);
entry.m_ResType = rawEntry.m_ResourceType;
entry.m_ResId = rawEntry.m_ResID;
entry.m_ReferencedBifResId = rawEntry.m_ResID & 0x00003FFF; // See Bif_Friendly.cpp for explanation.
entry.m_ReferencedBifIndex = rawEntry.m_ResID >> 20;
m_ReferencedResources.emplace_back(std::move(entry));
}
}
std::vector<KeyBifReference> const& Key::GetReferencedBifs() const
{
return m_ReferencedBifs;
}
std::vector<KeyBifReferencedResource> const& Key::GetReferencedResources() const
{
return m_ReferencedResources;
}
}
| 38.129032 | 164 | 0.71066 | xloss |
7c363a4058ccd0b05b8d9b5886de610267d1e842 | 5,307 | hpp | C++ | Lodestar/primitives/sets/SetUnion.hpp | helkebir/Lodestar | 6b325d3e7a388676ed31d44eac1146630ee4bb2c | [
"BSD-3-Clause"
] | 4 | 2020-06-05T14:08:23.000Z | 2021-06-26T22:15:31.000Z | Lodestar/primitives/sets/SetUnion.hpp | helkebir/Lodestar | 6b325d3e7a388676ed31d44eac1146630ee4bb2c | [
"BSD-3-Clause"
] | 2 | 2021-06-25T15:14:01.000Z | 2021-07-01T17:43:20.000Z | Lodestar/primitives/sets/SetUnion.hpp | helkebir/Lodestar | 6b325d3e7a388676ed31d44eac1146630ee4bb2c | [
"BSD-3-Clause"
] | 1 | 2021-06-16T03:15:23.000Z | 2021-06-16T03:15:23.000Z | //
// Created by Hamza El-Kebir on 6/21/21.
//
#ifndef LODESTAR_SETUNION_HPP
#define LODESTAR_SETUNION_HPP
#include "SetExpression.hpp"
#include <type_traits>
#include <algorithm>
namespace ls {
namespace primitives {
namespace sets {
/**
* @brief Union of two SetExpressions.
*
* @details The syntax is as follows:
* \code
* // C = A U B
* auto C = SetUnion(A, B);
* \endcode
*
* @tparam TTypeLeft Type of the left SetExpression.
* @tparam TTypeRight Type of the right SetExpression.
*/
template<typename TTypeLeft, typename TTypeRight>
class SetUnion : public SetExpression<SetUnion<TTypeLeft, TTypeRight>> {
public:
using Base = SetExpression<SetUnion<TTypeLeft, TTypeRight>>; //! Base class.
using ltype = TTypeLeft; //! Left type.
using rtype = TTypeRight; //! Right type.
using type = SetUnion<TTypeLeft, TTypeRight>; //! Expression type.
/**
* @brief Constructor for the union operation.
*
* @details The syntax is as follows:
* \code
* // A U B
* SetUnion(A, B);
* \endcode
*
* @param left The left operand.
* @param right The right operand.
*
* @param empty If true, the expression will be treated as the empty set.
*/
SetUnion(const TTypeLeft &left, const TTypeRight &right, bool empty = false) : left_(left),
right_(right),
empty_(empty)
{
// if (std::is_same<TTypeLeft, TTypeRight>::value)
// Base::sEnum_ = static_cast<TTypeLeft const &>(left).getEnum();
// else
this->sEnum_ = SetEnum::Union;
}
/**
* @brief Returns true if the expression is the empty set.
*
* @return True if expression is the empty set.
*/
bool isEmpty() const
{
return empty_;
}
/**
* @brief Returns true if this expression contains \c el.
*
* @tparam TElementType Type of the element.
*
* @param el Element.
*
* @return True if this expression contains \c el, false otherwise.
*/
template<typename TElementType>
bool contains(const TElementType &el) const
{
return left_.contains(el) || right_.contains(el);
}
/**
* @brief Creates a union between this expression and another SetExpression.
*
* @tparam TExpression Type of the other expression.
*
* @param expr Expression to create a union with.
*
* @return Union.
*/
template<typename TOtherExpr>
SetUnion<type, TOtherExpr> unionize(const SetExpression <TOtherExpr> &expr)
{
return SetUnion<type, TOtherExpr>(*this, *static_cast<const TOtherExpr *>(&expr),
isEmpty() && expr.isEmpty());
}
/**
* @brief Returns signed distance to \c p.
*
* @tparam Derived Derived MatrixBase class.
*
* @param p A point.
*
* @return Signed distance.
*/
template<typename Derived>
double sdf(Eigen::MatrixBase<Derived> &p) const
{
if (isEmpty())
return std::numeric_limits<double>::infinity();
else
return std::min(left_.sdf(p), right_.sdf(p));
}
/**
* @brief Gets the left expression.
*
* @return Left expression.
*/
const TTypeLeft &getLeft() const
{
return left_;
}
/**
* @brief Gets the right expression.
*
* @return Right expression.
*/
const TTypeRight &getRight() const
{
return right_;
}
protected:
const TTypeLeft &left_; //! Left constant reference.
const TTypeRight &right_; //! Right constant reference.
bool empty_; //! Empty bool.
};
}
}
}
#endif //LODESTAR_SETUNION_HPP
| 35.61745 | 109 | 0.419823 | helkebir |
7c38523fe7d90353fb50cc5dc38bb1f9c613a054 | 592 | inl | C++ | rasterizables/RasterizablePrimitiveList.inl | jaredhoberock/gotham | e3551cc355646530574d086d7cc2b82e41e8f798 | [
"Apache-2.0"
] | 6 | 2015-12-29T07:21:01.000Z | 2020-05-29T10:47:38.000Z | rasterizables/RasterizablePrimitiveList.inl | jaredhoberock/gotham | e3551cc355646530574d086d7cc2b82e41e8f798 | [
"Apache-2.0"
] | null | null | null | rasterizables/RasterizablePrimitiveList.inl | jaredhoberock/gotham | e3551cc355646530574d086d7cc2b82e41e8f798 | [
"Apache-2.0"
] | null | null | null | /*! \file RasterizablePrimitiveList.inl
* \author Jared Hoberock
* \brief Inline file for RasterizablePrimitiveList.h.
*/
#include "RasterizablePrimitiveList.h"
template<typename PrimitiveListParentType>
void RasterizablePrimitiveList<PrimitiveListParentType>
::rasterize(void)
{
for(typename Parent0::iterator prim = Parent0::begin();
prim != Parent0::end();
++prim)
{
Rasterizable *r = dynamic_cast<Rasterizable*>((*prim).get());
if(r != 0)
{
r->rasterize();
} // end if
} // end for prim
} // end RasterizablePrimitiveList::rasterize()
| 25.73913 | 65 | 0.679054 | jaredhoberock |
7c3a81683459fac9a0ba9307804e0775f8ae07fb | 1,776 | hpp | C++ | include/engine/game/scripttrigger.hpp | eXl-Nic/eXl | a5a0f77f47db3179365c107a184bb38b80280279 | [
"MIT"
] | null | null | null | include/engine/game/scripttrigger.hpp | eXl-Nic/eXl | a5a0f77f47db3179365c107a184bb38b80280279 | [
"MIT"
] | null | null | null | include/engine/game/scripttrigger.hpp | eXl-Nic/eXl | a5a0f77f47db3179365c107a184bb38b80280279 | [
"MIT"
] | null | null | null | /*
Copyright 2009-2021 Nicolas Colombe
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.
*/
#pragma once
#include <engine/physics/trigger.hpp>
namespace eXl
{
class LuaScriptSystem;
struct ScriptTrigger : TriggerCallback
{
ScriptTrigger(World& iWorld);
void OnEnter(const Vector<ObjectPair>& iNewPairs);
void OnLeave(const Vector<ObjectPair>& iNewPairs);
World& m_World;
LuaScriptSystem& m_Scripts;
private:
Name m_BehaviourName;
Name m_EnterName;
Name m_LeaveName;
};
class ScriptTriggerSystem : public WorldSystem
{
DECLARE_RTTI(ScriptTriggerSystem, WorldSystem);
public:
void Register(World& iWorld);
TriggerCallbackHandle GetScriptCallbackhandle() const { return m_Handle; }
protected:
TriggerCallbackHandle m_Handle;
};
} | 40.363636 | 460 | 0.773649 | eXl-Nic |
7c3c7ff8f6955166bdbd693e0effd6edc45ca4ac | 1,463 | cpp | C++ | tests/streaming/src_model/Model.cpp | TonyBrewer/OpenHT | 63898397de4d303ba514d88b621cc91367ffe2a6 | [
"BSD-3-Clause"
] | 13 | 2015-02-26T22:46:18.000Z | 2020-03-24T11:53:06.000Z | tests/streaming/src_model/Model.cpp | PacificBiosciences/OpenHT | 63898397de4d303ba514d88b621cc91367ffe2a6 | [
"BSD-3-Clause"
] | 5 | 2016-02-25T17:08:19.000Z | 2018-01-20T15:24:36.000Z | tests/streaming/src_model/Model.cpp | TonyBrewer/OpenHT | 63898397de4d303ba514d88b621cc91367ffe2a6 | [
"BSD-3-Clause"
] | 12 | 2015-04-13T21:39:54.000Z | 2021-01-15T01:00:13.000Z | #include "Ht.h"
void HtCoprocModel()
{
uint32_t haltCnt = 0;
uint16_t nau = 0;
uint16_t au = 0;
CHtModelHif *pModel = new CHtModelHif;
CHtModelAuUnit *const *pAuUnits = pModel->AllocAllAuUnits();
nau = pModel->GetAuUnitCnt();
uint16_t rcvAu;
uint32_t rcvCnt;
// Loop until all AUs are done echoing data
while (haltCnt < nau) {
for (au = 0; au < nau; au++) {
uint32_t wordCnt = 0;
uint64_t recvData = 0;
int32_t errs = 0;
if(pAuUnits[au]->RecvCall_htmain(rcvAu, rcvCnt)) {
printf("Model: AU %2d - Processing\n", rcvAu);
while (wordCnt < rcvCnt) {
// Rerun loop if no data to read
if (!pAuUnits[au]->RecvHostData(1, &recvData)) {
continue;
}
// At this point, there is valid data in recvData
// Generate an expected response and compare
uint64_t expectedData = 0;
expectedData |= ((rcvAu & 0xFFFFLL)<<48);
expectedData |= ((wordCnt + 1) & 0xFFFFFFFFFFFFLL);
if (expectedData != recvData) {
printf("Model: WARNING - Expected Data did not match Received data!\n");
printf(" 0x%016llx != 0x%016llx\n",
(unsigned long long)expectedData, (unsigned long long)recvData);
errs++;
}
// Send it back!
while (!pAuUnits[au]->SendHostData(1, &expectedData));
wordCnt++;
}
while (!pAuUnits[au]->SendReturn_htmain(errs));
}
haltCnt += pAuUnits[au]->RecvHostHalt();
}
}
pModel->FreeAllAuUnits();
delete pModel;
}
| 21.514706 | 77 | 0.626111 | TonyBrewer |
7c3eba0795cd22609dde200195c4fd3e6b8b8741 | 5,485 | cpp | C++ | savedecrypter-master/savedecrypter/ClanLib-2.0/Sources/Core/System/thread_local_storage.cpp | ZephyrXD/Z-Builder-Source-CPP | f48e0f22b5d4d183b841abb8e61e1bdb5c25999d | [
"Apache-2.0"
] | 6 | 2020-11-11T15:49:11.000Z | 2021-03-08T10:29:23.000Z | savedecrypter-master/savedecrypter/ClanLib-2.0/Sources/Core/System/thread_local_storage.cpp | ZeppyXD/Z-Builder-Source-CPP | f48e0f22b5d4d183b841abb8e61e1bdb5c25999d | [
"Apache-2.0"
] | 1 | 2020-11-08T17:28:35.000Z | 2020-11-09T01:35:27.000Z | savedecrypter-master/savedecrypter/ClanLib-2.0/Sources/Core/System/thread_local_storage.cpp | ZeppyXD/Z-Builder-Source-CPP | f48e0f22b5d4d183b841abb8e61e1bdb5c25999d | [
"Apache-2.0"
] | 3 | 2021-06-26T13:00:23.000Z | 2022-02-01T02:16:50.000Z | /*
** ClanLib SDK
** Copyright (c) 1997-2010 The ClanLib Team
**
** This software is provided 'as-is', without any express or implied
** warranty. In no event will the authors be held liable for any damages
** arising from the use of this software.
**
** Permission is granted to anyone to use this software for any purpose,
** including commercial applications, and to alter it and redistribute it
** freely, subject to the following restrictions:
**
** 1. The origin of this software must not be misrepresented; you must not
** claim that you wrote the original software. If you use this software
** in a product, an acknowledgment in the product documentation would be
** appreciated but is not required.
** 2. Altered source versions must be plainly marked as such, and must not be
** misrepresented as being the original software.
** 3. This notice may not be removed or altered from any source distribution.
**
** Note: Some of the libraries ClanLib may link to may have additional
** requirements or restrictions.
**
** File Author(s):
**
** Harry Storbacka
*/
#include "Core/precomp.h"
#include "API/Core/System/thread_local_storage.h"
#include "thread_local_storage_impl.h"
#include "../core_global.h"
/////////////////////////////////////////////////////////////////////////////
// CL_ThreadLocalStorage Construction:
void CL_ThreadLocalStorage::create_initial_instance()
{
if (!cl_core_global.cl_tls)
{
cl_core_global.cl_tls = new(CL_ThreadLocalStorage);
}
}
CL_ThreadLocalStorage::CL_ThreadLocalStorage()
{
CL_System::alloc_thread_temp_pool();
#ifdef WIN32
if (cl_core_global.cl_tls_index == TLS_OUT_OF_INDEXES)
{
CL_MutexSection mutex_lock(&cl_core_global.cl_tls_mutex);
cl_core_global.cl_tls_index = TlsAlloc();
}
CL_ThreadLocalStorage_Impl *tls_impl = (CL_ThreadLocalStorage_Impl *) TlsGetValue(cl_core_global.cl_tls_index);
if (!tls_impl)
{
tls_impl = new CL_ThreadLocalStorage_Impl;
TlsSetValue(cl_core_global.cl_tls_index, tls_impl);
}
else
{
tls_impl->add_reference();
}
#elif !defined(HAVE_TLS)
if (!cl_core_global.cl_tls_index_created)
{
CL_MutexSection mutex_lock(&cl_core_global.cl_tls_mutex);
pthread_key_create(&cl_core_global.cl_tls_index, 0);
cl_core_global.cl_tls_index_created = true;
}
CL_ThreadLocalStorage_Impl *tls_impl = (CL_ThreadLocalStorage_Impl *) pthread_getspecific(cl_core_global.cl_tls_index);
if (!tls_impl)
{
tls_impl = new CL_ThreadLocalStorage_Impl;
pthread_setspecific(cl_core_global.cl_tls_index, tls_impl);
}
else
{
tls_impl->add_reference();
}
#else
if (!cl_core_global.cl_tls_impl)
{
cl_core_global.cl_tls_impl = new CL_ThreadLocalStorage_Impl;
}
else
{
cl_core_global.cl_tls_impl->add_reference();
}
#endif
}
CL_ThreadLocalStorage::~CL_ThreadLocalStorage()
{
#ifdef WIN32
if (cl_core_global.cl_tls_index == TLS_OUT_OF_INDEXES)
return;
CL_ThreadLocalStorage_Impl *tls_impl = (CL_ThreadLocalStorage_Impl *) TlsGetValue(cl_core_global.cl_tls_index);
if (tls_impl)
tls_impl->release_reference();
#elif !defined(HAVE_TLS)
if (!cl_core_global.cl_tls_index_created)
return;
CL_ThreadLocalStorage_Impl *tls_impl = (CL_ThreadLocalStorage_Impl *) pthread_getspecific(cl_core_global.cl_tls_index);
if (tls_impl)
tls_impl->release_reference();
#else
if (cl_core_global.cl_tls_impl)
cl_core_global.cl_tls_impl->release_reference();
#endif
CL_System::free_thread_temp_pool();
}
/////////////////////////////////////////////////////////////////////////////
// CL_ThreadLocalStorage Attributes:
CL_UnknownSharedPtr CL_ThreadLocalStorage::get_variable(const CL_StringRef &name)
{
#ifdef WIN32
if (cl_core_global.cl_tls_index == TLS_OUT_OF_INDEXES)
throw CL_Exception("No CL_ThreadLocalStorage object created for this thread.");
CL_ThreadLocalStorage_Impl *tls_impl = (CL_ThreadLocalStorage_Impl *) TlsGetValue(cl_core_global.cl_tls_index);
#elif !defined(HAVE_TLS)
if (!cl_core_global.cl_tls_index_created)
throw CL_Exception("No CL_ThreadLocalStorage object created for this thread.");
CL_ThreadLocalStorage_Impl *tls_impl = (CL_ThreadLocalStorage_Impl *) pthread_getspecific(cl_core_global.cl_tls_index);
#else
CL_ThreadLocalStorage_Impl *tls_impl = cl_core_global.cl_tls_impl;
#endif
if (tls_impl == 0)
throw CL_Exception("No CL_ThreadLocalStorage object created for this thread.");
return tls_impl->get_variable(name);
}
/////////////////////////////////////////////////////////////////////////////
// CL_ThreadLocalStorage Operations:
void CL_ThreadLocalStorage::set_variable(const CL_StringRef &name, CL_UnknownSharedPtr ptr)
{
#ifdef WIN32
if (cl_core_global.cl_tls_index == TLS_OUT_OF_INDEXES)
throw CL_Exception("No CL_ThreadLocalStorage object created for this thread.");
CL_ThreadLocalStorage_Impl *tls_impl = (CL_ThreadLocalStorage_Impl *) TlsGetValue(cl_core_global.cl_tls_index);
#elif !defined(HAVE_TLS)
if (!cl_core_global.cl_tls_index_created)
throw CL_Exception("No CL_ThreadLocalStorage object created for this thread.");
CL_ThreadLocalStorage_Impl *tls_impl = (CL_ThreadLocalStorage_Impl *) pthread_getspecific(cl_core_global.cl_tls_index);
#else
CL_ThreadLocalStorage_Impl *tls_impl = cl_core_global.cl_tls_impl;
#endif
if (tls_impl == 0)
throw CL_Exception("No CL_ThreadLocalStorage object created for this thread.");
tls_impl->set_variable(name,ptr);
}
/////////////////////////////////////////////////////////////////////////////
// CL_ThreadLocalStorage Implementation:
| 32.844311 | 120 | 0.742024 | ZephyrXD |
7c47701300dfe2487a85d90fc459ba063cae22a6 | 654 | cpp | C++ | windows-lockscreen-extractor/src/helpers/User.cpp | chistyakoviv/windows-lockscreen-extractor | 189c396fe15fd3facdb2ebe4d8cab2317af0098f | [
"MIT"
] | null | null | null | windows-lockscreen-extractor/src/helpers/User.cpp | chistyakoviv/windows-lockscreen-extractor | 189c396fe15fd3facdb2ebe4d8cab2317af0098f | [
"MIT"
] | null | null | null | windows-lockscreen-extractor/src/helpers/User.cpp | chistyakoviv/windows-lockscreen-extractor | 189c396fe15fd3facdb2ebe4d8cab2317af0098f | [
"MIT"
] | null | null | null | #include "User.h"
#include <clocale>
#include <locale>
#include <codecvt>
static const wchar_t* LOCK_SCREEN_IMAGES_PATH = L"\\AppData\\Local\\Packages\\Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy\\LocalState\\Assets";
static std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> s_Converter;
std::wstring User::GetProfileDir()
{
return s_Converter.from_bytes(getenv("USERPROFILE"));
}
std::wstring User::GetLockScreenImagesDir()
{
return User::GetProfileDir() + LOCK_SCREEN_IMAGES_PATH;
}
std::wstring User::GetLockScreenImageAbsolutePath(const std::wstring& imageName)
{
return User::GetLockScreenImagesDir() + L"\\" + imageName;
}
| 26.16 | 154 | 0.778287 | chistyakoviv |
7c4aed921ec64f75f6cd7158352edf044939f391 | 2,781 | cpp | C++ | Demo/GameCode/IntroScene.cpp | TimPhoeniX/LuaDemo | 99930f376f08f080e43737eb28606ab3f5d24eb9 | [
"MIT"
] | 2 | 2019-09-26T09:12:54.000Z | 2019-10-03T10:43:59.000Z | Demo/GameCode/IntroScene.cpp | TimPhoeniX/LuaDemo | 99930f376f08f080e43737eb28606ab3f5d24eb9 | [
"MIT"
] | null | null | null | Demo/GameCode/IntroScene.cpp | TimPhoeniX/LuaDemo | 99930f376f08f080e43737eb28606ab3f5d24eb9 | [
"MIT"
] | null | null | null | #include "IntroScene.hpp"
#include <Object/Shape/sge_shape.hpp>
#include <Game/sge_game.hpp>
#include <Game/Director/sge_director.hpp>
#include "Image.hpp"
#include "Logics.hpp"
#include "Actions.hpp"
#include "Renderer/sge_renderer.hpp"
IntroScene::IntroScene(SGE::Scene* next, const char* path): path(path), next(next)
{}
void IntroScene::loadScene()
{
auto o = new Image(0, 0, SGE::Shape::Rectangle(1024.f / 64.f, 768.f / 64.f, true));
auto g = SGE::Game::getGame();
auto game = SGE::Game::getGame();
SGE::BatchRenderer* renderer = game->getRenderer();
auto program = renderer->getProgramID("BatchShader.vert","BatchShader.frag");
size_t batch = renderer->newBatch(program, path, 1, false, true);
renderer->getBatch(batch)->addObject(o);
o->setVisible(true);
o->setDrawable(true);
this->addObject(o);
this->addLogic(new Timer(2, new Load(next)));
g->getCamera()->setPositionGLM(0, 0);
g->getCamera()->setCameraScale(1.f);
}
IntroScene::~IntroScene()
{}
void IntroScene::finalize()
{}
void IntroScene::onDraw()
{
auto g = SGE::Game::getGame();
g->getCamera()->setPositionGLM(0, 0);
g->getCamera()->setCameraScale(1.f);
SGE::Director::getDirector()->unloadScene(next);
}
EndScene::EndScene(Scene* next, const char* path, const char* path2): IntroScene(next, path), path2(path2), won(nullptr)
{
}
void EndScene::onDraw()
{
auto g = SGE::Game::getGame();
g->getCamera()->setPositionGLM(0, 0);
g->getCamera()->setCameraScale(1.f);
if(this->won)
{
this->getObjects()[0]->setVisible(true);
this->getObjects()[1]->setVisible(false);
}
else
{
this->getObjects()[0]->setVisible(false);
this->getObjects()[1]->setVisible(true);
}
SGE::Director::getDirector()->unloadScene(next);
}
void EndScene::loadScene()
{
auto i1 = new Image(0, 0, SGE::Shape::Rectangle(1024.f / 64.f, 768.f / 64.f, true));
auto i2 = new Image(0, 0, SGE::Shape::Rectangle(1024.f / 64.f, 768.f / 64.f, true));
auto game = SGE::Game::getGame();
SGE::BatchRenderer* renderer = game->getRenderer();
if(this->winBatch == 0)
{
auto program = renderer->getProgramID("BatchShader.vert", "BatchShader.frag");
this->winBatch = renderer->newBatch(program, path, 1, false, true);
}
if(this->loseBatch == 0)
{
auto program = renderer->getProgramID("BatchShader.vert", "BatchShader.frag");
this->loseBatch = renderer->newBatch(program, path2, 1, false, true);
}
renderer->getBatch(this->winBatch)->addObject(i1);
i1->setVisible(true);
i1->setDrawable(true);
renderer->getBatch(this->loseBatch)->addObject(i2);
i2->setVisible(true);
i2->setDrawable(true);
auto g = SGE::Game::getGame();
this->addObject(i1);
this->addObject(i2);
this->addLogic(new OnKey(SGE::Key::Return, next));
g->getCamera()->setPositionGLM(0, 0);
g->getCamera()->setCameraScale(1.f);
}
| 28.670103 | 120 | 0.685365 | TimPhoeniX |
7c510ec662d1a3d9eb901118b6cf9ce02e546aba | 1,403 | cpp | C++ | src/windows/filesystem_win32.cpp | puremourning/netcoredbg | c34eaef68abe06197d03bc8c19282707cfc1adda | [
"MIT"
] | null | null | null | src/windows/filesystem_win32.cpp | puremourning/netcoredbg | c34eaef68abe06197d03bc8c19282707cfc1adda | [
"MIT"
] | null | null | null | src/windows/filesystem_win32.cpp | puremourning/netcoredbg | c34eaef68abe06197d03bc8c19282707cfc1adda | [
"MIT"
] | null | null | null | // Copyright (C) 2020 Samsung Electronics Co., Ltd.
// See the LICENSE file in the project root for more information.
/// \file filesystem_win32.cpp
/// This file contains definitions of windows-specific functions related to file system.
#ifdef WIN32
#include <windows.h>
#include <string>
#include "filesystem.h"
namespace netcoredbg
{
const char* FileSystemTraits<Win32PlatformTag>::PathSeparatorSymbols = "/\\";
// Function returns absolute path to currently running executable.
std::string GetExeAbsPath()
{
const size_t MAX_LONGPATH = 1024;
char hostPath[MAX_LONGPATH + 1];
static const std::string result(hostPath, ::GetModuleFileNameA(NULL, hostPath, MAX_LONGPATH));
return result;
}
// Function returns path to directory, which should be used for creation of
// temporary files. Typically this is `/tmp` on Unix and something like
// `C:\Users\localuser\Appdata\Local\Temp` on Windows.
string_view GetTempDir()
{
CHAR path[MAX_PATH + 1];
static const std::string result(path, GetTempPathA(MAX_PATH, path));
return result;
}
// Function changes current working directory. Return value is `false` in case of error.
bool SetWorkDir(string_view path)
{
char str[MAX_PATH];
if (path.size() >= sizeof(str))
return false;
path.copy(str, path.size());
str[path.size()] = 0;
return SetCurrentDirectoryA(str);
}
} // ::netcoredbg
#endif
| 26.980769 | 98 | 0.721311 | puremourning |
7c540cd285c2a41253b995ad72bc218634d63192 | 604 | cpp | C++ | 34. Find First and Last Position of Element in Sorted Array.cpp | kushagra-18/Leetcode-solutions | cf276e6cc5491429144a79c59dd1097f1d625a6b | [
"MIT"
] | null | null | null | 34. Find First and Last Position of Element in Sorted Array.cpp | kushagra-18/Leetcode-solutions | cf276e6cc5491429144a79c59dd1097f1d625a6b | [
"MIT"
] | null | null | null | 34. Find First and Last Position of Element in Sorted Array.cpp | kushagra-18/Leetcode-solutions | cf276e6cc5491429144a79c59dd1097f1d625a6b | [
"MIT"
] | null | null | null | class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int n = nums.size(),i,count = 0,flag;
for(i = 0;i<n;i++){
if(nums[i]==target){
count++;
flag = i;
}
}
if(count==0){
vector <int> arr = {-1,-1};
return arr;
}else{
vector <int> arr = {(flag-count) +1 ,flag};
return arr;
}
}
}; | 19.483871 | 60 | 0.306291 | kushagra-18 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.